diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml index f96bf9a4a7..37796f6816 100644 --- a/.github/workflows/formats.yml +++ b/.github/workflows/formats.yml @@ -16,6 +16,7 @@ on: - "crates/tiff/**" - "crates/heif/**" - "crates/cms/**" + - "crates/cdr/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/formats.yml" @@ -33,6 +34,7 @@ on: - "crates/tiff/**" - "crates/heif/**" - "crates/cms/**" + - "crates/cdr/**" - "Cargo.toml" - "Cargo.lock" - ".github/workflows/formats.yml" @@ -67,6 +69,7 @@ jobs: - { crate: craft-tiff, features: "" } - { crate: craft-heif, features: "testdata" } - { crate: craft-cms, features: "" } + - { crate: craft-cdr, features: "synth" } # fmt, clippy with default and with all features, and the tests run in the Workspace gate on # every OS; this lints each feature alone and checks the web build. name: ${{ matrix.crate }} feature sets, WASM diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 910f2bd710..3d1ef77494 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -183,3 +183,9 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. `crates/xfdf` extracts PDFCraft field reading from #5937 refresh `cb564fd827f572818e9ddb0ea5989a432b1f39fd` (MIT OR Apache-2.0). App-side annotation and form policy remains local; source history is retained in the original repository. Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnulfo, pkibiego and storybored379; module split by aiongg. Subsequent budget/integration work by Dylan M. Taylor. + +## Y4M range-backed playback + +`crates/media-source/src/y4m.rs` adapts the in-house [FilmCraft Y4mSource at 3f137a7e](https://github.com/storytold/filmcraft/blob/3f137a7ed420cac79b32145f5243b7f98b31f71c/crates/codecs/src/y4m.rs), MIT OR Apache-2.0. Original playback by Lloyd Nicholson ([FilmCraft #1303](https://github.com/storytold/filmcraft/pull/1303)); shared-parser integration by Dylan M. Taylor ([FilmCraft #4862](https://github.com/storytold/filmcraft/pull/4862)). The adaptation changes source/frame types and declines payloads above the shared media allocation ceiling before playback. The parser and its previous header-safety work remain in `craft-y4m` ([craft-libs #933](https://github.com/storytold/craft-libs/pull/933)). + +`crates/media-source/tests/it/y4m.rs` contains original repository-authored synthetic test data under MIT OR Apache-2.0: literal YUV samples and a sparse reader that reports only the length of an oversized frame. It does not use external media or decoder output. diff --git a/Cargo.lock b/Cargo.lock index 90d62aef38..e65b6a3907 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1742,6 +1742,7 @@ dependencies = [ "craft-affinity", "craft-ai", "craft-ai-core", + "craft-android-res", "craft-anicraft-format", "craft-assuan", "craft-atomic", @@ -1752,6 +1753,7 @@ dependencies = [ "craft-ber", "craft-browse", "craft-captions", + "craft-cdr", "craft-cfb", "craft-cloud", "craft-cloud-local", @@ -1876,6 +1878,7 @@ dependencies = [ "craft-platform", "craft-plist", "craft-plotter", + "craft-png", "craft-ppt-binary", "craft-pptx", "craft-prc", @@ -2012,6 +2015,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-android-res" +version = "0.1.0" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-anicraft-format" version = "0.1.0" @@ -2133,6 +2144,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-cdr" +version = "0.1.0" +dependencies = [ + "craft-cdr", + "crc32fast", + "flate2", + "proptest", +] + [[package]] name = "craft-cfb" version = "0.1.0" @@ -2330,8 +2351,11 @@ dependencies = [ name = "craft-develop" version = "0.1.0" dependencies = [ + "craft-color", "craft-color-transform", "craft-develop-model", + "craft-geom", + "craft-raw", "craft-render-parity", "proptest", "rayon", @@ -3261,6 +3285,7 @@ dependencies = [ "craft-frame", "craft-media", "craft-time", + "craft-y4m", "serde", "serde_json", "thiserror 2.0.21", @@ -3658,6 +3683,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-png" +version = "0.1.0" +dependencies = [ + "png 0.18.1", + "thiserror 2.0.21", +] + [[package]] name = "craft-ppt-binary" version = "0.1.0" @@ -4169,6 +4202,7 @@ dependencies = [ name = "craft-tga" version = "0.1.0" dependencies = [ + "image", "thiserror 2.0.21", ] @@ -4216,9 +4250,11 @@ dependencies = [ name = "craft-tiff" version = "0.1.0" dependencies = [ + "image", "proptest", "serde", "thiserror 2.0.21", + "tiff", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 44b4079a65..5b9c085a84 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-android-res = { path = "crates/android-res" } craft-audio-dsp = { path = "crates/audio-dsp" } craft-xfa = { path = "crates/xfa" } craft-evm = { path = "crates/evm" } @@ -37,9 +38,11 @@ log = "0.4" craft-plist = { path = "crates/plist" } craft-wasm = { path = "crates/wasm" } craft-platform = { path = "crates/platform" } +craft-png = { path = "crates/png" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } craft-win32 = { path = "crates/win32" } +craft-cdr = { path = "crates/cdr" } craft-ai = { path = "crates/ai" } craft-ai-core = { path = "crates/ai-core" } craft-anicraft-format = { path = "crates/anicraft-format" } diff --git a/NOTICE b/NOTICE index 8ca284e8db..c63edc0812 100644 --- a/NOTICE +++ b/NOTICE @@ -432,3 +432,14 @@ Original src/avx2/fdct.rs opening notice * Based on the x86 SIMD extension for IJG JPEG library * Copyright (C) 1999-2006, MIYASAKA Masaru. */ + +The .cdr reader (crates/cdr, moved from VectorCraft crates/cdr) reads the record layouts that the +Kaitai Struct specification coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, +MIT License) and its fork by Zach Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch +new_stuff, MIT License) describe. No part of either specification is copied into the crate; the +license text is in crates/cdr/LICENSE-kaitai.txt. + +The Y4M range-backed source in crates/media-source/src/y4m.rs adapts FilmCraft's +original implementation (3f137a7ed420cac79b32145f5243b7f98b31f71c), licensed +MIT OR Apache-2.0. Source notice retained: +Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors. diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs index 8e4828f554..7ea67f4ec1 100644 --- a/crates/aaf/src/aaf.rs +++ b/crates/aaf/src/aaf.rs @@ -37,6 +37,7 @@ //! name), `FilmCraft Frame Size` and `FilmCraft Audio Sample Rate` (on the composition). mod ids; +pub mod properties; mod read; pub(crate) mod store; mod write; diff --git a/crates/aaf/src/aaf/properties.rs b/crates/aaf/src/aaf/properties.rs new file mode 100644 index 0000000000..e9e6d45562 --- /dev/null +++ b/crates/aaf/src/aaf/properties.rs @@ -0,0 +1,93 @@ +//! Borrowed little-endian AAF property-stream records, independent of CFB and object policy. + +/// One indexed AAF property. The payload borrows the original stream. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Property<'a> { + /// The property ID (pid). + pub id: u16, + /// The stored form of the value, as the index records it. + pub form: u16, + /// The value's bytes. + pub payload: &'a [u8], +} + +/// Malformed property-stream framing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PropertyError { + /// The stream ends before its 4-byte header. + ShortHeader, + /// The header's byte-order mark is not little-endian (0x4c). + UnsupportedByteOrder, + /// The stream ends inside the property index. + TruncatedIndex, + /// A property's length runs past the end of the stream. + TruncatedValue, +} + +/// Property-stream record iterator. It does not deduplicate IDs, interpret forms, +/// copy payloads or impose object budgets; those decisions belong to the caller. +#[derive(Clone, Debug)] +pub struct Properties<'a> { + headers: std::slice::Iter<'a, [u8; 6]>, + payload: &'a [u8], +} + +impl<'a> Properties<'a> { + /// Validate the header and complete index. Payload extents are checked during + /// iteration; callers can validate all extents before copying by iterating a clone. + pub fn new(stream: &'a [u8]) -> Result { + let [order, _, lo, hi, tail @ ..] = stream else { return Err(PropertyError::ShortHeader) }; + if *order != 0x4c { + return Err(PropertyError::UnsupportedByteOrder); + } + let count = usize::from(u16::from_le_bytes([*lo, *hi])); + let (headers, payload) = tail.split_at_checked(count * 6).ok_or(PropertyError::TruncatedIndex)?; + Ok(Self { headers: headers.as_chunks::<6>().0.iter(), payload }) + } + pub(super) fn remaining_count(&self) -> usize { + self.headers.len() + } + + // The store checks duplicate IDs before validating the corresponding payload, + // so a record that is both duplicate and truncated retains its old diagnostic. + pub(super) fn next_id(&self) -> Option { + let [lo, hi, ..] = self.headers.as_slice().first()?; + Some(u16::from_le_bytes([*lo, *hi])) + } +} + +impl<'a> Iterator for Properties<'a> { + type Item = Result, PropertyError>; + + fn next(&mut self) -> Option { + let [id0, id1, form0, form1, len0, len1] = self.headers.next()?; + let len = usize::from(u16::from_le_bytes([*len0, *len1])); + let Some((payload, tail)) = self.payload.split_at_checked(len) else { + self.headers = [].iter(); + return Some(Err(PropertyError::TruncatedValue)); + }; + self.payload = tail; + Some(Ok(Property { id: u16::from_le_bytes([*id0, *id1]), form: u16::from_le_bytes([*form0, *form1]), payload })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn records_borrow_ordered_payloads_without_deduplicating() { + let stream = [0x4c, 0x20, 2, 0, 0x55, 0, 0x82, 0, 2, 0, 0x55, 0, 0x22, 0, 1, 0, 9, 8, 7]; + let mut records = Properties::new(&stream).unwrap(); + assert_eq!(records.remaining_count(), 2); + assert_eq!(records.next_id(), Some(0x55)); + let first = records.next().unwrap().unwrap(); + assert_eq!(records.next_id(), Some(0x55)); + let second = records.next().unwrap().unwrap(); + assert_eq!(first, Property { id: 0x55, form: 0x82, payload: &[9, 8] }); + assert_eq!(second, Property { id: 0x55, form: 0x22, payload: &[7] }); + assert!(std::ptr::eq(first.payload, &stream[16..18])); + assert!(std::ptr::eq(second.payload, &stream[18..19])); + assert!(records.next().is_none()); + } +} diff --git a/crates/aaf/src/aaf/store.rs b/crates/aaf/src/aaf/store.rs index 859c0ea776..27bfad8560 100644 --- a/crates/aaf/src/aaf/store.rs +++ b/crates/aaf/src/aaf/store.rs @@ -450,28 +450,21 @@ impl R<'_> { } let mut o = Obj::new(e.clsid); let props = self.stream(entry, "properties")?; - if props.len() < 4 { - return Err(bad("short properties stream")); - } - if props[0] != BYTE_ORDER_LE { - return Err(bad("big-endian AAF files are not supported")); - } - let n = rd_u16(&props, 2).unwrap_or(0) as usize; - let mut at = 4 + n * 6; - if at > props.len() { - return Err(bad("truncated property index")); - } + use super::properties::{Properties, Property, PropertyError}; + let framing = |e| match e { + PropertyError::ShortHeader => bad("short properties stream"), + PropertyError::UnsupportedByteOrder => bad("big-endian AAF files are not supported"), + PropertyError::TruncatedIndex => bad("truncated property index"), + PropertyError::TruncatedValue => bad("truncated property value"), + }; + let mut records = Properties::new(&props).map_err(framing)?; // A properties stream can name tens of thousands of ids: do not rescan all earlier ids. - let mut seen = std::collections::HashSet::with_capacity(n); - for i in 0..n { - let (Some(pid), Some(sf), Some(len)) = (rd_u16(&props, 4 + i * 6), rd_u16(&props, 6 + i * 6), rd_u16(&props, 8 + i * 6)) else { - return Err(bad("truncated property index")); - }; + let mut seen = std::collections::HashSet::with_capacity(records.remaining_count()); + while let Some(pid) = records.next_id() { if !seen.insert(pid) { return Err(bad("duplicate property id")); } - let v = props.get(at..at + len as usize).ok_or_else(|| bad("truncated property value"))?; - at += len as usize; + let Property { form: sf, payload: v, .. } = records.next().ok_or_else(|| bad("truncated property index"))?.map_err(framing)?; let value = match sf { SF_STRONG => { let c = self.child(entry, &utf16_of(v))?; diff --git a/crates/android-res/Cargo.toml b/crates/android-res/Cargo.toml new file mode 100644 index 0000000000..cc54d2513c --- /dev/null +++ b/crates/android-res/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "craft-android-res" +description = "Bounded readers for compiled Android binary XML and resource tables" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/android-res/README.md b/crates/android-res/README.md new file mode 100644 index 0000000000..cc3a643e11 --- /dev/null +++ b/crates/android-res/README.md @@ -0,0 +1,16 @@ +# craft-android-res + +Read-only wire decoding for Android compiled XML (AXML) and Android resource +tables (ARSC). XML and resource tables share the bounded chunk, string-pool, +and typed-value readers. APK container selection, manifest inventory policy, +device/security interpretation, and presentation remain consumer-owned. + +## Provenance + +The decoders, checked-reader subset, and synthetic test fixture subset were +moved from [Craft Anything at 8cec25d](https://github.com/storytold/craft-anything/tree/8cec25d02007db604b57ce6735ad4eb44a1a9948/crates/formats). +The original implementation is Brandon Thomas (echelon), [f64ae3bf](https://github.com/storytold/craft-anything/commit/f64ae3bf3c8863a982af1304e06de20653803968). +Later parser bounds and resource identity/qualifier work came from Afloat +and BFlat; typed-attribute handling also includes RRFZ's work. The original +[fixture generator](https://github.com/storytold/craft-anything/blob/8cec25d02007db604b57ce6735ad4eb44a1a9948/crates/testkit/src/android.rs) +remains the source of the test data. No external assets or added dependencies. diff --git a/crates/android-res/src/arsc.rs b/crates/android-res/src/arsc.rs new file mode 100644 index 0000000000..79a029625c --- /dev/null +++ b/crates/android-res/src/arsc.rs @@ -0,0 +1,677 @@ +//! Android compiled resource tables (`resources.arsc`): the global string pool, packages, type +//! and key string pools, type specs, and typed entries per configuration (locale, density, +//! orientation, SDK level…). Simple and complex (bag) entries, sparse and 16-bit offset tables. + +use crate::Error; +use crate::axml::{ResValue, StringPool, chunk}; +use crate::bytes::Reader; +use serde::Serialize; + +const RES_TABLE: u16 = 0x0002; +const RES_PACKAGE: u16 = 0x0200; +const RES_TYPE: u16 = 0x0201; +const RES_TYPE_SPEC: u16 = 0x0202; +const RES_LIBRARY: u16 = 0x0203; +const NO_ENTRY: u32 = 0xffff_ffff; +const MAX_PACKAGES: usize = 64; +const MAX_BAG: usize = 4096; + +/// Limits for one table. +#[derive(Debug, Clone, Copy)] +pub struct Limits { + /// Most entries decoded across all types and configurations. + pub max_entries: usize, +} + +impl Default for Limits { + fn default() -> Self { + Limits { max_entries: 2_000_000 } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct TypeInfo { + pub id: u8, + pub name: String, + pub entry_count: u32, + /// Configuration qualifiers that have values for this type ("default" for none). + pub configs: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Package { + pub id: u32, + pub name: String, + pub types: Vec, + pub keys: usize, + /// Shared-library package references (id → name). + pub libraries: Vec<(u32, String)>, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BagItem { + pub name: String, + pub value: String, + pub value_type: &'static str, +} + +/// One value of one resource in one configuration. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Entry { + /// `0xPPTTEEEE` + pub id: String, + pub package: String, + #[serde(rename = "type")] + pub type_name: String, + pub key: String, + /// Qualifier string, e.g. `fr`, `es-rMX`, `night-xhdpi`, or `default`. + pub config: String, + /// Android locale qualifier, empty for the default locale. + pub locale: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub value: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub value_type: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub bag: Vec, + #[serde(skip)] + pub raw: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +pub struct Table { + pub packages: Vec, + pub global_strings: usize, + pub entries: Vec, + pub truncated: bool, + pub warnings: Vec, +} + +fn utf16_fixed(r: &Reader<'_>, off: usize, chars: usize) -> String { + let units: Vec = (0..chars).map_while(|i| r.u16_le(off + i * 2)).take_while(|&u| u != 0).collect(); + String::from_utf16_lossy(&units) +} + +fn ascii2(b: &[u8]) -> String { + b.iter().take_while(|&&c| c != 0).map(|&c| if c.is_ascii_graphic() { c as char } else { '?' }).collect() +} + +/// A packed 2-byte language or region code (3-letter codes are packed into 15 bits). +fn unpack_code(b: &[u8], base: u8) -> String { + let (b0, b1) = (b.first().copied().unwrap_or(0), b.get(1).copied().unwrap_or(0)); + if b0 & 0x80 != 0 { + let first = b1 & 0x1f; + let second = ((b1 & 0xe0) >> 5) | ((b0 & 0x03) << 3); + let third = (b0 & 0x7c) >> 2; + [first, second, third].iter().map(|c| (c.wrapping_add(base)) as char).collect() + } else { + ascii2(&[b0, b1]) + } +} + +fn locale_qualifier(r: &Reader<'_>, off: usize, size: usize, get8: impl Fn(usize) -> Option) -> String { + let lang = if size >= 12 { r.slice(off + 8, 2).map(|b| unpack_code(b, b'a')).unwrap_or_default() } else { String::new() }; + let region = if size >= 12 { r.slice(off + 10, 2).map(|b| unpack_code(b, b'0')).unwrap_or_default() } else { String::new() }; + // Extended locale fields were appended to ResTable_config. Older + // configurations end before one or more of these fields. + let subtag = |start: usize, len: usize| { + if start + len <= size { r.slice(off + start, len).map(ascii2).unwrap_or_default() } else { String::new() } + }; + let script = if get8(52).unwrap_or(0) == 0 { subtag(36, 4) } else { String::new() }; + let variant = subtag(40, 8); + let numbering = subtag(53, 8); + let mut locale = lang; + if !locale.is_empty() && (!script.is_empty() || !variant.is_empty() || !numbering.is_empty()) { + locale.insert_str(0, "b+"); + for part in [&script, ®ion, &variant].into_iter().filter(|p| !p.is_empty()) { + locale.push('+'); + locale.push_str(part); + } + if !numbering.is_empty() { + locale.push_str("+u+nu+"); + locale.push_str(&numbering); + } + } else if !locale.is_empty() && !region.is_empty() { + locale.push_str(&format!("-r{region}")); + } + locale +} + +/// Qualifier string and locale for a `ResTable_config` at `off`. +fn config_qualifiers(r: &Reader<'_>, off: usize) -> (String, String) { + let size = r.u32_le(off).unwrap_or(0) as usize; + let get8 = |o: usize| if o < size { r.u8(off + o) } else { None }; + let get16 = |o: usize| if o + 1 < size { r.u16_le(off + o) } else { None }; + let mut q: Vec = Vec::new(); + if let Some(mcc) = get16(4).filter(|&v| v != 0) { + q.push(format!("mcc{mcc}")); + } + if let Some(mnc) = get16(6).filter(|&v| v != 0) { + q.push(format!("mnc{}", if mnc == u16::MAX { 0 } else { mnc })); + } + let locale = locale_qualifier(r, off, size, get8); + if !locale.is_empty() { + q.push(locale.clone()); + } + let axis = |q: &mut Vec, v: Option, mask, names: &[(u8, &str)]| { + if let Some(key) = v.map(|n| n & mask) + && let Some((_, name)) = names.iter().find(|(value, _)| *value == key) + { + q.push((*name).to_owned()); + } + }; + axis(&mut q, get8(19), 0x03, &[(1, "neuter"), (2, "feminine"), (3, "masculine")]); + if let Some(sl) = get8(28) { + match sl & 0xc0 { + 0x40 => q.push("ldltr".into()), + 0x80 => q.push("ldrtl".into()), + _ => {} + } + } + if let Some(sw) = get16(30).filter(|&v| v != 0) { + q.push(format!("sw{sw}dp")); + } + if let Some(w) = get16(32).filter(|&v| v != 0) { + q.push(format!("w{w}dp")); + } + if let Some(h) = get16(34).filter(|&v| v != 0) { + q.push(format!("h{h}dp")); + } + if let Some(sl) = get8(28) { + match sl & 0x0f { + 1 => q.push("small".into()), + 2 => q.push("normal".into()), + 3 => q.push("large".into()), + 4 => q.push("xlarge".into()), + _ => {} + } + match sl & 0x30 { + 0x10 => q.push("notlong".into()), + 0x20 => q.push("long".into()), + _ => {} + } + } + axis(&mut q, get8(48), 0x03, &[(1, "notround"), (2, "round")]); + axis(&mut q, get8(49), 0x03, &[(1, "nowidecg"), (2, "widecg")]); + axis(&mut q, get8(49), 0x0c, &[(4, "lowdr"), (8, "highdr")]); + match get8(12) { + Some(1) => q.push("port".into()), + Some(2) => q.push("land".into()), + Some(3) => q.push("square".into()), + _ => {} + } + if let Some(ui) = get8(29) { + match ui & 0x0f { + 2 => q.push("desk".into()), + 3 => q.push("car".into()), + 4 => q.push("television".into()), + 5 => q.push("appliance".into()), + 6 => q.push("watch".into()), + 7 => q.push("vrheadset".into()), + _ => {} + } + match ui & 0x30 { + 0x10 => q.push("notnight".into()), + 0x20 => q.push("night".into()), + _ => {} + } + } + if let Some(d) = get16(14).filter(|&v| v != 0) { + q.push(match d { + 120 => "ldpi".into(), + 160 => "mdpi".into(), + 213 => "tvdpi".into(), + 240 => "hdpi".into(), + 320 => "xhdpi".into(), + 480 => "xxhdpi".into(), + 640 => "xxxhdpi".into(), + 0xfffe => "anydpi".into(), + 0xffff => "nodpi".into(), + d => format!("{d}dpi"), + }); + } + match get8(13) { + Some(1) => q.push("notouch".into()), + Some(3) => q.push("finger".into()), + _ => {} + } + axis(&mut q, get8(18), 0x03, &[(1, "keysexposed"), (2, "keyshidden"), (3, "keyssoft")]); + match get8(16) { + Some(1) => q.push("nokeys".into()), + Some(2) => q.push("qwerty".into()), + Some(3) => q.push("12key".into()), + _ => {} + } + axis(&mut q, get8(18), 0x0c, &[(4, "navexposed"), (8, "navhidden")]); + match get8(17) { + Some(1) => q.push("nonav".into()), + Some(2) => q.push("dpad".into()), + Some(3) => q.push("trackball".into()), + Some(4) => q.push("wheel".into()), + _ => {} + } + if let (Some(w), Some(h)) = (get16(20), get16(22)) + && w != 0 + && h != 0 + { + q.push(format!("{w}x{h}")); + } + if let Some(v) = get16(24).filter(|&v| v != 0) { + q.push(format!("v{v}")); + } + let s = if q.is_empty() { "default".to_string() } else { q.join("-") }; + (s, locale) +} + +/// A type's configuration is part of its header, not the entry offsets or payload. +fn type_config(r: &Reader<'_>, at: usize, header_size: usize) -> Option<(String, String)> { + let config = Reader::new(r.slice(at.checked_add(20)?, header_size.checked_sub(20)?)?); + let size = config.u32_le(0)? as usize; + if size < 4 || config.slice(0, size).is_none() { + return None; + } + Some(config_qualifiers(&config, 0)) +} + +struct Pkg<'a> { + name: &'a str, + id: u32, + types: &'a StringPool, + keys: &'a StringPool, +} + +fn type_name(p: &Pkg<'_>, id: u8) -> String { + p.types.get(u32::from(id).wrapping_sub(1)).map(str::to_string).unwrap_or_else(|| format!("type{id}")) +} + +/// Parse a resource table. +pub fn parse(data: &[u8], limits: Limits) -> Result { + let r = Reader::new(data); + let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("resource table header".into()))?; + if t != RES_TABLE { + return Err(Error::Malformed(format!("not a resource table (chunk type {t:#x})"))); + } + if h < 12 { + return Err(Error::Truncated("resource table header".into())); + } + let data = data.get(..size).ok_or_else(|| Error::Truncated("resource table payload".into()))?; + let r = Reader::new(data); + let mut table = Table::default(); + let mut global = StringPool::default(); + let mut pos = h; + while pos < size { + let Some((ct, _ch, cs)) = chunk(&r, pos) else { + table.warnings.push(format!("unreadable chunk at offset {pos}")); + break; + }; + match ct { + crate::axml::RES_STRING_POOL => match StringPool::parse(data, pos) { + Ok(p) => { + if p.strings.len() < p.declared { + table.truncated = true; + table.warnings.push(format!("global string pool was capped at {} of {} strings", p.strings.len(), p.declared)); + } + table.global_strings = p.declared; + global = p; + } + Err(e) => table.warnings.push(format!("global string pool: {e}")), + }, + RES_PACKAGE => { + if table.packages.len() >= MAX_PACKAGES { + table.truncated = true; + table.warnings.push("too many packages; the rest were skipped".into()); + } else { + parse_package(data, pos, cs, &global, &mut table, limits); + } + } + _ => {} + } + pos = match pos.checked_add(cs) { + Some(p) => p, + None => break, + }; + } + Ok(table) +} + +fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits) { + let Some(data) = pos.checked_add(cs).and_then(|end| data.get(..end)) else { + table.warnings.push("package runs past its resource table".into()); + return; + }; + let r = Reader::new(data); + let hsize = usize::from(r.u16_le(pos + 2).unwrap_or(0)); + if hsize < 284 { + table.warnings.push(format!("package at offset {pos}: incomplete header")); + return; + } + let id = r.u32_le(pos + 8).unwrap_or(0); + let name = utf16_fixed(&r, pos + 12, 128); + // Older 284-byte packages predate this field. Type names still use the + // unshifted chunk ID, while public resource identities include the offset. + let type_id_offset = if hsize >= 288 { r.u32_le(pos + 284).unwrap_or(0) } else { 0 }; + let Ok(type_id_offset) = u8::try_from(type_id_offset) else { + table.truncated = true; + table.warnings.push(format!("package {name}: type ID offset is outside the one-byte type field")); + return; + }; + let type_strings = r.u32_le(pos + 268).unwrap_or(0) as usize; + let key_strings = r.u32_le(pos + 276).unwrap_or(0) as usize; + let end = data.len(); + let mut read_pool = |offset: usize, label: &str| { + if offset == 0 { + return StringPool::default(); + } + let Some(start) = pos.checked_add(offset).filter(|&start| offset >= hsize && start < end) else { + table.warnings.push(format!("package {name}: {label} string pool is outside its payload")); + return StringPool::default(); + }; + match StringPool::parse(data, start) { + Ok(pool) => { + if pool.strings.len() < pool.declared { + table.truncated = true; + table.warnings.push(format!( + "package {name}: {label} string pool was capped at {} of {} strings", + pool.strings.len(), + pool.declared + )); + } + pool + } + Err(error) => { + table.warnings.push(format!("package {name}: {label} string pool: {error}")); + StringPool::default() + } + } + }; + let types = read_pool(type_strings, "type"); + let keys = read_pool(key_strings, "key"); + let mut package = Package { id, name: name.clone(), types: Vec::new(), keys: keys.declared, libraries: Vec::new() }; + let p = Pkg { name: &name, id, types: &types, keys: &keys }; + let mut c = pos.saturating_add(hsize.max(8)); + while c < end { + let Some((ct, ch, sz)) = chunk(&r, c) else { + table.warnings.push(format!("package {name}: unreadable chunk at offset {c}")); + break; + }; + // Each child was checked against its package; reads within it must also stop before + // the next sibling, including fixed-width library records and bag headers. + let Some(child) = data.get(..c.saturating_add(sz)) else { + table.warnings.push(format!("package {name}: child chunk runs past its package")); + break; + }; + let r = Reader::new(child); + let local_tid = r.u8(c + 8).unwrap_or(0); + let type_id = local_tid.checked_add(type_id_offset).filter(|_| local_tid != 0); + match (ct, type_id) { + (RES_TYPE_SPEC, Some(tid)) if ch >= 16 => { + let count = r.u32_le(c + 12).unwrap_or(0); + if !package.types.iter().any(|t| t.id == tid) && package.types.len() < 256 { + package.types.push(TypeInfo { id: tid, name: type_name(&p, local_tid), entry_count: count, configs: Vec::new() }); + } + } + (RES_TYPE, Some(tid)) if ch >= 24 => { + let Some((cfg, locale)) = type_config(&r, c, ch) else { + table.truncated = true; + table.warnings.push(format!("package {name}: incomplete type configuration at offset {c}")); + // The child extent was already validated by chunk(). + c += sz; + continue; + }; + match package.types.iter_mut().find(|t| t.id == tid) { + Some(t) => { + if !t.configs.contains(&cfg) && t.configs.len() < 4096 { + t.configs.push(cfg.clone()); + } + } + None => { + if package.types.len() < 256 { + package.types.push(TypeInfo { + id: tid, + name: type_name(&p, local_tid), + entry_count: r.u32_le(c + 12).unwrap_or(0), + configs: vec![cfg.clone()], + }) + } + } + } + parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits); + } + (RES_TYPE_SPEC | RES_TYPE, None) if ch >= 16 => { + table.truncated = true; + table.warnings.push(format!("package {name}: type ID {local_tid} with offset {type_id_offset} is outside the one-byte type field")); + } + (RES_LIBRARY, _) if ch >= 12 => { + let n = r.u32_le(c + 8).unwrap_or(0) as usize; + let available = (sz - ch) / 260; + if n > available { + table.warnings.push(format!("package {name}: library records run past their chunk")); + } + for i in 0..n.min(256).min(available) { + let e = c + ch + i * 260; + if let Some(lid) = r.u32_le(e) { + package.libraries.push((lid, utf16_fixed(&r, e + 4, 128))); + } + } + } + (RES_TYPE_SPEC | RES_TYPE | RES_LIBRARY, _) => { + table.warnings.push(format!("package {name}: incomplete chunk header at offset {c}")); + } + _ => {} + } + c = match c.checked_add(sz) { + Some(x) => x, + None => break, + }; + } + table.packages.push(package); +} + +#[allow(clippy::too_many_arguments)] +fn parse_type( + r: &Reader<'_>, + c: usize, + (ch, sz): (usize, usize), + (cfg, locale): (String, String), + p: &Pkg<'_>, + type_id: u8, + global: &StringPool, + table: &mut Table, + limits: Limits, +) { + let tid = r.u8(c + 8).unwrap_or(0); + let flags = r.u8(c + 9).unwrap_or(0); + let count = r.u32_le(c + 12).unwrap_or(0) as usize; + let entries_start = r.u32_le(c + 16).unwrap_or(0) as usize; + let end = c + sz; + let tname = type_name(p, tid); + let sparse = flags & 0x01 != 0; + let off16 = flags & 0x02 != 0; + // (entry index, offset from entries_start) + let mut slots: Vec<(u32, usize)> = Vec::new(); + let table_bytes = if sparse || off16 { count.saturating_mul(if sparse { 4 } else { 2 }) } else { count.saturating_mul(4) }; + if c.saturating_add(ch).saturating_add(table_bytes) > end { + table.warnings.push(format!("{tname} ({cfg}): entry table runs past its chunk")); + return; + } + if count != 0 && (entries_start < ch.saturating_add(table_bytes) || entries_start > sz) { + table.warnings.push(format!("{tname} ({cfg}): invalid entry data start")); + return; + } + for i in 0..count { + let at = c + ch; + if sparse { + let (Some(idx), Some(o)) = (r.u16_le(at + i * 4), r.u16_le(at + i * 4 + 2)) else { break }; + slots.push((u32::from(idx), usize::from(o) * 4)); + } else if off16 { + let Some(o) = r.u16_le(at + i * 2) else { break }; + if o != 0xffff { + slots.push((i as u32, usize::from(o) * 4)); + } + } else { + let Some(o) = r.u32_le(at + i * 4) else { break }; + if o != NO_ENTRY { + slots.push((i as u32, o as usize)); + } + } + } + for (idx, o) in slots { + if table.entries.len() >= limits.max_entries { + table.truncated = true; + return; + } + let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)) else { continue }; + if e.saturating_add(8) > end { + continue; + } + let esize = usize::from(r.u16_le(e).unwrap_or(0)); + let eflags = r.u16_le(e + 2).unwrap_or(0); + let id = (p.id << 24) | (u32::from(type_id) << 16) | (idx & 0xffff); + let mut entry = Entry { + id: format!("{id:#010x}"), + package: p.name.to_string(), + type_name: tname.clone(), + key: String::new(), + config: cfg.clone(), + locale: locale.clone(), + value: None, + value_type: None, + parent: None, + bag: Vec::new(), + raw: None, + }; + if eflags & 0x08 != 0 { + // Compact entry: key index in the size field, type in the high byte of flags. + entry.key = p.keys.get(u32::from(r.u16_le(e).unwrap_or(0))).unwrap_or("").to_string(); + let v = ResValue { data_type: (eflags >> 8) as u8, data: r.u32_le(e + 4).unwrap_or(0) }; + entry.value = Some(v.format(global)); + entry.value_type = Some(v.type_name()); + entry.raw = Some(v); + } else { + entry.key = r.u32_le(e + 4).and_then(|k| p.keys.get(k)).unwrap_or("").to_string(); + if eflags & 0x01 != 0 { + if esize < 16 || e.saturating_add(esize) > end { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): incomplete bag header")); + table.entries.push(entry); + continue; + } + let n = r.u32_le(e + 12).unwrap_or(0) as usize; + let mut m = e + esize; + if n > (end - m) / 12 { + table.truncated = true; + table.warnings.push(format!("{tname} ({cfg}): incomplete bag data")); + table.entries.push(entry); + continue; + } + let parent = r.u32_le(e + 8).unwrap_or(0); + if parent != 0 { + entry.parent = Some(format!("@{parent:#010x}")); + } + if n > MAX_BAG { + table.truncated = true; + } + for _ in 0..n.min(MAX_BAG) { + if m.saturating_add(12) > end { + break; + } + let name = r.u32_le(m).unwrap_or(0); + let v = ResValue { data_type: r.u8(m + 7).unwrap_or(0), data: r.u32_le(m + 8).unwrap_or(0) }; + entry.bag.push(BagItem { name: format!("@{name:#010x}"), value: v.format(global), value_type: v.type_name() }); + m += 12; + } + } else { + let v_at = e.saturating_add(esize.max(8)); + if v_at.saturating_add(8) <= end { + let v = ResValue { data_type: r.u8(v_at + 3).unwrap_or(0), data: r.u32_le(v_at + 4).unwrap_or(0) }; + entry.value = Some(v.format(global)); + entry.value_type = Some(v.type_name()); + entry.raw = Some(v); + } + } + } + table.entries.push(entry); + } +} + +impl Table { + /// String resources grouped by locale (`""` = default): (locale, key, value). + pub fn strings_by_locale(&self) -> std::collections::BTreeMap> { + let mut out: std::collections::BTreeMap> = Default::default(); + for e in self.entries.iter().filter(|e| e.type_name == "string") { + if let Some(v) = &e.value { + out.entry(e.locale.clone()).or_default().push((e.key.clone(), v.clone())); + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fixtures as fx; + + #[test] + fn incomplete_table_prefix_is_rejected() { + let bytes = fx::resources_arsc(); + assert!(matches!(parse(&bytes[..7], Limits::default()), Err(Error::Truncated(_)))); + } + + #[test] + fn decodes_table() { + let t = parse(&fx::resources_arsc(), Limits::default()).unwrap(); + assert!(t.warnings.is_empty(), "{:?}", t.warnings); + assert_eq!(t.packages.len(), 1); + let p = &t.packages[0]; + assert_eq!(p.id, 0x7f); + assert_eq!(p.name, fx::PACKAGE); + assert_eq!(p.types[0].name, "string"); + assert_eq!(p.types[0].configs, vec!["default", "fr"]); + let by = t.strings_by_locale(); + assert_eq!(by[""], vec![("app_name".to_string(), "Notes".to_string()), ("greeting".to_string(), "Hello".to_string())]); + assert_eq!(by["fr"], vec![("app_name".to_string(), "Notes FR".to_string()), ("greeting".to_string(), "Bonjour".to_string())]); + let app = t.entries.iter().find(|e| e.key == "app_name" && e.locale.is_empty()).unwrap(); + assert_eq!(app.id, "0x7f010000"); + let style = t.entries.iter().find(|e| e.type_name == "style").unwrap(); + assert_eq!(style.key, "AppTheme"); + assert_eq!(style.parent.as_deref(), Some("@0x01030005")); + assert_eq!(style.bag[0].value, "#ff336699"); + assert_eq!(style.config, "night-xhdpi-v21"); + } + + #[test] + fn distinct_locale_scripts_and_variants_keep_separate_keys() { + let mut cfg = [0u8; 64]; + cfg[0] = 64; + cfg[8..12].copy_from_slice(b"zhTW"); + cfg[36..40].copy_from_slice(b"Hant"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+Hant+TW"); + cfg[36..40].copy_from_slice(b"Hans"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+Hans+TW"); + cfg[52] = 1; // The inferred script is not part of the requested locale. + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "zh-rTW"); + cfg[40..45].copy_from_slice(b"POSIX"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+TW+POSIX"); + cfg[53..57].copy_from_slice(b"latn"); + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+TW+POSIX+u+nu+latn"); + cfg[0] = 36; // Bytes beyond the declared configuration are unrelated. + assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "zh-rTW"); + } + + #[test] + fn qualifiers() { + let mut cfg = vec![0u8; 64]; + cfg[0] = 64; + cfg[8] = b'e'; + cfg[9] = b's'; + cfg[10] = b'M'; + cfg[11] = b'X'; + cfg[12] = 2; + let (q, l) = config_qualifiers(&Reader::new(&cfg), 0); + assert_eq!(q, "es-rMX-land"); + assert_eq!(l, "es-rMX"); + } +} diff --git a/crates/android-res/src/axml.rs b/crates/android-res/src/axml.rs new file mode 100644 index 0000000000..3aea1f7ffc --- /dev/null +++ b/crates/android-res/src/axml.rs @@ -0,0 +1,793 @@ +//! Android binary XML (AXML): the compiled form of `AndroidManifest.xml` and `res/*.xml`. +//! Chunks, the string pool (UTF-8 and UTF-16), the resource-id map, namespaces, elements and +//! typed attribute values. Also the string pool and typed-value formatting that resource tables +//! share. Manifest inventory and policy are left to callers. + +use crate::Error; +use crate::bytes::Reader; +use serde::Serialize; + +pub const RES_STRING_POOL: u16 = 0x0001; +pub const RES_XML: u16 = 0x0003; +const XML_START_NS: u16 = 0x0100; +const XML_END_NS: u16 = 0x0101; +const XML_START_ELEMENT: u16 = 0x0102; +const XML_END_ELEMENT: u16 = 0x0103; +const XML_CDATA: u16 = 0x0104; +const XML_RESOURCE_MAP: u16 = 0x0180; + +/// Most strings decoded from one pool. +const MAX_STRINGS: usize = 1_000_000; +/// Longest string kept (characters). +const MAX_STRING: usize = 64 * 1024; +/// Base budget for decoded string bytes; larger chunks allow at most three times their size. +const BASE_POOL_BYTES: usize = 64 << 20; +/// Most extra UTF-8 length candidates examined across one string pool. +const MAX_RECOVERY_PROBES: usize = 65_536; +/// Most XML nodes decoded. +const MAX_NODES: usize = 200_000; +/// Deepest element nesting tracked. +const MAX_DEPTH: usize = 512; + +pub const ANDROID_NS: &str = "http://schemas.android.com/apk/res/android"; + +/// A chunk header: type, header size, total size, at `off`. +pub(crate) fn chunk(r: &Reader<'_>, off: usize) -> Option<(u16, usize, usize)> { + let t = r.u16_le(off)?; + let h = usize::from(r.u16_le(off.checked_add(2)?)?); + let s = r.u32_le(off.checked_add(4)?)? as usize; + if h < 8 || s < h || off.checked_add(s)? > r.len() { + return None; + } + Some((t, h, s)) +} + +/// Reads the bounded Android chunk header at the given byte offset. +pub fn chunk_header(data: &[u8], off: usize) -> Option<(u16, usize, usize)> { + chunk(&Reader::new(data), off) +} + +/// A decoded string pool. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct StringPool { + pub strings: Vec, + pub utf8: bool, + /// Strings the pool declared (may exceed `strings.len()` when capped). + pub declared: usize, +} + +impl StringPool { + pub fn get(&self, i: u32) -> Option<&str> { + if i == u32::MAX { + return None; + } + self.strings.get(i as usize).map(String::as_str) + } + + /// Parse the pool whose chunk starts at `off`, retaining a prefix within the string and byte budgets. + pub fn parse(data: &[u8], off: usize) -> Result { + let mut recovery_left = MAX_RECOVERY_PROBES; + Self::parse_with_recovery_budget(data, off, &mut recovery_left) + } + + fn parse_with_recovery_budget(data: &[u8], off: usize, recovery_left: &mut usize) -> Result { + let r = Reader::new(data); + let (t, hdr, size) = chunk(&r, off).ok_or_else(|| Error::Truncated("string pool header".into()))?; + if t != RES_STRING_POOL { + return Err(Error::Malformed(format!("expected a string pool, found chunk type {t:#x}"))); + } + if hdr < 28 { + return Err(Error::Malformed("string pool header is smaller than 28 bytes".into())); + } + let r = Reader::new(r.slice(off, size).ok_or_else(|| Error::Truncated("string pool".into()))?); + let count = r.u32_le(8).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let styles = r.u32_le(12).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let flags = r.u32_le(16).ok_or_else(|| Error::Truncated("string pool".into()))?; + let strings_start = r.u32_le(20).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let styles_start = r.u32_le(24).ok_or_else(|| Error::Truncated("string pool".into()))? as usize; + let utf8 = flags & (1 << 8) != 0; + let offsets_end = count + .checked_add(styles) + .and_then(|n| n.checked_mul(4)) + .and_then(|n| hdr.checked_add(n)) + .ok_or_else(|| Error::Malformed("string pool offset tables are too large".into()))?; + if offsets_end > size || strings_start > size || (count != 0 && strings_start < offsets_end) { + return Err(Error::Malformed("string pool offset tables or string data lie outside their area".into())); + } + if (styles != 0 && styles_start == 0) + || (styles_start != 0 && (styles_start < offsets_end || styles_start < strings_start || styles_start > size)) + { + return Err(Error::Malformed("string pool style data lie outside their area".into())); + } + let end = if styles_start == 0 { size } else { styles_start }; + let string_bytes = r.slice(strings_start, end - strings_start).ok_or_else(|| Error::Truncated("string data".into()))?; + let strings_reader = Reader::new(string_bytes); + let mut strings = Vec::with_capacity(count.min(MAX_STRINGS).min(65_536)); + let mut bytes_left = BASE_POOL_BYTES.max(size.saturating_mul(3)); + for i in 0..count.min(MAX_STRINGS) { + let at = r.u32_le(hdr + i * 4).ok_or_else(|| Error::Truncated("string offsets".into()))? as usize; + let s = if at >= string_bytes.len() { + None + } else if utf8 { + utf8_string(&strings_reader, at, string_bytes.len(), recovery_left) + } else { + utf16_string(&strings_reader, at, string_bytes.len()) + }; + let s = s.unwrap_or_default(); + if s.len() > bytes_left { + break; + } + bytes_left -= s.len(); + strings.push(s); + } + Ok(StringPool { strings, utf8, declared: count }) + } +} + +fn utf8_len(r: &Reader<'_>, at: usize) -> Option<(usize, usize)> { + let b0 = usize::from(r.u8(at)?); + if b0 & 0x80 != 0 { + let b1 = usize::from(r.u8(at + 1)?); + Some((((b0 & 0x7f) << 8) | b1, 2)) + } else { + Some((b0, 1)) + } +} + +fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize) -> Option { + let (_chars, n1) = utf8_len(r, at)?; + let (mut bytes, n2) = utf8_len(r, at.checked_add(n1)?)?; + let start = at.checked_add(n1 + n2)?; + // Older AAPT keeps only the low 15 length bits; probe matching lengths inside this pool. + loop { + let terminator = start.checked_add(bytes)?; + if terminator >= end { + return None; + } + // The declared candidate costs one read per entry, already bounded by MAX_STRINGS. + if bytes >= 0x8000 { + *recovery_left = recovery_left.checked_sub(1)?; + } + if r.u8(terminator)? == 0 { + break; + } + bytes = bytes.checked_add(0x8000)?; + } + let b = r.slice(start, bytes.min(MAX_STRING * 4))?; + Some(String::from_utf8_lossy(b).into_owned()) +} + +fn utf16_string(r: &Reader<'_>, at: usize, end: usize) -> Option { + let u0 = usize::from(r.u16_le(at)?); + let (len, hdr) = if u0 & 0x8000 != 0 { (((u0 & 0x7fff) << 16) | usize::from(r.u16_le(at + 2)?), 4) } else { (u0, 2) }; + let start = at.checked_add(hdr)?; + let terminator = start.checked_add(len.checked_mul(2)?)?; + if terminator.checked_add(2)? > end || r.u16_le(terminator)? != 0 { + return None; + } + let n = len.min(MAX_STRING); + let mut units = Vec::with_capacity(n); + for i in 0..n { + units.push(r.u16_le(start + i * 2)?); + } + Some(String::from_utf16_lossy(&units)) +} + +/// A typed value (`Res_value`): data type and 32-bit data. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +pub struct ResValue { + pub data_type: u8, + pub data: u32, +} + +impl ResValue { + pub fn type_name(&self) -> &'static str { + match self.data_type { + 0x00 => "null", + 0x01 => "reference", + 0x02 => "attribute", + 0x03 => "string", + 0x04 => "float", + 0x05 => "dimension", + 0x06 => "fraction", + 0x07 => "dynamic-reference", + 0x08 => "dynamic-attribute", + 0x10 => "int-dec", + 0x11 => "int-hex", + 0x12 => "boolean", + 0x1c => "color-argb8", + 0x1d => "color-rgb8", + 0x1e => "color-argb4", + 0x1f => "color-rgb4", + _ => "unknown", + } + } + + /// Human form; strings come from `pool`. + pub fn format(&self, pool: &StringPool) -> String { + let d = self.data; + match self.data_type { + 0x00 => { + if d == 1 { + "@empty".into() + } else { + "@null".into() + } + } + 0x01 | 0x07 => { + if d == 0 { + "@null".into() + } else { + format!("@{d:#010x}") + } + } + 0x02 | 0x08 => format!("?{d:#010x}"), + 0x03 => pool.get(d).unwrap_or("").to_string(), + 0x04 => format!("{}", f32::from_bits(d)), + 0x05 => complex(d, &["px", "dp", "sp", "pt", "in", "mm"]), + 0x06 => complex(d, &["%", "%p"]), + 0x10 => (d as i32).to_string(), + 0x11 => format!("{d:#x}"), + 0x12 => (if d != 0 { "true" } else { "false" }).into(), + 0x1c..=0x1f => format!("#{d:08x}"), + _ => format!("{d:#x} (type {:#x})", self.data_type), + } + } +} + +fn complex(d: u32, units: &[&str]) -> String { + const RADIX: [f64; 4] = [1.0, 1.0 / 128.0, 1.0 / 32768.0, 1.0 / 8_388_608.0]; + let mantissa = f64::from((d & 0xffff_ff00) as i32 >> 8); + let radix = RADIX.get(((d >> 4) & 3) as usize).copied().unwrap_or(1.0); + let mut v = mantissa * radix; + let unit = units.get((d & 0xf) as usize).copied().unwrap_or("?"); + if units.len() == 2 { + v *= 100.0; + } + let v = (v * 10_000.0).round() / 10_000.0; + format!("{v}{unit}") +} + +/// One attribute of an element. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Attribute { + #[serde(skip_serializing_if = "Option::is_none")] + pub namespace: Option, + pub name: String, + /// The framework/app resource id of the attribute name, when the resource map gives one. + #[serde(skip_serializing_if = "Option::is_none")] + pub resource_id: Option, + /// Formatted value. + pub value: String, + pub value_type: &'static str, + #[serde(skip)] + pub raw: ResValue, +} + +/// One XML node event. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Node { + Start { depth: usize, name: String, namespace: Option, line: u32, attributes: Vec }, + End { depth: usize, name: String }, + Text { depth: usize, text: String }, + Namespace { prefix: String, uri: String }, +} + +/// A decoded binary XML document. +#[derive(Debug, Clone, Default, PartialEq, Serialize)] +pub struct Document { + pub nodes: Vec, + #[serde(skip)] + pub pool: StringPool, + pub resource_ids: usize, + pub namespaces: Vec<(String, String)>, + pub truncated: bool, + pub warnings: Vec, +} + +/// Names of common framework attributes by resource id, used when a name string was stripped. +pub fn framework_attr(id: u32) -> Option<&'static str> { + Some(match id { + 0x0101_0000 => "theme", + 0x0101_0001 => "label", + 0x0101_0002 => "icon", + 0x0101_0003 => "name", + 0x0101_0006 => "permission", + 0x0101_0007 => "readPermission", + 0x0101_0008 => "writePermission", + 0x0101_0009 => "protectionLevel", + 0x0101_000e => "enabled", + 0x0101_000f => "debuggable", + 0x0101_0010 => "exported", + 0x0101_0018 => "authorities", + 0x0101_020c => "minSdkVersion", + 0x0101_021b => "versionCode", + 0x0101_021c => "versionName", + 0x0101_0270 => "targetSdkVersion", + 0x0101_0271 => "maxSdkVersion", + 0x0101_0280 => "allowBackup", + _ => return None, + }) +} + +/// Decode a binary XML file. +pub fn parse(data: &[u8]) -> Result { + parse_with_limits(data, MAX_NODES, MAX_DEPTH) +} + +fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize) -> Result { + let r = Reader::new(data); + let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("binary XML header".into()))?; + if t != RES_XML { + return Err(Error::Malformed(format!("not binary XML (chunk type {t:#x})"))); + } + let data = r.slice(0, size).ok_or_else(|| Error::Truncated("binary XML document".into()))?; + let r = Reader::new(data); + let mut doc = Document::default(); + let mut res_map: Vec = Vec::new(); + let mut pos = h; + let mut depth = 0usize; + let mut ns_stack: Vec<(String, String)> = Vec::new(); + while pos < size { + let Some((ct, ch, cs)) = chunk(&r, pos) else { + doc.truncated = true; + doc.warnings.push(format!("unreadable chunk at offset {pos}")); + break; + }; + let extension = match ct { + XML_START_NS | XML_END_NS | XML_END_ELEMENT => 8, + XML_START_ELEMENT => 20, + XML_CDATA => 12, + _ => 0, + }; + if extension != 0 && (ch < 16 || cs - ch < extension) { + doc.truncated = true; + doc.warnings.push(format!("incomplete XML node at offset {pos}")); + break; + } + if matches!(ct, XML_START_NS | XML_START_ELEMENT | XML_END_ELEMENT | XML_CDATA) && doc.nodes.len() >= max_nodes { + doc.truncated = true; + doc.warnings.push("XML node limit reached; the remaining events were skipped".into()); + break; + } + match ct { + RES_STRING_POOL => match StringPool::parse(data, pos) { + Ok(p) => { + if p.strings.len() < p.declared { + doc.truncated = true; + doc.warnings.push(format!("string pool was capped at {} of {} strings", p.strings.len(), p.declared)); + } + doc.pool = p; + } + Err(e) => doc.warnings.push(format!("string pool: {e}")), + }, + XML_RESOURCE_MAP => { + let n = (cs - ch) / 4; + res_map = (0..n.min(MAX_STRINGS)).filter_map(|i| r.u32_le(pos + ch + i * 4)).collect(); + doc.resource_ids = res_map.len(); + } + XML_START_NS | XML_END_NS => { + let prefix = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + let uri = r.u32_le(pos + ch + 4).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + if ct == XML_START_NS { + if doc.namespaces.len() < 256 { + doc.namespaces.push((prefix.clone(), uri.clone())); + } + if ns_stack.len() < MAX_DEPTH { + ns_stack.push((prefix.clone(), uri.clone())); + } + doc.nodes.push(Node::Namespace { prefix, uri }); + } else { + ns_stack.pop(); + } + } + XML_START_ELEMENT => { + if depth >= max_depth { + doc.truncated = true; + doc.warnings.push("XML nesting limit reached; the remaining events were skipped".into()); + break; + } + let line = r.u32_le(pos + 8).unwrap_or(0); + let ext = pos + ch; + let ns = r.u32_le(ext).and_then(|i| doc.pool.get(i)).map(str::to_string); + let name = r.u32_le(ext + 4).and_then(|i| doc.pool.get(i)).unwrap_or("?").to_string(); + let a_start = usize::from(r.u16_le(ext + 8).unwrap_or(20)); + let a_size = usize::from(r.u16_le(ext + 10).unwrap_or(20)); + let a_count = usize::from(r.u16_le(ext + 12).unwrap_or(0)); + if a_count != 0 && (a_start < 20 || a_size < 20) { + doc.truncated = true; + doc.warnings.push(format!("element {name}: invalid attribute table layout")); + break; + } + let mut attributes = Vec::new(); + for i in 0..a_count { + let relative = a_start + i * a_size; + if relative.checked_add(a_size).is_none_or(|end| end > cs - ch) { + doc.truncated = true; + doc.warnings.push(format!("element {name}: attribute {i} runs past its chunk")); + break; + } + let a = ext + relative; + let value_size = usize::from(r.u16_le(a + 12).unwrap_or(0)); + if value_size < 8 || value_size > a_size - 12 { + doc.truncated = true; + doc.warnings.push(format!("element {name}: invalid typed value size in attribute {i}")); + break; + } + let ans = r.u32_le(a).and_then(|i| doc.pool.get(i)).map(str::to_string); + let name_idx = r.u32_le(a + 4).unwrap_or(u32::MAX); + let raw_str = r.u32_le(a + 8).unwrap_or(u32::MAX); + let vt = r.u8(a + 15).unwrap_or(0); + let vd = r.u32_le(a + 16).unwrap_or(0); + let rid = res_map.get(name_idx as usize).copied(); + let mut aname = doc.pool.get(name_idx).unwrap_or("").to_string(); + if aname.is_empty() { + aname = rid.and_then(framework_attr).map(str::to_string).unwrap_or_else(|| format!("attr_{name_idx}")); + } + let raw = ResValue { data_type: vt, data: vd }; + let value = if vt == 0x03 || (raw_str != u32::MAX && vt == 0) { + doc.pool.get(if vt == 0x03 { vd } else { raw_str }).unwrap_or("").to_string() + } else { + raw.format(&doc.pool) + }; + attributes.push(Attribute { + namespace: ans, + name: aname, + resource_id: rid.map(|x| format!("{x:#010x}")), + value, + value_type: raw.type_name(), + raw, + }); + } + doc.nodes.push(Node::Start { depth, name, namespace: ns, line, attributes }); + depth += 1; + } + XML_END_ELEMENT => { + depth = depth.saturating_sub(1); + let name = r.u32_le(pos + ch + 4).and_then(|i| doc.pool.get(i)).unwrap_or("?").to_string(); + doc.nodes.push(Node::End { depth, name }); + } + XML_CDATA => { + let text = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string(); + doc.nodes.push(Node::Text { depth, text }); + } + _ => {} + } + pos = match pos.checked_add(cs) { + Some(p) => p, + None => break, + }; + } + Ok(doc) +} + +fn esc(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +impl Document { + fn prefix_for(&self, uri: &str) -> Option<&str> { + self.namespaces.iter().find(|(_, u)| u == uri).map(|(p, _)| p.as_str()) + } + + /// An XML text rendition (for reading, not byte-exact source). + pub fn to_xml(&self, max_bytes: usize) -> String { + let mut out = String::from("\n"); + let mut first = true; + for n in &self.nodes { + if out.len() > max_bytes { + out.push_str("\n"); + break; + } + match n { + Node::Start { depth, name, attributes, .. } => { + out.push_str(&" ".repeat((*depth).min(64))); + out.push('<'); + out.push_str(name); + if first { + for (p, u) in &self.namespaces { + out.push_str(&format!(" xmlns:{p}=\"{}\"", esc(u))); + } + first = false; + } + for a in attributes { + let p = a.namespace.as_deref().and_then(|u| self.prefix_for(u)).map(|p| format!("{p}:")).unwrap_or_default(); + out.push_str(&format!(" {p}{}=\"{}\"", a.name, esc(&a.value))); + } + out.push_str(">\n"); + } + Node::End { depth, name } => { + out.push_str(&" ".repeat((*depth).min(64))); + out.push_str(&format!("\n")); + } + Node::Text { depth, text } => { + out.push_str(&" ".repeat((*depth).min(64))); + out.push_str(&esc(text)); + out.push('\n'); + } + Node::Namespace { .. } => {} + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fixtures as fx; + + fn pool_with_offsets(offsets: &[u32], string_data: &[u8]) -> Vec { + let start = 28 + offsets.len() * 4; + let mut data = vec![0; start]; + data[..2].copy_from_slice(&RES_STRING_POOL.to_le_bytes()); + data[2..4].copy_from_slice(&28u16.to_le_bytes()); + data[8..12].copy_from_slice(&(offsets.len() as u32).to_le_bytes()); + data[16..20].copy_from_slice(&0x100u32.to_le_bytes()); + data[20..24].copy_from_slice(&(start as u32).to_le_bytes()); + for (i, offset) in offsets.iter().enumerate() { + let at = 28 + i * 4; + data[at..at + 4].copy_from_slice(&offset.to_le_bytes()); + } + data.extend_from_slice(string_data); + data.resize(data.len().next_multiple_of(4), b'x'); + let size = data.len() as u32; + data[4..8].copy_from_slice(&size.to_le_bytes()); + data + } + + fn append_legacy_ascii(data: &mut Vec, len: usize) -> u32 { + let offset = data.len() as u32; + let encoded = [0x80 | ((len >> 8) & 0x7f) as u8, (len & 0xff) as u8]; + data.extend_from_slice(&encoded); + data.extend_from_slice(&encoded); + data.resize(data.len() + len, b'x'); + data.push(0); + offset + } + + fn shared_ascii_pool(utf8: bool, count: usize) -> Vec { + let len = 16_384usize; + let mut strings = Vec::new(); + if utf8 { + append_legacy_ascii(&mut strings, len); + } else { + strings.extend_from_slice(&(len as u16).to_le_bytes()); + for _ in 0..len { + strings.extend_from_slice(b"x\0"); + } + strings.extend_from_slice(&[0, 0]); + } + let mut data = pool_with_offsets(&vec![0; count], &strings); + if !utf8 { + data[16..20].fill(0); + } + data + } + + #[test] + fn shared_offsets_spend_a_pool_byte_budget() { + for utf8 in [true, false] { + let mut data = shared_ascii_pool(utf8, 8192); + for appended in [false, true] { + if appended { + // Unrelated bytes after the chunk cannot buy more retained copies. + data.resize(24 << 20, 0); + } + let pool = StringPool::parse(&data, 0).unwrap(); + assert_eq!(pool.declared, 8192); + assert_eq!(pool.strings.len(), 4096); + assert_eq!(pool.strings.iter().map(String::len).sum::(), 64 << 20); + assert_eq!(pool.get(4095).map(str::len), Some(16_384)); + assert_eq!(pool.get(4096), None); + } + let data = shared_ascii_pool(utf8, 2); + let pool = StringPool::parse(&data, 0).unwrap(); + assert_eq!(pool.strings.len(), 2); + assert_eq!(pool.get(0), pool.get(1)); + } + } + + fn pool_container(kind: u16, header: usize, children: &[u8]) -> Vec { + let mut data = vec![0; header]; + data[0..2].copy_from_slice(&kind.to_le_bytes()); + data[2..4].copy_from_slice(&(header as u16).to_le_bytes()); + data.extend_from_slice(children); + let len = data.len() as u32; + data[4..8].copy_from_slice(&len.to_le_bytes()); + data + } + + #[test] + fn xml_and_resource_tables_disclose_partial_string_pools() { + let pool = shared_ascii_pool(true, 8192); + { + let doc = parse(&pool_container(RES_XML, 8, &pool)).unwrap(); + assert!(doc.truncated); + assert!(doc.warnings.iter().any(|w| w.contains("string pool") && w.contains("4096 of 8192"))); + assert_eq!(doc.pool.strings.len(), 4096); + } + let table = crate::arsc::parse(&pool_container(2, 12, &pool), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated); + assert_eq!(table.global_strings, 8192); + assert!(table.warnings.iter().any(|w| w.contains("global string pool") && w.contains("4096 of 8192"))); + for (field, label) in [(268, "type"), (276, "key")] { + let mut package = pool_container(0x0200, 288, &pool); + package[8..12].copy_from_slice(&0x7fu32.to_le_bytes()); + package[field..field + 4].copy_from_slice(&288u32.to_le_bytes()); + let table = crate::arsc::parse(&pool_container(2, 12, &package), crate::arsc::Limits::default()).unwrap(); + assert!(table.truncated, "{label}"); + assert!(table.warnings.iter().any(|w| w.contains(&format!("{label} string pool")) && w.contains("4096 of 8192"))); + assert_eq!(table.packages.len(), 1); + } + } + + #[test] + fn repeated_offsets_share_the_utf8_recovery_budget() { + let mut strings = Vec::new(); + let long = append_legacy_ascii(&mut strings, 0x8000); + let short = strings.len() as u32; + strings.extend_from_slice(b"\x02\x02ok\0"); + let data = pool_with_offsets(&[long, long, long, short], &strings); + let mut left = 2; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, 0); + assert_eq!(parsed.declared, 4); + assert_eq!(parsed.strings.len(), 4); + assert_eq!(parsed.get(0).map(str::len), Some(0x8000)); + assert_eq!(parsed.get(1), parsed.get(0)); + assert_eq!(parsed.get(2), Some("")); + assert_eq!(parsed.get(3), Some("ok")); + } + + #[test] + fn distinct_offsets_share_the_utf8_recovery_budget() { + let mut strings = Vec::new(); + let mut offsets: Vec = (0..3).map(|_| append_legacy_ascii(&mut strings, 0x8000)).collect(); + offsets.push(strings.len() as u32); + strings.extend_from_slice(b"\x02\x02ok\0"); + let data = pool_with_offsets(&offsets, &strings); + let mut left = 2; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, 0); + assert_eq!(parsed.get(0).map(str::len), Some(0x8000)); + assert_eq!(parsed.get(1).map(str::len), Some(0x8000)); + assert_eq!(parsed.get(2), Some("")); + assert_eq!(parsed.get(3), Some("ok")); + } + + #[test] + fn utf8_recovery_stops_before_a_probe_without_credit() { + let mut strings = Vec::new(); + let long = append_legacy_ascii(&mut strings, 0x10000); + let short = strings.len() as u32; + strings.extend_from_slice(b"\x02\x02ok\0"); + let data = pool_with_offsets(&[long, short], &strings); + for (allowance, length, remaining) in [(0, 0, 0), (1, 0, 0), (2, 0x10000, 0), (3, 0x10000, 1)] { + let mut left = allowance; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, remaining); + assert_eq!(parsed.get(0).map(str::len), Some(length)); + assert_eq!(parsed.get(1), Some("ok")); + } + } + + #[test] + fn short_strings_and_out_of_bounds_candidates_spend_no_recovery_probes() { + let data = pool_with_offsets(&[0, 5], b"\x80\0\x80\0x\x02\x02ok\0"); + let mut left = 7; + let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap(); + assert_eq!(left, 7); + assert_eq!(parsed.get(0), Some("")); + assert_eq!(parsed.get(1), Some("ok")); + } + + #[test] + fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() { + let mut strings = vec![b'x'; 2 * 0x8000 + 16]; + strings[..4].copy_from_slice(&[0x80, 0, 0x80, 0]); + let long = append_legacy_ascii(&mut strings, 0x8000); + let short = strings.len() as u32; + strings.extend_from_slice(b"\x02\x02ok\0"); + // Offset zero has three in-bounds extra candidates, all nonzero. + let repeated = MAX_RECOVERY_PROBES / 3 + 1; + let mut offsets = vec![0; repeated]; + offsets.extend([long, short]); + let data = pool_with_offsets(&offsets, &strings); + let parsed = StringPool::parse(&data, 0).unwrap(); + assert_eq!(parsed.declared, repeated + 2); + assert_eq!(parsed.strings.len(), repeated + 2); + assert!(parsed.strings[..repeated].iter().all(String::is_empty)); + assert_eq!(parsed.get(repeated as u32), Some("")); + assert_eq!(parsed.get((repeated + 1) as u32), Some("ok")); + } + + fn chunk_at(data: &[u8], kind: u16) -> usize { + let r = Reader::new(data); + let mut pos = 8; + loop { + let (t, _, n) = chunk(&r, pos).unwrap(); + if t == kind { + return pos; + } + pos += n; + } + } + + #[test] + fn namespace_extensions_follow_the_declared_header() { + let mut data = fx::manifest_axml(); + let pos = chunk_at(&data, XML_START_NS); + data.splice(pos + 16..pos + 16, [0xff; 4]); + data[pos + 2..pos + 4].copy_from_slice(&20u16.to_le_bytes()); + data[pos + 4..pos + 8].copy_from_slice(&28u32.to_le_bytes()); + let len = data.len() as u32; + data[4..8].copy_from_slice(&len.to_le_bytes()); + let doc = parse(&data).unwrap(); + assert!(doc.warnings.is_empty()); + assert_eq!(doc.namespaces[0], ("android".into(), ANDROID_NS.into())); + } + + #[test] + fn extended_attribute_strides_keep_each_manifest_value() { + let mut data = fx::manifest_axml(); + let pos = chunk_at(&data, XML_START_ELEMENT); + let ext = pos + 16; + // The fixture writes three 20-byte attributes with 8-byte typed values. + for index in (1..=3).rev() { + let end = ext + 20 + index * 20; + data.splice(end..end, [0xff; 4]); + } + data[ext + 10..ext + 12].copy_from_slice(&24u16.to_le_bytes()); + data[pos + 4..pos + 8].copy_from_slice(&(36 + 3 * 24u32).to_le_bytes()); + let len = data.len() as u32; + data[4..8].copy_from_slice(&len.to_le_bytes()); + + let doc = parse(&data).unwrap(); + assert!(!doc.truncated); + assert!(doc.warnings.is_empty(), "{:?}", doc.warnings); + let Node::Start { attributes, .. } = &doc.nodes[1] else { + panic!("expected the manifest start after the namespace"); + }; + let pairs: Vec<_> = attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect(); + assert_eq!(pairs, [("package", fx::PACKAGE), ("versionCode", "42"), ("versionName", "1.2.3")]); + } + + #[test] + fn dropping_a_close_event_marks_the_document_partial() { + let bytes = fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::End("root")]); + let complete = parse_with_limits(&bytes, 3, 1).unwrap(); + assert!(!complete.truncated); + assert!(matches!(complete.nodes.last(), Some(Node::End { depth: 0, .. }))); + + let partial = parse_with_limits(&bytes, 2, 1).unwrap(); + assert!(partial.truncated); + assert_eq!(partial.nodes, complete.nodes[..2]); + } + + #[test] + fn nesting_limit_keeps_an_exact_prefix_instead_of_saturating_depth() { + let bytes = + fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::Start("child", vec![]), fx::AxNode::End("child"), fx::AxNode::End("root")]); + let complete = parse_with_limits(&bytes, 5, 2).unwrap(); + assert!(!complete.truncated); + assert!(matches!(complete.nodes[3], Node::End { depth: 1, .. })); + assert!(matches!(complete.nodes[4], Node::End { depth: 0, .. })); + + let partial = parse_with_limits(&bytes, 5, 1).unwrap(); + assert!(partial.truncated); + assert_eq!(partial.nodes, complete.nodes[..2]); + } + + #[test] + fn values_format() { + let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1 }; + assert_eq!(ResValue { data_type: 0x05, data: (16 << 8) | 1 }.format(&p), "16dp"); + assert_eq!(ResValue { data_type: 0x12, data: 0xffff_ffff }.format(&p), "true"); + assert_eq!(ResValue { data_type: 0x1c, data: 0xff00_ff00 }.format(&p), "#ff00ff00"); + assert_eq!(ResValue { data_type: 0x10, data: (-5i32) as u32 }.format(&p), "-5"); + assert_eq!(ResValue { data_type: 0x03, data: 0 }.format(&p), "x"); + assert_eq!(ResValue { data_type: 0x04, data: 1.5f32.to_bits() }.format(&p), "1.5"); + } +} diff --git a/crates/android-res/src/bytes.rs b/crates/android-res/src/bytes.rs new file mode 100644 index 0000000000..bf2e751d66 --- /dev/null +++ b/crates/android-res/src/bytes.rs @@ -0,0 +1,37 @@ +//! Checked little/big-endian reads over untrusted bytes. Every read returns `None` when out of range. + +#[derive(Debug, Clone, Copy)] +pub struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + pub fn len(&self) -> usize { + self.data.len() + } + + pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } +} diff --git a/crates/android-res/src/fixtures.rs b/crates/android-res/src/fixtures.rs new file mode 100644 index 0000000000..54235d3b0c --- /dev/null +++ b/crates/android-res/src/fixtures.rs @@ -0,0 +1,376 @@ +//! Test-only XML and resource table fixtures ported from Craft Anything. + +pub const PACKAGE: &str = "com.example.notes"; + +fn u16le(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_le_bytes()); +} + +fn u32le(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_le_bytes()); +} + +fn align4(v: &mut Vec) { + while !v.len().is_multiple_of(4) { + v.push(0); + } +} + +/// A string pool chunk (UTF-16, or UTF-8 when `utf8`). +pub fn string_pool(strings: &[&str], utf8: bool) -> Vec { + let mut data = Vec::new(); + let mut offs = Vec::new(); + for s in strings { + offs.push(data.len() as u32); + if utf8 { + let n16 = s.encode_utf16().count(); + data.push(n16 as u8); + data.push(s.len() as u8); + data.extend_from_slice(s.as_bytes()); + data.push(0); + } else { + let units: Vec = s.encode_utf16().collect(); + u16le(&mut data, units.len() as u16); + for u in units { + u16le(&mut data, u); + } + u16le(&mut data, 0); + } + } + align4(&mut data); + let strings_start = 28 + 4 * strings.len(); + let mut v = Vec::new(); + u16le(&mut v, 0x0001); + u16le(&mut v, 28); + u32le(&mut v, (strings_start + data.len()) as u32); + u32le(&mut v, strings.len() as u32); + u32le(&mut v, 0); + u32le(&mut v, if utf8 { 1 << 8 } else { 0 }); + u32le(&mut v, strings_start as u32); + u32le(&mut v, 0); + for o in offs { + u32le(&mut v, o); + } + v.extend_from_slice(&data); + v +} + +/// An attribute value in a binary XML element. +#[derive(Debug, Clone, Copy)] +pub enum AxVal<'a> { + Str(&'a str), + Bool(bool), + Int(i32), + Hex(u32), + Ref(u32), +} + +#[derive(Debug, Clone)] +pub struct AxAttr<'a> { + pub name: &'a str, + /// Android framework attribute (namespaced, with its resource id). + pub res_id: Option, + pub val: AxVal<'a>, +} + +#[derive(Debug, Clone)] +pub enum AxNode<'a> { + Start(&'a str, Vec>), + End(&'a str), +} + +const NS: &str = "http://schemas.android.com/apk/res/android"; + +/// Shorthand for an `android:` attribute. +pub fn a<'a>(name: &'a str, res_id: u32, val: AxVal<'a>) -> AxAttr<'a> { + AxAttr { name, res_id: Some(res_id), val } +} + +/// Write a binary XML document with the android namespace declared on the root. +pub fn axml(nodes: &[AxNode<'_>]) -> Vec { + let mut strings: Vec = Vec::new(); + let mut ids: Vec = Vec::new(); + for n in nodes { + if let AxNode::Start(_, attrs) = n { + for at in attrs { + if let Some(id) = at.res_id + && !strings.iter().any(|s| s == at.name) + { + strings.push(at.name.to_string()); + ids.push(id); + } + } + } + } + let intern = |s: &str, strings: &mut Vec| -> u32 { + if let Some(i) = strings.iter().position(|x| x == s) { + return i as u32; + } + strings.push(s.to_string()); + (strings.len() - 1) as u32 + }; + let prefix = intern("android", &mut strings); + let uri = intern(NS, &mut strings); + let mut body = Vec::new(); + let ns_chunk = |t: u16| { + let mut c = Vec::new(); + u16le(&mut c, t); + u16le(&mut c, 16); + u32le(&mut c, 24); + u32le(&mut c, 1); + u32le(&mut c, u32::MAX); + u32le(&mut c, prefix); + u32le(&mut c, uri); + c + }; + body.extend(ns_chunk(0x0100)); + for (line, n) in nodes.iter().enumerate() { + match n { + AxNode::Start(name, attrs) => { + let nidx = intern(name, &mut strings); + let mut c = Vec::new(); + u16le(&mut c, 0x0102); + u16le(&mut c, 16); + u32le(&mut c, (36 + 20 * attrs.len()) as u32); + u32le(&mut c, line as u32 + 2); + u32le(&mut c, u32::MAX); + u32le(&mut c, u32::MAX); + u32le(&mut c, nidx); + u16le(&mut c, 20); + u16le(&mut c, 20); + u16le(&mut c, attrs.len() as u16); + u16le(&mut c, 0); + u16le(&mut c, 0); + u16le(&mut c, 0); + for at in attrs { + let an = intern(at.name, &mut strings); + let (raw, ty, data) = match at.val { + AxVal::Str(s) => { + let i = intern(s, &mut strings); + (i, 0x03u8, i) + } + AxVal::Bool(b) => (u32::MAX, 0x12, if b { u32::MAX } else { 0 }), + AxVal::Int(i) => (u32::MAX, 0x10, i as u32), + AxVal::Hex(h) => (u32::MAX, 0x11, h), + AxVal::Ref(r) => (u32::MAX, 0x01, r), + }; + u32le(&mut c, if at.res_id.is_some() { uri } else { u32::MAX }); + u32le(&mut c, an); + u32le(&mut c, raw); + u16le(&mut c, 8); + c.push(0); + c.push(ty); + u32le(&mut c, data); + } + body.extend(c); + } + AxNode::End(name) => { + let nidx = intern(name, &mut strings); + let mut c = Vec::new(); + u16le(&mut c, 0x0103); + u16le(&mut c, 16); + u32le(&mut c, 24); + u32le(&mut c, line as u32 + 2); + u32le(&mut c, u32::MAX); + u32le(&mut c, u32::MAX); + u32le(&mut c, nidx); + body.extend(c); + } + } + } + body.extend(ns_chunk(0x0101)); + let refs: Vec<&str> = strings.iter().map(String::as_str).collect(); + let pool = string_pool(&refs, false); + let mut map = Vec::new(); + u16le(&mut map, 0x0180); + u16le(&mut map, 8); + u32le(&mut map, (8 + 4 * ids.len()) as u32); + for id in &ids { + u32le(&mut map, *id); + } + let mut out = Vec::new(); + u16le(&mut out, 0x0003); + u16le(&mut out, 8); + u32le(&mut out, (8 + pool.len() + map.len() + body.len()) as u32); + out.extend(pool); + out.extend(map); + out.extend(body); + out +} + +/// The Notes app's `AndroidManifest.xml`. +pub fn manifest_axml() -> Vec { + use AxNode::{End, Start}; + use AxVal::*; + let name = |v| a("name", 0x0101_0003, Str(v)); + axml(&[ + Start( + "manifest", + vec![ + AxAttr { name: "package", res_id: None, val: Str(PACKAGE) }, + a("versionCode", 0x0101_021b, Int(42)), + a("versionName", 0x0101_021c, Str("1.2.3")), + ], + ), + Start("uses-sdk", vec![a("minSdkVersion", 0x0101_020c, Int(24)), a("targetSdkVersion", 0x0101_0270, Int(34))]), + End("uses-sdk"), + Start("uses-permission", vec![name("android.permission.INTERNET")]), + End("uses-permission"), + Start("uses-permission", vec![name("android.permission.CAMERA")]), + End("uses-permission"), + Start("permission", vec![name("com.example.notes.permission.SYNC"), a("protectionLevel", 0x0101_0009, Hex(2))]), + End("permission"), + Start( + "application", + vec![ + name(".NotesApp"), + a("label", 0x0101_0001, Ref(0x7f01_0000)), + a("debuggable", 0x0101_000f, Bool(true)), + a("allowBackup", 0x0101_0280, Bool(false)), + ], + ), + Start("activity", vec![name(".MainActivity"), a("exported", 0x0101_0010, Bool(true))]), + Start("intent-filter", vec![]), + Start("action", vec![name("android.intent.action.MAIN")]), + End("action"), + Start("category", vec![name("android.intent.category.LAUNCHER")]), + End("category"), + Start("data", vec![a("scheme", 0x0101_0027, Str("notes")), a("host", 0x0101_0028, Str("open"))]), + End("data"), + End("intent-filter"), + End("activity"), + Start("service", vec![name(".SyncService"), a("exported", 0x0101_0010, Bool(false))]), + End("service"), + Start( + "provider", + vec![ + name("androidx.core.content.FileProvider"), + a("authorities", 0x0101_0018, Str("com.example.notes.files")), + a("exported", 0x0101_0010, Bool(false)), + ], + ), + End("provider"), + End("application"), + End("manifest"), + ]) +} + +fn config(lang: &[u8; 2], density: u16, ui_mode: u8, sdk: u16) -> Vec { + let mut c = vec![0u8; 64]; + c[0] = 64; + if lang != b"\0\0" { + c[8..10].copy_from_slice(lang); + } + c[14..16].copy_from_slice(&density.to_le_bytes()); + c[24..26].copy_from_slice(&sdk.to_le_bytes()); + c[29] = ui_mode; + c +} + +fn type_spec(id: u8, entries: u32) -> Vec { + let mut c = Vec::new(); + u16le(&mut c, 0x0202); + u16le(&mut c, 16); + u32le(&mut c, 16 + 4 * entries); + c.push(id); + c.push(0); + u16le(&mut c, 0); + u32le(&mut c, entries); + for _ in 0..entries { + u32le(&mut c, 0); + } + c +} + +/// A type chunk from already-encoded entries. +fn type_chunk(id: u8, cfg: &[u8], entries: &[Vec]) -> Vec { + let header = 20 + cfg.len(); + let start = header + 4 * entries.len(); + let mut offs = Vec::new(); + let mut body = Vec::new(); + for e in entries { + offs.push(body.len() as u32); + body.extend_from_slice(e); + } + let mut c = Vec::new(); + u16le(&mut c, 0x0201); + u16le(&mut c, header as u16); + u32le(&mut c, (start + body.len()) as u32); + c.push(id); + c.push(0); + u16le(&mut c, 0); + u32le(&mut c, entries.len() as u32); + u32le(&mut c, start as u32); + c.extend_from_slice(cfg); + for o in offs { + u32le(&mut c, o); + } + c.extend(body); + c +} + +fn simple_entry(key: u32, ty: u8, data: u32) -> Vec { + let mut e = Vec::new(); + u16le(&mut e, 8); + u16le(&mut e, 0); + u32le(&mut e, key); + u16le(&mut e, 8); + e.push(0); + e.push(ty); + u32le(&mut e, data); + e +} + +/// `resources.arsc`: `string/app_name` and `string/greeting` in the default locale and French, +/// and one `style/AppTheme` bag (night, xhdpi, v21) with a parent and a colour item. +pub fn resources_arsc() -> Vec { + let global = string_pool(&["Notes", "Hello", "Notes FR", "Bonjour"], true); + let types = string_pool(&["string", "style"], false); + let keys = string_pool(&["app_name", "greeting", "AppTheme"], false); + let mut bag = Vec::new(); + u16le(&mut bag, 16); + u16le(&mut bag, 1); + u32le(&mut bag, 2); + u32le(&mut bag, 0x0103_0005); + u32le(&mut bag, 1); + u32le(&mut bag, 0x7f03_0000); + u16le(&mut bag, 8); + bag.push(0); + bag.push(0x1c); + u32le(&mut bag, 0xff33_6699); + let mut chunks = Vec::new(); + chunks.extend(type_spec(1, 2)); + chunks.extend(type_chunk(1, &config(b"\0\0", 0, 0, 0), &[simple_entry(0, 3, 0), simple_entry(1, 3, 1)])); + chunks.extend(type_chunk(1, &config(b"fr", 0, 0, 0), &[simple_entry(0, 3, 2), simple_entry(1, 3, 3)])); + chunks.extend(type_spec(2, 1)); + chunks.extend(type_chunk(2, &config(b"\0\0", 320, 0x20, 21), &[bag])); + let header = 288usize; + let mut pkg = Vec::new(); + u16le(&mut pkg, 0x0200); + u16le(&mut pkg, header as u16); + u32le(&mut pkg, (header + types.len() + keys.len() + chunks.len()) as u32); + u32le(&mut pkg, 0x7f); + let mut name = [0u16; 128]; + for (i, u) in PACKAGE.encode_utf16().enumerate() { + name[i] = u; + } + for u in name { + u16le(&mut pkg, u); + } + u32le(&mut pkg, header as u32); + u32le(&mut pkg, 2); + u32le(&mut pkg, (header + types.len()) as u32); + u32le(&mut pkg, 3); + u32le(&mut pkg, 0); + pkg.extend(types); + pkg.extend(keys); + pkg.extend(chunks); + let mut out = Vec::new(); + u16le(&mut out, 0x0002); + u16le(&mut out, 12); + u32le(&mut out, (12 + global.len() + pkg.len()) as u32); + u32le(&mut out, 1); + out.extend(global); + out.extend(pkg); + out +} diff --git a/crates/android-res/src/lib.rs b/crates/android-res/src/lib.rs new file mode 100644 index 0000000000..656f6dbf13 --- /dev/null +++ b/crates/android-res/src/lib.rs @@ -0,0 +1,17 @@ +//! Bounded readers for compiled Android XML and resource tables. +pub mod arsc; +pub mod axml; +mod bytes; +#[cfg(test)] +mod fixtures; + +/// Failure to decode the Android wire format. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// A required record did not fit within the available bytes. + #[error("truncated: {0}")] + Truncated(String), + /// The available bytes do not form the required structure. + #[error("malformed: {0}")] + Malformed(String), +} diff --git a/crates/audio/src/flac_decode.rs b/crates/audio/src/flac_decode.rs index bb56e65c52..790a9110e9 100644 --- a/crates/audio/src/flac_decode.rs +++ b/crates/audio/src/flac_decode.rs @@ -205,6 +205,16 @@ impl<'a> Bits<'a> { const BLOCK_SIZES: [usize; 16] = [0, 192, 576, 1152, 2304, 4608, 0, 0, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768]; +struct FrameHeader { + variable: bool, + number: u64, + block_size: usize, + sample_rate: u32, + bits: u32, + channels: usize, + mode: Stereo, +} + /// A frame decoder. `info` supplies what a frame header leaves to the STREAMINFO. #[derive(Debug, Clone, Copy, Default)] pub struct Decoder { @@ -223,14 +233,12 @@ impl Decoder { Decoder { info: None } } - /// Decode the frame at the start of `data`. - pub fn decode_frame(&self, data: &[u8]) -> Result { + fn read_frame_header(&self, r: &mut Bits<'_>) -> Result { // StreamInfo has public fields: container callers can construct it without // parse(), so validate before it can control shifts and sample reads. if self.info.is_some_and(|i| !(4..=32).contains(&i.bits_per_sample) || !(1..=8).contains(&i.channels) || i.sample_rate == 0) { return Err(DecodeError::Invalid("invalid decoder STREAMINFO")); } - let mut r = Bits::new(data); if r.bits(15)? != 0x7FFC { return Err(DecodeError::Invalid("missing frame sync code")); } @@ -240,7 +248,7 @@ impl Decoder { if r.bit()? != 0 { return Err(DecodeError::Invalid("reserved bit set")); } - let number = coded_number(&mut r)?; + let number = coded_number(r)?; let block_size = match bs_code { 0 => return Err(DecodeError::Invalid("reserved block size")), 6 => r.bits(8)? as usize + 1, @@ -267,7 +275,7 @@ impl Decoder { }; let header_len = r.pos.div_ceil(8); let stored_crc = r.bits(8)? as u8; - if crc8(&data[..header_len]) != stored_crc { + if crc8(&r.data[..header_len]) != stored_crc { return Err(DecodeError::Crc("a frame header")); } let bits = match bps_code { @@ -287,6 +295,24 @@ impl Decoder { 10 => (2, Stereo::MidSide), _ => return Err(DecodeError::Invalid("reserved channel assignment")), }; + Ok(FrameHeader { variable, number, block_size, sample_rate, bits, channels, mode }) + } + + /// Read a FLAC packet's sample count from an intact header even if the body is damaged. + pub(crate) fn packet_block_size(&self, data: &[u8]) -> Option { + let info = self.info?; + let header = self.read_frame_header(&mut Bits::new(data)).ok()?; + (header.sample_rate == info.sample_rate + && header.bits == u32::from(info.bits_per_sample) + && header.channels == usize::from(info.channels) + && header.block_size <= usize::from(u16::MAX)) + .then_some(header.block_size) + } + + /// Decode the frame at the start of `data`. + pub fn decode_frame(&self, data: &[u8]) -> Result { + let mut r = Bits::new(data); + let FrameHeader { variable, number, block_size, sample_rate, bits, channels, mode } = self.read_frame_header(&mut r)?; let mut out: Vec> = Vec::with_capacity(channels); for c in 0..channels { let extra = match (mode, c) { diff --git a/crates/audio/src/flac_layout.rs b/crates/audio/src/flac_layout.rs new file mode 100644 index 0000000000..f1f53e5b86 --- /dev/null +++ b/crates/audio/src/flac_layout.rs @@ -0,0 +1,114 @@ +//! FLAC speaker layout from STREAMINFO and Vorbis comments (RFC 9639). + +use crate::ChannelLayout; +use crate::pcm::{be_u32, le_u32}; + +/// The layout of the FLAC stream at `at`, from its STREAMINFO channel count and its channel mask +/// comment, or `None` when it does not start with a STREAMINFO block. +#[cfg(feature = "symphonia")] +pub(crate) fn layout(b: &[u8], at: usize) -> Option { + let head = be_u32(b, at.checked_add(4)?)?; + if (head >> 24) & 0x7f != 0 { + return None; + } + // In STREAMINFO: 3 bits of channels - 1 after the 20 bits of rate. + let channels = u16::from((b.get(at.checked_add(4 + 4 + 10 + 2)?)? >> 1) & 0x7) + 1; + Some(layout_of(b, at, channels)) +} + +/// `channels` channels described by the channel mask comment of the stream at `at`, or else in +/// the layout decoders assume for the count (RFC 9639 §8.6.2, §9.1.3). +pub(crate) fn layout_of(b: &[u8], at: usize, channels: u16) -> ChannelLayout { + layout_from(channel_mask(b, at), channels) +} + +/// `channels` channels described by a channel mask comment's value, or else in the layout decoders +/// assume for the count. +pub(crate) fn layout_from(mask: Option, channels: u16) -> ChannelLayout { + let mask = mask.unwrap_or_else(|| crate::layout::flac_assumed_mask(usize::from(channels))); + ChannelLayout::from_mask_and_channels(mask, channels) +} + +/// The value of the first `WAVEFORMATEXTENSIBLE_CHANNEL_MASK` comment that holds a `0x` hexadecimal +/// number, in the stream at `at`. +fn channel_mask(b: &[u8], at: usize) -> Option { + let mut pos = at.checked_add(4)?; + loop { + let head = be_u32(b, pos)?; + let (body, len) = (pos.checked_add(4)?, (head & 0x00ff_ffff) as usize); + let end = body.checked_add(len)?.min(b.len()); + if (head >> 24) & 0x7f == 4 { + return comments_mask(b.get(body..end)?); + } + if head >> 31 == 1 { + return None; + } + pos = body.checked_add(len)?; + } +} + +/// The mask in a comment, when its key is the channel mask's and its value a `0x` hexadecimal number. +fn comment_mask(key: &[u8], value: &[u8]) -> Option { + if !key.eq_ignore_ascii_case(b"WAVEFORMATEXTENSIBLE_CHANNEL_MASK") { + return None; + } + let hex = value.strip_prefix(b"0x").or_else(|| value.strip_prefix(b"0X"))?; + u32::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok() +} + +/// The channel mask in a Vorbis comment block's body. +pub(crate) fn comments_mask(block: &[u8]) -> Option { + let vendor = le_u32(block, 0)? as usize; + let mut at = 4usize.checked_add(vendor)?; + let count = le_u32(block, at)?; + at += 4; + for _ in 0..count { + let len = le_u32(block, at)? as usize; + let comment = block.get(at + 4..(at + 4).checked_add(len)?)?; + at += 4 + len; + let Some(eq) = comment.iter().position(|&c| c == b'=') else { continue }; + if let Some(mask) = comment_mask(&comment[..eq], &comment[eq + 1..]) { + return Some(mask); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::comments_mask; + + fn block(comments: &[&str]) -> Vec { + let mut b = 3u32.to_le_bytes().to_vec(); + b.extend_from_slice(b"abc"); + b.extend_from_slice(&(comments.len() as u32).to_le_bytes()); + for c in comments { + b.extend_from_slice(&(c.len() as u32).to_le_bytes()); + b.extend_from_slice(c.as_bytes()); + } + b + } + + #[test] + fn the_channel_mask_comment_is_found_in_any_case() { + assert_eq!(comments_mask(&block(&["TITLE=x", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"])), Some(0x107)); + assert_eq!(comments_mask(&block(&["waveformatextensible_channel_mask=0X3f"])), Some(0x3F)); + assert_eq!(comments_mask(&block(&["TITLE=x"])), None); + } + + #[test] + fn a_bad_channel_mask_comment_is_ignored() { + for value in ["63", "0x", "0xZZ", "0x1FFFFFFFF"] { + assert_eq!(comments_mask(&block(&[&format!("WAVEFORMATEXTENSIBLE_CHANNEL_MASK={value}")])), None, "{value}"); + } + assert_eq!(comments_mask(&block(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=bad", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x3"])), Some(3)); + } + + #[test] + fn a_truncated_comment_block_has_no_mask() { + let whole = block(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x3"]); + for cut in 0..whole.len() { + assert_eq!(comments_mask(&whole[..cut]), None, "{cut}"); + } + } +} diff --git a/crates/audio/src/layout.rs b/crates/audio/src/layout.rs index fc3cb2d524..08abe5423d 100644 --- a/crates/audio/src/layout.rs +++ b/crates/audio/src/layout.rs @@ -151,6 +151,7 @@ impl TryFrom for ChannelLayout { feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode", + feature = "flac-decode", feature = "pcm-encode" ))] pub(crate) fn count(n: usize) -> u16 { @@ -273,7 +274,7 @@ impl std::fmt::Display for ChannelLayout { /// The layout decoders assume for 1–8 FLAC channels with no channel mask comment, as a WAV mask. /// RFC 9639 §9.1.3 leaves "back/surround" open for 5 and 6 channels; libFLAC and ffmpeg read side /// surrounds. 7 channels are 6.1 with sides (FL FR FC LFE BC SL SR). -#[cfg(any(feature = "symphonia", feature = "flac-encode"))] +#[cfg(any(feature = "symphonia", feature = "flac-encode", feature = "flac-decode"))] pub(crate) fn flac_assumed_mask(channels: usize) -> u32 { match channels { 5 => 0x607, diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 9ca1571cf8..29054288ec 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -49,6 +49,8 @@ pub mod alac; mod buffer; #[cfg(feature = "dsd")] pub mod dsd; +#[cfg(any(feature = "flac-decode", feature = "symphonia"))] +mod flac_layout; #[cfg(feature = "g722")] pub mod g722; #[cfg(feature = "g726")] @@ -62,7 +64,14 @@ pub mod mp3; pub mod mpa; #[cfg(any(feature = "opus-decode", feature = "opus-encode"))] pub mod opus; -#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] +#[cfg(any( + feature = "aac-decode", + feature = "alac-decode", + feature = "opus-decode", + feature = "ac3-decode", + feature = "mpa-decode", + feature = "flac-decode" +))] mod pcm; #[cfg(feature = "peaks")] pub mod peaks; @@ -72,7 +81,14 @@ pub mod qoa; mod read; #[cfg(feature = "sbc")] pub mod sbc; -#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] +#[cfg(any( + feature = "aac-decode", + feature = "alac-decode", + feature = "opus-decode", + feature = "ac3-decode", + feature = "mpa-decode", + feature = "flac-decode" +))] mod track; #[cfg(feature = "vmd-decode")] pub mod vmd; @@ -150,7 +166,14 @@ pub use read::{ }; #[cfg(feature = "decode-native")] pub use read::{RawPcm, aiff_pcm, wav_pcm}; -#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] +#[cfg(any( + feature = "aac-decode", + feature = "alac-decode", + feature = "opus-decode", + feature = "ac3-decode", + feature = "mpa-decode", + feature = "flac-decode" +))] pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; #[cfg(any( feature = "pcm-encode", diff --git a/crates/audio/src/pcm.rs b/crates/audio/src/pcm.rs index 397f0c07f6..6cef7527f0 100644 --- a/crates/audio/src/pcm.rs +++ b/crates/audio/src/pcm.rs @@ -14,7 +14,7 @@ pub(crate) fn le_u16(b: &[u8], pos: usize) -> Option { } /// Little-endian `u32` at `pos`. -#[cfg(feature = "decode-native")] +#[cfg(any(feature = "decode-native", feature = "flac-decode"))] pub(crate) fn le_u32(b: &[u8], pos: usize) -> Option { let s: [u8; 4] = b.get(pos..pos.checked_add(4)?)?.try_into().ok()?; Some(u32::from_le_bytes(s)) @@ -35,7 +35,7 @@ pub(crate) fn be_u16(b: &[u8], pos: usize) -> Option { } /// Big-endian `u32` at `pos`. -#[cfg(feature = "decode-native")] +#[cfg(any(feature = "decode-native", feature = "flac-decode"))] pub(crate) fn be_u32(b: &[u8], pos: usize) -> Option { let s: [u8; 4] = b.get(pos..pos.checked_add(4)?)?.try_into().ok()?; Some(u32::from_be_bytes(s)) diff --git a/crates/audio/src/read/flac.rs b/crates/audio/src/read/flac.rs index 16ffd3a06c..fb8da9851a 100644 --- a/crates/audio/src/read/flac.rs +++ b/crates/audio/src/read/flac.rs @@ -2,8 +2,10 @@ use craft_media::ogg; +use crate::flac_layout::{comments_mask, layout_of}; +pub(crate) use crate::flac_layout::{layout, layout_from}; use crate::pcm::{be_u32, le_u32}; -use crate::{AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result, SampleFormat}; +use crate::{AudioError, AudioInfo, CodecId, Container, Result, SampleFormat}; /// Refuse the FLAC stream at `at` if a comment or picture field claims more bytes than its /// metadata block holds: symphonia allocates each field's length before reading it. @@ -72,58 +74,6 @@ pub(crate) fn empty_stream_info(b: &[u8], at: usize) -> Option { Some(AudioInfo::new(Container::Flac, CodecId::Flac, sample_format, sample_rate, layout_of(b, at, channels), 0)) } -/// The layout of the FLAC stream at `at`, from its STREAMINFO channel count and its channel mask -/// comment, or `None` when it does not start with a STREAMINFO block. -pub(crate) fn layout(b: &[u8], at: usize) -> Option { - let head = be_u32(b, at.checked_add(4)?)?; - if (head >> 24) & 0x7f != 0 { - return None; - } - // In STREAMINFO: 3 bits of channels - 1 after the 20 bits of rate. - let channels = u16::from((b.get(at.checked_add(4 + 4 + 10 + 2)?)? >> 1) & 0x7) + 1; - Some(layout_of(b, at, channels)) -} - -/// `channels` channels described by the channel mask comment of the stream at `at`, or else in -/// the layout decoders assume for the count (RFC 9639 §8.6.2, §9.1.3). -fn layout_of(b: &[u8], at: usize, channels: u16) -> ChannelLayout { - layout_from(channel_mask(b, at), channels) -} - -/// `channels` channels described by a channel mask comment's value, or else in the layout decoders -/// assume for the count. -pub(crate) fn layout_from(mask: Option, channels: u16) -> ChannelLayout { - let mask = mask.unwrap_or_else(|| crate::layout::flac_assumed_mask(usize::from(channels))); - ChannelLayout::from_mask_and_channels(mask, channels) -} - -/// The value of the first `WAVEFORMATEXTENSIBLE_CHANNEL_MASK` comment that holds a `0x` hexadecimal -/// number, in the stream at `at`. -fn channel_mask(b: &[u8], at: usize) -> Option { - let mut pos = at.checked_add(4)?; - loop { - let head = be_u32(b, pos)?; - let (body, len) = (pos.checked_add(4)?, (head & 0x00ff_ffff) as usize); - let end = body.checked_add(len)?.min(b.len()); - if (head >> 24) & 0x7f == 4 { - return comments_mask(b.get(body..end)?); - } - if head >> 31 == 1 { - return None; - } - pos = body.checked_add(len)?; - } -} - -/// The mask in a comment, when its key is the channel mask's and its value a `0x` hexadecimal number. -fn comment_mask(key: &[u8], value: &[u8]) -> Option { - if !key.eq_ignore_ascii_case(b"WAVEFORMATEXTENSIBLE_CHANNEL_MASK") { - return None; - } - let hex = value.strip_prefix(b"0x").or_else(|| value.strip_prefix(b"0X"))?; - u32::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok() -} - /// The audio streams of the Ogg file `b` in file order, as `tracks` lists them: each one's serial /// and, for FLAC, its channel mask comment. Empty when the demuxer cannot read the file. pub(crate) fn ogg_audio_streams(b: &[u8]) -> Vec<(u32, Option)> { @@ -136,24 +86,6 @@ pub(crate) fn ogg_audio_streams(b: &[u8]) -> Vec<(u32, Option)> { file.streams.iter().filter(|s| s.codec.codec_id().is_audio()).map(|s| (s.serial, mask(s).filter(|_| s.codec == ogg::Codec::Flac))).collect() } -/// The channel mask in a Vorbis comment block's body. -fn comments_mask(block: &[u8]) -> Option { - let vendor = le_u32(block, 0)? as usize; - let mut at = 4usize.checked_add(vendor)?; - let count = le_u32(block, at)?; - at += 4; - for _ in 0..count { - let len = le_u32(block, at)? as usize; - let comment = block.get(at + 4..(at + 4).checked_add(len)?)?; - at += 4 + len; - let Some(eq) = comment.iter().position(|&c| c == b'=') else { continue }; - if let Some(mask) = comment_mask(&comment[..eq], &comment[eq + 1..]) { - return Some(mask); - } - } - None -} - /// Whether a vendor string or comment in a (little-endian) Vorbis comment block claims more than /// the block holds. fn comments_overrun(b: &[u8], body: usize, end: usize) -> bool { diff --git a/crates/audio/src/read/native.rs b/crates/audio/src/read/native.rs index d2eef95e59..a42aec6d47 100644 --- a/crates/audio/src/read/native.rs +++ b/crates/audio/src/read/native.rs @@ -820,6 +820,11 @@ fn open_mp4<'a>(src: &Src<'a>, container: Container, track: Option) -> Op return Some(Err(AudioError::Malformed("MP4 sample is larger than the file".into()))); } let params = t.codec_params(); + // Keep file-level FLAC on its existing path until this reader can index variable packet + // lengths and final duration from the frame headers. The packet API has no such timing role. + if params.codec == CodecId::Flac { + return None; + } let lookahead: Vec> = (0..t.samples.len().min(crate::track::LOOKAHEAD_PACKETS)).filter_map(|i| file.read_sample(src, track, i).ok()).collect(); let timescale = t.timescale; @@ -897,6 +902,11 @@ fn open_mkv<'a>(src: &Src<'a>, container: Container, track: Option) -> Op return None; } let params = t.codec_params(); + // The Matroska file API needs FLAC frame counts to undo timestamp rounding on seeks. + // Keep its existing fallback until it can index those counts. + if params.codec == CodecId::Flac { + return None; + } let lookahead: Vec> = (0..t.samples.len().min(crate::track::LOOKAHEAD_PACKETS)).filter_map(|i| demux.read_sample(track, i).ok()).collect(); let probe = TrackDecoder::new(¶ms, &lookahead.iter().map(Vec::as_slice).collect::>()).ok()?; diff --git a/crates/audio/src/track.rs b/crates/audio/src/track.rs index ce0182d75a..cc1d9d7079 100644 --- a/crates/audio/src/track.rs +++ b/crates/audio/src/track.rs @@ -1,5 +1,5 @@ //! [`TrackDecoder`]: one track's packets in, planar `f32` in WAV channel order out, whatever the -//! codec. The file-level [`crate::decode`] and [`crate::Decoder`] use it for every native codec; +//! codec. The file-level [`crate::decode`] and [`crate::Decoder`] use it for their native routes; //! an app with its own demuxer (MXF, MPEG-TS, a network stream) uses it directly. #[cfg(feature = "aac-decode")] @@ -17,6 +17,9 @@ use crate::opus; use crate::pcm::{PcmKind, deinterleave}; use crate::{AudioBuffer, AudioError, ChannelLayout, CodecId, CodecParams, Result, SampleFormat}; +#[cfg(feature = "flac-decode")] +mod flac_packet; + /// How many leading packets [`TrackDecoder::new`] looks at. pub const LOOKAHEAD_PACKETS: usize = 8; @@ -39,6 +42,8 @@ enum Inner { /// 2^-(bit depth - 1): full scale to ±1. scale: f64, }, + #[cfg(feature = "flac-decode")] + Flac(Box), /// The decoder, and what the packets read so far say of the track's packets. #[cfg(feature = "ac3-decode")] Ac3(Box, Ac3Packets), @@ -76,7 +81,7 @@ pub(crate) type PacketFrames = fn(&[u8], u64) -> Option; /// /// It takes the track's [`CodecParams`] (from `isobmff::Track::codec_params`, /// `matroska::Track::codec_params`, `ogg::Stream::codec_params`, or built by hand for another -/// container) and decodes AAC (LC, and HE-AAC with its SBR high band), ALAC, Opus, AC-3/E-AC-3, +/// container) and decodes AAC (LC, and HE-AAC with its SBR high band), ALAC, FLAC, Opus, AC-3/E-AC-3, /// MP1/MP2, MP3 and PCM. Container timing (AAC priming, Opus pre-skip, end trimming) is the caller's: /// every decoded sample is returned. /// @@ -130,11 +135,10 @@ impl TrackDecoder { /// Opus with empty `extradata` and 1 or 2 `channels` (RTP, MPEG-TS) needs no `OpusHead`. Other /// missing configuration is [`AudioError::Malformed`]. /// + /// FLAC needs the `fLaC` magic and metadata blocks, starting with STREAMINFO, in `extradata`. /// ALAC needs its magic cookie in `extradata`. /// - /// Codecs without a native packet decoder yet (FLAC, Vorbis) are - /// [`AudioError::Unsupported`]; `craft_audio::decode` decodes them through symphonia when the - /// `symphonia` feature is on. + /// Unavailable packet codecs return [`AudioError::Unsupported`]. pub fn new(params: &CodecParams, lookahead: &[&[u8]]) -> Result { #[cfg(not(feature = "aac-decode"))] let _ = lookahead; @@ -209,6 +213,18 @@ impl TrackDecoder { let scale = 2f64.powi(1 - i32::from(cfg.bit_depth)); (Inner::Alac { dec, order, scale }, CodecId::Alac, rate, layout, sample_format) } + #[cfg(feature = "flac-decode")] + CodecId::Flac => { + let (track, layout) = flac_packet::FlacTrack::new(¶ms.extradata)?; + let rate = track.info.sample_rate; + let sample_format = match track.info.bits_per_sample { + 4..=8 => SampleFormat::Int8, + 9..=16 => SampleFormat::Int16, + 17..=24 => SampleFormat::Int24, + _ => SampleFormat::Int32, + }; + (Inner::Flac(Box::new(track)), CodecId::Flac, rate, layout, sample_format) + } #[cfg(feature = "ac3-decode")] CodecId::Ac3 | CodecId::Eac3 => match ac3::parse_header(first) { Ok(h) => { @@ -313,6 +329,25 @@ impl TrackDecoder { self.sample_format } + /// The exact codec configuration for a FLAC track. + #[cfg(feature = "flac-decode")] + pub fn flac_stream_info(&self) -> Option { + match &self.inner { + Inner::Flac(track) => Some(track.info), + _ => None, + } + } + + /// The FLAC packet's actual sample count, including a short final frame. This requires an + /// intact header and matching stream format but can read through a damaged frame body. + #[cfg(feature = "flac-decode")] + pub fn flac_packet_frames(&self, packet: &[u8]) -> Option { + match &self.inner { + Inner::Flac(track) => track.packet_frames(packet), + _ => None, + } + } + /// Decode one packet. An MP4 or Matroska packet may hold several AC-3 or MPEG audio frames; /// an E-AC-3 dependent substream decodes to no frames. A packet that fails is an error for /// every codec: call [`TrackDecoder::conceal`] for audio of its length, so what follows keeps @@ -347,6 +382,8 @@ impl TrackDecoder { let floats = decoded.into_iter().map(|c| c.into_iter().map(|v| (f64::from(v) * *scale) as f32).collect()).collect(); reorder(floats, *order) } + #[cfg(feature = "flac-decode")] + Inner::Flac(track) => track.decode(packet)?, #[cfg(feature = "mpa-decode")] Inner::Mpa { dec, several } => { let (out, first, count, cut) = mpa_frames(packet, |f| dec.decode(f))?; @@ -453,6 +490,8 @@ impl TrackDecoder { Inner::Alac { dec, .. } => { Some(dec.packet_frames(data).unwrap_or(if self.last_frames > 0 { self.last_frames } else { dec.config().frame_length as usize })) } + #[cfg(feature = "flac-decode")] + Inner::Flac(track) => track.packet_frames(data), #[cfg(feature = "ac3-decode")] Inner::Ac3(..) => Some(ac3_packet_frames(data)), #[cfg(feature = "mpa-decode")] @@ -488,6 +527,8 @@ impl TrackDecoder { Inner::Aac { sbr, .. } => Some(aac::FRAME_LEN * if *sbr { 2 } else { 1 }), #[cfg(feature = "alac-decode")] Inner::Alac { .. } => None, + #[cfg(feature = "flac-decode")] + Inner::Flac(..) => None, #[cfg(feature = "ac3-decode")] Inner::Ac3(_, shape) if shape.varies => None, #[cfg(feature = "ac3-decode")] @@ -544,6 +585,8 @@ impl TrackDecoder { Inner::Aac { sbr, .. } => 2 * aac::FRAME_LEN * if *sbr { 2 } else { 1 }, #[cfg(feature = "alac-decode")] Inner::Alac { .. } => 0, + #[cfg(feature = "flac-decode")] + Inner::Flac(..) => 0, #[cfg(feature = "ac3-decode")] Inner::Ac3(_, shape) if shape.short => usize::MAX, #[cfg(feature = "ac3-decode")] @@ -570,6 +613,8 @@ impl TrackDecoder { Inner::Aac { dec, .. } => dec.reset(), #[cfg(feature = "alac-decode")] Inner::Alac { .. } => {} + #[cfg(feature = "flac-decode")] + Inner::Flac(..) => {} #[cfg(feature = "ac3-decode")] Inner::Ac3(d, _) => d.reset(), #[cfg(feature = "opus-decode")] @@ -587,6 +632,7 @@ fn unsupported(codec: CodecId) -> AudioError { let feature = match codec { CodecId::Aac | CodecId::HeAac => Some("aac-decode"), CodecId::Alac => Some("alac-decode"), + CodecId::Flac => Some("flac-decode"), CodecId::Ac3 | CodecId::Eac3 => Some("ac3-decode"), CodecId::Opus => Some("opus-decode"), CodecId::Mp1 | CodecId::Mp2 => Some("mpa-decode"), @@ -596,7 +642,7 @@ fn unsupported(codec: CodecId) -> AudioError { match feature { // A codec this crate decodes, in a build without its feature. Some(f) => AudioError::Unsupported(format!("decoding {} needs the `{f}` feature", codec.name())), - None if cfg!(feature = "symphonia") && matches!(codec, CodecId::Flac | CodecId::Vorbis) => { + None if cfg!(feature = "symphonia") && codec == CodecId::Vorbis => { AudioError::Unsupported(format!("no native {} packet decoder yet (craft_audio::decode reads it through symphonia)", codec.name())) } None => AudioError::Unsupported(format!("no native {} packet decoder yet", codec.name())), diff --git a/crates/audio/src/track/flac_packet.rs b/crates/audio/src/track/flac_packet.rs new file mode 100644 index 0000000000..07cc5c047c --- /dev/null +++ b/crates/audio/src/track/flac_packet.rs @@ -0,0 +1,46 @@ +//! FLAC framing shared by the MP4 and Matroska packet readers. + +use crate::flac_decode::{Decoder, StreamInfo}; +use crate::{AudioError, ChannelLayout, Result}; + +pub(super) struct FlacTrack { + pub(super) info: StreamInfo, + decoder: Decoder, +} + +impl FlacTrack { + pub(super) fn new(private: &[u8]) -> Result<(Self, ChannelLayout)> { + let [b'f', b'L', b'a', b'C', kind, 0, 0, 34, body @ ..] = private else { + return Err(AudioError::Malformed("FLAC track without a STREAMINFO block".into())); + }; + if kind & 0x7f != 0 { + return Err(AudioError::Malformed("FLAC STREAMINFO must be the first metadata block".into())); + } + let info = StreamInfo::parse(body).map_err(|error| AudioError::Malformed(format!("FLAC STREAMINFO: {error}")))?; + if info.sample_rate == 0 { + return Err(AudioError::Malformed("FLAC track sample rate is zero".into())); + } + let layout = crate::flac_layout::layout_of(private, 0, u16::from(info.channels)); + Ok((Self { info, decoder: Decoder::new(info) }, layout)) + } + + pub(super) fn decode(&self, packet: &[u8]) -> Result>> { + let frame = self.decoder.decode_frame(packet).map_err(|error| AudioError::Malformed(format!("FLAC packet: {error}")))?; + if frame.size != packet.len() { + return Err(AudioError::Malformed("FLAC packet must hold exactly one frame".into())); + } + if frame.sample_rate != self.info.sample_rate + || frame.bits_per_sample != self.info.bits_per_sample + || frame.channels.len() != usize::from(self.info.channels) + || frame.block_size > usize::from(u16::MAX) + { + return Err(AudioError::Malformed("FLAC packet format differs from STREAMINFO".into())); + } + let scale = 2f64.powi(1 - i32::from(self.info.bits_per_sample)); + Ok(frame.channels.into_iter().map(|plane| plane.into_iter().map(|sample| (f64::from(sample) * scale) as f32).collect()).collect()) + } + + pub(super) fn packet_frames(&self, data: &[u8]) -> Option { + self.decoder.packet_block_size(data) + } +} diff --git a/crates/audio/tests/flac_decode.rs b/crates/audio/tests/flac_decode.rs index a1895789b2..d252372514 100644 --- a/crates/audio/tests/flac_decode.rs +++ b/crates/audio/tests/flac_decode.rs @@ -4,6 +4,7 @@ //! ffmpeg's encoder writes at every compression level. use craft_audio::flac::{DecodeError, Decoder, Encoder, EncoderConfig, STREAMINFO_OFFSET, StreamInfo, decode}; +use craft_audio::{AudioError, CodecId, CodecParams, SampleFormat, TrackDecoder}; use std::process::Command; fn signal(channels: usize, frames: usize, bits: u32, seed: u32) -> Vec> { @@ -79,6 +80,56 @@ fn frames_decode_one_at_a_time() { let _ = Decoder::without_streaminfo().decode_frame(&file[at..]); } +#[test] +fn track_decoder_uses_streaminfo_layout_and_packet_length() { + let source = signal(4, 80, 24, 17); + let mut config = EncoderConfig::new(96_000, 4, 24); + config.block_size = 32; + let mut encoder = Encoder::new(config).expect("encoder"); + let mut private = encoder.header(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x603"]); + let planes: Vec<&[i32]> = source.iter().map(Vec::as_slice).collect(); + let mut packets = encoder.encode_frames(&planes).expect("packets"); + packets.push(encoder.finish()); + let at = STREAMINFO_OFFSET as usize; + private[at..at + 34].copy_from_slice(&encoder.streaminfo()); + + let params = CodecParams::new(CodecId::Flac).with_extradata(private).with_sample_rate(48_000).with_channels(4); + let mut track = TrackDecoder::new(¶ms, &[]).expect("native FLAC track"); + assert_eq!(track.sample_rate(), 96_000); + assert_eq!(track.flac_stream_info().expect("FLAC stream info").bits_per_sample, 24); + assert_eq!(track.layout().channels(), 4); + assert_eq!(track.layout().mask(), Some(0x603)); + assert_eq!(track.sample_format(), SampleFormat::Int24); + assert_eq!(track.frames_per_packet(), None); + assert_eq!(track.preroll(), 0); + + let final_packet = packets.last().expect("final packet"); + let decoded = track.decode(final_packet).expect("independent final frame"); + assert_eq!(decoded.frames(), 16); + for (plane, expected) in decoded.channels.iter().zip(&source) { + for (sample, expected) in plane.iter().zip(&expected[64..]) { + assert_eq!(*sample, (f64::from(*expected) / 8_388_608.0) as f32); + } + } + assert_eq!(track.decode(&packets[0]).expect("backwards seek").frames(), 32); + let truncated = &final_packet[..final_packet.len() - 1]; + assert_eq!(track.flac_packet_frames(truncated), Some(16)); + assert!(matches!(track.decode(truncated), Err(AudioError::Malformed(_)))); + let concealed = track.conceal(Some(truncated)).expect("silence from the intact header"); + assert_eq!(concealed.frames(), 16); + assert_eq!(concealed.peak(), 0.0); + track.reset(); + assert_eq!(track.decode(final_packet).expect("decode after reset"), decoded); + + let mut extra = final_packet.clone(); + extra.push(0); + assert!(matches!(track.decode(&extra), Err(AudioError::Malformed(_)))); + assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Flac), &[]), Err(AudioError::Malformed(_)))); + let mut incomplete = params.clone(); + incomplete.extradata.truncate(at + 33); + assert!(matches!(TrackDecoder::new(&incomplete, &[]), Err(AudioError::Malformed(_)))); +} + #[test] fn hostile_input_is_an_error_not_a_panic() { let src = signal(2, 6000, 16, 11); diff --git a/crates/cdr/Cargo.toml b/crates/cdr/Cargo.toml new file mode 100644 index 0000000000..edeb8d72e2 --- /dev/null +++ b/crates/cdr/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "craft-cdr" +description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers, and the picture a file keeps of its drawing" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer. +synth = [] + +[dependencies] +crc32fast = "1.5" +flate2 = { version = "1", default-features = false, features = ["rust_backend"] } + +[dev-dependencies] +proptest = { workspace = true } +craft-cdr = { path = ".", features = ["synth"] } diff --git a/crates/cdr/LICENSE-kaitai.txt b/crates/cdr/LICENSE-kaitai.txt new file mode 100644 index 0000000000..296cf04d0e --- /dev/null +++ b/crates/cdr/LICENSE-kaitai.txt @@ -0,0 +1,33 @@ +The record layouts this crate reads are described in the Kaitai Struct +specification `coreldraw_cdr.ksy` +(https://github.com/kaitai-io/coreldraw_cdr.ksy, commit +9d8e2704b946961f5114115f1a488750a3c86ed0), which is published under the +license below. No part of that specification is copied into this crate; +`PROVENANCE.md` cites it by line. + +Some layouts are also taken from the fork of that specification by Zach Wolfe +(https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, commit +2189b68f07e0cafe9afec3dcf699ebc0342144c7), which is published under the same +license and copyright notice. + +MIT License + +Copyright (c) 2020 Kaitai team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md new file mode 100644 index 0000000000..7c3ddadbb5 --- /dev/null +++ b/crates/cdr/PROVENANCE.md @@ -0,0 +1,132 @@ +# Where each layout comes from + +The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and +`tests/it/provenance.rs` fails when a cited id has no row here. + +Sources: + +- **K**: the Kaitai Struct specification `coreldraw_cdr.ksy` (MIT, notice in `LICENSE-kaitai.txt`), + https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/coreldraw_cdr.ksy +- **KF**: the fork of K by Zach Wolfe, `filestar/coreldraw_cdr.ksy`, branch `new_stuff`, under the same + MIT license and notice as K (`LICENSE-kaitai.txt`), + https://github.com/filestar/coreldraw_cdr.ksy/blob/2189b68f07e0cafe9afec3dcf699ebc0342144c7/coreldraw_cdr.ksy +- **KR**: the README and the `bin/cdr-unpk` script of the Kaitai Struct specification (MIT), at + the same commit as K, + https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/README.md + and https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/bin/cdr-unpk +- **Z**: the PKWARE ZIP specification, APPNOTE.TXT version 6.3.10, + https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE), + https://www.rfc-editor.org/rfc/rfc1951 +- **F**: the magic database of the `file` utility (BSD-2-Clause), + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images and + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff +- **PR**: the PRONOM registry's signatures for versions 1.0, 2.0 and 4.0, + https://pronom.nationalarchives.gov.uk/fmt/467.xml, + https://pronom.nationalarchives.gov.uk/fmt/466.xml and + https://pronom.nationalarchives.gov.uk/fmt/465.xml +- **G**: the reference pages for the BMP file header and the bitmap info header, + https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapfileheader and + https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader +- **S**: own inspection of the bytes of public sample files, checked against the picture each file + carries of its drawing where it has one (versions 2 and 4 to 25; files of versions 1 and 3 carry + none). The files come from: + - **TP**: https://telparia.com/fileFormatSamples/image/cdr/, by file name + - **LT**: https://git.libreoffice.org/libcdr-test at commit + `dafe4fe53d685d89df20a5c0bb18f318ccefb4a8`, `testset//` + - **UC**: https://svn.code.sf.net/p/uniconvertor/code/formats/CDR/testing%20base/ at revision + 434, by file name + - **TDF**: attachments to The Document Foundation's bug tracker, + https://bugs.documentfoundation.org/attachment.cgi?id= + - **NR**: Natural Resources Canada's tactile maps, + https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/approach-approch/cdr/banff_ap_en.cdr and + https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/atlas-atlas/cdr/ab_en_br.cdr + - **DM**: the clip art of https://discmaster.textfiles.com/browse/31541, by file name + - **CX**: the `.cmx` files of https://telparia.com/fileFormatSamples/image/cmx/, by file name. The + nine with 32-bit coordinates are `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, + `gold_bar.cmx`, `goldblue.cmx`, `PC.CMX`, `squares.cmx` and `thatch.cmx`; they carry no picture + of their drawing. +- **CN**: the `.cmx` notes of an MIT OR Apache-2.0 drawing program, which mark each layout + "confirmed" when the program's authors found it in sample files, + https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cmx-format.md. + The same program's `.cmx` reader at that commit, + https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs, + was read for the order of fields that the notes do not spell out (the table entries, the rendering + attributes and the curve body); no code was copied from it + +Status: `public-spec` (K, KF, KR, Z, F, PR or G), `sample` (S), `public-notes` (a layout CN marks +confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows; +listed so it can be checked against a file, with what the reader does when it is wrong). + +Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as +the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the +sample files they name. +The test inputs are the synthetic files that `src/synth.rs` builds from the rows below; no sample +file is committed. + +| Id | What the code relies on | Source | Status | +|---|---|---|---| +| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01 from the form type alone, whatever its `vrsn` chunk names, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) | +| R2 | `vrsn`: the version as a u16, in hundreds | K L276-L278 | public-spec | +| R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682 | public-spec | +| R4 | A chunk is an id, a u32 size and the body, padded to an even length; a `LIST` body starts with its form type; from version 7 a `LIST stlt` holds the style tables, not chunks | K L68-L78, L135-L155, L307-L334 | public-spec | +| R5 | Coordinates: i16 in 1/1000 inch before version 6, else i32 in 1/254000 inch; header fields, counts and offsets are u16 before version 6, else u32 | K L58-L66, L2688-L2700 | public-spec | +| R6 | `loda` and `lobj`: length, argument count, offsets table, types table, object type; count + 1 offsets bound the arguments; the types table runs in reverse; object types (1 rectangle, 2 ellipse, 3 curve, 0x14 polygon) and argument types (10 outline, 20 fill, 30 coordinates, 1000 name, 11000 polygon, 19130 page size) | K L335-L450, L846-L893 | public-spec | +| R7 | Angles: i16 tenths of a degree before version 6, else i32 millionths of a degree | K L2835-L2855 | public-spec | +| R8 | `trfd`: length, count, offsets table; each entry has 8 bytes first from version 13, a u16 type, and type 8 is a matrix after 6 bytes (from version 6) of six f64 `a c tx b d ty`, `tx` and `ty` in coordinate units; the matrices of one record apply in file order | K L895-L953, L2808-L2834 | public-spec | +| R9 | Name argument (1000): Windows-1252 up to a NUL before version 12, UTF-16LE from it | K L601-L630 | public-spec | +| R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765 | public-spec | +| R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; S: LT `testset/15` to `testset/25` `circle_redfill_nooutline_cdr.cdr`, whose fill records hold a record tagged 2400 before the one tagged 1300 | public-spec (2400 records: sample) | +| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; a record of id 2 holds a property list laid out as R11's, and the reader takes the outline's color from it when it names a library color; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; KF L1225-L1249 (the id 2 record); S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them; the id 2 record: no sample names a library color in it, and a wrong guess changes only the outline's color) | +| R13 | Bit 0 of the outline's line type: no outline | S: LT `square_blackfill_nooutline_cdr.cdr` and the other `nooutline` files of `testset/15` to `testset/25`, whose outline records all have line type 1 and whose pictures show no outline | sample | +| R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; S: model 25 in LT `testset/12/square_pantoneblackfill_nooutline.cdr` (number 14, tint 100), model 1 in UC `rogan_logo_cdr11.cdr` (number 4, tint 50) | public-spec (library values of models 1 and 25: sample; model 14: unconfirmed, and its color opens as a spot color without a look) | +| R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700 | public-spec | +| R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807 | public-spec | +| R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; S: the pies of negative height in the ellipse-sector drawings of versions 12 and 13 in UC | public-spec (axis direction of a negative size: sample) | +| R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; S: the polygons and stars of UC `shapes_cdr10.cdr` | public-spec (base curve: sample) | +| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. On a layer, group or object, bit 0x01 of byte 1 hides it and bit 0x10 of byte 0 locks it. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); KF L1831-L1866 (the hidden and lock bits); S: every grid layer of versions 14 to 25 in the sample files (631) carries byte 1 = 1, and 206 of the 927 of versions 7 to 13 do; desktop layers carry byte 1 = 0 except TDF 114901's [0, 1, 1]; the drawing layers with byte 1 = 1 (TDF 114901, NR `banff_ap_en.cdr` and `symbology_en.cdr`) also carry bit 0x08; of the group and object lists in the sample files, only one object of TDF 60491 (version 14) sets either bit, the lock bit; in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects; bit 0x10 is also the lock bit, so a locked guides layer without a `loda` reads as a grid) | +| R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec | +| R21 | Page size argument (19130): width and height | K L666-L672 | public-spec | +| R22 | `LIST page` holds `LIST layr` lists, directly or in a list it holds (a `LIST gobj` in the samples); a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); S: the chunk trees of every sample file of versions 3 to 25 | sample | +| R23 | Guideline (object type 0x16), argument 16000: 12 bytes, the angle in millionths of a degree, then points from the page centre; version 7 keeps them in a `guid` chunk: a u32 count, the count again, 40-byte records laid out the same way | S: argument 16000 in NR `ab_en_br.cdr` (9) and TDF 194220 (13); the `guid` chunk of TDF 123971 (7). Pictures do not show guidelines | sample | +| R24 | ZIP: the end of central directory record (signature `PK\5\6`, 22 bytes and a comment of up to 65,535 bytes) gives the member count and where the central directory lies; each central directory entry (46 bytes, then name, extra field and comment) gives the flags, method, CRC-32, sizes and its local header; a local header is 30 bytes, then its name and extra field, then the member's bytes. Flag bit 0 marks an encrypted member; method 0 is stored and 8 deflated; 0xFFFF and 0xFFFFFFFF mark ZIP64 fields, and a ZIP64 locator (`PK\6\7`, 20 bytes) precedes the end record of a ZIP64 archive; disk numbers other than 0 mark an archive split across files | Z 4.3.7, 4.3.12, 4.3.15, 4.3.16, 4.4.1.4, 4.4.4, 4.4.5, 4.4.7, 4.4.8, 4.4.13 | public-spec | +| R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30 | public-spec | +| R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180 | public-spec | +| R75 | `DISP`, a chunk of the RIFF form itself, holds the picture of the drawing: 4 bytes, then a bitmap info header (its own length u32, width, height, planes u16, bit count u16, compression u32, image size, two resolutions, the colors used u32, the important colors), then the color table or color masks and the pixels, to the end of the chunk. A BMP file is that bitmap after a 14-byte file header: `BM`, the file length u32, 4 reserved bytes of 0 and the offset of the pixels u32. The color table holds the colors used, at most 2^bit count, or 2^bit count colors when that is 0 at 8 bits or fewer; compression 3 (valid at 16 and 32 bits) puts three u32 masks after the header, before the pixels. The plane count is 1, and the image size is 0 or the rows' size. Uncompressed pixels (compression 0 or 3) are one row for each line of the height, each the width times the bit count rounded up to whole 32-bit words. The reader takes only a `DISP` chunk whose 4 bytes are `08 00 00 00`, with a 40-byte header and compression 0 or 3, and refuses other header lengths and compressions | K L231, L280-L306; G (both pages); S: every RIFF file of versions 4 to 13 in TP, UC, LT, NR, DM and TDF (469 files) has one `DISP`, starting with the bytes `08 00 00 00` and a 40-byte header of 1 plane and 1, 4 or 8 bits, compression 0, a positive height and an image size equal to the rows' size, whose color table and rows fill the rest of the chunk; the files of version 3 (TP, 9) have none | public-spec (the 4 bytes and where the chunk lies: sample; bit counts above 8 and compression 3: unconfirmed, as no sample has one, and a wrong guess gives a picture that fails to decode) | +| R76 | The package holds the picture of the drawing as `metadata/thumbnails/thumbnail.bmp`, a BMP file, in versions 14 to 16, and as `previews/thumbnail.png`, a PNG file, from version 17; each page's picture is beside it (`page1.bmp`, `page1.png` ...) ; the package's RIFF stream has no `DISP` chunk | S: every package of versions 14 to 16 (62) and of 17 to 25 (231) in LT, TP and TDF | sample | +| R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193 | public-spec | +| R28 | Templates have the form type `CDT` and a letter of their own; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | none: no sample template | unconfirmed (a template is read as a drawing of the version its `vrsn` chunk names, and one without that chunk is refused) | +| R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; S: LT `square_blackfill_nooutline_roundedcorners_cdr.cdr` of `testset/15` to `testset/25` (flag clear, a share of 0.25) | public-spec (radius share with the flag clear: sample; that the scale is not applied: unconfirmed, as every sample has a scale of 1, and a wrong guess changes only the corners' size) | +| R30 | Object type 0x25 (version 10 on) is a path: 4 bytes, two u16 counts that add up to the point count, 16 bytes, then the points and their type bytes as in R16 | K L788-L799, L892; S: TDF 78250 (version 15) and UC `shapes_cdr10.cdr`, `shapes_cdr11.cdr`, `shapes_cdr12.cdr` and `shapes_x3.cdr` (versions 10 to 13), whose type bytes start where the counts put them; no sample before version 10 holds the type | public-spec (from version 10: sample) | +| R31 | Version 3 is a RIFF file with the form type `CDR ` (a space) and a `vrsn` of 300; version 4 has the form type `CDR4` and a `vrsn` chunk. Both use the 16-bit fields of R5 and R7. Their pages, layers, groups and objects are read by the rules of R19 and R22 | K L117-L134; PR fmt/465; F `riff` L786; S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | public-spec (pages and layers as R19 and R22: sample) | +| R32 | Version 3 counts its object types from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4; later versions use these plus one | S: the rectangles, curves and text of TP `ARMYSTF1.CDR`, `DALI.CDR` and `FOX.CDR`, which come out whole | sample (ellipse 1 and bitmap 4: unconfirmed, as no sample holds them; a bitmap is left out with a warning) | +| R33 | Version 3 keeps an object's transforms in argument 100 of its `lobj`: a u16, the entry count (u16), then 10-byte entries of a type (u16) and, at byte 6, where the entry's data starts, counted from the start of the argument. Type 0x8c is a matrix as R37, and the matrices apply in file order. Type 0x14 is an envelope, which this reader does not apply: the shape keeps its outline, placed by the matrices alone, and the drawing's warnings name the envelopes. A group's own `lobj` holds an argument 100 that places all of the group's objects after their own transforms | K L851; S: the matrices of every version 3 file in TP, whose drawings come out whole | sample (envelope type 0x14: unconfirmed, as no sample holds one; it is not applied, with a warning) | +| R34 | Version 3 fill, argument 20: a type byte (0 none, 1 uniform, 2 and 4 fountain, 6 texture, 7 and 10 pattern); a uniform fill's color follows as R36 | K L452-L547 | public-spec | +| R35 | Version 3 outline, argument 10: a flags byte with bit 0 set when the object is outlined, the width (coordinate), the stretch (u16), the nib angle, the color as R36, 7 bytes, the dash count (u8) and 10 bytes that hold the dashes as one byte each, the join (u16 at byte 30) and the caps (u16 at byte 32) numbered as R12, then the two arrowhead ids (u32). Dashes are read in multiples of the width as R12 | K L548-L592; S: the outlines of the version 3 files in TP | public-spec (flag bit: sample; dash unit, and the join, where bytes 32 and 33 of some samples hold 2 and 2: unconfirmed, and a wrong guess changes only how corners, ends and dashes are drawn) | +| R36 | A color before version 5: in versions 1 to 3 a model byte and four value bytes, in version 4 a model u16, four u16 values and 2 bytes. Model 1 is cyan, magenta, yellow and black in percent. Model 0 is an ink number (u16) and a tint in percent (u16): ink 0 is black at the tint, ink 1 is white, and other numbers are inks of a numbered library that the file does not store. Other models are read as R14 | K L2882-L2908; S: model 1 in TP `ARMYSTF1.CDR` (3) and DM `lion1.cdr` (4), model 0 in TP `ARROW5.CDR` (3) and `WI.CDR` (1) | sample (ink 1, and models other than 0 and 1: unconfirmed; an ink of another number opens as a spot color without a look) | +| R37 | A matrix of versions 3 and 4: six i32 `a c tx b d ty`, the four factors in 16.16 fixed point and `tx` and `ty` in coordinate units. A version 4 `trfd` entry of type 8 holds one where R8 has six f64 | S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | sample | +| R38 | `mcfg` of version 3: 2 bytes, then the page's two corners as four coordinates; the page size is the distance between them | K L1676-L1678, L1745-L1756 | public-spec | +| R39 | A point list before version 6 starts with a u16 count and another u16 (1 in some curves of versions 1, 2 and 4, 0 in the others), where K reads the two as one u32 | S: TP `DALI.CDR` (3), DM `headup.cdr` and `lion1.cdr` (4), TP `WI.CDR` (1), `FLAG.CDR` and `MENU.CDR` (2) | sample | +| R40 | Versions 1 and 2 are not RIFF files. A file starts with `WL`, a marker byte, a zero byte and five u32: the start of the settings, the start and the end of the object records, the start of the trailer and that value minus two. Version 1 has the marker `e` and its settings start at byte 28. Version 2 has the marker `m` or `l`, and its settings start after a 1-bit picture of the drawing, whose header starts where the u32 at byte 28 says. The reader takes these three markers | F `images` L4159-L4172; PR fmt/467, fmt/466; S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`), `MENU.CDR` and `DRINKS.CDR` (`l`) | public-spec (markers `e` and `m`: F and PR; the offsets and the marker `l`: sample) | +| R41 | The page's box in a file of version 1 or 2: four i16 two bytes after the start of the settings (left, top, right, bottom) in 1/1000 inch around the page's centre, y pointing up | S: TP `WI.CDR`, `FLAG.CDR` and `MENU.CDR` | sample | +| R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample | +| R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample | +| R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) | +| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u16 before version 6, u32 from it). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables; argument 200 is 2 bytes on all 844 objects of versions 4 and 5 in the sample files that carry it, and 4 bytes on all 18 of version 6 | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | +| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32, a u16 before version 6) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | +| R47 | Argument 8000 marks an object seen through: a lens or a transparency. From version 13 it holds records of a u32 version, a u32 length and a body; a body of version 1300 that is 117 bytes long holds an f64 at byte 61 and a merge mode byte at byte 77, which the reader applies as a uniform transparency. VectorCraft reads the f64 as the transparency in percent (0 opaque, 100 clear) and maps the merge modes 0 normal, 9 multiply, 11 lighten, 12 darken, 14 color, 15 hue, 16 saturation, 17 luminosity, 24 difference, 28 screen, 29 overlay, 30 soft light, 31 hard light, 33 color dodge, 34 color burn and 36 exclusion to its blend modes. Other merge modes, other records (a lens record of version 13 is 84 bytes) and the argument before version 13 are not applied, and the reader names them with lenses in the warnings | K L859 (the argument); KF L707-L798 (the records, the 117-byte body and the merge modes); S: the version 1300 record of LT `square_blackfill_nooutline_transparency50percent` of `testset/15` to `testset/25` is 117 bytes long, with 50.0 at byte 61 and 0 at byte 77; the lens records of UC `corel_lens_test_x3.cdr` (13) are 84 bytes long; of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; the direction of the value: VectorCraft's own reading, as every sample is at 50%, and a wrong reading shows a 25% transparency at 75%; the layout before version 13: unconfirmed, and it is not read) | +| R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set (316 of them, in 29 files) stores dashes; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample | +| R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample | +| R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) | +| R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec | +| R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) | +| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | +| R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample | +| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | +| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | +| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | +| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample | +| R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) | +| R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) | +| R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) | +| R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) | +| R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample | diff --git a/crates/cdr/README.md b/crates/cdr/README.md new file mode 100644 index 0000000000..7a842a3abc --- /dev/null +++ b/crates/cdr/README.md @@ -0,0 +1,116 @@ +# craft-cdr + +A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates). +It reads the `WL` files of versions 1 and 2, the RIFF chunk tree of versions 3 and later with its +compressed lists, the ZIP packages that versions 14 and later save (with the data streams of +versions 16 and later) and the records listed below, and hands the engine a drawing in points, +with each object's transform. It does not write `.cdr` files. + +## What is read + +| In the `.cdr` file | Read as | +|---|---| +| ZIP packages: `content/riffData.cdr` (versions 14 and 15), `content/root.dat` with the data streams `content/dataFileList.dat` names (16 on) | the RIFF chunk tree; a data stream is inflated only when a chunk the reader reads, or a list it splits, points into it | +| Pages, the page size in `mcfg` or a page's own size | pages, laid out by the engine as artboards side by side | +| Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind | +| The hidden and locked flags of layers, groups and objects | flags | +| Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle | +| Groups (`LIST grp `) | groups | +| Clipping containers and the groups of `LIST clpt` they clip | the container with the objects it clips | +| Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 10 on) | paths | +| Rectangles (one corner radius, four from version 9) | rectangles with each corner's radius | +| Ellipses, arcs and pies | ellipses, and paths for arcs and pies | +| Polygons and stars (a base side copied for each side) | paths | +| Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints | +| The fill's winding flag | the nonzero fill rule, or even-odd | +| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags, and from version 13 a library color named in their property list | outlines | +| Uniform transparency (version 13 on) and its merge mode | the shape's opacity and blend mode | +| Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own | + +Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain, +pattern, texture and PostScript fills, outline arrowheads, lenses, transparency other than uniform +transparency of version 13 and later, and merge modes without a VectorCraft blend mode are not +read; the drawing's +`warnings` name each kind it held. Drawings of versions after 27 are refused, and so are packages +that are encrypted, ZIP64 archives or split across files. + +VectorCraft reads a uniform transparency's stored value as the transparency in percent (0 opaque, +100 clear), and a winding flag other than 0 as the nonzero fill rule. These are VectorCraft's own +readings: no public source states either direction. + +## Versions 1 to 4 + +Public specifications cover only parts of these versions, such as the version 3 fill and page +settings. For the rest, the reader follows the layouts of public sample files that +`PROVENANCE.md` lists (rows R31 to R44), and its tests read the synthetic files that +`src/synth.rs` builds from those rows. + +| Version | Read | Left out or refused | +|---|---|---| +| 1 and 2 (`WL` files) | the page size; rectangles with one corner radius, whole ellipses and curves, each with its matrix; uniform fills and outlines with their width and color, in CMYK percent and the inks black and white. The objects come in on one page and one layer, front to back | text and objects of other types, and ellipses whose two angles differ (arcs and pies), with the unsupported-objects warning; fills of other types, with the unsupported-fills warning; inks of a numbered library, which read as spot colors without a look; groups and layers, whose records are passed over; dashes, caps, joins and arrowheads, which the reader does not look for; the records after a drawn object of another type, with the unsupported-objects warning | +| 3 (RIFF, form type `CDR `) | the page size from the page's corners; pages, layers and groups; rectangles, ellipses, arcs and curves with the matrices of the object and of the groups around it; uniform fills; outlines with their width, color, caps, joins and dashes | text and bitmaps; envelopes, with the envelopes warning (the objects and groups under one keep their outlines and matrices); fountain, pattern and texture fills; arrowheads | +| 4 (RIFF, form type `CDR4`) | as version 5, with the colors and the fixed-point transforms of version 4 | as version 5 | + +A file is taken for version 1 or 2 by its content only when, after `WL`, its marker byte is one of +`e`, `l` and `m`, the next byte is zero, and the offsets of its header fit the file. The reader +reports version 1 for the marker `e` and version 2 for the other two. A RIFF file that names +a version before 3 is refused, and so is the version 4 template form type `CDST`, which reads as +not a `.cdr` drawing. + +## Previews + +`preview` returns the picture a `.cdr` file keeps of its drawing without reading the drawing (rows +R75 and R76). In versions 4 to 13 the picture is the `DISP` chunk, returned as a BMP file. In versions +14 to 16 it is the package member `metadata/thumbnails/thumbnail.bmp`, and from version 17 on it +is `previews/thumbnail.png`. The package's drawing stream is not read, so a package that holds +both members gives the PNG. Files of versions 1 and 3 keep no picture. A version 2 file keeps a +1-bit picture (R40) that `preview` does not read, so it refuses the file. `preview` does not check +the drawing's version, so a RIFF file that `read` refuses for its version, such as one that names a +version before 3, still gives its `DISP` picture. + +A `DISP` bitmap must start with the 4 bytes `08 00 00 00`, have a 40-byte info header and be +uncompressed (compression 0, or 3 with color masks at 16 or 32 bits). A `DISP` chunk of another +kind, or a bitmap with another header length or compression, is passed over without checking the +rest of its bytes, and a file with no other `DISP` chunk is refused. A RIFF file without a `DISP` bitmap is refused as damaged when its last chunk does not end +where the form's length says the form ends, which includes a file cut short. The bytes are returned +still encoded, so the caller decodes them within its own image limits. + +## `.cmx` files + +`read_cmx` reads `.cmx` exchange files with 32-bit coordinates (rows R53 to R63) into the same +drawing model, with a version of 0. It reads the color, pen, line type, dash, outline and +arrowhead tables, then each page's instructions in drawing order: + +| In the `.cmx` file | Read as | +|---|---| +| Pages, with the size the page gives, or else the size of the drawing's bounds that the page stores | pages; a page sized to the bounds is centered on them | +| Layers, by their UTF-16 or 8-bit name | drawing layers, unnamed when the file gives no name; a layer that holds nothing is left out | +| Groups | groups | +| Curves (moves, lines and cubic curves, as `.cdr` point lists) | paths | +| Uniform fills: CMYK in percent or 0 to 255, CMY, RGB, gray, and library colors with their names | colors, spot colors | +| Outlines: width, color, caps, joins, dashes, the no-outline, behind-the-fill and scaled-with flags | outlines | + +Text, images, rectangles, ellipses, clipping paths, fills other than uniform ones, outline +arrowheads and lenses are not read; the drawing's `warnings` name each kind it held. A clipping +path is left out and the objects it clips are read without it. Files in big-endian byte order and +files with 16-bit coordinates are refused. + +## Provenance + +`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status. +Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row. +The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the +`synth` feature); no third-party file is committed. + +## Limits + +`Limits` bounds the input size, the bytes inflated from compressed lists and package members, the +size of one package member, the number of members, the nesting depth, the chunk count, the +objects, the coordinates and the outline dashes of one read. Past a limit the reader stops with an +error or leaves the rest out with a warning; it does not recurse and does not panic. Each record +of a version 1 or 2 file counts toward the chunk count, and the transform entries of a version 3 +object are held to the arguments one record may have. A package's +data stream is read once however many lines of `content/dataFileList.dat` name it. A redirected +list whose bytes overlap those of an earlier redirected list is left out with the damage warning. +Other records may share bytes, and the bytes read again may add up to the member limit; past it +the records are left out with the limit warning. diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs new file mode 100644 index 0000000000..0bf017e4d7 --- /dev/null +++ b/crates/cdr/src/build.rs @@ -0,0 +1,917 @@ +//! The drawing the chunk index holds: pages, layers, objects and the fills and outlines they name +//! (R19 to R23). Records are decoded only when an object refers to them. + +use std::collections::HashMap; + +use crate::bytes::Rd; +use crate::geometry; +use crate::inline; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Blend, Color, Drawing, Flags, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; +use crate::records::{self, Loda}; +use crate::riff::{Chunk, Index, push}; +use crate::styles::Styles; +use crate::{Error, Warning}; + +/// Object types (R6). +const RECTANGLE: u32 = 1; +const ELLIPSE: u32 = 2; +const CURVE: u32 = 3; +const POLYGON: u32 = 0x14; +const GUIDELINE: u32 = 0x16; +const PATH: u32 = 0x25; +/// Argument types (R6, R20, R21, R33, R52). +const ARG_OUTLINE: u32 = 10; +const ARG_FILL: u32 = 20; +const ARG_COORDS: u32 = 30; +const ARG_TRANSFORMS: u32 = 100; +const ARG_STYLE: u32 = 200; +const ARG_NAME: u32 = 1000; +const ARG_LENS: u32 = 8000; +const ARG_CONTAINER: u32 = 8005; +const ARG_POLYGON: u32 = 11000; +const ARG_WINDING: u32 = 14001; +const ARG_GUIDE: u32 = 16000; +const ARG_PAGE_SIZE: u32 = 19130; + +/// What a RIFF file that names a version before 3 is refused as. +const BEFORE_3: &str = "RIFF files of versions before 3"; + +/// What one read keeps while mapping. +struct Ctx<'a, 'b> { + ix: &'b Index<'a>, + p: Profile, + budget: &'b mut Budget, + warn: &'b mut Vec, + /// Fill and outline records by id, decoded on first use. + fill_chunks: HashMap, + outline_chunks: HashMap, + fills: HashMap>, + outlines: HashMap>, + /// The styles objects name in argument 200 (R45): `Err` when the file's style table doesn't + /// parse. + styles: Result, + /// The groups of `LIST clpt` that containers clip, by the id in their `spnd` chunk (R46). + clips: HashMap, + /// The clipped groups being read, innermost last. + open_clips: Vec, + /// Whether the walk of a clipped group stopped at the clipped chunk limit. + clip_cut: bool, + /// The chunks the object lists of clipped groups keep for themselves, by list, each found the + /// first time a read needs it. + own: HashMap<(*const Chunk, Own), Option<&'b Chunk>>, + /// The matrices the `trfd` chunks of clipped groups' objects hold, by chunk; `None` for one + /// that can't be read. + trfds: HashMap<*const Chunk, Option>, +} + +/// A chunk an object list keeps for itself. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Own { + /// Its `loda` (or `lobj`). + Loda, + /// Its `flgs`, among its own chunks alone. + Flags, + /// Its `trfd`. + Trfd, +} + +impl Own { + fn ids(self) -> &'static [&'static [u8; 4]] { + match self { + Own::Loda => &[b"loda", b"lobj"], + Own::Flags => &[b"flgs"], + Own::Trfd => &[b"trfd"], + } + } +} + +/// The most clipped groups read one inside another: VectorCraft's own limit. +const MAX_CLIP_DEPTH: usize = 64; + +pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) -> Result { + let root = ix.root().ok_or(Error::NotCdr)?; + let version = ix.version(); + // A template whose `vrsn` chunk doesn't name a version read (R28). + if version == 0 { + return Err(Error::NotCdr); + } + // Versions 1 and 2 are `WL` files (R40); no source shows a RIFF file that names a version + // before 3. + if version < layout::OLDEST_RIFF { + return Err(Error::Unsupported(BEFORE_3)); + } + let p = layout::for_version(version).ok_or(Error::Version(version))?; + let mut found = Found::default(); + collect(ix, root, &mut found); + let page_size = found.mcfg.and_then(|c| page_size(ix.data(c), &p)); + // Before version 7 a `LIST stlt` holds chunks, not the style table (R4). + let styles = match found.stlt { + Some(c) if version >= 700 => Styles::read(ix.data(c), version, budget)?.ok_or(()), + _ => Ok(Styles::default()), + }; + let mut cx = Ctx { + ix, + p, + budget, + warn, + fill_chunks: HashMap::new(), + outline_chunks: HashMap::new(), + fills: HashMap::new(), + outlines: HashMap::new(), + styles, + clips: HashMap::new(), + open_clips: Vec::new(), + clip_cut: false, + own: HashMap::new(), + trfds: HashMap::new(), + }; + // The `spnd` id is a u16 in files of 16-bit fields (R46). + let spnd = |b: &[u8]| if p.short { Rd::new(b).u16().map(u32::from) } else { Rd::new(b).u32() }; + for g in found.clpt.iter().flat_map(|c| ix.children(c)).filter(|g| g.is_list(b"grp ")) { + if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| spnd(ix.data(c))) { + cx.clips.entry(id).or_insert(g); + } + } + for c in &found.fills { + if let Some(id) = Rd::new(ix.data(c)).u32() { + cx.fill_chunks.entry(id).or_insert(ix.data(c)); + } + } + for c in &found.outlines { + if let Some(id) = Rd::new(ix.data(c)).u32() { + cx.outline_chunks.entry(id).or_insert(ix.data(c)); + } + } + let mut guides = found.guid.map(|c| guid_chunk(ix.data(c), &cx.p, cx.budget, cx.warn)).unwrap_or_default(); + let mut pages = Vec::new(); + let mut master = Vec::new(); + for page in &found.pages { + let (is_master, read) = cx.page(page); + if is_master { + // Guidelines on any of the master page's layers show on every page. + for mut layer in read.layers { + guides.append(&mut layer.guides); + if !layer.objects.is_empty() && layer.kind != LayerKind::Grid { + master.push(layer); + } + } + } else { + pages.push(read); + } + } + // A file of only a master page keeps it as its page. + if pages.is_empty() && !master.is_empty() { + pages.push(Page { size: None, layers: std::mem::take(&mut master) }); + } + Ok(Drawing { version, page_size, pages, master, guides, warnings: std::mem::take(cx.warn) }) +} + +#[derive(Default)] +struct Found<'i> { + fills: Vec<&'i Chunk>, + outlines: Vec<&'i Chunk>, + mcfg: Option<&'i Chunk>, + guid: Option<&'i Chunk>, + stlt: Option<&'i Chunk>, + clpt: Vec<&'i Chunk>, + pages: Vec<&'i Chunk>, +} + +/// Every fill, outline, `LIST clpt` and page in file order, and the first `mcfg`, `guid` and +/// `LIST stlt`; pages are not looked into. +fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { + let mut stack: Vec<&Chunk> = ix.children(root).iter().rev().collect(); + while let Some(c) = stack.pop() { + match &c.id { + b"fild" | b"fill" => found.fills.push(c), + b"outl" => found.outlines.push(c), + b"mcfg" => found.mcfg = found.mcfg.or(Some(c)), + b"guid" => found.guid = found.guid.or(Some(c)), + // Before version 7 the list holds chunks, which are looked through. + _ if c.is_list(b"stlt") => { + found.stlt = found.stlt.or(Some(c)); + stack.extend(ix.children(c).iter().rev()); + } + _ if c.is_list(b"clpt") => found.clpt.push(c), + _ if c.is_list(b"page") => found.pages.push(c), + _ => stack.extend(ix.children(c).iter().rev()), + } + } +} + +/// The page size in `mcfg` (R10); in version 3 the distance between the page's two corners, after +/// 2 bytes (R38). +fn page_size(b: &[u8], p: &Profile) -> Option<(f64, f64)> { + let mut r = Rd::at(b, p.mcfg_skip); + if p.mcfg_corners { + r.skip(2)?; + let (x0, y0, x1, y1) = (records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?); + return sane_size(x1 - x0, y1 - y0); + } + sane_size(records::coord(&mut r, p)?, records::coord(&mut r, p)?) +} + +fn sane_size(w: f64, h: f64) -> Option<(f64, f64)> { + let (w, h) = (w.abs(), h.abs()); + (w > 0.0 && h > 0.0).then_some((w, h)) +} + +/// The version 7 `guid` chunk (R23): two counts, then 40-byte records laid out as argument 16000. +/// Each guideline counts toward the objects a read maps; past them the rest are left out. +fn guid_chunk(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Vec { + let mut r = Rd::new(b); + let Some(n) = r.u32() else { return Vec::new() }; + let _again = r.u32(); + let fits = r.left() / 40; + if n as usize > fits { + push(warn, Warning::Damaged); + } + let n = (n as usize).min(fits); + let mut out = Vec::new(); + for i in 0..n { + if !budget.take_object() { + push(warn, Warning::TooDeep); + break; + } + out.extend(b.get(8 + i * 40..8 + (i + 1) * 40).and_then(|g| guideline(g, p))); + } + out +} + +/// A guideline record (R23): 12 bytes, the angle in millionths of a degree, then a point. +fn guideline(b: &[u8], p: &Profile) -> Option { + if p.short { + return None; + } + let mut r = Rd::at(b, 12); + let angle = f64::from(r.i32()?) / 1_000_000.0; + let at = Pt { x: records::coord(&mut r, p)?, y: records::coord(&mut r, p)? }; + Some(Guideline { at, angle, hidden: false }) +} + +/// Marks the guidelines from `from` on hidden when `flags` hide what holds them. +fn hide_guides(guides: &mut [Guideline], from: usize, flags: Flags) { + if flags.hidden { + for g in guides.iter_mut().skip(from) { + g.hidden = true; + } + } +} + +/// A list's flags (R19): four bytes. +fn flags(ix: &Index, list: &Chunk) -> Option<[u8; 4]> { + flgs_bytes(ix, ix.children(list).iter().find(|c| &c.id == b"flgs")?) +} + +/// The four bytes of a `flgs` chunk. +fn flgs_bytes(ix: &Index, c: &Chunk) -> Option<[u8; 4]> { + ix.data(c).get(..4)?.try_into().ok() +} + +/// Whether a layer, group or object list is hidden (bit 0x01 of byte 1) or locked (bit 0x10 of +/// byte 0) (R19). +fn state(ix: &Index, list: &Chunk) -> Flags { + flags(ix, list).map_or(Flags::default(), flag_bits) +} + +/// What a list's four flag bytes say, as [`state`] reads them. +fn flag_bits([b0, b1, _, _]: [u8; 4]) -> Flags { + Flags { hidden: b1 & 0x01 != 0, locked: b0 & 0x10 != 0 } +} + +/// `o` with `f` added to its own flags: the objects of a group left ungrouped keep the group's. +fn inherit(o: &mut Object, f: Flags) { + let own = match o { + Object::Shape(s) => &mut s.flags, + Object::Group { flags, .. } => flags, + Object::Clip { container, .. } => &mut container.flags, + }; + own.hidden |= f.hidden; + own.locked |= f.locked; +} + +/// What a layer's object type makes it (R19): 11 a grid, 12 guides, 17 the desktop, any other a +/// drawing layer. Version 3 counts its types from 0, one less (R32). +fn layer_kind_of_type(kind: u32, types_from_zero: bool) -> LayerKind { + match kind.saturating_add(u32::from(types_from_zero)) { + 11 => LayerKind::Grid, + 12 => LayerKind::Guides, + 17 => LayerKind::Desktop, + _ => LayerKind::Drawing, + } +} + +/// What a layer's flags make it, for a layer without an object type of its own (R19). The low +/// four bits of byte 0 hold the kind: 0x0a guides, or a grid with bit 0x10 set (versions 7 to 13 +/// also flag them 0x02); 0x08 the desktop when byte 2 is set, a drawing layer when it is clear. +/// Versions 7 to 13 may flag the master page's desktop layer 0 with bytes 1 and 2 set. Bit 0x10 +/// alone does not make a grid. +fn layer_kind(f: [u8; 4], version_below_14: bool) -> LayerKind { + let [b0, b1, b2, _] = f; + let grid_bit = b0 & 0x10 != 0; + match b0 & 0x0f { + 0x0a if grid_bit => LayerKind::Grid, + 0x0a => LayerKind::Guides, + 0x02 if version_below_14 && grid_bit => LayerKind::Grid, + 0x02 if version_below_14 => LayerKind::Guides, + 0x08 if b2 != 0 => LayerKind::Desktop, + 0 if version_below_14 && b1 == 1 && b2 == 1 => LayerKind::Desktop, + _ => LayerKind::Drawing, + } +} + +/// The first chunk of one of `ids` that a page, layer or object keeps for itself: among its own +/// chunks, or in its `lgob` list and the `trfl` list there (R22). +fn own_chunk<'i>(ix: &'i Index, list: &'i Chunk, ids: &[&[u8; 4]]) -> Option<&'i Chunk> { + find_own(ix, list, ids, true, || true).flatten() +} + +/// The first chunk of one of `ids` among `list`'s own chunks, and when `nested` also in its `lgob` +/// list and the `trfl` list there, as [`own_chunk`] finds it. `visit` is asked before each chunk +/// the search looks at, and the search stops with `None` when it answers `false`. +fn find_own<'i>(ix: &'i Index, list: &'i Chunk, ids: &[&[u8; 4]], nested: bool, mut visit: impl FnMut() -> bool) -> Option> { + // The lists being looked through, outermost first, each with the next chunk to look at, and + // the innermost one's place. + let mut stack: [(&'i [Chunk], usize); 3] = [(ix.children(list), 0), (&[], 0), (&[], 0)]; + let mut depth = 0; + loop { + let Some(top) = stack.get_mut(depth) else { return Some(None) }; + let chunks: &'i [Chunk] = top.0; + let Some(c) = chunks.get(top.1) else { + if depth == 0 { + return Some(None); + } + depth -= 1; + continue; + }; + top.1 += 1; + if !visit() { + return None; + } + if ids.contains(&&c.id) { + return Some(Some(c)); + } + if nested && depth < 2 && (c.is_list(b"lgob") || c.is_list(b"trfl")) { + depth += 1; + if let Some(next) = stack.get_mut(depth) { + *next = (ix.children(c), 0); + } + } + } +} + +/// The `loda` (or `lobj`) a page, layer or object keeps for itself. +fn own_loda<'i>(ix: &'i Index, list: &'i Chunk) -> Option<&'i Chunk> { + own_chunk(ix, list, &[b"loda", b"lobj"]) +} + +/// A page's layer lists in file order: its own, and those in the lists it holds, such as the +/// `gobj` list of files of versions 7 to 13 (R22). +fn page_layers<'i>(ix: &'i Index, page: &'i Chunk) -> Vec<&'i Chunk> { + let mut out = Vec::new(); + let mut stack: Vec<&Chunk> = ix.children(page).iter().rev().collect(); + while let Some(c) = stack.pop() { + if c.is_list(b"layr") { + out.push(c); + } else if c.id == crate::riff::LIST && !c.is_list(b"lgob") { + stack.extend(ix.children(c).iter().rev()); + } + } + out +} + +/// One frame of the object walk: a list's chunks, the next one to look at, and the objects so far. +struct Frame<'i> { + chunks: &'i [Chunk], + next: usize, + objects: Vec, + /// Whether its objects form a group in the frame below. + group: bool, + /// The group's own flags. + flags: Flags, + /// The first of the guidelines read inside it. + guides_from: usize, + /// What places its objects after their own transforms: the matrices of the version 3 groups + /// around them (R33). The identity in other versions, whose objects hold their whole transform. + outer: Matrix, +} + +impl<'a, 'b> Ctx<'a, 'b> { + /// A page: whether it is the master page, and its layers. + fn page(&mut self, page: &Chunk) -> (bool, Page) { + let ix = self.ix; + let is_master = flags(ix, page).is_some_and(|f| f[2] != 0); + let size = own_loda(ix, page) + .and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) + .and_then(|l| l.arg(ARG_PAGE_SIZE).and_then(|b| self.size_arg(b))); + let mut layers = Vec::new(); + for l in page_layers(ix, page) { + let layer = self.layer(l); + let empty = layer.objects.is_empty() && layer.guides.is_empty(); + // The entries that stand for the master page's layers hold nothing of the page's own. + if empty && (is_master || layer.kind != LayerKind::Drawing) { + continue; + } + layers.push(layer); + } + (is_master, Page { size, layers }) + } + + fn size_arg(&self, b: &[u8]) -> Option<(f64, f64)> { + let mut r = Rd::new(b); + sane_size(records::coord(&mut r, &self.p)?, records::coord(&mut r, &self.p)?) + } + + fn layer(&mut self, list: &Chunk) -> Layer { + let ix = self.ix; + let loda = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)); + // The layer's own object type says what it is; its flags, only when it has none (R19). + let kind = match &loda { + Some(l) => layer_kind_of_type(l.kind, self.p.types_from_zero), + None => flags(ix, list).map_or(LayerKind::Drawing, |f| layer_kind(f, self.p.old_master_flags)), + }; + let name = loda.and_then(|l| l.arg(ARG_NAME).map(|b| records::name(b, &self.p, self.warn))).unwrap_or_default(); + let mut guides = Vec::new(); + let objects = self.objects(ix.children(list), &mut guides); + let flags = state(ix, list); + hide_guides(&mut guides, 0, flags); + Layer { name, kind, flags, objects, guides } + } + + /// The objects of a layer's chunks, groups nested, front to back; guidelines go to `guides`. + fn objects(&mut self, chunks: &'b [Chunk], guides: &mut Vec) -> Vec { + let ix = self.ix; + let mut stack = vec![Frame { + chunks, + next: 0, + objects: Vec::new(), + group: false, + flags: Flags::default(), + guides_from: guides.len(), + outer: Matrix::IDENTITY, + }]; + loop { + let Some(top) = stack.last_mut() else { return Vec::new() }; + let (here, outer) = (top.chunks, top.outer); + let Some(c) = here.get(top.next) else { + let Some(done) = stack.pop() else { return Vec::new() }; + // A hidden group hides the guidelines inside it. + hide_guides(guides, done.guides_from, done.flags); + match stack.last_mut() { + // A group counts toward the objects a read maps; past them its objects stay, + // ungrouped, with the group's flags. + Some(parent) if done.group && !done.objects.is_empty() => { + if self.budget.take_object() { + parent.objects.push(Object::Group { objects: done.objects, flags: done.flags }); + } else { + push(self.warn, Warning::TooDeep); + let mut objects = done.objects; + for o in &mut objects { + inherit(o, done.flags); + } + parent.objects.extend(objects); + } + } + Some(parent) if !done.group => parent.objects.extend(done.objects), + Some(_) => {} + None => return done.objects, + } + continue; + }; + top.next += 1; + // Every chunk of a clipped group counts, empty groups included, each time a container + // names the group; past the limit the group is left out. + if !self.open_clips.is_empty() && !self.budget.take_clipped_chunk() { + push(self.warn, Warning::TooDeep); + self.clip_cut = true; + return Vec::new(); + } + if c.is_list(b"obj ") { + if let Some(o) = self.object(c, guides, &outer) { + top.objects.push(o); + } + // Past the limit while looking for what the object keeps for itself. + if self.clip_cut { + return Vec::new(); + } + } else if c.is_list(b"grp ") { + let own = self.group_placement(c); + let flags = state(ix, c); + let guides_from = guides.len(); + stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, flags, guides_from, outer: outer.after(&own) }); + } else if c.is_list(b"lnkg") { + // Linked groups (brush strokes, blends, contours) place their objects with a + // matrix of their own, which this reader doesn't apply: they are left out. + push(self.warn, Warning::UnsupportedObjects); + } else if c.id == crate::riff::LIST && !c.is_list(b"lgob") { + // Other lists under a layer are looked through (R22). + let guides_from = guides.len(); + stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, flags: Flags::default(), guides_from, outer }); + } + } + } + + /// The `which` chunk object list `list` keeps for itself. In a clipped group it is looked for + /// once per read, the first time a container's walk needs it, and each chunk the search looks + /// at counts toward the clipped chunk limit then; past that limit the walk stops (`None`). + fn own(&mut self, list: &'b Chunk, which: Own) -> Option> { + let nested = which != Own::Flags; + if self.open_clips.is_empty() { + return find_own(self.ix, list, which.ids(), nested, || true); + } + let key = (std::ptr::from_ref(list), which); + if let Some(c) = self.own.get(&key) { + return Some(*c); + } + let Some(c) = find_own(self.ix, list, which.ids(), nested, || self.budget.take_clipped_chunk()) else { + push(self.warn, Warning::TooDeep); + self.clip_cut = true; + return None; + }; + self.own.insert(key, c); + Some(c) + } + + /// The matrix `trfd` holds, or `None` when it can't be read. In a clipped group each `trfd` is + /// read once per read, however many containers name the group. + fn trfd(&mut self, c: &'b Chunk) -> Option { + if self.open_clips.is_empty() { + return records::trfd(self.ix.data(c), &self.p); + } + let ix = self.ix; + let p = &self.p; + *self.trfds.entry(std::ptr::from_ref(c)).or_insert_with(|| records::trfd(ix.data(c), p)) + } + + /// The matrix a group places its objects with. Only a version 3 group has one, in the + /// transforms argument of its own `lobj` (R33); one that can't be read is damage, and the + /// group's objects stay where their own transforms put them. + fn group_placement(&mut self, list: &Chunk) -> Matrix { + if !self.p.inline_styles { + return Matrix::IDENTITY; + } + let ix = self.ix; + let Some(arg) = + own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)).and_then(|l| l.arg(ARG_TRANSFORMS)) + else { + return Matrix::IDENTITY; + }; + self.placement(arg) + } + + /// The matrices of a transforms argument (R33). An envelope among them is not applied: the + /// shapes keep their outlines, placed by the matrices alone, with the envelopes warning. + fn placement(&mut self, arg: &[u8]) -> Matrix { + match inline::transforms(arg, &self.p, &self.budget.limits, self.warn) { + Some(t) => { + if t.envelope { + push(self.warn, Warning::Envelopes); + } + t.matrix + } + None => { + push(self.warn, Warning::Damaged); + Matrix::IDENTITY + } + } + } + + /// One `LIST obj `: a shape placed by its own transform and then by `outer`, or `None` (a + /// guideline goes to `guides`). + fn object(&mut self, list: &'b Chunk, guides: &mut Vec, outer: &Matrix) -> Option { + let ix = self.ix; + let Some(loda) = self.own(list, Own::Loda)?.and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) else { + push(self.warn, Warning::Damaged); + return None; + }; + // Guidelines count toward the objects a read maps. + if !self.budget.take_object() { + push(self.warn, Warning::TooDeep); + return None; + } + let flags = self.own(list, Own::Flags)?.and_then(|c| flgs_bytes(ix, c)).map_or(Flags::default(), flag_bits); + if loda.kind == GUIDELINE { + guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p)).map(|g| Guideline { hidden: flags.hidden, ..g })); + return None; + } + if self.p.inline_styles { + return self.inline_object(&loda, outer, flags); + } + let geometry = self.geometry(&loda)?; + // A uniform transparency from version 13 applies (R47); a lens, and a transparency of + // another kind or version, is not applied: the shape shows opaque. + let (opacity, blend) = match loda.arg(ARG_LENS) { + None => (1.0, Blend::Normal), + Some(b) => match records::transparency(b).filter(|_| self.p.tagged) { + Some(t) => t, + None => { + push(self.warn, Warning::Lenses); + (1.0, Blend::Normal) + } + }, + }; + let nonzero = self.nonzero(&loda); + // A transform that is there but can't be read is damage; the shape stays where it is. + let matrix = match self.own(list, Own::Trfd)? { + None => Matrix::IDENTITY, + Some(c) => self.trfd(c).unwrap_or_else(|| { + push(self.warn, Warning::Damaged); + Matrix::IDENTITY + }), + }; + // Without a fill or outline argument of its own, an object takes its style's (R45). The + // style id is a u16 in files of 16-bit fields. + let style = loda.arg(ARG_STYLE).and_then(|b| if self.p.short { self.short_id(b) } else { self.id(b) }); + let fill_id = match loda.arg(ARG_FILL) { + Some(b) => self.id(b), + None => style.and_then(|s| self.style_entry(s, Styles::fill)), + }; + let outline_id = match loda.arg(ARG_OUTLINE) { + Some(b) => self.id(b), + None => style.and_then(|s| self.style_entry(s, Styles::outline)), + }; + let fill = fill_id.and_then(|id| self.fill(id)); + let outline = outline_id.and_then(|id| self.outline(id)); + let shape = Box::new(Shape { geometry, matrix, fill, outline, nonzero, opacity, blend, flags }); + // A container clips the group its argument 8005 names (R46). + Some(match loda.arg(ARG_CONTAINER).and_then(|b| self.id(b)) { + Some(id) => self.clip(shape, id, guides), + None => Object::Shape(shape), + }) + } + + /// `container` and the objects of the clipped group `id`, which keep their own transforms. + /// A group that isn't there is damage; one already being read, past the depth limit or past + /// the chunks clipped groups may walk is left out with the limit warning, the guidelines it + /// holds included. Either way the container stays, as a plain shape. + fn clip(&mut self, container: Box, id: u32, guides: &mut Vec) -> Object { + let Some(&group) = self.clips.get(&id) else { + push(self.warn, Warning::Damaged); + return Object::Shape(container); + }; + if self.open_clips.contains(&id) || self.open_clips.len() >= MAX_CLIP_DEPTH { + push(self.warn, Warning::TooDeep); + return Object::Shape(container); + } + self.open_clips.push(id); + let (ix, mark) = (self.ix, guides.len()); + let objects = self.objects(ix.children(group), guides); + self.open_clips.pop(); + if std::mem::take(&mut self.clip_cut) { + guides.truncate(mark); + return Object::Shape(container); + } + // The clipped group's own flags hide or lock the objects it holds; it and the container + // hide its guidelines. + let flags = state(ix, group); + hide_guides(guides, mark, flags); + hide_guides(guides, mark, container.flags); + if objects.is_empty() { + return Object::Shape(container); + } + let mut objects = objects; + for o in &mut objects { + inherit(o, flags); + } + Object::Clip { container, objects } + } + + /// The record id that argument `b` names; an argument too short for one is damage. + fn id(&mut self, b: &[u8]) -> Option { + let id = id_of(b); + if id.is_none() { + push(self.warn, Warning::Damaged); + } + id + } + + /// A u16 id at the start of argument `b`; an argument too short for one is damage. + fn short_id(&mut self, b: &[u8]) -> Option { + let id = Rd::new(b).u16().map(u32::from); + if id.is_none() { + push(self.warn, Warning::Damaged); + } + id + } + + /// Whether the object's fill rule is nonzero: byte 0 of argument 14001 set (R52). Without the + /// argument the fill is even-odd; an argument without its byte is damage. + fn nonzero(&mut self, loda: &Loda) -> bool { + let Some(b) = loda.arg(ARG_WINDING) else { return false }; + match b.first() { + Some(v) => *v != 0, + None => { + push(self.warn, Warning::Damaged); + false + } + } + } + + /// The fill or outline record that style `id` names; a style table that doesn't parse is + /// damage, and the object is drawn without it. + fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option) -> Option { + match &self.styles { + Ok(s) => entry(s, id), + Err(()) => { + push(self.warn, Warning::Damaged); + None + } + } + } + + /// A version 3 object, whose transforms, fill and outline are arguments of its own record + /// (R33, R34, R35). A fill or an outline that is there but can't be read is damage. + fn inline_object(&mut self, loda: &Loda, outer: &Matrix, flags: Flags) -> Option { + let own = match loda.arg(ARG_TRANSFORMS) { + None => Matrix::IDENTITY, + Some(arg) => self.placement(arg), + }; + let geometry = self.geometry(loda)?; + let fill = loda.arg(ARG_FILL).and_then(|b| { + let read = inline::fill(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.flatten() + }); + let outline = loda.arg(ARG_OUTLINE).and_then(|b| { + let read = inline::outline(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.flatten() + }); + // Past the dashes a read takes, the outline is solid. + let outline = outline.map(|mut o| { + if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + o + }); + let nonzero = self.nonzero(loda); + let shape = Shape { nonzero, flags, ..Shape::new(geometry, outer.after(&own), fill, outline) }; + Some(Object::Shape(Box::new(shape))) + } + + fn geometry(&mut self, loda: &Loda) -> Option { + let coords = loda.arg(ARG_COORDS); + // Version 3 counts the first object types from 0, one below the later numbers (R32). + let kind = if self.p.types_from_zero && loda.kind <= 4 { loda.kind + 1 } else { loda.kind }; + // A shape without its coordinates, or a polygon without its sides, is damage like a shape + // whose coordinates can't be read; one left out at the coordinate limit is not. + self.budget.coordinates_refused(); + let g = match kind { + RECTANGLE => coords.and_then(|c| geometry::rect(c, &self.p)), + ELLIPSE => coords.and_then(|c| geometry::ellipse(c, &self.p)), + CURVE => coords.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)).map(Geometry::Path), + PATH if self.p.paths => coords.and_then(|c| geometry::path_record(c, &self.p, self.budget, self.warn)).map(Geometry::Path), + POLYGON => match loda.arg(ARG_POLYGON) { + Some(sides) => coords + .and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)) + .and_then(|base| geometry::polygon(&base, sides, &self.p, self.budget, self.warn)), + None => { + push(self.warn, Warning::Damaged); + return None; + } + }, + _ => { + push(self.warn, Warning::UnsupportedObjects); + return None; + } + }; + if g.is_none() && !self.budget.coordinates_refused() { + push(self.warn, Warning::Damaged); + } + g + } + + fn fill(&mut self, id: u32) -> Option { + if let Some(f) = self.fills.get(&id) { + return f.clone(); + } + // A record that is missing or can't be read is damage, and the shape is drawn without a + // fill; id 0 without a record is no fill. + if id != 0 && !self.fill_chunks.contains_key(&id) { + push(self.warn, Warning::Damaged); + } + let read = self.fill_chunks.get(&id).and_then(|b| { + let read = records::fill(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.and_then(|(_, c)| c) + }); + self.fills.insert(id, read.clone()); + read + } + + /// The outline of record `id`. Its dashes count toward the read's dashes for every shape that + /// uses it; past them the shape's outline is solid. + fn outline(&mut self, id: u32) -> Option { + if !self.outlines.contains_key(&id) { + // A record that is missing is damage, as one that can't be read is; id 0 without a + // record is no outline. + if id != 0 && !self.outline_chunks.contains_key(&id) { + push(self.warn, Warning::Damaged); + } + let read = self.outline_chunks.get(&id).and_then(|b| { + let read = records::outline(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.and_then(|(_, o)| o) + }); + // An outline with more dashes than the read may still take is kept solid. + let read = read.map(|mut o| { + if o.dashes.len() > self.budget.dashes_left() { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + o + }); + self.outlines.insert(id, read); + } + let o = self.outlines.get_mut(&id)?.as_mut()?; + // The dashes left only shrink, so an outline refused once is refused for every later + // shape: its dashes are dropped from the cache, and later shapes take it solid. + if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + Some(o.clone()) + } +} + +/// A fill or outline argument: the record id (R20). +fn id_of(b: &[u8]) -> Option { + Rd::new(b).u32() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layer_flags_name_the_kinds() { + assert_eq!(layer_kind([0, 0, 0, 0x98], true), LayerKind::Drawing); + assert_eq!(layer_kind([0x0a, 0, 0, 0x98], true), LayerKind::Guides); + assert_eq!(layer_kind([0x02, 1, 1, 0x98], true), LayerKind::Guides); + assert_eq!(layer_kind([0x08, 0, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0, 1, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0x1a, 0, 1, 0x98], true), LayerKind::Grid); + assert_eq!(layer_kind([0x12, 0, 1, 0x98], true), LayerKind::Grid); + // From version 14 the master page flags its layers by byte 0 alone. + assert_eq!(layer_kind([0x0a, 0, 1, 0x98], false), LayerKind::Guides); + assert_eq!(layer_kind([0x08, 0, 1, 0x98], false), LayerKind::Desktop); + assert_eq!(layer_kind([0x5a, 1, 1, 0x98], false), LayerKind::Grid); + assert_eq!(layer_kind([0x02, 1, 1, 0x98], false), LayerKind::Drawing); + assert_eq!(layer_kind([0, 1, 1, 0x98], false), LayerKind::Drawing); + // Drawing layers flagged 0x10, 0x08, 0x18, 0x40 and 0x58 with byte 2 clear, as sample + // files flag them, and desktop and guides layers with bit 0x40 or 0x10 set. + for f in [[0x10, 0, 0, 0x98], [0x08, 1, 0, 0x98], [0x18, 1, 0, 0x98], [0x40, 0, 0, 0x98], [0x58, 1, 0, 0x98]] { + assert_eq!(layer_kind(f, true), LayerKind::Drawing, "{f:?}"); + assert_eq!(layer_kind(f, false), LayerKind::Drawing, "{f:?}"); + } + assert_eq!(layer_kind([0x18, 0, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0x48, 0, 1, 0x98], false), LayerKind::Desktop); + assert_eq!(layer_kind([0x4a, 1, 1, 0x98], true), LayerKind::Guides); + } + + /// An outline record refused at the dash limit keeps no dashes in the cache, so the shapes + /// that use it later copy none. + #[test] + fn an_outline_past_the_dash_limit_keeps_no_dashes() { + let v = crate::synth::V(1100); + let pen = crate::synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 }; + let record = v.outline(1, pen, &crate::synth::color(5, [0, 0, 0, 255]), &[3, 1, 3]); + let file = crate::synth::riff(1100, &[]); + let mut budget = Budget::new(crate::Limits { dashes: 4, ..crate::Limits::default() }); + let mut warn = Vec::new(); + let ix = crate::riff::Index::build(&file, None, &mut budget, &mut warn).unwrap(); + let mut cx = Ctx { + ix: &ix, + p: layout::for_version(1100).unwrap(), + budget: &mut budget, + warn: &mut warn, + fill_chunks: HashMap::new(), + outline_chunks: HashMap::from([(1, record.as_slice())]), + fills: HashMap::new(), + outlines: HashMap::new(), + styles: Ok(Styles::default()), + clips: HashMap::new(), + open_clips: Vec::new(), + clip_cut: false, + own: HashMap::new(), + trfds: HashMap::new(), + }; + assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(3)); + for _ in 0..3 { + assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(0)); + assert_eq!(cx.outlines.get(&1).and_then(|o| o.as_ref()).map(|o| o.dashes.len()), Some(0)); + } + assert_eq!(*cx.warn, vec![Warning::TooDeep]); + } +} diff --git a/crates/cdr/src/bytes.rs b/crates/cdr/src/bytes.rs new file mode 100644 index 0000000000..216bd90024 --- /dev/null +++ b/crates/cdr/src/bytes.rs @@ -0,0 +1,76 @@ +//! Little-endian reads that fail instead of panicking. + +/// A cursor over one record's bytes. Every read returns `None` past the end. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Rd<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Rd<'a> { + pub(crate) fn new(b: &'a [u8]) -> Self { + Rd { b, pos: 0 } + } + + pub(crate) fn at(b: &'a [u8], pos: usize) -> Self { + Rd { b, pos } + } + + pub(crate) fn pos(&self) -> usize { + self.pos + } + + pub(crate) fn left(&self) -> usize { + self.b.len().saturating_sub(self.pos) + } + + pub(crate) fn skip(&mut self, n: usize) -> Option<()> { + let end = self.pos.checked_add(n)?; + (end <= self.b.len()).then(|| self.pos = end) + } + + pub(crate) fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { + let end = self.pos.checked_add(n)?; + let s = self.b.get(self.pos..end)?; + self.pos = end; + Some(s) + } + + fn array(&mut self) -> Option<[u8; N]> { + self.bytes(N)?.try_into().ok() + } + + pub(crate) fn u8(&mut self) -> Option { + Some(self.array::<1>()?[0]) + } + + pub(crate) fn u16(&mut self) -> Option { + self.array().map(u16::from_le_bytes) + } + + pub(crate) fn i16(&mut self) -> Option { + self.array().map(i16::from_le_bytes) + } + + pub(crate) fn u32(&mut self) -> Option { + self.array().map(u32::from_le_bytes) + } + + pub(crate) fn i32(&mut self) -> Option { + self.array().map(i32::from_le_bytes) + } + + /// A finite f64; NaN and the infinities read as `None`. + pub(crate) fn f64(&mut self) -> Option { + self.array().map(f64::from_le_bytes).filter(|v| v.is_finite()) + } + + pub(crate) fn fourcc(&mut self) -> Option<[u8; 4]> { + self.array() + } +} + +/// The u32 at `pos` of `b`. +pub(crate) fn u32_at(b: &[u8], pos: usize) -> Option { + Rd::at(b, pos).u32() +} diff --git a/crates/cdr/src/cmx.rs b/crates/cdr/src/cmx.rs new file mode 100644 index 0000000000..4960c4b8df --- /dev/null +++ b/crates/cdr/src/cmx.rs @@ -0,0 +1,655 @@ +//! Reader for `.cmx` exchange files with 32-bit coordinates: the RIFF form `CMX1` (R53), its +//! header (R54), the color, pen, line type, dash, outline and arrowhead tables (R55 to R59) and the +//! instructions of each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills +//! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses +//! are left out with a warning. + +use crate::bytes::{Rd, u32_at}; +use crate::geometry::path_of; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Cap, Color, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; +use crate::records::{name, property_color}; +use crate::riff::{LIST, push}; +use crate::{Error, Warning}; + +const FORM: [u8; 4] = *b"CMX1"; +/// Meters per coordinate unit when the header gives no usable value: the 0.1 µm of every sample +/// file with 32-bit coordinates (R54). +const DEFAULT_UNIT: f64 = 1e-7; +/// How far past a chunk that runs short the next chunk id is looked for (R53). +const RESYNC: usize = 64; +/// The chunks the reader uses (R53 to R60). +const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"]; +/// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them. +const MAX_NAME_UNITS: usize = 4096; + +// Instruction codes (R60). +const BEGIN_PAGE: i16 = 9; +const END_PAGE: i16 = 10; +const BEGIN_LAYER: i16 = 11; +const END_LAYER: i16 = 12; +const BEGIN_GROUP: i16 = 13; +const END_GROUP: i16 = 14; +const BEGIN_TEXT: i16 = 20; +const END_TEXT: i16 = 21; +const GLYPH_RUN: i16 = 65; +const ELLIPSE: i16 = 66; +const CURVE: i16 = 67; +const RECTANGLE: i16 = 68; +const IMAGE: i16 = 69; +const ADD_CLIP: i16 = 88; +const REMOVE_CLIP: i16 = 89; +const JUMP: i16 = 111; + +/// Does `bytes` start as a CMX file: a RIFF or RIFX form of type `CMX1` (R53)? +pub(crate) fn is_cmx(bytes: &[u8]) -> bool { + matches!(bytes.get(0..4), Some(b"RIFF" | b"RIFX")) && bytes.get(8..12) == Some(FORM.as_slice()) +} + +/// A chunk outside the `LIST` chunks: its id, its body and where the body starts in the file. +struct Chunk<'a> { + id: [u8; 4], + body: &'a [u8], + start: usize, +} + +/// The tables that page instructions refer to by 1-based index (R55 to R59). +#[derive(Default)] +struct Tables { + colors: Vec>, + /// Outline widths in points. + pens: Vec>, + /// Flags, and the caps and join. + line_types: Vec>, + dashes: Vec>, + /// Line type, screen, color, arrowheads, pen and dashes. + outlines: Vec>, + arrowheads: Vec<(u16, u16)>, +} + +pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result { + if !is_cmx(bytes) { + return Err(Error::NotCmx); + } + if bytes.get(0..4) == Some(b"RIFX") { + return Err(Error::Unsupported("big-endian CMX files")); + } + let mut warn = Vec::new(); + let chunks = chunks(bytes, budget, &mut warn)?; + let cont = chunks.iter().find(|c| c.id == *b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?; + match cont.get(52) { + Some(b'4') => {} + Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")), + _ => return Err(Error::Damaged("CMX header")), + } + let meters = Rd::at(cont, 64).f64().filter(|m| *m > 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT); + let unit = meters / 0.0254 * 72.0; + let tables = Tables::read(&chunks, unit, budget, &mut warn)?; + let mut pages = Vec::new(); + for c in chunks.iter().filter(|c| c.id == *b"page") { + pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?); + } + Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) +} + +/// The chunks of the file in order, those inside `LIST` chunks in place (R53). +fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Result>, Error> { + let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len()); + if declared > b.len() { + // The file was cut short of the size its header gives. + push(warn, Warning::Damaged); + } + let end = declared.min(b.len()); + let mut out = Vec::new(); + // (position, end, depth) of the lists still to walk; a list's children go before the rest of + // the list that holds it. + let mut stack = vec![(12usize, end, 0usize)]; + while let Some((mut pos, end, depth)) = stack.pop() { + while pos.saturating_add(8) <= end { + let Some(id) = Rd::at(b, pos).fourcc() else { break }; + if !is_id(&id) { + match resync(b, pos, end) { + Some(next) => { + pos = next; + continue; + } + None => { + push(warn, Warning::Damaged); + break; + } + } + } + budget.take_chunk()?; + let size = u32_at(b, pos + 4).map_or(0, |s| s as usize); + let start = pos + 8; + let stop = start.saturating_add(size); + if stop > end { + // Stray bytes that happen to start with four letters give a length past the list: + // look for the next chunk id after them. A chunk the reader uses is kept, cut at + // the end of the list. + if !READ_IDS.contains(&id) + && let Some(next) = resync(b, pos, end) + { + pos = next; + continue; + } + push(warn, Warning::Damaged); + } + let stop = stop.min(end); + let next = stop.saturating_add(size & 1); + if id == LIST { + if depth >= budget.limits.depth { + push(warn, Warning::TooDeep); + pos = next; + continue; + } + stack.push((next, end, depth)); + stack.push((start + 4, stop, depth + 1)); + break; + } + if let Some(body) = b.get(start..stop) { + out.push(Chunk { id, body, start }); + } + pos = next; + } + } + Ok(out) +} + +/// Is `t` a chunk id: an ASCII letter, then three ASCII letters, digits or spaces (R53)? +fn is_id(t: &[u8]) -> bool { + matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' ')) +} + +/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`] +/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list +/// that ends at `end` (R53). +fn resync(b: &[u8], pos: usize, end: usize) -> Option { + let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end); + let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p))); + (pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p)) +} + +/// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs +/// past it (R55). +fn list_end(b: &[u8], mut pos: usize) -> usize { + while let Some(&tag) = b.get(pos) { + if tag == 0xff { + return pos + 1; + } + match Rd::at(b, pos + 1).u16().map(usize::from).filter(|n| *n >= 3) { + Some(n) if pos + n <= b.len() => pos += n, + _ => break, + } + } + b.len() +} + +/// The data of field `tag` in the field list `b` (R55). +fn field(b: &[u8], tag: u8) -> Option<&[u8]> { + let mut pos = 0; + while let Some(&t) = b.get(pos) { + if t == 0xff { + return None; + } + let n = usize::from(Rd::at(b, pos + 1).u16()?); + let data = b.get(pos + 3..pos.checked_add(n)?).filter(|_| n >= 3)?; + if t == tag { + return Some(data); + } + pos += n; + } + None +} + +/// The field lists of a table: a u16 count, then that many lists (R55). Each entry counts toward +/// the chunk limit. +fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result, Error> { + let count = Rd::new(d).u16().map_or(0, usize::from); + let mut out = Vec::new(); + let mut pos = 2; + for _ in 0..count { + if pos >= d.len() { + break; + } + budget.take_chunk()?; + let end = list_end(d, pos); + out.push(d.get(pos..end).unwrap_or_default()); + pos = end; + } + Ok(out) +} + +impl Tables { + /// The first chunk of each table; a table that is missing is empty. + fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec) -> Result { + let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body); + // A color record of field 10 holds a property list as a `.cdr` fill does (R56). + let record = layout::for_version(1300); + let mut t = Tables::default(); + for e in entries(first(b"rclr"), budget)? { + t.colors.push(color(e, record.as_ref(), warn)); + } + for e in entries(first(b"rpen"), budget)? { + t.pens.push(field(e, 1).and_then(|f| Rd::new(f).u32()).map(|w| f64::from(w) * unit)); + } + for e in entries(first(b"rott"), budget)? { + t.line_types.push(field(e, 1).and_then(|f| Some((*f.first()?, f.get(1).copied().unwrap_or(0))))); + } + for e in entries(first(b"rdot"), budget)? { + let mut r = Rd::new(field(e, 1).unwrap_or_default()); + let n = r.u16().map_or(0, usize::from); + let mut pattern: Vec = (0..n).map_while(|_| r.u16()).collect(); + // A pattern of zero lengths draws as a solid line, as in a `.cdr` outline (R48). + if pattern.iter().all(|x| *x == 0) { + pattern.clear(); + } + t.dashes.push(pattern); + } + for e in entries(first(b"rotl"), budget)? { + t.outlines.push(field(e, 1).and_then(|f| { + let mut r = Rd::new(f); + Some([r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?]) + })); + } + // Arrowhead pairs are plain u16 pairs after the count, not field lists (R59). + let mut r = Rd::new(first(b"rota")); + let n = r.u16().map_or(0, usize::from); + for _ in 0..n { + let Some(pair) = r.u16().zip(r.u16()) else { break }; + budget.take_chunk()?; + t.arrowheads.push(pair); + } + Ok(t) + } + + /// Entry `index` (1-based) of `list`, or `None` with a warning when there is none. + fn get(list: &[Option], index: u16, warn: &mut Vec) -> Option { + let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten(); + if found.is_none() { + push(warn, Warning::Damaged); + } + found + } + + fn color(&self, index: u16, warn: &mut Vec) -> Color { + Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3])) + } + + /// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58). + fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec) -> Option { + let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?; + let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0)); + if flags & 1 != 0 { + return None; + } + let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0); + let mut dashes = Vec::new(); + if flags & 4 != 0 { + let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i)); + match stored { + Some(d) if d.is_empty() => {} + Some(d) if budget.take_dashes(d.len()) => dashes = d.iter().map(|x| f64::from(*x)).collect(), + Some(_) => push(warn, Warning::TooDeep), + None => push(warn, Warning::Damaged), + } + } + if usize::from(arrows).checked_sub(1).and_then(|i| self.arrowheads.get(i)).is_some_and(|(s, e)| *s != 0 || *e != 0) { + push(warn, Warning::Arrowheads); + } + Some(Outline { + width, + color: self.color(color, warn), + cap: match caps_join & 0x0f { + 1 => Cap::Round, + 2 => Cap::Square, + _ => Cap::Butt, + }, + join: match caps_join >> 4 { + 1 => Join::Round, + 2 => Join::Bevel, + _ => Join::Miter, + }, + dashes, + behind_fill: flags & 8 != 0, + scale_with: flags & 16 != 0, + }) + } +} + +/// A color entry (R56): the property list of field 10 when there is one, else the model and +/// palette bytes of field 1 and the values of field 2. Colors in other models read as black with a +/// warning. +fn color(e: &[u8], record: Option<&Profile>, warn: &mut Vec) -> Option { + if let (Some(f), Some(p)) = (field(e, 10), record) { + let mut r = Rd::new(f); + let len = r.u32()? as usize; + return property_color(r.bytes(len.min(r.left()))?, p, warn); + } + let model = *field(e, 1)?.first()?; + let v = field(e, 2)?; + let byte = |i: usize| v.get(i).map(|b| f32::from(*b)); + let pct = |i: usize| byte(i).map(|x| (x / 100.0).clamp(0.0, 1.0)); + let full = |i: usize| byte(i).map(|x| x / 255.0); + Some(match model { + 2 => Color::Cmyk([pct(0)?, pct(1)?, pct(2)?, pct(3)?]), + 3 => Color::Cmyk([full(0)?, full(1)?, full(2)?, full(3)?]), + 4 => Color::Cmyk([full(0)?, full(1)?, full(2)?, 0.0]), + 5 => Color::Rgb([full(0)?, full(1)?, full(2)?]), + 9 => Color::Gray(1.0 - full(0)?), + _ => { + push(warn, Warning::UnknownColors); + Color::Rgb([0.0; 3]) + } + }) +} + +/// The objects of one layer while it is read: the layer's own list, then one list for each group +/// left open. +struct LayerRead { + name: String, + lists: Vec>, +} + +impl LayerRead { + /// The layer, its open groups closed. Lists are drawn back to front (R60), and the model holds + /// them front to back. + fn finish(mut self) -> Layer { + while self.lists.len() > 1 { + close_group(&mut self.lists); + } + let mut objects = self.lists.pop().unwrap_or_default(); + objects.reverse(); + Layer { name: self.name, kind: LayerKind::Drawing, flags: Default::default(), objects, guides: Vec::new() } + } +} + +/// Close the innermost open group of `lists` into the one that holds it. +fn close_group(lists: &mut Vec>) { + if lists.len() < 2 { + return; + } + let mut objects = lists.pop().unwrap_or_default(); + objects.reverse(); + if let Some(top) = lists.last_mut() { + top.push(Object::Group { objects, flags: Default::default() }); + } +} + +/// The reading of one page chunk. +struct PageRead<'t, 'b> { + tables: &'t Tables, + unit: f64, + budget: &'b mut Budget, + warn: &'b mut Vec, + size: Option<(f64, f64)>, + /// The page's center in the file's coordinates when the page takes its size from the + /// drawing's bounds; points are moved by it so the art lies on the page. + center: (f64, f64), + layers: Vec, + open: Option, + /// Groups nested past the depth limit that are still open; their content is left out. + skipped: usize, +} + +impl<'t, 'b> PageRead<'t, 'b> { + fn new(tables: &'t Tables, unit: f64, budget: &'b mut Budget, warn: &'b mut Vec) -> Self { + PageRead { tables, unit, budget, warn, size: None, center: (0.0, 0.0), layers: Vec::new(), open: None, skipped: 0 } + } + + /// The instructions of a page chunk: a u16 size counting the whole instruction and an i16 code, + /// or 0xFFFF, a u32 size and the code; then the code's field lists (R60). + fn read(mut self, c: &Chunk) -> Result { + let d = c.body; + let mut pos = 0usize; + while pos.saturating_add(4) <= d.len() { + self.budget.take_chunk()?; + let mut r = Rd::at(d, pos); + let (size, code, head) = match r.u16() { + Some(0xFFFF) => match (r.u32(), r.i16()) { + (Some(size), Some(code)) => (size as usize, code, 8), + _ => break, + }, + Some(size) => match r.i16() { + Some(code) => (usize::from(size), code, 4), + None => break, + }, + None => break, + }; + if size < head { + push(self.warn, Warning::Damaged); + break; + } + let end = pos.saturating_add(size); + if end > d.len() { + push(self.warn, Warning::Damaged); + } + let body = d.get(pos + head..end.min(d.len())).unwrap_or_default(); + if code == JUMP { + // Field 1 is the file offset the instructions go on from; the bytes passed over + // hold the page's images (R60). + let target = field(body, 1).and_then(|f| Rd::new(f).u32()).and_then(|t| (t as usize).checked_sub(c.start)); + pos = target.filter(|t| *t >= end && *t <= d.len()).unwrap_or(end); + if pos > end { + push(self.warn, Warning::UnsupportedObjects); + } + continue; + } + self.instruction(code, body); + pos = end; + } + if pos < d.len() { + // An instruction whose head runs past the page was not read. + push(self.warn, Warning::Damaged); + } + self.close_layer(); + // A layer that holds nothing (the special layers every sample file lists empty) is left + // out. The file lists layers back to front. + let mut layers = self.layers; + layers.retain(|l| !l.objects.is_empty()); + layers.reverse(); + Ok(Page { size: self.size, layers }) + } + + fn instruction(&mut self, code: i16, body: &[u8]) { + match code { + BEGIN_PAGE => { + // Field 4: the page's width and height (R61). + let mut r = Rd::new(field(body, 4).unwrap_or_default()); + if let (Some(w), Some(h)) = (r.u32(), r.u32()) { + let (w, h) = (f64::from(w) * self.unit, f64::from(h) * self.unit); + self.size = (w > 0.0 && h > 0.0).then_some((w, h)); + } + if self.size.is_none() { + self.size_from_bounds(field(body, 1).unwrap_or_default()); + } + } + BEGIN_LAYER => { + self.close_layer(); + // A layer without a name is left unnamed, as in a `.cdr` drawing. + let name = self.layer_name(body).unwrap_or_default(); + self.open = Some(LayerRead { name, lists: vec![Vec::new()] }); + } + END_LAYER => self.close_layer(), + BEGIN_GROUP => { + let open = self.layer().lists.len(); + if self.skipped > 0 || open > self.budget.limits.depth { + self.skipped += 1; + push(self.warn, Warning::TooDeep); + } else if self.budget.take_object() { + self.layer().lists.push(Vec::new()); + } else { + // Past the object limit the group's content joins the group that holds it. + self.skipped += 1; + push(self.warn, Warning::TooDeep); + } + } + END_GROUP => { + if self.skipped > 0 { + self.skipped -= 1; + } else { + close_group(&mut self.layer().lists); + } + } + CURVE if self.skipped == 0 => { + if let Some(shape) = self.curve(body) { + if self.budget.take_object() { + if let Some(list) = self.layer().lists.last_mut() { + list.push(Object::Shape(Box::new(shape))); + } + } else { + push(self.warn, Warning::TooDeep); + } + } + } + BEGIN_TEXT | GLYPH_RUN | ELLIPSE | RECTANGLE | IMAGE | ADD_CLIP => push(self.warn, Warning::UnsupportedObjects), + // These and the other codes (text styles and characters, color contexts) draw nothing + // on their own. + END_PAGE | END_TEXT | REMOVE_CLIP => {} + _ => {} + } + } + + /// A page without a size of its own is sized to the drawing's bounds in field 1 (R61): a u16 + /// page number, a u32 of flags, then the left, top, right and bottom edges as i32 in + /// coordinate units. The page is centered on those bounds. + fn size_from_bounds(&mut self, f: &[u8]) { + let mut r = Rd::new(f); + if r.u16().is_none() || r.u32().is_none() { + return; + } + let (Some(l), Some(t), Some(rt), Some(b)) = (r.i32(), r.i32(), r.i32(), r.i32()) else { + return; + }; + let (l, t, rt, b) = (f64::from(l) * self.unit, f64::from(t) * self.unit, f64::from(rt) * self.unit, f64::from(b) * self.unit); + let (w, h) = ((rt - l).abs(), (t - b).abs()); + if w > 0.0 && h > 0.0 { + self.size = Some((w, h)); + self.center = ((l + rt) / 2.0, (t + b) / 2.0); + } + } + + /// The open layer, or a new unnamed one when objects come before any layer begins. + fn layer(&mut self) -> &mut LayerRead { + self.open.get_or_insert_with(|| LayerRead { name: String::new(), lists: vec![Vec::new()] }) + } + + fn close_layer(&mut self) { + self.skipped = 0; + if let Some(l) = self.open.take() { + self.layers.push(l.finish()); + } + } + + /// A layer's name: field 4 as a u32 count and UTF-16 units, else field 1 from byte 12 as a + /// u16 count and 8-bit characters (R62). + fn layer_name(&mut self, body: &[u8]) -> Option { + // A field 4 that can't be read leaves the name to field 1. + let wide = field(body, 4).and_then(|f| { + let mut r = Rd::new(f); + let n = (r.u32()? as usize).min(MAX_NAME_UNITS).min(r.left() / 2); + Some((r.bytes(n * 2)?, layout::for_version(1200)?)) + }); + if let Some((units, l)) = wide { + let s = name(units, &l, self.warn); + if !s.trim().is_empty() { + return Some(s); + } + } + let mut r = Rd::at(field(body, 1)?, 12); + let n = usize::from(r.u16()?).min(r.left()); + let s = name(r.bytes(n)?, &layout::for_version(1100)?, self.warn); + (!s.trim().is_empty()).then_some(s) + } + + /// A curve (R62): field 1 its rendering attributes, field 2 a u16 point count, the points (i32 + /// x and y) and one type byte for each. Points are from the page's center, y up. + fn curve(&mut self, body: &[u8]) -> Option { + let mut r = Rd::new(field(body, 2).unwrap_or_default()); + let Some(count) = r.u16().map(usize::from) else { + // A curve without its points is lost. + push(self.warn, Warning::Damaged); + return None; + }; + // `stored` points are read, so the type bytes are found after all of them, and the first + // `n`, those that have a type byte, are kept. When the field holds every point, a short + // field has lost type bytes. When it holds whole points and their types for fewer points, + // the count is too large. Otherwise the field lost points, and its type bytes can't be + // found: the curve is lost. + let left = r.left(); + let (stored, n) = match count.checked_mul(8).filter(|c| *c <= left) { + Some(c) => (count, count.min(left - c)), + None if left.is_multiple_of(9) => (left / 9, left / 9), + None => { + push(self.warn, Warning::Damaged); + return None; + } + }; + if n < count { + push(self.warn, Warning::Damaged); + } + if !self.budget.take_coordinates(stored) { + push(self.warn, Warning::TooDeep); + return None; + } + let mut points = Vec::with_capacity(stored); + for _ in 0..stored { + let (x, y) = (f64::from(r.i32()?) * self.unit, f64::from(r.i32()?) * self.unit); + points.push(Pt { x: x - self.center.0, y: y - self.center.1 }); + } + points.truncate(n); + let path = path_of(&points, r.bytes(n)?); + if path.subpaths.is_empty() { + return None; + } + let (fill, outline) = self.attributes(field(body, 1).unwrap_or_default()); + Some(Shape::new(Geometry::Path(path), Matrix::IDENTITY, fill, outline)) + } + + /// Rendering attributes (R63): a mask (1 fill, 2 outline, 4 lens), then a field list for the + /// fill and one for the outline when the mask names them. + fn attributes(&mut self, a: &[u8]) -> (Option, Option) { + let Some(&mask) = a.first() else { return (None, None) }; + let mut pos = 1; + let mut fill = None; + if mask & 1 != 0 { + let end = list_end(a, pos); + let list = a.get(pos..end).unwrap_or_default(); + pos = end; + // Field 1: the fill type (u16), then its own field list; type 1, uniform, names its + // color in field 1. + let v = field(list, 1).unwrap_or_default(); + match Rd::new(v).u16() { + Some(0) | None => {} + Some(1) => { + let index = field(v.get(2..).unwrap_or_default(), 1).and_then(|c| Rd::new(c).u16()); + fill = Some(match index { + Some(i) => self.tables.color(i, self.warn), + None => { + push(self.warn, Warning::Damaged); + Color::Rgb([0.0; 3]) + } + }); + } + Some(_) => push(self.warn, Warning::UnsupportedFills), + } + } + let mut outline = None; + if mask & 2 != 0 { + let list = a.get(pos..list_end(a, pos)).unwrap_or_default(); + match field(list, 1).and_then(|f| Rd::new(f).u16()) { + Some(i) => outline = self.tables.outline(i, self.budget, self.warn), + None => push(self.warn, Warning::Damaged), + } + } + if mask & 4 != 0 { + push(self.warn, Warning::Lenses); + } + // A canvas (8) or a container (16) is not read. + if mask & (8 | 16) != 0 { + push(self.warn, Warning::UnsupportedObjects); + } + (fill, outline) + } +} diff --git a/crates/cdr/src/geometry.rs b/crates/cdr/src/geometry.rs new file mode 100644 index 0000000000..61b776f23a --- /dev/null +++ b/crates/cdr/src/geometry.rs @@ -0,0 +1,455 @@ +//! The coordinates argument (30) of each object type read as geometry: curves (R16), rectangles +//! (R15), ellipses and arcs (R17) and polygons (R18). + +use std::f64::consts::PI; + +use crate::Warning; +use crate::bytes::Rd; +use crate::layout::Profile; +use crate::limits::Budget; +use crate::model::{Geometry, Path, Pt, Segment, SubPath}; +use crate::records::{angle, coord}; +use crate::riff::push; + +/// The most sides a polygon record may give (VectorCraft's own bound). +const MAX_POLYGON_SIDES: u32 = 1000; +/// The base curve of a polygon lies on a circle of 1000 mm (R18), in points. +const POLYGON_UNIT_RADIUS: f64 = 1000.0 / 25.4 * 72.0; + +/// What a point type byte asks for (R16): bits 7 and 6. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Op { + Move, + Line, + Curve, + Control, +} + +fn op(t: u8) -> Op { + match t >> 6 { + 0 => Op::Move, + 1 => Op::Line, + 2 => Op::Curve, + _ => Op::Control, + } +} + +/// Bit 3 closes the subpath (R16). +const CLOSES: u8 = 0x08; + +/// A point list (R16): the count, the points, then one type byte each. The count is a u32 from +/// version 6 and a u16 followed by another u16 before it (R39). It is held to what the bytes hold; +/// `None` when the points are past the budget. +pub(crate) fn point_list(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + let count = if p.short { + let count = usize::from(r.u16()?); + r.skip(2)?; + count + } else { + r.u32()? as usize + }; + points(b, r, count, p, budget, warn) +} + +/// A path record (object type 0x25, R30): 4 bytes, two u16 counts whose sum is the point count, 16 +/// bytes, then the points and their type bytes as in a point list. +pub(crate) fn path_record(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + r.skip(4)?; + let count = usize::from(r.u16()?) + usize::from(r.u16()?); + r.skip(16)?; + points(b, r, count, p, budget, warn) +} + +/// `count` points from `r` over `b`, then their type bytes. A list cut short is read two ways: as +/// all `count` points with the type bytes after them, and as the points and type bytes the bytes +/// hold split evenly. The reading that keeps more points with a type byte wins, the first on a tie. +fn points(b: &[u8], mut r: Rd, count: usize, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let each = 2 * p.word(); + let left = r.left(); + let split = (left / (each + 1)).min(count); + let whole = count.checked_mul(each).filter(|len| *len <= left).map(|len| (left - len).min(count)); + let stored = match whole { + Some(typed) if typed >= split => count, + _ => split, + }; + let types = b.get(r.pos() + stored * each..)?; + let n = stored.min(types.len()); + if count > n { + push(warn, Warning::Damaged); + } + if !budget.take_coordinates(n) { + push(warn, Warning::TooDeep); + return None; + } + let mut points = Vec::with_capacity(n); + for _ in 0..n { + points.push(Pt { x: coord(&mut r, p)?, y: coord(&mut r, p)? }); + } + Some(path_of(&points, types)) +} + +/// The subpaths that points and their type bytes draw. +pub(crate) fn path_of(points: &[Pt], types: &[u8]) -> Path { + let mut subpaths = Vec::new(); + let mut cur: Option = None; + // The last two control points: a curve end uses only those. + let mut controls: Vec = Vec::with_capacity(2); + for (&pt, &t) in points.iter().zip(types) { + let o = op(t); + if o == Op::Control { + if controls.len() == 2 { + controls.remove(0); + } + controls.push(pt); + continue; + } + if o == Op::Move || cur.is_none() { + subpaths.extend(cur.take()); + cur = Some(SubPath { start: pt, segments: Vec::new(), closed: t & CLOSES != 0 && o == Op::Move }); + controls.clear(); + if o == Op::Move { + continue; + } + } + let Some(sp) = cur.as_mut() else { continue }; + let seg = match (o, controls.as_slice()) { + (Op::Curve, [c1, c2]) => Segment::Cubic(*c1, *c2, pt), + _ => Segment::Line(pt), + }; + controls.clear(); + sp.segments.push(seg); + if t & CLOSES != 0 { + sp.closed = true; + } + } + subpaths.extend(cur); + // A closed subpath with no segments, or an open one with none, draws nothing. + subpaths.retain(|s| !s.segments.is_empty()); + Path { subpaths } +} + +/// A rectangle record (R15): width, height, then one corner radius for every corner, four from +/// version 9. +pub(crate) fn rect(b: &[u8], p: &Profile) -> Option { + if p.f64_rect { + return rect_f64(b, p); + } + let mut r = Rd::new(b); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let first = coord(&mut r, p)?.abs(); + let mut radii = [first; 4]; + if p.four_radii { + for slot in radii.iter_mut().skip(1) { + *slot = coord(&mut r, p)?.abs(); + } + } + Some(Geometry::Rect { w, h, radii }) +} + +/// A rectangle record from version 15 (R29): width and height as f64 coordinate units, two scale +/// factors that repeat the transform's (not applied), the scale-with flag and 7 bytes, then the +/// four radii as f64 16 bytes apart. With the flag clear each radius is a share of half the shorter +/// side; with it set the radius is in inches. A corner is held to half the shorter side, and +/// sizes to the range of the 32-bit coordinates of earlier versions. +fn rect_f64(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let size = |v: f64| (v.abs() <= f64::from(i32::MAX)).then(|| v * p.unit()); + let (w, h) = (size(r.f64()?)?, size(r.f64()?)?); + r.skip(8 + 8)?; + let inches = r.u8()? != 0; + r.skip(7)?; + let short = w.abs().min(h.abs()); + let mut radii = [0.0; 4]; + for (k, slot) in radii.iter_mut().enumerate() { + if k > 0 { + r.skip(16)?; + } + let v = r.f64()?.abs(); + let radius = if inches { v * 72.0 } else { v * short / 2.0 }; + *slot = radius.min(short / 2.0); + } + Some(Geometry::Rect { w, h, radii }) +} + +/// An ellipse record (R17): the box's width and height, the start and end angles and whether +/// the arc closes through the centre. Equal angles make a whole ellipse. +pub(crate) fn ellipse(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let (a1, a2) = (angle(&mut r, p)?, angle(&mut r, p)?); + let pie = if p.short { r.u16()? != 0 } else { r.u32()? != 0 }; + let sweep = (a2 - a1).rem_euclid(360.0); + if sweep.abs() < 1e-9 { + return Some(Geometry::Ellipse { w, h }); + } + Some(Geometry::Path(arc(w, h, a1, sweep, pie))) +} + +/// The arc of the ellipse in the box from the origin to (`w`, `h`), from `start` degrees through +/// `sweep` degrees, in the ellipse's own axes; a pie runs from the centre and closes there. The +/// radii are half the size, and a negative width or height points its axis the other way (R17), so +/// with a negative height 0 to 180 degrees is the half below the centre. +fn arc(w: f64, h: f64, start: f64, sweep: f64, pie: bool) -> Path { + let (cx, cy, rx, ry) = (w / 2.0, h / 2.0, w / 2.0, h / 2.0); + let at = |t: f64| Pt { x: cx + rx * t.cos(), y: cy + ry * t.sin() }; + let tangent = |t: f64| Pt { x: -rx * t.sin(), y: ry * t.cos() }; + let pieces = (sweep / 90.0).ceil().max(1.0) as usize; + let step = sweep.to_radians() / pieces as f64; + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let t0 = start.to_radians(); + let mut segments = Vec::with_capacity(pieces + 2); + if pie { + segments.push(Segment::Line(at(t0))); + } + for i in 0..pieces { + let (a, b) = (t0 + step * i as f64, t0 + step * (i + 1) as f64); + let (p0, p1, d0, d1) = (at(a), at(b), tangent(a), tangent(b)); + segments.push(Segment::Cubic(Pt { x: p0.x + k * d0.x, y: p0.y + k * d0.y }, Pt { x: p1.x - k * d1.x, y: p1.y - k * d1.y }, p1)); + } + let start = if pie { Pt { x: cx, y: cy } } else { at(t0) }; + Path { subpaths: vec![SubPath { start, segments, closed: pie }] } +} + +/// A polygon (R18): its base curve, one side of the outline on a circle of 1000 mm with its top +/// vertex first, copied once per side and turned clockwise each time by the vertices the side +/// spans, then scaled by (`rx`, `ry`) and moved to the centre the polygon argument (11000) gives. +/// A star whose sides skip vertices draws as one outline, or as several when the side count and +/// the step share a factor. +pub(crate) fn polygon(base: &Path, b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + if !p.tagged { + r.skip(4)?; + } + let sides = r.u32()?; + // The next point: the first field, or the second when the first is 0 or 1. + let (first, second) = (r.u32()?, r.u32()?); + let next = if first > 1 { first } else { second }; + if p.tagged { + r.skip(4)?; + } + let (rx, ry) = (r.f64()?, r.f64()?); + let (cx, cy) = (coord(&mut r, p)?, coord(&mut r, p)?); + let side = base.subpaths.first()?; + if !(1..=MAX_POLYGON_SIDES).contains(&sides) { + push(warn, Warning::Damaged); + return None; + } + if !budget.take_coordinates(side.segments.len().saturating_mul(3).saturating_mul(sides as usize)) { + push(warn, Warning::TooDeep); + return None; + } + // The base curve's own unit radius, measured from its first point, keeps the scale right + // whatever unit the file's coordinates are in. + let unit = side.start.x.hypot(side.start.y); + let unit = if unit > 0.0 { unit } else { POLYGON_UNIT_RADIUS }; + let place = |q: Pt, turn: f64| { + let (s, c) = turn.sin_cos(); + let (x, y) = (q.x * c - q.y * s, q.x * s + q.y * c); + Pt { x: x / unit * POLYGON_UNIT_RADIUS * rx + cx, y: y / unit * POLYGON_UNIT_RADIUS * ry + cy } + }; + let step = side_step(side, sides, next); + let outlines = gcd(sides, step); + let each = sides / outlines; + let angle = |k: u32| -2.0 * PI * f64::from(k % sides) / f64::from(sides); + let mut subpaths = Vec::with_capacity(outlines as usize); + for o in 0..outlines { + let mut segments = Vec::with_capacity(side.segments.len() * each as usize); + for j in 0..each { + let turn = angle(o + j * step); + segments.extend(side.segments.iter().map(|s| match *s { + Segment::Line(a) => Segment::Line(place(a, turn)), + Segment::Cubic(a, b, c) => Segment::Cubic(place(a, turn), place(b, turn), place(c, turn)), + })); + } + subpaths.push(SubPath { start: place(side.start, angle(o)), segments, closed: true }); + } + Some(Geometry::Path(Path { subpaths })) +} + +/// How many vertices the base side moves on from its first point (R18): the vertex its last +/// point lies at, clockwise; else the next-point field when it names one; else 1. +fn side_step(side: &SubPath, sides: u32, next: u32) -> u32 { + let field = if (1..sides).contains(&next) { next } else { 1 }; + let Some(end) = side.segments.last().map(|s| match *s { + Segment::Line(e) | Segment::Cubic(_, _, e) => e, + }) else { + return field; + }; + let (r0, r1) = (side.start.x.hypot(side.start.y), end.x.hypot(end.y)); + if !(r0 > 0.0 && (r1 - r0).abs() <= r0 * 1e-3) { + return field; + } + let turned = (side.start.y.atan2(side.start.x) - end.y.atan2(end.x)) / (2.0 * PI / f64::from(sides)); + let k = turned.round(); + if !k.is_finite() || (turned - k).abs() > 1e-3 { + return field; + } + match k.rem_euclid(f64::from(sides)) as u32 { + 0 => field, + k => k, + } +} + +fn gcd(a: u32, b: u32) -> u32 { + let (mut a, mut b) = (a, b); + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pt(x: f64, y: f64) -> Pt { + Pt { x, y } + } + + #[test] + fn type_bytes_make_moves_lines_curves_and_closes() { + let points = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0), pt(20.0, 20.0), pt(30.0, 20.0)]; + // move (closed), line, control, control, curve end closing; move, line. + let types = [0x08, 0x40, 0xC0, 0xC0, 0x88, 0x00, 0x40]; + let path = path_of(&points, &types); + assert_eq!(path.subpaths.len(), 2); + let first = &path.subpaths[0]; + assert!(first.closed); + assert_eq!(first.segments, vec![Segment::Line(pt(10.0, 0.0)), Segment::Cubic(pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0))]); + assert!(!path.subpaths[1].closed); + } + + #[test] + fn a_point_list_short_of_type_bytes_reads_them_after_all_its_points() { + let p = crate::layout::for_version(1300).unwrap_or_else(|| panic!("profile")); + // Three points, (0, 0), (1 inch, 0) and (0, 0), and type bytes for the first two only. + let mut b = 3u32.to_le_bytes().to_vec(); + for v in [0i32, 0, 254_000, 0, 0, 0] { + b.extend(v.to_le_bytes()); + } + b.extend([0x00, 0x40]); + let mut warn = vec![]; + let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path")); + assert_eq!(path.subpaths.len(), 1); + assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(72.0, 0.0))]); + assert_eq!(warn, vec![Warning::Damaged]); + // A count past the points the bytes hold keeps the points that have a type byte. + // Eight points and their eight type bytes take the bytes of nine points. + let mut b = 9u32.to_le_bytes().to_vec(); + for i in 0..8 { + b.extend((i * 254_000i32).to_le_bytes()); + b.extend(0i32.to_le_bytes()); + } + b.extend([0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40]); + let mut warn = vec![]; + let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path")); + assert_eq!(path.subpaths[0].segments.len(), 7); + assert!(matches!(path.subpaths[0].segments[6], Segment::Line(end) if (end.x - 504.0).abs() < 1e-9 && end.y == 0.0)); + assert_eq!(warn, vec![Warning::Damaged]); + } + + #[test] + fn a_run_of_control_points_keeps_the_last_two() { + let points: Vec = (0..7).map(|i| pt(f64::from(i), 0.0)).collect(); + let path = path_of(&points, &[0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80]); + assert_eq!(path.subpaths[0].segments, vec![Segment::Cubic(pt(4.0, 0.0), pt(5.0, 0.0), pt(6.0, 0.0))]); + } + + #[test] + fn a_curve_end_without_two_controls_is_a_line() { + let path = path_of(&[pt(0.0, 0.0), pt(1.0, 1.0)], &[0x00, 0x80]); + assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(1.0, 1.0))]); + } + + #[test] + fn a_quarter_arc_ends_on_the_ellipse() { + let p = arc(20.0, 10.0, 0.0, 90.0, false); + let sp = &p.subpaths[0]; + assert_eq!(sp.start, pt(20.0, 5.0)); + let Some(Segment::Cubic(_, _, end)) = sp.segments.last() else { panic!("no curve") }; + assert!((end.x - 10.0).abs() < 1e-9 && (end.y - 10.0).abs() < 1e-9); + let pie = arc(20.0, 10.0, 0.0, 180.0, true); + assert!(pie.subpaths[0].closed && pie.subpaths[0].start == pt(10.0, 5.0)); + } + + #[test] + fn a_negative_height_turns_the_arc_below_the_centre() { + let p = arc(20.0, -10.0, 0.0, 180.0, false); + let sp = &p.subpaths[0]; + assert_eq!(sp.start, pt(20.0, -5.0)); + let Some(Segment::Cubic(_, _, mid)) = sp.segments.first() else { panic!("no curve") }; + assert!((mid.x - 10.0).abs() < 1e-9 && (mid.y + 10.0).abs() < 1e-9, "{mid:?}"); + } + + /// A version 13 polygon argument: `sides`, the two next-point fields, then rx = ry = 1 at the + /// origin. + fn polygon_arg(sides: u32, first: u32, second: u32) -> Vec { + let mut b = Vec::new(); + for v in [sides, first, second, 0] { + b.extend(v.to_le_bytes()); + } + b.extend(1.0f64.to_le_bytes()); + b.extend(1.0f64.to_le_bytes()); + b.extend([0; 8]); + b + } + + /// Vertex `k` of `sides`, counted clockwise from the top, on the base circle. + fn vertex(k: u32, sides: u32) -> Pt { + let a = PI / 2.0 - 2.0 * PI * f64::from(k) / f64::from(sides); + pt(POLYGON_UNIT_RADIUS * a.cos(), POLYGON_UNIT_RADIUS * a.sin()) + } + + fn ends(sp: &SubPath) -> Vec { + sp.segments + .iter() + .map(|s| match *s { + Segment::Line(e) | Segment::Cubic(_, _, e) => e, + }) + .collect() + } + + fn close(a: &[Pt], b: &[Pt]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.x - q.x).abs() < 1e-6 && (p.y - q.y).abs() < 1e-6) + } + + fn star(sides: u32, step: u32, first: u32, second: u32) -> Path { + let p = crate::layout::for_version(1300).unwrap(); + let base = Path { subpaths: vec![SubPath { start: vertex(0, sides), segments: vec![Segment::Line(vertex(step, sides))], closed: false }] }; + let mut budget = Budget::new(crate::Limits::default()); + let Some(Geometry::Path(path)) = polygon(&base, &polygon_arg(sides, first, second), &p, &mut budget, &mut vec![]) else { + panic!("no polygon") + }; + path + } + + #[test] + fn a_star_whose_sides_skip_a_vertex_chains_its_points() { + // {5/2}: each side runs two vertices on, so the outline visits 2, 4, 1, 3 and 0. + let path = star(5, 2, 2, 0); + assert_eq!(path.subpaths.len(), 1); + let want: Vec = [2, 4, 1, 3, 0].iter().map(|&k| vertex(k, 5)).collect(); + assert!(close(&ends(&path.subpaths[0]), &want), "{:?}", ends(&path.subpaths[0])); + // The base side alone tells the step when the field doesn't. + assert!(close(&ends(&star(5, 2, 0, 0).subpaths[0]), &want)); + } + + #[test] + fn a_star_sharing_a_factor_with_its_sides_draws_one_outline_for_each() { + // {6/2}: two triangles, 0-2-4 and 1-3-5. + let path = star(6, 2, 0, 2); + assert_eq!(path.subpaths.len(), 2); + assert!(close(&ends(&path.subpaths[0]), &[vertex(2, 6), vertex(4, 6), vertex(0, 6)])); + assert!(close(&[path.subpaths[1].start], &[vertex(1, 6)])); + assert!(close(&ends(&path.subpaths[1]), &[vertex(3, 6), vertex(5, 6), vertex(1, 6)])); + } + + #[test] + fn a_plain_polygon_turns_one_vertex_for_each_side() { + let path = star(4, 1, 0, 1); + assert_eq!(path.subpaths.len(), 1); + assert!(close(&ends(&path.subpaths[0]), &[1, 2, 3, 0].map(|k| vertex(k, 4)))); + } +} diff --git a/crates/cdr/src/inline.rs b/crates/cdr/src/inline.rs new file mode 100644 index 0000000000..3d5214f136 --- /dev/null +++ b/crates/cdr/src/inline.rs @@ -0,0 +1,230 @@ +//! What a version 3 object holds as arguments where later versions name records: its transforms +//! (argument 100, R33), its fill (argument 20, R34) and its outline (argument 10, R35). + +use crate::bytes::Rd; +use crate::layout::Profile; +use crate::model::{Cap, Color, Join, Matrix, Outline}; +use crate::records::{self, angle, coord}; +use crate::riff::push; +use crate::{Limits, Warning}; + +/// Transform entry types (R33): a matrix, and an envelope. +const MATRIX: u16 = 0x8c; +const ENVELOPE: u16 = 0x14; +/// The bytes of one transform entry (R33). +const ENTRY: usize = 10; +/// The bytes an outline keeps for its dashes, one byte each (R35). +const DASH_AREA: usize = 10; + +/// The transforms of one object or group. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Placement { + /// The matrices composed in file order, in points. + pub(crate) matrix: Matrix, + /// An envelope bends the shape. The reader doesn't apply envelopes. + pub(crate) envelope: bool, +} + +/// The transforms argument (R33): a u16, the entry count, then 10-byte entries of a type and, at +/// byte 6, where the entry's data starts in the argument. The count is held to the entries the +/// argument holds and to the arguments a record may have. Entries of other types are passed over. +pub(crate) fn transforms(b: &[u8], p: &Profile, limits: &Limits, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + r.skip(2)?; + let stored = usize::from(r.u16()?); + let count = stored.min(r.left() / ENTRY).min(limits.arguments); + if count < stored { + push(warn, Warning::Damaged); + } + let mut out = Placement { matrix: Matrix::IDENTITY, envelope: false }; + for _ in 0..count { + let mut e = Rd::new(r.bytes(ENTRY)?); + let kind = e.u16()?; + e.skip(4)?; + let at = usize::from(e.u16()?); + match kind { + MATRIX => out.matrix = records::fixed_matrix(&mut Rd::at(b, at), p.unit())?.after(&out.matrix), + ENVELOPE => out.envelope = true, + _ => {} + } + } + Some(out) +} + +/// The fill argument (R34): a type byte, 0 for none and 1 for a uniform fill with its color. Fills +/// of other types read as none with a warning. The outer `None` is an argument that can't be read. +pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + match r.u8()? { + 0 => Some(None), + 1 => Some(Some(records::color(&mut r, p, warn)?)), + _ => { + push(warn, Warning::UnsupportedFills); + Some(None) + } + } +} + +/// The outline argument (R35): a flags byte whose bit 0 is set when the object is outlined, the +/// width, the stretch, the nib angle, the color, 7 bytes, the dash count and 10 bytes that hold the +/// dashes, the join and the caps (u16 each), then the two arrowhead ids. An argument that ends +/// after its color gives a solid line with butt caps and miter joins. The outer `None` is an +/// argument that can't be read. +pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + if r.u8()? & 1 == 0 { + return Some(None); + } + let width = coord(&mut r, p)?.abs(); + let _stretch = r.u16()?; + let _nib = angle(&mut r, p)?; + let color = records::color(&mut r, p, warn)?; + let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false }; + let Some(stored) = r.skip(7).and_then(|()| r.u8()).map(usize::from) else { return Some(Some(out)) }; + let Some(area) = r.bytes(DASH_AREA) else { return Some(Some(out)) }; + if stored > DASH_AREA { + push(warn, Warning::Damaged); + } + let dashes: Vec = area.iter().take(stored).map(|d| f64::from(*d)).collect(); + if dashes.iter().any(|d| *d > 0.0) { + out.dashes = dashes; + } + out.join = match r.u16() { + Some(1) => Join::Round, + Some(2) => Join::Bevel, + _ => Join::Miter, + }; + out.cap = match r.u16() { + Some(1) => Cap::Round, + Some(2) => Cap::Square, + _ => Cap::Butt, + }; + if matches!((r.u32(), r.u32()), (Some(s), Some(e)) if s != 0 || e != 0) { + push(warn, Warning::Arrowheads); + } + Some(Some(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p3() -> Profile { + crate::layout::for_version(300).unwrap() + } + + /// A transforms argument of `entries` (type, data offset), then `data` from byte 4 + 10 for + /// each entry. + fn arg(count: u16, entries: &[(u16, u16)], data: &[i32]) -> Vec { + let mut b = vec![0, 0]; + b.extend(count.to_le_bytes()); + for (kind, at) in entries { + b.extend(kind.to_le_bytes()); + b.extend([0; 4]); + b.extend(at.to_le_bytes()); + b.extend([0; 2]); + } + b.extend(data.iter().flat_map(|v| v.to_le_bytes())); + b + } + + #[test] + fn matrices_compose_in_file_order_and_other_entries_are_passed_over() { + // Scale by 2, then move 1 inch right: entry types 0x8c, an unknown one and 0x8c. + let scale = [131072, 0, 0, 0, 131072, 0]; + let shift = [65536, 0, 1000, 0, 65536, 0]; + let b = arg(3, &[(MATRIX, 34), (0x99, 0), (MATRIX, 58)], &[scale, shift].concat()); + let mut w = vec![]; + let t = transforms(&b, &p3(), &Limits::default(), &mut w).unwrap(); + assert_eq!((t.matrix, t.envelope), (Matrix([2.0, 0.0, 0.0, 2.0, 72.0, 0.0]), false)); + assert!(w.is_empty()); + let b = arg(2, &[(MATRIX, 24), (ENVELOPE, 0)], &scale); + assert!(transforms(&b, &p3(), &Limits::default(), &mut vec![]).unwrap().envelope); + } + + #[test] + fn hostile_transform_arguments_do_not_read_past_their_bytes() { + let scale = [131072, 0, 0, 0, 131072, 0]; + // A count of 65,535 over one entry reads that entry, with the damage warning. + let b = arg(u16::MAX, &[(MATRIX, 14)], &scale); + let mut w = vec![]; + assert_eq!(transforms(&b, &p3(), &Limits::default(), &mut w).unwrap().matrix.0[0], 2.0); + assert_eq!(w, vec![Warning::Damaged]); + // A data offset past the argument, and one that leaves less than a matrix. + for at in [5000, 14 + 4] { + assert!(transforms(&arg(1, &[(MATRIX, at)], &scale), &p3(), &Limits::default(), &mut vec![]).is_none(), "{at}"); + } + // More entries than a record may have arguments. + let many: Vec<(u16, u16)> = vec![(0x99, 0); 100]; + let limits = Limits { arguments: 8, ..Limits::default() }; + let mut w = vec![]; + assert!(transforms(&arg(100, &many, &[]), &p3(), &limits, &mut w).is_some()); + assert_eq!(w, vec![Warning::Damaged]); + for len in 0..4 { + assert!(transforms(&b[..len], &p3(), &Limits::default(), &mut vec![]).is_none()); + } + } + + /// An outline argument: flags, width in 1/1000 inch, black, `dashes`, join, caps, arrowheads. + fn outline_arg(flags: u8, count: u8, dashes: &[u8], join: u16, cap: u16, heads: [u32; 2]) -> Vec { + let mut b = vec![flags]; + b.extend(28i16.to_le_bytes()); + b.extend([100, 0, 0, 0]); + b.extend([1, 0, 0, 0, 100]); + b.extend([0; 7]); + b.push(count); + let mut area = dashes.to_vec(); + area.resize(DASH_AREA, 0); + b.extend(area); + b.extend(join.to_le_bytes()); + b.extend(cap.to_le_bytes()); + b.extend(heads.iter().flat_map(|h| h.to_le_bytes())); + b + } + + #[test] + fn an_outline_reads_its_width_color_dashes_join_and_caps() { + let mut w = vec![]; + let o = outline(&outline_arg(1, 2, &[3, 1], 1, 2, [0, 0]), &p3(), &mut w).unwrap().unwrap(); + assert!((o.width - 2.016).abs() < 1e-9, "{}", o.width); + assert_eq!((o.color, o.join, o.cap, o.dashes), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Join::Round, Cap::Square, vec![3.0, 1.0])); + assert!(w.is_empty()); + // Bit 0 clear: no outline, whatever follows. + assert_eq!(outline(&outline_arg(0, 2, &[3, 1], 1, 2, [7, 0]), &p3(), &mut w), Some(None)); + assert_eq!(outline(&[0], &p3(), &mut w), Some(None)); + assert!(w.is_empty()); + outline(&outline_arg(1, 0, &[], 0, 0, [0, 9]), &p3(), &mut w).unwrap().unwrap(); + assert_eq!(w, vec![Warning::Arrowheads]); + } + + #[test] + fn a_dash_count_past_the_dash_bytes_is_held_to_them() { + let mut w = vec![]; + let o = outline(&outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]), &p3(), &mut w).unwrap().unwrap(); + assert_eq!(o.dashes.len(), DASH_AREA); + assert_eq!(w, vec![Warning::Damaged]); + // An argument that ends inside the dashes keeps a solid line; one cut before the color is + // unreadable. + let full = outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]); + assert_eq!(outline(&full[..25], &p3(), &mut vec![]).unwrap().unwrap().dashes, Vec::::new()); + assert_eq!(outline(&full[..12], &p3(), &mut vec![]).unwrap().unwrap().cap, Cap::Butt); + for len in 0..12 { + assert!(outline(&full[..len], &p3(), &mut vec![]).is_none(), "{len}"); + } + } + + #[test] + fn fills_read_none_uniform_and_other_types() { + let mut w = vec![]; + assert_eq!(fill(&[0], &p3(), &mut w), Some(None)); + assert_eq!(fill(&[1, 1, 100, 0, 0, 0], &p3(), &mut w), Some(Some(Color::Cmyk([1.0, 0.0, 0.0, 0.0])))); + assert!(w.is_empty()); + for kind in [2, 4, 6, 7, 10] { + let mut w = vec![]; + assert_eq!(fill(&[kind, 0, 0], &p3(), &mut w), Some(None)); + assert_eq!(w, vec![Warning::UnsupportedFills], "{kind}"); + } + assert_eq!(fill(&[], &p3(), &mut w), None); + assert_eq!(fill(&[1, 1, 100], &p3(), &mut w), None); + } +} diff --git a/crates/cdr/src/layout.rs b/crates/cdr/src/layout.rs new file mode 100644 index 0000000000..46c28496cf --- /dev/null +++ b/crates/cdr/src/layout.rs @@ -0,0 +1,181 @@ +//! Where the fields of each record lie, by version: one table, resolved once per file. Each field +//! names the `PROVENANCE.md` row it rests on. + +/// The layouts of one range of versions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Profile { + /// Coordinates are i16 in 1/1000 inch, record headers, counts and angles 16-bit (R5, R6, R7). + pub(crate) short: bool, + /// Bytes before the page size in `mcfg` (R10). + pub(crate) mcfg_skip: usize, + /// Bytes before a `trfd` entry's type (R8). + pub(crate) trfd_head: usize, + /// Bytes between a matrix entry's type and its six numbers (R8). + pub(crate) matrix_skip: usize, + /// Fill and outline records start with tagged records (R11, R12). + pub(crate) tagged: bool, + /// Outline: bytes after the join, after the stretch, after the nib angle and after the color + /// (R12). + pub(crate) outl_after_join: usize, + pub(crate) outl_after_stretch: usize, + pub(crate) outl_after_angle: usize, + pub(crate) outl_after_color: usize, + /// Where the start marker id lies after the first dash (R13); `None` where no source says. + pub(crate) marker_after_dash: Option, + /// Rectangles carry four corner radii, not one (R15). + pub(crate) four_radii: bool, + /// Rectangles are f64 sizes with radii as shares of half the shorter side (R29). + pub(crate) f64_rect: bool, + /// The master page flags its guides and desktop layers the way of versions 7 to 13 (R19). + pub(crate) old_master_flags: bool, + /// Object type 0x25 is a path (R30). + pub(crate) paths: bool, + /// Names are UTF-16LE, not Windows-1252 (R9). + pub(crate) utf16_names: bool, + /// An object holds its transform, fill and outline as arguments; there are no `trfd`, `fill` + /// or `outl` records (R33, R34, R35). + pub(crate) inline_styles: bool, + /// Object types count from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4 (R32). + pub(crate) types_from_zero: bool, + /// How a color is laid out (R14, R36). + pub(crate) color: ColorLayout, + /// A matrix is six i32 with its factors in 16.16 fixed point, not six f64 (R37). + pub(crate) fixed_matrix: bool, + /// `mcfg` holds 2 bytes and the page's two corners, not its width and height (R38). + pub(crate) mcfg_corners: bool, +} + +/// The layouts of a color. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ColorLayout { + /// A model byte and four value bytes (R36). + Bytes5, + /// A model u16, four u16 values and 2 bytes (R36). + Words12, + /// A model u16, a palette u16, 4 bytes and four value bytes (R14). + Record12, +} + +const fn profile(from: u16) -> Profile { + let short = from < 600; + Profile { + short, + inline_styles: from < 400, + types_from_zero: from < 400, + color: if from < 400 { + ColorLayout::Bytes5 + } else if from < 500 { + ColorLayout::Words12 + } else { + ColorLayout::Record12 + }, + fixed_matrix: from < 500, + mcfg_corners: from < 400, + mcfg_skip: if from >= 1300 { + 12 + } else if from >= 900 { + 4 + } else if from >= 600 && from < 700 { + 28 + } else { + 0 + }, + trfd_head: if from >= 1300 { 8 } else { 0 }, + matrix_skip: if short { 0 } else { 6 }, + tagged: from >= 1300, + outl_after_join: if from >= 600 && from < 1300 { 2 } else { 0 }, + outl_after_stretch: if short { 0 } else { 2 }, + outl_after_angle: if from >= 1300 { + 46 + } else if !short { + 52 + } else { + 0 + }, + outl_after_color: if short { 10 } else { 16 }, + marker_after_dash: if from >= 1300 { + Some(20) + } else if from >= 600 { + Some(22) + } else { + None + }, + four_radii: from >= 900, + f64_rect: from >= 1500, + old_master_flags: from < 1400, + paths: from >= 1000, + utf16_names: from >= 1200, + } +} + +/// The newest version read: 27, as the `vrsn` chunk names it (R1, R2). +pub(crate) const NEWEST: u16 = 2799; + +/// The first version of each range, with its layouts. Ranges start where a field moves. +const PROFILES: &[(u16, Profile)] = &[ + (300, profile(300)), + (400, profile(400)), + (500, profile(500)), + (600, profile(600)), + (700, profile(700)), + (800, profile(800)), + (900, profile(900)), + (1000, profile(1000)), + (1100, profile(1100)), + (1200, profile(1200)), + (1300, profile(1300)), + (1400, profile(1400)), + (1500, profile(1500)), + (1600, profile(1600)), +]; + +/// The oldest version of a RIFF file read: 3 (R31). Versions 1 and 2 are not RIFF files (`wl.rs`). +pub(crate) const OLDEST_RIFF: u16 = 300; + +/// The layouts of the RIFF file of `version` (hundreds; 801 is the 8.01 variant, 2430 is 24.3), or +/// `None` outside 3 to 27. +pub(crate) fn for_version(version: u16) -> Option { + if !(OLDEST_RIFF..=NEWEST).contains(&version) { + return None; + } + PROFILES.iter().rev().find(|(from, _)| *from <= version).map(|(_, p)| *p) +} + +impl Profile { + /// Points per coordinate unit. + pub(crate) fn unit(&self) -> f64 { + if self.short { 72.0 / 1000.0 } else { 72.0 / 254_000.0 } + } + + /// Bytes of a coordinate, and of header fields and counts. + pub(crate) fn word(&self) -> usize { + if self.short { 2 } else { 4 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_version_from_3_to_27_has_one_profile() { + assert!(for_version(299).is_none() && for_version(2800).is_none()); + assert!(for_version(300).is_some_and(|p| p.short && p.inline_styles && p.types_from_zero && p.mcfg_corners && p.fixed_matrix)); + assert!(for_version(399).is_some_and(|p| p.color == ColorLayout::Bytes5)); + assert!(for_version(400).is_some_and(|p| p.short && !p.inline_styles && !p.mcfg_corners && p.fixed_matrix)); + assert!(for_version(499).is_some_and(|p| p.color == ColorLayout::Words12)); + assert!(for_version(500).is_some_and(|p| !p.fixed_matrix && !p.types_from_zero && p.color == ColorLayout::Record12)); + assert!(for_version(1300).is_some_and(|p| p.old_master_flags)); + assert!(for_version(1400).is_some_and(|p| p.tagged && !p.f64_rect && !p.old_master_flags)); + assert!(for_version(1500).is_some_and(|p| p.tagged && p.f64_rect && p.mcfg_skip == 12 && p.paths)); + assert!(for_version(2430).is_some_and(|p| p.f64_rect && p.paths && p.utf16_names)); + assert!(for_version(500).is_some_and(|p| p.short && p.mcfg_skip == 0 && p.marker_after_dash.is_none())); + assert!(for_version(600).is_some_and(|p| !p.short && p.mcfg_skip == 28 && p.marker_after_dash == Some(22))); + assert!(for_version(801).is_some_and(|p| p.mcfg_skip == 0 && p.marker_after_dash == Some(22))); + assert!(for_version(999).is_some_and(|p| !p.paths && p.marker_after_dash == Some(22))); + assert!(for_version(1000).is_some_and(|p| p.mcfg_skip == 4 && p.four_radii && !p.utf16_names && p.paths)); + assert!(for_version(1300).is_some_and(|p| p.tagged && p.trfd_head == 8 && p.outl_after_angle == 46)); + // The table is in order, so the search finds each range's own row. + assert!(PROFILES.windows(2).all(|w| w[0].0 < w[1].0)); + } +} diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs new file mode 100644 index 0000000000..8eb2d48125 --- /dev/null +++ b/crates/cdr/src/lib.rs @@ -0,0 +1,115 @@ +//! Reader for `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the `WL` files +//! of versions 1 and 2, the RIFF chunk tree of versions 3 on with its compressed lists, the ZIP +//! packages of versions 14 on with their data streams, then pages, layers, guidelines, groups, +//! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. It also reads +//! `.cmx` exchange files with 32-bit coordinates ([`read_cmx`]): their pages, layers, groups and +//! curves with uniform fills and outlines. [`preview()`] gives the picture a `.cdr` file keeps of its +//! drawing, without reading the drawing. +//! +//! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source +//! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not +//! panic. Nothing here writes `.cdr` or `.cmx` files. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::fmt; + +mod build; +mod bytes; +mod cmx; +mod geometry; +mod inline; +mod layout; +mod limits; +pub mod model; +mod package; +mod preview; +mod records; +mod riff; +mod styles; +#[cfg(any(test, feature = "synth"))] +pub mod synth; +#[cfg(any(test, feature = "synth"))] +pub mod synth_cmx; +mod wl; +mod zip; + +pub use limits::Limits; +pub use model::{Drawing, Warning}; +pub use preview::{Preview, PreviewFormat, preview}; + +/// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file +/// of version 1 or 2 whose header offsets fit the file? +pub fn is_cdr(bytes: &[u8]) -> bool { + riff::is_cdr_riff(bytes) || package::is_package(bytes) || wl::is_wl(bytes) +} + +/// Does `bytes` start as a `.cmx` exchange file: a RIFF form (or its big-endian RIFX form) of type +/// `CMX1`? +pub fn is_cmx(bytes: &[u8]) -> bool { + cmx::is_cmx(bytes) +} + +/// Why a file can't be read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + /// Not a `.cdr` drawing. + NotCdr, + /// Not a `.cmx` file. + NotCmx, + /// A drawing of a version this reader doesn't read (hundreds: 2800 is version 28). + Version(u16), + /// A container structure that doesn't parse. + Damaged(&'static str), + /// Past one of the [`Limits`]. + Limit(&'static str), + /// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that + /// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates; a + /// `DISP` preview that is not an uncompressed bitmap with a 40-byte header; a version 2 file's + /// picture. + Unsupported(&'static str), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::NotCdr => write!(f, "not a CDR drawing"), + Error::NotCmx => write!(f, "not a CMX file"), + Error::Version(v) => write!(f, "version {} drawings are not read", v / 100), + Error::Damaged(what) => write!(f, "damaged {what}"), + Error::Limit(what) => write!(f, "past the {what} limit"), + Error::Unsupported(what) => write!(f, "{what} are not read"), + } + } +} + +impl std::error::Error for Error {} + +/// Read a drawing within `limits`. +pub fn read(bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + let mut budget = limits::Budget::new(limits); + // Versions 1 and 2 are not RIFF files (R40). + if wl::is_wl(bytes) { + return wl::drawing(bytes, &mut budget); + } + let mut warnings = Vec::new(); + // Versions 14 on save a ZIP package around the RIFF stream (R24, R25, R26). + let (stream, streams) = if zip::is_zip(bytes) { package::open(bytes, &mut budget)? } else { (std::borrow::Cow::Borrowed(bytes), None) }; + let ix = riff::Index::build(&stream, streams, &mut budget, &mut warnings)?; + let mut drawing = build::drawing(&ix, &mut budget, &mut warnings)?; + ix.stream_warnings(&mut drawing.warnings); + Ok(drawing) +} + +/// Read a `.cmx` exchange file within `limits`. Files in big-endian byte order and files with +/// 16-bit coordinates are refused with [`Error::Unsupported`]. Its [`Drawing::version`] is 0. +pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + let mut budget = limits::Budget::new(limits); + cmx::drawing(bytes, &mut budget) +} diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs new file mode 100644 index 0000000000..bb9804557f --- /dev/null +++ b/crates/cdr/src/limits.rs @@ -0,0 +1,168 @@ +//! What one read may take. The values are VectorCraft's own; wasm32 gets half the memory limits. + +use crate::Error; + +/// The most a read may take, checked before every allocation and descent. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// Bytes of input. + pub input: usize, + /// Bytes inflated from compressed lists and package members, all of one file together. + pub inflated: usize, + /// Bytes of one package member. + pub member: usize, + /// Members of a package. + pub members: usize, + /// Nested lists below the file's own. Deeper content is left out with a warning. + pub depth: usize, + /// Chunks in the index, nested ones included, and the entries and styles of the style table; + /// in a `.cmx` file, its chunks, table entries and page instructions. + pub chunks: usize, + /// Objects mapped (shapes, groups and guidelines). + pub objects: usize, + /// Points of all curves together. + pub coordinates: usize, + /// Arguments of one `loda` record. + pub arguments: usize, + /// Dashes of all outlines together, an outline's counted again for every shape that uses it. + /// Past them a shape's outline is solid, with a warning. + pub dashes: usize, + /// Chunks walked inside clipped groups, all containers together, a group's counted again for + /// every container that names it. Each search of an object's list for its `loda`, `flgs` and + /// `trfd` runs once per read and counts every chunk it looks at. Past them a container's group + /// is left out, with a warning. + pub clipped_chunks: usize, +} + +#[cfg(not(target_arch = "wasm32"))] +const MIB: usize = 1 << 20; + +impl Default for Limits { + #[cfg(not(target_arch = "wasm32"))] + fn default() -> Self { + Limits { + input: 512 * MIB, + inflated: 1024 * MIB, + member: 512 * MIB, + members: 4096, + depth: 256, + chunks: 2_000_000, + objects: 1_000_000, + coordinates: 16_000_000, + arguments: 64, + dashes: 16_000_000, + clipped_chunks: 2_000_000, + } + } + + #[cfg(target_arch = "wasm32")] + fn default() -> Self { + Limits { + input: 256 << 20, + inflated: 512 << 20, + member: 256 << 20, + members: 4096, + depth: 256, + chunks: 2_000_000, + objects: 1_000_000, + coordinates: 16_000_000, + arguments: 64, + dashes: 8_000_000, + clipped_chunks: 2_000_000, + } + } +} + +/// The running counters of one read against its [`Limits`]. +#[derive(Debug)] +pub(crate) struct Budget { + pub(crate) limits: Limits, + inflated: usize, + chunks: usize, + objects: usize, + coordinates: usize, + dashes: usize, + clipped_chunks: usize, + /// A request for coordinates was refused since [`Budget::coordinates_refused`] last asked. + refused: bool, +} + +impl Budget { + pub(crate) fn new(limits: Limits) -> Self { + Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0, clipped_chunks: 0, refused: false } + } + + /// Whether a request for coordinates was refused since the last call, which tells a shape + /// left out at the limit from one whose bytes don't parse. + pub(crate) fn coordinates_refused(&mut self) -> bool { + std::mem::take(&mut self.refused) + } + + /// Bytes an inflate may still produce. + pub(crate) fn inflate_left(&self) -> usize { + self.limits.inflated.saturating_sub(self.inflated) + } + + pub(crate) fn take_inflated(&mut self, n: usize) -> Result<(), Error> { + self.inflated = self.inflated.checked_add(n).filter(|&t| t <= self.limits.inflated).ok_or(Error::Limit("inflated size"))?; + Ok(()) + } + + pub(crate) fn take_chunk(&mut self) -> Result<(), Error> { + self.take_chunks(1) + } + + /// `n` more chunks or style table entries. + pub(crate) fn take_chunks(&mut self, n: usize) -> Result<(), Error> { + self.chunks = self.chunks.saturating_add(n); + if self.chunks > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) } + } + + /// One more object, or `false` when the drawing already holds as many as a read maps. + pub(crate) fn take_object(&mut self) -> bool { + if self.objects >= self.limits.objects { + return false; + } + self.objects += 1; + true + } + + /// `n` more curve points, or `false` past the limit (nothing is taken then). + pub(crate) fn take_coordinates(&mut self, n: usize) -> bool { + match self.coordinates.checked_add(n).filter(|&t| t <= self.limits.coordinates) { + Some(t) => { + self.coordinates = t; + true + } + None => { + self.refused = true; + false + } + } + } + + /// Dashes the read may still take. + pub(crate) fn dashes_left(&self) -> usize { + self.limits.dashes.saturating_sub(self.dashes) + } + + /// `n` more dashes, or `false` past the limit (nothing is taken then). + pub(crate) fn take_dashes(&mut self, n: usize) -> bool { + match self.dashes.checked_add(n).filter(|&t| t <= self.limits.dashes) { + Some(t) => { + self.dashes = t; + true + } + None => false, + } + } + + /// One more chunk walked inside a clipped group, or `false` past the limit. + pub(crate) fn take_clipped_chunk(&mut self) -> bool { + if self.clipped_chunks >= self.limits.clipped_chunks { + return false; + } + self.clipped_chunks += 1; + true + } +} diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs new file mode 100644 index 0000000000..e4af34f365 --- /dev/null +++ b/crates/cdr/src/model.rs @@ -0,0 +1,255 @@ +//! What a drawing reads as. Lengths are in points (1/72 inch), from the centre of the page, with y +//! pointing up, as the file stores them. + +/// A point in points. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pt { + pub x: f64, + pub y: f64, +} + +/// An affine map `[a, b, c, d, e, f]`: x' = a x + c y + e, y' = b x + d y + f. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Matrix(pub [f64; 6]); + +impl Matrix { + pub const IDENTITY: Matrix = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + + /// `self` after `first`: the map that applies `first`, then `self`. + pub fn after(&self, first: &Matrix) -> Matrix { + let [a, b, c, d, e, f] = self.0; + let [p, q, r, s, t, u] = first.0; + Matrix([a * p + c * q, b * p + d * q, a * r + c * s, b * r + d * s, a * t + c * u + e, b * t + d * u + f]) + } + + pub fn apply(&self, p: Pt) -> Pt { + let [a, b, c, d, e, f] = self.0; + Pt { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f } + } +} + +/// One segment after the previous point. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Segment { + Line(Pt), + /// Two control points, then the end point. + Cubic(Pt, Pt, Pt), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SubPath { + pub start: Pt, + pub segments: Vec, + pub closed: bool, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Path { + pub subpaths: Vec, +} + +/// The shape of an object, in its own space ([`Shape::matrix`] places it). +#[derive(Clone, Debug, PartialEq)] +pub enum Geometry { + Path(Path), + /// A rectangle from the origin to (`w`, `h`) (either may be negative). `radii` round its + /// corners counterclockwise from the one at (`w`, 0): (`w`, 0), (`w`, `h`), (0, `h`), (0, 0). + Rect { + w: f64, + h: f64, + radii: [f64; 4], + }, + /// A whole ellipse in the box from the origin to (`w`, `h`). + Ellipse { + w: f64, + h: f64, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Color { + Rgb([f32; 3]), + Cmyk([f32; 4]), + /// Ink: 0 is white, 1 black. + Gray(f32), + /// Every ink at full strength. + Registration, + /// A color of a named library, printed on its own plate. `look` is its full-strength color + /// when the file stores one (an approximation in sRGB); `tint` is 0 to 1. + Spot { + name: String, + tint: f32, + look: Option<[f32; 3]>, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cap { + Butt, + Round, + Square, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Join { + Miter, + Round, + Bevel, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Outline { + pub width: f64, + pub color: Color, + pub cap: Cap, + pub join: Join, + /// Dash and gap lengths, in outline widths; empty for a solid line. + pub dashes: Vec, + /// Drawn behind the fill, so that a filled shape shows only the outer half of it. + pub behind_fill: bool, + /// Scaled with the shape: the shape's matrix scales the width and dashes as it scales the + /// geometry. + pub scale_with: bool, +} + +/// Whether a layer, group or shape is hidden or locked. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Flags { + pub hidden: bool, + pub locked: bool, +} + +/// How a shape's colors combine with the art below it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Blend { + #[default] + Normal, + Multiply, + Screen, + Overlay, + SoftLight, + HardLight, + ColorDodge, + ColorBurn, + Darken, + Lighten, + Difference, + Exclusion, + Hue, + Saturation, + Color, + Luminosity, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Shape { + pub geometry: Geometry, + pub matrix: Matrix, + pub fill: Option, + pub outline: Option, + /// The fill covers every area its subpaths wind around (nonzero); otherwise subpaths that + /// overlap leave holes (even-odd). + pub nonzero: bool, + /// 1 opaque, 0 clear. + pub opacity: f32, + pub blend: Blend, + pub flags: Flags, +} + +impl Shape { + /// An opaque, shown shape filled even-odd. + pub fn new(geometry: Geometry, matrix: Matrix, fill: Option, outline: Option) -> Shape { + Shape { geometry, matrix, fill, outline, nonzero: false, opacity: 1.0, blend: Blend::Normal, flags: Flags::default() } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Object { + Shape(Box), + Group { + objects: Vec, + flags: Flags, + }, + /// A clipping container and the objects it clips: `objects` (front to back) show only + /// inside the container's shape, with its fill behind them and its outline over them. + Clip { + container: Box, + objects: Vec, + }, +} + +/// A guideline through `at`, at `angle` degrees counterclockwise from horizontal. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Guideline { + pub at: Pt, + pub angle: f64, + /// The guideline, a group around it or its layer is hidden. + pub hidden: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LayerKind { + Drawing, + /// The objects left beside the pages. + Desktop, + Guides, + Grid, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Layer { + pub name: String, + pub kind: LayerKind, + pub flags: Flags, + /// Front to back, as the file lists them. + pub objects: Vec, + pub guides: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Page { + /// Width and height in points, when the page gives its own. + pub size: Option<(f64, f64)>, + /// Front to back, as the file lists them. + pub layers: Vec, +} + +/// What was left out or changed while reading. Each kind is listed once. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Warning { + /// Text, bitmaps, splines and other objects not read yet. + UnsupportedObjects, + /// Fountain, pattern, texture and PostScript fills. + UnsupportedFills, + /// Colors in models not read; shown black. + UnknownColors, + /// Library spot colors whose look the file doesn't store; shown black. + SpotLooks, + /// Outline arrowheads. + Arrowheads, + /// Envelopes, which are not applied: the shapes under them keep their outlines. + Envelopes, + /// Lenses, and object transparency that isn't read, which are not applied: the objects show + /// opaque. + Lenses, + /// Content nested deeper, or past the counts, that a read takes. + TooDeep, + /// Chunks or records that end early or don't parse. + Damaged, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Drawing { + /// In hundreds, as a RIFF file stores it: 300 to 2799. A file of version 1 or 2 stores no + /// number: it gives 200 when its marker byte is the one of version 2, and 100 otherwise. A + /// `.cmx` file gives 0. + pub version: u16, + /// Page size from the document settings, in points. + pub page_size: Option<(f64, f64)>, + pub pages: Vec, + /// Layers every page shows, from the master page. + pub master: Vec, + /// Guidelines every page shows, kept outside any layer. + pub guides: Vec, + pub warnings: Vec, +} diff --git a/crates/cdr/src/package.rs b/crates/cdr/src/package.rs new file mode 100644 index 0000000000..6d7fd7e1e3 --- /dev/null +++ b/crates/cdr/src/package.rs @@ -0,0 +1,152 @@ +//! The packages of versions 14 on (R25, R26): a ZIP archive holding the RIFF stream as +//! `content/riffData.cdr` (14 and 15), or as `content/root.dat` with its chunk bodies in the data +//! streams that `content/dataFileList.dat` names (16 on). A data stream is inflated only when a +//! chunk the reader reads, or a list it splits, points into it. + +use std::borrow::Cow; +use std::cell::{Cell, OnceCell}; + +use crate::limits::{Budget, Limits}; +use crate::riff::push; +use crate::zip::{self, Archive}; +use crate::{Error, Warning}; + +const RIFF_DATA: &[u8] = b"content/riffData.cdr"; +const ROOT: &[u8] = b"content/root.dat"; +const DATA_FILE_LIST: &[u8] = b"content/dataFileList.dat"; +const DATA_DIR: &[u8] = b"content/data/"; + +/// Is `bytes` a ZIP archive with a `.cdr` drawing's root stream? +pub(crate) fn is_package(bytes: &[u8]) -> bool { + zip::is_zip(bytes) && Archive::open(bytes, Limits::default().members).is_ok_and(|a| holds_drawing(&a)) +} + +/// Does the archive `zip` hold a `.cdr` drawing's root stream? +pub(crate) fn holds_drawing(zip: &Archive) -> bool { + zip.find(RIFF_DATA).or_else(|| zip.find(ROOT)).is_some() +} + +/// The RIFF stream of the package `bytes`, and its data streams when it has them (16 on). +pub(crate) fn open<'a>(bytes: &'a [u8], budget: &mut Budget) -> Result<(Cow<'a, [u8]>, Option>), Error> { + let zip = Archive::open(bytes, budget.limits.members)?; + if let Some(i) = zip.find(RIFF_DATA) { + return Ok((member(&zip, i, budget)?, None)); + } + let root = zip.find(ROOT).ok_or(Error::NotCdr)?; + let root = member(&zip, root, budget)?; + let list = match zip.find(DATA_FILE_LIST) { + Some(i) => member(&zip, i, budget)?, + None => Cow::Borrowed(&[][..]), + }; + // One name for each line; a line feed after the last name ends it. + let list = list.strip_suffix(b"\n").unwrap_or(&list); + let mut members = Vec::new(); + if !list.is_empty() { + for line in list.split(|&b| b == b'\n') { + if members.len() == budget.limits.members { + return Err(Error::Limit("package member count")); + } + let name = line.strip_suffix(b"\r").unwrap_or(line); + let found = zip.find(&[DATA_DIR, name].concat()); + // A data stream that is encrypted or packed some other way refuses the file, as the + // root stream does. + if let Some(i) = found { + zip.check(i)?; + } + members.push(found); + } + } + let loaded = (0..zip.count()).map(|_| OnceCell::new()).collect(); + let streams = Streams { zip, members, loaded, member_limit: budget.limits.member, damaged: Cell::new(false) }; + Ok((root, Some(streams))) +} + +/// Member `i` within the member limit and, when deflated, what is left to inflate. +fn member<'a>(zip: &Archive<'a>, i: usize, budget: &mut Budget) -> Result, Error> { + let m = zip.read(i, budget.limits.member, budget.inflate_left())?; + if let Cow::Owned(v) = &m { + budget.take_inflated(v.len())?; + } + Ok(m) +} + +/// What reading one package member gave. +#[derive(Debug)] +enum Slot<'a> { + Read(Cow<'a, [u8]>), + Damaged, + PastLimit, +} + +/// The data streams of a version 16+ package, in `dataFileList.dat` order (R26). +#[derive(Debug)] +pub(crate) struct Streams<'a> { + zip: Archive<'a>, + /// The member holding each stream; `None` when the archive lacks it. + members: Vec>, + /// Each member's bytes once read, so that streams naming one member read it once. + loaded: Vec>>, + member_limit: usize, + /// A stream, or a chunk's bytes in one, could not be found. + damaged: Cell, +} + +impl<'a> Streams<'a> { + /// The member holding stream `s`; `None` when there is no such stream. + pub(crate) fn member_of(&self, s: usize) -> Option { + *self.members.get(s)? + } + + /// The size the archive gives stream `s`; `None` when there is no such stream. + pub(crate) fn size(&self, s: usize) -> Option { + Some(self.zip.size(self.member_of(s)?)) + } + + /// Stream `s`, its member read on first use within the member limit and, when deflated, + /// within `left` more inflated bytes (which it takes from). + pub(crate) fn get(&self, s: usize, left: &Cell) -> Option<&[u8]> { + let Some(i) = self.member_of(s) else { + self.damaged.set(true); + return None; + }; + let slot = self.loaded.get(i)?.get_or_init(|| { + let read = self.zip.read(i, self.member_limit, left.get()); + if !matches!(read, Err(Error::Limit(_))) { + left.set(left.get().saturating_sub(self.zip.inflate_cost(i))); + } + match read { + Ok(b) => Slot::Read(b), + Err(Error::Limit(_)) => Slot::PastLimit, + Err(_) => { + self.damaged.set(true); + Slot::Damaged + } + } + }); + match slot { + Slot::Read(b) => Some(b.as_ref()), + Slot::Damaged | Slot::PastLimit => None, + } + } + + /// Was stream `s` left out because it is past a limit? Chunks in it are then not damage. + pub(crate) fn past_limit(&self, s: usize) -> bool { + let slot = self.member_of(s).and_then(|i| self.loaded.get(i)).and_then(OnceCell::get); + matches!(slot, Some(Slot::PastLimit)) + } + + /// Mark a chunk whose stream bytes could not be found. + pub(crate) fn note_damage(&self) { + self.damaged.set(true); + } + + /// The warnings for streams that were left out. + pub(crate) fn warnings(&self, warn: &mut Vec) { + if self.damaged.get() { + push(warn, Warning::Damaged); + } + if self.loaded.iter().any(|s| matches!(s.get(), Some(Slot::PastLimit))) { + push(warn, Warning::TooDeep); + } + } +} diff --git a/crates/cdr/src/preview.rs b/crates/cdr/src/preview.rs new file mode 100644 index 0000000000..95edefeffd --- /dev/null +++ b/crates/cdr/src/preview.rs @@ -0,0 +1,530 @@ +//! The picture a drawing keeps of itself: the `DISP` chunk of a RIFF file (R75), or the thumbnail +//! member of a package (R76). Reading it walks only the RIFF form's own chunks, or reads one +//! package member, so it does not depend on the drawing's records. + +use std::borrow::Cow; + +use crate::bytes::Rd; +use crate::zip::{self, Archive}; +use crate::{Error, Limits, package, riff, wl}; + +const DISP: [u8; 4] = *b"DISP"; +/// The bytes of a `DISP` body before its bitmap info header (R75). +const DISP_LEAD: usize = 4; +/// The shortest bitmap info header, and the one whose color masks follow it (R75). +const INFO_LEN: usize = 40; +/// The compression values of uncompressed pixels, and of pixels that three color masks describe +/// (R75). +const RGB: u32 = 0; +const BITFIELDS: u32 = 3; +const COMPRESSED: &str = "compressed previews"; +const WL_PICTURE: &str = "pictures of version 2 files"; +const OTHER_HEADER: &str = "preview bitmap headers of other lengths"; +const OTHER_DISP: &str = "previews of other kinds than a bitmap"; +/// The lead bytes of every `DISP` chunk in the sample files, before a bitmap (R75). +const DISP_BITMAP: [u8; DISP_LEAD] = [8, 0, 0, 0]; +/// A BMP file header: `BM`, the file length, 4 reserved bytes and where the pixels start (R75). +const FILE_HEADER_LEN: usize = 14; +/// The package members that hold the drawing's picture (R76), in the order they are looked for. +const PNG_THUMBNAIL: &[u8] = b"previews/thumbnail.png"; +const BMP_THUMBNAIL: &[u8] = b"metadata/thumbnails/thumbnail.bmp"; +const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; +const BMP_SIGNATURE: &[u8] = b"BM"; + +/// How a [`Preview`]'s bytes are encoded. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreviewFormat { + /// A BMP file. + Bmp, + /// A PNG file. + Png, +} + +/// The picture a drawing keeps of itself, still encoded: the caller decodes it within its own +/// image limits. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Preview<'a> { + pub format: PreviewFormat, + pub bytes: Cow<'a, [u8]>, +} + +/// The picture the drawing `bytes` keeps of itself, within `limits`, without reading the drawing: +/// a version 4 to 13 file's `DISP` chunk as a BMP file, or a package's thumbnail member: +/// `previews/thumbnail.png` when the package has one (versions 17 on), else +/// `metadata/thumbnails/thumbnail.bmp` (versions 14 to 16). The package's drawing stream is not +/// read, so the member is chosen by its name, not by the drawing's version. `None` when the file +/// keeps no picture, as versions 1 and 3 do; the 1-bit picture of a version 2 file is not read, and +/// such a file is refused. The drawing's version is not checked, so a RIFF file +/// that [`read`](crate::read) refuses for its version still gives its `DISP` picture. A `DISP` +/// chunk that is not a bitmap, and a bitmap that is compressed or has another header than the +/// 40-byte one, are refused. A package member is read within the member and inflate limits, and its +/// CRC-32 is checked. +pub fn preview(bytes: &[u8], limits: Limits) -> Result>, Error> { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + if zip::is_zip(bytes) { + return thumbnail(bytes, limits); + } + if riff::is_cdr_riff(bytes) { + return disp(bytes, limits); + } + if wl::is_wl(bytes) { + // Version 1 (marker `e`) keeps no picture; version 2's 1-bit picture is not read (R40). + return if bytes.get(2) == Some(&b'e') { Ok(None) } else { Err(Error::Unsupported(WL_PICTURE)) }; + } + Err(Error::NotCdr) +} + +/// A package's thumbnail member (R76). +fn thumbnail(bytes: &[u8], limits: Limits) -> Result>, Error> { + let zip = Archive::open(bytes, limits.members)?; + if !package::holds_drawing(&zip) { + return Err(Error::NotCdr); + } + for (name, format, signature) in [(PNG_THUMBNAIL, PreviewFormat::Png, PNG_SIGNATURE), (BMP_THUMBNAIL, PreviewFormat::Bmp, BMP_SIGNATURE)] { + if let Some(i) = zip.find(name) { + let bytes = zip.read(i, limits.member, limits.inflated)?; + if !bytes.starts_with(signature) { + return Err(Error::Damaged("preview")); + } + return Ok(Some(Preview { format, bytes })); + } + } + Ok(None) +} + +/// The `DISP` chunk among the RIFF form's own chunks, as a BMP file (R75). A file cut short still +/// gives a `DISP` chunk it holds whole. When there is none, the last chunk must end where the form's +/// length says the form ends; otherwise the file is damaged. +fn disp(bytes: &[u8], limits: Limits) -> Result>, Error> { + let declared = Rd::at(bytes, 4).u32().ok_or(Error::NotCdr)? as usize; + // A form length past the file is taken to the file's end; one too short for the form type + // leaves no chunk to walk. + let end = declared.checked_add(8).filter(|e| *e <= bytes.len()).unwrap_or(bytes.len()); + let mut at: usize = 12; + let mut chunks = 0; + // Why the last `DISP` chunk passed over was not read: another kind than a bitmap, or a bitmap + // this reader does not read. + let mut passed: Option = None; + while at.checked_add(8).is_some_and(|h| h <= end) { + chunks += 1; + if chunks > limits.chunks { + return Err(Error::Limit("chunk count")); + } + let mut r = Rd::at(bytes, at); + let (id, len) = (r.fourcc(), r.u32().map(|n| n as usize)); + let (Some(id), Some(len)) = (id, len) else { break }; + let body = at + 8; + if id == DISP { + let data = body.checked_add(len).filter(|e| *e <= end).and_then(|e| bytes.get(body..e)).ok_or(Error::Damaged("preview"))?; + match data.get(..DISP_LEAD) { + None => return Err(Error::Damaged("preview")), + Some(lead) if lead == DISP_BITMAP => match bmp(data) { + Ok(b) => return Ok(Some(Preview { format: PreviewFormat::Bmp, bytes: Cow::Owned(b) })), + Err(e @ Error::Unsupported(_)) => passed = Some(e), + Err(e) => return Err(e), + }, + Some(_) => passed = Some(Error::Unsupported(OTHER_DISP)), + } + } + // Chunks are padded to an even length. + at = body.saturating_add(len).saturating_add(len & 1); + } + // A chunk past the end, a partial chunk header or a file cut short may hide a `DISP` chunk. + if at > bytes.len() || declared.checked_add(8) != Some(at) { + return Err(Error::Damaged("preview")); + } + passed.map_or(Ok(None), Err) +} + +/// The bitmap of a `DISP` body as a BMP file: a file header before its info header, color masks or +/// table and pixels (R75). +fn bmp(disp: &[u8]) -> Result, Error> { + let damaged = || Error::Damaged("preview"); + let dib = disp.get(DISP_LEAD..).ok_or_else(damaged)?; + let mut r = Rd::new(dib); + let info = r.u32().ok_or_else(damaged)? as usize; + // A header too short for its own length field, or longer than the chunk. + if info < 4 || info > dib.len() { + return Err(damaged()); + } + // Only the 40-byte header is read (R75). + if info != INFO_LEN { + return Err(Error::Unsupported(OTHER_HEADER)); + } + let (width, height) = (r.i32().ok_or_else(damaged)?, r.i32().ok_or_else(damaged)?); + // The planes, the bit count and compression; the image size and resolution, then the colors + // used. + let planes = r.u16().ok_or_else(damaged)?; + let bits = r.u16().ok_or_else(damaged)?; + let compression = r.u32().ok_or_else(damaged)?; + let size = r.u32().ok_or_else(damaged)?; + r.skip(8).ok_or_else(damaged)?; + let used = r.u32().ok_or_else(damaged)? as usize; + // Only uncompressed pixels are read: color masks are valid at 16 and 32 bits (R75). + match compression { + RGB if matches!(bits, 1 | 4 | 8 | 16 | 24 | 32) => {} + BITFIELDS if matches!(bits, 16 | 32) => {} + RGB | BITFIELDS => return Err(damaged()), + _ => return Err(Error::Unsupported(COMPRESSED)), + } + if planes != 1 { + return Err(damaged()); + } + // A table of 2^bits colors when the header names none for 8 bits or fewer, and never more. + let colors = if bits <= 8 && used == 0 { 1usize << bits } else { used }; + if bits < 32 && colors as u64 > 1u64 << bits { + return Err(damaged()); + } + // Three masks follow the header. + let masks = if compression == BITFIELDS { 12 } else { 0 }; + let pixels = colors.checked_mul(4).and_then(|t| (FILE_HEADER_LEN + info + masks).checked_add(t)).ok_or_else(damaged)?; + let total = FILE_HEADER_LEN + dib.len(); + // The pixels are rows of whole 32-bit words, as many as the height says (R75). + let width = u64::try_from(width).ok().filter(|w| *w > 0).ok_or_else(damaged)?; + if height == 0 { + return Err(damaged()); + } + let rows = ((width * u64::from(bits)).div_ceil(32) * 4).checked_mul(u64::from(height.unsigned_abs())); + // The image size is 0 or the rows' size. + if size != 0 && rows != Some(u64::from(size)) { + return Err(damaged()); + } + // The file ends with the last row; bytes after it in the chunk are left out. + let end = rows.and_then(|n| n.checked_add(pixels as u64)).filter(|e| *e <= total as u64).ok_or_else(damaged)? as usize; + let (end32, pixels32) = (u32::try_from(end).map_err(|_| damaged())?, u32::try_from(pixels).map_err(|_| damaged())?); + let mut out = Vec::new(); + out.try_reserve_exact(end).map_err(|_| Error::Limit("preview size"))?; + out.extend(BMP_SIGNATURE); + out.extend(end32.to_le_bytes()); + out.extend([0; 4]); + out.extend(pixels32.to_le_bytes()); + out.extend(dib.get(..end - FILE_HEADER_LEN).ok_or_else(damaged)?); + Ok(out) +} + +#[cfg(test)] +mod tests { + use proptest::prelude::*; + + use super::*; + use crate::synth::{self, Member, chunk}; + + /// A `DISP` body: the lead bytes, a 40-byte info header for `bits` per pixel and `used` + /// colors, the color table and `rows` rows of `width` pixels. + fn disp_body(width: u32, rows: u32, bits: u16, used: u32) -> Vec { + let mut b = 8u32.to_le_bytes().to_vec(); + b.extend(40u32.to_le_bytes()); + b.extend(width.to_le_bytes()); + b.extend(rows.to_le_bytes()); + b.extend(1u16.to_le_bytes()); + b.extend(bits.to_le_bytes()); + b.extend([0; 16]); + b.extend(used.to_le_bytes()); + b.extend([0; 4]); + let colors = if bits <= 8 && used == 0 { 1 << bits } else { used }; + b.extend((0..colors * 4).map(|i| i as u8)); + let stride = (width * u32::from(bits)).div_ceil(32) * 4; + b.extend((0..stride * rows).map(|i| (i * 7) as u8)); + b + } + + fn with_disp(version: u16, body: Vec) -> Vec { + let mut content = vec![chunk(b"vrsn", version.to_le_bytes().to_vec()), chunk(b"DISP", body)]; + content.extend(synth::sample_content(version)); + synth::riff(version, &content) + } + + fn png() -> Vec { + [PNG_SIGNATURE, b"rest of the picture"].concat() + } + + fn package16(extra: &[Member]) -> Vec { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + synth::package16(1700, &body, true, extra) + } + + fn member(name: &str, data: Vec, deflate: bool) -> Member { + Member { name: name.into(), data, deflate } + } + + #[test] + fn a_riff_files_disp_chunk_is_a_bmp_file_around_its_bitmap() { + for (bits, used) in [(8, 256), (8, 0), (4, 0), (4, 16), (1, 2)] { + let body = disp_body(9, 5, bits, used); + let file = with_disp(1100, body.clone()); + let p = preview(&file, Limits::default()).unwrap().unwrap(); + assert_eq!(p.format, PreviewFormat::Bmp); + let b = &p.bytes; + assert!(b.starts_with(b"BM")); + assert_eq!(&b[FILE_HEADER_LEN..], &body[DISP_LEAD..], "the bitmap follows the file header unchanged"); + assert_eq!(u32::from_le_bytes(b[2..6].try_into().unwrap()) as usize, b.len()); + // The pixels start after the info header and the whole color table. + let colors = if used == 0 { 1 << bits } else { used } as usize; + assert_eq!(u32::from_le_bytes(b[10..14].try_into().unwrap()) as usize, FILE_HEADER_LEN + 40 + colors * 4, "{bits} bits, {used} colors"); + } + // Bytes after the last row are left out of the file. + let body = disp_body(9, 5, 8, 0); + let trailing = [body.as_slice(), &[0xAA; 64]].concat(); + let file = with_disp(1100, trailing); + let p = preview(&file, Limits::default()).unwrap().unwrap(); + assert_eq!(&p.bytes[FILE_HEADER_LEN..], &body[DISP_LEAD..]); + assert_eq!(u32::from_le_bytes(p.bytes[2..6].try_into().unwrap()) as usize, p.bytes.len()); + } + + #[test] + fn a_file_without_a_picture_has_no_preview() { + assert_eq!(preview(&synth::sample(300, false), Limits::default()), Ok(None)); + assert_eq!(preview(&synth::sample(1100, true), Limits::default()), Ok(None)); + assert_eq!(preview(&synth::wl_sample(b'e'), Limits::default()), Ok(None)); + assert_eq!(preview(&package16(&[]), Limits::default()), Ok(None)); + assert_eq!(preview(&synth::package14(synth::sample(1500, true), true), Limits::default()), Ok(None)); + } + + #[test] + fn a_package_gives_its_thumbnail_member() { + let bmp = with_disp(1100, disp_body(3, 2, 8, 0)); + let bmp = preview(&bmp, Limits::default()).unwrap().unwrap().bytes.into_owned(); + let v15 = synth::zip( + &[member("content/riffData.cdr", synth::sample(1500, true), true), member("metadata/thumbnails/thumbnail.bmp", bmp.clone(), true)], + b"", + ); + assert_eq!(preview(&v15, Limits::default()), Ok(Some(Preview { format: PreviewFormat::Bmp, bytes: Cow::Owned(bmp) }))); + // A stored member is lent, not copied. + let v16 = package16(&[member("previews/page1.png", vec![1; 10], false), member("previews/thumbnail.png", png(), false)]); + let p = preview(&v16, Limits::default()).unwrap().unwrap(); + assert_eq!(p.format, PreviewFormat::Png); + assert!(matches!(p.bytes, Cow::Borrowed(b) if b == png().as_slice())); + } + + #[test] + fn a_thumbnail_that_is_not_its_format_is_damage() { + let v16 = package16(&[member("previews/thumbnail.png", b"BM not a PNG".to_vec(), false)]); + assert_eq!(preview(&v16, Limits::default()), Err(Error::Damaged("preview"))); + let v15 = synth::zip( + &[member("content/riffData.cdr", synth::sample(1500, false), false), member("metadata/thumbnails/thumbnail.bmp", png(), false)], + b"", + ); + assert_eq!(preview(&v15, Limits::default()), Err(Error::Damaged("preview"))); + } + + #[test] + fn a_disp_chunk_too_short_for_its_bitmap_is_damage() { + let body = disp_body(4, 4, 8, 0); + // Cut inside the info header, inside the color table, and before the lead bytes end. + for cut in [DISP_LEAD + 20, DISP_LEAD + 40 + 100, 2] { + let file = with_disp(1100, body[..cut].to_vec()); + assert_eq!(preview(&file, Limits::default()), Err(Error::Damaged("preview")), "cut at {cut}"); + } + // An info header longer than the chunk or too short for its length field, and a plane + // count other than 1. + for info in [u32::MAX, 0, 3] { + let mut b = body.clone(); + b[DISP_LEAD..DISP_LEAD + 4].copy_from_slice(&info.to_le_bytes()); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview")), "info {info}"); + } + for planes in [0u16, 2] { + let mut b = body.clone(); + b[DISP_LEAD + 12..DISP_LEAD + 14].copy_from_slice(&planes.to_le_bytes()); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview")), "{planes} planes"); + } + // Header lengths other than 40 bytes. + for info in [12u32, 44, 52, 56, 64, 108, 124] { + let mut b = body.clone(); + b[DISP_LEAD..DISP_LEAD + 4].copy_from_slice(&info.to_le_bytes()); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Unsupported(OTHER_HEADER)), "info {info}"); + } + // A whole 12-byte core header of a 1-by-1 24-bit bitmap, shorter than the 40-byte fields. + let mut core = 8u32.to_le_bytes().to_vec(); + core.extend(12u32.to_le_bytes()); + core.extend([1, 0, 1, 0, 1, 0, 24, 0]); + core.extend([1, 2, 3, 0]); + assert_eq!(preview(&with_disp(1100, core), Limits::default()), Err(Error::Unsupported(OTHER_HEADER))); + // A color count past the chunk. + let mut b = body.clone(); + b[DISP_LEAD + 32..DISP_LEAD + 36].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview"))); + // Pixel rows cut short, and a width or bit count that gives no rows. + let rows = with_disp(1100, body[..body.len() - 1].to_vec()); + assert_eq!(preview(&rows, Limits::default()), Err(Error::Damaged("preview"))); + for (at, v) in [(4, 0u32.to_le_bytes().to_vec()), (14, 2u16.to_le_bytes().to_vec())] { + let mut b = body.clone(); + b[DISP_LEAD + at..DISP_LEAD + at + v.len()].copy_from_slice(&v); + assert_eq!(preview(&with_disp(1100, b), Limits::default()), Err(Error::Damaged("preview")), "field at {at}"); + } + // A chunk that runs past the end of the RIFF form, though not past the file. + let mut past = with_disp(1100, body.clone()); + let at = past.windows(4).position(|w| w == b"DISP").unwrap(); + let form_len = (at + 8 + body.len() - 1 - 8) as u32; + past[4..8].copy_from_slice(&form_len.to_le_bytes()); + assert_eq!(preview(&past, Limits::default()), Err(Error::Damaged("preview"))); + // A chunk whose length runs past the file. + let mut file = with_disp(1100, body); + let at = file.windows(4).position(|w| w == b"DISP").unwrap(); + file[at + 4..at + 8].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(preview(&file, Limits::default()), Err(Error::Damaged("preview"))); + } + + #[test] + fn color_masks_after_a_40_byte_header_come_before_the_pixels() { + let plain = disp_body(2, 2, 16, 0); + let mut body = plain[..DISP_LEAD + 40].to_vec(); + body[DISP_LEAD + 16..DISP_LEAD + 20].copy_from_slice(&BITFIELDS.to_le_bytes()); + body.extend([0x00, 0xF8, 0, 0, 0xE0, 0x07, 0, 0, 0x1F, 0, 0, 0]); + body.extend(&plain[DISP_LEAD + 40..]); + let pixels_at = |file: Vec| { + let p = preview(&file, Limits::default()).unwrap().unwrap(); + u32::from_le_bytes(p.bytes[10..14].try_into().unwrap()) as usize + }; + assert_eq!(pixels_at(with_disp(1100, body)), FILE_HEADER_LEN + 40 + 12); + // Without the masks the pixels start right after the header. + assert_eq!(pixels_at(with_disp(1100, plain)), FILE_HEADER_LEN + 40); + } + + #[test] + fn the_limits_hold() { + let file = with_disp(1100, disp_body(4, 4, 8, 0)); + assert_eq!(preview(&file, Limits { input: file.len() - 1, ..Limits::default() }), Err(Error::Limit("input size"))); + // The `DISP` chunk is the second chunk. + assert_eq!(preview(&file, Limits { chunks: 1, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert!(preview(&file, Limits { chunks: 2, ..Limits::default() }).unwrap().is_some()); + let big = vec![7; 4000]; + let v16 = package16(&[member("previews/thumbnail.png", [PNG_SIGNATURE, &big].concat(), true)]); + assert_eq!(preview(&v16, Limits { member: 4000, ..Limits::default() }), Err(Error::Limit("package member size"))); + assert_eq!(preview(&v16, Limits { inflated: 4000, ..Limits::default() }), Err(Error::Limit("inflated size"))); + assert_eq!(preview(&v16, Limits { members: 1, ..Limits::default() }), Err(Error::Limit("package member count"))); + } + + #[test] + fn a_walk_that_stops_short_of_the_forms_end_is_damage() { + let file = synth::sample(1100, true); + assert_eq!(preview(&file, Limits::default()), Ok(None)); + // A chunk whose length runs past the form, before any `DISP` chunk. + let mut past = file.clone(); + past[16..20].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(preview(&past, Limits::default()), Err(Error::Damaged("preview"))); + // A form length too short for the form type, with a `DISP` chunk after it. + let mut short = with_disp(1100, disp_body(4, 4, 8, 0)); + short[4..8].copy_from_slice(&2u32.to_le_bytes()); + assert_eq!(preview(&short, Limits::default()), Err(Error::Damaged("preview"))); + // A partial chunk header at the end: the start of a `DISP` chunk whose length is cut off. + let mut partial = file.clone(); + partial.extend(b"DISP"); + let form_len = (partial.len() - 8) as u32; + partial[4..8].copy_from_slice(&form_len.to_le_bytes()); + assert_eq!(preview(&partial, Limits::default()), Err(Error::Damaged("preview"))); + // A file without a `DISP` chunk cut inside its last chunk. + assert_eq!(preview(&file[..file.len() - 1], Limits::default()), Err(Error::Damaged("preview"))); + // A file cut where its `DISP` chunk would start, and one cut after it. + let whole = with_disp(1100, disp_body(4, 4, 8, 0)); + let at = whole.windows(4).position(|w| w == b"DISP").unwrap(); + assert_eq!(preview(&whole[..at], Limits::default()), Err(Error::Damaged("preview"))); + assert!(preview(&whole[..whole.len() - 1], Limits::default()).unwrap().is_some()); + } + + #[test] + fn a_disp_chunk_that_is_not_a_bitmap_is_passed_over() { + let text = [[1u8, 0, 0, 0].as_slice(), b"some text"].concat(); + let bitmap = disp_body(3, 2, 8, 0); + // A bitmap with a 12-byte header, which is not read. + let core = [[8u8, 0, 0, 0, 12, 0, 0, 0, 1, 0, 1, 0, 1, 0, 24, 0].as_slice(), &[1, 2, 3, 0]].concat(); + // A run-length bitmap, whose other fields are not checked: here a plane count of 0. + let mut rle = bitmap.clone(); + rle[DISP_LEAD + 12..DISP_LEAD + 14].copy_from_slice(&0u16.to_le_bytes()); + rle[DISP_LEAD + 16..DISP_LEAD + 20].copy_from_slice(&1u32.to_le_bytes()); + let mut content = + vec![chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), chunk(b"DISP", text.clone()), chunk(b"DISP", core), chunk(b"DISP", rle)]; + content.push(chunk(b"DISP", bitmap.clone())); + content.extend(synth::sample_content(1100)); + let file = synth::riff(1100, &content); + let p = preview(&file, Limits::default()).unwrap().unwrap(); + assert_eq!(&p.bytes[FILE_HEADER_LEN..], &bitmap[DISP_LEAD..]); + // With no bitmap after it, the file has a picture that is not read. + assert_eq!(preview(&with_disp(1100, text), Limits::default()), Err(Error::Unsupported(OTHER_DISP))); + } + + #[test] + fn a_color_table_larger_than_the_bit_count_allows_is_damage() { + assert!(preview(&with_disp(1100, disp_body(4, 4, 1, 2)), Limits::default()).unwrap().is_some()); + assert_eq!(preview(&with_disp(1100, disp_body(4, 4, 1, 3)), Limits::default()), Err(Error::Damaged("preview"))); + assert_eq!(preview(&with_disp(1100, disp_body(1, 1, 16, 65_537)), Limits::default()), Err(Error::Damaged("preview"))); + } + + #[test] + fn the_image_size_is_0_or_the_rows_size() { + // 4 rows of 4 bytes. + let body = disp_body(4, 4, 8, 0); + for (size, ok) in [(16u32, true), (17, false), (16 + 64, false)] { + let mut b = [body.as_slice(), &[0; 64]].concat(); + b[DISP_LEAD + 20..DISP_LEAD + 24].copy_from_slice(&size.to_le_bytes()); + let file = with_disp(1100, b); + assert_eq!(preview(&file, Limits::default()).is_ok(), ok, "size {size}"); + } + } + + #[test] + fn a_version_2_files_picture_is_not_read() { + for marker in *b"ml" { + assert_eq!(preview(&synth::wl_sample(marker), Limits::default()), Err(Error::Unsupported(WL_PICTURE))); + } + } + + #[test] + fn a_package_with_both_members_gives_the_png() { + let bmp = with_disp(1100, disp_body(3, 2, 8, 0)); + let bmp = preview(&bmp, Limits::default()).unwrap().unwrap().bytes.into_owned(); + for extra in [ + [member("metadata/thumbnails/thumbnail.bmp", bmp.clone(), false), member("previews/thumbnail.png", png(), false)], + [member("previews/thumbnail.png", png(), false), member("metadata/thumbnails/thumbnail.bmp", bmp.clone(), false)], + ] { + assert_eq!(preview(&package16(&extra), Limits::default()).unwrap().unwrap().format, PreviewFormat::Png); + } + } + + #[test] + fn a_compressed_or_masked_bitmap_outside_the_header_rules_is_refused() { + let body = disp_body(4, 4, 8, 0); + let with = |compression: u32, bits: u16| { + let mut b = body.clone(); + b[DISP_LEAD + 14..DISP_LEAD + 16].copy_from_slice(&bits.to_le_bytes()); + b[DISP_LEAD + 16..DISP_LEAD + 20].copy_from_slice(&compression.to_le_bytes()); + preview(&with_disp(1100, b), Limits::default()).map(|p| p.map(|p| p.format)) + }; + // Run-length, JPEG, PNG and alpha-mask compression, and a bit count of 0. + for (compression, bits) in [(1, 8), (2, 4), (4, 0), (5, 0), (6, 32)] { + assert_eq!(with(compression, bits), Err(Error::Unsupported(COMPRESSED)), "compression {compression}"); + } + // Color masks are valid only at 16 and 32 bits, and no bit count of 0 is uncompressed. + for (compression, bits) in [(BITFIELDS, 8), (BITFIELDS, 24), (BITFIELDS, 1), (RGB, 0)] { + assert_eq!(with(compression, bits), Err(Error::Damaged("preview")), "compression {compression}, {bits} bits"); + } + } + + #[test] + fn other_files_are_not_drawings() { + assert_eq!(preview(b"not a drawing", Limits::default()), Err(Error::NotCdr)); + let zip = synth::zip(&[member("previews/thumbnail.png", png(), false)], b""); + assert_eq!(preview(&zip, Limits::default()), Err(Error::NotCdr)); + } + + proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_mutated_files(package: bool, cut in any::(), edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = if package { + package16(&[member("previews/thumbnail.png", png(), false)]) + } else { + with_disp(900, disp_body(5, 3, 4, 0)) + }; + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = preview(&b, Limits::default()); + let _ = preview(&b[..cut % (n + 1)], Limits::default()); + } + } +} diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs new file mode 100644 index 0000000000..49adcedc7e --- /dev/null +++ b/crates/cdr/src/records.rs @@ -0,0 +1,659 @@ +//! Hand-written decoders of the records a drawing's objects refer to: the `loda` argument table +//! (R6), transforms (R8), colors (R14), fills (R11) and outlines (R12, R13). + +use crate::bytes::Rd; +use crate::layout::{ColorLayout, Profile}; +use crate::model::{Blend, Cap, Color, Join, Matrix, Outline}; +use crate::riff::push; +use crate::{Limits, Warning}; + +/// The tag of a record's current layout in tagged files (R11, R12). +const TAG_1300: u32 = 1300; +/// The most tagged records skipped before a fill's own (R11). +const MAX_SKIPPED: usize = 4; +/// The most records skipped before an outline's own (R12). +const MAX_OUTLINE_RECORDS: usize = 16; +/// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of +/// a layer's. +const MAX_NAME: usize = 256; + +/// A header field: u16 in short files, u32 otherwise. +fn word(r: &mut Rd, p: &Profile) -> Option { + if p.short { r.u16().map(usize::from) } else { r.u32().map(|v| v as usize) } +} + +/// A coordinate in points. +pub(crate) fn coord(r: &mut Rd, p: &Profile) -> Option { + let raw = if p.short { f64::from(r.i16()?) } else { f64::from(r.i32()?) }; + Some(raw * p.unit()) +} + +/// An angle in degrees: tenths in short files, millionths otherwise (R7). +pub(crate) fn angle(r: &mut Rd, p: &Profile) -> Option { + if p.short { Some(f64::from(r.i16()?) / 10.0) } else { Some(f64::from(r.i32()?) / 1_000_000.0) } +} + +/// A `loda` record (R6): its object type and arguments as (type, bytes). +pub(crate) struct Loda<'a> { + pub(crate) kind: u32, + pub(crate) args: Vec<(u32, &'a [u8])>, +} + +impl<'a> Loda<'a> { + pub(crate) fn arg(&self, kind: u32) -> Option<&'a [u8]> { + self.args.iter().find(|(k, _)| *k == kind).map(|(_, b)| *b) + } +} + +pub(crate) fn loda<'a>(b: &'a [u8], p: &Profile, limits: &Limits, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + let (_len, count, offsets_at, types_at, kind) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?); + // The types table is indexed from the stored count, however many arguments are read. + let stored = count; + let count = if count > limits.arguments { + push(warn, Warning::Damaged); + limits.arguments + } else { + count + }; + let table_bytes = count.checked_add(1)?.checked_mul(p.word())?; + if offsets_at.checked_add(table_bytes)? > b.len() { + return None; + } + let mut offsets = Vec::with_capacity(count + 1); + let mut ro = Rd::at(b, offsets_at); + for _ in 0..=count { + offsets.push(word(&mut ro, p)?); + } + let mut args = Vec::with_capacity(count); + for i in 0..count { + // The types table runs the other way: offset i pairs with type stored - 1 - i. + let kind = word(&mut Rd::at(b, types_at.checked_add((stored - 1 - i).checked_mul(p.word())?)?), p)? as u32; + let (start, end) = (*offsets.get(i)?, *offsets.get(i + 1)?); + match b.get(start..end) { + Some(body) => args.push((kind, body)), + None => push(warn, Warning::Damaged), + } + } + Some(Loda { kind: kind as u32, args }) +} + +/// The matrices of a `trfd` record composed in file order, in points (R8). Each entry ends where +/// the next offset points, and the last at the offset after it (R51); an entry too short for its +/// matrix makes the record unreadable. +pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let (_len, count, offsets_at) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?); + let mut m = Matrix::IDENTITY; + let k = p.unit(); + // Each entry takes at least its offset's bytes, which bounds the count by the record's size. + for i in 0..count.min(b.len() / p.word()) { + let slot = offsets_at.checked_add(i.checked_mul(p.word())?)?; + let start = word(&mut Rd::at(b, slot), p)?; + // A table that stops before the last entry's end offset leaves that entry the rest of the + // record. + let end = word(&mut Rd::at(b, slot.checked_add(p.word())?), p).unwrap_or(b.len()); + let mut e = Rd::at(b.get(start..end)?, p.trfd_head); + if e.u16()? != 8 { + continue; + } + e.skip(p.matrix_skip)?; + let next = if p.fixed_matrix { + fixed_matrix(&mut e, k)? + } else { + let (a, c, tx, bb, d, ty) = (e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?); + Matrix([a, bb, c, d, tx * k, ty * k]) + }; + m = next.after(&m); + } + Some(m) +} + +/// A number in 16.16 fixed point. +pub(crate) fn fixed(r: &mut Rd) -> Option { + Some(f64::from(r.i32()?) / 65536.0) +} + +/// A matrix of versions 3 and 4 (R37): six i32 `a c tx b d ty`, the factors in 16.16 fixed point +/// and `tx` and `ty` in coordinate units of `k` points. +pub(crate) fn fixed_matrix(r: &mut Rd, k: f64) -> Option { + let (a, c, tx) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?)); + let (b, d, ty) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?)); + Some(Matrix([a, b, c, d, tx * k, ty * k])) +} + +/// A color in the layout of the file's version (R14, R36). Unknown models read as black with a +/// warning. +pub(crate) fn color(r: &mut Rd, p: &Profile, warn: &mut Vec) -> Option { + match p.color { + ColorLayout::Record12 => { + let model = r.u16()?; + let palette = r.u16()?; + r.skip(4)?; + let v: [u8; 4] = r.bytes(4)?.try_into().ok()?; + Some(model_color(model, palette, v, warn)) + } + ColorLayout::Words12 => { + let model = r.u16()?; + let w = [r.u16()?, r.u16()?, r.u16()?, r.u16()?]; + r.skip(2)?; + // The models take 8-bit values, as in the other layouts; a larger value reads as 255. + Some(early_color(model, w.map(|x| u8::try_from(x).unwrap_or(u8::MAX)), w[0], w[1], warn)) + } + ColorLayout::Bytes5 => Some(color5(r.bytes(5)?.try_into().ok()?, warn)), + } +} + +/// A 5-byte color (R36): a model byte and four value bytes. +pub(crate) fn color5(b: [u8; 5], warn: &mut Vec) -> Color { + let [model, v @ ..] = b; + early_color(u16::from(model), v, u16::from_le_bytes([v[0], v[1]]), u16::from_le_bytes([v[2], v[3]]), warn) +} + +/// A color of versions 1 to 4 (R36). Model 1 is CMYK in percent. Model 0 is a numbered ink and +/// its tint in percent: 0 is black, 1 is white, and other numbers are inks of a library the file +/// doesn't store. Other models read as in later versions. +fn early_color(model: u16, v: [u8; 4], index: u16, tint: u16, warn: &mut Vec) -> Color { + let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0); + match (model, index) { + (1, _) => Color::Cmyk(v.map(|x| pct(f32::from(x)))), + (0, 0) => Color::Gray(pct(f32::from(tint))), + (0, 1) => Color::Gray(0.0), + (0, number) => { + push(warn, Warning::SpotLooks); + Color::Spot { name: format!("Spot 0:{number}"), tint: pct(f32::from(tint)), look: None } + } + _ => model_color(model, 0, v, warn), + } +} + +/// The color of `model` with the four value bytes `v`, from version 5 (R14). +fn model_color(model: u16, palette: u16, v: [u8; 4], warn: &mut Vec) -> Color { + let (v0, v1, v2, v3) = (f32::from(v[0]), f32::from(v[1]), f32::from(v[2]), f32::from(v[3])); + let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0); + let byte = |x: f32| x / 255.0; + match model { + 2 => Color::Cmyk([pct(v0), pct(v1), pct(v2), pct(v3)]), + 3 | 17 => Color::Cmyk([byte(v0), byte(v1), byte(v2), byte(v3)]), + 4 => Color::Cmyk([byte(v0), byte(v1), byte(v2), 0.0]), + 5 | 21 => Color::Rgb([byte(v2), byte(v1), byte(v0)]), + 9 => Color::Gray(1.0 - byte(v0)), + 20 => Color::Registration, + 1 | 14 | 25 => { + let number = u16::from_le_bytes([v[0], v[1]]); + let tint = pct(f32::from(u16::from_le_bytes([v[2], v[3]]))); + push(warn, Warning::SpotLooks); + // Each library numbers its own colors: the name holds the palette and the number. + Color::Spot { name: format!("Spot {palette}:{number}"), tint, look: None } + } + _ => { + push(warn, Warning::UnknownColors); + Color::Rgb([0.0; 3]) + } + } +} + +/// A UTF-16 name stored as a character count and its code units. Every shape that uses the color +/// gets its own copy of the name: a name longer than [`MAX_NAME`] units keeps its first ones and a +/// hash of the whole name, with a warning, so two long names that start alike stay apart. +fn counted_utf16(r: &mut Rd, warn: &mut Vec) -> Option { + let n = r.u32()? as usize; + let b = r.bytes(n.checked_mul(2)?)?; + // Trailing NULs are padding. + let all = b.as_chunks::<2>().0; + let all = all.get(..all.iter().rposition(|c| *c != [0, 0]).map_or(0, |i| i + 1)).unwrap_or_default(); + let units = all.iter().map(|c| u16::from_le_bytes(*c)); + if all.len() <= MAX_NAME { + let units: Vec = units.collect(); + return Some(String::from_utf16_lossy(&units)); + } + push(warn, Warning::TooDeep); + // FNV-1a over the code units. + let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u64::from(u)).wrapping_mul(0x0100_0000_01b3)); + let kept: Vec = units.take(MAX_NAME).collect(); + Some(format!("{} {hash:016x}", String::from_utf16_lossy(&kept))) +} + +/// The color of the property list of a tagged uniform fill (R11) or outline (R12): its color +/// record, named by the library name it carries. +pub(crate) fn property_color(b: &[u8], p: &Profile, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + let (mut found, mut name) = (None, None); + while r.left() >= 5 { + let kind = r.u8()?; + let len = r.u32()? as usize; + if kind == 0 { + break; + } + let body = r.bytes(len)?; + let mut br = Rd::new(body); + match kind { + 1 => found = color(&mut br, p, warn), + 8 => name = br.skip(16).and_then(|_| counted_utf16(&mut br, warn)), + 3 => name = name.or_else(|| counted_utf16(&mut br, warn)), + _ => {} + } + } + match (found?, name.filter(|n| !n.is_empty())) { + // A library color with its name: the record's sRGB has the tint applied already. + (Color::Rgb(rgb), Some(name)) => { + let tint = b_tint(b).unwrap_or(1.0); + Some(Color::Spot { name, tint, look: Some(untinted(rgb, tint)) }) + } + (c, _) => Some(c), + } +} + +/// The tint byte of the first color property of a property list (model 21 keeps it last). +fn b_tint(b: &[u8]) -> Option { + let mut r = Rd::new(b); + while r.left() >= 5 { + let kind = r.u8()?; + let len = r.u32()? as usize; + let body = r.bytes(len)?; + if kind == 1 { + let mut c = Rd::new(body); + return (c.u16()? == 21).then(|| f32::from(*body.get(11).unwrap_or(&100)) / 100.0).map(|t| t.clamp(0.0, 1.0)); + } + } + None +} + +/// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white). +fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] { + if tint <= 0.0 { + return rgb; + } + rgb.map(|v| (1.0 - (1.0 - v) / tint).clamp(0.0, 1.0)) +} + +/// A fill record: its id, and its color (`None`: no fill). Fills of other kinds read as none with +/// a warning (R11). +pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec) -> Option<(u32, Option)> { + let mut r = Rd::new(b); + let id = r.u32()?; + let body = if p.tagged { tagged_body(&mut r)? } else { r.bytes(r.left())? }; + let mut r = Rd::new(body); + let kind = r.u16()?; + let color = match kind { + 0 => None, + 1 if p.tagged => { + if r.u32()? != TAG_1300 { + push(warn, Warning::Damaged); + return Some((id, None)); + } + // A uniform fill whose color can't be read is damage, not a fill of none. + let len = r.u32()? as usize; + Some(property_color(r.bytes(len.min(r.left()))?, p, warn)?) + } + 1 => { + r.skip(2)?; + Some(color(&mut r, p, warn)?) + } + _ => { + push(warn, Warning::UnsupportedFills); + None + } + }; + Some((id, color)) +} + +/// The body of the record tagged 1300 that follows tagged records of later layouts (R11). +fn tagged_body<'a>(r: &mut Rd<'a>) -> Option<&'a [u8]> { + for _ in 0..=MAX_SKIPPED { + let (tag, len) = (r.u32()?, r.u32()? as usize); + let body = r.bytes(len.min(r.left()))?; + if tag == TAG_1300 { + return Some(body); + } + } + None +} + +/// An outline record: its id and the outline (`None`: no outline) (R12, R13). +pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option<(u32, Option)> { + let mut r = Rd::new(b); + let id = r.u32()?; + // A library color named in a record of type 2, with the warnings its read gave. + let mut named = None; + if p.tagged { + let mut found = false; + for _ in 0..MAX_OUTLINE_RECORDS { + let (rec, len) = (r.u32()?, r.u32()? as usize); + if rec == 1 { + found = true; + break; + } + let body = r.bytes(len)?; + // Type 2 holds the outline's color as a property list, as a uniform fill does (R12). + // Only a library color with its name is taken from it; any other color comes from + // the fixed field below. + if rec == 2 { + let mut w = Vec::new(); + if let Some(c @ Color::Spot { look: Some(_), .. }) = property_color(body, p, &mut w) { + named = Some((c, w)); + } + } + } + if !found { + return None; + } + } + let (line_type, cap, join) = (r.u16()?, r.u16()?, r.u16()?); + r.skip(p.outl_after_join)?; + let width = coord(&mut r, p)?.abs(); + let _stretch = r.u16()?; + r.skip(p.outl_after_stretch)?; + let _nib = angle(&mut r, p)?; + r.skip(p.outl_after_angle)?; + let color = match named { + Some((named, w)) => { + color(&mut r, p, &mut Vec::new())?; + for x in w { + push(warn, x); + } + named + } + None => color(&mut r, p, warn)?, + }; + r.skip(p.outl_after_color)?; + let count = usize::from(r.u16()?); + let first_dash = r.pos(); + let fits = r.left() / 2; + if count > fits { + push(warn, Warning::Damaged); + } + // At most 65,535; the read's dash limit is applied where shapes use them. + let dashes: Vec = (0..count.min(fits)).filter_map(|_| r.u16().map(f64::from)).collect(); + if let Some(after) = p.marker_after_dash { + let mut m = Rd::at(b, first_dash + after); + if matches!((m.u32(), m.u32()), (Some(s), Some(e)) if s != 0 || e != 0) { + push(warn, Warning::Arrowheads); + } + } + // Bit 0 of the line type: no outline (R13). + if line_type & 1 != 0 { + return Some((id, None)); + } + let cap = match cap { + 1 => Cap::Round, + 2 => Cap::Square, + _ => Cap::Butt, + }; + let join = match join { + 1 => Join::Round, + 2 => Join::Bevel, + _ => Join::Miter, + }; + // Bit 2 of the line type marks the outline dashed; without it the dashes stored are not drawn + // (R48). + let dashes = if line_type & 4 != 0 && dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() }; + // Bit 4 of the line type: behind the fill (R49). + let behind_fill = line_type & 0x10 != 0; + // Bit 5 of the line type: scaled with the shape (R50). + let scale_with = line_type & 0x20 != 0; + Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill, scale_with }))) +} + +/// The opacity and blend of argument 8000 from version 13 (R47): records of a u32 version, a u32 +/// length and a body. A body of version 1300 that is [`UNIFORM_LEN`] bytes long is a uniform +/// transparency: an f64 at byte 61 and the merge mode at byte 77. VectorCraft reads the f64 as the +/// transparency in percent, 0 opaque and 100 clear. `None` for any other argument, such as a lens, +/// and for a value out of range or a merge mode without a VectorCraft blend mode. +pub(crate) fn transparency(b: &[u8]) -> Option<(f32, Blend)> { + let mut r = Rd::new(b); + while r.left() >= 8 { + let (since, len) = (r.u32()?, r.u32()? as usize); + let body = r.bytes(len)?; + if since != TAG_1300 { + continue; + } + if body.len() != UNIFORM_LEN { + return None; + } + let value = Rd::at(body, 61).f64()?; + if !(0.0..=100.0).contains(&value) { + return None; + } + return Some(((1.0 - value / 100.0) as f32, blend(*body.get(77)?)?)); + } + None +} + +/// The length of a uniform transparency's record body (R47). +const UNIFORM_LEN: usize = 117; + +/// The blend mode of a transparency's merge mode byte (R47); `None` for the modes VectorCraft has +/// no blend mode for. +fn blend(mode: u8) -> Option { + Some(match mode { + 0 => Blend::Normal, + 9 => Blend::Multiply, + 11 => Blend::Lighten, + 12 => Blend::Darken, + 14 => Blend::Color, + 15 => Blend::Hue, + 16 => Blend::Saturation, + 17 => Blend::Luminosity, + 24 => Blend::Difference, + 28 => Blend::Screen, + 29 => Blend::Overlay, + 30 => Blend::SoftLight, + 31 => Blend::HardLight, + 33 => Blend::ColorDodge, + 34 => Blend::ColorBurn, + 36 => Blend::Exclusion, + _ => return None, + }) +} + +/// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name +/// longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones (without half of a +/// surrogate pair) and a hash of the whole name, with a warning, as a library color's name does. +pub(crate) fn name(b: &[u8], p: &Profile, warn: &mut Vec) -> String { + if p.utf16_names { + let units = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0); + let (mut kept, hash) = capped(units, warn); + if hash.is_some() && kept.last().is_some_and(|u| (0xD800..0xDC00).contains(u)) { + kept.pop(); + } + with_hash(String::from_utf16_lossy(&kept), hash) + } else { + let bytes = b.iter().copied().take_while(|c| *c != 0); + let (kept, hash) = capped(bytes, warn); + with_hash(kept.into_iter().map(windows_1252).collect(), hash) + } +} + +/// The first [`MAX_NAME`] of `units`, and when there are more, an FNV-1a hash of them all, with a +/// warning. +fn capped>(units: impl Iterator + Clone, warn: &mut Vec) -> (Vec, Option) { + if units.clone().nth(MAX_NAME).is_none() { + return (units.collect(), None); + } + push(warn, Warning::TooDeep); + let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u.into()).wrapping_mul(0x0100_0000_01b3)); + (units.take(MAX_NAME).collect(), Some(hash)) +} + +/// `name`, followed by `hash` in hexadecimal when there is one. +fn with_hash(name: String, hash: Option) -> String { + match hash { + Some(h) => format!("{name} {h:016x}"), + None => name, + } +} + +/// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes +/// are Latin-1. +const CP1252_HIGH: [char; 32] = [ + '€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–', + '—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ', +]; + +fn windows_1252(c: u8) -> char { + match c { + 0x80..=0x9F => CP1252_HIGH.get(usize::from(c - 0x80)).copied().unwrap_or('\u{FFFD}'), + _ => char::from(c), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An outline that names an arrowhead says so with a warning, in each version whose arrowhead + /// ids have a known place: 22 bytes after the first dash in versions 6 to 12, 20 from 13. + #[test] + fn arrowheads_are_named_from_version_6() { + let pen = crate::synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }; + let color = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100]; + for (version, place) in [ + (500, None), + (600, Some(22)), + (700, Some(22)), + (800, Some(22)), + (900, Some(22)), + (1000, Some(22)), + (1100, Some(22)), + (1200, Some(22)), + (1300, Some(20)), + (1700, Some(20)), + ] { + let p = crate::layout::for_version(version).unwrap(); + let plain = crate::synth::V(version).outline(7, pen, &color, &[]); + // The record ends with 32 bytes after its dashes, and this one has none. + let first_dash = plain.len() - 32; + let mut w = vec![]; + assert!(outline(&plain, &p, &mut w).is_some_and(|(id, o)| id == 7 && o.is_some()), "{version}"); + assert!(w.is_empty(), "{version}: {w:?}"); + let Some(place) = place else { continue }; + let mut arrow = plain.clone(); + arrow[first_dash + place..first_dash + place + 4].copy_from_slice(&9u32.to_le_bytes()); + let mut w = vec![]; + assert!(outline(&arrow, &p, &mut w).is_some(), "{version}"); + assert_eq!(w, vec![Warning::Arrowheads], "{version}"); + } + } + + #[test] + fn single_byte_names_read_as_windows_1252() { + let p = crate::layout::for_version(1100).unwrap(); + assert_eq!(name(b"Caf\xe9 \x80\x96\0junk", &p, &mut vec![]), "Café €–"); + let p = crate::layout::for_version(1200).unwrap(); + assert_eq!(name(&[0x41, 0, 0x42, 0, 0, 0, 0x43, 0], &p, &mut vec![]), "AB"); + } + + /// A layer name longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones and a hash + /// of the whole name, with a warning, in both encodings. A cut never keeps half of a surrogate + /// pair. + #[test] + fn long_layer_names_are_cut_with_a_hash() { + for version in [1100, 1200] { + let p = crate::layout::for_version(version).unwrap(); + let bytes = + |s: &str| if p.utf16_names { s.encode_utf16().flat_map(u16::to_le_bytes).collect::>() } else { s.as_bytes().to_vec() }; + let mut w = vec![]; + let a = name(&bytes(&"N".repeat(100_000)), &p, &mut w); + let b = name(&bytes(&format!("{}M", "N".repeat(99_999))), &p, &mut vec![]); + assert_ne!(a, b, "{version}"); + assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{version}: {}", a.len()); + assert_eq!(w, vec![Warning::TooDeep], "{version}"); + let mut w = vec![]; + assert_eq!(name(&bytes(&"N".repeat(MAX_NAME)), &p, &mut w), "N".repeat(MAX_NAME), "{version}"); + assert!(w.is_empty(), "{version}"); + } + let p = crate::layout::for_version(1200).unwrap(); + let emoji: Vec = format!("N{}", "\u{1F600}".repeat(200)).encode_utf16().flat_map(u16::to_le_bytes).collect(); + let cut = name(&emoji, &p, &mut vec![]); + assert!(!cut.contains('\u{FFFD}'), "{cut}"); + assert_eq!(cut.chars().filter(|c| *c == '\u{1F600}').count(), (MAX_NAME - 1) / 2); + } + + #[test] + fn colors_read_in_their_models() { + let p = crate::layout::for_version(500).unwrap(); + let rec = |model: u16, v: [u8; 4]| { + let mut b = model.to_le_bytes().to_vec(); + b.extend([0; 6]); + b.extend(v); + let mut w = vec![]; + (color(&mut Rd::new(&b), &p, &mut w), w) + }; + assert_eq!(rec(2, [100, 50, 0, 10]).0, Some(Color::Cmyk([1.0, 0.5, 0.0, 0.1]))); + assert_eq!(rec(5, [255, 0, 0, 0]).0, Some(Color::Rgb([0.0, 0.0, 1.0]))); + assert_eq!(rec(9, [255, 0, 0, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(rec(25, [7, 0, 40, 0]).0, Some(Color::Spot { name: "Spot 0:7".into(), tint: 0.4, look: None })); + // The same number in another library is another color. + let mut other = 25u16.to_le_bytes().to_vec(); + other.extend(3u16.to_le_bytes()); + other.extend([0; 4]); + other.extend([7, 0, 40, 0]); + assert_eq!(color(&mut Rd::new(&other), &p, &mut vec![]), Some(Color::Spot { name: "Spot 3:7".into(), tint: 0.4, look: None })); + let (c, w) = rec(6, [1, 2, 3, 4]); + assert_eq!((c, w), (Some(Color::Rgb([0.0; 3])), vec![Warning::UnknownColors])); + } + + #[test] + fn colors_of_versions_3_and_4_read_models_0_and_1() { + let read = |version: u16, model: u8, v: [u16; 4]| { + let p = crate::layout::for_version(version).unwrap(); + let b: Vec = if version < 400 { + std::iter::once(model).chain(v.map(|x| x as u8)).collect() + } else { + u16::from(model).to_le_bytes().into_iter().chain(v.iter().flat_map(|x| x.to_le_bytes())).chain([0, 0]).collect() + }; + let mut r = Rd::new(&b); + let mut w = vec![]; + let c = color(&mut r, &p, &mut w); + assert_eq!(r.left(), 0, "{version}"); + (c, w) + }; + for version in [300, 400] { + // Model 1 is CMYK in percent, not a library color as from version 5. + assert_eq!(read(version, 1, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}"); + assert_eq!(read(version, 2, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}"); + } + // Model 0: an ink number and a tint. Version 3 stores each as a u16 in its four bytes. + assert_eq!(read(300, 0, [0, 0, 60, 0]).0, Some(Color::Gray(0.6))); + assert_eq!(read(300, 0, [1, 0, 60, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(read(300, 0, [44, 1, 60, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks])); + assert_eq!(read(400, 0, [0, 60, 0, 0]).0, Some(Color::Gray(0.6))); + assert_eq!(read(400, 0, [1, 60, 0, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(read(400, 0, [300, 60, 0, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks])); + } + + #[test] + fn a_fixed_point_matrix_reads_its_factors_and_offsets() { + let raw: Vec = [65536i32, -32768, 1000, 131072, 16384, -500].iter().flat_map(|v| v.to_le_bytes()).collect(); + let m = fixed_matrix(&mut Rd::new(&raw), 0.5).unwrap(); + assert_eq!(m, Matrix([1.0, 2.0, -0.5, 0.25, 500.0, -250.0])); + assert!(fixed_matrix(&mut Rd::new(&raw[..23]), 0.5).is_none()); + } + + #[test] + fn long_names_that_start_alike_stay_apart() { + let read = |name: &str| { + let mut b = (name.encode_utf16().count() as u32).to_le_bytes().to_vec(); + b.extend(name.encode_utf16().flat_map(u16::to_le_bytes)); + let mut w = vec![]; + (counted_utf16(&mut Rd::new(&b), &mut w).unwrap(), w) + }; + let (a, w) = read(&"N".repeat(300)); + let (b, _) = read(&format!("{}M", "N".repeat(299))); + assert_ne!(a, b); + assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{a}"); + assert_eq!(w, vec![Warning::TooDeep]); + assert_eq!(read("Sky Blue"), ("Sky Blue".to_string(), vec![])); + // Padding doesn't count toward the length or the name. + let (padded, w) = read(&format!("{}\0\0", "N".repeat(MAX_NAME - 1))); + assert_eq!((padded, w), ("N".repeat(MAX_NAME - 1), vec![])); + } + + #[test] + fn a_tint_mixes_toward_white_and_comes_off_again() { + let shown = [0.6, 0.8, 1.0]; + let base = untinted(shown, 0.5); + assert!((base[0] - 0.2).abs() < 1e-6 && (base[1] - 0.6).abs() < 1e-6 && base[2] == 1.0); + } +} diff --git a/crates/cdr/src/riff.rs b/crates/cdr/src/riff.rs new file mode 100644 index 0000000000..3f041b4c37 --- /dev/null +++ b/crates/cdr/src/riff.rs @@ -0,0 +1,465 @@ +//! The chunk index: one flat table of every chunk, a list's children contiguous, built without +//! recursion. Payloads are not copied: an entry names a range of the RIFF stream, of the bytes +//! inflated from `LIST cmpr`, or of a package's data stream (layouts R1 to R4, R27). + +use std::cell::Cell; +use std::collections::BTreeMap; +use std::io::Read as _; + +use crate::bytes::{Rd, u32_at}; +use crate::layout; +use crate::limits::Budget; +use crate::package::Streams; +use crate::{Error, Warning}; + +pub(crate) const LIST: [u8; 4] = *b"LIST"; +const CMPR: [u8; 4] = *b"cmpr"; +const CPNG: [u8; 4] = *b"CPng"; +/// What follows `CPng` before the zlib stream (R3). +const CPNG_HEAD: [u8; 4] = [1, 0, 4, 0]; +/// The size of a redirect record, and the stream number of one that holds its body (R27). +const REDIRECT: usize = 16; +const INLINE: u32 = u32::MAX; + +/// One chunk: 28 bytes. `start` and `len` give the payload (after a list's form type) in its +/// source: 0 is the RIFF stream followed by the inflated bytes, `s + 1` is data stream `s`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Chunk { + pub(crate) id: [u8; 4], + /// A list's form type; zeros for other chunks. + pub(crate) form: [u8; 4], + src: u32, + start: u32, + len: u32, + first: u32, + count: u32, +} + +impl Chunk { + pub(crate) fn is_list(&self, form: &[u8; 4]) -> bool { + self.id == LIST && &self.form == form + } +} + +/// Every chunk of a file, and the bytes they point into. +pub(crate) struct Index<'a> { + input: &'a [u8], + inflated: Vec, + chunks: Vec, + /// The version the form type names: hundreds, as `vrsn` stores it (0 when the `vrsn` chunk + /// decides). + pub(crate) form_version: u16, + /// A version 16+ package's data streams; chunks of 16 bytes are redirect records then. + streams: Option>, + /// Bytes that inflating may still produce. + left: Cell, + /// The bytes redirected lists have taken: (package member, start) to end. + lists: Cell>, + /// The bytes other redirected chunks have taken, the same way. + leaves: Cell>, + /// Bytes that redirects to bytes another chunk already took may still read. + shared_left: Cell, + /// The first `vrsn` chunk among the file's own chunks, once seen, and the version it names + /// (`None` when it can't be read) (R2). + vrsn: Option>, +} + +/// A list still to be split into its children. +struct Pending { + entry: usize, + src: u32, + /// Its children's bytes. + start: usize, + end: usize, + /// The size pool of a compressed list's stream (`start..end` in source 0). + pool: Option<(usize, usize)>, + depth: usize, +} + +/// What reading one chunk header gives. +enum Read { + Chunk(Chunk), + /// A redirect record whose body can't be found: the chunk is left out, its list read on. + Lost, + /// A redirect record into a data stream past a limit: the chunk is left out without the + /// damage warning. + PastLimit, + /// A redirect record to bytes another chunk took, past the shared-bytes limit: the chunk is + /// left out with the limit warning. + SharedPastLimit, +} + +/// The version the RIFF form type names (R1): `CDR5`..`CDR9`, `CDRA` (10) to `CDRH` (17) with `I` +/// unused, then `J` (18) on; `CDR ` is version 3. Some files use a lower-case `cdr`, which names +/// the same versions except that `cdr8` is the 8.01 variant. Templates of version 21 have the form +/// type `CDTQ`; for `CDT` the `vrsn` chunk names the version, so this gives 0 (R28). +pub(crate) fn form_version(form: [u8; 4]) -> Option { + let [a, b, c, v] = form; + match (&[a, b, c], v) { + (b"cdr", b'8') => Some(801), + (b"CDR" | b"cdr", b' ') => Some(300), + (b"CDR" | b"cdr", b'1'..=b'9') => Some(100 * u16::from(v - b'0')), + (b"CDR" | b"cdr", b'A'..=b'H') => Some(100 * u16::from(v - b'A' + 10)), + (b"CDR" | b"cdr", b'J'..=b'W') => Some(100 * u16::from(v - b'J' + 18)), + (b"CDT", b'A'..=b'Z') => Some(0), + _ => None, + } +} + +/// Does `bytes` start like a RIFF `.cdr` drawing (not the `CDRX` exchange variant)? +pub(crate) fn is_cdr_riff(bytes: &[u8]) -> bool { + bytes.get(..4) == Some(b"RIFF") && bytes.get(8..12).and_then(|f| f.try_into().ok()).and_then(form_version).is_some() +} + +impl<'a> Index<'a> { + pub(crate) fn build(input: &'a [u8], streams: Option>, budget: &mut Budget, warn: &mut Vec) -> Result { + if input.len() > budget.limits.input { + return Err(Error::Limit("input size")); + } + let mut r = Rd::new(input); + if r.fourcc() != Some(*b"RIFF") { + return Err(Error::NotCdr); + } + let declared = r.u32().ok_or(Error::NotCdr)? as usize; + let form = r.fourcc().ok_or(Error::NotCdr)?; + let version = form_version(form).ok_or(Error::NotCdr)?; + // A file cut short keeps what it holds: its last chunk is truncated with a warning. A + // length that ends inside the form type is damage too, and the chunks after it are read. + let end = match declared.checked_add(8) { + Some(e) if (12..=input.len()).contains(&e) => e, + _ => { + push(warn, Warning::Damaged); + input.len() + } + }; + let left = Cell::new(budget.inflate_left()); + let mut ix = Index { + input, + inflated: Vec::new(), + chunks: Vec::new(), + form_version: version, + streams, + left, + lists: Cell::default(), + leaves: Cell::default(), + shared_left: Cell::new(budget.limits.member), + vrsn: None, + }; + ix.chunks.push(Chunk { id: *b"RIFF", form, src: 0, start: 12, len: 0, first: 0, count: 0 }); + let mut queue = vec![Pending { entry: 0, src: 0, start: 12, end, pool: None, depth: 0 }]; + while let Some(p) = queue.pop() { + ix.split(p, &mut queue, budget, warn)?; + } + Ok(ix) + } + + /// The bytes `start..end` of source `src`, or `None` when the range crosses its end. A data + /// stream is read on first use. + fn span(&self, src: u32, start: usize, end: usize) -> Option<&[u8]> { + if src > 0 { + let s = self.streams.as_ref()?; + return s.get(src as usize - 1, &self.left)?.get(start..end); + } + let n = self.input.len(); + if end <= n { + self.input.get(start..end) + } else if start >= n { + self.inflated.get(start - n..end - n) + } else { + None + } + } + + pub(crate) fn data(&self, c: &Chunk) -> &[u8] { + let start = c.start as usize; + match self.span(c.src, start, start + c.len as usize) { + Some(b) => b, + None => { + if let Some(s) = &self.streams + && !self.past_limit(c.src) + { + s.note_damage(); + } + &[] + } + } + } + + /// Was source `src` a data stream left out because it is past a limit? Its chunks are then + /// left out with that warning alone. + fn past_limit(&self, src: u32) -> bool { + src > 0 && self.streams.as_ref().is_some_and(|s| s.past_limit(src as usize - 1)) + } + + pub(crate) fn children(&self, c: &Chunk) -> &[Chunk] { + let first = c.first as usize; + self.chunks.get(first..first + c.count as usize).unwrap_or_default() + } + + pub(crate) fn root(&self) -> Option<&Chunk> { + self.chunks.first() + } + + /// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1, + /// R2). A template's form type names no version, so its `vrsn` chunk decides whatever it names + /// (R28). Letters count differently from the version 24 update on (R1), so when both name a + /// version after 27 the `vrsn` chunk's is the one refused. The `cdr8` form type alone makes a + /// file the 8.01 variant, whatever its `vrsn` chunk names (R1). + pub(crate) fn version(&self) -> u16 { + match self.vrsn.flatten() { + _ if self.form_version == 801 => 801, + Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v, + Some(v) if self.form_version == 0 => v, + Some(v) if v > layout::NEWEST && self.form_version > layout::NEWEST => v, + _ => self.form_version, + } + } + + /// The warnings for data streams that were left out. + pub(crate) fn stream_warnings(&self, warn: &mut Vec) { + if let Some(s) = &self.streams { + s.warnings(warn); + } + } + + /// Split list `p` into its children, appended to the table together; their lists are queued. + fn split(&mut self, p: Pending, queue: &mut Vec, budget: &mut Budget, warn: &mut Vec) -> Result<(), Error> { + let first = self.chunks.len(); + let mut at = p.start; + let mut lists = Vec::new(); + while at < p.end { + let Some((read, next, cut)) = self.read_chunk(p.src, at, p.end, p.pool) else { + push(warn, Warning::Damaged); + break; + }; + if cut { + push(warn, Warning::Damaged); + } + at = next; + // A redirect record whose body can't be found counts as well, so that lists redirected + // to again and again can't repeat such records past the limit. + budget.take_chunk()?; + let chunk = match read { + Read::Chunk(chunk) => chunk, + Read::Lost => { + push(warn, Warning::Damaged); + continue; + } + Read::PastLimit => continue, + Read::SharedPastLimit => { + push(warn, Warning::TooDeep); + continue; + } + }; + if p.entry == 0 && chunk.id == *b"vrsn" && self.vrsn.is_none() { + let at = chunk.start as usize; + self.vrsn = Some(self.span(chunk.src, at, at + chunk.len as usize).and_then(|b| Rd::new(b).u16())); + } + if chunk.id == LIST { + lists.push(self.chunks.len()); + } + self.chunks.push(chunk); + } + let count = (self.chunks.len() - first) as u32; + if let Some(parent) = self.chunks.get_mut(p.entry) { + parent.first = first as u32; + parent.count = count; + } + for i in lists { + let Some(c) = self.chunks.get(i).copied() else { continue }; + // From version 7 a `LIST stlt` holds the style tables, not chunks (R4); its body is read + // whole (R45). Before version 7 it holds chunks. The file's own chunks, its `vrsn` + // among them, are all read before this. + if c.form == *b"stlt" && self.version() >= 700 { + continue; + } + if p.depth + 1 > budget.limits.depth { + push(warn, Warning::TooDeep); + continue; + } + let (start, end) = (c.start as usize, c.start as usize + c.len as usize); + if c.form == CMPR && p.pool.is_none() { + match self.inflate_cmpr(c.src, start, end) { + Ok((s, e, pool)) => queue.push(Pending { entry: i, src: 0, start: s, end: e, pool: Some(pool), depth: p.depth + 1 }), + Err(Error::Limit(what)) => return Err(Error::Limit(what)), + Err(_) => push(warn, Warning::Damaged), + } + } else { + queue.push(Pending { entry: i, src: c.src, start, end, pool: p.pool, depth: p.depth + 1 }); + } + } + Ok(()) + } + + /// The chunk at `at` (before `end`) of source `src`, and where the next one starts. In a + /// compressed stream the size field is an index into the size pool (R3); in a version 16+ + /// package a chunk of 16 bytes outside one is a redirect record (R27). The flag is set for a + /// list cut short at `end`. + fn read_chunk(&self, src: u32, at: usize, end: usize, pool: Option<(usize, usize)>) -> Option<(Read, usize, bool)> { + let head = self.span(src, at, at.checked_add(8)?.min(end))?; + let id: [u8; 4] = head.get(..4)?.try_into().ok()?; + let raw = u32_at(head, 4)? as usize; + let size = match pool { + None => raw, + Some((ps, pe)) => { + let off = raw.checked_mul(4)?.checked_add(ps)?; + (off.checked_add(4)? <= pe).then_some(())?; + u32_at(self.span(0, off, off + 4)?, 0)? as usize + } + }; + let body = at + 8; + // A list cut short by the end of its parent keeps the bytes it has, so the children + // before the cut are read; the caller warns that it is damaged. Other chunks are lost. + let (size, cut) = match body.checked_add(size) { + Some(e) if e <= end => (size, false), + _ if id == LIST => (end.checked_sub(body)?, true), + _ => return None, + }; + let next = (body + size + (size & 1)).min(end); + if cut { + return Some((self.chunk(id, src, body, size).map_or(Read::Lost, Read::Chunk), next, true)); + } + if self.streams.is_some() && pool.is_none() && size == REDIRECT { + let read = match self.redirect(id, src, body) { + Some(read) => read, + None if self.redirect_past_limit(src, body) => Read::PastLimit, + None => Read::Lost, + }; + return Some((read, next, false)); + } + Some((Read::Chunk(self.chunk(id, src, body, size)?), next, false)) + } + + /// Chunk `id` whose body is `len` bytes at `body` of source `src`; a list's body starts with + /// its form type. + fn chunk(&self, id: [u8; 4], src: u32, body: usize, len: usize) -> Option { + let (form, start) = if id == LIST { + let f: [u8; 4] = self.span(src, body, body.checked_add(4).filter(|_| len >= 4)?)?.try_into().ok()?; + (f, body + 4) + } else { + ([0; 4], body) + }; + let len = len - (start - body); + Some(Chunk { id, form, src, start: u32::try_from(start).ok()?, len: u32::try_from(len).ok()?, first: 0, count: 0 }) + } + + /// The chunk the redirect record at `body` of `src` stands for (R27): stream, length, offset + /// and a reserved u32. Stream `0xFFFFFFFF` holds at most 8 bytes in the record itself, after + /// the length. The body is not read again as a redirect record. `None` when the body can't + /// be found. + /// + /// A redirected list whose bytes overlap those of an earlier redirected list, in any stream of + /// the same package member, is left out, so that no list is split twice. Other chunks may + /// share bytes: each one after the first to read them takes their length from the + /// shared-bytes limit (the member limit), so that many redirects to one body can't decode it + /// without end. + fn redirect(&self, id: [u8; 4], src: u32, body: usize) -> Option { + let mut r = Rd::new(self.span(src, body, body + REDIRECT)?); + let stream = r.u32()?; + let len = r.u32()? as usize; + if stream == INLINE { + return (len <= 8).then(|| self.chunk(id, src, body + 8, len).map(Read::Chunk))?; + } + let off = r.u32()? as usize; + let streams = self.streams.as_ref()?; + let size = streams.size(stream as usize)?; + let end = off.checked_add(len).filter(|&e| e <= size)?; + let member = streams.member_of(stream as usize)?; + if id == LIST { + if !claim(&self.lists, member, off, end) { + return None; + } + } else if !claim(&self.leaves, member, off, end) { + let left = self.shared_left.get(); + if len > left { + return Some(Read::SharedPastLimit); + } + self.shared_left.set(left - len); + } + // Only a list's form type is read now; other bodies are read when the mapping asks. + self.chunk(id, stream.checked_add(1)?, off, len).map(Read::Chunk) + } + + /// Does the redirect record at `body` of `src` point into a data stream past a limit? + fn redirect_past_limit(&self, src: u32, body: usize) -> bool { + let stream = self.span(src, body, body + 4).and_then(|b| u32_at(b, 0)); + stream.is_some_and(|s| s != INLINE && self.past_limit(s.saturating_add(1))) + } + + /// Inflate the two blocks of a `LIST cmpr` body at `start..end` of `src` (R3) → the chunk + /// stream and the size pool, as ranges of source 0. + fn inflate_cmpr(&mut self, src: u32, start: usize, end: usize) -> Result<(usize, usize, (usize, usize)), Error> { + let body = self.span(src, start, end).ok_or(Error::Damaged("compressed list"))?; + let mut r = Rd::new(body); + let c1 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize; + r.skip(4).ok_or(Error::Damaged("compressed list"))?; + let c2 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize; + let block = |at: usize, len: usize| -> Result<&[u8], Error> { + let b = body.get(at..at.checked_add(len).ok_or(Error::Damaged("compressed list"))?).ok_or(Error::Damaged("compressed list"))?; + let mut h = Rd::new(b); + if h.fourcc() != Some(CPNG) || h.fourcc() != Some(CPNG_HEAD) { + return Err(Error::Damaged("compressed block")); + } + Ok(b.get(8..).unwrap_or_default()) + }; + let second_at = c1.checked_add(16).ok_or(Error::Damaged("compressed list"))?; + let (first, second) = (block(16, c1)?.to_vec(), block(second_at, c2)?.to_vec()); + let base = self.input.len(); + let stream = self.inflate(&first)?; + let pool = self.inflate(&second)?; + Ok((base + stream.0, base + stream.1, (base + pool.0, base + pool.1))) + } + + /// Inflate zlib `data` onto the end of the inflated bytes, within what is left → its range + /// there. + fn inflate(&mut self, data: &[u8]) -> Result<(usize, usize), Error> { + let at = self.inflated.len(); + let left = self.left.get(); + let reader = flate2::read::ZlibDecoder::new(data); + // One byte past what is left tells a stream that is too long from one that just fits. + let got = match reader.take((left as u64).saturating_add(1)).read_to_end(&mut self.inflated) { + Ok(n) => n, + Err(_) => { + // What a stream inflated before it failed counts toward the limit too, so that + // streams that fail late can't inflate past it again and again. + let produced = self.inflated.len().saturating_sub(at); + self.left.set(left.saturating_sub(produced)); + self.inflated.truncate(at); + return Err(Error::Damaged("compressed block")); + } + }; + if got > left { + self.inflated.truncate(at); + return Err(Error::Limit("inflated size")); + } + self.left.set(left - got); + if self.input.len().saturating_add(self.inflated.len()) > u32::MAX as usize { + return Err(Error::Limit("inflated size")); + } + Ok((at, at + got)) + } +} + +/// Take bytes `start..end` of package member `member` in `claimed`, or `false` when an earlier +/// redirect there took any of them. Empty ranges take nothing. +fn claim(claimed: &Cell>, member: usize, start: usize, end: usize) -> bool { + if start == end { + return true; + } + let mut taken = claimed.take(); + let before = taken.range(..=(member, start)).next_back().is_some_and(|(&(m, _), &e)| m == member && e > start); + let after = taken.range((member, start)..).next().is_some_and(|(&(m, s), _)| m == member && s < end); + let free = !before && !after; + if free { + taken.insert((member, start), end); + } + claimed.set(taken); + free +} + +/// Add `w` to the warnings once. +pub(crate) fn push(warn: &mut Vec, w: Warning) { + if !warn.contains(&w) { + warn.push(w); + } +} diff --git a/crates/cdr/src/styles.rs b/crates/cdr/src/styles.rs new file mode 100644 index 0000000000..e4022563c2 --- /dev/null +++ b/crates/cdr/src/styles.rs @@ -0,0 +1,258 @@ +//! The style table in a `LIST stlt` of versions 7 to 15 (R45): the fill and outline records that a +//! style gives the objects that name it and have no fill or outline argument of their own. + +use std::collections::{HashMap, HashSet}; + +use crate::Error; +use crate::bytes::{Rd, u32_at}; +use crate::limits::Budget; + +/// One style: its parent, and the fill and outline table entries it names (0: none). +#[derive(Clone, Copy)] +struct Style { + parent: u32, + fill: u32, + outline: u32, +} + +/// The styles of a drawing: for each style id, the fill and outline records it gives, its +/// parents' included. +#[derive(Default)] +pub(crate) struct Styles { + fills: HashMap, + outlines: HashMap, +} + +impl Styles { + /// The style table in body `b` of a `LIST stlt` of `version` (R45), or `None` when it doesn't + /// parse to its end. Its fill and outline entries and its styles count toward the chunks a + /// read takes. + pub(crate) fn read(b: &[u8], version: u16, budget: &mut Budget) -> Result, Error> { + let mut limit = None; + let styles = parse(b, version, &mut |n| match budget.take_chunks(n) { + Ok(()) => true, + Err(e) => { + limit = Some(e); + false + } + }); + match limit { + Some(e) => Err(e), + None => Ok(styles), + } + } + + /// The fill record that style `id` gives. + pub(crate) fn fill(&self, id: u32) -> Option { + self.fills.get(&id).copied() + } + + /// The outline record that style `id` gives. + pub(crate) fn outline(&self, id: u32) -> Option { + self.outlines.get(&id).copied() + } +} + +/// The style table in `b`. `take` is asked for each count of entries or styles before they are +/// read; a `false` stops the read. +fn parse(b: &[u8], version: u16, take: &mut dyn FnMut(usize) -> bool) -> Option { + let mut r = Rd::new(b); + let count = r.u32()? as usize; + if count == 0 { + return (r.left() == 0).then(Styles::default); + } + // Fill entries carry 48 more bytes from version 13. + let fills = table(&mut r, if version >= 1300 { 60 } else { 12 }, take)?; + let outlines = table(&mut r, 12, take)?; + // The text style tables: fonts, alignments, spacings, two tables of fixed records, bullets, + // indents, hyphenation and drop caps, and from version 8.01 one more. + skip_table(&mut r, if version >= 1000 { 60 } else { 44 })?; + skip_table(&mut r, 12)?; + skip_table(&mut r, 52)?; + skip_table(&mut r, 152)?; + skip_table(&mut r, 784)?; + let bullets = r.u32()?; + for _ in 0..bullets { + bullet(&mut r, version)?; + } + skip_table(&mut r, 28)?; + skip_table(&mut r, if version >= 1300 { 36 } else { 32 })?; + skip_table(&mut r, 28)?; + if version >= 801 { + skip_table(&mut r, 12)?; + } + // Each style is at least 32 bytes. + if count > r.left() / 32 || !take(count) { + return None; + } + let mut styles = HashMap::new(); + for _ in 0..count { + let (id, s) = style(&mut r, version)?; + styles.entry(id).or_insert(s); + } + if r.left() != 0 { + return None; + } + let mut work = 0; + Some(Styles { fills: resolve(&styles, &fills, |s| s.fill, &mut work), outlines: resolve(&styles, &outlines, |s| s.outline, &mut work) }) +} + +/// For each style, the record of `table` that its own entry names, or the nearest parent's where +/// its entry is 0. Each style is resolved once, and each path forgets only the styles on it, so a +/// chain of any length takes time in proportion to the styles; a chain that comes back to a style +/// on it, or reaches a style that isn't there, gives no record. `work` counts the styles visited +/// and forgotten. +fn resolve(styles: &HashMap, table: &HashMap, entry: impl Fn(&Style) -> u32, work: &mut usize) -> HashMap { + // `None`: resolved to no record. + let mut done: HashMap> = HashMap::new(); + let mut path = Vec::new(); + let mut on_path = HashSet::new(); + for &start in styles.keys() { + let mut id = start; + let found = loop { + *work += 1; + if let Some(&known) = done.get(&id) { + break known; + } + let Some(s) = styles.get(&id) else { break None }; + // Back at a style on this path: a cycle. + if !on_path.insert(id) { + break None; + } + path.push(id); + match entry(s) { + 0 => id = s.parent, + e => break table.get(&e).copied(), + } + }; + for id in path.drain(..) { + *work += 1; + on_path.remove(&id); + done.insert(id, found); + } + } + done.into_iter().filter_map(|(id, r)| Some((id, r?))).collect() +} + +/// A table of a u32 count and entries of `size` bytes, each a table id, 4 bytes and a record id. +fn table(r: &mut Rd, size: usize, take: &mut dyn FnMut(usize) -> bool) -> Option> { + let n = r.u32()? as usize; + if n > r.left() / size || !take(n) { + return None; + } + let mut out = HashMap::new(); + for _ in 0..n { + let e = r.bytes(size)?; + out.entry(u32_at(e, 0)?).or_insert(u32_at(e, 8)?); + } + Some(out) +} + +/// A table of a u32 count and entries of `size` bytes, passed over. +fn skip_table(r: &mut Rd, size: usize) -> Option<()> { + let n = r.u32()? as usize; + r.skip(n.checked_mul(size)?) +} + +/// A bullet record, passed over: its length depends on a u32 inside it. +fn bullet(r: &mut Rd, version: u16) -> Option<()> { + r.skip(40)?; + if version >= 1300 { + if version >= 1400 { + r.skip(4)?; + } + let more = r.u32()?; + return r.skip(if more != 0 { 68 } else { 12 }); + } + r.skip(if version >= 1000 { 28 } else { 20 })?; + let more = r.u32()?; + if more != 0 { + r.skip(8)?; + } + r.skip(8) +} + +/// A style record: its kind (u32), id, parent, 8 bytes, a name length and the name (bytes before +/// version 12, UTF-16 units from it), the fill and outline entries, then the entries of text +/// styles (kinds 2 and 3). +fn style(r: &mut Rd, version: u16) -> Option<(u32, Style)> { + let kind = r.u32()?; + let (id, parent) = (r.u32()?, r.u32()?); + r.skip(8)?; + let len = r.u32()? as usize; + r.skip(len.checked_mul(if version >= 1200 { 2 } else { 1 })?)?; + let (fill, outline) = (r.u32()?, r.u32()?); + if kind > 1 { + r.skip(if version >= 801 { 20 } else { 16 })?; + } + if kind > 2 { + r.skip(20)?; + } + Some((id, Style { parent, fill, outline })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Limits; + use crate::synth::{self, V}; + + fn read(b: &[u8], version: u16) -> Option { + Styles::read(b, version, &mut Budget::new(Limits::default())).unwrap() + } + + #[test] + fn styles_that_name_each_other_as_parents_end() { + let looped = [synth::Style { id: 0x10, parent: 0x11, fill: 0, outline: 0 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let s = read(&synth::stlt_body(V(700), &[(0x100, 1)], &[], &looped, false), 700).unwrap(); + assert_eq!((s.fill(0x10), s.outline(0x11), s.fill(0x12)), (None, None, None)); + } + + #[test] + fn a_long_chain_of_parents_reaches_the_style_that_names_an_entry() { + let mut chain = vec![synth::Style { id: 1, parent: 0, fill: 0x100, outline: 0 }]; + chain.extend((2..=500).map(|id| synth::Style { id, parent: id - 1, fill: 0, outline: 0 })); + let s = read(&synth::stlt_body(V(1100), &[(0x100, 7)], &[], &chain, false), 1100).unwrap(); + assert_eq!((s.fill(500), s.fill(250), s.outline(500)), (Some(7), Some(7), None)); + } + + /// A loop of 2,000 styles, which every walk into it follows around, leaves the walks of 20,000 + /// other styles no more work than the styles they visit. + #[test] + fn one_long_walk_does_not_slow_the_walks_after_it() { + let mut styles: HashMap = (1..=2000).map(|id| (id, Style { parent: id % 2000 + 1, fill: 0, outline: 0 })).collect(); + styles.extend((10_001..=30_000).map(|id| (id, Style { parent: 0, fill: 0x100, outline: 0 }))); + let table = HashMap::from([(0x100, 7)]); + let mut work = 0; + let fills = resolve(&styles, &table, |s| s.fill, &mut work); + assert_eq!((fills.get(&1), fills.get(&10_001), fills.len()), (None, Some(&7), 20_000)); + assert!(work <= 4 * styles.len(), "{work}"); + } + + #[test] + fn an_entry_missing_from_its_table_names_no_record() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x101, outline: 0x200 }]; + let s = read(&synth::stlt_body(V(1300), &[(0x100, 1)], &[(0x200, 2)], &styles, false), 1300).unwrap(); + assert_eq!((s.fill(0x10), s.outline(0x10)), (None, Some(2))); + } + + #[test] + fn counts_past_the_body_do_not_parse() { + let mut b = synth::stlt_body(V(900), &[], &[], &[], false); + b[..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(read(&b, 900).is_none()); + let empty = 0u32.to_le_bytes(); + assert!(read(&empty, 900).is_some()); + assert!(read(&[], 900).is_none()); + } + + #[test] + fn entries_and_styles_count_toward_the_chunk_limit() { + let styles: Vec<_> = (1..=10).map(|id| synth::Style { id, parent: 0, fill: 0x100, outline: 0 }).collect(); + let b = synth::stlt_body(V(1000), &[(0x100, 1)], &[], &styles, false); + let mut budget = Budget::new(Limits { chunks: 10, ..Limits::default() }); + assert_eq!(Styles::read(&b, 1000, &mut budget).err(), Some(Error::Limit("chunk count"))); + let mut budget = Budget::new(Limits { chunks: 11, ..Limits::default() }); + assert!(Styles::read(&b, 1000, &mut budget).is_ok_and(|s| s.is_some())); + } +} diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs new file mode 100644 index 0000000000..e109d8bf1d --- /dev/null +++ b/crates/cdr/src/synth.rs @@ -0,0 +1,1083 @@ +//! Synthetic drawings for tests and fuzz seeds, built from the layouts in `PROVENANCE.md`. Not a +//! `.cdr` writer: nothing checks that other programs open these files. + +use std::io::Write as _; + +/// A chunk or a list, before it is laid out. +#[derive(Clone, Debug)] +pub enum Node { + Chunk([u8; 4], Vec), + List([u8; 4], Vec), +} + +pub fn chunk(id: &[u8; 4], data: Vec) -> Node { + Node::Chunk(*id, data) +} + +pub fn list(form: &[u8; 4], children: Vec) -> Node { + Node::List(*form, children) +} + +fn put(out: &mut Vec, id: &[u8; 4], size: u32, body: &[u8], len: usize) { + out.extend(id); + out.extend(size.to_le_bytes()); + out.extend(body); + if len % 2 == 1 { + out.push(0); + } +} + +/// `n` laid out with real sizes. +pub fn plain(n: &Node) -> Vec { + let mut out = Vec::new(); + match n { + Node::Chunk(id, data) => put(&mut out, id, data.len() as u32, data, data.len()), + Node::List(form, kids) => { + let mut body = form.to_vec(); + body.extend(kids.iter().flat_map(plain)); + put(&mut out, b"LIST", body.len() as u32, &body, body.len()); + } + } + out +} + +/// `n` laid out for a compressed stream: each size field is an index into `pool`. +fn pooled(n: &Node, pool: &mut Vec) -> Vec { + let mut out = Vec::new(); + let (id, body) = match n { + Node::Chunk(id, data) => (*id, data.clone()), + Node::List(form, kids) => { + let mut body = form.to_vec(); + for k in kids { + body.extend(pooled(k, pool)); + } + (*b"LIST", body) + } + }; + let index = pool.len() as u32; + pool.push(body.len() as u32); + put(&mut out, &id, index, &body, body.len()); + out +} + +fn zlib(data: &[u8]) -> Vec { + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + let _ = e.write_all(data); + e.finish().unwrap_or_default() +} + +/// A `LIST cmpr` holding `children` (R3). +pub fn cmpr(children: &[Node]) -> Node { + let mut pool = Vec::new(); + let stream: Vec = children.iter().flat_map(|c| pooled(c, &mut pool)).collect(); + let sizes: Vec = pool.iter().flat_map(|s| s.to_le_bytes()).collect(); + let block = |raw: &[u8]| { + let mut b = b"CPng".to_vec(); + b.extend([1, 0, 4, 0]); + b.extend(zlib(raw)); + b + }; + let (b1, b2) = (block(&stream), block(&sizes)); + let mut body = Vec::new(); + for (c, u) in [(b1.len(), stream.len()), (b2.len(), sizes.len())] { + body.extend((c as u32).to_le_bytes()); + body.extend((u as u32).to_le_bytes()); + } + body.extend(b1); + body.extend(b2); + Node::Chunk(*b"LIST", [b"cmpr".to_vec(), body].concat()) +} + +/// The form type letter of `version` (hundreds) (R1). +pub fn form(version: u16) -> [u8; 4] { + let n = (version / 100) as u8; + let c = match n { + // Version 3 has a space where later versions have their character. + 3 => b' ', + 0..=9 => b'0' + n, + 10..=17 => b'A' + n - 10, + _ => b'J' + n - 18, + }; + [b'C', b'D', b'R', c] +} + +/// A RIFF file of `version` holding `children`. +pub fn riff(version: u16, children: &[Node]) -> Vec { + let mut body = form(version).to_vec(); + for c in children { + body.extend(match c { + // A prebuilt `LIST cmpr` carries its own form type. + Node::Chunk(id, data) if id == b"LIST" => { + let mut o = Vec::new(); + put(&mut o, id, data.len() as u32, data, data.len()); + o + } + _ => plain(c), + }); + } + let mut out = b"RIFF".to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + out +} + +/// Field writers for one version. +#[derive(Clone, Copy, Debug)] +pub struct V(pub u16); + +impl V { + pub fn short(self) -> bool { + self.0 < 600 + } + + pub fn word(self, v: usize) -> Vec { + if self.short() { (v as u16).to_le_bytes().to_vec() } else { (v as u32).to_le_bytes().to_vec() } + } + + /// Rectangle coordinates of `w` × `h` points with corners of `radius` points: coordinates + /// before version 15 (R15), from 15 f64 sizes and radii as shares of half the shorter side + /// (R29). + pub fn rect(self, w: f64, h: f64, radius: f64) -> Vec { + if self.0 < 1500 { + let n = if self.0 >= 900 { 4 } else { 1 }; + let mut out = [self.coord(w), self.coord(h)].concat(); + for _ in 0..n { + out.extend(self.coord(radius)); + } + return out; + } + let units = |pt: f64| pt / 72.0 * 254_000.0; + let mut out = Vec::new(); + for v in [units(w), units(h), 1.0, 1.0] { + out.extend(v.to_le_bytes()); + } + out.extend([0; 8]); + let share = radius / (w.abs().min(h.abs()) / 2.0); + for k in 0..4 { + if k > 0 { + out.extend([0; 16]); + } + out.extend(share.to_le_bytes()); + } + out + } + + /// A length in points as a coordinate. + pub fn coord(self, pt: f64) -> Vec { + if self.short() { + ((pt / 72.0 * 1000.0).round() as i16).to_le_bytes().to_vec() + } else { + ((pt / 72.0 * 254_000.0).round() as i32).to_le_bytes().to_vec() + } + } + + pub fn angle(self, deg: f64) -> Vec { + if self.short() { ((deg * 10.0).round() as i16).to_le_bytes().to_vec() } else { ((deg * 1_000_000.0).round() as i32).to_le_bytes().to_vec() } + } + + /// A `loda` record of object type `kind` (R6): header, arguments, offsets, then the types in + /// reverse. + pub fn loda(self, kind: u32, args: &[(u32, Vec)]) -> Vec { + let w = if self.short() { 2 } else { 4 }; + let head = 5 * w; + let mut body: Vec = Vec::new(); + let mut offsets = Vec::new(); + for (_, a) in args { + offsets.push(head + body.len()); + body.extend(a); + } + offsets.push(head + body.len()); + let offsets_at = head + body.len(); + let types_at = offsets_at + offsets.len() * w; + let total = types_at + args.len() * w; + let mut out = Vec::new(); + for f in [total, args.len(), offsets_at, types_at, kind as usize] { + out.extend(self.word(f)); + } + out.extend(body); + for o in offsets { + out.extend(self.word(o)); + } + for (t, _) in args.iter().rev() { + out.extend(self.word(*t as usize)); + } + out + } + + /// A `trfd` of `matrices` `[a, b, c, d, e, f]` with offsets in points (R8); before version 5 + /// each matrix is in fixed point (R37). + pub fn trfd(self, matrices: &[[f64; 6]]) -> Vec { + let w = if self.short() { 2 } else { 4 }; + let head = 3 * w; + let table = head; + let mut entries = Vec::new(); + let mut offsets = Vec::new(); + // The table holds one offset more than the entries: the record's end (R51). + let first = table + (matrices.len() + 1) * w; + for m in matrices { + offsets.push(first + entries.len()); + if self.0 >= 1300 { + entries.extend([0; 8]); + } + entries.extend(8u16.to_le_bytes()); + if !self.short() { + entries.extend([0; 6]); + } + if self.0 < 500 { + entries.extend(fixed_matrix(m)); + continue; + } + let unit = if self.short() { 1000.0 / 72.0 } else { 254_000.0 / 72.0 }; + let [a, b, c, d, e, f] = *m; + for v in [a, c, e * unit, b, d, f * unit] { + entries.extend(v.to_le_bytes()); + } + } + offsets.push(first + entries.len()); + let mut out = Vec::new(); + for f in [first + entries.len(), matrices.len(), table] { + out.extend(self.word(f)); + } + for o in offsets { + out.extend(self.word(o)); + } + out.extend(entries); + out + } + + /// A curve's point list (R16). + pub fn points(self, pts: &[(f64, f64, u8)]) -> Vec { + let mut out = (pts.len() as u32).to_le_bytes().to_vec(); + for (x, y, _) in pts { + out.extend(self.coord(*x)); + out.extend(self.coord(*y)); + } + out.extend(pts.iter().map(|p| p.2)); + out + } + + /// A uniform fill record (R11) of 12-byte color `color`. + pub fn fill(self, id: u32, color: &[u8; 12]) -> Vec { + let mut out = id.to_le_bytes().to_vec(); + if self.0 >= 1300 { + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(color); + props.extend([0, 0, 0, 0, 0]); + let mut solid = 1300u32.to_le_bytes().to_vec(); + solid.extend((props.len() as u32).to_le_bytes()); + solid.extend(props); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(solid); + out.extend(1300u32.to_le_bytes()); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + } else { + out.extend(1u16.to_le_bytes()); + out.extend([0, 0]); + out.extend(color); + } + out + } + + /// An outline record (R12) of `pen`, `color` and `dashes`. + pub fn outline(self, id: u32, pen: Pen, color: &[u8; 12], dashes: &[u16]) -> Vec { + let Pen { line_type, width, cap, join } = pen; + let mut out = id.to_le_bytes().to_vec(); + if self.0 >= 1300 { + out.extend(1u32.to_le_bytes()); + out.extend(0u32.to_le_bytes()); + } + for f in [line_type, cap, join] { + out.extend(f.to_le_bytes()); + } + let v = self.0; + out.extend(vec![0; if (600..1300).contains(&v) { 2 } else { 0 }]); + out.extend(self.coord(width)); + out.extend(100u16.to_le_bytes()); + out.extend(vec![0; if self.short() { 0 } else { 2 }]); + out.extend(self.angle(0.0)); + out.extend(vec![ + 0; + if v >= 1300 { + 46 + } else if self.short() { + 0 + } else { + 52 + } + ]); + out.extend(color); + out.extend(vec![0; if self.short() { 10 } else { 16 }]); + out.extend((dashes.len() as u16).to_le_bytes()); + for d in dashes { + out.extend(d.to_le_bytes()); + } + out.extend([0; 32]); + out + } +} + +/// An outline's line type (bit 0: none), width in points, cap and join. +#[derive(Clone, Copy, Debug)] +pub struct Pen { + pub line_type: u16, + pub width: f64, + pub cap: u16, + pub join: u16, +} + +/// A 12-byte color record (R14) of `model` and its four value bytes. +pub fn color(model: u16, v: [u8; 4]) -> [u8; 12] { + let mut c = [0; 12]; + c[..2].copy_from_slice(&model.to_le_bytes()); + c[8..].copy_from_slice(&v); + c +} + +/// A version 4 color (R36): `model` and its four values as u16, then 2 bytes. +pub fn color4(model: u16, v: [u16; 4]) -> [u8; 12] { + let mut c = [0; 12]; + c[..2].copy_from_slice(&model.to_le_bytes()); + for (k, x) in v.into_iter().enumerate() { + c[2 + 2 * k..4 + 2 * k].copy_from_slice(&x.to_le_bytes()); + } + c +} + +/// A color of versions 1 to 3 (R36): `model` and its four value bytes. +pub fn color3(model: u8, v: [u8; 4]) -> [u8; 5] { + [model, v[0], v[1], v[2], v[3]] +} + +/// A matrix `[a, b, c, d, e, f]` with offsets in points as six i32 `a c tx b d ty`: the factors in +/// 16.16 fixed point, the offsets in 1/1000 inch (R37). +fn fixed_matrix(m: &[f64; 6]) -> Vec { + let [a, b, c, d, e, f] = *m; + let fixed = |v: f64| (v * 65536.0).round() as i32; + let units = |pt: f64| (pt / 72.0 * 1000.0).round() as i32; + [fixed(a), fixed(c), units(e), fixed(b), fixed(d), units(f)].iter().flat_map(|v| v.to_le_bytes()).collect() +} + +/// The transforms argument (100) of a version 3 object or group (R33): one matrix entry for each +/// of `matrices` `[a, b, c, d, e, f]` with offsets in points, applied in the order given. +pub fn transforms3(matrices: &[[f64; 6]]) -> Vec { + let first = 4 + 10 * matrices.len(); + let mut out = vec![0, 0]; + out.extend((matrices.len() as u16).to_le_bytes()); + for i in 0..matrices.len() { + out.extend(0x8cu16.to_le_bytes()); + out.extend([0; 4]); + out.extend(((first + 24 * i) as u16).to_le_bytes()); + out.extend([0; 2]); + } + out.extend(matrices.iter().flat_map(fixed_matrix)); + out +} + +/// The fill argument (20) of a version 3 object (R34): the type byte, then `color` for a uniform +/// fill (type 1). +pub fn fill3(kind: u8, color: &[u8]) -> Vec { + let mut out = vec![kind]; + out.extend(color); + out +} + +/// The outline argument (10) of a version 3 object (R35) of `pen`, `color` and `dashes`; bit 0 of +/// its flags is set unless the pen's line type says no outline. +pub fn outline3(pen: Pen, color: [u8; 5], dashes: &[u8]) -> Vec { + let v = V(300); + let mut out = vec![u8::from(pen.line_type & 1 == 0)]; + out.extend(v.coord(pen.width)); + out.extend(100u16.to_le_bytes()); + out.extend(v.angle(0.0)); + out.extend(color); + out.extend([0; 7]); + out.push(dashes.len() as u8); + let mut area = dashes.to_vec(); + area.resize(10, 0); + out.extend(area); + out.extend(pen.join.to_le_bytes()); + out.extend(pen.cap.to_le_bytes()); + out.extend([0; 8]); + out +} + +/// A version 3 group (R33): its own `lobj` with the transforms that place `objects`, then the +/// objects. +pub fn group3(matrices: &[[f64; 6]], objects: Vec) -> Node { + let mut kids = vec![chunk(b"flgs", vec![0, 0, 0, 0x10]), chunk(b"lobj", V(300).loda(0, &[(100, transforms3(matrices))]))]; + kids.extend(objects); + list(b"grp ", kids) +} + +/// An object list: flags, then a `lgob` list with the `loda` and an optional transform in a `trfl` +/// list (R22). A version 3 object is a `lobj` whose type counts from 0 (R32) and whose transform is +/// its argument 100 (R33). +pub fn object(v: V, kind: u32, args: &[(u32, Vec)], matrix: Option<[f64; 6]>) -> Node { + if v.0 < 400 { + let kind = if (1..=5).contains(&kind) { kind - 1 } else { kind }; + let mut args = args.to_vec(); + args.extend(matrix.map(|m| (100, transforms3(&[m])))); + return list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08]), chunk(b"lobj", v.loda(kind, &args))]); + } + let mut own = vec![chunk(b"loda", v.loda(kind, args))]; + if let Some(m) = matrix { + own.push(list(b"trfl", vec![chunk(b"trfd", v.trfd(&[m]))])); + } + list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08]), list(b"lgob", own)]) +} + +/// A layer list of `kind` flags named `name` holding `objects`, its `loda` in a `lgob` list (R22), +/// with the object type that layers of such flags have in sample files (R19). +pub fn layer(v: V, flags: [u8; 4], name: &str, objects: Vec) -> Node { + let kind = match flags { + [b0, ..] if (b0 & 0x0f == 0x0a || b0 & 0x0f == 0x02) && b0 & 0x10 != 0 => 11, + [b0, ..] if b0 & 0x0f == 0x0a || b0 & 0x0f == 0x02 => 12, + [b0, _, b2, _] if b0 & 0x0f == 0x08 && b2 != 0 => 17, + [0, 1, 1, _] => 17, + _ => 0, + }; + // Version 3 counts its types from 0, one less (R32). + let kind = if v.0 < 400 && kind > 0 { kind - 1 } else { kind }; + layer_of_type(v, flags, kind, name, objects) +} + +/// A layer list as [`layer`] writes it, with the object type `kind` in its `loda`. +pub fn layer_of_type(v: V, flags: [u8; 4], kind: u32, name: &str, objects: Vec) -> Node { + let name: Vec = + if v.0 >= 1200 { name.encode_utf16().chain([0]).flat_map(|u| u.to_le_bytes()).collect() } else { name.bytes().chain([0]).collect() }; + let mut kids = vec![chunk(b"flgs", flags.to_vec()), list(b"lgob", vec![chunk(b"loda", v.loda(kind, &[(1000, name)]))])]; + kids.extend(objects); + list(b"layr", kids) +} + +/// A page list: flags (byte 2 set for the master page), then its layers in a `gobj` list (R22). +pub fn page(master: bool, layers: Vec) -> Node { + list(b"page", vec![chunk(b"flgs", vec![0, 0, u8::from(master), 0x90]), list(b"gobj", layers)]) +} + +/// The `mcfg` chunk of `version` with a page of `w` × `h` points (R10); in version 3, 2 bytes and +/// the page's top left and bottom right corners (R38). +pub fn mcfg(v: V, w: f64, h: f64) -> Node { + if v.0 < 400 { + let mut b = vec![0; 2]; + b.extend([v.coord(-w / 2.0), v.coord(h / 2.0), v.coord(w / 2.0), v.coord(-h / 2.0)].concat()); + b.extend([0; 16]); + return chunk(b"mcfg", b); + } + let skip = if v.0 >= 1300 { + 12 + } else if v.0 >= 900 { + 4 + } else if (600..700).contains(&v.0) { + 28 + } else { + 0 + }; + let mut b = vec![0; skip]; + b.extend(v.coord(w)); + b.extend(v.coord(h)); + b.extend([0; 16]); + chunk(b"mcfg", b) +} + +/// A style of a [`stlt_body`]: its id, its parent's id, and its fill and outline table entries. +#[derive(Clone, Copy, Debug)] +pub struct Style { + pub id: u32, + pub parent: u32, + pub fill: u32, + pub outline: u32, +} + +/// The body of a `LIST stlt` of `v` (R45): the style count, the fill table (`(entry, fild id)`) and +/// the outline table (`(entry, outl id)`), the text style tables (each with one record when +/// `text`), then `styles` as styles of kind 1, and when `text` a style of kind 2 and one of kind 3. +pub fn stlt_body(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style], text: bool) -> Vec { + let version = v.0; + let u32s = |vals: &[u32]| -> Vec { vals.iter().flat_map(|x| x.to_le_bytes()).collect() }; + let count = styles.len() + if text { 2 } else { 0 }; + let mut b = u32s(&[count as u32]); + // A table without styles holds nothing else. + if count == 0 { + return b; + } + for (table, size) in [(fills, if version >= 1300 { 60 } else { 12 }), (outlines, 12)] { + b.extend(u32s(&[table.len() as u32])); + for (entry, record) in table { + let mut e = u32s(&[*entry, 0, *record]); + e.resize(size, 0); + b.extend(e); + } + } + let n = u32::from(text); + let fixed = |size: usize| -> Vec { + let mut t = n.to_le_bytes().to_vec(); + t.extend(vec![0x5a; size * n as usize]); + t + }; + // Fonts, alignments, spacings and two tables of fixed records. + for size in [if version >= 1000 { 60 } else { 44 }, 12, 52, 152, 784] { + b.extend(fixed(size)); + } + // One bullet, whose u32 inside asks for the longer form. + b.extend(n.to_le_bytes()); + if text { + b.extend([0x5a; 40]); + if version >= 1300 { + if version >= 1400 { + b.extend([0x5a; 4]); + } + b.extend(u32s(&[1])); + b.extend([0x5a; 68]); + } else { + b.extend(vec![0x5a; if version >= 1000 { 28 } else { 20 }]); + b.extend(u32s(&[1])); + b.extend([0x5a; 16]); + } + } + // Indents, hyphenation, drop caps, and from version 8.01 one more table. + for size in [28, if version >= 1300 { 36 } else { 32 }, 28] { + b.extend(fixed(size)); + } + if version >= 801 { + b.extend(fixed(12)); + } + let text_styles = [(2, Style { id: 0x7f02, parent: 0, fill: 0, outline: 0 }), (3, Style { id: 0x7f03, parent: 0x7f02, fill: 0, outline: 0 })]; + let all = styles.iter().map(|s| (1u32, *s)).chain(text_styles.into_iter().filter(|_| text)); + for (kind, s) in all { + b.extend(u32s(&[kind, s.id, s.parent, 1, 1])); + if version >= 1200 { + b.extend(u32s(&[7])); + b.extend("Graphic".encode_utf16().flat_map(u16::to_le_bytes)); + } else { + b.extend(u32s(&[8])); + b.extend(b"Graphic\0"); + } + b.extend(u32s(&[s.fill, s.outline])); + if kind > 1 { + b.extend(vec![0; if version >= 801 { 20 } else { 16 }]); + } + if kind > 2 { + b.extend([0; 20]); + } + } + b +} + +/// A `LIST stlt` of [`stlt_body`]. +pub fn stlt(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style], text: bool) -> Node { + Node::Chunk(*b"LIST", [b"stlt".to_vec(), stlt_body(v, fills, outlines, styles, text)].concat()) +} + +/// A `LIST clpt` of clipped groups (R46): each a `LIST grp ` with its `spnd` id, then its objects. +pub fn clpt(groups: Vec<(u32, Vec)>) -> Node { + let groups = groups + .into_iter() + .map(|(id, objects)| { + let mut kids = vec![chunk(b"spnd", id.to_le_bytes().to_vec())]; + kids.extend(objects); + list(b"grp ", kids) + }) + .collect(); + list(b"clpt", groups) +} + +/// The container argument (8005) naming clipped group `id` (R46), laid out as sample files lay it +/// out. +pub fn container(id: u32) -> (u32, Vec) { + (8005, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect()) +} + +/// The argument 8000 of a uniform transparency from version 13 (R47): one record of version 1300 +/// whose 117-byte body holds `percent` at byte 61 and `merge` at byte 77. +pub fn transparency(percent: f64, merge: u8) -> (u32, Vec) { + let mut body = vec![0; 117]; + body[61..69].copy_from_slice(&percent.to_le_bytes()); + body[77] = merge; + let mut out = 1300u32.to_le_bytes().to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + (8000, out) +} + +/// A property list (R11, R12) of 12-byte color `color` and, when `name` is given, a type 8 +/// property with that library name. +pub fn properties(color: &[u8; 12], name: Option<&str>) -> Vec { + let mut out = vec![1]; + out.extend(12u32.to_le_bytes()); + out.extend(color); + if let Some(name) = name { + let mut body = vec![0; 16]; + body.extend((name.encode_utf16().count() as u32).to_le_bytes()); + body.extend(name.encode_utf16().flat_map(u16::to_le_bytes)); + out.push(8); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + } + out.extend([0, 0, 0, 0, 0]); + out +} + +/// `n` (an object, group or layer list) with its `flgs` chunk replaced by `flags` (R19). +pub fn flagged(n: Node, flags: [u8; 4]) -> Node { + match n { + Node::List(form, kids) => { + let kids = kids + .into_iter() + .map(|k| if matches!(&k, Node::Chunk(id, _) if id == b"flgs") { chunk(b"flgs", flags.to_vec()) } else { k }) + .collect(); + Node::List(form, kids) + } + chunk => chunk, + } +} + +/// A RIFF drawing of `version` (7 to 13) with a style table, a clipping container and a lens: a rectangle +/// that takes its fill and outline from its style, a container that clips two rectangles, one +/// with an outline behind the fill, a rectangle with a lens, a hidden and locked rectangle with a +/// winding flag and a uniform transparency, and a hidden group whose rectangle's outline names a +/// library color from version 13; compressed when `compress`. Before version 7, the [`sample`]. +pub fn feature_sample(version: u16, compress: bool) -> Vec { + if version < 700 { + return sample(version, false); + } + let v = V(version); + let black = color(2, [0, 0, 0, 100]); + let rect = |w: f64, extra: Vec<(u32, Vec)>, at: f64| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + object(v, 1, &args, Some([1.0, 0.0, 0.0, 1.0, at, at])) + }; + let style = (200, 0x10u32.to_le_bytes().to_vec()); + let clipped = + vec![rect(30.0, vec![style.clone()], 10.0), rect(30.0, vec![(10, 3u32.to_le_bytes().to_vec()), (20, 1u32.to_le_bytes().to_vec())], -10.0)]; + // From version 13 outline 4 names a library color in a record of type 2 (R12). + let mut named = v.outline(4, Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &color(25, [7, 0, 100, 0]), &[]); + if version >= 1300 { + let props = properties(&color(5, [0, 0, 255, 0]), Some("Sky Blue")); + let mut record = 2u32.to_le_bytes().to_vec(); + record.extend((props.len() as u32).to_le_bytes()); + record.extend(props); + named.splice(4..4, record); + } + let doc = list( + b"doc ", + vec![ + mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(b"fild", v.fill(1, &color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, Pen { line_type: 4, width: 2.0, cap: 1, join: 1 }, &black, &[3, 1])), + chunk(b"outl", v.outline(3, Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[])), + chunk(b"outl", named), + ], + ), + stlt(v, &[(0x100, 1)], &[(0x200, 2)], &[Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }], true), + clpt(vec![(7, clipped)]), + ], + ); + let objects = vec![ + rect(20.0, vec![style.clone()], 0.0), + rect(40.0, vec![style.clone(), container(7)], 50.0), + rect(20.0, vec![style.clone(), (8000, vec![1, 0, 0, 0])], -50.0), + // Hidden and locked, filled nonzero, 25% transparent with merge mode 9 (R19, R47, R52). + flagged(rect(10.0, vec![style.clone(), (14001, vec![1, 0, 0, 0]), transparency(25.0, 9)], 80.0), [0x10, 1, 0, 0x08]), + list(b"grp ", vec![chunk(b"flgs", vec![0, 1, 0, 0x10]), rect(10.0, vec![(10, 4u32.to_le_bytes().to_vec())], -80.0)]), + ]; + let page = page(false, vec![layer(v, [0, 0, 0, 0x98], "Art", objects)]); + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + if compress { + body.push(cmpr(&[doc, page])); + } else { + body.extend([doc, page]); + } + riff(version, &body) +} + +/// A file of `version` holding `content` as the program of that version saves it: a RIFF file +/// before 14, then a package (R25, R26). +pub fn file_of(version: u16, content: Vec) -> Vec { + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(content); + match version { + ..1400 => riff(version, &body), + 1400..1600 => package14(riff(version, &body), false), + _ => package16(version, &body, false, &[]), + } +} + +/// The document list and pages of the [`sample`] of `version`. +pub fn sample_content(version: u16) -> Vec { + let v = V(version); + // Before version 5 the sample's colors are CMYK in percent, model 1 (R36). + let (red, black) = + if version < 500 { (color4(1, [0, 100, 100, 0]), color4(1, [0, 0, 0, 100])) } else { (color(5, [0, 0, 255, 0]), color(2, [0, 0, 0, 100])) }; + let (round, none) = (Pen { line_type: 0, width: 2.0, cap: 1, join: 1 }, Pen { line_type: 1, width: 1.0, cap: 0, join: 0 }); + let mut settings = vec![mcfg(v, 612.0, 792.0)]; + // Version 3 keeps fills and outlines in the objects (R34, R35). + if version >= 400 { + settings.push(list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &red))])); + settings.push(list(b"otlt", vec![chunk(b"outl", v.outline(2, round, &black, &[])), chunk(b"outl", v.outline(3, none, &black, &[]))])); + } + let doc = list(b"doc ", settings); + // Fill 1 is red and 0 none; outline 2 is 2 pt with round caps and joins, 3 none. + let style = |fill: u32, outline: u32| { + if version >= 400 { + return vec![(20, fill.to_le_bytes().to_vec()), (10, outline.to_le_bytes().to_vec())]; + } + let fill = if fill == 1 { fill3(1, &color3(1, [0, 100, 100, 0])) } else { fill3(0, &[]) }; + vec![(20, fill), (10, outline3(if outline == 2 { round } else { none }, color3(1, [0, 0, 0, 100]), &[]))] + }; + let mut rect_args = style(1, 2); + rect_args.push((30, v.rect(100.0, 50.0, 5.0))); + let mut ellipse_args = style(1, 3); + ellipse_args.push((30, [v.coord(40.0), v.coord(-40.0), v.angle(0.0), v.angle(0.0), v.word(0)].concat())); + let mut curve_args = style(0, 2); + curve_args.push((30, v.points(&[(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0xC0), (20.0, 50.0, 0xC0), (0.0, 50.0, 0x88)]))); + let mut arc_args = style(0, 2); + arc_args.push((30, [v.coord(30.0), v.coord(30.0), v.angle(0.0), v.angle(90.0), v.word(1)].concat())); + let side = POLYGON_SIDE; + let mut poly_args = style(1, 2); + poly_args.push((30, v.points(&[(0.0, side, 0x0C), (side * 0.587, side * 0.809, 0x44), (side * 0.951, side * 0.309, 0x44)]))); + let mut poly = if version >= 1300 { vec![] } else { vec![0; 4] }; + poly.extend(5u32.to_le_bytes()); + poly.extend([0; 8]); + if version >= 1300 { + poly.extend([0; 4]); + } + poly.extend(0.05f64.to_le_bytes()); + poly.extend(0.05f64.to_le_bytes()); + poly.extend([v.coord(0.0), v.coord(0.0)].concat()); + poly_args.push((11000, poly)); + let art = layer( + v, + [0, 0, 0, 0x98], + "Art", + vec![ + object(v, 1, &rect_args, Some([1.0, 0.0, 0.0, 1.0, -100.0, 100.0])), + object(v, 2, &ellipse_args, Some([1.0, 0.0, 0.0, 1.0, 50.0, -50.0])), + object(v, 3, &curve_args, None), + list(b"grp ", vec![chunk(b"flgs", vec![0, 0, 0, 0x10]), object(v, 0x14, &poly_args, None), object(v, 2, &arc_args, None)]), + object(v, 4, &[(30, [v.coord(0.0), v.coord(0.0)].concat())], None), + ], + ); + let mut guide = vec![0; 12]; + guide.extend((90_000_000i32).to_le_bytes()); + guide.extend([v.coord(36.0), v.coord(0.0), v.coord(36.0), v.coord(100.0), v.coord(36.0), v.coord(0.0)].concat()); + let guides = layer(v, [0x0a, 0, 1, 0x98], "Guides", vec![object(v, 0x16, &[(16000, guide)], None)]); + let desktop = + layer(v, [0x08, 0, 1, 0x98], "Desktop", vec![object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], Some([1.0, 0.0, 0.0, 1.0, 400.0, 0.0]))]); + let pages = vec![page(true, vec![guides, desktop]), page(false, vec![art])]; + std::iter::once(doc).chain(pages).collect() +} + +/// A drawing of `version` with one page of each kind of object this reader reads, a text object +/// it doesn't, a master page with a guideline and a desktop object; compressed (version 7 on) +/// when `compress`. +pub fn sample(version: u16, compress: bool) -> Vec { + let content = sample_content(version); + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + if compress { + body.push(cmpr(&content)); + } else { + body.extend(content); + } + riff(version, &body) +} + +/// The sample of `version` as the program of that version saves it: a RIFF file before 14, then +/// a package (R25, R26); `compress` compresses the RIFF stream before 16 and deflates the package +/// members. +pub fn sample_file(version: u16, compress: bool) -> Vec { + match version { + ..1400 => sample(version, compress), + 1400..1600 => package14(sample(version, compress), compress), + _ => { + // The full version chunk comes first from 16; the reader doesn't use it. + let fver: Vec = [u32::from(version), 1, 0, u32::from(version / 100)].iter().flat_map(|v| v.to_le_bytes()).collect(); + let mut body = vec![chunk(b"fver", fver), chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(sample_content(version)); + package16(version, &body, compress, &[]) + } + } +} + +/// One member of a synthetic ZIP archive. +#[derive(Clone, Debug)] +pub struct Member { + pub name: String, + pub data: Vec, + pub deflate: bool, +} + +fn deflate(data: &[u8]) -> Vec { + let mut e = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); + let _ = e.write_all(data); + e.finish().unwrap_or_default() +} + +/// A ZIP archive of `members`, stored or deflated, with `comment` after the end record (R24). +pub fn zip(members: &[Member], comment: &[u8]) -> Vec { + let (mut out, mut dir) = (Vec::new(), Vec::new()); + for m in members { + let packed = if m.deflate { deflate(&m.data) } else { m.data.clone() }; + let method: u16 = if m.deflate { 8 } else { 0 }; + // Version needed, flags, method, time, date, CRC-32, packed and full sizes, name length. + let mut common = Vec::new(); + common.extend(20u16.to_le_bytes()); + common.extend(0u16.to_le_bytes()); + common.extend(method.to_le_bytes()); + common.extend([0; 4]); + common.extend(crc32fast::hash(&m.data).to_le_bytes()); + common.extend((packed.len() as u32).to_le_bytes()); + common.extend((m.data.len() as u32).to_le_bytes()); + common.extend((m.name.len() as u16).to_le_bytes()); + let at = out.len() as u32; + out.extend(0x0403_4b50u32.to_le_bytes()); + out.extend(&common); + out.extend(0u16.to_le_bytes()); + out.extend(m.name.as_bytes()); + out.extend(&packed); + dir.extend(0x0201_4b50u32.to_le_bytes()); + dir.extend(20u16.to_le_bytes()); + dir.extend(&common); + // Extra and comment lengths, disk, internal and external attributes, header offset. + dir.extend([0; 12]); + dir.extend(at.to_le_bytes()); + dir.extend(m.name.as_bytes()); + } + let dir_at = out.len() as u32; + let n = members.len() as u16; + out.extend(&dir); + out.extend(0x0605_4b50u32.to_le_bytes()); + out.extend([0; 4]); + out.extend(n.to_le_bytes()); + out.extend(n.to_le_bytes()); + out.extend((dir.len() as u32).to_le_bytes()); + out.extend(dir_at.to_le_bytes()); + out.extend((comment.len() as u16).to_le_bytes()); + out.extend(comment); + out +} + +/// A version 14 or 15 package: the RIFF file `riff` as `content/riffData.cdr` (R25). +pub fn package14(riff: Vec, deflate: bool) -> Vec { + zip(&[Member { name: "content/riffData.cdr".into(), data: riff, deflate }], b"") +} + +/// A version 16+ package of a drawing of `version` holding `children` (R26, R27): the chunk tree +/// in `content/root.dat`, each chunk body of more than 8 bytes moved to a data stream (the +/// document's and other chunks' to `data1.dat`, each page's to `page.dat`, each other list's +/// to a stream named after its form type) behind a redirect record, and shorter bodies kept in +/// theirs. Lists stay in the tree. `extra` members are added to the archive. +pub fn package16(version: u16, children: &[Node], deflate: bool, extra: &[Member]) -> Vec { + package16_with(version, children, deflate, extra, &[]) +} + +/// [`package16`], moving the lists whose form types are in `moved_lists` whole into their stream. +pub fn package16_with(version: u16, children: &[Node], deflate: bool, extra: &[Member], moved_lists: &[[u8; 4]]) -> Vec { + let mut members = package16_members(version, children, deflate, moved_lists); + members.extend(extra.iter().cloned()); + zip(&members, b"") +} + +/// The members of a [`package16_with`] archive. +pub fn package16_members(version: u16, children: &[Node], deflate: bool, moved_lists: &[[u8; 4]]) -> Vec { + let mut streams: Vec<(String, Vec)> = vec![("data1.dat".into(), Vec::new())]; + let mut body = form(version).to_vec(); + for c in children { + let s = match c { + Node::List(f, _) if *f != *b"doc " => { + let name = if *f == *b"page" { format!("page{}", streams.len()) } else { String::from_utf8_lossy(f).trim().to_string() }; + streams.push((format!("{name}.dat"), Vec::new())); + streams.len() - 1 + } + _ => 0, + }; + body.extend(redirected(c, s, &mut streams, moved_lists)); + } + let mut root = b"RIFF".to_vec(); + root.extend((body.len() as u32).to_le_bytes()); + root.extend(body); + let list: Vec = streams.iter().map(|(n, _)| n.clone()).collect(); + let mut members = vec![ + Member { name: "content/root.dat".into(), data: root, deflate }, + Member { name: "content/dataFileList.dat".into(), data: list.join("\n").into_bytes(), deflate }, + ]; + members.extend(streams.into_iter().map(|(n, data)| Member { name: format!("content/data/{n}"), data, deflate })); + members +} + +/// `n` laid out for `root.dat`, its bodies moved into stream `s`. +fn redirected(n: &Node, s: usize, streams: &mut [(String, Vec)], moved_lists: &[[u8; 4]]) -> Vec { + let mut out = Vec::new(); + match n { + Node::List(f, kids) if !moved_lists.contains(f) => { + let mut body = f.to_vec(); + body.extend(kids.iter().flat_map(|k| redirected(k, s, streams, moved_lists))); + put(&mut out, b"LIST", body.len() as u32, &body, body.len()); + } + _ => { + // A moved list's children are laid out in the stream by the same rule. + let (id, data) = match n { + Node::Chunk(id, data) => (*id, data.clone()), + Node::List(f, kids) => { + let mut body = f.to_vec(); + for k in kids { + body.extend(redirected(k, s, streams, moved_lists)); + } + (*b"LIST", body) + } + }; + let mut rec = Vec::new(); + if data.len() <= 8 && id != *b"LIST" { + rec.extend(u32::MAX.to_le_bytes()); + rec.extend((data.len() as u32).to_le_bytes()); + rec.extend(&data); + rec.resize(16, 0); + } else { + let Some((_, stream)) = streams.get_mut(s) else { return out }; + rec.extend((s as u32).to_le_bytes()); + rec.extend((data.len() as u32).to_le_bytes()); + rec.extend((stream.len() as u32).to_le_bytes()); + rec.extend(0u32.to_le_bytes()); + stream.extend(&data); + } + put(&mut out, &id, 16, &rec, 16); + } + } + out +} + +/// The radius the base curve of a polygon lies on, 1000 mm, in points (R18). +pub const POLYGON_SIDE: f64 = 1000.0 / 25.4 * 72.0; + +/// The shape of a drawn object in a file of version 1 or 2 (R43, R44), sizes in points. +#[derive(Clone, Debug)] +pub enum WlShape { + Rect { + w: f64, + h: f64, + radius: f64, + }, + /// The two angle fields are written as given. + Ellipse { + w: f64, + h: f64, + angles: (i16, i16), + }, + /// Points with their type bytes, as [`V::points`] takes them. + Curve(Vec<(f64, f64, u8)>), + Text, +} + +/// A drawn object's record of a version 1 file (R42, R43, R44): `shape` placed by `matrix` +/// `[a, b, c, d, e, f]` with offsets in points, a uniform fill of `fill` and an outline of a width +/// in points and a color. The record's point holds the matrix's x offset and its `ty` the y +/// offset. [`wl_file`] moves the fill and the shape to their places in a version 2 file. +pub fn wl_object(shape: WlShape, matrix: [f64; 6], fill: Option<[u8; 5]>, outline: Option<(f64, [u8; 5])>) -> Vec { + let v = V(300); + let (kind, body): (u8, Vec) = match shape { + WlShape::Rect { w, h, radius } => (0, [v.coord(w), v.coord(h), v.coord(radius), vec![0; 2]].concat()), + WlShape::Ellipse { w, h, angles } => (1, [v.coord(w), v.coord(h), angles.0.to_le_bytes().to_vec(), angles.1.to_le_bytes().to_vec()].concat()), + WlShape::Curve(points) => (2, v.points(&points)), + WlShape::Text => (3, vec![0; 30]), + }; + let mut r = vec![0u8; (114 + body.len()).max(118)]; + r[..4].copy_from_slice(&WL_RECORD_START); + r[26] = 0x40; + r[27] = 0x20; + let size = (r.len() - 32) as u16; + r[28..30].copy_from_slice(&size.to_le_bytes()); + let [a, b, c, d, e, f] = matrix; + r[32..34].copy_from_slice(&v.coord(e)); + let fixed = |x: f64| ((x * 65536.0).round() as i32).to_le_bytes(); + // a, b, tx, c, d, ty: x' = a x + b y + tx, y' = c x + d y + ty. + for (k, x) in [a, c, 0.0, b, d, f / 72.0 * 1000.0].into_iter().enumerate() { + r[36 + 4 * k..40 + 4 * k].copy_from_slice(&fixed(x)); + } + r[60] = kind; + if let Some((width, color)) = outline { + r[67] = 1; + r[68..70].copy_from_slice(&v.coord(width)); + r[74..79].copy_from_slice(&color); + } + if let Some(color) = fill { + r[94] = 1; + r[95..100].copy_from_slice(&color); + } + r[114..114 + body.len()].copy_from_slice(&body); + r +} + +/// The u32 that starts every record of a version 1 or 2 file (R42). +const WL_RECORD_START: [u8; 4] = 24u32.to_le_bytes(); + +/// A group or layer record of a version 1 or 2 file (R42): 28 bytes. +pub fn wl_group() -> Vec { + let mut r = vec![0u8; 28]; + r[..4].copy_from_slice(&WL_RECORD_START); + r[26] = 1; + r[27] = 0x60; + r +} + +/// A drawn object's record of a version 1 file laid out as in a version 2 file (R43): 11 more bytes +/// before the fill and 11 more before the shape. Group records stay as they are. +fn wl_v2_record(rec: &[u8]) -> Vec { + if rec.get(26).is_none_or(|flags| flags & 0x40 == 0) || rec.len() < 114 { + return rec.to_vec(); + } + let mut out = [&rec[..94], &[0; 11], &rec[94..114], &[0; 11], &rec[114..]].concat(); + let size = (out.len() - 32) as u16; + out[28..30].copy_from_slice(&size.to_le_bytes()); + out +} + +/// A file of version 1 or 2 (R40, R41): the header with `marker` (`e` for version 1, `l` or `m` +/// for version 2), a page of `page` points, the `records` and an empty font table. A version 1 +/// file's settings start after the header; a version 2 file's start further on, where a picture +/// lies in the files of that version, and its drawn objects are laid out as [`wl_v2_record`] says. +pub fn wl_file(marker: u8, page: (f64, f64), records: &[Vec]) -> Vec { + let v = V(300); + let settings = if marker == b'e' { 28u32 } else { 40 }; + let start = 64u32; + let mut out = vec![0u8; start as usize]; + out[..4].copy_from_slice(&[b'W', b'L', marker, 0]); + let (w, h) = page; + let page_box = settings as usize + 2; + out[page_box..page_box + 8].copy_from_slice(&[v.coord(-w / 2.0), v.coord(h / 2.0), v.coord(w / 2.0), v.coord(-h / 2.0)].concat()); + for r in records { + if marker == b'e' { + out.extend(r); + } else { + out.extend(wl_v2_record(r)); + } + } + let end = out.len() as u32; + out.extend([0; 2]); + let trailer = out.len() as u32; + for (k, offset) in [settings, start, end, trailer, trailer - 2].into_iter().enumerate() { + out[4 + 4 * k..8 + 4 * k].copy_from_slice(&offset.to_le_bytes()); + } + out +} + +/// A drawing of version 1 or 2 with a group record and one of each kind of object: a rounded +/// rectangle with a fill and an outline, an ellipse, a closed curve and a text object, front to +/// back. +pub fn wl_sample(marker: u8) -> Vec { + let (red, black) = (color3(1, [0, 100, 100, 0]), color3(1, [0, 0, 0, 100])); + let curve = vec![(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0xC0), (20.0, 50.0, 0xC0), (0.0, 50.0, 0x88)]; + let records = [ + wl_object(WlShape::Rect { w: 100.0, h: 50.0, radius: 5.0 }, [1.0, 0.0, 0.0, 1.0, -100.0, 100.0], Some(red), Some((2.0, black))), + wl_group(), + wl_object(WlShape::Ellipse { w: 40.0, h: -40.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 50.0, -50.0], Some(red), None), + wl_object(WlShape::Curve(curve), [2.0, 0.0, 0.0, 2.0, 0.0, 0.0], None, Some((2.0, black))), + wl_object(WlShape::Text, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(black), None), + ]; + wl_file(marker, (612.0, 792.0), &records) +} diff --git a/crates/cdr/src/synth_cmx.rs b/crates/cdr/src/synth_cmx.rs new file mode 100644 index 0000000000..c70fd8545c --- /dev/null +++ b/crates/cdr/src/synth_cmx.rs @@ -0,0 +1,287 @@ +//! Synthetic `.cmx` files for tests and fuzz seeds, built from the layouts in `PROVENANCE.md` (R53 +//! to R63). Not a `.cmx` writer: nothing checks that other programs open these files. + +/// A chunk: its id, a u32 size, the body and a pad byte after an odd body (R53). +pub fn chunk(id: &[u8; 4], body: &[u8]) -> Vec { + let mut out = id.to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + if body.len() % 2 == 1 { + out.push(0); + } + out +} + +/// A `LIST` chunk of form `form`. +pub fn list(form: &[u8; 4], children: &[Vec]) -> Vec { + let mut body = form.to_vec(); + body.extend(children.concat()); + chunk(b"LIST", &body) +} + +/// The RIFF form `CMX1` around `children`. +pub fn riff(children: &[Vec]) -> Vec { + let mut body = b"CMX1".to_vec(); + body.extend(children.concat()); + chunk(b"RIFF", &body) +} + +/// The header (R54): `coord` is the coordinate size digit (`b'4'` or `b'2'`) and `meters` the size +/// of a coordinate unit. The header string and the system name, which the reader doesn't read, +/// are left as zeros. +pub fn cont(coord: u8, meters: f64) -> Vec { + let mut c = vec![0u8; 180]; + c[48] = b'2'; + c[52] = coord; + c[54] = b'2'; + c[64..72].copy_from_slice(&meters.to_le_bytes()); + chunk(b"cont", &c) +} + +/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). +pub fn field(tag: u8, data: &[u8]) -> Vec { + let mut f = vec![tag]; + f.extend(((data.len() + 3) as u16).to_le_bytes()); + f.extend(data); + f +} + +/// A field list: the fields, then 0xff (R55). +pub fn fields(fields: &[Vec]) -> Vec { + let mut l = fields.concat(); + l.push(0xff); + l +} + +/// A table chunk: a u16 count, then the entries (field lists) (R55). +pub fn table(id: &[u8; 4], entries: &[Vec]) -> Vec { + let mut d = (entries.len() as u16).to_le_bytes().to_vec(); + d.extend(entries.concat()); + chunk(id, &d) +} + +/// A color entry in the older form: the model and palette bytes in field 1, the values in field 2 +/// (R56). +pub fn color(model: u8, values: &[u8]) -> Vec { + fields(&[field(1, &[model, 5]), field(2, values)]) +} + +/// A color entry with a property list in field 10 whose color record (part 1) holds `model` and +/// the four value bytes `v` (R56). +pub fn color_record(model: u16, v: [u8; 4]) -> Vec { + color_record_named(model, v, None) +} + +/// A color entry as [`color_record`], with a name part (part 3: a u32 count and UTF-16 units) +/// after the color when `name` is given (R56). +pub fn color_record_named(model: u16, v: [u8; 4], name: Option<&str>) -> Vec { + let mut part = vec![1u8]; + part.extend(12u32.to_le_bytes()); + part.extend(model.to_le_bytes()); + part.extend(5u16.to_le_bytes()); + part.extend([0; 4]); + part.extend(v); + if let Some(name) = name { + let units: Vec = name.encode_utf16().collect(); + part.push(3); + part.extend((4 + 2 * units.len() as u32).to_le_bytes()); + part.extend((units.len() as u32).to_le_bytes()); + part.extend(units.iter().flat_map(|u| u.to_le_bytes())); + } + let mut rec = (part.len() as u32).to_le_bytes().to_vec(); + rec.extend(part); + fields(&[field(10, &rec)]) +} + +/// A pen entry (R57): the width in coordinate units, an aspect of 100 and no angle, with the +/// identity matrix. +pub fn pen(width: u32) -> Vec { + let mut d = width.to_le_bytes().to_vec(); + d.extend(100u16.to_le_bytes()); + d.extend(0i32.to_le_bytes()); + d.extend(1u16.to_le_bytes()); + fields(&[field(1, &d)]) +} + +/// A line type entry (R57): its flags and the caps (low 4 bits) and join (high 4 bits). +pub fn line_type(flags: u8, caps_join: u8) -> Vec { + fields(&[field(1, &[flags, caps_join])]) +} + +/// A dash pattern entry (R57): the lengths in outline widths. +pub fn dashes(lengths: &[u16]) -> Vec { + let mut d = (lengths.len() as u16).to_le_bytes().to_vec(); + d.extend(lengths.iter().flat_map(|l| l.to_le_bytes())); + fields(&[field(1, &d)]) +} + +/// An outline entry (R58): 1-based indexes of the line type, screen, color, arrowhead pair, pen and +/// dash pattern. +pub fn outline(parts: [u16; 6]) -> Vec { + fields(&[field(1, &parts.iter().flat_map(|p| p.to_le_bytes()).collect::>())]) +} + +/// The arrowhead pairs chunk (R59): a u16 count, then start and end (u16 each). +pub fn arrowheads(pairs: &[(u16, u16)]) -> Vec { + let mut d = (pairs.len() as u16).to_le_bytes().to_vec(); + for (s, e) in pairs { + d.extend(s.to_le_bytes()); + d.extend(e.to_le_bytes()); + } + chunk(b"rota", &d) +} + +/// An instruction in the short form: a u16 size counting the whole instruction, the code, the +/// body (R60). +pub fn instr(code: i16, body: &[u8]) -> Vec { + let mut i = ((body.len() + 4) as u16).to_le_bytes().to_vec(); + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// An instruction in the long form: 0xFFFF, a u32 size counting the whole instruction, the code, +/// the body (R60). +pub fn long_instr(code: i16, body: &[u8]) -> Vec { + let mut i = 0xFFFFu16.to_le_bytes().to_vec(); + i.extend(((body.len() + 8) as u32).to_le_bytes()); + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// Begin a page (R61), with its width and height in coordinate units in field 4 when given. +pub fn begin_page(size: Option<(u32, u32)>) -> Vec { + let mut f = vec![field(1, &[1, 0, 0, 0, 0, 0])]; + if let Some((w, h)) = size { + let mut d = w.to_le_bytes().to_vec(); + d.extend(h.to_le_bytes()); + f.push(field(4, &d)); + } + instr(9, &fields(&f)) +} + +/// Begin a page (R61) without a size of its own, with the drawing's left, top, right and bottom +/// edges in field 1. +pub fn begin_page_in_bounds(left: i32, top: i32, right: i32, bottom: i32) -> Vec { + let mut d = vec![1, 0, 0, 0, 0, 0]; + for v in [left, top, right, bottom] { + d.extend(v.to_le_bytes()); + } + instr(9, &fields(&[field(1, &d)])) +} + +/// Begin a layer (R62) named in 8-bit characters in field 1 from byte 12, and in UTF-16 in +/// field 4 when `wide` is given. +pub fn begin_layer(name: &str, wide: Option<&str>) -> Vec { + let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + d.extend((name.len() as u16).to_le_bytes()); + d.extend(name.bytes()); + let mut f = vec![field(1, &d)]; + if let Some(w) = wide { + let units: Vec = w.encode_utf16().collect(); + let mut d = (units.len() as u32).to_le_bytes().to_vec(); + d.extend(units.iter().flat_map(|u| u.to_le_bytes())); + f.push(field(4, &d)); + } + instr(11, &fields(&f)) +} + +pub fn end_layer() -> Vec { + instr(12, &[]) +} + +pub fn end_page() -> Vec { + instr(10, &[]) +} + +pub fn begin_group() -> Vec { + instr(13, &fields(&[field(1, &[0; 26])])) +} + +pub fn end_group() -> Vec { + instr(14, &[]) +} + +/// Rendering attributes (R63): a uniform fill of color `fill` and the outline `outline` (1-based +/// indexes; `None` leaves the part out of the mask), and `lens` sets the lens bit. +pub fn attrs(fill: Option, outline: Option, lens: bool) -> Vec { + let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1) | (u8::from(lens) << 2); + let mut a = vec![mask]; + if let Some(c) = fill { + let mut v = 1u16.to_le_bytes().to_vec(); + let mut uniform = c.to_le_bytes().to_vec(); + uniform.extend(0u16.to_le_bytes()); + v.extend(fields(&[field(1, &uniform)])); + a.extend(fields(&[field(1, &v)])); + } + if let Some(o) = outline { + a.extend(fields(&[field(1, &o.to_le_bytes())])); + } + a +} + +/// Rendering attributes with a fill of type `kind` and no settings of its own. +pub fn attrs_fill_type(kind: u16) -> Vec { + let mut a = vec![1u8]; + a.extend(fields(&[field(1, &kind.to_le_bytes())])); + a +} + +/// A curve (R62): `attrs`, then a u16 count, the points (i32 x, y) and their type bytes. +pub fn curve(attrs: &[u8], points: &[(i32, i32)], types: &[u8]) -> Vec { + let mut g = (points.len() as u16).to_le_bytes().to_vec(); + for (x, y) in points { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend(types); + instr(67, &fields(&[field(1, attrs), field(2, &g), field(3, &[0; 16])])) +} + +/// A closed square of side `side` with its lower left corner at (`x`, `y`). +pub fn square(attrs: &[u8], x: i32, y: i32, side: i32) -> Vec { + curve(attrs, &[(x, y), (x + side, y), (x + side, y + side), (x, y + side), (x, y)], &[0x0c, 0x44, 0x44, 0x44, 0x48]) +} + +/// A `page` chunk of `instructions`. +pub fn page(instructions: &[Vec]) -> Vec { + chunk(b"page", &instructions.concat()) +} + +/// The tables of [`sample`]: colors red (RGB), black (CMYK in percent) and blue (a color record, +/// blue, green, red); pens of 0.5 mm and 1 mm; line types solid with round caps and joins, none, +/// and dashed behind the fill; one dash pattern; three outlines; one empty arrowhead pair. +pub fn tables() -> Vec> { + vec![ + table(b"rclr", &[color(5, &[255, 0, 0]), color(2, &[0, 0, 0, 100]), color_record(5, [255, 0, 0, 0])]), + table(b"rpen", &[pen(5_000), pen(10_000)]), + table(b"rott", &[line_type(2, 0x11), line_type(1, 0), line_type(2 | 4 | 8, 0x02)]), + table(b"rdot", &[dashes(&[3, 1])]), + table(b"rotl", &[outline([1, 1, 2, 1, 1, 1]), outline([2, 1, 2, 1, 1, 1]), outline([3, 1, 3, 1, 2, 1])]), + arrowheads(&[(0, 0)]), + ] +} + +/// One page of 210 x 297 mm with two layers: "Art" holds a red square outlined in black, then a +/// group of a square with no outline and a blue one with the dashed outline; "Top" holds a black +/// square drawn last. Units are 0.1 µm. +pub fn sample() -> Vec { + let p = page(&[ + begin_page(Some((2_100_000, 2_970_000))), + begin_layer("Art", None), + square(&attrs(Some(1), Some(1), false), -500_000, -500_000, 1_000_000), + begin_group(), + square(&attrs(Some(2), Some(2), false), 0, 0, 100_000), + square(&attrs(Some(3), Some(3), false), 200_000, 0, 100_000), + end_group(), + end_layer(), + begin_layer("Top", Some("Top")), + square(&attrs(Some(2), None, false), 0, 0, 10_000), + end_layer(), + end_page(), + ]); + let mut children = vec![cont(b'4', 1e-7), p]; + children.extend(tables()); + riff(&children) +} diff --git a/crates/cdr/src/wl.rs b/crates/cdr/src/wl.rs new file mode 100644 index 0000000000..bae22ba5a0 --- /dev/null +++ b/crates/cdr/src/wl.rs @@ -0,0 +1,358 @@ +//! Drawings of versions 1 and 2: the file before RIFF, which starts with `WL` (R40 to R44). A +//! header of offsets, the settings with the page's box, then one flat list of records: 28 bytes +//! for a group or a layer, and a longer record for each drawn object, which holds its matrix, fill, +//! outline and shape. The reader maps the rectangles, ellipses and curves onto one page with one +//! layer and keeps no groups. + +use crate::bytes::{Rd, u32_at}; +use crate::geometry; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Cap, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape}; +use crate::records::{self, coord, fixed}; +use crate::riff::push; +use crate::{Error, Warning}; + +/// The header: the signature, a marker byte, a zero and five u32 offsets (R40). +const HEADER: usize = 28; +/// The marker bytes read after `WL` (R40): `e` for version 1, `l` and `m` for version 2. +const MARKERS: [u8; 3] = *b"elm"; +/// Where the page's box lies after the start of the settings (R41). +const PAGE_BOX: usize = 2; +/// The bytes of a group or layer record (R42). +const GROUP: usize = 28; +/// The u32 that starts every record (R42). +const RECORD_START: u32 = 24; +/// The flag bit, in byte 26, of a drawn object (R42). +const DRAWN: u8 = 0x40; +/// The bytes after a drawn object's body size (R42). +const AFTER_BODY: usize = 32; +/// Where a drawn object's fields lie (R43, R44). +const POINT: usize = 32; +const KIND: usize = 60; +const OUTLINED: usize = 67; +const OUTLINE_WIDTH: usize = 68; +const OUTLINE_COLOR: usize = 74; + +/// Where a drawn object's fill and shape lie, which differs between the markers (R43, R44). +#[derive(Clone, Copy)] +struct Fields { + fill_kind: usize, + shape: usize, +} + +impl Fields { + fn of(marker: u8) -> Self { + if marker == b'e' { Fields { fill_kind: 94, shape: 114 } } else { Fields { fill_kind: 105, shape: 136 } } + } + + /// The least a drawn object takes: its fixed fields and the 4 bytes of a shape's size. + fn least(self) -> usize { + self.shape + 4 + } +} +/// Object types (R43). +const RECTANGLE: u8 = 0; +const ELLIPSE: u8 = 1; +const CURVE: u8 = 2; +const TEXT: u8 = 3; + +/// Where the settings start, and where the records start and end, when `b` has a `WL` header +/// whose offsets fit the file. +fn header(b: &[u8]) -> Option<(usize, usize, usize)> { + if b.get(..2)? != b"WL" || !MARKERS.contains(b.get(2)?) || *b.get(3)? != 0 { + return None; + } + let (settings, start, end) = (u32_at(b, 4)? as usize, u32_at(b, 8)? as usize, u32_at(b, 12)? as usize); + (settings >= HEADER && settings <= start && start <= end && end <= b.len()).then_some((settings, start, end)) +} + +/// Does `b` start like a drawing of version 1 or 2? The two letters alone are not enough: the +/// marker byte, the zero after it and the record offsets must fit too. +pub(crate) fn is_wl(b: &[u8]) -> bool { + header(b).is_some() +} + +pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result { + let (settings, start, end) = header(b).ok_or(Error::NotCdr)?; + let marker = b.get(2).copied().ok_or(Error::NotCdr)?; + let fields = Fields::of(marker); + // Lengths are i16 in 1/1000 inch, as in version 3 (R5). + let p = layout::for_version(layout::OLDEST_RIFF).ok_or(Error::NotCdr)?; + let mut warn = Vec::new(); + let mut objects = Vec::new(); + let mut at = start; + // Every step takes at least a group record's bytes, so the file's size bounds the steps. + while end - at >= GROUP { + budget.take_chunk()?; + // A record that doesn't start as records do is past one whose length isn't known. + if u32_at(b, at) != Some(RECORD_START) { + break; + } + if b.get(at + 26).is_none_or(|flags| flags & DRAWN == 0) { + at += GROUP; + continue; + } + // A drawn object of another type than rectangle, ellipse, curve and text doesn't say its + // length in the same way, so the records after it can't be found. + if b.get(at + KIND).is_none_or(|kind| *kind > TEXT) { + push(&mut warn, Warning::UnsupportedObjects); + at = end; + break; + } + let len = Rd::at(b, at + 28).u16().map_or(0, |body| usize::from(body) + AFTER_BODY); + let Some(rec) = b.get(at..at + len).filter(|_| len >= fields.least() && at + len <= end) else { + push(&mut warn, Warning::Damaged); + at = end; + break; + }; + at += len; + if !budget.take_object() { + push(&mut warn, Warning::TooDeep); + at = end; + break; + } + objects.extend(object(rec, fields, &p, budget, &mut warn)); + } + if at != end { + push(&mut warn, Warning::Damaged); + } + let version = if marker == b'e' { 100 } else { 200 }; + let layer = Layer { name: String::new(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() }; + let pages = vec![Page { size: None, layers: vec![layer] }]; + Ok(Drawing { version, page_size: page_box(b, settings, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) +} + +/// The page's size from its box (R41): left, top, right and bottom around the page's centre. +fn page_box(b: &[u8], settings: usize, p: &Profile) -> Option<(f64, f64)> { + let mut r = Rd::at(b, settings + PAGE_BOX); + let (left, top, right, bottom) = (coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?); + let (w, h) = ((right - left).abs(), (top - bottom).abs()); + (w > 0.0 && h > 0.0).then_some((w, h)) +} + +/// One drawn object's record (R43, R44): a shape, or `None` with a warning for text, for an object +/// of another type and for a shape that can't be read. +fn object(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + // A curve left out at the coordinate limit is not damage. + budget.coordinates_refused(); + let read = shape(rec, fields, p, budget, warn); + if read.is_none() && !budget.coordinates_refused() { + push(warn, Warning::Damaged); + } + read?.map(|s| Object::Shape(Box::new(s))) +} + +/// The shape of a record. The outer `None` is a record that can't be read; the inner one an object +/// the reader leaves out, with its warning. +fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option> { + let k = p.unit(); + let mut r = Rd::at(rec, POINT); + let (x, y) = (f64::from(r.i16()?), f64::from(r.i16()?)); + // x' = a x + b y + tx + x of the point, y' = c x + d y + ty + y of the point. + let (a, b, tx, c, d, ty) = (fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?); + let matrix = Matrix([a, c, b, d, (tx + x) * k, (ty + y) * k]); + let body = rec.get(fields.shape..)?; + let geometry = match *rec.get(KIND)? { + RECTANGLE => rect(body, p)?, + ELLIPSE => { + let mut s = Rd::new(body); + let (w, h) = (coord(&mut s, p)?, coord(&mut s, p)?); + // Two angles follow. No source confirms how they make an arc, so an ellipse whose + // angles differ is left out; one whose angles are missing is damage. + let (from, to) = (s.i16()?, s.i16()?); + if from != to { + push(warn, Warning::UnsupportedObjects); + return Some(None); + } + Geometry::Ellipse { w, h } + } + CURVE => Geometry::Path(geometry::point_list(body, p, budget, warn)?), + _ => { + push(warn, Warning::UnsupportedObjects); + return Some(None); + } + }; + let color_at = |at: usize, warn: &mut Vec| Some(records::color5(rec.get(at..at + 5)?.try_into().ok()?, warn)); + let fill = match *rec.get(fields.fill_kind)? { + 0 => None, + 1 => Some(color_at(fields.fill_kind + 1, warn)?), + _ => { + push(warn, Warning::UnsupportedFills); + None + } + }; + let outline = if *rec.get(OUTLINED)? != 0 { + let width = f64::from(Rd::at(rec, OUTLINE_WIDTH).u16()?) * k; + Some(Outline { + width, + color: color_at(OUTLINE_COLOR, warn)?, + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }) + } else { + None + }; + Some(Some(Shape::new(geometry, matrix, fill, outline))) +} + +/// A rectangle (R44): its width and height, then a corner radius, which is kept when it is at most +/// half the shorter side. +fn rect(body: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(body); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let radius = coord(&mut r, p).filter(|v| *v > 0.0 && *v <= w.abs().min(h.abs()) / 2.0).unwrap_or(0.0); + Some(Geometry::Rect { w, h, radii: [radius; 4] }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Limits; + use crate::model::Color; + use crate::synth::{self, WlShape}; + + fn read(b: &[u8]) -> Result { + drawing(b, &mut Budget::new(Limits::default())) + } + + #[test] + fn the_header_is_taken_only_when_its_offsets_fit() { + let file = synth::wl_file(b'e', (612.0, 792.0), &[synth::wl_group()]); + assert!(is_wl(&file)); + // The two letters, a marker and a zero are not enough. + assert!(!is_wl(b"WLe\0")); + assert!(!is_wl(b"WLe\0 and then some text that is long enough to hold offsets")); + let with = |at: usize, v: u32| { + let mut f = file.clone(); + f[at..at + 4].copy_from_slice(&v.to_le_bytes()); + f + }; + // Records that start inside the header, start after their end, or end past the file. + assert!(!is_wl(&with(8, 27))); + assert!(!is_wl(&with(8, file.len() as u32))); + assert!(!is_wl(&with(12, file.len() as u32 + 1))); + // Settings that start inside the header or after the records. + assert!(!is_wl(&with(4, 27))); + assert!(!is_wl(&with(4, 65))); + let mut other = file.clone(); + other[2] = b'x'; + assert!(!is_wl(&other)); + // No sample shows the marker `d`, so it is not taken. + other[2] = b'd'; + assert!(!is_wl(&other)); + for marker in *b"lm" { + assert!(is_wl(&synth::wl_file(marker, (612.0, 792.0), &[synth::wl_group()]))); + } + other[2] = b'e'; + other[3] = 1; + assert!(!is_wl(&other)); + } + + #[test] + fn a_version_2_file_keeps_its_page_box_fill_and_shape_where_that_version_puts_them() { + let (red, black) = ([1, 0, 100, 100, 0], [1, 0, 0, 0, 100]); + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 9.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(red), Some((2.0, black))); + for marker in *b"elm" { + let file = synth::wl_file(marker, (720.0, 504.0), std::slice::from_ref(&rect)); + // Version 2 files start their settings after a picture, not after the header. + assert_eq!(u32_at(&file, 4) == Some(28), marker == b'e'); + let d = read(&file).unwrap(); + let near = |a: f64, b: f64| (a - b).abs() < 0.02; + assert_eq!((d.version, d.warnings.clone()), (if marker == b'e' { 100 } else { 200 }, vec![])); + assert!(d.page_size.is_some_and(|(w, h)| near(w, 720.0) && near(h, 504.0)), "{:?}", d.page_size); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert!( + matches!(s.geometry, Geometry::Rect { w, h, radii } if near(w, 72.0) && near(h, 36.0) && near(radii[0], 9.0)), + "{}", + marker as char + ); + assert_eq!(s.fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0])), "{}", marker as char); + assert!(s.outline.as_ref().is_some_and(|o| near(o.width, 2.0) && o.color == Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{}", marker as char); + } + } + + #[test] + fn a_drawn_object_is_marked_by_its_flag_bit() { + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], None, None); + let mut file = synth::wl_file(b'l', (612.0, 792.0), &[rect]); + // Files with the marker `l` set another flag bit beside it. + file[64 + 26] = 0xc0; + let d = read(&file).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![])); + } + + #[test] + fn the_walk_stops_where_records_can_no_longer_be_found() { + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let rect = || synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, unit, None, None); + // An object of another type doesn't give its length in the same way. + let mut other = rect(); + other[KIND] = 0xff; + let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[rect(), other, rect()])).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::UnsupportedObjects])); + // A record that doesn't start as records do. + let mut lost = rect(); + lost[0] = 0x84; + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), lost, rect()])).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::Damaged])); + } + + #[test] + fn a_rectangle_keeps_a_radius_of_at_most_half_its_shorter_side() { + let p = layout::for_version(300).unwrap(); + let body = |radius: i16| [1000i16, 500, radius].iter().flat_map(|v| v.to_le_bytes()).collect::>(); + let radius_of = |b: &[u8]| match rect(b, &p) { + Some(Geometry::Rect { w, h, radii }) if (w - 72.0).abs() < 1e-9 && (h - 36.0).abs() < 1e-9 => radii[0], + other => panic!("{other:?}"), + }; + assert!((radius_of(&body(200)) - 14.4).abs() < 1e-9); + for radius in [300, -5, 0] { + assert_eq!(radius_of(&body(radius)), 0.0, "{radius}"); + } + // A record that ends after the size has square corners. + assert_eq!(radius_of(&body(200)[..4]), 0.0); + assert_eq!(rect(&body(200)[..3], &p), None); + } + + #[test] + fn a_record_shorter_than_its_fields_ends_the_walk_as_damage() { + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None); + let mut short = rect.clone(); + // A body size that leaves less than the fixed fields. + short[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY - 1) as u16).to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect.clone(), short, rect])).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + + #[test] + fn an_ellipse_without_its_angles_is_damage() { + let ellipse = + synth::wl_object(WlShape::Ellipse { w: 72.0, h: 36.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None); + let mut cut = ellipse.clone(); + // A body size that ends the record after the ellipse's width and height. + cut[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY) as u16).to_le_bytes()); + cut.truncate(Fields::of(b'e').least()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[ellipse, cut])).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + + #[test] + fn fill_types_other_than_uniform_and_unknown_inks_are_named() { + let mut textured = + synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([0, 9, 0, 50, 0]), None); + let d = read(&synth::wl_file(b'm', (612.0, 792.0), std::slice::from_ref(&textured))).unwrap(); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert_eq!(s.fill, Some(Color::Spot { name: "Spot 0:9".into(), tint: 0.5, look: None })); + assert_eq!((d.version, d.warnings), (200, vec![Warning::SpotLooks])); + textured[Fields::of(b'e').fill_kind] = 5; + let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[textured])).unwrap(); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert_eq!((s.fill.clone(), d.warnings), (None, vec![Warning::UnsupportedFills])); + } +} diff --git a/crates/cdr/src/zip.rs b/crates/cdr/src/zip.rs new file mode 100644 index 0000000000..67994192a0 --- /dev/null +++ b/crates/cdr/src/zip.rs @@ -0,0 +1,308 @@ +//! The ZIP archives of `.cdr` drawings from version 14 on (R24): the central directory, then stored +//! and deflated members read on request. Archives that span disks, ZIP64 archives and encrypted +//! members are refused; so are directories whose members overlap or repeat a name. + +use std::borrow::Cow; +use std::io::Read as _; + +use crate::Error; +use crate::bytes::Rd; + +/// End of central directory record: signature and fixed length. +const END: u32 = 0x0605_4b50; +const END_LEN: usize = 22; +/// The longest archive comment, which the end record may be followed by. +const MAX_COMMENT: usize = 0xFFFF; +/// ZIP64 end of central directory locator, 20 bytes before the end record when present. +const ZIP64_LOCATOR: u32 = 0x0706_4b50; +/// Central directory header: signature and fixed length. +const CENTRAL: u32 = 0x0201_4b50; +const CENTRAL_LEN: usize = 46; +/// Local file header: signature and fixed length. +const LOCAL: u32 = 0x0403_4b50; +const LOCAL_LEN: usize = 30; +/// General purpose flag bit 0: the member is encrypted. +const ENCRYPTED: u16 = 1; +const STORED: u16 = 0; +const DEFLATED: u16 = 8; +/// What members packed by another method are refused as. +const OTHER_METHODS: &str = "package compression methods other than storing and deflate"; + +/// One member, as the central directory and its local header give it. +#[derive(Clone, Copy, Debug)] +struct Entry<'a> { + name: &'a [u8], + flags: u16, + method: u16, + crc: u32, + packed: usize, + size: usize, + /// Where its local header starts and where its packed bytes start. + header: usize, + data: usize, +} + +/// An archive's directory over its bytes. +#[derive(Debug)] +pub(crate) struct Archive<'a> { + bytes: &'a [u8], + entries: Vec>, + /// The entries in name order, for lookups. + by_name: Vec, +} + +/// Does `bytes` start with a local file header? +pub(crate) fn is_zip(bytes: &[u8]) -> bool { + bytes.starts_with(b"PK\x03\x04") +} + +impl<'a> Archive<'a> { + /// The directory of `bytes`, holding at most `max_entries` members. + pub(crate) fn open(bytes: &'a [u8], max_entries: usize) -> Result { + let end = find_end(bytes).ok_or(Error::Damaged("package directory"))?; + if end >= 20 && Rd::at(bytes, end - 20).u32() == Some(ZIP64_LOCATOR) { + return Err(Error::Unsupported("ZIP64 packages")); + } + let mut r = Rd::at(bytes, end + 4); + let dir = || Error::Damaged("package directory"); + let (disk, dir_disk) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?); + let (on_disk, total) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?); + let (dir_len, dir_at) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?); + if total == u16::MAX || dir_len == u32::MAX || dir_at == u32::MAX { + return Err(Error::Unsupported("ZIP64 packages")); + } + if disk != 0 || dir_disk != 0 || on_disk != total { + return Err(Error::Unsupported("packages split across files")); + } + let total = usize::from(total); + if total > max_entries { + return Err(Error::Limit("package member count")); + } + let (dir_at, dir_len) = (dir_at as usize, dir_len as usize); + let dir_end = dir_at.checked_add(dir_len).filter(|&e| e <= end).ok_or_else(dir)?; + let mut r = Rd::at(bytes, dir_at); + let mut entries = Vec::with_capacity(total); + for _ in 0..total { + let e = central_entry(bytes, &mut r, dir_end)?; + entries.push(e); + } + // Each member's bytes end before the next member's header and before the directory. + let mut order: Vec<&Entry> = entries.iter().collect(); + order.sort_unstable_by_key(|e| e.header); + for (i, e) in order.iter().enumerate() { + let stop = order.get(i + 1).map_or(dir_at, |n| n.header); + if e.data.checked_add(e.packed).is_none_or(|x| x > stop) { + return Err(Error::Damaged("package members overlap")); + } + } + let mut by_name: Vec = (0..entries.len()).collect(); + by_name.sort_unstable_by_key(|&i| entries.get(i).map(|e| e.name)); + let name = |i: &usize| entries.get(*i).map(|e| e.name); + if by_name.windows(2).any(|w| name(&w[0]) == name(&w[1])) { + return Err(Error::Damaged("package member named twice")); + } + Ok(Archive { bytes, entries, by_name }) + } + + /// The member named `name`. + pub(crate) fn find(&self, name: &[u8]) -> Option { + let at = self.by_name.binary_search_by(|&i| self.entries.get(i).map(|e| e.name).cmp(&Some(name))).ok()?; + self.by_name.get(at).copied() + } + + /// The size member `i`'s directory entry gives. + pub(crate) fn size(&self, i: usize) -> usize { + self.entries.get(i).map_or(0, |e| e.size) + } + + /// How many members the archive holds. + pub(crate) fn count(&self) -> usize { + self.entries.len() + } + + /// The bytes reading member `i` may inflate: its stated size when it is deflated, else 0. + pub(crate) fn inflate_cost(&self, i: usize) -> usize { + self.entries.get(i).filter(|e| e.method == DEFLATED).map_or(0, |e| e.size) + } + + /// An error when member `i` is encrypted or packed by a method other than storing or deflate. + pub(crate) fn check(&self, i: usize) -> Result<(), Error> { + let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?; + if e.flags & ENCRYPTED != 0 { + return Err(Error::Unsupported("encrypted packages")); + } + if e.method != STORED && e.method != DEFLATED { + return Err(Error::Unsupported(OTHER_METHODS)); + } + Ok(()) + } + + /// Member `i`'s bytes when they come to at most `limit`, and a deflated member's when they + /// also come to at most `inflate_left`. A stored member is borrowed; a deflated one inflates to + /// at most its stated size plus one byte, so a member that inflates past what it states stops + /// there. The length and CRC-32 must match the directory's. + pub(crate) fn read(&self, i: usize, limit: usize, inflate_left: usize) -> Result, Error> { + self.check(i)?; + let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?; + if e.size > limit { + return Err(Error::Limit("package member size")); + } + if e.method == DEFLATED && e.size > inflate_left { + return Err(Error::Limit("inflated size")); + } + let packed = self.bytes.get(e.data..e.data + e.packed).ok_or(Error::Damaged("package member"))?; + let out: Cow<'a, [u8]> = match e.method { + STORED if e.packed == e.size => Cow::Borrowed(packed), + STORED => return Err(Error::Damaged("package member")), + DEFLATED => { + let mut out = Vec::new(); + let got = flate2::read::DeflateDecoder::new(packed) + .take(e.size as u64 + 1) + .read_to_end(&mut out) + .map_err(|_| Error::Damaged("package member"))?; + if got != e.size { + return Err(Error::Damaged("package member")); + } + Cow::Owned(out) + } + _ => return Err(Error::Unsupported(OTHER_METHODS)), + }; + if crc32fast::hash(&out) != e.crc { + return Err(Error::Damaged("package member")); + } + Ok(out) + } +} + +/// Where the end of central directory record starts: searched back from the end over at most the +/// longest comment, among the records whose comment reaches exactly to the end the first that +/// names members in a directory before it, else the first. A comment or a member may hold bytes +/// that look like an empty archive's end record. +fn find_end(bytes: &[u8]) -> Option { + let last = bytes.len().checked_sub(END_LEN)?; + let first = last.saturating_sub(MAX_COMMENT); + let mut found = None; + for at in (first..=last).rev() { + let mut r = Rd::at(bytes, at); + if r.u32() != Some(END) || r.skip(6).is_none() { + continue; + } + let (total, dir_len, dir_at, comment) = (r.u16(), r.u32(), r.u32(), r.u16()); + if !comment.is_some_and(|c| at + END_LEN + usize::from(c) == bytes.len()) { + continue; + } + let names_members = total.is_some_and(|t| t > 0) + && dir_len.zip(dir_at).is_some_and(|(len, dir)| { + (dir as usize).checked_add(len as usize).is_some_and(|e| e <= at) && Rd::at(bytes, dir as usize).u32() == Some(CENTRAL) + }); + if names_members { + return Some(at); + } + found = found.or(Some(at)); + } + found +} + +/// The central directory entry at `r` (before `dir_end`) and its local header. +fn central_entry<'a>(bytes: &'a [u8], r: &mut Rd<'a>, dir_end: usize) -> Result, Error> { + let dir = || Error::Damaged("package directory"); + if r.pos().checked_add(CENTRAL_LEN).is_none_or(|e| e > dir_end) || r.u32() != Some(CENTRAL) { + return Err(dir()); + } + r.skip(4).ok_or_else(dir)?; + let flags = r.u16().ok_or_else(dir)?; + let method = r.u16().ok_or_else(dir)?; + r.skip(4).ok_or_else(dir)?; + let crc = r.u32().ok_or_else(dir)?; + let (packed, size) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?); + let name_len = usize::from(r.u16().ok_or_else(dir)?); + let extra_len = usize::from(r.u16().ok_or_else(dir)?); + let comment_len = usize::from(r.u16().ok_or_else(dir)?); + let disk = r.u16().ok_or_else(dir)?; + r.skip(6).ok_or_else(dir)?; + let header = r.u32().ok_or_else(dir)?; + if packed == u32::MAX || size == u32::MAX || header == u32::MAX { + return Err(Error::Unsupported("ZIP64 packages")); + } + if disk != 0 { + return Err(Error::Unsupported("packages split across files")); + } + let name = r.bytes(name_len).ok_or_else(dir)?; + r.skip(extra_len).and_then(|()| r.skip(comment_len)).ok_or_else(dir)?; + if r.pos() > dir_end { + return Err(dir()); + } + // The local header repeats the name; its own extra field may differ in length. + let header = header as usize; + let mut l = Rd::at(bytes, header); + let local = || Error::Damaged("package member header"); + if l.u32() != Some(LOCAL) { + return Err(local()); + } + // The signature, 22 bytes, then the name and extra field lengths. + l.skip(LOCAL_LEN - 8).ok_or_else(local)?; + let (local_name, local_extra) = (usize::from(l.u16().ok_or_else(local)?), usize::from(l.u16().ok_or_else(local)?)); + if l.bytes(local_name) != Some(name) { + return Err(local()); + } + l.skip(local_extra).ok_or_else(local)?; + Ok(Entry { name, flags, method, crc, packed: packed as usize, size: size as usize, header, data: l.pos() }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::synth::{Member, zip}; + + fn stored(name: &str, data: &[u8]) -> Member { + Member { name: name.into(), data: data.to_vec(), deflate: false } + } + + #[test] + fn stored_and_deflated_members_read_back() { + let bytes = zip(&[stored("a", b"hello"), Member { name: "b".into(), data: vec![7; 5000], deflate: true }], b""); + let a = Archive::open(&bytes, 10).unwrap(); + assert!(matches!(a.read(a.find(b"a").unwrap(), 100, 100).unwrap(), Cow::Borrowed(b"hello"))); + assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 5000).unwrap().as_ref(), &[7; 5000][..]); + assert_eq!(a.read(a.find(b"b").unwrap(), 4999, 5000), Err(Error::Limit("package member size"))); + assert_eq!(a.find(b"c"), None); + // What is left to inflate holds back deflated members only. + assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 4999), Err(Error::Limit("inflated size"))); + assert!(a.read(a.find(b"a").unwrap(), 100, 0).is_ok()); + } + + #[test] + fn the_end_record_is_found_behind_a_comment() { + let bytes = zip(&[stored("a", b"x")], &[b'c'; 300]); + assert!(Archive::open(&bytes, 10).is_ok()); + // A comment longer than the record says leaves no end record to find. + let mut cut = bytes.clone(); + cut.push(0); + assert_eq!(Archive::open(&cut, 10).unwrap_err(), Error::Damaged("package directory")); + // A comment that ends in bytes like an empty archive's end record: the record that names + // members in a directory is the archive's. + let mut fake = END.to_le_bytes().to_vec(); + fake.resize(END_LEN, 0); + let bytes = zip(&[stored("a", b"x")], &fake); + let a = Archive::open(&bytes, 10).unwrap(); + assert_eq!(a.count(), 1); + } + + #[test] + fn a_member_whose_crc_or_length_is_wrong_is_damage() { + let bytes = zip(&[Member { name: "a".into(), data: vec![1; 64], deflate: true }], b""); + let a = Archive::open(&bytes, 10).unwrap(); + // The directory's CRC-32 sits 16 bytes into its entry. + let dir_at = bytes.windows(4).position(|w| w == CENTRAL.to_le_bytes()).unwrap(); + let mut bad = bytes.clone(); + bad[dir_at + 16] ^= 1; + let b = Archive::open(&bad, 10).unwrap(); + assert_eq!(b.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member")); + // A stated size one short: the inflate runs past it. + let mut short = bytes.clone(); + short[dir_at + 24] -= 1; + let s = Archive::open(&short, 10).unwrap(); + assert_eq!(s.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member")); + assert!(a.read(0, 1000, 1000).is_ok()); + } +} diff --git a/crates/cdr/tests/it/bench.rs b/crates/cdr/tests/it/bench.rs new file mode 100644 index 0000000000..6b60a0a5a7 --- /dev/null +++ b/crates/cdr/tests/it/bench.rs @@ -0,0 +1,65 @@ +//! Read time of a large synthetic drawing. Run with +//! `cargo test --release -p craft-cdr --test it bench -- --ignored --nocapture`. + +use craft_cdr::synth::{self, V, chunk, list}; +use craft_cdr::{Limits, read}; + +/// A version 13 drawing of `n` curves of 22 points each, filled and outlined, compressed when +/// `compress`. +fn many_curves(n: usize, compress: bool) -> Vec { + let v = V(1300); + let red = synth::color(5, [0, 0, 255, 0]); + let black = synth::color(2, [0, 0, 0, 100]); + let styles = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(b"fild", v.fill(1, &red))]), + list(b"otlt", vec![chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &black, &[]))]), + ], + ); + let objects: Vec<_> = (0..n) + .map(|i| { + let o = (i % 500) as f64; + // A move, then curves of two control points and an end point each. + let kind = |k: i32| { + if k == 0 { + 0x08 + } else if k % 3 == 0 { + 0x80 + } else { + 0xC0 + } + }; + let pts: Vec<(f64, f64, u8)> = (0..22).map(|k| (o + f64::from(k), o + f64::from(k % 5), kind(k))).collect(); + let args = vec![(20, 1u32.to_le_bytes().to_vec()), (10, 2u32.to_le_bytes().to_vec()), (30, v.points(&pts))]; + synth::object(v, 3, &args, Some([1.0, 0.0, 0.0, 1.0, o, -o])) + }) + .collect(); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", objects)]); + let body = vec![styles, page]; + let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())]; + if compress { + kids.push(synth::cmpr(&body)); + } else { + kids.extend(body); + } + synth::riff(1300, &kids) +} + +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn read_a_large_drawing() { + for compress in [false, true] { + let file = many_curves(50_000, compress); + let mut times = Vec::new(); + for _ in 0..5 { + let t = std::time::Instant::now(); + let d = read(&file, Limits::default()).unwrap(); + times.push(t.elapsed().as_secs_f64() * 1000.0); + assert_eq!(d.pages.len(), 1); + } + times.sort_by(f64::total_cmp); + println!("compress={compress} bytes={} median_ms={:.1} min_ms={:.1}", file.len(), times[2], times[0]); + } +} diff --git a/crates/cdr/tests/it/cmx.rs b/crates/cdr/tests/it/cmx.rs new file mode 100644 index 0000000000..0067d981b7 --- /dev/null +++ b/crates/cdr/tests/it/cmx.rs @@ -0,0 +1,568 @@ +//! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and +//! hostile ones. + +use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape}; +use craft_cdr::synth_cmx::*; +use craft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx}; +use proptest::prelude::*; + +fn shape(o: &Object) -> &Shape { + match o { + Object::Shape(s) => s, + other => panic!("not a shape: {other:?}"), + } +} + +/// The (x, y) bounds of a shape's path. +fn bounds(s: &Shape) -> (f64, f64, f64, f64) { + let Geometry::Path(p) = &s.geometry else { panic!("not a path") }; + let mut b = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for sp in &p.subpaths { + for pt in std::iter::once(sp.start).chain(sp.segments.iter().map(|s| match s { + craft_cdr::model::Segment::Line(p) | craft_cdr::model::Segment::Cubic(_, _, p) => *p, + })) { + b = (b.0.min(pt.x), b.1.min(pt.y), b.2.max(pt.x), b.3.max(pt.y)); + } + } + b +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +/// The file with `children` after a 32-bit header and the sample tables. +fn file(pages: &[Vec]) -> Vec { + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(pages.iter().cloned()); + children.extend(tables()); + riff(&children) +} + +#[test] +fn a_cmx_file_is_told_from_a_cdr_drawing() { + let f = sample(); + assert!(is_cmx(&f) && !is_cdr(&f)); + let mut rifx = f.clone(); + rifx[..4].copy_from_slice(b"RIFX"); + assert!(is_cmx(&rifx)); + assert!(!is_cmx(b"RIFF\0\0\0\0CDR9")); + assert_eq!(read_cmx(b"RIFF\0\0\0\0CDR9", Limits::default()), Err(Error::NotCmx)); +} + +#[test] +fn pages_layers_groups_and_curves() { + let d = read_cmx(&sample(), Limits::default()).unwrap(); + assert_eq!(d.version, 0); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + let page = &d.pages[0]; + // 2,100,000 units of 0.1 µm are 210 mm. + let (w, h) = page.size.unwrap(); + assert!(near(w, 210.0 / 25.4 * 72.0) && near(h, 297.0 / 25.4 * 72.0), "{w} {h}"); + // The layer drawn last is in front: the model lists layers front to back. + let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Top", "Art"]); + let art = &page.layers[1].objects; + assert_eq!(art.len(), 2); + // The group, drawn after the red square, is in front of it. + let Object::Group { objects: kids, .. } = &art[0] else { panic!("{:?}", art[0]) }; + assert_eq!(kids.len(), 2); + let red = shape(&art[1]); + assert_eq!(red.fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + // 1,000,000 units are 100 mm; the square's corner is 50 mm left of and below the center. + let mm = 72.0 / 25.4; + let b = bounds(red); + assert!(near(b.0, -50.0 * mm) && near(b.1, -50.0 * mm) && near(b.2, 50.0 * mm) && near(b.3, 50.0 * mm), "{b:?}"); + let Geometry::Path(p) = &red.geometry else { panic!() }; + assert!(p.subpaths.len() == 1 && p.subpaths[0].closed && p.subpaths[0].segments.len() == 4); + let o = red.outline.as_ref().unwrap(); + assert!(near(o.width, 0.5 * mm)); + assert_eq!((o.color.clone(), o.cap, o.join), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Round, Join::Round)); + assert!(o.dashes.is_empty() && !o.behind_fill && !o.scale_with); + // Line type 1 draws no outline. + let blue = shape(&kids[0]); + let black = shape(&kids[1]); + assert!(black.outline.is_none()); + assert_eq!(black.fill, Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0]))); + // The color record's values are blue, green and red. + assert_eq!(blue.fill, Some(Color::Rgb([0.0, 0.0, 1.0]))); + let o = blue.outline.as_ref().unwrap(); + assert!(near(o.width, 1.0 * mm)); + assert_eq!((o.dashes.clone(), o.behind_fill, o.cap, o.join), (vec![3.0, 1.0], true, Cap::Square, Join::Miter)); + assert_eq!(page.layers[0].name, "Top"); +} + +#[test] +fn layer_names_and_layers_without_objects() { + let p = page(&[ + begin_page(None), + begin_layer("Ebene 1", Some("Слой 1")), + square(&attrs(Some(1), None, false), 0, 0, 1000), + end_layer(), + begin_layer("Gitter", None), + end_layer(), + begin_layer("Caf\u{e9}", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + end_layer(), + end_page(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let page = &d.pages[0]; + assert_eq!(page.size, None); + // The empty layer is left out, and the UTF-16 name wins over the 8-bit one. + let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Caf\u{c3}\u{a9}", "Слой 1"]); +} + +#[test] +fn objects_before_any_layer_get_one() { + let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.pages[0].layers.len(), 1); + // The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place. + assert_eq!(d.pages[0].layers[0].name, ""); +} + +#[test] +fn a_page_without_a_size_takes_the_drawings_bounds() { + // A square of 100 mm whose bounds lie off the file's origin, above and to the right. + let p = page(&[ + begin_page_in_bounds(1_000_000, 3_000_000, 2_000_000, 2_000_000), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 1_000_000, 2_000_000, 1_000_000), + end_layer(), + end_page(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let page = &d.pages[0]; + let side = 100.0 / 25.4 * 72.0; + let (w, h) = page.size.unwrap(); + assert!(near(w, side) && near(h, side), "{w} x {h}"); + // The page is centered on the bounds, so the square fills it. + let (x0, y0, x1, y1) = bounds(shape(&page.layers[0].objects[0])); + assert!(near(x0, -side / 2.0) && near(x1, side / 2.0) && near(y0, -side / 2.0) && near(y1, side / 2.0), "{x0} {y0} {x1} {y1}"); +} + +#[test] +fn curves_and_open_groups() { + let c = + curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]); + // A group the layer leaves open closes with it. + let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let objects = &d.pages[0].layers[0].objects; + let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") }; + let s = shape(&kids[0]); + assert!(s.fill.is_none()); + let Geometry::Path(p) = &s.geometry else { panic!() }; + assert_eq!(p.subpaths.len(), 2); + assert!(matches!(p.subpaths[0].segments[..], [craft_cdr::model::Segment::Cubic(..)])); + assert!(!p.subpaths[1].closed); +} + +#[test] +fn a_curve_without_its_points_is_reported() { + let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() { + let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0]; + d.extend(b"Art"); + let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])])); + let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.pages[0].layers[0].name, "Art"); +} + +#[test] +fn what_is_not_read_is_reported() { + let other = |code: i16| instr(code, &fields(&[field(1, &[0; 8])])); + let p = page(&[ + begin_page(None), + begin_layer("L", None), + other(66), + other(68), + other(20), + other(88), + square(&attrs_fill_type(2), 0, 0, 1000), + square(&attrs(Some(1), None, true), 0, 0, 1000), + end_layer(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] { + assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings); + } + // A fill of another type leaves the curve unfilled; the curve is still read. + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 2); + assert!(shape(&objects[1]).fill.is_none()); +} + +#[test] +fn colors_of_other_models_and_missing_entries() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[ + begin_page(None), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + square(&attrs(Some(9), None, false), 0, 0, 1000), + square(&attrs(Some(2), None, false), 0, 0, 1000), + ])); + children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0]))); + assert_eq!(shape(&objects[1]).fill, Some(Color::Rgb([0.0; 3]))); +} + +#[test] +fn gray_cmy_and_rgb_colors_of_the_older_fields() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[ + begin_page(None), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + square(&attrs(Some(2), None, false), 0, 0, 1000), + square(&attrs(Some(3), None, false), 0, 0, 1000), + ])); + children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + // The model holds objects front to back: the RGB square, the CMY one, then the gray one. + assert_eq!(shape(&objects[0]).fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + match (shape(&objects[1]).fill.clone(), shape(&objects[2]).fill.clone()) { + (Some(Color::Cmyk([c, m, y, k])), Some(Color::Gray(g))) => { + assert!((c - 1.0).abs() < 1e-6 && m == 0.0 && (y - 0.2).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}"); + assert!((g - 0.8).abs() < 1e-6, "{g}"); + } + other => panic!("{other:?}"), + } +} + +#[test] +fn outline_arrowheads_are_reported() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota"))); + children.push(arrowheads(&[(0, 2)])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::Arrowheads]); +} + +#[test] +fn a_long_instruction_and_a_jump_over_image_bytes() { + // The jump's target counts from the start of the file: header, `cont`, then the page body. + let before = riff(&[cont(b'4', 1e-7), page(&[])]).len() - 8; + let head = [begin_page(None), begin_layer("L", None)].concat(); + let jump_len = 4 + 1 + 3 + 4; + let image = vec![0xEEu8; 37]; + let target = (before + 8 + head.len() + jump_len + image.len()) as u32; + let jump = instr(111, &fields(&[field(1, &target.to_le_bytes())])); + assert_eq!(jump.len(), jump_len); + let body = [ + head, + jump, + image, + long_instr(67, &curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48])[4..]), + end_layer(), + ] + .concat(); + let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + // The images jumped over are not read, and the warning says so. + assert_eq!(d.warnings, [Warning::UnsupportedObjects]); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn bytes_after_a_chunk_that_runs_short_are_passed_over() { + let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff]; + let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn other_byte_orders_and_coordinate_sizes_are_refused() { + let mut f = sample(); + f[..4].copy_from_slice(b"RIFX"); + assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files"))); + let mut children = vec![cont(b'2', 1e-3)]; + children.extend(tables()); + assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates"))); + assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header"))); + assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header"))); +} + +#[test] +fn a_header_without_a_usable_unit_reads_0_1_micrometers() { + for meters in [0.0, -1.0, f64::NAN, 2.0] { + let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let (w, _) = d.pages[0].size.unwrap(); + assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}"); + } +} + +#[test] +fn groups_past_the_depth_limit_are_left_out() { + let mut ins = vec![begin_page(None), begin_layer("L", None)]; + for _ in 0..6 { + ins.push(begin_group()); + } + ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); + for _ in 0..6 { + ins.push(end_group()); + } + ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); + let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep)); + // The square after the groups is still read, beside the three groups kept. + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 2); + let mut depth = 0; + let mut o = &objects[1]; + while let Object::Group { objects: kids, .. } = o { + depth += 1; + match kids.first() { + Some(k) => o = k, + None => break, + } + } + assert_eq!(depth, 3); +} + +#[test] +fn counts_past_the_limits_are_bounded() { + let ins: Vec> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect(); + let f = file(&[page(&ins)]); + let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 10); + assert!(d.warnings.contains(&Warning::TooDeep)); + let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 2); + assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size"))); + let dashed = |n: u16| { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)])); + children.extend(tables()); + read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap() + }; + let d = dashed(3); + let o: Vec = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect(); + assert_eq!(o, [0, 2]); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn a_curve_cut_short_keeps_the_points_it_holds() { + let mut c = curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48]); + // Claim 9 points where 3 are stored: the field's own length still covers only 3. + let at = c.windows(2).position(|w| w == [3, 0]).unwrap(); + c[at] = 9; + let p = page(&[begin_page(None), c]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_curve_that_lost_type_bytes_keeps_its_first_points() { + // Three whole points and only two of their type bytes. + let mut g = 3u16.to_le_bytes().to_vec(); + for (x, y) in [(0i32, 0i32), (1_000_000, 0), (1_000_000, 1_000_000)] { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend([0x0c, 0x44]); + let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)])); + let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() }; + let side = 100.0 / 25.4 * 72.0; + assert!(near(p.subpaths[0].start.x, 0.0) && near(p.subpaths[0].start.y, 0.0)); + match p.subpaths[0].segments[..] { + [craft_cdr::model::Segment::Line(e)] => assert!(near(e.x, side) && near(e.y, 0.0), "{e:?}"), + ref other => panic!("{other:?}"), + } +} + +#[test] +fn a_file_cut_short_of_its_declared_size_is_reported() { + let mut f = file(&[]); + let declared = (f.len() as u32 - 8 + 100).to_le_bytes(); + f[4..8].copy_from_slice(&declared); + let d = read_cmx(&f, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn a_page_that_ends_inside_an_instruction_is_reported() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_chunk_64_bytes_past_stray_bytes_is_found() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn stray_letters_with_a_length_past_the_file_are_passed_over() { + let mut stray = b"abcd".to_vec(); + stray.extend(0xFFFF_FF00u32.to_le_bytes()); + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl"))); + children.push(table(b"rdot", &[dashes(&[0, 0])])); + children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap(); + assert!(o.dashes.is_empty(), "{:?}", o.dashes); +} + +#[test] +fn a_curve_field_that_lost_points_is_left_out() { + // Three points claimed, two whole points stored and the third cut inside its y: the type + // bytes can't be found, so no node types are read from coordinates. + let mut g = 3u16.to_le_bytes().to_vec(); + for (x, y) in [(0i32, 0i32), (1_000_000, 0)] { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend(1_000_000i32.to_le_bytes()); + g.extend([0x40, 0x42]); + let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)])); + let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers); +} + +#[test] +fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() { + // Stray bytes, a chunk the reader passes over whose id ends in a digit, then the page. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 6]; + b.extend(chunk(b"inf1", &[0; 70])); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() { + // After stray bytes, four spaces with a small length, or letters with a length past the list, + // come before the page: neither is taken for a chunk, so the page is found. + for filler in [b" \x08\x00\x00\x00".to_vec(), b"junk\x40\x42\x0f\x00".to_vec()] { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(filler); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + } +} + +#[test] +fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() { + // Stray bytes, then a chunk the reader passes over whose body starts with the letters of a + // page chunk, then the page: only the page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut inner = b"page".to_vec(); + inner.extend(4u32.to_le_bytes()); + inner.extend([0; 10]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_canvas_or_a_container_is_reported() { + for bit in [8u8, 16] { + let mut a = attrs(Some(1), None, false); + a[0] |= bit; + let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}"); + assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some()); + } +} + +#[test] +fn a_library_color_with_its_name_reads_as_a_spot_color() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)])); + children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + match shape(&d.pages[0].layers[0].objects[0]).fill.clone() { + Some(Color::Spot { name, tint, look }) => { + assert_eq!((name.as_str(), tint), ("Brick 12", 1.0)); + assert!(look.is_some()); + } + other => panic!("{other:?}"), + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { + let mut b = b"RIFF\0\0\0\0CMX1".to_vec(); + b.extend(bytes); + let _ = read_cmx(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_samples(edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = sample(); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read_cmx(&b, Limits::default()); + } +} diff --git a/crates/cdr/tests/it/main.rs b/crates/cdr/tests/it/main.rs new file mode 100644 index 0000000000..4fc7dcbdc9 --- /dev/null +++ b/crates/cdr/tests/it/main.rs @@ -0,0 +1,8 @@ +//! Integration tests: one test binary for the crate, one module per area. +// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod bench; +mod cmx; +mod provenance; +mod read; diff --git a/crates/cdr/tests/it/provenance.rs b/crates/cdr/tests/it/provenance.rs new file mode 100644 index 0000000000..fffc006cb4 --- /dev/null +++ b/crates/cdr/tests/it/provenance.rs @@ -0,0 +1,43 @@ +//! Every layout id the code cites (`R1` ...) has a row in `PROVENANCE.md`. + +use std::collections::BTreeSet; + +/// The ids `R` in `text`. +fn ids(text: &str) -> BTreeSet { + let b = text.as_bytes(); + let mut out = BTreeSet::new(); + for (i, c) in b.iter().enumerate() { + let starts = *c == b'R' && (i == 0 || !b[i - 1].is_ascii_alphanumeric()); + if !starts { + continue; + } + let digits: String = b[i + 1..].iter().take_while(|d| d.is_ascii_digit()).map(|d| *d as char).collect(); + let ends = b.get(i + 1 + digits.len()).is_none_or(|d| !d.is_ascii_alphanumeric()); + if !digits.is_empty() && ends { + out.insert(digits.parse().unwrap()); + } + } + out +} + +#[test] +fn every_cited_layout_has_a_row() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let table = std::fs::read_to_string(dir.join("PROVENANCE.md")).unwrap(); + let rows: BTreeSet = table.lines().filter_map(|l| l.strip_prefix("| R")).filter_map(|l| l.split(' ').next()?.parse().ok()).collect(); + let mut cited = BTreeSet::new(); + for entry in std::fs::read_dir(dir.join("src")).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_some_and(|e| e == "rs") { + cited.extend(ids(&std::fs::read_to_string(&path).unwrap())); + } + } + assert!(!cited.is_empty()); + let missing: Vec<_> = cited.difference(&rows).collect(); + assert!(missing.is_empty(), "cited without a PROVENANCE.md row: {missing:?}"); +} + +#[test] +fn ids_are_found_only_as_whole_words() { + assert_eq!(ids("(R1, R12) RIFF R3x xR4 R"), BTreeSet::from([1, 12])); +} diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs new file mode 100644 index 0000000000..6ea8672635 --- /dev/null +++ b/crates/cdr/tests/it/read.rs @@ -0,0 +1,2288 @@ +//! Reading synthetic drawings of every version the reader takes, plain and compressed, and +//! hostile files. + +use craft_cdr::model::{Blend, Cap, Color, Flags, Geometry, Join, LayerKind, Matrix, Object, Segment}; +use craft_cdr::synth::{self, V, chunk, list}; +use craft_cdr::{Error, Limits, Warning, preview, read}; +use proptest::prelude::*; + +fn shapes(objects: &[Object]) -> Vec<&craft_cdr::model::Shape> { + let mut out = Vec::new(); + let mut stack: Vec<&Object> = objects.iter().rev().collect(); + while let Some(o) = stack.pop() { + match o { + Object::Shape(s) => out.push(&**s), + Object::Group { objects: kids, .. } => stack.extend(kids.iter().rev()), + Object::Clip { container, objects } => { + out.push(&**container); + stack.extend(objects.iter().rev()); + } + } + } + out +} + +/// The page and layers of the sample of `version`. +fn check_pages(d: &craft_cdr::Drawing, version: u16) { + assert_eq!(d.version, version); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{version}: {w} {h}"); + assert_eq!(d.pages.len(), 1, "{version}"); + let art = &d.pages[0].layers[0]; + assert_eq!((art.name.as_str(), art.kind), ("Art", LayerKind::Drawing)); + assert!(matches!(art.objects[3], Object::Group { objects: ref g, .. } if g.len() == 2)); + assert!(d.warnings.contains(&Warning::UnsupportedObjects)); + // The master page: its guideline every page shows, and its desktop object. + if version >= 600 { + assert_eq!(d.guides.len(), 1); + assert!((d.guides[0].angle - 90.0).abs() < 1e-9 && (d.guides[0].at.x - 36.0).abs() < 0.01); + } + assert_eq!(d.master.len(), 1); + assert_eq!(d.master[0].kind, LayerKind::Desktop); +} + +/// The shapes of the sample of `version`: rectangle, ellipse, curve, and the group's polygon and +/// arc; the text is left out. +fn check_shapes(d: &craft_cdr::Drawing, version: u16) { + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 5, "{version}"); + assert!(matches!(s[0].geometry, Geometry::Rect { radii, .. } if radii.iter().all(|r| (r - 5.0).abs() < 0.1))); + // The samples of versions 3 and 4 store their red as CMYK in percent. + let red = if version < 500 { Color::Cmyk([0.0, 1.0, 1.0, 0.0]) } else { Color::Rgb([1.0, 0.0, 0.0]) }; + assert_eq!(s[0].fill, Some(red), "{version}"); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 2.0).abs() < 0.05 && o.cap == Cap::Round, "{version}: {o:?}"); + assert!((s[0].matrix.0[4] + 100.0).abs() < 0.1 && (s[0].matrix.0[5] - 100.0).abs() < 0.1); + assert!(matches!(s[1].geometry, Geometry::Ellipse { .. }) && s[1].outline.is_none()); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths[0].closed && matches!(p.subpaths[0].segments[1], Segment::Cubic(..)))); + assert!(s[2].fill.is_none()); + if version >= 600 { + let Geometry::Path(p) = &s[3].geometry else { panic!("polygon") }; + assert_eq!(p.subpaths[0].segments.len(), 10, "five sides of two segments"); + // 5 % of 1000 mm. + let r = p.subpaths[0].start.y; + assert!((r - 0.05 * synth::POLYGON_SIDE).abs() < 0.5, "{r}"); + } + assert!(matches!(&s[4].geometry, Geometry::Path(p) if p.subpaths[0].closed)); +} + +#[test] +fn every_version_from_5_to_13_reads_its_sample() { + for version in [500, 600, 700, 800, 900, 1000, 1100, 1200, 1300] { + for compress in [false, version >= 700] { + let d = read(&synth::sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version} {compress}: {e}")); + check_pages(&d, version); + check_shapes(&d, version); + } + } +} + +#[test] +fn versions_3_and_4_read_their_sample() { + for version in [300, 400] { + let file = synth::sample(version, false); + assert_eq!(&file[8..12], if version == 300 { b"CDR " } else { b"CDR4" }); + assert!(craft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(!d.warnings.contains(&Warning::Damaged), "{version}: {:?}", d.warnings); + check_pages(&d, version); + check_shapes(&d, version); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!((o.join, &o.color), (Join::Round, &Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{version}"); + // The ellipse 50 pt right of and below the page centre, and the curve where it was drawn. + assert!((s[1].matrix.0[4] - 50.0).abs() < 0.1 && (s[1].matrix.0[5] + 50.0).abs() < 0.1, "{version}: {:?}", s[1].matrix); + assert_eq!(s[2].matrix, Matrix::IDENTITY, "{version}"); + } + // The form type alone names version 3, and a `vrsn` chunk names it under another form type. + let mut plain = vec![]; + plain.extend(synth::sample_content(300)); + check_shapes(&read(&synth::riff(300, &plain), Limits::default()).unwrap(), 300); + let mut relabeled = synth::sample(300, false); + relabeled[11] = b'5'; + assert_eq!(read(&relabeled, Limits::default()).unwrap().version, 300); +} + +/// A version 3 drawing of one layer holding `objects`. +fn drawing3(objects: Vec) -> Vec { + let page = synth::page(false, vec![synth::layer(V(300), [0, 0, 0, 0x98], "L", objects)]); + synth::riff(300, &[chunk(b"vrsn", 300u16.to_le_bytes().to_vec()), page]) +} + +/// A version 3 rectangle of 10 × 10 pt with the transforms `matrices`. +fn rect3(matrices: &[[f64; 6]]) -> synth::Node { + let v = V(300); + let mut args = vec![(30, v.rect(10.0, 10.0, 0.0))]; + if !matrices.is_empty() { + args.push((100, synth::transforms3(matrices))); + } + synth::object(v, 1, &args, None) +} + +#[test] +fn version_3_groups_place_their_objects() { + let shift = |x: f64, y: f64| [1.0, 0.0, 0.0, 1.0, x, y]; + let double = [2.0, 0.0, 0.0, 2.0, 0.0, 0.0]; + // A rectangle moved 72 pt right, in a group that doubles sizes, in a group that moves 36 pt + // up; beside the inner group, a rectangle of the outer group alone; then one outside both. + let inner = synth::group3(&[double], vec![rect3(&[shift(72.0, 0.0)])]); + let outer = synth::group3(&[shift(0.0, 36.0)], vec![inner, rect3(&[])]); + let d = read(&drawing3(vec![outer, rect3(&[shift(7.2, 0.0)])]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + assert!( + matches!(&objects[0], Object::Group { objects: g, .. } if matches!(&g[0], Object::Group { objects: i, .. } if i.len() == 1) && g.len() == 2) + ); + let s = shapes(objects); + let close = |m: &Matrix, want: [f64; 6]| m.0.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01); + // Its own shift, then the inner group's scale, then the outer group's shift. + assert!(close(&s[0].matrix, [2.0, 0.0, 0.0, 2.0, 144.0, 36.0]), "{:?}", s[0].matrix); + assert!(close(&s[1].matrix, [1.0, 0.0, 0.0, 1.0, 0.0, 36.0]), "{:?}", s[1].matrix); + assert!(close(&s[2].matrix, [1.0, 0.0, 0.0, 1.0, 7.2, 0.0]), "{:?}", s[2].matrix); + // Two matrices of one object apply in file order. + let d = read(&drawing3(vec![rect3(&[shift(72.0, 0.0), double])]), Limits::default()).unwrap(); + assert!(close(&shapes(&d.pages[0].layers[0].objects)[0].matrix, [2.0, 0.0, 0.0, 2.0, 144.0, 0.0])); +} + +#[test] +fn version_3_objects_and_groups_under_an_envelope_keep_their_outlines_and_matrices() { + // A transforms argument of one envelope entry (type 0x14). + let mut envelope = vec![0, 0, 1, 0, 0x14, 0]; + envelope.resize(14 + 24, 0); + // A matrix that moves 72 pt right, then an envelope entry whose data follows the matrix's. + let matrix = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0]]).split_off(14); + let mut shifted = vec![0, 0, 2, 0, 0x8c, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0x14, 0, 0, 0, 0, 0, 48, 0, 0, 0]; + shifted.extend(matrix); + shifted.resize(48 + 24, 0); + let v = V(300); + let bent = synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, envelope.clone())], None); + let moved = synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, shifted)], None); + let group = list(b"grp ", vec![chunk(b"lobj", v.loda(0, &[(100, envelope)])), rect3(&[])]); + let d = read(&drawing3(vec![bent, moved, group, rect3(&[])]), Limits::default()).unwrap(); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 4); + assert!(matches!(&objects[2], Object::Group { objects: g, .. } if g.len() == 1)); + let s = shapes(objects); + assert_eq!(s.len(), 4); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && s[0].matrix == Matrix::IDENTITY); + assert!((s[1].matrix.0[4] - 72.0).abs() < 0.01 && s[1].matrix.0[5].abs() < 0.01, "{:?}", s[1].matrix); + assert_eq!(s[2].matrix, Matrix::IDENTITY); + assert_eq!(d.warnings, vec![Warning::Envelopes]); +} + +#[test] +fn version_3_object_types_count_from_0() { + let v = V(300); + // `lobj` records written with their stored types: 0 rectangle, 2 curve, 3 text, 4 bitmap. + let raw = |kind: u32, coords: Vec| list(b"obj ", vec![chunk(b"lobj", v.loda(kind, &[(30, coords)]))]); + let curve = v.points(&[(0.0, 0.0, 0x00), (10.0, 0.0, 0x40)]); + let ellipse = [v.coord(40.0), v.coord(20.0), v.angle(0.0), v.angle(0.0), v.word(0)].concat(); + let d = read( + &drawing3(vec![raw(0, v.rect(10.0, 10.0, 0.0)), raw(1, ellipse), raw(2, curve), raw(3, vec![0; 8]), raw(4, vec![0; 8])]), + Limits::default(), + ) + .unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && matches!(s[1].geometry, Geometry::Ellipse { .. })); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths.len() == 1)); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); +} + +#[test] +fn version_3_fills_and_outlines_read_from_the_object() { + let v = V(300); + let styled = |fill: Vec, outline: Vec| synth::object(v, 1, &[(20, fill), (10, outline), (30, v.rect(10.0, 10.0, 0.0))], None); + let pen = |line_type: u16| synth::Pen { line_type, width: 3.0, cap: 2, join: 2 }; + let black = synth::color3(1, [0, 0, 0, 100]); + let d = read( + &drawing3(vec![ + styled(synth::fill3(1, &synth::color3(0, [0, 0, 40, 0])), synth::outline3(pen(0), black, &[3, 1])), + styled(synth::fill3(1, &synth::color3(0, [1, 0, 100, 0])), synth::outline3(pen(1), black, &[])), + styled(synth::fill3(0, &[]), synth::outline3(pen(0), synth::color3(0, [200, 0, 80, 0]), &[])), + ]), + Limits::default(), + ) + .unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + // Ink 0 is black at its tint, ink 1 white, and another number a library ink. + assert_eq!((s[0].fill.clone(), s[1].fill.clone(), s[2].fill.clone()), (Some(Color::Gray(0.4)), Some(Color::Gray(0.0)), None)); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 3.0).abs() < 0.05, "{}", o.width); + assert_eq!((o.cap, o.join, &o.dashes), (Cap::Square, Join::Bevel, &vec![3.0, 1.0])); + assert!(s[1].outline.is_none()); + assert_eq!(s[2].outline.as_ref().unwrap().color, Color::Spot { name: "Spot 0:200".into(), tint: 0.8, look: None }); + assert_eq!(d.warnings, vec![Warning::SpotLooks]); + // Fountain, texture and pattern fills are named and leave the shape unfilled; a fill or an + // outline cut short is damage. + for kind in [2, 4, 6, 7, 10] { + let d = read(&drawing3(vec![styled(synth::fill3(kind, &[0; 12]), synth::outline3(pen(1), black, &[]))]), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedFills], "{kind}"); + assert!(shapes(&d.pages[0].layers[0].objects)[0].fill.is_none()); + } + let d = read(&drawing3(vec![styled(vec![1, 1], vec![1, 0])]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].fill.is_none() && s[0].outline.is_none()); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +#[test] +fn version_3_dashes_count_toward_the_dash_limit() { + let v = V(300); + let pen = synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }; + let dashed = + || synth::object(v, 1, &[(10, synth::outline3(pen, synth::color3(1, [0, 0, 0, 100]), &[2, 2, 2])), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = read(&drawing3(vec![dashed(), dashed()]), Limits { dashes: 4, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!((s[0].outline.as_ref().unwrap().dashes.len(), s[1].outline.as_ref().unwrap().dashes.len()), (3, 0)); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + +#[test] +fn hostile_version_3_transforms_are_damage() { + let v = V(300); + let with = |arg: Vec| synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, arg)], None); + // A matrix whose data offset lies past the argument, and an argument cut inside its header. + let mut past = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 5.0, 5.0]]); + past[10..12].copy_from_slice(&60000u16.to_le_bytes()); + for arg in [past, vec![0, 0, 9]] { + let d = read(&drawing3(vec![with(arg)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].matrix, Matrix::IDENTITY); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + // A count of 65,535 over one entry reads that entry. + let mut many = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0]]); + many[2..4].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&drawing3(vec![with(many)]), Limits::default()).unwrap(); + assert!((shapes(&d.pages[0].layers[0].objects)[0].matrix.0[4] - 72.0).abs() < 0.01); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +#[test] +fn version_4_transforms_are_fixed_point_and_compose_in_file_order() { + let v = V(400); + let own = vec![ + chunk(b"loda", v.loda(1, &[(30, v.rect(10.0, 10.0, 0.0))])), + list(b"trfl", vec![chunk(b"trfd", v.trfd(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0], [0.0, 2.0, -2.0, 0.0, 0.0, 0.0]]))]), + ]; + let object = list(b"obj ", vec![list(b"lgob", own)]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])]); + let d = read(&synth::riff(400, &[chunk(b"vrsn", 400u16.to_le_bytes().to_vec()), page]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // Moved 72 pt right, then turned a quarter and doubled: (0, 0) lands at (0, 144). + let m = shapes(&d.pages[0].layers[0].objects)[0].matrix; + assert!(m.0.iter().zip([0.0, 2.0, -2.0, 0.0, 0.0, 144.0]).all(|(a, b)| (a - b).abs() < 0.01), "{m:?}"); +} + +#[test] +fn version_4_colors_are_words() { + let v = V(400); + let file = |fill: [u8; 12]| { + let doc = list(b"doc ", vec![list(b"filt", vec![chunk(b"fill", v.fill(1, &fill))])]); + let rect = synth::object(v, 1, &[(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect])]); + synth::riff(400, &[chunk(b"vrsn", 400u16.to_le_bytes().to_vec()), doc, page]) + }; + let fill_of = |fill: [u8; 12]| { + let d = read(&file(fill), Limits::default()).unwrap(); + (shapes(&d.pages[0].layers[0].objects)[0].fill.clone(), d.warnings) + }; + assert_eq!(fill_of(synth::color4(1, [20, 40, 60, 80])), (Some(Color::Cmyk([0.2, 0.4, 0.6, 0.8])), vec![])); + assert_eq!(fill_of(synth::color4(0, [0, 30, 0, 0])), (Some(Color::Gray(0.3)), vec![])); + assert_eq!(fill_of(synth::color4(0, [1, 30, 0, 0])), (Some(Color::Gray(0.0)), vec![])); + assert_eq!( + fill_of(synth::color4(0, [513, 30, 0, 0])), + (Some(Color::Spot { name: "Spot 0:513".into(), tint: 0.3, look: None }), vec![Warning::SpotLooks]) + ); + // The version 5 record read in the version 4 layout would take these values from other bytes. + assert_ne!(fill_of(synth::color(2, [20, 40, 60, 80])).0, Some(Color::Cmyk([0.2, 0.4, 0.6, 0.8]))); +} + +#[test] +fn the_version_3_page_size_is_the_distance_between_its_corners() { + let v = V(300); + for corners in [[-306.0, 396.0, 306.0, -396.0], [306.0, -396.0, -306.0, 396.0]] { + let mut b = vec![0xff; 2]; + b.extend(corners.iter().flat_map(|c| v.coord(*c))); + let d = read(&synth::riff(300, &[list(b"doc ", vec![chunk(b"mcfg", b)])]), Limits::default()).unwrap(); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{w} {h}"); + } + // Corners that give no width, and a chunk cut inside them, give no page size. + let mut flat = vec![0; 2]; + flat.extend([v.coord(10.0), v.coord(5.0), v.coord(10.0), v.coord(-5.0)].concat()); + for b in [flat.clone(), flat[..9].to_vec()] { + assert_eq!(read(&synth::riff(300, &[list(b"doc ", vec![chunk(b"mcfg", b)])]), Limits::default()).unwrap().page_size, None); + } +} + +#[test] +fn a_point_list_before_version_6_counts_its_points_with_a_u16() { + for version in [300, 400, 500] { + let v = V(version); + let mut points = v.points(&[(0.0, 0.0, 0x00), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]); + // The u16 after the count is 1 in some curves; as part of a u32 count it would run the + // count past the points. + points[2] = 1; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &[(30, points)], None)])]); + let d = read(&synth::riff(version, &[chunk(b"vrsn", version.to_le_bytes().to_vec()), page]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(matches!(&s[0].geometry, Geometry::Path(p) if p.subpaths[0].segments.len() == 2), "{version}"); + } +} + +/// The objects of the one layer of a version 1 or 2 drawing. +fn wl_objects(d: &craft_cdr::Drawing) -> &[Object] { + assert_eq!((d.pages.len(), d.pages[0].layers.len(), d.master.len(), d.guides.len()), (1, 1, 0, 0)); + &d.pages[0].layers[0].objects +} + +#[test] +fn versions_1_and_2_read_their_sample() { + for (marker, version) in [(b'e', 100), (b'l', 200), (b'm', 200)] { + let file = synth::wl_sample(marker); + assert!(file.starts_with(b"WL") && craft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.version, version); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{w} {h}"); + // The text is left out, and the group record holds nothing. + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); + let s = shapes(wl_objects(&d)); + assert_eq!(s.len(), 3); + // Front to back: the rounded rectangle, the ellipse, the curve. + assert!( + matches!(s[0].geometry, Geometry::Rect { w, h, radii } if (w - 100.0).abs() < 0.1 && (h - 50.0).abs() < 0.1 && radii.iter().all(|r| (r - 5.0).abs() < 0.1)) + ); + assert_eq!(s[0].fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0]))); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 2.0).abs() < 0.05, "{}", o.width); + assert_eq!((&o.color, o.cap, o.join, o.dashes.len()), (&Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Butt, Join::Miter, 0)); + assert!((s[0].matrix.0[4] + 100.0).abs() < 0.1 && (s[0].matrix.0[5] - 100.0).abs() < 0.1, "{:?}", s[0].matrix); + assert!(matches!(s[1].geometry, Geometry::Ellipse { w, h } if (w - 40.0).abs() < 0.1 && (h + 40.0).abs() < 0.1)); + assert!(s[1].outline.is_none() && (s[1].matrix.0[4] - 50.0).abs() < 0.1 && (s[1].matrix.0[5] + 50.0).abs() < 0.1); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths[0].closed && matches!(p.subpaths[0].segments[1], Segment::Cubic(..)))); + assert!(s[2].fill.is_none() && s[2].outline.is_some()); + assert_eq!(&s[2].matrix.0[..4], &[2.0, 0.0, 0.0, 2.0]); + } +} + +#[test] +fn a_version_1_matrix_and_point_place_the_shape() { + use synth::WlShape; + // x' = 0 x - 1 y + 72 and y' = 1 x + 0 y + 36: a quarter turn, then a shift. + let turned = synth::wl_object(WlShape::Rect { w: 10.0, h: 10.0, radius: 0.0 }, [0.0, 1.0, -1.0, 0.0, 72.0, 36.0], None, None); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[turned]), Limits::default()).unwrap(); + let m = shapes(wl_objects(&d))[0].matrix; + assert!(m.0.iter().zip([0.0, 1.0, -1.0, 0.0, 72.0, 36.0]).all(|(a, b)| (a - b).abs() < 0.01), "{m:?}"); + let at = m.apply(craft_cdr::model::Pt { x: 10.0, y: 0.0 }); + assert!((at.x - 72.0).abs() < 0.01 && (at.y - 46.0).abs() < 0.01, "{at:?}"); +} + +#[test] +fn version_1_arcs_and_text_are_left_out_with_a_warning() { + use synth::WlShape; + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let arc = synth::wl_object(WlShape::Ellipse { w: 40.0, h: 40.0, angles: (0, 900) }, unit, None, None); + let whole = synth::wl_object(WlShape::Ellipse { w: 40.0, h: 40.0, angles: (900, 900) }, unit, None, None); + let mut other = synth::wl_object(WlShape::Text, unit, None, None); + other[60] = 9; + for (records, kept) in [(vec![arc], 0), (vec![whole], 1), (vec![synth::wl_object(WlShape::Text, unit, None, None)], 0), (vec![other], 0)] { + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &records), Limits::default()).unwrap(); + assert_eq!(wl_objects(&d).len(), kept); + assert_eq!(d.warnings.contains(&Warning::UnsupportedObjects), kept == 0); + assert!(!d.warnings.contains(&Warning::Damaged)); + } +} + +#[test] +fn hostile_version_1_files_stop_within_their_bytes_and_limits() { + use synth::WlShape; + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let rect = || synth::wl_object(WlShape::Rect { w: 10.0, h: 10.0, radius: 0.0 }, unit, None, None); + let file = synth::wl_sample(b'e'); + // Cut at every length: an error, or what the bytes still hold. + for len in 0..file.len() { + let _ = read(&file[..len], Limits::default()); + } + // A body size that runs past the records' end. + let mut long = rect(); + long[28..30].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), long]), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); + // A point count larger than the record holds reads the points that fit. + let mut curve = synth::wl_object(WlShape::Curve(vec![(0.0, 0.0, 0x00), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]), unit, None, None); + curve[114..116].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[curve.clone()]), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); + // Points past the coordinate limit leave the curve out. + curve[114..116].copy_from_slice(&3u16.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[curve]), Limits { coordinates: 2, ..Limits::default() }).unwrap(); + assert_eq!(wl_objects(&d).len(), 0); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + // Objects past the object limit are left out, and records past the chunk limit stop the read. + let many: Vec> = (0..10).map(|_| rect()).collect(); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &many), Limits { objects: 4, ..Limits::default() }).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (4, vec![Warning::TooDeep])); + let groups: Vec> = (0..10).map(|_| synth::wl_group()).collect(); + assert_eq!(read(&synth::wl_file(b'e', (612.0, 792.0), &groups), Limits { chunks: 4, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read(&file, Limits { input: file.len() - 1, ..Limits::default() }), Err(Error::Limit("input size"))); + // Bytes left after the last whole record are damage. + let mut ragged = vec![rect()]; + ragged.push(vec![0; 5]); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &ragged), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); +} + +#[test] +fn a_wl_prefix_alone_is_not_a_drawing() { + for bytes in [ + &b"WL"[..], + b"WLe\0", + b"WLAN settings, exported as plain text for the help desk", + // Records that start inside the header, and a marker and a fourth byte no source gives. + b"WLe\0\x1c\0\0\0\x10\0\0\0\x1c\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", + b"WLAN\x1c\0\0\0\x1c\0\0\0\x1c\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", + ] { + assert!(!craft_cdr::is_cdr(bytes)); + assert_eq!(read(bytes, Limits::default()), Err(Error::NotCdr)); + } +} + +#[test] +fn versions_outside_1_to_27_and_other_files_are_refused() { + // No source shows a RIFF file of version 1 or 2: those versions are `WL` files. + for version in [100, 200] { + let refused = read(&synth::riff(version, &[]), Limits::default()).unwrap_err(); + assert_eq!(refused, Error::Unsupported("RIFF files of versions before 3"), "{version}"); + assert_eq!(refused.to_string(), "RIFF files of versions before 3 are not read"); + } + assert_eq!(read(&synth::riff(2800, &[]), Limits::default()), Err(Error::Version(2800))); + assert_eq!(read(b"RIFF\x04\0\0\0WAVE", Limits::default()), Err(Error::NotCdr)); + assert_eq!(read(b"RIFF\x04\0\0\0CDRX", Limits::default()), Err(Error::NotCdr)); + assert!(!craft_cdr::is_cdr(b"PK\x03\x04")); + assert!(craft_cdr::is_cdr(&synth::sample(1100, true))); +} + +#[test] +fn letters_that_count_differently_take_the_vrsn_version() { + // Version 27 saves the letter `U`, which counts as 29 the older way; the next letter with a + // `vrsn` of 2800 is refused as version 28. + let mut file = synth::sample(2700, false); + file[11] = b'U'; + let d = read(&file, Limits::default()).unwrap(); + check_pages(&d, 2700); + check_shapes(&d, 2700); + let mut file = synth::riff(2800, &[chunk(b"vrsn", 2800u16.to_le_bytes().to_vec())]); + file[11] = b'V'; + assert_eq!(read(&file, Limits::default()), Err(Error::Version(2800))); +} + +#[test] +fn every_version_from_14_to_27_reads_its_package() { + for version in [1400, 1500, 1600, 1700, 1800, 2000, 2200, 2400, 2430, 2600, 2700] { + for compress in [false, true] { + let file = synth::sample_file(version, compress); + assert!(file.starts_with(b"PK\x03\x04") && craft_cdr::is_cdr(&file), "{version}"); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version} {compress}: {e}")); + assert!(!d.warnings.contains(&Warning::Damaged), "{version} {compress}: {:?}", d.warnings); + check_pages(&d, version); + check_shapes(&d, version); + } + } +} + +/// The version 17 sample's content with `extra` added after it, as a package. +fn package17(extra: Vec, members: &[synth::Member]) -> Vec { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + body.extend(extra); + synth::package16(1700, &body, true, members) +} + +#[test] +fn lists_whose_bodies_move_to_a_data_stream_read_the_same() { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + for moved in [*b"layr", *b"obj ", *b"page"] { + let file = synth::package16_with(1700, &body, true, &[], &[moved]); + let d = read(&file, Limits::default()).unwrap(); + assert!(!d.warnings.contains(&Warning::Damaged), "{moved:?}: {:?}", d.warnings); + check_pages(&d, 1700); + check_shapes(&d, 1700); + } +} + +#[test] +fn a_data_stream_no_chunk_reads_is_not_inflated() { + // 32 MiB of picture data that the reader doesn't use, in a stream of its own. + let bitmaps = list(b"bmpt", vec![chunk(b"bmp ", vec![0; 32 << 20])]); + let file = package17(vec![bitmaps], &[]); + assert!(file.len() < 1 << 20); + let d = read(&file, Limits { inflated: 4 << 20, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); + check_shapes(&d, 1700); +} + +#[test] +fn a_redirected_list_is_inflated_and_counts_toward_the_limit() { + // A list whose body is in a stream must be inflated to be split; past the limit it is left + // out with a warning, and the rest of the drawing reads. + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + body.push(list(b"bmpt", vec![chunk(b"bmp ", vec![0; 32 << 20])])); + let file = synth::package16_with(1700, &body, true, &[], &[*b"bmpt"]); + let d = read(&file, Limits { inflated: 4 << 20, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep) && !d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + check_shapes(&d, 1700); + let d = read(&file, Limits::default()).unwrap(); + assert!(!d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn chunks_in_a_data_stream_past_a_limit_are_not_damage() { + // A record and a list in a 2 MiB stream, read with a 1 MiB member limit, stored and deflated + // with a 1 MiB inflate limit: only the limit warning. + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.resize(2 << 20, 0); + stream[(1 << 20)..(1 << 20) + 4].copy_from_slice(b"fntt"); + let mut root = b"RIFF".to_vec(); + let body = doc_of(&[redirect(b"mcfg", 0, n, 0), redirect(b"LIST", 0, 4, 1 << 20)]); + root.extend(((body.len() + 4) as u32).to_le_bytes()); + root.extend(b"CDRH"); + root.extend(body); + let m = |name: &str, data: Vec, deflate: bool| synth::Member { name: name.into(), data, deflate }; + for (deflate, limits) in [(false, Limits { member: 1 << 20, ..Limits::default() }), (true, Limits { inflated: 1 << 20, ..Limits::default() })] { + let file = synth::zip( + &[ + m("content/root.dat", root.clone(), false), + m("content/dataFileList.dat", b"data1.dat".to_vec(), false), + m("content/data/data1.dat", stream.clone(), deflate), + ], + b"", + ); + let d = read(&file, limits).unwrap(); + assert_eq!(d.warnings, vec![Warning::TooDeep], "{deflate}"); + assert!(d.page_size.is_none()); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{deflate}: {:?}", d.warnings); + } +} + +#[test] +fn encrypted_data_streams_and_other_methods_are_refused() { + let good = synth::sample_file(1700, false); + assert!(read(&good, Limits::default()).is_ok()); + // The directory entry of a data stream: its name's last place, 46 bytes after the entry start. + let name = b"content/data/data1.dat"; + let entry = good.windows(name.len()).rposition(|w| w == name).unwrap() - 46; + assert_eq!(&good[entry..entry + 4], b"PK\x01\x02"); + let mut encrypted = good.clone(); + encrypted[entry + 8] |= 1; + assert_eq!(read(&encrypted, Limits::default()), Err(Error::Unsupported("encrypted packages"))); + let mut other = good.clone(); + other[entry + 10] = 12; + assert_eq!(read(&other, Limits::default()), Err(Error::Unsupported("package compression methods other than storing and deflate"))); +} + +/// A version 17 package whose `root.dat` is `root` (the RIFF body after the form type) and whose +/// one data stream is `stream`. +fn raw_package(root: &[u8], stream: &[u8], list: &[u8]) -> Vec { + let mut riff = b"RIFF".to_vec(); + riff.extend(((root.len() + 4) as u32).to_le_bytes()); + riff.extend(b"CDRH"); + riff.extend(root); + let m = |name: &str, data: &[u8]| synth::Member { name: name.into(), data: data.to_vec(), deflate: false }; + synth::zip(&[m("content/root.dat", &riff), m("content/dataFileList.dat", list), m("content/data/data1.dat", stream)], b"") +} + +/// A chunk header for a redirect record of `stream`, `len` and `offset`. +fn redirect(id: &[u8; 4], stream: u32, len: u32, offset: u32) -> Vec { + let mut out = id.to_vec(); + out.extend(16u32.to_le_bytes()); + for v in [stream, len, offset, 0] { + out.extend(v.to_le_bytes()); + } + out +} + +#[test] +fn a_list_redirected_into_its_own_bytes_is_read_once() { + // The stream holds a `grp ` body whose children are lists redirected to that body again: + // the bytes are taken, so each child is damage and the list is read once. + for children in [1, 2] { + let len = 4 + 24 * children; + let mut stream = b"grp ".to_vec(); + for _ in 0..children { + stream.extend(redirect(b"LIST", 0, len, 0)); + } + let file = raw_package(&redirect(b"LIST", 0, len, 0), &stream, b"data1.dat"); + let d = read(&file, Limits { chunks: 100, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::Damaged], "{children}"); + } +} + +/// A `doc ` list holding `records`, as `root.dat`'s body. +fn doc_of(records: &[Vec]) -> Vec { + let records = records.concat(); + let mut body = b"LIST".to_vec(); + body.extend(((records.len() + 4) as u32).to_le_bytes()); + body.extend(b"doc "); + body.extend(records); + body +} + +#[test] +fn records_share_bytes_within_the_member_limit() { + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.extend(&mcfg); + // The same bytes, bytes that overlap them, bytes that only touch them, and the same bytes + // through a second line naming the same member: both redirects read. + for (second, list) in [ + (redirect(b"mcfg", 0, n, 0), &b"data1.dat"[..]), + (redirect(b"mcfg", 0, n, n - 1), b"data1.dat"), + (redirect(b"mcfg", 0, n, n), b"data1.dat"), + (redirect(b"mcfg", 1, n, 0), b"data1.dat\ndata1.dat"), + ] { + let file = raw_package(&doc_of(&[redirect(b"mcfg", 0, n, 0), second.clone()]), &stream, list); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{:?}: {:?}", &second[8..], d.warnings); + } + // Bytes read again take from the member limit: with a limit of the stream's 1,024 bytes, a + // record of all of them reads twice, and a third read is left out with the limit warning. + let mut stream = mcfg.clone(); + stream.resize(1024, 0); + let limits = Limits { member: 1024, ..Limits::default() }; + for (reads, warnings) in [(2, vec![]), (3, vec![Warning::TooDeep])] { + let records = vec![redirect(b"mcfg", 0, 1024, 0); reads]; + let d = read(&raw_package(&doc_of(&records), &stream, b"data1.dat"), limits).unwrap(); + assert!(d.page_size.is_some(), "{reads}"); + assert_eq!(d.warnings, warnings, "{reads}"); + } +} + +#[test] +fn a_member_two_streams_name_is_inflated_once() { + // One deflated member of 2 MiB named on two lines, a list read from one and the page size + // from the other: within a 3 MiB inflate limit it is inflated once. + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.resize(2 << 20, 0); + stream[(1 << 20)..(1 << 20) + 4].copy_from_slice(b"fntt"); + let mut root = b"RIFF".to_vec(); + let body = doc_of(&[redirect(b"LIST", 1, 4, 1 << 20), redirect(b"mcfg", 0, n, 0)]); + root.extend(((body.len() + 4) as u32).to_le_bytes()); + root.extend(b"CDRH"); + root.extend(body); + let m = |name: &str, data: Vec, deflate: bool| synth::Member { name: name.into(), data, deflate }; + let file = synth::zip( + &[ + m("content/root.dat", root, false), + m("content/dataFileList.dat", b"data1.dat\ndata1.dat".to_vec(), false), + m("content/data/data1.dat", stream, true), + ], + b"", + ); + let d = read(&file, Limits { inflated: 3 << 20, ..Limits::default() }).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{:?}", d.warnings); +} + +#[test] +fn redirects_past_their_stream_or_to_a_missing_one_are_damage() { + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + for (root, list, damaged) in [ + (redirect(b"mcfg", 0, n, 0), &b"data1.dat"[..], false), + (redirect(b"mcfg", 0, n, 0), b"data1.dat\r\n", false), + (redirect(b"mcfg", 0, n + 1, 0), b"data1.dat", true), + (redirect(b"mcfg", 0, n, u32::MAX), b"data1.dat", true), + (redirect(b"mcfg", 1, n, 0), b"data1.dat", true), + (redirect(b"mcfg", 0, n, 0), b"gone.dat", true), + (redirect(b"mcfg", 0, n, 0), b"", true), + ] { + let mut body = b"LIST".to_vec(); + body.extend(((root.len() + 4) as u32).to_le_bytes()); + body.extend(b"doc "); + body.extend(&root); + let d = read(&raw_package(&body, &mcfg, list), Limits::default()).unwrap(); + assert_eq!(d.warnings.contains(&Warning::Damaged), damaged, "{list:?} {:?}", &root[8..]); + assert_eq!(d.page_size.is_some(), !damaged); + } +} + +#[test] +fn a_redirect_record_holds_up_to_8_bytes_itself() { + let mut inline = b"vrsn".to_vec(); + inline.extend(16u32.to_le_bytes()); + inline.extend(u32::MAX.to_le_bytes()); + inline.extend(2u32.to_le_bytes()); + inline.extend(1800u16.to_le_bytes()); + inline.extend([0; 6]); + let d = read(&raw_package(&inline, b"", b""), Limits::default()).unwrap(); + assert_eq!(d.version, 1800); + // A length past the record's 8 bytes is damage, and the form type's version stands. + inline[12] = 9; + let d = read(&raw_package(&inline, b"", b""), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + assert_eq!(d.version, 1700); +} + +fn zip_of(members: &[(&str, Vec)]) -> Vec { + let m: Vec<_> = members.iter().map(|(n, d)| synth::Member { name: (*n).into(), data: d.clone(), deflate: false }).collect(); + synth::zip(&m, b"") +} + +/// Where the first central directory entry starts. +fn directory(bytes: &[u8]) -> usize { + bytes.windows(4).position(|w| w == b"PK\x01\x02").unwrap() +} + +#[test] +fn hostile_packages_are_refused() { + let riff = synth::sample(1400, false); + let good = zip_of(&[("content/riffData.cdr", riff.clone())]); + assert!(read(&good, Limits::default()).is_ok()); + // More members than a read takes. + let many: Vec<(String, Vec)> = (0..4097).map(|i| (format!("m{i}"), vec![])).collect(); + let many: Vec<(&str, Vec)> = many.iter().map(|(n, d)| (n.as_str(), d.clone())).collect(); + assert_eq!(read(&zip_of(&many), Limits::default()), Err(Error::Limit("package member count"))); + assert_eq!(read(&zip_of(&many[..4096]), Limits::default()), Err(Error::NotCdr)); + // A member named twice. + let twice = zip_of(&[("content/riffData.cdr", riff.clone()), ("content/riffData.cdr", riff.clone())]); + assert_eq!(read(&twice, Limits::default()), Err(Error::Damaged("package member named twice"))); + // A member whose bytes run into the next member's header. + let two = zip_of(&[("a", vec![1; 10]), ("content/riffData.cdr", riff.clone())]); + let mut overlap = two.clone(); + let at = directory(&two) + 20; + overlap[at..at + 4].copy_from_slice(&20u32.to_le_bytes()); + assert_eq!(read(&overlap, Limits::default()), Err(Error::Damaged("package members overlap"))); + // A central directory cut short, and an archive without its end record. + let mut short = good.clone(); + let n = short.len(); + let len_at = n - 22 + 12; + let len = u32::from_le_bytes(short[len_at..len_at + 4].try_into().unwrap()); + short[len_at..len_at + 4].copy_from_slice(&(len - 10).to_le_bytes()); + assert_eq!(read(&short, Limits::default()), Err(Error::Damaged("package directory"))); + assert_eq!(read(&good[..directory(&good) + 30], Limits::default()), Err(Error::Damaged("package directory"))); + // Encrypted members, ZIP64 fields and archives split across files. + let mut encrypted = good.clone(); + encrypted[directory(&good) + 8] |= 1; + assert_eq!(read(&encrypted, Limits::default()), Err(Error::Unsupported("encrypted packages"))); + let mut zip64 = good.clone(); + zip64[n - 22 + 10..n - 22 + 12].copy_from_slice(&[0xff, 0xff]); + assert_eq!(read(&zip64, Limits::default()), Err(Error::Unsupported("ZIP64 packages"))); + let mut split = good.clone(); + split[n - 22 + 4] = 1; + assert_eq!(read(&split, Limits::default()), Err(Error::Unsupported("packages split across files"))); +} + +#[test] +fn a_package_member_bomb_stops_at_its_stated_size_or_the_limit() { + let riff = synth::sample(1400, false); + let m = synth::Member { name: "content/riffData.cdr".into(), data: riff.clone(), deflate: true }; + let good = synth::zip(std::slice::from_ref(&m), b""); + assert!(read(&good, Limits::default()).is_ok()); + // A member that inflates past the size its entry states stops one byte past it. + let bomb = synth::zip(&[synth::Member { data: [riff.clone(), vec![0; 64 << 20]].concat(), ..m.clone() }], b""); + assert!(bomb.len() < 1 << 20); + let mut lying = bomb.clone(); + let at = directory(&bomb) + 24; + lying[at..at + 4].copy_from_slice(&(riff.len() as u32).to_le_bytes()); + assert_eq!(read(&lying, Limits::default()), Err(Error::Damaged("package member"))); + // One that states more than a member may hold, or than is left to inflate, is not inflated. + assert_eq!(read(&bomb, Limits { member: 1 << 20, ..Limits::default() }), Err(Error::Limit("package member size"))); + assert_eq!(read(&bomb, Limits { inflated: 1 << 20, ..Limits::default() }), Err(Error::Limit("inflated size"))); +} + +#[test] +fn stored_package_members_take_nothing_from_the_inflate_limit() { + // Nothing may be inflated, and the stored members of either package layout still read, as + // the same drawing does as a plain RIFF file. + let none = Limits { inflated: 0, ..Limits::default() }; + assert!(read(&synth::sample(1400, false), none).is_ok()); + for version in [1400, 1700] { + let d = read(&synth::sample_file(version, false), none).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(d.warnings.iter().all(|w| *w == Warning::UnsupportedObjects), "{version}: {:?}", d.warnings); + check_shapes(&d, version); + } + // Deflated members do take from it. + assert_eq!(read(&synth::sample_file(1400, true), none), Err(Error::Limit("inflated size"))); +} + +#[test] +fn redirect_records_that_lead_nowhere_count_toward_the_chunk_limit() { + // 3,000 redirects to a stream the package lacks: each lost record is counted. + let root: Vec = (0..3000).flat_map(|_| redirect(b"mcfg", 7, 4, 0)).collect(); + let file = raw_package(&root, b"", b"data1.dat"); + assert_eq!(read(&file, Limits { chunks: 2_000, ..Limits::default() }), Err(Error::Limit("chunk count"))); + let d = read(&file, Limits { chunks: 4_000, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn rectangles_from_version_15_give_radii_as_shares_of_half_the_shorter_side() { + let v = V(1500); + let mut c = synth::V(1500).rect(100.0, 50.0, 0.0); + // The four shares: 0.2, 0.4, 0, and 3, which half the shorter side holds to 25 pt. + for (k, share) in [0.2f64, 0.4, 0.0, 3.0].iter().enumerate() { + let at = 40 + 24 * k; + c[at..at + 8].copy_from_slice(&share.to_le_bytes()); + } + let file = + synth::riff(1500, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c.clone())], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { w, h, radii } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + assert!((w - 100.0).abs() < 1e-6 && (h - 50.0).abs() < 1e-6); + for (got, want) in radii.iter().zip([5.0, 10.0, 0.0, 25.0]) { + assert!((got - want).abs() < 1e-6, "{radii:?}"); + } + // With the scale-with flag set the radii are inches, held to half the shorter side as well. + c[32] = 1; + let file = synth::riff(1500, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { radii, .. } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + for (got, want) in radii.iter().zip([14.4, 25.0, 0.0, 25.0]) { + assert!((got - want).abs() < 1e-6, "{radii:?}"); + } +} + +#[test] +fn paths_from_version_10_read_their_points() { + let v = V(1700); + let mut c = vec![0; 4]; + c.extend(2u16.to_le_bytes()); + c.extend(1u16.to_le_bytes()); + c.extend([0; 16]); + c.extend(&v.points(&[(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0x48)])[4..]); + let objects = |version: u16| { + let v = V(version); + synth::riff( + version, + &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 0x25, &[(30, c.clone())], None)])])], + ) + }; + for version in [1000, 1300, 1500, 1700] { + let d = read(&objects(version), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Path(p) = &s[0].geometry else { panic!("{version}: {:?}", s[0].geometry) }; + assert_eq!(p.subpaths[0].segments.len(), 2); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } + // No sample before version 10 holds the type, so it is not read as a path there. + let d = read(&objects(900), Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty() && d.warnings.contains(&Warning::UnsupportedObjects)); +} + +#[test] +fn a_template_takes_its_version_from_the_vrsn_chunk() { + let mut file = synth::sample(2100, false); + file[8..12].copy_from_slice(b"CDTQ"); + assert!(craft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.version, 2100); + check_shapes(&d, 2100); + let mut bare = synth::riff(2100, &[]); + bare[8..12].copy_from_slice(b"CDTQ"); + assert_eq!(read(&bare, Limits::default()), Err(Error::NotCdr)); + // A template of a version after 27 is refused by its version, and one before 3 as a RIFF + // file of those versions. + for (version, refused) in [(2800u16, Error::Version(2800)), (200, Error::Unsupported("RIFF files of versions before 3"))] { + let mut t = synth::riff(2100, &[chunk(b"vrsn", version.to_le_bytes().to_vec())]); + t[8..12].copy_from_slice(b"CDTQ"); + assert_eq!(read(&t, Limits::default()), Err(refused)); + } +} + +#[test] +fn layers_take_their_kind_from_their_object_type() { + for version in [300, 800, 1300, 1700] { + let v = V(version); + let rect = || synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], None); + // Version 3 counts its types from 0 (R32). + let ty = |t: u32| if version < 400 { t - 1 } else { t }; + // Master page layers flagged in the older way, with the types of guides and desktop layers, + // and a drawing layer whose flags would make it a desktop layer. + let master = synth::page( + true, + vec![ + synth::layer_of_type(v, [2, 1, 1, 0x98], ty(12), "G", vec![rect()]), + synth::layer_of_type(v, [0, 1, 1, 0x98], ty(17), "D", vec![rect()]), + synth::layer_of_type(v, [8, 1, 0, 0x98], 0, "M", vec![rect()]), + ], + ); + // A drawing layer with flag bit 0x10 set, and a grid layer. + let own = synth::page( + false, + vec![ + synth::layer_of_type(v, [0x10, 0, 0, 0x98], 0, "L", vec![rect()]), + synth::layer_of_type(v, [0x1a, 0, 1, 0x98], ty(11), "Grid", vec![rect()]), + ], + ); + let body = [chunk(b"vrsn", version.to_le_bytes().to_vec()), master, own]; + let file = if version < 1400 { synth::riff(version, &body) } else { synth::package16(version, &body, true, &[]) }; + let d = read(&file, Limits::default()).unwrap(); + let kinds: Vec<_> = d.master.iter().map(|l| l.kind).collect(); + assert_eq!(kinds, [LayerKind::Guides, LayerKind::Desktop, LayerKind::Drawing], "{version}"); + let kinds: Vec<_> = d.pages[0].layers.iter().map(|l| (l.kind, l.objects.len())).collect(); + assert_eq!(kinds, [(LayerKind::Drawing, 1), (LayerKind::Grid, 1)], "{version}"); + } +} + +#[test] +fn a_lower_case_form_type_names_the_same_versions() { + let mut file = synth::sample(600, false); + file[8..12].copy_from_slice(b"cdr6"); + // The `vrsn` chunk agrees; without it the form type alone decides. + assert_eq!(read(&file, Limits::default()).unwrap().version, 600); + assert!(craft_cdr::is_cdr(&file)); + file[8..12].copy_from_slice(b"cdrX"); + assert_eq!(read(&file, Limits::default()), Err(Error::NotCdr)); +} + +#[test] +fn rectangles_keep_four_corner_radii_from_version_9() { + let v = V(900); + let c = [v.coord(100.0), v.coord(50.0), v.coord(1.0), v.coord(2.0), v.coord(3.0), v.coord(4.0)].concat(); + let file = synth::riff(900, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { radii, .. } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + for (got, want) in radii.iter().zip([1.0, 2.0, 3.0, 4.0]) { + assert!((got - want).abs() < 0.01, "{radii:?}"); + } + // Before version 9 one radius rounds every corner. + let v = V(800); + let c = [v.coord(100.0), v.coord(50.0), v.coord(6.0)].concat(); + let file = synth::riff(800, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let s = read(&file, Limits::default()).unwrap(); + let s = shapes(&s.pages[0].layers[0].objects); + assert!(matches!(s[0].geometry, Geometry::Rect { radii, .. } if radii.iter().all(|r| (r - 6.0).abs() < 0.01))); +} + +#[test] +fn version_7_guidelines_count_toward_the_object_limit() { + let v = V(700); + let mut guid = 1000u32.to_le_bytes().to_vec(); + guid.extend(1000u32.to_le_bytes()); + for i in 0..1000 { + guid.extend([0; 12]); + guid.extend(90_000_000i32.to_le_bytes()); + guid.extend([v.coord(f64::from(i)), v.coord(0.0), v.coord(f64::from(i)), v.coord(1.0), v.coord(f64::from(i)), v.coord(0.0)].concat()); + } + let file = synth::riff(700, &[chunk(b"vrsn", 700u16.to_le_bytes().to_vec()), list(b"doc ", vec![chunk(b"guid", guid)])]); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.guides.len(), 1000); + let d = read(&file, Limits { objects: 10, ..Limits::default() }).unwrap(); + assert_eq!(d.guides.len(), 10); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +/// Guidelines on any layer of the master page show on every page, not only those of its guides +/// layer: one on a drawing layer that also holds art, and one alone on the desktop layer. +#[test] +fn master_guidelines_on_any_layer_show_on_every_page() { + let v = V(1100); + let guide = |x: f64| { + let mut g = vec![0; 12]; + g.extend(90_000_000i32.to_le_bytes()); + g.extend([v.coord(x), v.coord(0.0)].concat()); + synth::object(v, 0x16, &[(16000, g)], None) + }; + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let master = synth::page( + true, + vec![synth::layer(v, [0, 0, 1, 0x98], "Art", vec![guide(10.0), rect]), synth::layer(v, [0x08, 0, 1, 0x98], "Desktop", vec![guide(20.0)])], + ); + let file = synth::riff(1100, &[master, synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", vec![])])]); + let d = read(&file, Limits::default()).unwrap(); + let mut xs: Vec = d.guides.iter().map(|g| g.at.x).collect(); + xs.sort_by(f64::total_cmp); + assert_eq!(xs.len(), 2, "{:?}", d.guides); + assert!((xs[0] - 10.0).abs() < 0.01 && (xs[1] - 20.0).abs() < 0.01, "{xs:?}"); + assert_eq!(d.master.len(), 1); + assert_eq!(d.master[0].objects.len(), 1); +} + +/// An object with more arguments than the limit keeps the ones read paired with their own types: +/// the types table runs from the stored count, not from the limit. +#[test] +fn arguments_past_the_limit_leave_the_first_ones_paired_with_their_types() { + let v = V(1100); + let mut args = vec![(30, [v.coord(40.0), v.coord(20.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())]; + args.extend((0..69).map(|i| (500 + i, vec![0; 4]))); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!( + matches!(s.first().map(|s| &s.geometry), Some(Geometry::Rect { w, h, .. }) if (w - 40.0).abs() < 0.01 && (h - 20.0).abs() < 0.01), + "{s:?}" + ); + assert!(d.warnings.contains(&Warning::Damaged)); +} + +/// Groups count toward the object limit; a group past it leaves its objects ungrouped. +#[test] +fn groups_count_toward_the_object_limit() { + fn count(objects: &[Object]) -> usize { + objects.iter().map(|o| 1 + if let Object::Group { objects: kids, .. } = o { count(kids) } else { 0 }).sum() + } + let v = V(1100); + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let nested = list(b"grp ", vec![list(b"grp ", vec![rect])]); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![nested])])]); + let d = read(&file, Limits { objects: 2, ..Limits::default() }).unwrap(); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(count(objects), 2, "{objects:?}"); + assert!(matches!(objects.as_slice(), [Object::Group { objects: kids, .. }] if matches!(kids.as_slice(), [Object::Shape(_)])), "{objects:?}"); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +/// A rectangle, ellipse, curve or polygon stored without its coordinates is left out as damage. +#[test] +fn shapes_without_their_coordinates_are_damage() { + let v = V(1100); + for kind in [1, 2, 3, 0x14] { + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, kind, &[], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty(), "{kind}"); + assert!(d.warnings.contains(&Warning::Damaged), "{kind}: {:?}", d.warnings); + } +} + +/// An object list without its `loda`, a fill or outline record that can't be read, and a `guid` +/// chunk that counts more guidelines than it holds are each damage. +#[test] +fn unreadable_records_and_lists_are_damage() { + let v = V(1300); + let rect = |args: Vec<(u32, Vec)>| { + let mut args = args; + args.push((30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())); + synth::object(v, 1, &args, None) + }; + let on_page = |objects: Vec, styles: Vec| { + let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())]; + kids.extend(styles); + kids.push(synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)])); + read(&synth::riff(1300, &kids), Limits::default()).unwrap() + }; + let d = on_page(vec![list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08])])], vec![]); + assert!(d.warnings.contains(&Warning::Damaged), "no loda: {:?}", d.warnings); + // A fill record of only its id. + let d = on_page(vec![rect(vec![(20, 4u32.to_le_bytes().to_vec())])], vec![list(b"filt", vec![chunk(b"fild", 4u32.to_le_bytes().to_vec())])]); + assert_eq!(shapes(&d.pages[0].layers[0].objects)[0].fill, None); + assert!(d.warnings.contains(&Warning::Damaged), "fill: {:?}", d.warnings); + // A tagged outline whose first records are none of record 1. + let mut outl = 9u32.to_le_bytes().to_vec(); + for _ in 0..16 { + outl.extend(5u32.to_le_bytes()); + outl.extend(0u32.to_le_bytes()); + } + let d = on_page(vec![rect(vec![(10, 9u32.to_le_bytes().to_vec())])], vec![list(b"otlt", vec![chunk(b"outl", outl)])]); + assert!(shapes(&d.pages[0].layers[0].objects)[0].outline.is_none()); + assert!(d.warnings.contains(&Warning::Damaged), "outline: {:?}", d.warnings); + // Version 7: a `guid` chunk counting three guidelines and holding one. + let mut guid = 3u32.to_le_bytes().to_vec(); + guid.extend(3u32.to_le_bytes()); + guid.extend([0; 40]); + let d = read(&synth::riff(700, &[chunk(b"vrsn", 700u16.to_le_bytes().to_vec()), list(b"doc ", vec![chunk(b"guid", guid)])]), Limits::default()) + .unwrap(); + assert_eq!(d.guides.len(), 1); + assert!(d.warnings.contains(&Warning::Damaged), "guid: {:?}", d.warnings); +} + +/// Pages keep their layers in a `gobj` list, and layers and objects their `loda` (and objects +/// their transform) in a `lgob` list. The layout with those chunks directly in the page, layer and +/// object lists reads the same. +#[test] +fn layers_and_objects_read_from_their_gobj_and_lgob_lists() { + let v = V(1000); + let c = [v.coord(10.0), v.coord(20.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat(); + let m = [1.0, 0.0, 0.0, 1.0, 5.0, 6.0]; + let nested = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c.clone())], Some(m))])]); + let plain_object = list(b"obj ", vec![chunk(b"loda", v.loda(1, &[(30, c)])), list(b"trfl", vec![chunk(b"trfd", v.trfd(&[m]))])]); + let plain_layer = list(b"layr", vec![chunk(b"flgs", vec![0, 0, 0, 0x98]), chunk(b"loda", v.loda(0, &[(1000, b"L\0".to_vec())])), plain_object]); + let plain = list(b"page", vec![chunk(b"flgs", vec![0, 0, 0, 0x90]), plain_layer]); + for page in [nested, plain] { + let d = read(&synth::riff(1000, &[page]), Limits::default()).unwrap(); + let layer = &d.pages[0].layers[0]; + assert_eq!(layer.name, "L"); + let s = shapes(&layer.objects); + assert_eq!(s.len(), 1, "{:?}", layer.objects); + assert!(matches!(s[0].geometry, Geometry::Rect { w, .. } if (w - 10.0).abs() < 0.01)); + assert!((s[0].matrix.0[4] - 5.0).abs() < 0.01 && (s[0].matrix.0[5] - 6.0).abs() < 0.01, "{:?}", s[0].matrix); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + } +} + +/// From version 7 a `LIST stlt` holds the style tables, which don't parse as chunks: it is not +/// damage. +#[test] +fn a_style_table_list_is_not_read_as_chunks() { + let v = V(1000); + let stlt = chunk(b"LIST", [b"stlt".to_vec(), 3u32.to_le_bytes().to_vec(), vec![0xff; 30]].concat()); + let d = read(&synth::riff(1000, &[list(b"doc ", vec![stlt, synth::mcfg(v, 100.0, 50.0)])]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert!(d.page_size.is_some_and(|(w, h)| (w - 100.0).abs() < 0.01 && (h - 50.0).abs() < 0.01)); +} + +/// Before version 7 a `LIST stlt` holds chunks (R4), which are read like the document's others. +#[test] +fn a_style_list_before_version_7_is_read_as_chunks() { + for version in [400, 500, 600] { + let v = V(version); + let red = if version < 500 { synth::color4(1, [0, 100, 100, 0]) } else { synth::color(5, [0, 0, 255, 0]) }; + let styles = list(b"stlt", vec![list(b"filt", vec![chunk(b"fill", v.fill(1, &red))])]); + let rect = synth::object(v, 1, &[(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect])]); + let content = vec![list(b"doc ", vec![styles]), page]; + let d = read(&synth::file_of(version, content.clone()), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].fill.is_some(), "{version}"); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + // A template, whose form type names no version, by its `vrsn` chunk. + let mut template = synth::file_of(version, content); + template[8..12].copy_from_slice(b"CDTA"); + let d = read(&template, Limits::default()).unwrap(); + assert!(shapes(&d.pages[0].layers[0].objects)[0].fill.is_some(), "{version}"); + } +} + +/// The objects of a styled drawing: a rectangle with only its style (argument 200), one whose +/// style leaves the fill and outline to its parent, and one with an outline argument of its own. +fn graphic_style_drawing(version: u16, table: synth::Node) -> Vec { + let v = V(version); + let black = synth::color(2, [0, 0, 0, 100]); + let doc = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 2.0, cap: 1, join: 1 }, &black, &[])), + chunk(b"outl", v.outline(3, synth::Pen { line_type: 1, width: 1.0, cap: 0, join: 0 }, &black, &[])), + ], + ), + table, + ], + ); + let rect = (30, v.rect(20.0, 10.0, 0.0)); + let styled = |style: u32, own: &[(u32, Vec)]| { + let mut args = vec![(200, style.to_le_bytes().to_vec())]; + args.extend(own.iter().cloned()); + args.push(rect.clone()); + synth::object(v, 1, &args, None) + }; + let objects = vec![styled(0x10, &[]), styled(0x11, &[]), styled(0x10, &[(10, 3u32.to_le_bytes().to_vec())])]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::file_of(version, vec![doc, page]) +} + +/// From version 7 an object without a fill or outline argument of its own takes its style's +/// (argument 200, `LIST stlt`), through the style's parent where the style names none; its own +/// argument wins over the style's. +#[test] +fn objects_without_their_own_fill_or_outline_take_their_styles() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + for version in [700, 800, 801, 900, 1000, 1100, 1200, 1300, 1400, 1500] { + for text in [false, true] { + let table = synth::stlt(V(version), &[(0x100, 1)], &[(0x200, 2)], &styles, text); + let d = read(&graphic_style_drawing(version, table), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3, "{version}"); + for shape in &s[..2] { + assert_eq!(shape.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version} {text}"); + assert!(shape.outline.as_ref().is_some_and(|o| (o.width - 2.0).abs() < 0.05), "{version} {text}: {:?}", shape.outline); + } + assert_eq!(s[2].fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version} {text}"); + assert!(s[2].outline.is_none(), "{version} {text}"); + assert!(d.warnings.is_empty(), "{version} {text}: {:?}", d.warnings); + } + } +} + +/// A template whose style table comes before its `vrsn` chunk still reads the table by the +/// version that chunk names. +#[test] +fn a_style_table_before_the_version_chunk_reads_by_that_version() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let table = synth::stlt(V(1000), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + let mut file = graphic_style_drawing(1000, chunk(b"junk", vec![])); + // The drawing's chunks, the table put first, ahead of `vrsn`. + let body = file.split_off(12); + file.extend(synth::plain(&table)); + file.extend(body); + file[8..12].copy_from_slice(b"CDTA"); + let len = (file.len() - 8) as u32; + file[4..8].copy_from_slice(&len.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); +} + +/// A style table that doesn't parse to its end is damage when an object needs a style from it; +/// the object is drawn with what it holds itself. +#[test] +fn a_style_table_that_does_not_parse_is_damage_when_an_object_needs_it() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let mut body = synth::stlt_body(V(1000), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + body.push(0); + let table = chunk(b"LIST", [b"stlt".to_vec(), body].concat()); + let d = read(&graphic_style_drawing(1000, table), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3); + assert!(s[0].fill.is_none() && s[0].outline.is_none()); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +/// A drawing with fill 1 (red), whose `LIST clpt` holds `groups` and whose page holds `objects`. +fn clip_drawing(version: u16, groups: Vec<(u32, Vec)>, objects: Vec) -> Vec { + let v = V(version); + let doc = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + synth::clpt(groups), + ], + ); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::file_of(version, vec![doc, page]) +} + +fn clip_rect(v: V, w: f64, extra: &[(u32, Vec)], at: [f64; 2]) -> synth::Node { + let mut args = vec![(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(w, w, 0.0))]; + args.extend(extra.iter().cloned()); + synth::object(v, 1, &args, Some([1.0, 0.0, 0.0, 1.0, at[0], at[1]])) +} + +/// A container (argument 8005) clips the group of `LIST clpt` whose `spnd` id it names; the +/// group's objects keep their own transforms, front to back. +#[test] +fn a_container_clips_the_group_it_names() { + for version in [700, 900, 1200, 1300, 1500, 1600, 2000] { + let v = V(version); + let contents = vec![clip_rect(v, 10.0, &[], [5.0, 6.0]), clip_rect(v, 20.0, &[], [-50.0, 0.0])]; + let container = clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![(0x77, contents)], vec![container]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + let [Object::Clip { container, objects: clipped }] = objects.as_slice() else { panic!("{version}: {objects:?}") }; + assert!(matches!(container.geometry, Geometry::Rect { w, .. } if (w - 40.0).abs() < 0.01), "{version}"); + let s = shapes(clipped); + assert_eq!(s.len(), 2, "{version}"); + assert!((s[0].matrix.0[4] - 5.0).abs() < 0.01 && (s[1].matrix.0[4] + 50.0).abs() < 0.01, "{version}: {:?}", s[0].matrix); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } +} + +/// The feature sample, the seed of the importer's fuzz tests, reads its style table, clipping +/// container, lens, flags, winding flag, transparency and named outline color in every version +/// from 7 to 13, plain and compressed. +#[test] +fn the_feature_sample_reads_its_styles_container_and_lens() { + for version in [700, 800, 900, 1000, 1100, 1200, 1300] { + for compress in [false, true] { + let d = read(&synth::feature_sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + let [ + Object::Shape(styled), + Object::Clip { objects: clipped, .. }, + Object::Shape(_), + Object::Shape(flagged), + Object::Group { objects: grouped, flags }, + ] = objects.as_slice() + else { + panic!("{version}: {objects:?}") + }; + assert_eq!(styled.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version}"); + assert!(styled.outline.as_ref().is_some_and(|o| o.dashes == [3.0, 1.0]), "{version}"); + let s = shapes(clipped); + assert_eq!(s.len(), 2, "{version}"); + assert!(s[1].outline.as_ref().is_some_and(|o| o.behind_fill), "{version}"); + assert_eq!(flagged.flags, Flags { hidden: true, locked: true }, "{version}"); + assert!(flagged.nonzero, "{version}"); + assert_eq!(*flags, Flags { hidden: true, locked: false }, "{version}"); + let named = shapes(grouped)[0].outline.as_ref().map(|o| o.color.clone()); + // A transparency and a named outline color are read from version 13. + if version >= 1300 { + assert_eq!((flagged.opacity, flagged.blend), (0.75, Blend::Multiply), "{version}"); + assert_eq!(named, Some(Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([1.0, 0.0, 0.0]) }), "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses], "{version} {compress}"); + } else { + assert_eq!((flagged.opacity, flagged.blend), (1.0, Blend::Normal), "{version}"); + assert_eq!(named, Some(Color::Spot { name: "Spot 0:7".into(), tint: 1.0, look: None }), "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses, Warning::SpotLooks], "{version} {compress}"); + } + } + } +} + +/// A container whose group isn't there is damage, and one whose group holds a container naming +/// it again is read once, with the limit warning; the containers stay as plain shapes. +#[test] +fn a_missing_or_repeating_clipped_group_keeps_the_container() { + let v = V(1100); + let missing = clip_rect(v, 40.0, &[synth::container(0x78)], [0.0, 0.0]); + let d = read(&clip_drawing(1100, vec![(0x77, vec![clip_rect(v, 10.0, &[], [0.0, 0.0])])], vec![missing]), Limits::default()).unwrap(); + assert!(matches!(d.pages[0].layers[0].objects.as_slice(), [Object::Shape(_)])); + assert_eq!(d.warnings, vec![Warning::Damaged]); + let inner = clip_rect(v, 10.0, &[synth::container(0x77)], [0.0, 0.0]); + let outer = clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0]); + let d = read(&clip_drawing(1100, vec![(0x77, vec![inner])], vec![outer]), Limits::default()).unwrap(); + let [Object::Clip { objects: clipped, .. }] = d.pages[0].layers[0].objects.as_slice() else { panic!("{:?}", d.pages[0].layers[0].objects) }; + assert!(matches!(clipped.as_slice(), [Object::Shape(_)]), "{clipped:?}"); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + +/// Each chunk of a clipped group counts toward the clipped chunk limit every time a container +/// names the group, empty groups included; past it the containers stay as plain shapes, and a +/// group cut off at the limit leaves out its guidelines too. +#[test] +fn containers_naming_one_group_stop_at_the_clipped_chunk_limit() { + let v = V(1100); + // The group walks 53 chunks: its `spnd`, a guideline, 50 empty groups and a rectangle. + let mut guide = vec![0; 12]; + guide.extend(90_000_000i32.to_le_bytes()); + guide.extend([v.coord(36.0), v.coord(0.0)].concat()); + let mut contents = vec![synth::object(v, 0x16, &[(16000, guide)], None)]; + contents.extend((0..50).map(|_| list(b"grp ", vec![]))); + contents.push(clip_rect(v, 10.0, &[], [0.0, 0.0])); + let containers: Vec = (0..20).map(|_| clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])).collect(); + let file = clip_drawing(1100, vec![(0x77, contents)], containers); + let count = |objects: &[Object]| objects.iter().filter(|o| matches!(o, Object::Clip { .. })).count(); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!((count(&d.pages[0].layers[0].objects), d.pages[0].layers[0].guides.len()), (20, 20)); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // Looking through the guideline's and the rectangle's lists for what they keep for themselves + // takes 13 chunks, counted once. The sixth container's walk stops after its guideline and 8 + // empty groups. + let d = read(&file, Limits { clipped_chunks: 53 * 5 + 13 + 10, ..Limits::default() }).unwrap(); + let layer = &d.pages[0].layers[0]; + assert_eq!((layer.objects.len(), count(&layer.objects), layer.guides.len()), (20, 5, 5)); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + +/// The chunks an object of a clipped group keeps for itself count toward the clipped chunk limit +/// the first time a container names the group, and are not looked through again for the next +/// containers. +#[test] +fn a_clipped_objects_own_chunks_count_once() { + let v = V(1100); + // A rectangle whose list holds 1,000 chunks before its own 5. + let synth::Node::List(form, own) = clip_rect(v, 10.0, &[], [0.0, 0.0]) else { panic!("an object is a list") }; + let rect = synth::Node::List(form, (0..1000).map(|_| chunk(b"pad ", vec![])).chain(own).collect()); + let containers: Vec = (0..20).map(|_| clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])).collect(); + let file = clip_drawing(1100, vec![(0x77, vec![rect.clone()])], containers); + let count = |d: &craft_cdr::Drawing| d.pages[0].layers[0].objects.iter().filter(|o| matches!(o, Object::Clip { .. })).count(); + // Each container walks the group's `spnd` and the rectangle's list, and the first also looks + // through the rectangle's chunks for its `loda` (1,003 chunks), `flgs` (1,001) and `trfd` + // (1,005). + let first = 1003 + 1001 + 1005; + let d = read(&file, Limits { clipped_chunks: first + 20 * 2, ..Limits::default() }).unwrap(); + assert_eq!(count(&d), 20); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // Past the limit while looking through them, no container keeps its group, nor the objects + // and guidelines read before it. + let mut guide = vec![0; 12]; + guide.extend(90_000_000i32.to_le_bytes()); + guide.extend([v.coord(36.0), v.coord(0.0)].concat()); + let before = vec![clip_rect(v, 5.0, &[], [0.0, 0.0]), synth::object(v, 0x16, &[(16000, guide)], None), rect]; + let file = clip_drawing(1100, vec![(0x77, before)], vec![clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])]); + let d = read(&file, Limits { clipped_chunks: 1000, ..Limits::default() }).unwrap(); + let layer = &d.pages[0].layers[0]; + assert!(matches!(layer.objects.as_slice(), [Object::Shape(_)]), "{:?}", layer.objects); + assert!(layer.guides.is_empty() && d.guides.is_empty(), "{:?}", layer.guides); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + // The same past the limit while looking for an object's `loda`, `flgs` or `trfd` after 1,000 + // chunks. + let synth::Node::List(form, own) = clip_rect(v, 10.0, &[], [0.0, 0.0]) else { panic!("an object is a list") }; + let [flgs, lgob @ synth::Node::List(lgob_form, kids)] = own.as_slice() else { panic!("{own:?}") }; + let [loda, transform @ synth::Node::List(trfl, trfd)] = kids.as_slice() else { panic!("{kids:?}") }; + let pads = || (0..1000).map(|_| chunk(b"pad ", vec![])); + let loda_late = synth::Node::List( + form, + vec![flgs.clone(), synth::Node::List(*lgob_form, std::iter::once(transform.clone()).chain(pads()).chain([loda.clone()]).collect())], + ); + let flags_late = synth::Node::List(form, std::iter::once(lgob.clone()).chain(pads()).chain([flgs.clone()]).collect()); + let trfd_late = synth::Node::List( + form, + vec![flgs.clone(), synth::Node::List(*lgob_form, vec![loda.clone(), synth::Node::List(*trfl, pads().chain(trfd.iter().cloned()).collect())])], + ); + for late in [loda_late, flags_late, trfd_late] { + let file = clip_drawing(1100, vec![(0x77, vec![late])], vec![clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])]); + let d = read(&file, Limits { clipped_chunks: 500, ..Limits::default() }).unwrap(); + assert!(matches!(d.pages[0].layers[0].objects.as_slice(), [Object::Shape(_)]), "{:?}", d.pages[0].layers[0].objects); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + } + // Chunks after the ones an object keeps for itself are not looked through. + let synth::Node::List(form, own) = clip_rect(v, 10.0, &[], [0.0, 0.0]) else { panic!("an object is a list") }; + let rect = synth::Node::List(form, own.into_iter().chain((0..1000).map(|_| chunk(b"pad ", vec![]))).collect()); + let containers: Vec = (0..20).map(|_| clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])).collect(); + let file = clip_drawing(1100, vec![(0x77, vec![rect])], containers); + let d = read(&file, Limits { clipped_chunks: 3 + 1 + 5 + 20 * 2, ..Limits::default() }).unwrap(); + assert_eq!(count(&d), 20); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); +} + +/// A container, fill, outline or style argument too short for the id it names is damage: the +/// shape comes in as a plain shape without that id. +#[test] +fn an_id_argument_cut_short_is_damage() { + for version in [700, 1100, 1600] { + let v = V(version); + let group = vec![(0x77, vec![clip_rect(v, 10.0, &[], [0.0, 0.0])])]; + let container = clip_rect(v, 40.0, &[(8005, vec![0x77, 0, 0])], [0.0, 0.0]); + let d = read(&clip_drawing(version, group, vec![container]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(matches!(d.pages[0].layers[0].objects.as_slice(), [Object::Shape(_)]), "{version}: {:?}", d.pages[0].layers[0].objects); + assert_eq!(d.warnings, vec![Warning::Damaged], "{version}"); + for kind in [20, 10, 200] { + let short = synth::object(v, 1, &[(kind, vec![1, 0]), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = read(&clip_drawing(version, vec![], vec![short]), Limits::default()).unwrap_or_else(|e| panic!("{version} {kind}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() == 1 && s[0].fill.is_none() && s[0].outline.is_none(), "{version} {kind}"); + assert_eq!(d.warnings, vec![Warning::Damaged], "{version} {kind}"); + } + } +} + +/// A fill or outline id that no record has is damage: the shape comes in without that paint. Id 0 +/// without a record is no paint. +#[test] +fn a_fill_or_outline_without_its_record_is_damage() { + for version in [700, 1100, 1600] { + let v = V(version); + for kind in [20, 10] { + for (id, want) in [(9u32, vec![Warning::Damaged]), (0, vec![])] { + let object = synth::object(v, 1, &[(kind, id.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = + read(&clip_drawing(version, vec![], vec![object]), Limits::default()).unwrap_or_else(|e| panic!("{version} {kind} {id}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() == 1 && s[0].fill.is_none() && s[0].outline.is_none(), "{version} {kind} {id}"); + assert_eq!(d.warnings, want, "{version} {kind} {id}"); + } + } + } +} + +/// An object with a lens or transparency (argument 8000) comes in opaque, with the lenses +/// warning; one without the argument gives no warning. +#[test] +fn lenses_and_transparency_are_named_in_the_warnings() { + for (version, lens) in [(1000, [1u8, 0, 0, 0].to_vec()), (1200, [5, 0, 0, 0].to_vec()), (1500, [0x14, 5, 0, 0, 0x75, 0, 0, 0, 5].to_vec())] { + let v = V(version); + let plain = clip_rect(v, 10.0, &[], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![], vec![plain]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + let see_through = clip_rect(v, 10.0, &[(8000, lens)], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![], vec![see_through]), Limits::default()).unwrap(); + assert_eq!(shapes(&d.pages[0].layers[0].objects).len(), 1, "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses], "{version}"); + } +} + +/// From version 13 a uniform transparency (a 117-byte record of version 1300 in argument 8000) +/// gives the shape its opacity and blend mode, records of other versions before it skipped. A +/// lens record, a value outside 0 to 100, a merge mode without a blend mode, and the record in an +/// earlier version are not applied: the shape stays opaque, with the lenses warning. +#[test] +fn a_uniform_transparency_from_version_13_applies() { + let record = |since: u32, body: Vec| [since.to_le_bytes().to_vec(), (body.len() as u32).to_le_bytes().to_vec(), body].concat(); + for version in [1300, 1500, 1600, 2000] { + let v = V(version); + let read_with = |arg: Vec| { + let d = read(&clip_drawing(version, vec![], vec![clip_rect(v, 10.0, &[(8000, arg)], [0.0, 0.0])]), Limits::default()) + .unwrap_or_else(|e| panic!("{version}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects)[0]; + ((s.opacity, s.blend), d.warnings) + }; + for (percent, merge, want) in [(25.0, 0, Blend::Normal), (0.0, 9, Blend::Multiply), (100.0, 28, Blend::Screen), (60.0, 36, Blend::Exclusion)] + { + let opacity = (1.0 - percent / 100.0) as f32; + assert_eq!(read_with(synth::transparency(percent, merge).1), ((opacity, want), vec![]), "{version} {percent} {merge}"); + } + // A record of a later version comes first. + let later = [record(1600, vec![0; 20]), synth::transparency(25.0, 0).1].concat(); + assert_eq!(read_with(later), ((0.75, Blend::Normal), vec![]), "{version}"); + let opaque = ((1.0, Blend::Normal), vec![Warning::Lenses]); + assert_eq!(read_with(record(1300, vec![0; 84])), opaque, "{version}: a lens"); + for bad in [150.0, -1.0, f64::NAN] { + assert_eq!(read_with(synth::transparency(bad, 0).1), opaque, "{version} {bad}"); + } + for merge in [1, 2, 3, 6, 7, 8, 10, 13, 18, 19, 20, 27, 37, 255] { + assert_eq!(read_with(synth::transparency(25.0, merge).1), opaque, "{version} {merge}"); + } + assert_eq!(read_with(vec![]), opaque, "{version}: empty"); + } + let d = + read(&clip_drawing(1200, vec![], vec![clip_rect(V(1200), 10.0, &[synth::transparency(25.0, 0)], [0.0, 0.0])]), Limits::default()).unwrap(); + assert_eq!(shapes(&d.pages[0].layers[0].objects)[0].opacity, 1.0); + assert_eq!(d.warnings, vec![Warning::Lenses]); +} + +/// Bit 0x01 of byte 1 of a layer's, group's or object's flags hides it and bit 0x10 of byte 0 +/// locks it, in every version; a group left ungrouped at the object limit passes its flags to its +/// objects. +#[test] +fn flags_hide_and_lock_layers_groups_and_objects() { + for version in [300, 700, 1100, 1300, 1600] { + let v = V(version); + let rect = |flags: [u8; 4]| synth::flagged(synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], None), flags); + let group = |flags: [u8; 4], objects: Vec| { + let mut kids = vec![chunk(b"flgs", flags.to_vec())]; + kids.extend(objects); + list(b"grp ", kids) + }; + let objects = vec![ + rect([0, 0, 0, 8]), + rect([0, 1, 0, 8]), + rect([0x10, 0, 0, 8]), + rect([0x10, 1, 0, 8]), + group([0x10, 1, 0, 0x10], vec![rect([0, 0, 0, 8])]), + ]; + let layers = + vec![synth::layer(v, [0, 0, 0, 0x98], "Shown", objects), synth::layer(v, [0x10, 1, 0, 0x98], "Hidden", vec![rect([0, 0, 0, 8])])]; + let file = synth::file_of(version, vec![synth::page(false, layers)]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let [shown, hidden] = d.pages[0].layers.as_slice() else { panic!("{version}: {:?}", d.pages[0].layers) }; + assert_eq!(shown.flags, Flags::default(), "{version}"); + assert_eq!(hidden.flags, Flags { hidden: true, locked: true }, "{version}"); + let f = |hidden: bool, locked: bool| Flags { hidden, locked }; + let own: Vec = shown + .objects + .iter() + .map(|o| match o { + Object::Shape(s) => s.flags, + Object::Group { flags, .. } => *flags, + Object::Clip { container, .. } => container.flags, + }) + .collect(); + assert_eq!(own, [f(false, false), f(true, false), f(false, true), f(true, true), f(true, true)], "{version}"); + assert!( + matches!(&shown.objects[4], Object::Group { objects, .. } if matches!(&objects[0], Object::Shape(s) if s.flags == Flags::default())), + "{version}" + ); + assert!(d.warnings.contains(&Warning::UnsupportedObjects) || d.warnings.is_empty(), "{version}: {:?}", d.warnings); + // Past the object limit the group's rectangle comes in ungrouped, hidden and locked. + let d = read(&file, Limits { objects: 5, ..Limits::default() }).unwrap_or_else(|e| panic!("{version}: {e}")); + let last = d.pages[0].layers[0].objects.last(); + assert!(matches!(last, Some(Object::Shape(s)) if s.flags == f(true, true)), "{version}: {last:?}"); + } +} + +/// A guideline is hidden when its own object, a group around it or its layer is. +#[test] +fn hidden_guidelines_say_so() { + for version in [700, 1300, 1600] { + let v = V(version); + let guide = |flags: [u8; 4]| { + let mut arg = vec![0; 12]; + arg.extend(90_000_000i32.to_le_bytes()); + arg.extend([v.coord(36.0), v.coord(0.0)].concat()); + synth::flagged(synth::object(v, 0x16, &[(16000, arg)], None), flags) + }; + let group = list(b"grp ", vec![chunk(b"flgs", vec![0, 1, 0, 0x10]), guide([0, 0, 0, 8])]); + let layers = vec![ + synth::layer(v, [0, 0, 0, 0x98], "Shown", vec![guide([0, 0, 0, 8]), guide([0, 1, 0, 8]), group]), + synth::layer(v, [0, 1, 0, 0x98], "Hidden", vec![guide([0, 0, 0, 8])]), + ]; + let d = read(&synth::file_of(version, vec![synth::page(false, layers)]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let hidden: Vec> = d.pages[0].layers.iter().map(|l| l.guides.iter().map(|g| g.hidden).collect()).collect(); + assert_eq!(hidden, [vec![false, true, true], vec![true]], "{version}"); + } +} + +/// Byte 0 of argument 14001 other than 0 fills the shape nonzero; 0, or no argument, fills it +/// even-odd; an argument without its byte is damage. +#[test] +fn a_winding_flag_fills_nonzero() { + for version in [300, 700, 1200, 1600] { + let v = V(version); + let read_with = |extra: &[(u32, Vec)]| { + let mut args = vec![(30, v.rect(10.0, 10.0, 0.0))]; + args.extend(extra.iter().cloned()); + let file = synth::file_of( + version, + vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])])], + ); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].nonzero, d.warnings) + }; + assert_eq!(read_with(&[(14001, vec![1, 0, 0, 0])]), (true, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![2])]), (true, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![0, 0, 0, 0])]), (false, vec![]), "{version}"); + assert_eq!(read_with(&[]), (false, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![])]), (false, vec![Warning::Damaged]), "{version}"); + } +} + +/// A `cdr8` form type makes the file the 8.01 variant whatever its `vrsn` chunk names: its style +/// table is read with the 8.01 layout. +#[test] +fn a_cdr8_file_whose_version_chunk_names_800_reads_as_801() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + for named in [800u16, 900, 1300] { + let table = synth::stlt(V(801), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + let mut file = graphic_style_drawing(801, table); + file[8..12].copy_from_slice(b"cdr8"); + let at = file.windows(4).position(|w| w == b"vrsn").unwrap() + 8; + assert_eq!(&file[at..at + 2], &801u16.to_le_bytes()); + file[at..at + 2].copy_from_slice(&named.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{named}: {e}")); + assert_eq!(d.version, 801, "{named}"); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{named}"); + assert!(d.warnings.is_empty(), "{named}: {:?}", d.warnings); + } +} + +/// Before version 6 an object names its style in 2 bytes, which is not damage; an argument too +/// short for them is. +#[test] +fn a_style_id_before_version_6_is_two_bytes() { + for version in [400, 500] { + let v = V(version); + let read_with = |style: Vec| { + let object = synth::object(v, 1, &[(200, style), (30, v.rect(10.0, 10.0, 0.0))], None); + let file = synth::file_of(version, vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects).len(), d.warnings) + }; + assert_eq!(read_with(vec![0x10, 0]), (1, vec![]), "{version}"); + assert_eq!(read_with(vec![0x10]), (1, vec![Warning::Damaged]), "{version}"); + } +} + +/// A hidden or locked group of `LIST clpt` hides or locks the objects a container clips from it. +#[test] +fn a_clipped_groups_flags_reach_its_objects() { + for version in [700, 1300, 1600] { + let v = V(version); + let group = list( + b"grp ", + vec![chunk(b"flgs", vec![0x10, 1, 0x80, 0x10]), chunk(b"spnd", 0x77u32.to_le_bytes().to_vec()), clip_rect(v, 10.0, &[], [0.0, 0.0])], + ); + let doc = list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), list(b"clpt", vec![group])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])])]); + let d = read(&synth::file_of(version, vec![doc, page]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let [Object::Clip { container, objects }] = d.pages[0].layers[0].objects.as_slice() else { + panic!("{version}: {:?}", d.pages[0].layers[0].objects) + }; + assert_eq!(container.flags, Flags::default(), "{version}"); + assert!(matches!(objects.as_slice(), [Object::Shape(s)] if s.flags == Flags { hidden: true, locked: true }), "{version}: {objects:?}"); + } +} + +/// Before version 6 a clipped group's `spnd` id is 2 bytes. +#[test] +fn a_clipped_group_id_before_version_6_is_two_bytes() { + for version in [400, 500] { + let v = V(version); + let rect = |w: f64, extra: Vec<(u32, Vec)>| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let clpt = list(b"clpt", vec![list(b"grp ", vec![chunk(b"spnd", vec![0x77, 0]), rect(10.0, vec![])])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(0x77)])])]); + let d = read(&synth::file_of(version, vec![list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), clpt]), page]), Limits::default()) + .unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + assert!(matches!(objects.as_slice(), [Object::Clip { objects, .. }] if objects.len() == 1), "{version}: {objects:?}"); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } +} + +/// A `trfd` entry ends at the next offset: one too short for its matrix makes the transform +/// damage and leaves the shape in place, even when the bytes after it would read as a matrix. A +/// table that stops before the last entry's end offset leaves that entry the rest of the record. +#[test] +fn a_transform_entry_ends_at_the_next_offset() { + for version in [400, 1100, 1300, 1600] { + let v = V(version); + let w = if version < 600 { 2 } else { 4 }; + let moved = [1.0, 0.0, 0.0, 1.0, 72.0, 0.0]; + let object = |trfd: Vec| { + let own = vec![chunk(b"loda", v.loda(1, &[(30, v.rect(10.0, 10.0, 0.0))])), list(b"trfl", vec![chunk(b"trfd", trfd)])]; + list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 8]), list(b"lgob", own)]) + }; + let read_with = |trfd: Vec| { + let file = synth::file_of(version, vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object(trfd)])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].matrix.0[4], d.warnings) + }; + let whole = v.trfd(&[moved]); + assert!((read_with(whole.clone()).0 - 72.0).abs() < 0.01, "{version}"); + // The end offset, right after the first, made 4 bytes past the entry's start. + let mut short = whole.clone(); + let start = if w == 2 { + usize::from(u16::from_le_bytes([short[3 * w], short[3 * w + 1]])) + } else { + u32::from_le_bytes(short[12..16].try_into().unwrap()) as usize + }; + short[4 * w..5 * w].copy_from_slice(&v.word(start + 4)); + assert_eq!(read_with(short), (0.0, vec![Warning::Damaged]), "{version}"); + // The entry first, then a table of its start alone at the record's end. + let entry = whole[5 * w..].to_vec(); + let at = 3 * w + entry.len(); + let mut end = [v.word(at + w), v.word(1), v.word(at)].concat(); + end.extend(entry); + end.extend(v.word(3 * w)); + let (x, warnings) = read_with(end); + assert!((x - 72.0).abs() < 0.01 && warnings.is_empty(), "{version}: {x} {warnings:?}"); + } +} + +/// From version 13 an outline's record of type 2 that names a library color gives the outline +/// that color; one without a name leaves the fixed color field. +#[test] +fn an_outline_takes_a_named_library_color_from_its_property_list() { + for version in [1300, 1500, 1600] { + let v = V(version); + let read_with = |props: Vec| { + let mut outl = v.outline(4, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &synth::color(2, [0, 0, 0, 100]), &[]); + let mut record = 2u32.to_le_bytes().to_vec(); + record.extend((props.len() as u32).to_le_bytes()); + record.extend(props); + outl.splice(4..4, record); + let doc = list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), list(b"otlt", vec![chunk(b"outl", outl)])]); + let object = synth::object(v, 1, &[(10, 4u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let file = synth::file_of(version, vec![doc, synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].outline.as_ref().map(|o| o.color.clone()), d.warnings) + }; + let named = synth::properties(&synth::color(5, [0, 0, 255, 0]), Some("Sky Blue")); + assert_eq!(read_with(named), (Some(Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([1.0, 0.0, 0.0]) }), vec![]), "{version}"); + let plain = synth::properties(&synth::color(5, [0, 0, 255, 0]), None); + assert_eq!(read_with(plain), (Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0])), vec![]), "{version}"); + } +} + +#[test] +fn linked_groups_are_left_out_with_a_warning() { + let v = V(1100); + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![list(b"lnkg", vec![rect])])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty()); + assert!(d.warnings.contains(&Warning::UnsupportedObjects)); +} + +#[test] +fn a_file_cut_short_keeps_what_it_holds() { + let full = synth::sample(900, false); + let cut = &full[..full.len() - 40]; + let d = read(cut, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + // The last page is cut inside its layer: the lists that hold the cut keep their whole + // children, so the rectangle, ellipse and curve before the cut are read. + assert_eq!(d.pages.len(), 1); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() >= 3, "{}", s.len()); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && matches!(s[1].geometry, Geometry::Ellipse { .. })); +} + +#[test] +fn a_riff_length_shorter_than_the_form_type_is_damage() { + for declared in 0u32..4 { + let mut file = synth::sample(900, false); + file[4..8].copy_from_slice(&declared.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{declared}"); + check_shapes(&d, 900); + } +} + +#[test] +fn a_zip_bomb_stops_at_the_inflate_limit() { + let v = V(1100); + let big = chunk(b"junk", vec![0; 4 << 20]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), synth::cmpr(&[big, synth::mcfg(v, 10.0, 10.0)])]); + assert!(file.len() < 64 << 10); + let limits = Limits { inflated: 1 << 20, ..Limits::default() }; + assert_eq!(read(&file, limits), Err(Error::Limit("inflated size"))); +} + +/// What a compressed stream inflates before it fails counts toward the inflate limit, so that +/// streams failing at their checksum can't each inflate up to the limit. +#[test] +fn bytes_inflated_by_a_failing_stream_count_toward_the_limit() { + let failing = || { + let mut cmpr = synth::cmpr(&[chunk(b"junk", vec![0; 600 << 10])]); + if let synth::Node::Chunk(_, body) = &mut cmpr { + // The last byte of the first block's zlib stream is part of its checksum. + let first = u32::from_le_bytes(body[4..8].try_into().unwrap()) as usize; + body[4 + 16 + first - 1] ^= 0xff; + } + cmpr + }; + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), failing(), failing()]); + let one = + read(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), failing()]), Limits { inflated: 1 << 20, ..Limits::default() }); + assert!(one.is_ok_and(|d| d.warnings == vec![Warning::Damaged])); + assert_eq!(read(&file, Limits { inflated: 1 << 20, ..Limits::default() }), Err(Error::Limit("inflated size"))); +} + +#[test] +fn a_million_empty_chunks_stop_at_the_chunk_limit() { + let kids: Vec<_> = (0..5000).map(|_| chunk(b"junk", vec![])).collect(); + let file = synth::riff(1100, &[list(b"doc ", kids)]); + let limits = Limits { chunks: 1000, ..Limits::default() }; + assert_eq!(read(&file, limits), Err(Error::Limit("chunk count"))); + assert!(read(&file, Limits::default()).is_ok()); +} + +#[test] +fn deep_nesting_is_left_out_with_a_warning() { + let v = V(1100); + let mut inner = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + for _ in 0..300 { + inner = list(b"grp ", vec![inner]); + } + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![inner])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn a_size_pool_index_out_of_range_is_damage() { + // A compressed stream whose one chunk names pool entry 7 of a pool of one. + let mut cmpr = synth::cmpr(&[chunk(b"mcfg", vec![0; 8])]); + if let synth::Node::Chunk(_, body) = &mut cmpr { + // Rebuild the stream with a bad index: the pool keeps its one size. + let mut stream = b"mcfg".to_vec(); + stream.extend(7u32.to_le_bytes()); + stream.extend([0; 8]); + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut e, &stream).unwrap(); + let z = e.finish().unwrap(); + let pool_block = body[4 + 16 + u32::from_le_bytes(body[4..8].try_into().unwrap()) as usize..].to_vec(); + let mut b = b"cmpr".to_vec(); + b.extend(((z.len() + 8) as u32).to_le_bytes()); + b.extend((stream.len() as u32).to_le_bytes()); + b.extend(body[12..20].to_vec()); + b.extend(b"CPng\x01\x00\x04\x00"); + b.extend(z); + b.extend(pool_block); + *body = b; + } + let d = read(&synth::riff(1100, &[cmpr]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn backward_and_huge_loda_offsets_do_not_panic() { + let v = V(1100); + let mut loda = v.loda(3, &[(30, v.points(&[(0.0, 0.0, 0), (1.0, 1.0, 0x40)]))]); + // The offsets table now points before the header and far past the end. + let at = u32::from_le_bytes(loda[8..12].try_into().unwrap()) as usize; + loda[at..at + 4].copy_from_slice(&40u32.to_le_bytes()); + loda[at + 4..at + 8].copy_from_slice(&2u32.to_le_bytes()); + let obj = list(b"obj ", vec![chunk(b"loda", loda)]); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![obj])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); +} + +#[test] +fn outlines_flagged_none_and_dashes_read() { + let v = V(1300); + let black = synth::color(2, [0, 0, 0, 100]); + let dashed = v.outline(9, synth::Pen { line_type: 4, width: 1.0, cap: 2, join: 2 }, &black, &[3, 1]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40)]))]; + let file = synth::riff( + 1300, + &[ + chunk(b"vrsn", 1300u16.to_le_bytes().to_vec()), + list(b"otlt", vec![chunk(b"outl", dashed)]), + synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &style, None)])]), + ], + ); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!(o.dashes, vec![3.0, 1.0]); + assert_eq!((o.cap, o.join), (Cap::Square, craft_cdr::model::Join::Bevel)); +} + +/// A curve or polygon left out at the coordinate limit gives the limit warning, not the damage +/// warning. +#[test] +fn shapes_past_the_coordinate_limit_are_not_damage() { + let v = V(1100); + let curve = synth::object(v, 3, &[(30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]))], None); + let side = synth::POLYGON_SIDE; + let mut sides = vec![0; 4]; + sides.extend(5u32.to_le_bytes()); + sides.extend([0; 8]); + sides.extend(0.05f64.to_le_bytes()); + sides.extend(0.05f64.to_le_bytes()); + sides.extend([v.coord(0.0), v.coord(0.0)].concat()); + let base = v.points(&[(0.0, side, 0x0C), (side * 0.587, side * 0.809, 0x44)]); + let polygon = synth::object(v, 0x14, &[(30, base.clone()), (11000, sides)], None); + for (objects, limit) in [(vec![curve], 2), (vec![polygon], 4)] { + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)])]); + let d = read(&file, Limits { coordinates: limit, ..Limits::default() }).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty()); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + } + // A polygon without its sides is damage, past the limit too. + let sideless = synth::object(v, 0x14, &[(30, base)], None); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![sideless])])]); + let d = read(&file, Limits { coordinates: 1, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +/// Dashes stored in an outline whose line type doesn't mark it dashed (bit 2) are not drawn: the +/// outline is solid. +#[test] +fn dashes_are_drawn_only_when_the_line_type_marks_them() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1200, 1500] { + for (line_type, dashed) in [(2, false), (0x22, false), (0x42, false), (4, true), (0x24, true), (0x44, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 1.0, cap: 0, join: 0 }, &black, &[2, 1]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40)]))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!(o.dashes.is_empty(), !dashed, "{version} {line_type:#x}: {:?}", o.dashes); + } + } +} + +/// Bit 4 of the line type puts the outline behind the fill. +#[test] +fn outlines_flagged_behind_the_fill_say_so() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1300, 1600] { + for (line_type, behind) in [(2, false), (0x22, false), (0x12, true), (0x14, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 4.0, cap: 0, join: 0 }, &black, &[]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].outline.as_ref().map(|o| o.behind_fill), Some(behind), "{version} {line_type:#x}"); + } + } +} + +/// Bit 5 of the line type scales the outline with the shape. +#[test] +fn outlines_flagged_to_scale_with_the_shape_say_so() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1300, 1600] { + for (line_type, scale_with) in [(2, false), (0x22, true), (0x12, false), (0x26, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 4.0, cap: 0, join: 0 }, &black, &[]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].outline.as_ref().map(|o| o.scale_with), Some(scale_with), "{version} {line_type:#x}"); + } + } +} + +#[test] +fn library_colors_from_version_13_keep_their_names_and_tints() { + // A model 21 color (blue, green, red, tint) shown at 50 %, and its library name. + let shown = synth::color(21, [255, 191, 128, 50]); + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(shown); + props.push(8); + let name: Vec = "Sky Blue".encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + props.extend((16 + 4 + name.len() as u32).to_le_bytes()); + props.extend([0; 16]); + props.extend(8u32.to_le_bytes()); + props.extend(name); + props.extend([0, 0, 0, 0, 0]); + let mut solid = 1300u32.to_le_bytes().to_vec(); + solid.extend((props.len() as u32).to_le_bytes()); + solid.extend(props); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(solid); + let mut fill = 4u32.to_le_bytes().to_vec(); + // A record of a later layout first, which the reader steps over. + fill.extend(2400u32.to_le_bytes()); + fill.extend(16u32.to_le_bytes()); + fill.extend([0; 16]); + fill.extend(1300u32.to_le_bytes()); + fill.extend((body.len() as u32).to_le_bytes()); + fill.extend(body); + // The same records in a plain file of version 13 and the packages of later versions. + for version in [1300, 1400, 1700, 2700] { + let v = V(version); + let style = vec![(20, 4u32.to_le_bytes().to_vec()), (30, v.rect(1.0, 1.0, 0.0))]; + let body = [ + chunk(b"vrsn", version.to_le_bytes().to_vec()), + list(b"filt", vec![chunk(b"fild", fill.clone())]), + synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]), + ]; + let file = match version { + ..1400 => synth::riff(version, &body), + 1400..1600 => synth::package14(synth::riff(version, &body), true), + _ => synth::package16(version, &body, true, &[]), + }; + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Some(Color::Spot { name, tint, look: Some(look) }) = &s[0].fill else { panic!("{version}: {:?}", s[0].fill) }; + assert_eq!((name.as_str(), *tint), ("Sky Blue", 0.5)); + // 128/255 shown at half strength comes from about 1/255 at full strength. + assert!(look[0] < 0.01 && (look[2] - 1.0).abs() < 1e-6, "{version}: {look:?}"); + } +} + +/// One rectangle of version `v` that uses fill `fill` and outline `outline` (0: none). +fn styled_rect(v: V, fill: u32, outline: u32) -> synth::Node { + let mut args = vec![(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())]; + if fill != 0 { + args.push((20, fill.to_le_bytes().to_vec())); + } + if outline != 0 { + args.push((10, outline.to_le_bytes().to_vec())); + } + synth::object(v, 1, &args, None) +} + +/// A drawing of version `v` with `styles` in its `doc` list and `objects` on one page. +fn styled_drawing(v: V, styles: Vec, objects: Vec) -> Vec { + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::riff(v.0, &[chunk(b"vrsn", v.0.to_le_bytes().to_vec()), list(b"doc ", styles), page]) +} + +/// An outline's dashes count toward the read's dashes for every shape that uses it: one outline +/// of 65,535 dashes on 260 shapes would copy 17 million dashes, past the default limit. +#[test] +fn a_shared_dashed_outline_counts_its_dashes_for_every_shape() { + let v = V(1300); + let pen = synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 }; + let outl = |dashes: &[u16]| list(b"otlt", vec![chunk(b"outl", v.outline(9, pen, &synth::color(2, [0, 0, 0, 100]), dashes))]); + let file = styled_drawing(v, vec![outl(&[2, 1].repeat(10))], (0..20).map(|_| styled_rect(v, 0, 9)).collect()); + let d = read(&file, Limits { dashes: 100, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 20); + let dashed = s.iter().filter(|s| s.outline.as_ref().is_some_and(|o| o.dashes.len() == 20)).count(); + assert_eq!(dashed, 5, "100 dashes hold five outlines of 20"); + assert!(s.iter().all(|s| s.outline.as_ref().is_some_and(|o| o.dashes.is_empty() || o.dashes.len() == 20))); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); + // An outline with more dashes than the limit is solid, not cut short. + let file = styled_drawing(v, vec![outl(&[2, 1])], vec![styled_rect(v, 0, 9)]); + let d = read(&file, Limits { dashes: 1, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].outline.as_ref().is_some_and(|o| o.dashes.is_empty()), "{:?}", s[0].outline); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + // At the default limit. + let file = styled_drawing(v, vec![outl(&[1; 65_535])], (0..260).map(|_| styled_rect(v, 0, 9)).collect()); + assert!(file.len() < 256 << 10); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let total: usize = s.iter().filter_map(|s| s.outline.as_ref()).map(|o| o.dashes.len()).sum(); + assert!(total <= Limits::default().dashes, "{total}"); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); +} + +/// A library color's name is copied for every shape that uses it: a long one keeps its first 256 +/// units and a hash of the whole name. +#[test] +fn a_library_color_keeps_the_first_256_units_of_its_name() { + let v = V(1300); + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(synth::color(21, [255, 191, 128, 100])); + props.push(8); + let name: Vec = "N".repeat(10_000).encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + props.extend((16 + 4 + name.len() as u32).to_le_bytes()); + props.extend([0; 16]); + props.extend(10_000u32.to_le_bytes()); + props.extend(name); + props.extend([0, 0, 0, 0, 0]); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(1300u32.to_le_bytes()); + body.extend((props.len() as u32).to_le_bytes()); + body.extend(props); + let mut fill = 4u32.to_le_bytes().to_vec(); + fill.extend(1300u32.to_le_bytes()); + fill.extend((body.len() as u32).to_le_bytes()); + fill.extend(body); + let d = read(&styled_drawing(v, vec![list(b"filt", vec![chunk(b"fild", fill)])], vec![styled_rect(v, 4, 0)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Some(Color::Spot { name, .. }) = &s[0].fill else { panic!("{:?}", s[0].fill) }; + assert_eq!(name.chars().count(), 256 + 17, "{name}"); + assert!(name.starts_with(&"N".repeat(256)), "{name}"); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); +} + +/// A transform or a uniform fill's color that is there but can't be read is damage: the shape +/// stays, without its transform or its fill, and the warnings say so. +#[test] +fn unreadable_transforms_and_fill_colors_are_damage() { + let v = V(1100); + let rect = [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat(); + let obj = list(b"obj ", vec![chunk(b"loda", v.loda(1, &[(30, rect)])), list(b"trfl", vec![chunk(b"trfd", vec![1, 2])])]); + let d = read(&styled_drawing(v, vec![], vec![obj]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!((s.len(), s[0].matrix), (1, craft_cdr::model::Matrix::IDENTITY)); + assert!(d.warnings.contains(&Warning::Damaged), "trfd: {:?}", d.warnings); + // A uniform fill cut off in its color record, before version 13 and from it. + for v in [V(1100), V(1300)] { + let mut fill = v.fill(4, &synth::color(2, [0, 100, 0, 0])); + fill.truncate(fill.len() - 10); + let d = read(&styled_drawing(v, vec![list(b"filt", vec![chunk(b"fild", fill)])], vec![styled_rect(v, 4, 0)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, None, "{}", v.0); + assert!(d.warnings.contains(&Warning::Damaged), "fill {}: {:?}", v.0, d.warnings); + } +} + +/// The inflate limit may be as large as `usize` holds. +#[test] +fn the_largest_inflate_limit_reads_compressed_lists() { + let d = read(&synth::sample(1100, true), Limits { inflated: usize::MAX, ..Limits::default() }).unwrap(); + check_shapes(&d, 1100); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { + let mut b = b"RIFF".to_vec(); + b.extend(bytes); + let _ = read(&b, Limits::default()); + let _ = preview(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_samples(version in prop::sample::select(vec![300u16, 400, 500, 700, 900, 1100, 1300]), compress: bool, edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = synth::sample(version, compress && version >= 700); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read(&b, Limits::default()); + let _ = preview(&b, Limits::default()); + } + + #[test] + fn never_panics_on_garbage_after_a_wl_header(marker in prop::sample::select(vec![b'e', b'l', b'm']), bytes in prop::collection::vec(any::(), 0..2048)) { + // Offsets that fit the file, so the garbage is walked as records. + let mut b = vec![b'W', b'L', marker, 0]; + b.extend(28u32.to_le_bytes()); + b.extend(28u32.to_le_bytes()); + b.extend((28 + bytes.len() as u32).to_le_bytes()); + b.extend([0; 12]); + b.extend(bytes); + prop_assert!(craft_cdr::is_cdr(&b)); + let _ = read(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_wl_files(marker in prop::sample::select(vec![b'e', b'l', b'm']), cut in any::(), edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = synth::wl_sample(marker); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read(&b, Limits::default()); + let _ = read(&b[..cut % (n + 1)], Limits::default()); + } + + #[test] + fn never_panics_on_mutated_packages(version in prop::sample::select(vec![1400u16, 1500, 1700, 2700]), edits in prop::collection::vec((any::(), any::(), any::()), 1..24)) { + // The members are edited before they are zipped, so that the edits reach the chunks and + // redirect records rather than stop at the CRC-32. + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(version)); + let mut members = if version < 1600 { + vec![synth::Member { name: "content/riffData.cdr".into(), data: synth::sample(version, false), deflate: false }] + } else { + synth::package16_members(version, &body, false, &[]) + }; + for (m, at, v) in edits { + let k = m % members.len(); + let data = &mut members[k].data; + if !data.is_empty() { + let n = data.len(); + data[at % n] = v; + } + } + let zip = synth::zip(&members, b""); + let _ = read(&zip, Limits::default()); + // The package has no picture member, and `preview` does not read the damaged drawing. + prop_assert_eq!(preview(&zip, Limits::default()), Ok(None)); + } + + #[test] + fn preview_never_panics_on_mutated_pictures(version in prop::sample::select(vec![700u16, 1100, 1300, 1500, 1700]), deflate: bool, zipped: bool, edits in prop::collection::vec((any::(), any::()), 1..24)) { + let bitmap = disp_body(5, 3, 8); + let mut b = if version < 1400 { + // A compressed list before the `DISP` chunk, which the walk passes over. + let mut content = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + content.push(synth::cmpr(&synth::sample_content(version))); + content.push(chunk(b"DISP", bitmap)); + synth::riff(version, &content) + } else { + let (name, picture) = if version < 1700 { + ("metadata/thumbnails/thumbnail.bmp", [b"BM".as_slice(), &bitmap].concat()) + } else { + ("previews/thumbnail.png", [b"\x89PNG\r\n\x1a\n".as_slice(), &bitmap].concat()) + }; + let mut picture = synth::Member { name: name.into(), data: picture, deflate }; + // Edits to the member before it is zipped reach past its CRC-32. + if !zipped { + let n = picture.data.len(); + for &(at, v) in &edits { + picture.data[at % n] = v; + } + } + if version < 1600 { + synth::zip(&[synth::Member { name: "content/riffData.cdr".into(), data: synth::sample(version, false), deflate }, picture], b"") + } else { + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(version)); + synth::package16(version, &body, deflate, &[picture]) + } + }; + if zipped || version < 1400 { + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + } + let _ = preview(&b, Limits::default()); + } +} + +/// A `DISP` body: 4 bytes, a 40-byte bitmap info header for `bits` per pixel, a full color table +/// and the rows. +fn disp_body(width: u32, rows: u32, bits: u16) -> Vec { + let mut b = 8u32.to_le_bytes().to_vec(); + b.extend(40u32.to_le_bytes()); + b.extend(width.to_le_bytes()); + b.extend(rows.to_le_bytes()); + b.extend(1u16.to_le_bytes()); + b.extend(bits.to_le_bytes()); + b.extend([0; 24]); + b.extend((0..(1u32 << bits) * 4).map(|i| i as u8)); + let stride = (width * u32::from(bits)).div_ceil(32) * 4; + b.extend((0..stride * rows).map(|i| (i * 3) as u8)); + b +} diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 4eaeaa1cf9..d83bffe713 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -66,8 +66,10 @@ craft-ui = { workspace = true, optional = true } craft-aaf = { workspace = true, optional = true } craft-aep = { workspace = true, optional = true } craft-affinity = { workspace = true, optional = true } +craft-android-res = { workspace = true, optional = true } craft-assuan = { workspace = true, optional = true } craft-captions = { workspace = true, optional = true } +craft-cdr = { workspace = true, optional = true } craft-cfb = { workspace = true, optional = true } craft-codepage = { workspace = true, optional = true } craft-crs = { workspace = true, optional = true } @@ -125,6 +127,7 @@ craft-pdn = { workspace = true, optional = true } craft-penpot = { workspace = true, optional = true } craft-pkcs7 = { workspace = true, optional = true } craft-plotter = { workspace = true, optional = true } +craft-png = { workspace = true, optional = true } craft-pptx = { workspace = true, optional = true } craft-prc = { workspace = true, optional = true } craft-psd = { workspace = true, optional = true } @@ -303,6 +306,8 @@ ai-local = ["ai", "craft-ai/local"] ai-core = ["dep:craft-ai-core"] +android-res = ["dep:craft-android-res"] + anicraft-format = ["dep:craft-anicraft-format"] assuan = ["dep:craft-assuan"] @@ -361,6 +366,9 @@ browse = ["dep:craft-browse"] captions = ["dep:craft-captions"] captions-mov-text = ["captions", "craft-captions/mov-text"] +cdr = ["dep:craft-cdr"] +cdr-synth = ["cdr", "craft-cdr/synth"] + cfb = ["dep:craft-cfb"] cloud = ["dep:craft-cloud"] @@ -449,6 +457,7 @@ ews = ["dep:craft-ews"] exr = ["dep:craft-exr"] exr-decode = ["exr", "craft-exr/decode"] +exr-zlib-inflate = ["exr", "craft-exr/zlib-inflate"] fcproj-format = ["dep:craft-fcproj-format"] @@ -621,6 +630,7 @@ media-serde = ["media", "craft-media/serde"] media-vmd = ["media", "craft-media/vmd"] media-source = ["dep:craft-media-source"] +media-source-y4m = ["media-source", "craft-media-source/y4m"] menu = ["dep:craft-menu"] @@ -711,6 +721,8 @@ plist = ["dep:craft-plist"] plotter = ["dep:craft-plotter"] plotter-serde = ["plotter", "craft-plotter/serde"] +png = ["dep:craft-png"] + ppt-binary = ["dep:craft-ppt-binary"] pptx = ["dep:craft-pptx"] @@ -902,6 +914,7 @@ theme-editor = ["dep:craft-theme-editor"] theme-store = ["dep:craft-theme-store"] tiff = ["dep:craft-tiff"] +tiff-plain-rgba16 = ["tiff", "craft-tiff/plain-rgba16"] time = ["dep:craft-time"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 2279ac71de..97c4d7721e 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -16,6 +16,8 @@ pub use craft_affinity as affinity; pub use craft_ai as ai; #[cfg(feature = "ai-core")] pub use craft_ai_core as ai_core; +#[cfg(feature = "android-res")] +pub use craft_android_res as android_res; #[cfg(feature = "anicraft-format")] pub use craft_anicraft_format as anicraft_format; #[cfg(feature = "assuan")] @@ -35,6 +37,8 @@ pub use craft_ber as ber; pub use craft_browse as browse; #[cfg(feature = "captions")] pub use craft_captions as captions; +#[cfg(feature = "cdr")] +pub use craft_cdr as cdr; #[cfg(feature = "cfb")] pub use craft_cfb as cfb; #[cfg(feature = "cloud")] @@ -281,6 +285,8 @@ pub use craft_platform as platform; pub use craft_plist as plist; #[cfg(feature = "plotter")] pub use craft_plotter as plotter; +#[cfg(feature = "png")] +pub use craft_png as png; #[cfg(feature = "ppt-binary")] pub use craft_ppt_binary as ppt_binary; #[cfg(feature = "pptx")] diff --git a/crates/develop-model/src/lib.rs b/crates/develop-model/src/lib.rs index 2df9317b12..88e66cf86e 100644 --- a/crates/develop-model/src/lib.rs +++ b/crates/develop-model/src/lib.rs @@ -9,6 +9,7 @@ pub mod controls; pub mod crs; pub mod crs_masks; +pub mod migration; pub mod presets; pub mod segmask; pub mod settings; diff --git a/crates/develop-model/src/migration.rs b/crates/develop-model/src/migration.rs new file mode 100644 index 0000000000..7d1594824d --- /dev/null +++ b/crates/develop-model/src/migration.rs @@ -0,0 +1,508 @@ +//! Map PhotoCraft Camera Raw edit fields without changing the base processing version. +//! +//! Maps Camera Raw edit fields (Light, White Balance, Effects, Color, Tone Curve, Color +//! Mixer, Color Grading, Detail, Grain, Vignette, and Calibration) into `DevelopSettings`. +//! This is a settings mapping, not a promise that two renderers produce the same pixels. + +use std::{error::Error, fmt}; + +use craft_geom::Point; +use serde_json::Value; + +use crate::{DevelopSettings, VignetteStyle, WbMode, Wheel, controls, crs}; + +/// `(camera_raw_json_key, develop_model_control_id)` for 1-to-1 scalar controls. +const SCALAR_FIELDS: &[(&str, &str)] = &[ + ("exposure", "light.exposure"), + ("contrast", "light.contrast"), + ("highlights", "light.highlights"), + ("shadows", "light.shadows"), + ("whites", "light.whites"), + ("blacks", "light.blacks"), + ("texture", "effects.texture"), + ("clarity", "effects.clarity"), + ("dehaze", "effects.dehaze"), + ("vibrance", "color.vibrance"), + ("saturation", "color.saturation"), + ("curveShadows", "curve.shadows"), + ("curveDarks", "curve.darks"), + ("curveLights", "curve.lights"), + ("curveHighlights", "curve.highlights"), + ("gradeBlending", "grading.blending"), + ("gradeBalance", "grading.balance"), + ("sharpenAmount", "detail.sharpenAmount"), + ("sharpenRadius", "detail.sharpenRadius"), + ("sharpenDetail", "detail.sharpenDetail"), + ("sharpenMasking", "detail.sharpenMasking"), + ("noiseLuminance", "detail.nrLuminance"), + ("noiseLuminanceDetail", "detail.nrDetail"), + ("noiseColor", "detail.nrColor"), + ("noiseColorDetail", "detail.nrColorDetail"), + ("grainAmount", "grain.amount"), + ("grainSize", "grain.size"), + ("grainRoughness", "grain.roughness"), + ("vignetteAmount", "vignette.amount"), + ("vignetteMidpoint", "vignette.midpoint"), + ("vignetteFeather", "vignette.feather"), + ("vignetteRoundness", "vignette.roundness"), + ("vignetteHighlights", "vignette.highlights"), + ("shadowTint", "calibration.shadowsTint"), +]; + +const EXTRA_MAPPED_FIELDS: &[&str] = &[ + "temperature", + "tint", + "curveSplits", + "pointCurve", + "pointCurveRed", + "pointCurveGreen", + "pointCurveBlue", + "hslHue", + "hslSat", + "hslLum", + "gradeShadows", + "gradeMidtones", + "gradeHighlights", + "gradeGlobal", + "vignetteStyle", + "calibrationHue", + "calibrationSat", +]; + +const MIXER_BAND_CONTROLS: [&str; 8] = ["red", "orange", "yellow", "green", "aqua", "blue", "purple", "magenta"]; + +/// The partially migrated settings and the supplied field names not yet mapped. +#[derive(Debug)] +pub struct Migration { + /// A copy of the base with only the supported fields applied. + pub settings: DevelopSettings, + /// Sorted source keys, including recognized controls not yet mapped and unknown controls. + /// Values are not included. The caller must preserve any original state it still needs. + pub unmapped_fields: Vec, +} + +/// Why a PhotoCraft Camera Raw settings object could not be migrated. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum MigrationError { + /// The supplied settings are not a JSON object. + InvalidSettingsObject, + /// The supplied exposure is not a finite number in EV. + InvalidExposure, + /// The supplied exposure is outside the develop model's control range. + ExposureOutOfRange, + /// The develop model does not define its exposure control. + MissingExposureControl, + /// A supplied scalar field is not a finite number or has an invalid representation. + InvalidField(&'static str), + /// A supplied field is outside the supported control range. + FieldOutOfRange(&'static str), + /// The develop model does not define the target control. + MissingControl(&'static str), +} + +impl fmt::Display for MigrationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidSettingsObject => f.write_str("Camera Raw edit fields must be an object"), + Self::InvalidExposure => f.write_str("exposure must be a finite number in EV"), + Self::ExposureOutOfRange => f.write_str("exposure is outside the develop control range"), + Self::MissingExposureControl => f.write_str("the develop model has no exposure control"), + Self::InvalidField(field) => write!(f, "{field} has an invalid value"), + Self::FieldOutOfRange(field) => write!(f, "{field} is outside the develop control range"), + Self::MissingControl(control) => write!(f, "the develop model has no {control} control"), + } + } +} + +impl Error for MigrationError {} + +fn invalid_field_error(field: &'static str) -> MigrationError { + if field == "exposure" { MigrationError::InvalidExposure } else { MigrationError::InvalidField(field) } +} + +fn out_of_range_error(field: &'static str) -> MigrationError { + if field == "exposure" { MigrationError::ExposureOutOfRange } else { MigrationError::FieldOutOfRange(field) } +} + +fn missing_control_error(field: &'static str, control: &'static str) -> MigrationError { + if field == "exposure" { MigrationError::MissingExposureControl } else { MigrationError::MissingControl(control) } +} + +fn finite_in_range(value: &Value, field: &'static str, min: f64, max: f64) -> Result { + let valid = value.as_f64().filter(|v| v.is_finite()).ok_or_else(|| invalid_field_error(field))?; + if !(min..=max).contains(&valid) { + return Err(out_of_range_error(field)); + } + Ok(valid) +} + +fn apply_control(settings: &mut DevelopSettings, field: &'static str, control: &'static str, value: &Value) -> Result<(), MigrationError> { + let spec = controls::find(control).ok_or_else(|| missing_control_error(field, control))?; + let valid = finite_in_range(value, field, spec.min, spec.max)?; + if !controls::set(settings, control, valid) { + return Err(missing_control_error(field, control)); + } + Ok(()) +} + +fn apply_scalars(settings: &mut DevelopSettings, fields: &serde_json::Map) -> Result<(), MigrationError> { + for &(field, control) in SCALAR_FIELDS { + if let Some(value) = fields.get(field) { + apply_control(settings, field, control, value)?; + } + } + Ok(()) +} + +fn apply_wb(settings: &mut DevelopSettings, fields: &serde_json::Map) -> Result<(), MigrationError> { + if let Some(value) = fields.get("temperature") { + let rel = finite_in_range(value, "temperature", -100.0, 100.0)?; + settings.wb.mode = WbMode::Custom; + settings.wb.temp = crs::rel_to_kelvin(rel); + } + if let Some(value) = fields.get("tint") { + let tint = finite_in_range(value, "tint", -100.0, 100.0)?; + settings.wb.mode = WbMode::Custom; + settings.wb.tint = tint; + } + Ok(()) +} + +fn apply_curve_splits(settings: &mut DevelopSettings, fields: &serde_json::Map) -> Result<(), MigrationError> { + let Some(value) = fields.get("curveSplits") else { return Ok(()) }; + let items = value.as_array().filter(|a| a.len() == 3).ok_or(MigrationError::InvalidField("curveSplits"))?; + let controls = ["curve.splitShadows", "curve.splitMid", "curve.splitHighlights"]; + let mut parsed = [0.0; 3]; + for (i, (item, control)) in items.iter().zip(controls).enumerate() { + let spec = controls::find(control).ok_or(MigrationError::MissingControl(control))?; + parsed[i] = finite_in_range(item, "curveSplits", spec.min, spec.max)?; + } + if !(parsed[0] < parsed[1] && parsed[1] < parsed[2]) { + return Err(MigrationError::InvalidField("curveSplits")); + } + settings.curve.split_shadows = parsed[0]; + settings.curve.split_mid = parsed[1]; + settings.curve.split_highlights = parsed[2]; + Ok(()) +} + +fn parse_point_curve(value: &Value, field: &'static str) -> Result, MigrationError> { + let items = value.as_array().ok_or(MigrationError::InvalidField(field))?; + if items.is_empty() { + return Ok(Vec::new()); + } + if items.len() < 2 { + return Err(MigrationError::InvalidField(field)); + } + let mut points = Vec::with_capacity(items.len()); + let mut prev_x = -1.0; + for item in items { + let pair = item.as_array().filter(|p| p.len() == 2).ok_or(MigrationError::InvalidField(field))?; + let x = finite_in_range(&pair[0], field, 0.0, 255.0)?; + let y = finite_in_range(&pair[1], field, 0.0, 255.0)?; + if x <= prev_x { + return Err(MigrationError::InvalidField(field)); + } + prev_x = x; + points.push(Point::new(x / 255.0, y / 255.0)); + } + Ok(points) +} + +fn apply_point_curves(settings: &mut DevelopSettings, fields: &serde_json::Map) -> Result<(), MigrationError> { + if let Some(v) = fields.get("pointCurve") { + settings.curve.master = parse_point_curve(v, "pointCurve")?; + } + if let Some(v) = fields.get("pointCurveRed") { + settings.curve.red = parse_point_curve(v, "pointCurveRed")?; + } + if let Some(v) = fields.get("pointCurveGreen") { + settings.curve.green = parse_point_curve(v, "pointCurveGreen")?; + } + if let Some(v) = fields.get("pointCurveBlue") { + settings.curve.blue = parse_point_curve(v, "pointCurveBlue")?; + } + Ok(()) +} + +fn apply_hsl(settings: &mut DevelopSettings, fields: &serde_json::Map) -> Result<(), MigrationError> { + for (field, suffix) in [("hslHue", "hue"), ("hslSat", "sat"), ("hslLum", "lum")] { + let Some(value) = fields.get(field) else { continue }; + let items = value.as_array().filter(|a| a.len() == 8).ok_or(MigrationError::InvalidField(field))?; + for (band, item) in MIXER_BAND_CONTROLS.iter().zip(items) { + let control = format!("mixer.{band}.{suffix}"); + let Some(spec) = controls::find(&control) else { + return Err(MigrationError::MissingControl(suffix)); + }; + let valid = finite_in_range(item, field, spec.min, spec.max)?; + controls::set(settings, &control, valid); + } + } + Ok(()) +} + +fn apply_wheel(wheel: &mut Wheel, prefix: &'static str, field: &'static str, value: &Value) -> Result<(), MigrationError> { + let obj = value.as_object().ok_or(MigrationError::InvalidField(field))?; + for (key, val) in obj { + let (target, control) = match key.as_str() { + "hue" => (&mut wheel.hue, format!("grading.{prefix}.hue")), + "sat" => (&mut wheel.sat, format!("grading.{prefix}.sat")), + "lum" => (&mut wheel.lum, format!("grading.{prefix}.lum")), + _ => return Err(MigrationError::InvalidField(field)), + }; + let Some(spec) = controls::find(&control) else { + return Err(MigrationError::MissingControl(prefix)); + }; + *target = finite_in_range(val, field, spec.min, spec.max)?; + } + Ok(()) +} + +fn apply_grading(settings: &mut DevelopSettings, fields: &serde_json::Map) -> Result<(), MigrationError> { + if let Some(v) = fields.get("gradeShadows") { + apply_wheel(&mut settings.grading.shadows, "shadows", "gradeShadows", v)?; + } + if let Some(v) = fields.get("gradeMidtones") { + apply_wheel(&mut settings.grading.midtones, "midtones", "gradeMidtones", v)?; + } + if let Some(v) = fields.get("gradeHighlights") { + apply_wheel(&mut settings.grading.highlights, "highlights", "gradeHighlights", v)?; + } + if let Some(v) = fields.get("gradeGlobal") { + apply_wheel(&mut settings.grading.global, "global", "gradeGlobal", v)?; + } + Ok(()) +} + +fn apply_vignette_style(settings: &mut DevelopSettings, fields: &serde_json::Map) -> Result<(), MigrationError> { + let Some(value) = fields.get("vignetteStyle") else { return Ok(()) }; + settings.vignette.style = match value.as_str() { + Some("highlightPriority") => VignetteStyle::HighlightPriority, + Some("colorPriority") => VignetteStyle::ColorPriority, + Some("paintOverlay") => VignetteStyle::PaintOverlay, + _ => return Err(MigrationError::InvalidField("vignetteStyle")), + }; + Ok(()) +} + +fn apply_calibration(settings: &mut DevelopSettings, fields: &serde_json::Map) -> Result<(), MigrationError> { + if let Some(value) = fields.get("calibrationHue") { + let items = value.as_array().filter(|a| a.len() == 3).ok_or(MigrationError::InvalidField("calibrationHue"))?; + settings.calibration.red_hue = finite_in_range(&items[0], "calibrationHue", -100.0, 100.0)?; + settings.calibration.green_hue = finite_in_range(&items[1], "calibrationHue", -100.0, 100.0)?; + settings.calibration.blue_hue = finite_in_range(&items[2], "calibrationHue", -100.0, 100.0)?; + } + if let Some(value) = fields.get("calibrationSat") { + let items = value.as_array().filter(|a| a.len() == 3).ok_or(MigrationError::InvalidField("calibrationSat"))?; + settings.calibration.red_sat = finite_in_range(&items[0], "calibrationSat", -100.0, 100.0)?; + settings.calibration.green_sat = finite_in_range(&items[1], "calibrationSat", -100.0, 100.0)?; + settings.calibration.blue_sat = finite_in_range(&items[2], "calibrationSat", -100.0, 100.0)?; + } + Ok(()) +} + +fn is_mapped(key: &str) -> bool { + SCALAR_FIELDS.iter().any(|(field, _)| *field == key) || EXTRA_MAPPED_FIELDS.contains(&key) +} + +/// Apply supported fields from a PhotoCraft Camera Raw settings object to an explicit base. +/// +/// Supply edit fields only, not a PSD descriptor or transport metadata. Missing fields +/// are not defaults: absent fields leave the baseline unchanged. Like a partial preset +/// this replaces only named controls, and does not normalize unrelated base fields. +/// +/// # Errors +/// +/// A non-object or an explicit mapped field that is malformed or outside the shared +/// control range is rejected rather than silently replaced or clipped. +pub fn migrate_camera_raw(base: &DevelopSettings, fields: &Value) -> Result { + let fields = fields.as_object().ok_or(MigrationError::InvalidSettingsObject)?; + let mut settings = base.clone(); + apply_scalars(&mut settings, fields)?; + apply_wb(&mut settings, fields)?; + apply_curve_splits(&mut settings, fields)?; + apply_point_curves(&mut settings, fields)?; + apply_hsl(&mut settings, fields)?; + apply_grading(&mut settings, fields)?; + apply_vignette_style(&mut settings, fields)?; + apply_calibration(&mut settings, fields)?; + let mut unmapped_fields: Vec<_> = fields.keys().filter(|key| !is_mapped(key)).cloned().collect(); + unmapped_fields.sort_unstable(); + Ok(Migration { settings, unmapped_fields }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Process; + use serde_json::json; + + #[test] + fn camera_raw_full_edit_replaces_named_fields_and_preserves_process_and_unmapped() -> Result<(), MigrationError> { + // V7 is not the default: detect an accidental restamp to the latest process. + for process in [Process::V8, Process::V7] { + let mut base = DevelopSettings { process: process.version(), ..DevelopSettings::default() }; + base.light.exposure = -0.75; + base.light.contrast = 12.0; + // Using a stored value outside today's control range detects whole-model normalization. + base.optics.distortion = 123.0; + let fields: Value = serde_json::from_str( + r#"{ + "unknownField": [1, 2], + "encodingGamma": 1.8, + "temperature": 18, + "tint": -12, + "contrast": -38, + "exposure": 1.15, + "highlights": 35, + "shadows": -50, + "whites": 49, + "blacks": -34, + "texture": 12, + "clarity": 16, + "dehaze": 8, + "vibrance": 20, + "saturation": -5, + "curveShadows": 10, + "curveDarks": -8, + "curveLights": 12, + "curveHighlights": -6, + "curveSplits": [20, 50, 80], + "pointCurve": [[0, 0], [64, 52], [255, 255]], + "pointCurveRed": [[0, 0], [255, 200]], + "pointCurveGreen": [], + "hslHue": [5, -10, 0, 12, -4, 8, 0, -3], + "hslSat": [10, 5, -8, 0, 6, -12, 4, 0], + "hslLum": [-4, 8, 2, -6, 0, 10, -2, 3], + "gradeShadows": {"hue": 210, "sat": 25, "lum": -5}, + "gradeMidtones": {"hue": 45, "sat": 10, "lum": 0}, + "gradeHighlights": {"hue": 35, "sat": 20, "lum": 4}, + "gradeGlobal": {"hue": 0, "sat": 0, "lum": 2}, + "gradeBlending": 60, + "gradeBalance": -15, + "sharpenAmount": 40, + "sharpenRadius": 1.2, + "sharpenDetail": 30, + "sharpenMasking": 20, + "noiseLuminance": 15, + "noiseLuminanceDetail": 50, + "noiseColor": 25, + "noiseColorDetail": 50, + "grainAmount": 12, + "grainSize": 25, + "grainRoughness": 50, + "vignetteAmount": -20, + "vignetteMidpoint": 45, + "vignetteFeather": 55, + "vignetteRoundness": 10, + "vignetteHighlights": 15, + "vignetteStyle": "colorPriority", + "shadowTint": -6, + "calibrationHue": [4, -3, 2], + "calibrationSat": [8, -5, 6] + }"#, + ) + .map_err(|_| MigrationError::InvalidSettingsObject)?; + let result = migrate_camera_raw(&base, &fields)?; + + let mut expected = base.clone(); + expected.wb.mode = WbMode::Custom; + expected.wb.temp = crs::rel_to_kelvin(18.0); + expected.wb.tint = -12.0; + expected.light.exposure = 1.15; + expected.light.contrast = -38.0; + expected.light.highlights = 35.0; + expected.light.shadows = -50.0; + expected.light.whites = 49.0; + expected.light.blacks = -34.0; + expected.effects.texture = 12.0; + expected.effects.clarity = 16.0; + expected.effects.dehaze = 8.0; + expected.color.vibrance = 20.0; + expected.color.saturation = -5.0; + expected.curve.shadows = 10.0; + expected.curve.darks = -8.0; + expected.curve.lights = 12.0; + expected.curve.highlights = -6.0; + expected.curve.split_shadows = 20.0; + expected.curve.split_mid = 50.0; + expected.curve.split_highlights = 80.0; + expected.curve.master = vec![Point::new(0.0, 0.0), Point::new(64.0 / 255.0, 52.0 / 255.0), Point::new(1.0, 1.0)]; + expected.curve.red = vec![Point::new(0.0, 0.0), Point::new(1.0, 200.0 / 255.0)]; + expected.curve.green = Vec::new(); + expected.mixer.red = crate::Hsl { hue: 5.0, sat: 10.0, lum: -4.0 }; + expected.mixer.orange = crate::Hsl { hue: -10.0, sat: 5.0, lum: 8.0 }; + expected.mixer.yellow = crate::Hsl { hue: 0.0, sat: -8.0, lum: 2.0 }; + expected.mixer.green = crate::Hsl { hue: 12.0, sat: 0.0, lum: -6.0 }; + expected.mixer.aqua = crate::Hsl { hue: -4.0, sat: 6.0, lum: 0.0 }; + expected.mixer.blue = crate::Hsl { hue: 8.0, sat: -12.0, lum: 10.0 }; + expected.mixer.purple = crate::Hsl { hue: 0.0, sat: 4.0, lum: -2.0 }; + expected.mixer.magenta = crate::Hsl { hue: -3.0, sat: 0.0, lum: 3.0 }; + expected.grading.shadows = Wheel { hue: 210.0, sat: 25.0, lum: -5.0 }; + expected.grading.midtones = Wheel { hue: 45.0, sat: 10.0, lum: 0.0 }; + expected.grading.highlights = Wheel { hue: 35.0, sat: 20.0, lum: 4.0 }; + expected.grading.global = Wheel { hue: 0.0, sat: 0.0, lum: 2.0 }; + expected.grading.blending = 60.0; + expected.grading.balance = -15.0; + expected.detail.sharpen_amount = 40.0; + expected.detail.sharpen_radius = 1.2; + expected.detail.sharpen_detail = 30.0; + expected.detail.sharpen_masking = 20.0; + expected.detail.nr_luminance = 15.0; + expected.detail.nr_detail = 50.0; + expected.detail.nr_color = 25.0; + expected.detail.nr_color_detail = 50.0; + expected.grain.amount = 12.0; + expected.grain.size = 25.0; + expected.grain.roughness = 50.0; + expected.vignette.amount = -20.0; + expected.vignette.midpoint = 45.0; + expected.vignette.feather = 55.0; + expected.vignette.roundness = 10.0; + expected.vignette.highlights = 15.0; + expected.vignette.style = VignetteStyle::ColorPriority; + expected.calibration.shadows_tint = -6.0; + expected.calibration.red_hue = 4.0; + expected.calibration.green_hue = -3.0; + expected.calibration.blue_hue = 2.0; + expected.calibration.red_sat = 8.0; + expected.calibration.green_sat = -5.0; + expected.calibration.blue_sat = 6.0; + assert_eq!(result.settings, expected); + assert_eq!(result.unmapped_fields, ["encodingGamma", "unknownField"]); + } + Ok(()) + } + + #[test] + fn camera_raw_absent_and_invalid_field_cases() -> Result<(), MigrationError> { + let mut base = DevelopSettings::default(); + base.light.exposure = -0.75; + let result = migrate_camera_raw(&base, &json!({ "encodingGamma": 1.8 }))?; + assert_eq!(result.settings, base); + assert_eq!(result.unmapped_fields, ["encodingGamma"]); + + assert_eq!(migrate_camera_raw(&base, &json!([])).err(), Some(MigrationError::InvalidSettingsObject)); + + // JSON cannot represent a non-finite number; serde_json serializes it to null. + for invalid in [json!({ "exposure": null }), json!({ "exposure": "NaN" }), json!({ "exposure": f64::INFINITY })] { + assert_eq!(migrate_camera_raw(&base, &invalid).err(), Some(MigrationError::InvalidExposure)); + } + assert_eq!(migrate_camera_raw(&base, &json!({ "exposure": 5.1 })).err(), Some(MigrationError::ExposureOutOfRange)); + assert_eq!(migrate_camera_raw(&base, &json!({ "contrast": "high" })).err(), Some(MigrationError::InvalidField("contrast"))); + assert_eq!(migrate_camera_raw(&base, &json!({ "contrast": 101 })).err(), Some(MigrationError::FieldOutOfRange("contrast"))); + assert_eq!(migrate_camera_raw(&base, &json!({ "sharpenRadius": 0.4 })).err(), Some(MigrationError::FieldOutOfRange("sharpenRadius"))); + assert_eq!(migrate_camera_raw(&base, &json!({ "temperature": 101 })).err(), Some(MigrationError::FieldOutOfRange("temperature"))); + assert_eq!(migrate_camera_raw(&base, &json!({ "curveSplits": [50, 25, 75] })).err(), Some(MigrationError::InvalidField("curveSplits"))); + assert_eq!(migrate_camera_raw(&base, &json!({ "pointCurve": [[10, 10]] })).err(), Some(MigrationError::InvalidField("pointCurve"))); + assert_eq!(migrate_camera_raw(&base, &json!({ "hslHue": [0, 0] })).err(), Some(MigrationError::InvalidField("hslHue"))); + assert_eq!(migrate_camera_raw(&base, &json!({ "gradeShadows": {"bad": 1} })).err(), Some(MigrationError::InvalidField("gradeShadows"))); + assert_eq!(migrate_camera_raw(&base, &json!({ "vignetteStyle": "unknown" })).err(), Some(MigrationError::InvalidField("vignetteStyle"))); + assert_eq!( + migrate_camera_raw(&base, &json!({ "calibrationHue": [0, 0, 101] })).err(), + Some(MigrationError::FieldOutOfRange("calibrationHue")) + ); + Ok(()) + } +} diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml index 6d78859832..19335b990f 100644 --- a/crates/develop/Cargo.toml +++ b/crates/develop/Cargo.toml @@ -11,9 +11,13 @@ repository.workspace = true workspace = true [dependencies] +craft-color = { workspace = true } craft-color-transform = { workspace = true } craft-develop-model = { workspace = true } +craft-geom = { workspace = true } +craft-raw = { workspace = true } serde = { workspace = true } +serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } @@ -21,4 +25,3 @@ rayon = { workspace = true } [dev-dependencies] craft-render-parity = { workspace = true } proptest = { workspace = true } -serde_json = { workspace = true } diff --git a/crates/develop/README.md b/crates/develop/README.md index 6cab634280..14e194206e 100644 --- a/crates/develop/README.md +++ b/crates/develop/README.md @@ -12,10 +12,20 @@ craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "` (`Rgb32f`, `Rgba8`, `Plane`), separable blur, resampling, point sampling, morphology, and `Histogram`. | +| `sensor` | `crates/raw` | Sensor normalization, DNG opcodes (`OpcodeList1/2/3`), Bayer (AHD/PPG/Bilinear) & X-Trans demosaicing, highlight reconstruction, DNG colour matrices (`color`), `ProfileGainTableMap` evaluation (`gaintable`), and binned preview development. | | `tone` | `crates/pipeline` | Global tone mapping (`ToneMap` and `CameraTone`) from scene luminance to display-linear luminance, SDR and HDR. | | `inpaint` | `crates/inpaint` | Content-aware hole filling for spot removal: `complete` (multi-scale patch completion with PatchMatch) and `membrane_fill` (a smooth harmonic fill, its seed and fallback). Interleaved `f32` buffers of any channel count, a fixed-seed RNG, the same result on any number of threads. | @@ -39,7 +49,12 @@ Differences from LightCraft (ordinary-range output is covered by the baseline fi summed-area counts or padded table cannot be represented; patch-area arithmetic no longer overflows `i32`. An already-cancelled oversized-patch request returns `Cancelled`, not an unavailable-patch result. -## Not here yet +## Limits -The rest of the pipeline: the rest of colour, raster, the sensor stage, raw loading and the render stages. No app uses this crate -yet. +This crate includes the sensor stage and consumes decoded images from `craft-raw`. Raw loading +and end-to-end render orchestration remain outside it. + +For integer DNGs with a `LinearizationTable` and a nonempty `OpcodeList1`, `craft-raw` returns the +table unapplied. Shared sensor development and binned previews apply it after `OpcodeList1`, +before black/white normalisation and `OpcodeList2`. Already-linearised and floating-point +samples are not remapped. diff --git a/crates/develop/src/auto.rs b/crates/develop/src/auto.rs new file mode 100644 index 0000000000..f11382570d --- /dev/null +++ b/crates/develop/src/auto.rs @@ -0,0 +1,309 @@ +//! Auto tone (a Lightroom-like recipe, see [`auto_tone`]) and auto white balance (grey-world +//! statistics on a proxy). + +use craft_color_transform::cct::xy_to_temp_tint; +use craft_color_transform::{REC2020, Xy, bradford}; +use craft_develop_model::DevelopSettings; +use serde::Serialize; + +use crate::colorops::luminance_2020; +use crate::local::{WbSource, effective_wb}; +use crate::raster::Rgb32f; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)] +pub struct AutoTone { + pub exposure: f64, + pub contrast: f64, + pub highlights: f64, + pub shadows: f64, + pub whites: f64, + pub blacks: f64, + pub vibrance: f64, + pub saturation: f64, +} + +/// Exposure in EV that Auto adds per EV of the scene's log-average luminance (the slope is negative: +/// darker scenes get more). The slope is Lightroom's: regressing the Exposure its Auto chose on 24 +/// raw photos against our own [`scene_log_mean`] of each gives -0.41 EV/EV (r = -0.92). +const EXPOSURE_SLOPE: f64 = -0.41; +/// Exposure for a scene whose log-average luminance is middle grey: fitted, with [`CONTRAST`] and +/// [`VIBRANCE`], so our renders match Lightroom's Auto results on those photos (see [`auto_tone`]). +const EXPOSURE_AT_GREY: f64 = -0.58; +/// Highlights and Shadows are Lightroom's own: the average its Auto chose on the 24 photos (our +/// sliders aim at the same as its). Freeing them as well matched no better on held-out photos and +/// left them poorly determined. +const HIGHLIGHTS: f64 = -66.0; +const SHADOWS: f64 = 52.0; +/// Contrast and Vibrance are fitted: our slider scales differ from Lightroom's, and our base tone is +/// flatter, so Contrast is far above its +6. Whites, Blacks and Saturation stay at 0 (Whites and +/// Blacks made no difference to the match; Lightroom leaves Saturation at about 0). +const CONTRAST: f64 = 68.0; +const VIBRANCE: f64 = 30.0; + +/// The scene's log-average luminance under the current white balance, in EV relative to middle grey +/// (the mean of log2(Y / 0.18) over a 512 px proxy, scene-linear, before any tone curve). Pixels that +/// aren't finite (a damaged decode) are left out: they get no weight when the proxy is made, and +/// proxy pixels made only of them are skipped. `None` when no pixel is valid. +pub fn scene_log_mean(src: &Rgb32f, info: &WbSource, s: &DevelopSettings) -> Option { + let (mut clean, mut weight) = (src.clone(), Rgb32f::new(src.width, src.height)); + let mut any = false; + for (p, w) in clean.data.iter_mut().zip(weight.data.iter_mut()) { + if p.iter().all(|v| v.is_finite()) { + *w = [1.0; 3]; + any = true; + } else { + *p = [0.0; 3]; + } + } + if !any { + return None; + } + let fit = |img: &Rgb32f| crate::raster::resample::fit(img, 512, 512, crate::raster::resample::Filter::Box); + let (img, weight) = (fit(&clean), fit(&weight)); + // the mean of the valid pixels under each proxy pixel + let kept: Vec<[f32; 3]> = img.data.iter().zip(&weight.data).filter(|(_, w)| w[0] > 1e-6).map(|(p, w)| p.map(|v| v / w[0])).collect(); + let mut kept = Rgb32f { width: kept.len(), height: 1, data: kept }; + let base = DevelopSettings { wb: s.wb, process: s.process, ..DevelopSettings::default() }; + // (white balance is per pixel: the valid pixels can be balanced in a row of their own) + crate::local::scene_linear_pre(&mut kept, info, &base); + let (mut sum, mut n) = (0f64, 0usize); + for c in &kept.data { + let ev = (luminance_2020(*c).max(1e-6) / 0.18).log2(); + if ev.is_finite() { + sum += ev as f64; + n += 1; + } + } + (n > 0).then(|| sum / n as f64) +} + +/// Auto settings for `src` under the current white balance (ignores current tone values), aiming at +/// what Lightroom's Auto does: the Exposure a scene needs follows its log-average luminance +/// ([`scene_log_mean`], scene-linear, so the rule doesn't depend on the base tone curve), and the +/// other sliders are one fixed recipe. Calibrated black-box against Lightroom's observed behaviour +/// (the values its Auto chose and its exported results) on 24 Sony raw photos, of which 16 have a +/// starting look that Sony's in-camera DRO doesn't brighten. Held out one photo at a time, those 16 +/// come out at a median dE76 of 6.4 from Lightroom's Auto results (8.3 unedited; 18.8 with the +/// previous percentile rule, which ended about 16 L* too bright); all 24 at 7.7 (7.9 unedited). +/// Rendered sources (JPEGs) are already toned, so their log-average reads brighter and Auto changes +/// their exposure less. A source without a single valid pixel gets Exposure 0 (and the rest of the +/// recipe). +pub fn auto_tone(src: &Rgb32f, info: &WbSource, s: &DevelopSettings) -> AutoTone { + let exposure = scene_log_mean(src, info, s).map_or(0.0, |m| (EXPOSURE_AT_GREY + EXPOSURE_SLOPE * m).clamp(-2.0, 3.0)); + AutoTone { + exposure: (exposure * 100.0).round() / 100.0, + contrast: CONTRAST, + highlights: HIGHLIGHTS, + shadows: SHADOWS, + whites: 0.0, + blacks: 0.0, + vibrance: VIBRANCE, + saturation: 0.0, + } +} + +/// An automatic black & white mix (slider values, red … magenta) for `src` under `s`'s white +/// balance and tone: each hue band's colourful pixels are pushed away from the image's mean +/// lightness — bands brighter than average get brighter, darker ones darker — so areas that +/// differ only in colour stay apart in grey. Bands with almost no colourful pixels stay at 0. +pub fn auto_bw_mix(src: &Rgb32f, info: &WbSource, s: &DevelopSettings) -> [f64; 8] { + use craft_color_transform::oklab::{OkLab, lab_to_lch}; + let oklab = OkLab::for_space(&REC2020); + let mut img = crate::raster::resample::fit(src, 512, 512, crate::raster::resample::Filter::Box); + let base = DevelopSettings { wb: s.wb, light: s.light, process: s.process, ..DevelopSettings::default() }; + crate::local::scene_linear_pre(&mut img, info, &base); + let gain = 2f32.powf(base.light.exposure as f32); + let (mut mass, mut sum_l) = ([0f64; 8], [0f64; 8]); + let (mut all_l, mut n) = (0f64, 0usize); + for p in &img.data { + let lch = lab_to_lch(oklab.from_rgb(p.map(|v| (v * gain).max(0.0)))); + all_l += lch[0] as f64; + n += 1; + let k = (lch[1] / 0.2).min(1.0) as f64; // as in the B&W conversion + if k < 0.05 { + continue; + } + let w = crate::colorops::band_weights(lch[2]); + for i in 0..8 { + mass[i] += w[i] as f64 * k; + sum_l[i] += w[i] as f64 * k * lch[0] as f64; + } + } + if n == 0 { + return [0.0; 8]; + } + let mean = all_l / n as f64; + let total: f64 = mass.iter().sum(); + std::array::from_fn(|i| { + if total <= 0.0 || mass[i] / total < 0.01 { + return 0.0; + } + let sep = sum_l[i] / mass[i] - mean; + (sep * 400.0).clamp(-60.0, 60.0).round() + }) +} + +/// Grey-world white balance weighted towards mid-tone, low-chroma pixels. Returns (temp, tint). +pub fn auto_wb(src: &Rgb32f, info: &WbSource) -> (f64, f64) { + auto_wb_with(src, info, None) +} + +/// [`auto_wb`] with an optional camera-space neutral-white estimator (`neutral_white(avg_rgb)`). +pub fn auto_wb_with(src: &Rgb32f, info: &WbSource, neutral_white: Option<&dyn Fn([f64; 3]) -> Option>) -> (f64, f64) { + let img = crate::raster::resample::fit(src, 256, 256, crate::raster::resample::Filter::Box); + let (mut acc, mut wsum) = ([0.0f64; 3], 0.0f64); + for c in &img.data { + let y = luminance_2020(*c); + if !(0.01..=2.0).contains(&y) { + continue; + } + let mx = c[0].max(c[1]).max(c[2]); + let mn = c[0].min(c[1]).min(c[2]); + let chroma = (mx - mn) / (mx + 1e-6); + let w = (1.0 - chroma).powi(2) as f64 * (1.0 - ((y.log2() + 2.5) / 4.0).abs().min(1.0)) as f64; + for i in 0..3 { + acc[i] += c[i] as f64 * w; + } + wsum += w; + } + if wsum <= 0.0 { + return (info.as_shot_temp, info.as_shot_tint); + } + let avg = acc.map(|v| v / wsum); + let seen = match neutral_white.filter(|_| info.raw && !info.relative_wb).and_then(|f| f(avg)) { + Some(white) => white, + None => { + let shot = craft_color_transform::cct::temp_tint_to_xy(info.as_shot_temp, info.as_shot_tint); + let Some(white) = Xy::from_xyz(bradford(REC2020.white, shot).apply(REC2020.to_xyz().apply(avg))) else { + return (info.as_shot_temp, info.as_shot_tint); + }; + white + } + }; + let (t, tint) = xy_to_temp_tint(seen); + (t.clamp(2000.0, 50000.0).round(), tint.clamp(-150.0, 150.0).round()) +} + +/// Temperature/tint currently in effect (for UI display). +pub fn current_wb(info: &WbSource, s: &DevelopSettings) -> (f64, f64) { + effective_wb(info, s) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exposure_follows_the_log_average_luminance() { + let flat = |y: f32| Rgb32f::filled(64, 64, [y; 3]); + let auto = |img: &Rgb32f| auto_tone(img, &WbSource::default(), &DevelopSettings::default()); + let log_mean = |img: &Rgb32f| scene_log_mean(img, &WbSource::default(), &DevelopSettings::default()).unwrap(); + // a scene at middle grey gets the exposure at grey; each EV darker adds 0.41 EV + assert!(log_mean(&flat(0.18)).abs() < 1e-3); + assert_eq!(auto(&flat(0.18)).exposure, -0.58); + assert!((auto(&flat(0.18 / 8.0)).exposure - (-0.58 + 3.0 * 0.41)).abs() < 1e-9); + // darker scenes get more, brighter ones less, within -2..3 EV + let ramp = |lo: f32, step: f32| Rgb32f::from_fn(64, 64, |x, _| [lo + x as f32 * step; 3]); + let (dark, bright) = (auto(&ramp(0.01, 0.0003)), auto(&ramp(0.8, 0.01))); + assert!(dark.exposure > 0.5 && bright.exposure < -1.0, "{dark:?} {bright:?}"); + assert_eq!(auto(&flat(1e-9)).exposure, 3.0); + assert_eq!(auto(&flat(1e6)).exposure, -2.0); + // the rest is one recipe + assert_eq!( + (dark.contrast, dark.highlights, dark.shadows, dark.whites, dark.blacks, dark.vibrance, dark.saturation), + (68.0, -66.0, 52.0, 0.0, 0.0, 30.0, 0.0) + ); + assert_eq!((dark.contrast, dark.shadows), (bright.contrast, bright.shadows)); + } + + #[test] + fn pixels_that_are_not_finite_are_left_out() { + let auto = |img: &Rgb32f| auto_tone(img, &WbSource::default(), &DevelopSettings::default()); + // half middle grey, half NaN (or infinite): the grey half alone decides, as if the rest weren't there + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let half = Rgb32f::from_fn(64, 64, |x, _| if x < 32 { [0.18; 3] } else { [bad; 3] }); + assert_eq!(auto(&half).exposure, -0.58, "{bad}"); + // also through the resampling of a source larger than the proxy (proxy pixels on the border mix both halves) + let big = Rgb32f::from_fn(1030, 700, |x, _| if x < 515 { [0.045; 3] } else { [bad; 3] }); + assert!((auto(&big).exposure - (-0.58 + 2.0 * 0.41)).abs() < 1e-9, "{bad}"); + // a few broken pixels scattered over a grey image change nothing + let speckled = Rgb32f::from_fn(1030, 700, |x, y| if (x * 7 + y * 13) % 97 == 0 { [bad; 3] } else { [0.18; 3] }); + assert_eq!(auto(&speckled).exposure, -0.58, "{bad}"); + } + // with no valid pixel at all (or none at all) there is nothing to measure: Exposure 0, the recipe as usual + for img in [Rgb32f::filled(8, 8, [f32::NAN; 3]), Rgb32f::filled(600, 600, [f32::INFINITY; 3]), Rgb32f::new(0, 0)] { + let a = auto(&img); + assert_eq!((a.exposure, a.contrast, a.vibrance), (0.0, 68.0, 30.0)); + } + } + + #[test] + fn neutral_image_keeps_as_shot_wb() { + let img = Rgb32f::from_fn(32, 32, |x, y| [0.05 + (x + y) as f32 * 0.004; 3]); + let (t, tint) = auto_wb(&img, &WbSource::default()); + assert!((t - 6500.0).abs() < 150.0, "{t}"); + assert!(tint.abs() < 6.0, "{tint}"); + } + + #[test] + fn blue_cast_is_corrected_by_higher_temp() { + // A bluish cast should be neutralised by telling the pipeline the light was bluer (higher K). + let img = Rgb32f::from_fn(32, 32, |_, _| [0.16, 0.18, 0.24]); + let (t, _) = auto_wb(&img, &WbSource::default()); + assert!(t > 7000.0, "{t}"); + let mut s = DevelopSettings::default(); + s.wb.mode = craft_develop_model::WbMode::Custom; + s.wb.temp = t; + let (t2, tint2) = auto_wb(&img, &WbSource::default()); + let _ = (t2, tint2); + let mut out = img.clone(); + let (tt, ti) = auto_wb(&img, &WbSource::default()); + s.wb.temp = tt; + s.wb.tint = ti; + crate::local::scene_linear_pre(&mut out, &WbSource::default(), &s); + let c = out.get(0, 0); + assert!((c[0] - c[2]).abs() < 0.02, "{c:?}"); + } +} + +#[cfg(test)] +mod bw_tests { + use super::*; + + #[test] + fn auto_bw_mix_pushes_light_and_dark_hues_apart() { + // left: a light yellow, right: a dark blue (scene-linear Rec. 2020) + let src = Rgb32f::from_fn(64, 32, |x, _| if x < 32 { [0.55, 0.5, 0.05] } else { [0.01, 0.02, 0.12] }); + let m = auto_bw_mix(&src, &WbSource::default(), &DevelopSettings::default()); + let (yellow, blue) = (m[2], m[5]); + assert!(yellow > 0.0 && blue < 0.0, "{m:?}"); + // an image without colour leaves the mix alone + let grey = Rgb32f::from_fn(16, 16, |x, _| [x as f32 / 16.0; 3]); + assert_eq!(auto_bw_mix(&grey, &WbSource::default(), &DevelopSettings::default()), [0.0; 8]); + } +} + +#[cfg(test)] +mod tint_tests { + use super::*; + + #[test] + fn auto_wb_and_picker_correct_green_with_positive_tint() { + // The picker delegates a sampled patch to this same auto_wb implementation. + for (rgb, sign) in [([0.18, 0.24, 0.18], 1.0), ([0.24, 0.18, 0.24], -1.0)] { + let img = Rgb32f::filled(16, 16, rgb); + let info = WbSource { raw: true, relative_wb: true, ..Default::default() }; + let (temp, tint) = auto_wb(&img, &info); + assert!(tint * sign > 0.0, "{rgb:?}: temp {temp}, tint {tint}"); + let mut s = DevelopSettings::default(); + s.wb.mode = craft_develop_model::WbMode::Custom; + s.wb.temp = temp; + s.wb.tint = tint; + let mut corrected = img; + crate::local::white_balance(&mut corrected, &info, &s); + let p = corrected.get(0, 0); + let spread = p[0].max(p[1]).max(p[2]) - p[0].min(p[1]).min(p[2]); + assert!(spread < 0.003, "{rgb:?} -> {p:?}"); + } + } +} diff --git a/crates/develop/src/camera_raw/local_tone.rs b/crates/develop/src/camera_raw/local_tone.rs new file mode 100644 index 0000000000..33f825b666 --- /dev/null +++ b/crates/develop/src/camera_raw/local_tone.rs @@ -0,0 +1,658 @@ +//! Shadows and Highlights as a local Laplacian filter. +//! +//! Adobe has said Camera Raw's process version 2012 rests on local Laplacian filters (S. Paris, +//! S. W. Hasinoff, J. Kautz, *Local Laplacian Filters: Edge-aware Image Processing with a +//! Laplacian Pyramid*, SIGGRAPH 2011). This follows that paper, in its fast form (M. Aubry et +//! al., *Fast Local Laplacian Filters*, ACM TOG 2014: the remapping sampled at a few reference +//! values, each pyramid coefficient interpolated between them), on the log2 luminance: +//! +//! - **Shadows** raises pixels darker than their surroundings, by an amount set by their own and +//! their surroundings' place in the image's range (1st to 99th percentile); **Highlights** +//! pulls pixels brighter than their surroundings toward them. Differences under a threshold +//! are left alone, so fine detail stays. +//! - Shadows then keeps the image's 99th percentile, Highlights its 1st (Photoshop keeps the +//! brightest content under Shadows and the darkest under Highlights). +//! - A uniform image is unchanged, edges keep no halo, and the result does not depend on the +//! image size. +//! +//! The strengths were fitted to Photoshop 25.4's Camera Raw Filter on ten public-domain photos +//! (black-box measurements, no Adobe code or data). It is an approximation: on those photos the +//! mean error against Photoshop is 2.8–9.4 levels (of 255) where the previous heuristic's was +//! 3.7–14.3. + +use super::util::par_rows; +use super::{Encoding, luma, quantile_rank}; + +/// Spacing of the fast filter's reference values in stops. Its remapping changes within about +/// half a stop, and coefficients interpolated across wider gaps show as contour lines on smooth +/// gradients (12 references over a whole raw's range left visible steps; at an eighth of a stop a +/// ramp's slope varies by under a third, as the remapping itself makes it). +pub const REF_STEP: f32 = 0.125; +/// Most reference values one filter uses. +pub const MAX_REFS: usize = 96; +/// The lowest reference sits at this quantile of the log luminance: the deepest 0.1 % (noise down +/// to the floor) share it instead of stretching the spacing. +pub const REF_LOW_QUANTILE: f32 = 0.001; +/// The filter works on `log2(luminance + LOG_FLOOR)`. +pub const LOG_FLOOR: f32 = 1.0 / 65536.0; +/// The filter runs on a copy at most this many pixels across; the change it makes is brought back +/// to full size by a guided upsampling, so a preview and the full image agree. +pub const WORK_SIDE: usize = 1600; +/// The image range the strengths are placed in: these quantiles of the log luminance averaged +/// over cells of a copy at most [`RANGE_SIDE`] pixels across. +pub const RANGE_QUANTILES: [f32; 2] = [0.01, 0.99]; +/// See [`RANGE_QUANTILES`]. +pub const RANGE_SIDE: usize = 256; +/// Knots of the strength curves over the surroundings' place in the image range (0 … 1). +pub const KNOTS: usize = 5; + +/// Shadows: how far a pixel darker than its surroundings rises, in stops per unit slider, as +/// a function of its own place in the image range (`own`) times a factor of its surroundings' +/// place (`around`); it rises fully once it is `sigma` stops below them. The lift depends on +/// the pixel's tone, not on the size of the difference, so it is the same at every pyramid +/// level and a big edge keeps no halo. Lowering (negative values) is `down` times as strong. +const SHADOWS: Lift = Lift { own: [-0.017, 0.466, 0.886, 1.221, -0.081], around: [4.566, 4.067, 1.088, 0.149, 0.878], sigma: 0.571, down: 0.808 }; +const HIGHLIGHTS: Side = Side { pull: [0.179, 0.141, 0.196, 0.629, 2.07], push: [0.156, 0.08, 0.175, 0.049, 1.261], sigma: 0.05 }; + +/// See [`SHADOWS`]. +struct Lift { + own: [f32; KNOTS], + around: [f32; KNOTS], + sigma: f32, + down: f32, +} + +/// Highlights: strengths per unit slider over the surroundings' place in the image range, for +/// lowering (`pull`, toward the surroundings) and raising (`push`), and the detail threshold in +/// stops. +struct Side { + pull: [f32; KNOTS], + push: [f32; KNOTS], + sigma: f32, +} + +/// Which remapping a [`TonePass`] uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToneKind { + /// Pixels brighter than their surroundings move toward them (or away, for positive values) + /// by the part of the difference past `sigma`. + Highlights, + /// Pixels darker than their surroundings rise (or sink) by an amount set by their own and + /// their surroundings' place in the image range. + Shadows, +} + +/// One pass of the filter resolved for a slider value: everything its remapping reads. +#[derive(Clone, Debug, PartialEq)] +pub struct TonePass { + pub kind: ToneKind, + /// Highlights: the slider / 100. Shadows: its strength (the slider / 100, times `down` when + /// negative). + pub amount: f32, + /// Highlights: the strengths for the slider's direction, then an unused row. Shadows: the + /// curves over the pixel's own (`own`) and its surroundings' (`around`) place. + pub knots: [[f32; KNOTS]; 2], + /// The detail threshold in stops. + pub sigma: f32, + /// The quantile of the log luminance the pass puts back where it was. + pub keep: f32, +} + +/// Shadows and Highlights resolved: Highlights runs first, then Shadows on its result. +#[derive(Clone, Debug, PartialEq)] +pub struct LocalTone { + pub passes: Vec, +} + +impl LocalTone { + /// The passes for the sliders (−100 … 100); `None` when both are 0. + pub fn new(shadows: f32, highlights: f32) -> Option { + let mut passes = Vec::new(); + if highlights != 0.0 { + let amount = highlights.clamp(-100.0, 100.0) / 100.0; + let strengths = if amount < 0.0 { HIGHLIGHTS.pull } else { HIGHLIGHTS.push }; + // Then the darkest content is put back where it was. + passes.push(TonePass { kind: ToneKind::Highlights, amount, knots: [strengths, [0.0; KNOTS]], sigma: HIGHLIGHTS.sigma, keep: 0.01 }); + } + if shadows != 0.0 { + let amount = shadows.clamp(-100.0, 100.0) / 100.0; + let k = if amount > 0.0 { amount } else { amount * SHADOWS.down }; + // Keep the brightest content. + passes.push(TonePass { kind: ToneKind::Shadows, amount: k, knots: [SHADOWS.own, SHADOWS.around], sigma: SHADOWS.sigma, keep: 0.99 }); + } + (!passes.is_empty()).then_some(LocalTone { passes }) + } +} + +impl TonePass { + /// The remapping of log luminance `x` around the reference `g`, in an image range that + /// starts at `lo` and is `span` stops wide. + pub fn remap(&self, x: f32, g: f32, lo: f32, span: f32) -> f32 { + match self.kind { + ToneKind::Highlights => x + knot((g - lo) / span, &self.knots[0]) * self.amount * excess((x - g).max(0.0), self.sigma), + ToneKind::Shadows => { + let below = ((g - x) / self.sigma).clamp(0.0, 1.0); + if below == 0.0 { + return x; + } + let w = below * below * (3.0 - 2.0 * below); + x + self.amount * knot((x - lo) / span, &self.knots[0]) * knot((g - lo) / span, &self.knots[1]) * w + } + } + } + + /// The pass on the log luminance `u`: the filter, then the kept quantile put back. + fn run(&self, u: &Plane) -> Plane { + let (lo, hi) = range(u); + let span = (hi - lo).max(1.0); + let o = llf(u, |x, g| self.remap(x, g, lo, span)); + let shift = quantile(&u.v, self.keep) - quantile(&o.v, self.keep); + Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() } + } +} + +/// One channel, `w × h`. +struct Plane { + w: usize, + h: usize, + v: Vec, +} + +/// Mirrors `i` into `0..n` (the edge sample is not repeated). +fn mirror(i: isize, n: usize) -> usize { + let n = n as isize; + if n == 1 { + return 0; + } + let p = 2 * (n - 1); + let m = i.rem_euclid(p); + (if m >= n { p - m } else { m }) as usize +} + +/// The pyramid's binomial kernel. +pub const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0]; + +/// Planes smaller than this run their rows on one thread: the filter builds a whole pyramid per +/// reference (up to 96), and splitting its small levels into one-row tasks cost more in rayon's +/// scheduling than the rows themselves (a fifth of a Shadows render on 36 MP, measured). +const PAR_MIN: usize = 1 << 15; + +/// [`par_rows`] for a plane, on one thread when it is small (see [`PAR_MIN`]). +fn rows(buf: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync + Send) { + if buf.len() < PAR_MIN { + buf.chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| f(y, row)); + } else { + par_rows(buf, w, 1, f); + } +} + +/// The binomial 5-tap blur, sampled every `step` pixels from 0 (1 = full resolution). +fn blur_step(p: &Plane, step: usize) -> Plane { + let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step)); + // Columns first at the kept rows, then rows at the kept columns. Each sum adds the same terms + // in the same order as a `mirror` per tap would, so the result is bit for bit the same; the + // source rows are found once per row and the columns mirrored only near the edges. + let mut tmp = vec![0.0f32; p.w * h2]; + rows(&mut tmp, p.w, |y2, row| { + let y = (y2 * step) as isize; + let src: [&[f32]; 5] = std::array::from_fn(|k| { + let r = mirror(y + k as isize - 2, p.h); + &p.v[r * p.w..(r + 1) * p.w] + }); + for (x, o) in row.iter_mut().enumerate() { + *o = (0..5).map(|k| TAPS[k] * src[k][x]).sum(); + } + }); + let mut out = vec![0.0f32; w2 * h2]; + rows(&mut out, w2, |y2, row| { + let src = &tmp[y2 * p.w..(y2 + 1) * p.w]; + for (x2, o) in row.iter_mut().enumerate() { + let x = x2 * step; + *o = if x >= 2 && x + 2 < p.w { + let s = &src[x - 2..x + 3]; + (0..5).map(|k| TAPS[k] * s[k]).sum() + } else { + (0..5).map(|k| TAPS[k] * src[mirror(x as isize + k as isize - 2, p.w)]).sum() + }; + } + }); + Plane { w: w2, h: h2, v: out } +} + +/// The next coarser level. +fn down(p: &Plane) -> Plane { + blur_step(p, 2) +} + +/// `p` brought up to `w × h`: zeros between samples, then the blur times four. +/// +/// Three samples in four are zero, so their taps are skipped instead of blurring a zero-filled +/// plane: the nonzero terms are added in the same order (skipping `+0.0` terms changes at most the +/// sign of a zero, and the filter only adds and exponentiates these values). +fn up(p: &Plane, w: usize, h: usize) -> Plane { + let (lh, lw) = (p.h.min(h.div_ceil(2)), p.w.min(w.div_ceil(2))); + // The source sample behind index `i` of a zero-stuffed axis of length `n` holding `lim` samples. + let src = |i: isize, n: usize, lim: usize| { + let m = mirror(i, n); + (m.is_multiple_of(2) && m / 2 < lim).then_some(m / 2) + }; + // Columns first, only at the even columns (the odd ones are all zero). + let mut tmp = vec![0.0f32; lw * h]; + if lw > 0 { + rows(&mut tmp, lw, |y, row| { + let taps: [Option<&[f32]>; 5] = std::array::from_fn(|k| src(y as isize + k as isize - 2, h, lh).map(|r| &p.v[r * p.w..r * p.w + lw])); + for (j, o) in row.iter_mut().enumerate() { + *o = (0..5).filter_map(|k| taps[k].map(|s| TAPS[k] * (s[j] * 4.0))).sum(); + } + }); + } + let mut out = vec![0.0f32; w * h]; + rows(&mut out, w, |y, row| { + let t = &tmp[y * lw..(y + 1) * lw]; + for (x, o) in row.iter_mut().enumerate() { + *o = if x >= 2 && x + 2 < w { + // Away from the edges no tap mirrors. + (0..5) + .filter_map(|k| { + let i = x + k - 2; + (i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * t[i / 2]) + }) + .sum() + } else { + (0..5).filter_map(|k| src(x as isize + k as isize - 2, w, lw).map(|j| TAPS[k] * t[j])).sum() + }; + } + }); + Plane { w, h, v: out } +} + +/// The source rows of [`up`]`(p, w, h)` at output row `y`, one per tap (`None` where the +/// zero-stuffed row is all zeros). +fn up_rows(p: &Plane, h: usize, y: usize) -> [Option; 5] { + let lh = p.h.min(h.div_ceil(2)); + std::array::from_fn(|k| { + let m = mirror(y as isize + k as isize - 2, h); + (m.is_multiple_of(2) && m / 2 < lh).then_some(m / 2) + }) +} + +/// One sample of [`up`]`(p, w, h)`: column `x` of the output row whose [`up_rows`] are `rows`. +/// It adds the same terms in the same order as `up`, so it gives the same bits. +fn up_at(p: &Plane, w: usize, rows: &[Option; 5], x: usize) -> f32 { + let lw = p.w.min(w.div_ceil(2)); + let col = |j: usize| -> f32 { (0..5).filter_map(|k| rows[k].map(|r| TAPS[k] * (p.v[r * p.w + j] * 4.0))).sum() }; + if x >= 2 && x + 2 < w { + // Away from the edges no tap mirrors. + (0..5) + .filter_map(|k| { + let i = x + k - 2; + (i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * col(i / 2)) + }) + .sum() + } else { + (0..5) + .filter_map(|k| { + let m = mirror(x as isize + k as isize - 2, w); + (m.is_multiple_of(2) && m / 2 < lw).then(|| TAPS[k] * col(m / 2)) + }) + .sum() + } +} + +/// Levels down to about 2 pixels on the short side. +fn depth(w: usize, h: usize) -> usize { + let mut s = w.min(h); + let mut n = 1; + while s > 2 { + s = s.div_ceil(2); + n += 1; + } + n +} + +fn gaussian(p: Plane, n: usize) -> Vec { + let mut g = vec![p]; + for _ in 1..n { + let next = down(&g[g.len() - 1]); + g.push(next); + } + g +} + +/// The local Laplacian filter of `u` with `remap(value, reference)`; the coarsest level is kept. +fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane { + let n = depth(u.w, u.h); + let g = gaussian(Plane { w: u.w, h: u.h, v: u.v.clone() }, n); + // References span the image's tones (see `REF_LOW_QUANTILE`). + let hi = u.v.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v)); + let lo = quantile(&u.v, REF_LOW_QUANTILE).min(hi); + if hi - lo <= 1e-6 || (hi - lo).is_nan() { + return Plane { w: u.w, h: u.h, v: u.v.clone() }; + } + let refs = (((hi - lo) / REF_STEP).ceil() as usize + 1).clamp(2, MAX_REFS); + let step = (hi - lo) / (refs - 1) as f32; + let mut lap: Vec> = g[..n - 1].iter().map(|p| vec![0.0; p.v.len()]).collect(); + for k in 0..refs { + let r = lo + step * k as f32; + let mut m = Plane { w: u.w, h: u.h, v: u.v.clone() }; + rows(&mut m.v, u.w, |_, row| { + for v in row.iter_mut() { + *v = remap(*v, r); + } + }); + let gr = gaussian(m, n); + for l in 0..n - 1 { + let (gl, fine, lw, lh, coarse) = (&g[l].v, &gr[l].v, g[l].w, g[l].h, &gr[l + 1]); + rows(&mut lap[l], lw, |y, row| { + let taps = up_rows(coarse, lh, y); + for (x, o) in row.iter_mut().enumerate() { + let i = y * lw + x; + let wgt = (1.0 - (gl[i].clamp(lo, hi) - r).abs() / step).max(0.0); + if wgt > 0.0 { + *o += wgt * (fine[i] - up_at(coarse, lw, &taps, x)); + } + } + }); + } + } + let mut o = Plane { w: g[n - 1].w, h: g[n - 1].h, v: g[n - 1].v.clone() }; + for l in (0..n - 1).rev() { + let mut next = up(&o, g[l].w, g[l].h); + for (a, b) in next.v.iter_mut().zip(&lap[l]) { + *a += b; + } + o = next; + } + o +} + +/// The `q` quantile (0 … 1) of `v`. +fn quantile(v: &[f32], q: f32) -> f32 { + let mut s = v.to_vec(); + // Selecting the one element is linear, a full sort is not (5 sorts of the work copy were a + // fifteenth of a render). `total_cmp` ties are bit-identical, so it is the sorted element. + let i = quantile_rank(s.len(), q); + *s.select_nth_unstable_by(i, f32::total_cmp).1 +} + +/// The image range: [`RANGE_QUANTILES`] of the log luminance on a copy at most [`RANGE_SIDE`] +/// pixels across. +fn range(u: &Plane) -> (f32, f32) { + let f = u.w.max(u.h).div_ceil(RANGE_SIDE).max(1); + let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f)); + let mut sum = vec![(0.0f64, 0u32); sw * sh]; + for y in 0..u.h { + for x in 0..u.w { + let c = &mut sum[(y / f) * sw + x / f]; + c.0 += f64::from(u.v[y * u.w + x]); + c.1 += 1; + } + } + let cells: Vec = sum.iter().filter(|c| c.1 > 0).map(|c| (c.0 / f64::from(c.1)) as f32).collect(); + (quantile(&cells, RANGE_QUANTILES[0]), quantile(&cells, RANGE_QUANTILES[1])) +} + +/// `d` past the detail threshold: about 0 below `sigma`, `d − sigma` well above it. +fn excess(d: f32, sigma: f32) -> f32 { + d - sigma * (d / sigma).tanh() +} + +fn knot(t: f32, k: &[f32; KNOTS]) -> f32 { + let x = t.clamp(0.0, 1.0) * (KNOTS - 1) as f32; + let i = (x as usize).min(KNOTS - 2); + k[i] + (k[i + 1] - k[i]) * (x - i as f32) +} + +/// Applies Shadows and Highlights (−100 … 100) to straight RGBA pixels encoded with `enc` +/// (`Encoding::of(DevelopInputs::encoding_gamma)`). The filter is deterministic, so it reads no grain seed. +pub(crate) fn apply(px: &mut [[f32; 4]], w: usize, h: usize, shadows: f32, highlights: f32, enc: Encoding) { + let Some(tone) = LocalTone::new(shadows, highlights) else { return }; + if w < 2 || h < 2 { + return; + } + let u = Plane { w, h, v: px.iter().map(|q| (luma([0, 1, 2].map(|c| enc.decode(q[c]))).max(0.0) + LOG_FLOOR).log2()).collect() }; + // The filter on a copy at most WORK_SIDE across (box-averaged in log). + let f = w.max(h).div_ceil(WORK_SIDE).max(1); + let small = if f == 1 { Plane { w, h, v: u.v.clone() } } else { shrink(&u, f) }; + let mut o = Plane { w: small.w, h: small.h, v: small.v.clone() }; + for pass in &tone.passes { + o = pass.run(&o); + } + // The change in log luminance, at full size. + let change: Vec = if f == 1 { + o.v.iter().zip(&u.v).map(|(a, b)| a - b).collect() + } else { + let d: Vec = o.v.iter().zip(&small.v).map(|(a, b)| a - b).collect(); + guided_upsample(&small, &d, &u) + }; + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + let gain = change[y * w + x].exp2(); + for c in 0..3 { + q[c] = enc.encode(enc.decode(q[c]) * gain); + } + } + }); +} + +/// `u` averaged over `f × f` blocks. +fn shrink(u: &Plane, f: usize) -> Plane { + let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f)); + let mut v = vec![0.0f32; sw * sh]; + par_rows(&mut v, sw, 1, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let (x0, y0) = (x * f, y * f); + let (x1, y1) = ((x0 + f).min(u.w), (y0 + f).min(u.h)); + let mut s = 0.0f64; + for yy in y0..y1 { + for xx in x0..x1 { + s += f64::from(u.v[yy * u.w + xx]); + } + } + *o = (s / ((x1 - x0) * (y1 - y0)) as f64) as f32; + } + }); + Plane { w: sw, h: sh, v } +} + +/// The change `d` computed on `small` brought to the size of `full`, following its edges: a local +/// linear model of the change against the log luminance (the guided filter of K. He, J. Sun, +/// *Fast Guided Filter*, 2015), fitted on the small copy and evaluated on the full one. +fn guided_upsample(small: &Plane, d: &[f32], full: &Plane) -> Vec { + let (sw, sh) = (small.w, small.h); + let r = 2; + let eps = 0.01; + let mean = |v: &[f32]| super::box_mean(v, sw, sh, r); + let ud: Vec = small.v.iter().zip(d).map(|(a, b)| a * b).collect(); + let uu: Vec = small.v.iter().map(|a| a * a).collect(); + let (mu, md, mud, muu) = (mean(&small.v), mean(d), mean(&ud), mean(&uu)); + let a: Vec = (0..sw * sh).map(|i| (mud[i] - mu[i] * md[i]) / (muu[i] - mu[i] * mu[i] + eps)).collect(); + let b: Vec = (0..sw * sh).map(|i| md[i] - a[i] * mu[i]).collect(); + let (ma, mb) = (mean(&a), mean(&b)); + let (fx, fy) = (sw as f32 / full.w as f32, sh as f32 / full.h as f32); + let mut out = vec![0.0f32; full.w * full.h]; + par_rows(&mut out, full.w, 1, |y, row| { + let sy = (y as f32 + 0.5) * fy - 0.5; + for (x, o) in row.iter_mut().enumerate() { + let sx = (x as f32 + 0.5) * fx - 0.5; + let av = super::util::bilinear(&ma, sw, sh, 1, 0, sx, sy); + let bv = super::util::bilinear(&mb, sw, sh, 1, 0, sx, sy); + *o = av * full.v[y * full.w + x] + bv; + } + }); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const SRGB: Encoding = Encoding(0.0); + + /// The plain blur: a `mirror` per tap over the whole plane, the reference for [`blur_step`]. + fn blur_step_reference(p: &Plane, step: usize) -> Plane { + let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step)); + let mut tmp = vec![0.0f32; p.w * h2]; + for y2 in 0..h2 { + for x in 0..p.w { + tmp[y2 * p.w + x] = (0..5).map(|k| TAPS[k] * p.v[mirror((y2 * step) as isize + k as isize - 2, p.h) * p.w + x]).sum(); + } + } + let mut out = vec![0.0f32; w2 * h2]; + for y2 in 0..h2 { + for x2 in 0..w2 { + out[y2 * w2 + x2] = (0..5).map(|k| TAPS[k] * tmp[y2 * p.w + mirror((x2 * step) as isize + k as isize - 2, p.w)]).sum(); + } + } + Plane { w: w2, h: h2, v: out } + } + + /// The plain upsampling: a zero-stuffed plane blurred whole, the reference for [`up`]. + fn up_reference(p: &Plane, w: usize, h: usize) -> Plane { + let mut z = Plane { w, h, v: vec![0.0; w * h] }; + for y in 0..p.h.min(h.div_ceil(2)) { + for x in 0..p.w.min(w.div_ceil(2)) { + z.v[2 * y * w + 2 * x] = p.v[y * p.w + x] * 4.0; + } + } + blur_step_reference(&z, 1) + } + + fn noise_plane(w: usize, h: usize, seed: u32) -> Plane { + let mut s = seed.wrapping_mul(2_654_435_761).max(1); + let v = (0..w * h) + .map(|_| { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + (s % 20_000) as f32 / 1000.0 - 16.0 + }) + .collect(); + Plane { w, h, v } + } + + #[test] + fn the_fast_pyramid_matches_the_plain_one_exactly() { + // Odd, even, tiny and large-enough-to-run-in-parallel sizes, as the pyramid's levels are. + for (i, (w, h)) in [(1, 1), (1, 7), (2, 2), (3, 5), (5, 3), (8, 6), (37, 23), (64, 64), (301, 211)].into_iter().enumerate() { + let p = noise_plane(w, h, i as u32 + 1); + for step in [1, 2] { + assert_eq!(blur_step(&p, step).v, blur_step_reference(&p, step).v, "blur {w}×{h} step {step}"); + } + for (uw, uh) in [(w * 2, h * 2), (w * 2 - 1, h * 2 - 1), (w * 2, h * 2 - 1), (w.max(2) * 2 - 3, h * 2)] { + let full = up(&p, uw, uh); + assert_eq!(full.v, up_reference(&p, uw, uh).v, "up {w}×{h} → {uw}×{uh}"); + // The filter samples `up` one pixel at a time; every sample has the same bits. + for y in 0..uh { + let taps = up_rows(&p, uh, y); + for x in 0..uw { + assert_eq!(up_at(&p, uw, &taps, x).to_bits(), full.v[y * uw + x].to_bits(), "up_at {w}×{h} → {uw}×{uh} at {x},{y}"); + } + } + } + } + } + + #[test] + fn quantile_is_the_sorted_element() { + let p = noise_plane(301, 211, 9); + let mut v = p.v.clone(); + // Ties and signed zeros, which `total_cmp` orders by their bits. + v.extend([0.0, -0.0, 0.0, -0.0, 3.5, 3.5, f32::MIN_POSITIVE]); + let mut sorted = v.clone(); + sorted.sort_by(f32::total_cmp); + for q in [0.0, 0.001, 0.01, 0.25, 0.5, 0.99, 1.0] { + let want = sorted[((sorted.len() - 1) as f32 * q).round() as usize]; + assert_eq!(quantile(&v, q).to_bits(), want.to_bits(), "q {q}"); + } + } + + fn grey(w: usize, h: usize, f: impl Fn(usize, usize) -> f32) -> Vec<[f32; 4]> { + (0..w * h).map(|i| f(i % w, i / w)).map(|v| [v, v, v, 1.0]).collect() + } + + #[test] + fn a_flat_image_is_unchanged() { + let mut px = grey(64, 48, |_, _| 0.4); + apply(&mut px, 64, 48, 100.0, -100.0, SRGB); + assert!(px.iter().all(|q| (q[0] - 0.4).abs() < 1e-5)); + } + + #[test] + fn shadows_raise_a_dark_area_without_a_halo() { + // A 0.1 | 0.6 step (the dark half is the image's black point, which Photoshop barely + // moves either): the bright half stays, and no halo forms on either side of the edge. + let (w, h) = (256, 128); + let mut px = grey(w, h, |x, _| if x < w / 2 { 0.1 } else { 0.6 }); + apply(&mut px, w, h, 100.0, 0.0, SRGB); + let row = &px[64 * w..65 * w]; + assert!((row[w / 2 + 1][0] - 0.6).abs() < 0.002 && (row[w - 5][0] - 0.6).abs() < 0.002); + let (far, near) = (row[10][0], row[w / 2 - 1][0]); + assert!((far - 0.1).abs() < 0.004 && (far - near).abs() < 0.004, "{far} {near}"); + } + + #[test] + fn grey_moves_as_in_photoshop() { + // Mid-grey with 1 % black (0.015) and white (0.97) corners, Photoshop 25.4: Shadows +100 + // takes the grey from 127.5 to 165.3, Highlights −100 to 89.6 (of 255). + let n = 256; + let image = |c: f32| { + grey(n, n, |x, y| { + if x >= n - 26 && y >= n - 26 { + 0.97 + } else if x >= n - 26 && y < 26 { + 0.015 + } else { + c + } + }) + }; + for (s, hl, want) in [(100.0, 0.0, 165.3), (0.0, -100.0, 89.6)] { + let mut px = image(0.5); + apply(&mut px, n, n, s, hl, SRGB); + let got = px[175 * n + 100][0] * 255.0; + assert!((got - want).abs() < 5.0, "{s} {hl}: {got} vs {want}"); + } + } + + #[test] + fn highlights_lower_a_bright_area_and_keep_the_darkest() { + let (w, h) = (192, 192); + let mut px = grey(w, h, |x, y| if (64..128).contains(&x) && (64..128).contains(&y) { 0.8 } else { 0.2 }); + apply(&mut px, w, h, 0.0, -100.0, SRGB); + assert!(px[96 * w + 96][0] < 0.75, "{}", px[96 * w + 96][0]); + assert!((px[5 * w + 5][0] - 0.2).abs() < 0.01, "{}", px[5 * w + 5][0]); + } + + #[test] + fn smooth_gradients_stay_smooth() { + // A soft ramp over eight stops, as in an out-of-focus background. Coefficients interpolated + // between references too far apart drew contour lines across such ramps (Shadows +100 on + // a D4 raw): the output must rise steadily, without ripples. + let (w, h) = (640, 48); + let mut px = grey(w, h, |x, _| crate::camera_raw::util::linear_to_srgb((x as f32 / (w - 1) as f32 * 8.0 - 9.0).exp2())); + for (s, hl) in [(100.0, 0.0), (0.0, -100.0), (-100.0, 100.0)] { + let mut p = px.clone(); + apply(&mut p, w, h, s, hl, SRGB); + let row: Vec = (0..w).map(|x| crate::camera_raw::util::srgb_to_linear(p[24 * w + x][0]).max(1e-6).log2()).collect(); + let steps: Vec = row.windows(2).map(|d| d[1] - d[0]).collect(); + assert!(steps.iter().all(|d| *d > 0.0), "{s} {hl}: the ramp reverses"); + let jumps: Vec = steps.windows(2).map(|d| (d[1] - d[0]).abs()).collect(); + let ripple = jumps[16..jumps.len() - 16].iter().fold(0.0f32, |a, b| a.max(*b)); + // The ramp rises 0.0125 stops per pixel; its slope may change by a third at most. + assert!(ripple < 0.004, "{s} {hl}: slope jumps by {ripple} stops per pixel"); + } + px.clear(); + } + + #[test] + fn the_result_does_not_depend_on_the_image_size() { + let at = |n: usize| { + let mut px = grey(n, n, |x, y| if x < n / 3 || y < n / 4 { 0.08 } else { 0.7 }); + apply(&mut px, n, n, 70.0, -60.0, SRGB); + [px[(n / 8) * n + n / 8][0], px[(3 * n / 4) * n + 3 * n / 4][0]] + }; + let (a, b) = (at(96), at(384)); + assert!((a[0] - b[0]).abs() < 0.02 && (a[1] - b[1]).abs() < 0.02, "{a:?} {b:?}"); + } +} diff --git a/crates/develop/src/camera_raw/mod.rs b/crates/develop/src/camera_raw/mod.rs new file mode 100644 index 0000000000..0119fa1a08 --- /dev/null +++ b/crates/develop/src/camera_raw/mod.rs @@ -0,0 +1,1317 @@ +//! Filter › Camera Raw Filter: a float develop pipeline over RGB pixels. +//! +//! Stages, in order (each skipped when its controls are neutral, so defaults are an identity): +//! +//! 1. **White balance and exposure** in linear light (the document's values decoded with the sRGB +//! curve as a perceptual working encoding; encoding is undone exactly at the end). +//! 2. **Dehaze**: K. He, J. Sun, X. Tang, *Single Image Haze Removal Using Dark Channel Prior*, +//! CVPR 2009 (dark channel, atmospheric light from its brightest 0.1 %, transmission refined +//! with the guided filter); negative amounts add haze toward the atmospheric light. +//! 3. **Tone** on luminance with colour ratios kept: Highlights / Shadows as exposure changes +//! weighted by an edge-preserving base layer (guided filter: K. He, J. Sun, X. Tang, *Guided +//! Image Filtering*, ECCV 2010), so local contrast survives; Contrast is an S-curve about +//! middle grey; Clarity (large radius, midtone weighted) and Texture (small radius) add +//! band-pass local contrast. Whites / Blacks follow as Photoshop's Camera Raw applies them: +//! image-adaptive global curves measured on Photoshop 25.4 (see `whites_blacks`). +//! 4. **Presence**: Vibrance (weighted toward less saturated colours) and Saturation. +//! 5. **Tone Curve**: parametric regions (Highlights, Lights, Darks, Shadows with movable splits) +//! then point curves (master and per channel), monotone cubic interpolation (F. Fritsch, +//! R. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 1980). +//! 6. **Color Mixer (HSL)**: eight hue bands (red, orange, yellow, green, aqua, blue, purple, +//! magenta) with hat-function weights on the hue circle. +//! 7. **Color Grading**: shadows / midtones / highlights / global wheels (hue, saturation, +//! luminance) with Blending and Balance. +//! 8. **Detail**: sharpening on luminance (unsharp mask with Detail as halo control and Masking as +//! an edge mask) and noise reduction (luminance by guided filter, colour by chroma blur). +//! 9. **Effects**: post-crop vignette (amount, midpoint, roundness, feather, highlights, +//! style) and grain (amount, size, roughness; position-hashed, deterministic). + +#![allow(clippy::needless_range_loop)] // index loops mirror the maths (pixels × channels) +#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] + +// The settings are the framework's: one model, with its validation and identity rules. +mod types; +mod util; + +pub use types::{GradeWheel as Wheel, MAX_CURVE_POINTS, RawDevelopSettings as CameraRaw, VignetteStyle as StoredVignetteStyle, validate_curve}; + +// PLAN: `develop`, `per_pixel` and `white_black_points` now take `&DevelopInputs`; their callers outside this set's files need it: +// crates/gpu/tests/it/camera_raw.rs and examples/bench_camera_raw.rs (spatial(p) is a free function now), dialogs-w51's +// camera_raw_gpu.rs `CameraRawGpu::develop` (takes the inputs beside `p`), crates/io/src/camera_raw_xmp.rs (`vignette_style` is the +// framework's `VignetteStyle` enum, not a string). Owner: tools-w28 / dialogs-w51 / the io set. +/// What one develop reads besides the settings. PhotoCraft sets these per job (the proxy's scale, the document's +/// transfer curve), so they are not part of the settings the workspace edits and the commands store. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DevelopInputs { + /// Seeds the grain's noise. + pub seed: u32, + /// Pixel-size multiplier for previews on downsampled proxies (radii in px scale by it). + pub pixel_scale: f32, + /// The document's transfer curve: 0 for sRGB's, else the gamma of a power-law space (1.8 for ProPhoto). Whites and + /// Blacks act on light. + pub encoding_gamma: f32, +} + +impl Default for DevelopInputs { + fn default() -> Self { + DevelopInputs { seed: 0, pixel_scale: 1.0, encoding_gamma: 0.0 } + } +} + +use util::{hash01, linear_to_srgb, par_rows, srgb_to_linear}; + +pub mod local_tone; +mod per_pixel; +pub mod spatial; +mod whites_blacks; + +pub use local_tone::{LocalTone, ToneKind, TonePass}; +pub use per_pixel::{ + CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, spatial, white_black_points, + whites_blacks_model, +}; +pub use spatial::{Clarity, Dehaze, Texture}; + +/// How the pixels encode light: the sRGB curve (gamma 0) or a pure power law (ProPhoto's 1.8, +/// Adobe RGB's 2.2). The tone controls work on light, so the document's own curve decodes it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Encoding(f32); + +impl Encoding { + pub(crate) fn of(gamma: f32) -> Self { + Encoding(if gamma.is_finite() && gamma > 0.0 { gamma.clamp(0.5, 4.0) } else { 0.0 }) + } + /// A value in this encoding as linear light. + pub(crate) fn decode(self, v: f32) -> f32 { + if self.0 > 0.0 { v.max(0.0).powf(self.0) } else { srgb_to_linear(v) } + } + /// Linear light back into this encoding, the inverse of [`Encoding::decode`]. + pub(crate) fn encode(self, v: f32) -> f32 { + if self.0 > 0.0 { v.max(0.0).powf(1.0 / self.0) } else { linear_to_srgb(v) } + } +} + +fn luma_linear(c: [f32; 3]) -> f32 { + luma(c) +} + +/// Hue band centres of the Color Mixer (degrees). +pub const HSL_BANDS: [f32; 8] = [0.0, 30.0, 60.0, 120.0, 180.0, 240.0, 270.0, 300.0]; + +/// How far a primary turns at Hue ±100 (degrees), as the Color Mixer's hue sliders do. +const CALIBRATION_TURN: f32 = 30.0; + +/// How much of each primary (red, green, blue) a hue is made of: triangular weights around +/// 0°, 120° and 240° that sum to one, so a colour between two primaries follows both. +pub fn calibration_weights(hue: f32) -> [f32; 3] { + let h = hue.rem_euclid(360.0); + let mut w = [0.0f32; 3]; + for (i, centre) in [0.0f32, 120.0, 240.0].iter().enumerate() { + let d = (h - centre).abs().min(360.0 - (h - centre).abs()); + w[i] = (1.0 - d / 120.0).max(0.0); + } + let sum: f32 = w.iter().sum(); + if sum > 1e-6 { w.map(|v| v / sum) } else { [1.0, 0.0, 0.0] } +} + +/// The Calibration panel's primaries on one linear-light pixel: its hue turns by the weighted +/// Hue of the primaries it is made of (±100 is ±30°, positive towards the next primary) and its +/// saturation scales by their weighted Saturation (−100 greys it); the luminance is kept, so +/// neutrals are untouched. +fn calibrate(c: [f32; 3], hue: [f32; 3], sat: [f32; 3]) -> [f32; 3] { + let [h, s, v] = rgb_to_hsv(c.map(|x| x.max(0.0))); + if s <= 1e-5 || v <= 1e-6 { + return c; + } + let w = calibration_weights(h); + let (mut dh, mut ds) = (0.0f32, 0.0f32); + for i in 0..3 { + dh += w[i] * hue[i].clamp(-100.0, 100.0); + ds += w[i] * sat[i].clamp(-100.0, 100.0); + } + let nh = h + dh / 100.0 * CALIBRATION_TURN; + let ns = (s * (1.0 + ds / 100.0)).clamp(0.0, 1.0); + let out = hsv_to_rgb(nh, ns, v); + let (l0, l1) = (luma(c), luma(out)); + if l1 > 1e-6 { out.map(|x| x * l0 / l1) } else { out } +} + +/// Shadows › Tint on one linear-light pixel: `tint` −1 (green) … 1 (magenta), weighted by how +/// dark the pixel is; the luminance is kept. +fn shadow_tint(c: [f32; 3], tint: f32) -> [f32; 3] { + let l = luma(c).max(0.0); + // Linear 0.18 is middle grey: full strength below it, fading out towards white. + let weight = (1.0 - (l / 0.18).sqrt().min(1.0)).powi(2) * 0.5 + (1.0 - l.min(1.0)).powi(4) * 0.5; + let k = tint * 0.12 * weight * (l + 0.02); + let o = [c[0] + k, c[1] - k, c[2] + k].map(|v| v.max(0.0)); + let l2 = luma(o); + if l2 > 1e-6 { o.map(|v| v * l / l2) } else { o } +} + +/// Camera Raw's Auto for the Light panel: Exposure, Contrast, Highlights, Shadows, Whites and +/// Blacks from the image's luminance histogram (`px` in the document's encoding). A well +/// exposed image gets near-zero settings; a dark one more exposure and lifted shadows; one +/// with a crushed or blown end gets Blacks or Whites back from the edge. The other panels are +/// left alone, as Camera Raw's Auto leaves them. +pub fn auto_tone(px: &[[f32; 4]], p: &mut CameraRaw) { + if px.is_empty() { + return; + } + let mut lum: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]]).clamp(0.0, 1.0)).collect(); + lum.sort_by(|a, b| a.total_cmp(b)); + let at = |f: f32| lum[((lum.len() - 1) as f32 * f).round() as usize]; + let (black, shadow, median, light, white) = (at(0.001), at(0.1), at(0.5), at(0.9), at(0.999)); + // Exposure: the median towards middle grey (sRGB 0.46), damped so flat scenes aren't + // forced to it. + let median_lin = srgb_to_linear(median).max(1e-4); + p.exposure = (0.6 * (0.18f32 / median_lin).log2()).clamp(-2.0, 2.0); + // Blacks and Whites bring the ends to the edges without clipping more than Camera Raw does. + p.blacks = ((0.04 - black) * 400.0).clamp(-40.0, 40.0); + p.whites = ((0.96 - white) * 300.0).clamp(-40.0, 40.0); + // Shadows up when the darker tenth is crushed, highlights down when the brighter tenth is + // near white. + p.shadows = ((0.25 - shadow) * 200.0).clamp(0.0, 50.0); + p.highlights = ((light - 0.85) * -300.0).clamp(-50.0, 0.0); + // A little contrast for a flat histogram. + let spread = (light - shadow).max(0.0); + p.contrast = ((0.6 - spread) * 60.0).clamp(0.0, 25.0); + // Shown as Camera Raw shows them: Exposure to a hundredth of a stop, the others whole. + p.exposure = (p.exposure * 100.0).round() / 100.0; + for v in [&mut p.blacks, &mut p.whites, &mut p.shadows, &mut p.highlights, &mut p.contrast] { + *v = v.round(); + } +} + +fn luma(c: [f32; 3]) -> f32 { + 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2] +} + +fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// Box mean of a single-channel buffer (radius `r`, edge clamped): rows in parallel, then +/// columns in parallel bands with running column sums (cache-friendly, no transposes). +fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec { + if r == 0 || w == 0 || h == 0 { + return v.to_vec(); + } + let n = (2 * r + 1) as f64; + let mut tmp = vec![0.0f32; w * h]; + par_rows(&mut tmp, w, 1, |y, row| { + let src = &v[y * w..(y + 1) * w]; + let at = |k: i64| src[k.clamp(0, w as i64 - 1) as usize] as f64; + let mut acc: f64 = (-(r as i64)..=r as i64).map(at).sum(); + for (x, o) in row.iter_mut().enumerate() { + *o = (acc / n) as f32; + acc += at(x as i64 + r as i64 + 1) - at(x as i64 - r as i64); + } + }); + const BAND: usize = 256; + let bands = util::par_map(w.div_ceil(BAND), |b| { + let (x0, x1) = (b * BAND, ((b + 1) * BAND).min(w)); + let bw = x1 - x0; + let row = |y: i64| &tmp[y.clamp(0, h as i64 - 1) as usize * w + x0..y.clamp(0, h as i64 - 1) as usize * w + x1]; + let mut acc = vec![0.0f64; bw]; + for y in -(r as i64)..=r as i64 { + for (a, v) in acc.iter_mut().zip(row(y)) { + *a += *v as f64; + } + } + let mut out = vec![0.0f32; bw * h]; + for y in 0..h { + for (o, a) in out[y * bw..(y + 1) * bw].iter_mut().zip(&acc) { + *o = (*a / n) as f32; + } + let (add, sub) = (row(y as i64 + r as i64 + 1), row(y as i64 - r as i64)); + for ((a, p), m) in acc.iter_mut().zip(add).zip(sub) { + *a += (*p - *m) as f64; + } + } + out + }); + let mut out = vec![0.0f32; w * h]; + for (b, band) in bands.iter().enumerate() { + let (x0, x1) = (b * BAND, ((b + 1) * BAND).min(w)); + let bw = x1 - x0; + for y in 0..h { + out[y * w + x0..y * w + x1].copy_from_slice(&band[y * bw..(y + 1) * bw]); + } + } + out +} + +/// Approximate Gaussian (three box passes). +fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec { + box_means(v, w, h, &spatial::gauss_radii(sigma)) +} + +/// Box means of radii `radii` in turn. +fn box_means(v: &[f32], w: usize, h: usize, radii: &[usize]) -> Vec { + let mut out = v.to_vec(); + for &r in radii { + out = box_mean(&out, w, h, r); + } + out +} + +/// Fast guided filter (K. He, J. Sun, *Fast Guided Filter*, arXiv 2015): the linear +/// coefficients are computed on a `s×` subsampled copy and upsampled bilinearly, which is +/// visually equivalent for the large radii used by tone controls at a fraction of the cost. +fn guided_fast(i: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec { + let (s, rs) = spatial::fast_guided_steps(r); + if s == 1 { + return guided(i, p, w, h, r, eps); + } + let (sw, sh) = (w.div_ceil(s), h.div_ceil(s)); + let down = |v: &[f32]| -> Vec { + let mut o = vec![0.0f32; sw * sh]; + let mut c = vec![0.0f32; sw * sh]; + for y in 0..h { + for x in 0..w { + let k = (y / s) * sw + x / s; + o[k] += v[y * w + x]; + c[k] += 1.0; + } + } + o.iter().zip(&c).map(|(a, b)| a / b.max(1.0)).collect() + }; + let (si, sp) = (down(i), down(p)); + let mi = box_mean(&si, sw, sh, rs); + let mp = box_mean(&sp, sw, sh, rs); + let ip: Vec = si.iter().zip(&sp).map(|(a, b)| a * b).collect(); + let ii: Vec = si.iter().map(|a| a * a).collect(); + let mip = box_mean(&ip, sw, sh, rs); + let mii = box_mean(&ii, sw, sh, rs); + let a: Vec = (0..sw * sh).map(|k| (mip[k] - mi[k] * mp[k]) / (mii[k] - mi[k] * mi[k] + eps)).collect(); + let b: Vec = (0..sw * sh).map(|k| mp[k] - a[k] * mi[k]).collect(); + let (ma, mb) = (box_mean(&a, sw, sh, rs), box_mean(&b, sw, sh, rs)); + let mut out = vec![0.0f32; w * h]; + let sf = s as f32; + par_rows(&mut out, w, 1, |y, row| { + let fy = (y as f32 + 0.5) / sf - 0.5; + for (x, o) in row.iter_mut().enumerate() { + let fx = (x as f32 + 0.5) / sf - 0.5; + let av = util::bilinear(&ma, sw, sh, 1, 0, fx, fy); + let bv = util::bilinear(&mb, sw, sh, 1, 0, fx, fy); + *o = av * i[y * w + x] + bv; + } + }); + out +} + +/// Guided filter of `p` guided by `i` (He et al. 2010). +fn guided(i: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec { + let mi = box_mean(i, w, h, r); + let mp = box_mean(p, w, h, r); + let ip: Vec = i.iter().zip(p).map(|(a, b)| a * b).collect(); + let ii: Vec = i.iter().map(|a| a * a).collect(); + let mip = box_mean(&ip, w, h, r); + let mii = box_mean(&ii, w, h, r); + let a: Vec = (0..w * h).map(|k| (mip[k] - mi[k] * mp[k]) / (mii[k] - mi[k] * mi[k] + eps)).collect(); + let b: Vec = (0..w * h).map(|k| mp[k] - a[k] * mi[k]).collect(); + let ma = box_mean(&a, w, h, r); + let mb = box_mean(&b, w, h, r); + (0..w * h).map(|k| ma[k] * i[k] + mb[k]).collect() +} + +/// Monotone cubic (Fritsch–Carlson) through `pts` (x ascending, 0..=1), evaluated into a LUT via +/// [`crate::color::spline::MonotoneCurve`]. +pub fn curve_lut(pts: &[[f32; 2]], n: usize) -> Vec { + // Keep the legacy f32 knot selection; normalizing in f64 can drop a saved knot. + let mut p: Vec<[f32; 2]> = pts.iter().map(|q| [q[0] / 255.0, q[1] / 255.0]).collect(); + p.sort_by(|a, b| a[0].total_cmp(&b[0])); + p.dedup_by(|a, b| (a[0] - b[0]).abs() < 1e-6); + if p.len() < 2 || n < 2 { + return (0..n).map(|k| if n <= 1 { 0.0 } else { k as f32 / (n - 1) as f32 }).collect(); + } + let p: Vec<_> = p.into_iter().map(|[x, y]| (f64::from(x), f64::from(y))).collect(); + crate::color::spline::MonotoneCurve::new(&p).to_lut(n).v.into_iter().map(|v| v.clamp(0.0, 1.0)).collect() +} + +/// Migrate a PhotoCraft Camera Raw / `filter.cameraRaw` settings object to shared +/// [`craft_develop_model::DevelopSettings`], stripping PhotoCraft-only transport keys +/// (`layer`, `encodingGamma`, `__cameraRawPsd`) before delegating to +/// [`craft_develop_model::migration::migrate_camera_raw`]. +pub fn migrate_to_develop_settings( + base: &craft_develop_model::DevelopSettings, + fields: &serde_json::Value, +) -> Result { + let Some(obj) = fields.as_object() else { + return craft_develop_model::migration::migrate_camera_raw(base, fields); + }; + let cleaned: serde_json::Map = obj + .iter() + .filter(|(k, _)| !matches!(k.as_str(), "layer" | "encodingGamma" | "__cameraRawPsd")) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + craft_develop_model::migration::migrate_camera_raw(base, &serde_json::Value::Object(cleaned)) +} + +fn lut_eval(lut: &[f32], v: f32) -> f32 { + if !(0.0..=1.0).contains(&v) { + // Extend linearly outside (float documents). + return if v < 0.0 { v + lut[0] } else { lut[lut.len() - 1] + (v - 1.0) }; + } + let x = v * (lut.len() - 1) as f32; + let i = (x as usize).min(lut.len() - 2); + let t = x - i as f32; + lut[i] + (lut[i + 1] - lut[i]) * t +} + +/// Parametric tone curve as a LUT (regions split at `splits`, each slider ±100 moves its region +/// by up to a quarter of the range, smoothly). +fn parametric_lut(p: &CameraRaw, n: usize) -> Vec { + let s = p.curve_splits.map(|v| v.clamp(5.0, 95.0) / 100.0); + let centres = [s[0] / 2.0, (s[0] + s[1]) / 2.0, (s[1] + s[2]) / 2.0, (s[2] + 1.0) / 2.0]; + let amounts = [p.curve_shadows, p.curve_darks, p.curve_lights, p.curve_highlights]; + let widths = [s[0].max(0.1), (s[1] - s[0]).max(0.1), (s[2] - s[1]).max(0.1), (1.0 - s[2]).max(0.1)]; + let mut lut: Vec = (0..n) + .map(|i| { + let x = i as f32 / (n - 1) as f32; + let mut y = x; + for k in 0..4 { + let d = (x - centres[k]) / (widths[k] * 1.2); + let bump = (-d * d * 2.0).exp() * x * (1.0 - x) * 4.0; + y += amounts[k] / 100.0 * 0.25 * bump; + } + y.clamp(0.0, 1.0) + }) + .collect(); + // Keep it monotone. + for i in 1..n { + lut[i] = lut[i].max(lut[i - 1]); + } + lut +} + +fn rgb_to_hsv(c: [f32; 3]) -> [f32; 3] { + let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); + let d = mx - mn; + let h = if d <= 1e-9 { + 0.0 + } else if mx == c[0] { + 60.0 * (((c[1] - c[2]) / d).rem_euclid(6.0)) + } else if mx == c[1] { + 60.0 * ((c[2] - c[0]) / d + 2.0) + } else { + 60.0 * ((c[0] - c[1]) / d + 4.0) + }; + [h, if mx > 1e-9 { d / mx } else { 0.0 }, mx] +} + +fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] { + let h = h.rem_euclid(360.0) / 60.0; + let c = v * s; + let x = c * (1.0 - ((h % 2.0) - 1.0).abs()); + let (r, g, b) = match h as u32 { + 0 => (c, x, 0.0), + 1 => (x, c, 0.0), + 2 => (0.0, c, x), + 3 => (0.0, x, c), + 4 => (x, 0.0, c), + _ => (c, 0.0, x), + }; + let m = v - c; + [r + m, g + m, b + m] +} + +/// Weights of the eight HSL bands at hue `h` (hat functions between neighbouring centres). +pub fn band_weights(h: f32) -> [f32; 8] { + let mut w = [0.0f32; 8]; + for k in 0..8 { + let (c, prev, next) = (HSL_BANDS[k], HSL_BANDS[(k + 7) % 8], HSL_BANDS[(k + 1) % 8]); + let diff = (h - c + 540.0).rem_euclid(360.0) - 180.0; + let span = if diff >= 0.0 { (next - c).rem_euclid(360.0) } else { (c - prev).rem_euclid(360.0) }; + w[k] = (1.0 - diff.abs() / span.max(1e-3)).max(0.0); + } + w +} + +#[cfg(test)] +#[test] +fn band_weights_wrap_equivalent_hues_in_both_directions() { + let weights = band_weights(320.0); + assert_eq!(band_weights(-400.0), weights); + assert_eq!(band_weights(680.0), weights); +} + +/// Contrast, Highlights, Shadows, Texture and Clarity (the luminance stage) at rest. +fn local_tone_neutral(p: &CameraRaw) -> bool { + [p.contrast, p.highlights, p.shadows, p.texture, p.clarity].iter().all(|v| *v == 0.0) +} + +/// The Color Mixer at rest. +pub(crate) fn hsl_neutral(p: &CameraRaw) -> bool { + p.hsl_hue.iter().chain(&p.hsl_sat).chain(&p.hsl_lum).all(|v| *v == 0.0) +} + +/// Color Grading at rest. +pub(crate) fn grade_neutral(p: &CameraRaw) -> bool { + [&p.grade_shadows, &p.grade_midtones, &p.grade_highlights, &p.grade_global].iter().all(|w| w.sat == 0.0 && w.lum == 0.0) +} + +/// The Calibration panel at rest. +pub(crate) fn calibration_neutral(p: &CameraRaw) -> bool { + p.shadow_tint == 0.0 && p.calibration_hue.iter().chain(&p.calibration_sat).all(|v| *v == 0.0) +} + +/// The Tone Curve panel at rest. +fn curves_neutral(p: &CameraRaw) -> bool { + [p.curve_highlights, p.curve_lights, p.curve_darks, p.curve_shadows].iter().all(|v| *v == 0.0) + && [&p.point_curve, &p.point_curve_red, &p.point_curve_green, &p.point_curve_blue].iter().all(|c| is_linear(c)) +} + +fn is_linear(c: &[[f32; 2]]) -> bool { + c.len() < 2 || c.iter().all(|p| (p[0] - p[1]).abs() < 1e-3) +} + +/// Camera Raw's white-balance channel gains for Temperature / Tint (−100…100), relative to the +/// as-shot balance: warmer raises red and lowers blue (±35 % at the ends); a negative tint +/// raises green, a positive one lowers it toward magenta (±25 %). An observed approximation of +/// Adobe Camera Raw's sliders, not a colour-temperature model; shared by the filter (in linear +/// RGB) and the raw open (on the camera's white-balance multipliers) so both agree. +pub fn white_balance_gains(temperature: f32, tint: f32) -> [f32; 3] { + let t = temperature / 100.0; + let tn = tint / 100.0; + [1.0 + 0.35 * t, 1.0 - 0.25 * tn, 1.0 - 0.35 * t] +} + +/// Runs the Camera Raw pipeline on straight RGBA pixels (`w × h`, display-encoded RGB). +/// `float` keeps values above 1 (32-bit documents). `inputs` are the job's scale, grain seed and encoding. +pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs, float: bool) { + if px.is_empty() || p.is_identity() { + return; + } + let ps = inputs.pixel_scale.clamp(0.01, 1.0); + // 1. White balance + exposure in linear light. + if let Some(g) = per_pixel::gains(p) { + par_rows(px, w, 1, |_, row| { + for q in row.iter_mut() { + *q = balance(*q, g); + } + }); + } + // 1b. Calibration: the primaries turned and purer or greyer, and the shadows tinted, in + // linear light (the camera's primaries are what Camera Raw's panel calibrates). + if !calibration_neutral(p) { + let primaries = p.calibration_hue.iter().chain(&p.calibration_sat).any(|v| *v != 0.0); + let tint = p.shadow_tint.clamp(-100.0, 100.0) / 100.0; + par_rows(px, w, 1, |_, row| { + for q in row.iter_mut() { + let c = [srgb_to_linear(q[0]), srgb_to_linear(q[1]), srgb_to_linear(q[2])]; + let mut o = if primaries { calibrate(c, p.calibration_hue, p.calibration_sat) } else { c }; + if tint != 0.0 { + o = shadow_tint(o, tint); + } + for k in 0..3 { + q[k] = linear_to_srgb(o[k].max(0.0)); + } + } + }); + } + // 2. Dehaze. + if let Some(d) = Dehaze::new(p, w, h) { + dehaze(px, w, h, &d); + } + // 3. Tone. Highlights and Shadows: a local Laplacian filter (see `local_tone`). + if p.highlights != 0.0 || p.shadows != 0.0 { + local_tone::apply(px, w, h, p.shadows, p.highlights, Encoding::of(inputs.encoding_gamma)); + } + if !local_tone_neutral(p) && [p.contrast, p.texture, p.clarity].iter().any(|v| *v != 0.0) { + let l: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]]).max(0.0)).collect(); + let lc: Vec = l.iter().map(|v| v.min(1.0)).collect(); + let clarity = Clarity::new(p, w, h); + let texture = Texture::new(p, inputs, w, h); + let clar = clarity.as_ref().map(|c| guided_fast(&lc, &lc, w, h, c.radius, spatial::CLARITY_EPS)); + let tex = texture.as_ref().map(|t| box_means(&lc, w, h, &t.radii)); + let k_con = p.contrast / 100.0 * 0.6; + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + let i = y * w + x; + let l0 = l[i]; + let mut lv = lc[i]; + if let (Some(c), Some(k)) = (&clar, &clarity) { + let mw = 1.0 - (2.0 * lv.clamp(0.0, 1.0) - 1.0).powi(2); + lv += k.amount * (lc[i] - c[i]) * mw; + } + if let (Some(t), Some(k)) = (&tex, &texture) { + lv += k.amount * (lc[i] - t[i]).clamp(-spatial::TEXTURE_LIMIT, spatial::TEXTURE_LIMIT); + } + *q = tone(*q, l0, lc[i], lv, k_con); + } + }); + } + // 3b. Whites and Blacks: global curves adapted to the image's black and white points. + if p.whites != 0.0 || p.blacks != 0.0 { + let enc = Encoding::of(inputs.encoding_gamma); + let (bp, wp) = luminance_points(px, w, h, enc, |q| q); + let (xw, xb) = whites_blacks::amounts(p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0), bp, wp); + whites_blacks::apply(px, w, xw, xb, enc); + } + // 4–7: per-pixel colour stages. + let need_color = p.vibrance != 0.0 || p.saturation != 0.0 || !curves_neutral(p) || !hsl_neutral(p) || !grade_neutral(p); + if need_color { + let par = (!(p.curve_highlights == 0.0 && p.curve_lights == 0.0 && p.curve_darks == 0.0 && p.curve_shadows == 0.0)) + .then(|| parametric_lut(p, 1024)); + let pts = |c: &Vec<[f32; 2]>| (!is_linear(c)).then(|| curve_lut(c, 1024)); + let (master, cr, cg, cb) = (pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)); + let hsl = !hsl_neutral(p); + let grade = !grade_neutral(p); + let Grade { tints, lums, blend, balance: bal } = Grade::new(p); + par_rows(px, w, 1, |_, row| { + for q in row.iter_mut() { + let mut c = [q[0], q[1], q[2]]; + if p.vibrance != 0.0 || p.saturation != 0.0 { + let l = luma(c); + let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); + let sat = if mx > 1e-6 { (mx - mn) / mx } else { 0.0 }; + // Vibrance protects skin-ish hues (oranges) a little, like ACR. + let hue = rgb_to_hsv(c)[0]; + let skin = (1.0 - ((hue - 25.0).abs() / 25.0)).clamp(0.0, 1.0) * 0.5; + let k = 1.0 + p.saturation / 100.0 + p.vibrance / 100.0 * (1.0 - sat) * (1.0 - skin); + c = c.map(|v| l + (v - l) * k.max(0.0)); + } + if let Some(lut) = &par { + c = c.map(|v| lut_eval(lut, v)); + } + if let Some(lut) = &master { + c = c.map(|v| lut_eval(lut, v)); + } + for (ch, lut) in [&cr, &cg, &cb].iter().enumerate() { + if let Some(lut) = lut { + c[ch] = lut_eval(lut, c[ch]); + } + } + if hsl { + let [hh, s, v] = rgb_to_hsv(c.map(|x| x.max(0.0))); + if s > 1e-4 { + let wts = band_weights(hh); + let (mut dh, mut ds, mut dl) = (0.0f32, 0.0f32, 0.0f32); + for k in 0..8 { + dh += wts[k] * p.hsl_hue[k]; + ds += wts[k] * p.hsl_sat[k]; + dl += wts[k] * p.hsl_lum[k]; + } + let nh = hh + dh / 100.0 * 30.0; + let ns = (s * (1.0 + ds / 100.0)).clamp(0.0, 1.0); + let mut out = hsv_to_rgb(nh, ns, v); + // Keep the luminance, then apply the luminance shift weighted by saturation. + let (l0, l1) = (luma(c), luma(out)); + if l1 > 1e-6 { + out = out.map(|x| x * l0 / l1); + } + let k = 2f32.powf(dl / 100.0 * 1.0 * s); + c = out.map(|x| x * k); + } + } + if grade { + let l = luma(c).clamp(0.0, 1.0); + let sh = 1.0 - smoothstep(0.0, 0.5 + bal + blend, l); + let hi = smoothstep(0.5 + bal - blend, 1.0, l); + let mid = (1.0 - sh - hi).max(0.0); + let masks = [sh, mid, hi, 1.0]; + for k in 0..4 { + for ch in 0..3 { + c[ch] += masks[k] * tints[k][ch]; + } + if lums[k] != 0.0 { + let f = 2f32.powf(masks[k] * lums[k] / 100.0 * 0.6); + c = c.map(|x| x * f); + } + } + } + q[0] = c[0]; + q[1] = c[1]; + q[2] = c[2]; + } + }); + } + // 8. Detail. + if p.noise_luminance > 0.0 || p.noise_color > 0.0 || p.sharpen_amount > 0.0 { + detail(px, w, h, p, ps); + } + // 9. Effects. + if p.vignette_amount != 0.0 { + vignette(px, w, h, p); + } + if p.grain_amount > 0.0 { + let Grain { cell, roughness: rough, amount: amt, seed, scale: pscale } = Grain::new(p, inputs); + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + // Sample in full-resolution coordinates so previews match the result. + let (fx, fy) = (x as f32 * pscale / cell, y as f32 * pscale / cell); + let n = value_noise(fx, fy, seed) * (1.0 - rough) + (value_noise(fx * 2.3, fy * 2.3, seed + 7) - 0.0) * rough; + let l = luma([q[0], q[1], q[2]]).clamp(0.0, 1.0); + let g = (n - 0.5) * 2.0 * amt * (0.4 + 2.4 * l * (1.0 - l)); + for c in 0..3 { + q[c] += g; + } + } + }); + } + if !float { + for q in px.iter_mut() { + for c in 0..3 { + q[c] = q[c].clamp(0.0, 1.0); + } + } + } +} + +/// The end of stage 3 on one pixel: Contrast (strength `k_con`) on the luminance `lv` that +/// Clarity and Texture left, then the pixel rescaled to it. `l0` is its luminance, `lc` that +/// clipped to 1. +fn tone(mut q: [f32; 4], l0: f32, lc: f32, mut lv: f32, k_con: f32) -> [f32; 4] { + if k_con != 0.0 { + let tau = std::f32::consts::TAU; + let xx = lv.clamp(0.0, 1.0); + lv += -k_con * (tau * xx).sin() / tau; + } + let lv = lv.max(0.0) + (l0 - lc); + let ratio = if l0 > 1e-5 { lv / l0 } else { 1.0 }; + for c in 0..3 { + q[c] = if l0 > 1e-5 { q[c] * ratio } else { q[c] + (lv - l0) }; + } + q +} + +/// Stage 3 on one pixel when Contrast is its only control. +fn contrast(q: [f32; 4], k_con: f32) -> [f32; 4] { + let l0 = luma([q[0], q[1], q[2]]).max(0.0); + let lc = l0.min(1.0); + tone(q, l0, lc, lc, k_con) +} + +/// Stage 1 on one pixel: white balance and exposure `gains` in linear light. +fn balance(mut q: [f32; 4], g: [f32; 3]) -> [f32; 4] { + for c in 0..3 { + q[c] = linear_to_srgb((srgb_to_linear(q[c]) * g[c]).max(0.0)); + } + q +} + +/// The index of the `q` quantile (0 … 1) among `len` sorted values, as every percentile in the +/// develop picks it. +pub fn quantile_rank(len: usize, q: f32) -> usize { + let last = len.saturating_sub(1); + ((last as f32 * q).round() as usize).min(last) +} + +#[cfg(test)] +#[test] +fn quantile_rank_keeps_the_upper_endpoint_inside_the_sample() { + // This last index rounds up when cast to f32. + let len = 16_777_220; + assert_eq!(quantile_rank(len, 1.0), len - 1); + assert_eq!(quantile_rank(4, 0.5), 2); + assert_eq!(quantile_rank(0, 1.0), 0); +} + +/// The image's black and white points as sRGB-encoded grey levels: the 3rd percentile of the +/// luminance and the 99.5th of the brightest channel, on a copy at most 256 pixels across (so a +/// preview proxy and the full image agree). `map` is applied to each pixel first. +fn luminance_points(px: &[[f32; 4]], w: usize, h: usize, enc: Encoding, map: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> (f32, f32) { + let f = w.max(h).div_ceil(whites_blacks::POINTS_SIDE).max(1); + let (sw, sh) = (w.div_ceil(f), h.div_ceil(f)); + // Each band of `f` rows sums into its own row of cells, in the same order as one pass would. + let bands = util::par_map(sh, |sy| { + let mut sum = vec![[0.0f64; 4]; sw]; + for y in sy * f..((sy + 1) * f).min(h) { + for x in 0..w { + let q = map(px[y * w + x]); + let s = &mut sum[x / f]; + for c in 0..3 { + s[c] += f64::from(enc.decode(q[c]).clamp(0.0, 1.0)); + } + s[3] += 1.0; + } + } + sum + }); + let cells: Vec<[f32; 3]> = bands.iter().flatten().filter(|s| s[3] > 0.0).map(|s| [0, 1, 2].map(|c| (s[c] / s[3]) as f32)).collect(); + if cells.is_empty() { + return (0.0, 1.0); + } + let pct = |mut v: Vec, q: f32| { + v.sort_by(f32::total_cmp); + v[quantile_rank(v.len(), q)] + }; + let bp = pct(cells.iter().map(|c| luma(*c)).collect(), whites_blacks::POINT_QUANTILES[0]); + let wp = pct(cells.iter().map(|c| c[0].max(c[1]).max(c[2])).collect(), whites_blacks::POINT_QUANTILES[1]); + (linear_to_srgb(bp), linear_to_srgb(wp)) +} + +fn value_noise(x: f32, y: f32, seed: u64) -> f32 { + let (xi, yi) = (x.floor(), y.floor()); + let (tx, ty) = (x - xi, y - yi); + let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty)); + let h = |dx: i64, dy: i64| hash01(xi as i64 + dx, yi as i64 + dy, seed); + let top = h(0, 0) + (h(1, 0) - h(0, 0)) * sx; + let bot = h(0, 1) + (h(1, 1) - h(0, 1)) * sx; + top + (bot - top) * sy +} + +/// Dehaze's copy of `px` (`w × h`): each pixel mapped by `map`, clipped to 0 … 1 and averaged over +/// `d.factor × d.factor` blocks, each block summed in raster order. +fn haze_cells(px: &[[f32; 4]], w: usize, h: usize, d: &Dehaze, map: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Vec<[f32; 3]> { + let (k, [sw, sh]) = (d.factor, d.size); + let bands = util::par_map(sh, |sy| { + let mut small = vec![[0.0f32; 3]; sw]; + let mut cnt = vec![0f32; sw]; + for y in sy * k..((sy + 1) * k).min(h) { + for x in 0..w { + let q = map(px[y * w + x]); + let i = x / k; + for c in 0..3 { + small[i][c] += q[c].clamp(0.0, 1.0); + } + cnt[i] += 1.0; + } + } + small.iter().zip(&cnt).map(|(s, c)| s.map(|v| v / c.max(1.0))).collect::>() + }); + bands.into_iter().flatten().collect() +} + +fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, d: &Dehaze) { + // Transmission on a ≤ DEHAZE_SIDE px proxy, upsampled. + let (k, [sw, sh], r, amount) = (d.factor, d.size, d.radius, d.amount); + let small = haze_cells(px, w, h, d, |q| q); + // The minimum (or, with `f32::max`, maximum) over each (2r + 1)² window. + let rank_filter = |v: &[f32], start: f32, pick: fn(f32, f32) -> f32| -> Vec { + let mut a = vec![0.0f32; sw * sh]; + for y in 0..sh { + for x in 0..sw { + let (x0, x1) = (x.saturating_sub(r), (x + r).min(sw - 1)); + a[y * sw + x] = (x0..=x1).map(|xx| v[y * sw + xx]).fold(start, pick); + } + } + let mut b = vec![0.0f32; sw * sh]; + for y in 0..sh { + for x in 0..sw { + let (y0, y1) = (y.saturating_sub(r), (y + r).min(sh - 1)); + b[y * sw + x] = (y0..=y1).map(|yy| a[yy * sw + x]).fold(start, pick); + } + } + b + }; + let min_filter = |v: &[f32]| rank_filter(v, f32::MAX, f32::min); + let dark = min_filter(&small.iter().map(|c| c[0].min(c[1]).min(c[2])).collect::>()); + // Atmospheric light: mean colour of the brightest 0.1 % of the dark channel (ties in the + // order of the cells). + let mut idx: Vec = (0..sw * sh).collect(); + idx.sort_by(|&a, &b| dark[b].total_cmp(&dark[a])); + let top = d.top; + let mut air = [0.0f32; 3]; + for &i in &idx[..top] { + for c in 0..3 { + air[c] += small[i][c] / top as f32; + } + } + let air = air.map(|v| v.max(spatial::DEHAZE_AIR_FLOOR)); + let norm_dark = min_filter(&small.iter().map(|c| (c[0] / air[0]).min(c[1] / air[1]).min(c[2] / air[2])).collect::>()); + // Opened (a maximum filter of the same radius after the minimum): the minimum grows every + // dark object by `r`, so sky beside a dark building took its dark channel, counted as + // haze-free and kept a bright halo (#9273). Opening shrinks dark regions back to their + // outline and is still a lower bound of the dark channel over the window. It raises the dark + // channel on average, so the ω weight is scaled to keep the slider's overall strength. + let opened = rank_filter(&norm_dark, f32::MIN, f32::max); + // Summed in f64: an f32 running sum over the copy's few hundred thousand cells drifts by about + // 1e-5, which the low transmission beside haze multiplies up to a visible fraction of a level. + let mean = |v: &[f32]| (v.iter().map(|x| f64::from(*x)).sum::() / v.len().max(1) as f64) as f32; + let weight = spatial::DEHAZE_OMEGA * mean(&norm_dark) / mean(&opened).max(1e-6); + let t_raw: Vec = opened.iter().map(|d| 1.0 - weight * d).collect(); + let guide: Vec = small.iter().map(|c| luma(*c)).collect(); + let t = guided(&guide, &t_raw, sw, sh, d.guide_radius, spatial::DEHAZE_EPS); + let ks = k as f32; + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + let tv = util::bilinear(&t, sw, sh, 1, 0, (x as f32 + 0.5) / ks - 0.5, (y as f32 + 0.5) / ks - 0.5).clamp(spatial::DEHAZE_T_FLOOR, 1.0); + for c in 0..3 { + let i = q[c]; + let j = (i - air[c]) / tv + air[c]; + q[c] = if amount >= 0.0 { i + (j - i) * amount } else { i + (air[c] - i) * (-amount) * 0.5 * (1.0 - tv * 0.5) }; + } + } + }); +} + +fn sharpening_detail(detail: f32) -> f32 { + let detail = if detail.is_nan() { CameraRaw::default().sharpen_detail } else { detail.clamp(0.0, 100.0) }; + detail / 100.0 +} + +fn detail(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, ps: f32) { + // The controls' documented 0..=100 range: raw values drive the filter radii below. + let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0)); + // Work in Y + chroma (BT.709 luma, B−Y, R−Y). + let mut y: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect(); + let mut cb: Vec = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect(); + let mut cr: Vec = px.iter().zip(&y).map(|(q, l)| q[0] - l).collect(); + if nl > 0.0 { + let n = nl / 100.0; + let r = ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize; + let smooth = guided(&y, &y, w, h, r, (n * 0.06).powi(2) + 1e-6); + let keep = nld / 100.0 * 0.5; + for i in 0..w * h { + y[i] = smooth[i] + (y[i] - smooth[i]) * keep; + } + } + if nc > 0.0 { + let sigma = (nc / 100.0 * 6.0 * ps).max(0.3); + let (bcb, bcr) = (gauss(&cb, w, h, sigma), gauss(&cr, w, h, sigma)); + let keep = ncd / 100.0 * 0.3; + for i in 0..w * h { + cb[i] = bcb[i] + (cb[i] - bcb[i]) * keep; + cr[i] = bcr[i] + (cr[i] - bcr[i]) * keep; + } + } + if p.sharpen_amount > 0.0 { + let sigma = (p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3); + let blur = gauss(&y, w, h, sigma); + // Masking: an edge mask from the gradient of a smoothed luminance. + let mask: Option> = (p.sharpen_masking > 0.0).then(|| { + let s = gauss(&y, w, h, 1.0 * ps.max(0.5)); + let t = p.sharpen_masking / 100.0 * 0.08; + util::par_map(w * h, |i| { + let (x, yy) = (i % w, i / w); + let gx = s[yy * w + (x + 1).min(w - 1)] - s[yy * w + x.saturating_sub(1)]; + let gy = s[(yy + 1).min(h - 1) * w + x] - s[yy.saturating_sub(1) * w + x]; + smoothstep(t * 0.5, t + 1e-4, gx.hypot(gy)) + }) + }); + let amt = p.sharpen_amount / 100.0 * 1.2; + let det = sharpening_detail(p.sharpen_detail); + for i in 0..w * h { + let hp = y[i] - blur[i]; + // Low Detail damps large (halo-producing) differences. + let limit = 0.03 + det * 0.3; + let hp = hp.clamp(-limit, limit) * (0.5 + 0.5 * det); + let m = mask.as_ref().map_or(1.0, |m| m[i]); + y[i] += amt * hp * m; + } + } + for i in 0..w * h { + let (l, b, r) = (y[i], cb[i], cr[i]); + let (rr, bb) = (r + l, b + l); + let g = (l - 0.2126 * rr - 0.0722 * bb) / 0.7152; + px[i][0] = rr; + px[i][1] = g; + px[i][2] = bb; + } +} + +fn vignette(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw) { + let Vignette { amount: amt, highlights: hl, style, centre: [cx, cy], axes: [ax, ay], power: pw, edges: [edge0, edge1] } = Vignette::new(w, h, p); + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + let (dx, dy) = (((x as f32 + 0.5 - cx) / ax).abs(), ((y as f32 + 0.5 - cy) / ay).abs()); + let r = (dx.powf(pw) + dy.powf(pw)).powf(1.0 / pw); + let m = smoothstep(edge0, edge1, r); + if m <= 0.0 { + continue; + } + let l = luma([q[0], q[1], q[2]]).clamp(0.0, 1.0); + match style { + VignetteStyle::PaintOverlay => { + let target = if amt < 0.0 { 0.0 } else { 1.0 }; + let k = m * amt.abs(); + for c in 0..3 { + q[c] += (target - q[c]) * k; + } + } + _ => { + let mut k = 2f32.powf(amt * 2.0 * m); + if amt < 0.0 && hl > 0.0 { + // Highlights: let bright areas punch through a darkening vignette. + let protect = smoothstep(0.6, 1.0, l) * hl; + k += (1.0 - k) * protect; + } + if style == VignetteStyle::ColorPriority { + let nl = l * k; + for c in 0..3 { + q[c] += nl - l; + } + } else { + for c in 0..3 { + q[c] *= k; + } + } + } + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `CameraRaw` with the named fields set (the type is `#[non_exhaustive]`, so no struct expression), or a copy of a base with them set. + macro_rules! cr { + ($($f:ident : $v:expr),* $(,)?) => {{ + let mut s = CameraRaw::default(); + $(s.$f = $v;)* + s + }}; + ($base:expr => $($f:ident : $v:expr),* $(,)?) => {{ + let mut s: CameraRaw = $base; + $(s.$f = $v;)* + s + }}; + } + + /// [`super::develop`] with the default inputs (full scale, sRGB encoding, seed 0). + fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bool) { + super::develop(px, w, h, p, &DevelopInputs::default(), float); + } + + /// [`super::per_pixel`] with the default inputs. + fn per_pixel(p: &CameraRaw, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { + super::per_pixel(p, &DevelopInputs::default(), w, h, float, points) + } + + #[test] + fn sharpening_detail_stays_in_range_at_the_shared_entry_point() { + for value in [0.0_f32, 25.0, 37.5, 100.0] { + assert_eq!(sharpening_detail(value).to_bits(), (value / 100.0).to_bits()); + } + assert_eq!(sharpening_detail(-1.0), 0.0); + assert_eq!(sharpening_detail(101.0), 1.0); + assert_eq!(sharpening_detail(f32::NAN), sharpening_detail(CameraRaw::default().sharpen_detail)); + assert_eq!(sharpening_detail(f32::NEG_INFINITY), 0.0); + assert_eq!(sharpening_detail(f32::INFINITY), 1.0); + } + + /// #9273: Dehaze clears the haze evenly over a sky, right up to a dark building, instead of + /// leaving a bright halo of uncorrected haze around it. Synthetic scene: a clear sky and a + /// dark tower, hazed with `I = J·t + A·(1 − t)`. + #[test] + fn dehaze_leaves_no_halo_beside_dark_objects() { + let (w, h) = (600usize, 400usize); + let tower = |x: usize, y: usize| (250..350).contains(&x) && y >= 120; + let (t, air) = (0.55f32, [0.9f32, 0.9, 0.9]); + let mut px: Vec<[f32; 4]> = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let j = if tower(x, y) { [0.06, 0.06, 0.07] } else { [0.35 + 0.1 * y as f32 / h as f32, 0.5, 0.8] }; + let c: [f32; 3] = std::array::from_fn(|k| j[k] * t + air[k] * (1.0 - t)); + [c[0], c[1], c[2], 1.0] + }) + .collect(); + let d = Dehaze::new(&cr! { dehaze: 100.0}, w, h).unwrap(); + dehaze(&mut px, w, h, &d); + let sky = |xs: std::ops::Range| { + let v: Vec = (150..390) + .flat_map(|y| xs.clone().map(move |x| (x, y))) + .map(|(x, y)| luma([px[y * w + x][0], px[y * w + x][1], px[y * w + x][2]])) + .collect(); + v.iter().sum::() / v.len() as f32 + }; + // Sky 1–8 px from the tower against open sky: the haze left beside it, in 8-bit levels. + let halo = (sky(242..250) - sky(20..80)) * 255.0; + // 6.4 levels before the dark channel was opened, under 1 after. + assert!(halo < 3.0, "a {halo:.1}-level halo beside the tower"); + // The open sky is still cleared: darker than the hazy input. + let hazy = luma(std::array::from_fn(|k| [0.4, 0.5, 0.8][k] * t + air[k] * (1.0 - t))); + assert!(sky(20..80) < hazy - 0.02, "{} vs hazy {hazy}", sky(20..80)); + } + + #[test] + fn new_curves_are_validated_but_saved_curves_still_load_and_render() { + for field in ["pointCurve", "pointCurveRed", "pointCurveGreen", "pointCurveBlue"] { + for points in [ + serde_json::json!([[128, 128]]), + serde_json::json!([[255, 255], [0, 0]]), + serde_json::json!([[0, 0], [0, 255]]), + serde_json::json!([[0, -1], [255, 255]]), + serde_json::json!([[0, 0], [256, 255]]), + serde_json::json!([[0, 0], [1e30, 255]]), + serde_json::json!((0..17).map(|i| [i * 15, i * 15]).collect::>()), + ] { + let p: CameraRaw = serde_json::from_value(serde_json::json!({field: points})).unwrap(); + assert!(p.validate().is_err(), "{field}: {points}"); + } + for points in [ + serde_json::json!([]), + serde_json::json!([[0, 0], [255, 255]]), + serde_json::json!((0..16).map(|i| [i * 17, i * 17]).collect::>()), + ] { + let p: CameraRaw = serde_json::from_value(serde_json::json!({field: points})).unwrap(); + assert!(p.validate().is_ok(), "{field}: {points}"); + } + } + assert_eq!(serde_json::from_str::("{}").unwrap(), CameraRaw::default()); + // An older editor could stack two points on one input and exceed 16 points; such a + // saved Smart Filter must still develop instead of silently disappearing. + let mut legacy: Vec<[f32; 2]> = (0..20).map(|i| [i as f32 * 12.0, i as f32 * 12.0]).collect(); + legacy.insert(5, [60.0, 200.0]); + let p: CameraRaw = serde_json::from_value(serde_json::json!({"pointCurve": legacy})).unwrap(); + assert!(p.validate().is_err()); + let edited = cr! { p.clone() => exposure: 1.0}; + assert!(edited.validate_changes(&p).is_ok(), "an unchanged stored curve stays editable"); + let broken = cr! { p.clone() => point_curve: vec![[10.0, 10.0]]}; + assert!(broken.validate_changes(&p).is_err(), "a changed curve is validated"); + let mut px = img(4, 4); + develop(&mut px, 4, 4, &p, false); + assert!(px.iter().flatten().all(|v| v.is_finite())); + } + + fn img(w: usize, h: usize) -> Vec<[f32; 4]> { + (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as f32 / w as f32, (i / w) as f32 / h as f32); + [0.2 + 0.6 * x, 0.3 + 0.4 * y, 0.5 - 0.3 * x * y, 1.0] + }) + .collect() + } + + fn mean(px: &[[f32; 4]], c: usize) -> f32 { + px.iter().map(|q| q[c]).sum::() / px.len() as f32 + } + + #[test] + fn defaults_are_identity() { + let mut a = img(40, 30); + let b = a.clone(); + develop(&mut a, 40, 30, &CameraRaw::default(), false); + assert_eq!(a, b); + } + + #[test] + fn basic_panel_moves_the_right_way() { + let (w, h) = (64, 48); + let base = img(w, h); + let run = |p: CameraRaw| { + let mut a = base.clone(); + develop(&mut a, w, h, &p, false); + a + }; + let warm = run(cr! { temperature: 50.0}); + assert!(mean(&warm, 0) > mean(&base, 0) && mean(&warm, 2) < mean(&base, 2)); + let bright = run(cr! { exposure: 1.0}); + assert!(mean(&bright, 1) > mean(&base, 1) + 0.1); + let shadows = run(cr! { shadows: 100.0}); + let dark_px = |a: &[[f32; 4]]| a[0][1]; + assert!(dark_px(&shadows) > dark_px(&base)); + let hl = run(cr! { highlights: -100.0}); + assert!(hl[w * h - 1][0] < base[w * h - 1][0]); + let con = run(cr! { contrast: 100.0}); + // More contrast: darker darks, brighter brights. + assert!(con[0][1] < base[0][1] && con[w * h - 1][0] > base[w * h - 1][0]); + let desat = run(cr! { saturation: -100.0}); + assert!(desat.iter().all(|q| (q[0] - q[1]).abs() < 1e-4 && (q[1] - q[2]).abs() < 1e-4)); + let vib = run(cr! { vibrance: 100.0}); + let spread = |q: [f32; 4]| q[0].max(q[1]).max(q[2]) - q[0].min(q[1]).min(q[2]); + assert!(spread(vib[w * h / 2]) > spread(base[w * h / 2])); + for p in [cr! { clarity: 80.0}, cr! { texture: 80.0}, cr! { dehaze: 60.0}, cr! { dehaze: -60.0}, cr! { whites: 50.0, blacks: -50.0}] { + let out = run(p.clone()); + assert!(out.iter().all(|q| q[..3].iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))), "{p:?}"); + assert_ne!(out, base); + } + } + + #[test] + fn camera_raw_curve_keeps_legacy_close_knots() { + // The middle knots survive the original f32 normalization and make a sharp step. + let x = 127.5_f32; + let close = f32::from_bits(x.to_bits() + 33); + let lut = curve_lut(&[[0.0, 0.0], [x, 0.0], [close, 255.0], [255.0, 255.0]], 1024); + assert!(lut[256] < 0.01 && lut[767] > 0.99, "expected the legacy step, got {} and {}", lut[256], lut[767]); + } + + #[test] + fn curves_hsl_grading_detail_effects() { + // Monotone cubic LUT through the points. + let lut = curve_lut(&[[0.0, 0.0], [64.0, 40.0], [192.0, 220.0], [255.0, 255.0]], 256); + assert!((lut[64] - 40.0 / 255.0).abs() < 0.01 && (lut[192] - 220.0 / 255.0).abs() < 0.01); + assert!(lut.windows(2).all(|p| p[1] >= p[0])); + // Band weights sum to one everywhere. + for hh in (0..360).step_by(7) { + let s: f32 = band_weights(hh as f32).iter().sum(); + assert!((s - 1.0).abs() < 1e-4, "{hh}: {s}"); + } + let (w, h) = (48, 32); + let reds: Vec<[f32; 4]> = vec![[0.8, 0.2, 0.2, 1.0]; w * h]; + let mut a = reds.clone(); + let mut hs = [0.0; 8]; + hs[0] = -100.0; + develop(&mut a, w, h, &cr! { hsl_sat: hs}, false); + assert!(a[0][0] - a[0][1] < 0.1, "reds desaturated: {:?}", a[0]); + let blues: Vec<[f32; 4]> = vec![[0.2, 0.2, 0.8, 1.0]; w * h]; + let mut b = blues.clone(); + develop(&mut b, w, h, &cr! { hsl_sat: hs}, false); + assert!((b[0][2] - 0.8).abs() < 1e-4, "blues untouched"); + // Grading: blue shadows tint dark pixels, leave bright ones nearly alone. + let mut g: Vec<[f32; 4]> = vec![[0.1, 0.1, 0.1, 1.0], [0.95, 0.95, 0.95, 1.0]]; + develop(&mut g, 2, 1, &cr! { grade_shadows: Wheel { hue: 220.0, sat: 80.0, lum: 0.0 }}, false); + assert!(g[0][2] > g[0][0] + 0.05 && (g[1][2] - g[1][0]).abs() < 0.02, "{g:?}"); + // Point curve + parametric. + let mut c = img(w, h); + develop(&mut c, w, h, &cr! { point_curve: vec![[0.0, 30.0], [255.0, 255.0]], curve_shadows: 50.0}, false); + assert!(c.iter().all(|q| q[1] >= 30.0 / 255.0 - 1e-4)); + // Noise reduction reduces variance; sharpening increases it; grain is deterministic. + let noisy: Vec<[f32; 4]> = (0..w * h) + .map(|i| { + let n = hash01(i as i64, 0, 3) * 0.2; + [0.4 + n, 0.4 + n, 0.4 + n, 1.0] + }) + .collect(); + let var = |a: &[[f32; 4]]| { + let m = mean(a, 1); + a.iter().map(|q| (q[1] - m).powi(2)).sum::() / a.len() as f32 + }; + let mut nr = noisy.clone(); + develop(&mut nr, w, h, &cr! { noise_luminance: 80.0}, false); + assert!(var(&nr) < var(&noisy) * 0.5); + // Out-of-range noise settings are held to their 0..=100 range, not turned into huge radii. + let mut wild = noisy.clone(); + let hostile = cr! { noise_luminance: 1.0e30, noise_color: 1.0e30, noise_luminance_detail: 1.0e30, noise_color_detail: 1.0e30}; + develop(&mut wild, w, h, &hostile, false); + assert!(wild.iter().all(|q| q[0].is_finite())); + let mut sh = noisy.clone(); + develop(&mut sh, w, h, &cr! { sharpen_amount: 100.0}, false); + assert!(var(&sh) > var(&noisy)); + let mut g1 = img(w, h); + let mut g2 = img(w, h); + let gp = cr! { grain_amount: 50.0}; + let seeded = DevelopInputs { seed: 4, ..Default::default() }; + super::develop(&mut g1, w, h, &gp, &seeded, false); + super::develop(&mut g2, w, h, &gp, &seeded, false); + assert_eq!(g1, g2); + assert_ne!(g1, img(w, h)); + // Post-crop vignette darkens corners, leaves the centre. + let flat = vec![[0.5f32, 0.5, 0.5, 1.0]; w * h]; + let mut v = flat.clone(); + develop(&mut v, w, h, &cr! { vignette_amount: -80.0}, false); + assert!(v[0][0] < 0.35 && (v[(h / 2) * w + w / 2][0] - 0.5).abs() < 0.01, "{:?}", v[0]); + } + + #[test] + fn calibration_keeps_the_develop_off_the_per_pixel_gpu_stages() { + // The per-pixel stages (the Camera Raw dialog's GPU preview) don't run Calibration, so + // settings with it must fall back to the CPU develop instead of previewing without it. + for p in [ + cr! { shadow_tint: 40.0}, + cr! { calibration_hue: [0.0, 0.0, 30.0], whites: 20.0}, + cr! { calibration_sat: [-50.0, 0.0, 0.0], exposure: 0.5}, + ] { + assert!(!spatial(&p)); + assert!(per_pixel(&p, 2, 2, false, Some((0.0, 1.0))).is_none(), "{p:?}"); + } + assert!(per_pixel(&cr! { exposure: 0.5}, 2, 2, false, None).is_some()); + } + + #[test] + fn calibration_turns_primaries_keeps_neutrals_and_tints_shadows() { + let w = calibration_weights(0.0); + assert!((w[0] - 1.0).abs() < 1e-6, "pure red is all red primary: {w:?}"); + let w = calibration_weights(60.0); + assert!((w[0] - 0.5).abs() < 1e-6 && (w[1] - 0.5).abs() < 1e-6, "yellow is half red, half green: {w:?}"); + let w = calibration_weights(300.0); + assert!((w[2] - 0.5).abs() < 1e-6 && (w[0] - 0.5).abs() < 1e-6, "magenta wraps round: {w:?}"); + let (none, zero) = ([0.0f32; 3], [0.0f32; 3]); + let grey = calibrate([0.3, 0.3, 0.3], [100.0, -100.0, 50.0], [100.0, -100.0, 100.0]); + assert!(grey.iter().all(|v| (v - 0.3).abs() < 1e-5), "greys are untouched: {grey:?}"); + // Red turned towards green: it gains green, keeps its luminance. + let red = calibrate([0.5, 0.0, 0.0], [100.0, 0.0, 0.0], zero); + assert!(red[1] > 0.05 && (red[1] / red[0] - 0.5).abs() < 0.02 && red[2] < 1e-6, "red turns 30° towards green (orange): {red:?}"); + assert!((luma(red) - luma([0.5, 0.0, 0.0])).abs() < 1e-4, "luminance kept: {red:?}"); + // Blue at saturation −100 is grey; green at −50 is paler. + let blue = calibrate([0.0, 0.0, 0.8], none, [0.0, 0.0, -100.0]); + assert!((blue[0] - blue[1]).abs() < 1e-5 && (blue[1] - blue[2]).abs() < 1e-5, "blue at −100 saturation is grey: {blue:?}"); + let green = calibrate([0.2, 0.8, 0.2], none, [0.0, -50.0, 0.0]); + assert!(green[0] > 0.2 && green[1] < 0.8, "green at −50 is paler: {green:?}"); + // A primary's sliders leave the other primaries alone. + let unchanged = calibrate([0.0, 0.0, 0.8], [100.0, 100.0, 0.0], [100.0, 100.0, 0.0]); + assert!(unchanged.iter().zip([0.0, 0.0, 0.8]).all(|(a, b)| (a - b).abs() < 1e-5), "{unchanged:?}"); + // Shadows tint: magenta lifts red and blue over green in a dark pixel, keeps luminance, + // and leaves white alone. + let dark = shadow_tint([0.02, 0.02, 0.02], 1.0); + assert!(dark[0] > dark[1] && dark[2] > dark[1], "{dark:?}"); + assert!((luma(dark) - 0.02).abs() < 1e-4, "luminance kept: {dark:?}"); + let green = shadow_tint([0.02, 0.02, 0.02], -1.0); + assert!(green[1] > green[0], "{green:?}"); + let white = shadow_tint([1.0, 1.0, 1.0], 1.0); + assert!(white.iter().all(|v| (v - 1.0).abs() < 1e-3), "white is not tinted: {white:?}"); + // Through develop: neutral settings are an identity, a tint changes dark pixels only. + let mut p = CameraRaw::default(); + assert!(p.is_identity()); + p.shadow_tint = 100.0; + assert!(!p.is_identity()); + let mut px = vec![[0.1, 0.1, 0.1, 1.0], [0.95, 0.95, 0.95, 1.0]]; + develop(&mut px, 2, 1, &p, false); + assert!(px[0][0] > px[0][1], "dark grey turns magenta: {:?}", px[0]); + assert!((px[1][0] - px[1][1]).abs() < 0.01, "near-white stays neutral: {:?}", px[1]); + p = CameraRaw::default(); + p.calibration_hue[2] = 100.0; + let mut px = vec![[0.0, 0.0, 0.8, 1.0]]; + develop(&mut px, 1, 1, &p, false); + assert!(px[0][0] > 0.05, "blue turned towards red: {:?}", px[0]); + } + + #[test] + fn auto_tone_brightens_dark_and_darkens_bright_images() { + let mut p = CameraRaw::default(); + auto_tone(&[], &mut p); + assert_eq!(p, CameraRaw::default(), "no pixels: nothing changes"); + let dark: Vec<[f32; 4]> = (0..4096) + .map(|i| { + let v = 0.05 + (i % 64) as f32 / 64.0 * 0.15; + [v, v, v, 1.0] + }) + .collect(); + auto_tone(&dark, &mut p); + assert!(p.exposure > 0.5, "a dark image gets exposure: {}", p.exposure); + assert!(p.shadows > 0.0, "and lifted shadows: {}", p.shadows); + let mut p = CameraRaw::default(); + let bright: Vec<[f32; 4]> = (0..4096) + .map(|i| { + let v = 0.8 + (i % 64) as f32 / 64.0 * 0.19; + [v, v, v, 1.0] + }) + .collect(); + auto_tone(&bright, &mut p); + assert!(p.exposure < -0.5, "a bright image loses exposure: {}", p.exposure); + assert!(p.highlights < 0.0, "and its highlights come down: {}", p.highlights); + let mut p = CameraRaw::default(); + let good: Vec<[f32; 4]> = (0..4096) + .map(|i| { + let v = 0.04 + (i % 64) as f32 / 63.0 * 0.92; + [v, v, v, 1.0] + }) + .collect(); + auto_tone(&good, &mut p); + assert!(p.exposure.abs() < 0.3 && p.blacks.abs() < 10.0 && p.whites.abs() < 10.0, "a full-range image is left nearly alone: {p:?}"); + assert!(p.saturation == 0.0 && hsl_neutral(&p), "other panels untouched"); + } + + #[test] + fn float_documents_keep_overrange() { + let mut a = vec![[2.0f32, 1.5, 0.5, 1.0]; 16]; + develop(&mut a, 4, 4, &cr! { exposure: 0.5}, true); + assert!(a[0][0] > 2.0); + } + + /// A Gaussian narrower than 0.3 px has no box radii, so it returns its input unchanged, and + /// Texture on a proxy that small changes nothing. + #[test] + fn a_gaussian_below_0_3_px_leaves_the_image_alone() { + assert!(spatial::gauss_radii(0.29).is_empty()); + assert!(!spatial::gauss_radii(0.3).is_empty()); + let (w, h) = (64usize, 48usize); + let v: Vec = (0..w * h).map(|i| ((i * 37) % 101) as f32 / 100.0).collect(); + assert_eq!(gauss(&v, w, h, 0.29), v); + assert_eq!(box_means(&v, w, h, &[]), v); + assert_ne!(gauss(&v, w, h, 1.0), v); + let src: Vec<[f32; 4]> = v.iter().map(|&x| [x, 1.0 - x, 0.5 * x, 1.0]).collect(); + let base = cr! { contrast: 10.0}; + let scaled = DevelopInputs { pixel_scale: 0.1, ..Default::default() }; + let (mut plain, mut textured) = (src.clone(), src); + super::develop(&mut plain, w, h, &base, &scaled, false); + super::develop(&mut textured, w, h, &cr! { base => texture: 80.0}, &scaled, false); + assert_eq!(plain, textured); + } +} diff --git a/crates/develop/src/camera_raw/per_pixel.rs b/crates/develop/src/camera_raw/per_pixel.rs new file mode 100644 index 0000000000..9273036bce --- /dev/null +++ b/crates/develop/src/camera_raw/per_pixel.rs @@ -0,0 +1,284 @@ +//! Develop's stages resolved for one image: every constant and table the per-pixel ones use, so +//! another implementation of them (the GPU preview, `photocraft_gpu::CameraRawDevelop`) runs the +//! same maths. [`develop`](super::develop) builds its own constants with the same functions. +//! The spatial stages other than Detail come as their parameters: Dehaze, Clarity and Texture +//! (see [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`]. + +use super::local_tone::{LocalTone, WORK_SIDE}; +use super::spatial::{Clarity, Dehaze, Texture}; +use super::types::VignetteStyle as StoredStyle; +use super::{ + CameraRaw, DevelopInputs, Encoding, Wheel, calibration_neutral, curve_lut, grade_neutral, hsl_neutral, hsv_to_rgb, is_linear, luma, + parametric_lut, white_balance_gains, whites_blacks, +}; + +pub use whites_blacks::Model as WhitesBlacksModel; + +/// Entries of the tone curve tables (parametric and point curves). +pub const CURVE_LUT: usize = 1024; +/// Samples of a Whites or Blacks curve row: grey levels 0, 1/32, …, 1. +pub const WB_STEPS: usize = whites_blacks::STEPS; + +/// White balance and exposure: channel gains in linear light, when the stage is on. +pub(crate) fn gains(p: &CameraRaw) -> Option<[f32; 3]> { + if p.temperature == 0.0 && p.tint == 0.0 && p.exposure == 0.0 { + return None; + } + let g = white_balance_gains(p.temperature, p.tint); + let norm = luma(g); + Some(g.map(|v| v / norm * 2f32.powf(p.exposure))) +} + +/// Contrast's strength, when Contrast is set (with or without Texture and Clarity). +fn contrast(p: &CameraRaw) -> Option { + (p.contrast != 0.0).then_some(p.contrast / 100.0 * 0.6) +} + +/// Whites and Blacks' tables, for an implementation that measures the image's points itself. +pub fn whites_blacks_model() -> WhitesBlacksModel { + whites_blacks::model() +} + +/// Whites and Blacks as two curve rows for the image's amounts. +#[derive(Clone, Debug, PartialEq)] +pub struct WhitesBlacks { + /// The Whites curve over grey levels 0, 1/32, …, 1, when Whites is set. + pub whites: Option<[f32; WB_STEPS]>, + /// The Blacks curve, applied after Whites. + pub blacks: Option<[f32; WB_STEPS]>, + /// The clipping directions (Whites up, Blacks down) curve each channel; the others scale the + /// pixel by the change of its luminance. + pub per_channel: bool, +} + +/// Color Grading's wheels resolved. +#[derive(Clone, Debug, PartialEq)] +pub struct Grade { + /// Colour offsets of the shadows, midtones, highlights and global wheels. + pub tints: [[f32; 3]; 4], + /// Luminance of the same wheels (slider units). + pub lums: [f32; 4], + pub blend: f32, + pub balance: f32, +} + +impl Grade { + pub(crate) fn new(p: &CameraRaw) -> Self { + let tint = |wh: &Wheel| -> [f32; 3] { + let c = hsv_to_rgb(wh.hue, 1.0, 1.0); + let l = luma(c); + [c[0] - l, c[1] - l, c[2] - l].map(|v| v * wh.sat / 100.0 * 0.3) + }; + Grade { + tints: [tint(&p.grade_shadows), tint(&p.grade_midtones), tint(&p.grade_highlights), tint(&p.grade_global)], + lums: [p.grade_shadows.lum, p.grade_midtones.lum, p.grade_highlights.lum, p.grade_global.lum], + blend: 0.15 + p.grade_blending.clamp(0.0, 100.0) / 100.0 * 0.35, + balance: p.grade_balance.clamp(-100.0, 100.0) / 100.0 * 0.25, + } + } +} + +/// The vignette's `vignette_style`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum VignetteStyle { + HighlightPriority, + ColorPriority, + PaintOverlay, +} + +/// The post-crop vignette's shape on a `w × h` frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Vignette { + /// −1 … 1. + pub amount: f32, + /// 0 … 1. + pub highlights: f32, + pub style: VignetteStyle, + /// Frame centre (pixels). + pub centre: [f32; 2], + /// Half axes of the shape (pixels). + pub axes: [f32; 2], + /// Exponent of the superellipse. + pub power: f32, + /// The mask's smoothstep edges in normalised radius. + pub edges: [f32; 2], +} + +impl Vignette { + pub(crate) fn new(w: usize, h: usize, p: &CameraRaw) -> Self { + let mid = p.vignette_midpoint.clamp(0.0, 100.0) / 100.0; + let feather = p.vignette_feather.clamp(0.0, 100.0) / 100.0; + let round = p.vignette_roundness.clamp(-100.0, 100.0) / 100.0; + let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0); + // Roundness: 0 follows the frame's aspect, +1 a circle, −1 a rounded rectangle. + let (ax, ay) = if round >= 0.0 { + let r = cx.min(cy) + (cx.max(cy) - cx.min(cy)) * (1.0 - round); + (if cx >= cy { r } else { cx }, if cy > cx { r } else { cy }) + } else { + (cx, cy) + }; + let inner = 1.0 - mid * 0.8; + Vignette { + amount: p.vignette_amount / 100.0, + highlights: p.vignette_highlights.clamp(0.0, 100.0) / 100.0, + style: match p.vignette_style { + StoredStyle::PaintOverlay => VignetteStyle::PaintOverlay, + StoredStyle::ColorPriority => VignetteStyle::ColorPriority, + _ => VignetteStyle::HighlightPriority, + }, + centre: [cx, cy], + axes: [ax, ay], + power: 2.0 + (-round).max(0.0) * 6.0, + edges: [inner - feather * 0.5 * inner, inner + feather * 0.5 * (1.4 - inner) + 0.02], + } + } +} + +/// Grain: value noise sampled in full-resolution coordinates. +#[derive(Clone, Debug, PartialEq)] +pub struct Grain { + /// Noise cell size (full-resolution pixels). + pub cell: f32, + /// Weight of the finer octave. + pub roughness: f32, + pub amount: f32, + pub seed: u64, + /// Full-resolution pixels per pixel (`1 / pixel_scale`). + pub scale: f32, +} + +impl Grain { + pub(crate) fn new(p: &CameraRaw, inputs: &DevelopInputs) -> Self { + Grain { + cell: 1.0 + p.grain_size / 25.0, + roughness: p.grain_roughness / 100.0, + amount: p.grain_amount / 100.0 * 0.12, + seed: u64::from(inputs.seed), + scale: 1.0 / inputs.pixel_scale.clamp(0.01, 1.0), + } + } +} + +/// Develop's per-pixel stages for one image and settings, in order. `None` stages are off. +#[derive(Clone, Debug, PartialEq)] +pub struct PerPixel { + /// 1. White balance and exposure gains in linear light (sRGB-decoded values). + pub gains: Option<[f32; 3]>, + /// 2. Dehaze. + pub dehaze: Option, + /// 3. Shadows and Highlights: a local Laplacian filter of the whole frame, then each pixel's + /// light scaled by the change of its log luminance. + pub local_tone: Option, + /// 3. Clarity and Texture on the luminance clipped to 1, before Contrast. + pub clarity: Option, + pub texture: Option, + /// 3. Contrast's strength. + pub contrast: Option, + /// 3b. Whites and Blacks, in the document's encoding. + pub whites_blacks: Option, + /// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when a + /// spatial stage is set: the points then depend on its output, so whatever runs it + /// measures them and picks the curves from [`whites_blacks_model`]. `whites_blacks` is + /// then `None`. + pub measure_whites_blacks: Option<[f32; 2]>, + /// The document's transfer curve: 0 for sRGB's, else a power-law gamma. + pub encoding: f32, + /// 4. Vibrance and Saturation (slider / 100). + pub presence: Option<[f32; 2]>, + /// 5. The parametric tone curve, [`CURVE_LUT`] entries over 0 … 1. + pub parametric: Option>, + /// 5. Point curves: master, red, green, blue. + pub point: [Option>; 4], + /// 6. Color Mixer hue, saturation and luminance per band. + pub hsl: Option<[[f32; 8]; 3]>, + /// 7. Color Grading. + pub grade: Option, + /// 9. Vignette. + pub vignette: Option, + /// 9. Grain. + pub grain: Option, + /// Clip RGB to 0 … 1 at the end (all but 32-bit documents). + pub clamp: bool, +} + +/// Whether developing needs a stage that reads neighbouring pixels: Dehaze, Shadows and +/// Highlights, Texture, Clarity, sharpening or noise reduction. +pub fn spatial(p: &CameraRaw) -> bool { + p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) || detail_on(p) +} + +/// Whether developing needs Detail: sharpening or noise reduction. +fn detail_on(p: &CameraRaw) -> bool { + p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0 +} + +/// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`, +/// display-encoded) developed per pixel with `p`: what [`develop`](super::develop) measures +/// after white balance and Contrast. `None` when Whites and Blacks are 0 or `p` needs a +/// spatial stage. +pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> { + if (p.whites == 0.0 && p.blacks == 0.0) || spatial(p) || px.len() != w.saturating_mul(h) { + return None; + } + let enc = Encoding::of(inputs.encoding_gamma); + let (g, k_con) = (gains(p), contrast(p)); + Some(super::luminance_points(px, w, h, enc, |q| { + let q = g.map_or(q, |g| super::balance(q, g)); + k_con.map_or(q, |k| super::contrast(q, k)) + })) +} + +/// Develop's stages for settings without Detail or Calibration, on a `w × h` image; `points` are +/// the image's [`white_black_points`]. `None` when `p` needs Detail or Calibration (these stages +/// run neither), Shadows or Highlights on a frame wider than the filter's working copy (the +/// develop then filters a reduced copy) or only 2 pixels on its short side, or Whites or Blacks +/// without a spatial stage and without `points`. The points themselves leave Calibration out, so a +/// caller may cache them across Calibration changes. +pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { + if detail_on(p) || !calibration_neutral(p) { + return None; + } + // The develop leaves frames under 2 pixels on a side alone. + let local_tone = if w >= 2 && h >= 2 { LocalTone::new(p.shadows, p.highlights) } else { None }; + // At 2 pixels on the short side the GPU pass's pyramid has one level, so the CPU develops it. + if local_tone.is_some() && (w.max(h) > WORK_SIDE || w.min(h) <= 2) { + return None; + } + let (dehaze, clarity, texture) = (Dehaze::new(p, w, h), Clarity::new(p, w, h), Texture::new(p, inputs, w, h)); + let spatial = local_tone.is_some() || dehaze.is_some() || clarity.is_some() || texture.is_some(); + let identity = p.is_identity(); + let wb_on = p.whites != 0.0 || p.blacks != 0.0; + let measure_whites_blacks = (wb_on && spatial).then(|| [p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0)]); + let whites_blacks = if wb_on && measure_whites_blacks.is_none() { + let (bp, wp) = points?; + let (xw, xb) = whites_blacks::amounts(p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0), bp, wp); + (xw != 0.0 || xb != 0.0).then(|| WhitesBlacks { + whites: (xw != 0.0).then(|| whites_blacks::whites_row(xw)), + blacks: (xb != 0.0).then(|| whites_blacks::blacks_row(xb)), + per_channel: xw > 0.0 || xb < 0.0, + }) + } else { + None + }; + let parametric_on = !(p.curve_highlights == 0.0 && p.curve_lights == 0.0 && p.curve_darks == 0.0 && p.curve_shadows == 0.0); + let pts = |c: &Vec<[f32; 2]>| (!is_linear(c)).then(|| curve_lut(c, CURVE_LUT)); + Some(PerPixel { + gains: gains(p), + dehaze, + local_tone, + clarity, + texture, + contrast: contrast(p), + whites_blacks, + measure_whites_blacks, + encoding: Encoding::of(inputs.encoding_gamma).0, + presence: (p.vibrance != 0.0 || p.saturation != 0.0).then_some([p.vibrance / 100.0, p.saturation / 100.0]), + parametric: parametric_on.then(|| parametric_lut(p, CURVE_LUT)), + point: [pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)], + hsl: (!hsl_neutral(p)).then_some([p.hsl_hue, p.hsl_sat, p.hsl_lum]), + grade: (!grade_neutral(p)).then(|| Grade::new(p)), + vignette: (p.vignette_amount != 0.0).then(|| Vignette::new(w, h, p)), + grain: (p.grain_amount > 0.0).then(|| Grain::new(p, inputs)), + clamp: !float && !identity, + }) +} diff --git a/crates/develop/src/camera_raw/spatial.rs b/crates/develop/src/camera_raw/spatial.rs new file mode 100644 index 0000000000..a7b17347f0 --- /dev/null +++ b/crates/develop/src/camera_raw/spatial.rs @@ -0,0 +1,202 @@ +#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] + +//! Dehaze, Clarity and Texture resolved for one frame: the sizes, radii and constants their +//! filters use, so another implementation of them (the GPU preview, +//! `photocraft_gpu::CameraRawDevelop`) runs the same filters. [`develop`](super::develop) builds +//! its own from the same constructors. +//! +//! - **Dehaze** follows the dark channel prior (K. He, J. Sun, X. Tang, *Single Image Haze Removal +//! Using Dark Channel Prior*, CVPR 2009) on a box-averaged copy at most [`DEHAZE_SIDE`] pixels +//! across, with the transmission refined by a guided filter (K. He, J. Sun, X. Tang, *Guided +//! Image Filtering*, ECCV 2010) and brought back to full size bilinearly. +//! - **Clarity** raises the luminance's difference from a fast guided filter of itself (K. He, +//! J. Sun, *Fast Guided Filter*, arXiv 2015), weighted toward the midtones. +//! - **Texture** raises its difference from a Gaussian blur (three box passes), limited to +//! ±[`TEXTURE_LIMIT`]. + +use super::{CameraRaw, DevelopInputs}; + +/// Dehaze measures the haze on a copy at most this many pixels across. +pub const DEHAZE_SIDE: usize = 768; +/// The dark channel's minimum filter has a radius of the copy's long side over this, at least +/// [`DEHAZE_MIN_RADIUS`]. +pub const DEHAZE_RADIUS_DIVISOR: usize = 60; +/// See [`DEHAZE_RADIUS_DIVISOR`]. +pub const DEHAZE_MIN_RADIUS: usize = 2; +/// The atmospheric light is the mean colour of the brightest 1 / this of the dark channel (at +/// least one cell). +pub const DEHAZE_AIR_FRACTION: usize = 1000; +/// Each channel of the atmospheric light is at least this. +pub const DEHAZE_AIR_FLOOR: f32 = 0.2; +/// The share of the haze the raw transmission removes (the paper's ω). +pub const DEHAZE_OMEGA: f32 = 0.95; +/// The guided filter's regularisation for the transmission. +pub const DEHAZE_EPS: f32 = 1e-3; +/// The transmission is at least this. +pub const DEHAZE_T_FLOOR: f32 = 0.1; +/// Clarity's guided filter regularisation. +pub const CLARITY_EPS: f32 = 0.005; +/// Texture moves the luminance by at most this. +pub const TEXTURE_LIMIT: f32 = 0.1; + +/// Dehaze on a `w × h` frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Dehaze { + /// The slider / 100 (−1 … 1). + pub amount: f32, + /// The copy averages `factor × factor` blocks. + pub factor: usize, + /// The copy's size. + pub size: [usize; 2], + /// The minimum filter's radius. + pub radius: usize, + /// The guided filter's radius. + pub guide_radius: usize, + /// How many of the copy's cells the atmospheric light averages. + pub top: usize, +} + +impl Dehaze { + /// Dehaze for `p` on a `w × h` frame; `None` when it is off. + pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option { + if p.dehaze == 0.0 { + return None; + } + let factor = w.max(h).div_ceil(DEHAZE_SIDE).max(1); + let size = [w.div_ceil(factor), h.div_ceil(factor)]; + let radius = (size[0].max(size[1]) / DEHAZE_RADIUS_DIVISOR).max(DEHAZE_MIN_RADIUS); + Some(Dehaze { + amount: p.dehaze / 100.0, + factor, + size, + radius, + guide_radius: radius * 2, + top: (size[0] * size[1] / DEHAZE_AIR_FRACTION).max(1), + }) + } + + /// The copy the haze is measured on, for `px` (`w × h`, display-encoded) before white balance + /// and exposure (`gains`, as in [`PerPixel`](super::PerPixel)): `size` cells in rows, each the + /// mean light of its block, clipped to 0 … 1. These are exactly the cells + /// [`develop`](super::develop) uses: the brightest of them set the atmospheric light, and a + /// tie between them decides which, so another implementation that computes stage 1 to a few + /// ulps should start from these. Empty when `px` isn't `w × h`. + pub fn cells(&self, px: &[[f32; 4]], w: usize, h: usize, gains: Option<[f32; 3]>) -> Vec<[f32; 3]> { + if px.len() != w.saturating_mul(h) || w.div_ceil(self.factor) != self.size[0] || h.div_ceil(self.factor) != self.size[1] { + return Vec::new(); + } + super::haze_cells(px, w, h, self, |q| gains.map_or(q, |g| super::balance(q, g))) + } +} + +/// Clarity on a `w × h` frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Clarity { + /// The strength: the slider / 100 × 0.8. + pub amount: f32, + /// The guided filter's radius at full size. + pub radius: usize, + /// The fast guided filter works on `subsample × subsample` block means… + pub subsample: usize, + /// …with this radius… + pub sub_radius: usize, + /// …at this size. + pub sub_size: [usize; 2], +} + +impl Clarity { + /// Clarity for `p` on a `w × h` frame; `None` when it is off. + pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option { + if p.clarity == 0.0 { + return None; + } + let radius = ((w.max(h) as f32 * 0.02) as usize).max(3); + let (subsample, sub_radius) = fast_guided_steps(radius); + Some(Clarity { amount: p.clarity / 100.0 * 0.8, radius, subsample, sub_radius, sub_size: [w.div_ceil(subsample), h.div_ceil(subsample)] }) + } +} + +/// The fast guided filter's subsampling and its radius there, for radius `r` at full size. A +/// subsampling of 1 is the plain guided filter at radius `r`. +pub fn fast_guided_steps(r: usize) -> (usize, usize) { + let s = (r / 8).clamp(1, 8); + (s, if s == 1 { r } else { (r / s).max(1) }) +} + +/// Texture on a `w × h` frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Texture { + /// The strength: the slider / 100 × 0.9. + pub amount: f32, + /// The blur's box radii, in order; empty when the blur is too small to change anything. + pub radii: Vec, +} + +impl Texture { + /// Texture for `p` on a `w × h` frame; `None` when it is off. + pub fn new(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize) -> Option { + if p.texture == 0.0 { + return None; + } + let ps = inputs.pixel_scale.clamp(0.01, 1.0); + let sigma = (w.max(h) as f32 * 0.002).max(1.5 * ps); + Some(Texture { amount: p.texture / 100.0 * 0.9, radii: gauss_radii(sigma) }) + } +} + +/// The box radii of develop's Gaussian of `sigma`: none below 0.3. +pub(crate) fn gauss_radii(sigma: f32) -> Vec { + if sigma < 0.3 { + return Vec::new(); + } + super::util::gauss_box_radii(sigma).to_vec() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `CameraRaw` with the named fields set (the type is `#[non_exhaustive]`, so no struct expression), or a copy of a base with them set. + macro_rules! cr { + ($($f:ident : $v:expr),* $(,)?) => {{ + let mut s = CameraRaw::default(); + $(s.$f = $v;)* + s + }}; + ($base:expr => $($f:ident : $v:expr),* $(,)?) => {{ + let mut s: CameraRaw = $base; + $(s.$f = $v;)* + s + }}; + } + + #[test] + fn stages_resolve_for_the_dialogs_proxy_and_are_off_at_zero() { + let p = cr! { dehaze: 40.0, clarity: -50.0, texture: 50.0}; + let scale = |pixel_scale| DevelopInputs { pixel_scale, ..Default::default() }; + let d = Dehaze::new(&p, 858, 572).unwrap(); + assert_eq!((d.factor, d.size, d.radius, d.guide_radius, d.top), (2, [429, 286], 7, 14, 122)); + let c = Clarity::new(&p, 858, 572).unwrap(); + assert_eq!((c.radius, c.subsample, c.sub_radius, c.sub_size), (17, 2, 8, [429, 286])); + assert!((c.amount + 0.4).abs() < 1e-6); + assert_eq!(Texture::new(&p, &scale(0.143), 858, 572).unwrap().radii, [1, 1, 2]); + // Small frames: the plain guided filter, a blur too narrow to change anything. + assert_eq!(fast_guided_steps(3), (1, 3)); + assert!(Texture::new(&cr! { texture: 10.0}, &scale(0.1), 64, 48).unwrap().radii.is_empty()); + let off = CameraRaw::default(); + assert!( + Dehaze::new(&off, 858, 572).is_none() && Clarity::new(&off, 858, 572).is_none() && Texture::new(&off, &scale(1.0), 858, 572).is_none() + ); + } + + #[test] + fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() { + let d = Dehaze::new(&cr! { dehaze: 10.0}, 3, 1).unwrap(); + let px = [[0.2, 0.4, 1.5, 1.0], [0.4, 0.0, 0.5, 1.0], [0.9, 0.9, 0.9, 1.0]]; + assert_eq!(d.cells(&px, 3, 1, None), vec![[0.2, 0.4, 1.0], [0.4, 0.0, 0.5], [0.9, 0.9, 0.9]]); + let brighter = d.cells(&px, 3, 1, Some([2.0, 2.0, 2.0])); + assert!(brighter[0][0] > 0.2 && brighter[2] == [1.0; 3]); + assert!(d.cells(&px[..2], 3, 1, None).is_empty()); + assert!(d.cells(&px, 1, 3, None).is_empty()); + } +} diff --git a/crates/develop/src/camera_raw/types.rs b/crates/develop/src/camera_raw/types.rs new file mode 100644 index 0000000000..39eaec9e66 --- /dev/null +++ b/crates/develop/src/camera_raw/types.rs @@ -0,0 +1,252 @@ +//! Camera Raw filter settings model (`CameraRaw` / `RawDevelopSettings`), matching PhotoCraft's +//! stored `.pcraft` / Smart Filter schema. + +use serde::{Deserialize, Serialize}; + +/// One colour grading wheel. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct GradeWheel { + /// Degrees 0..360. + pub hue: f32, + /// 0..=100. + pub sat: f32, + /// -100..=100. + pub lum: f32, +} + +/// What the vignette protects. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum VignetteStyle { + /// Colour priority. + ColorPriority, + /// Paint overlay. + PaintOverlay, + /// Highlight priority; a stored name outside the three reads as this one (serde's fallback is the last variant). + #[default] + #[serde(other)] + HighlightPriority, +} + +/// Most points a point curve accepts from commands and the control channel. +pub const MAX_CURVE_POINTS: usize = 16; + +/// The settings the Camera Raw filter reads: the field set and serde names of PhotoCraft's +/// `CameraRaw`, without its three develop inputs (`seed`, `pixel_scale`, `encoding_gamma`). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +#[non_exhaustive] +pub struct RawDevelopSettings { + pub temperature: f32, + pub tint: f32, + pub exposure: f32, + pub contrast: f32, + pub highlights: f32, + pub shadows: f32, + pub whites: f32, + pub blacks: f32, + pub texture: f32, + pub clarity: f32, + pub dehaze: f32, + pub vibrance: f32, + pub saturation: f32, + pub curve_highlights: f32, + pub curve_lights: f32, + pub curve_darks: f32, + pub curve_shadows: f32, + pub curve_splits: [f32; 3], + pub point_curve: Vec<[f32; 2]>, + pub point_curve_red: Vec<[f32; 2]>, + pub point_curve_green: Vec<[f32; 2]>, + pub point_curve_blue: Vec<[f32; 2]>, + pub hsl_hue: [f32; 8], + pub hsl_sat: [f32; 8], + pub hsl_lum: [f32; 8], + pub grade_shadows: GradeWheel, + pub grade_midtones: GradeWheel, + pub grade_highlights: GradeWheel, + pub grade_global: GradeWheel, + pub grade_blending: f32, + pub grade_balance: f32, + pub sharpen_amount: f32, + pub sharpen_radius: f32, + pub sharpen_detail: f32, + pub sharpen_masking: f32, + pub noise_luminance: f32, + pub noise_luminance_detail: f32, + pub noise_color: f32, + pub noise_color_detail: f32, + pub grain_amount: f32, + pub grain_size: f32, + pub grain_roughness: f32, + pub vignette_amount: f32, + pub vignette_midpoint: f32, + pub vignette_roundness: f32, + pub vignette_feather: f32, + pub vignette_highlights: f32, + pub vignette_style: VignetteStyle, + pub shadow_tint: f32, + pub calibration_hue: [f32; 3], + pub calibration_sat: [f32; 3], +} + +impl Default for RawDevelopSettings { + fn default() -> Self { + RawDevelopSettings { + temperature: 0.0, + tint: 0.0, + exposure: 0.0, + contrast: 0.0, + highlights: 0.0, + shadows: 0.0, + whites: 0.0, + blacks: 0.0, + texture: 0.0, + clarity: 0.0, + dehaze: 0.0, + vibrance: 0.0, + saturation: 0.0, + curve_highlights: 0.0, + curve_lights: 0.0, + curve_darks: 0.0, + curve_shadows: 0.0, + curve_splits: [25.0, 50.0, 75.0], + point_curve: Vec::new(), + point_curve_red: Vec::new(), + point_curve_green: Vec::new(), + point_curve_blue: Vec::new(), + hsl_hue: [0.0; 8], + hsl_sat: [0.0; 8], + hsl_lum: [0.0; 8], + grade_shadows: GradeWheel::default(), + grade_midtones: GradeWheel::default(), + grade_highlights: GradeWheel::default(), + grade_global: GradeWheel::default(), + grade_blending: 50.0, + grade_balance: 0.0, + sharpen_amount: 0.0, + sharpen_radius: 1.0, + sharpen_detail: 25.0, + sharpen_masking: 0.0, + noise_luminance: 0.0, + noise_luminance_detail: 50.0, + noise_color: 0.0, + noise_color_detail: 50.0, + grain_amount: 0.0, + grain_size: 25.0, + grain_roughness: 50.0, + vignette_amount: 0.0, + vignette_midpoint: 50.0, + vignette_roundness: 0.0, + vignette_feather: 50.0, + vignette_highlights: 0.0, + vignette_style: VignetteStyle::HighlightPriority, + shadow_tint: 0.0, + calibration_hue: [0.0; 3], + calibration_sat: [0.0; 3], + } + } +} + +/// Checks a point curve from untrusted input: empty (linear) or 2..=16 finite points in 0..=255 +/// with inputs increasing by at least one level. +pub fn validate_curve(points: &[[f32; 2]]) -> Result<(), String> { + if points.len() == 1 { + return Err("a nonempty curve needs at least two points".into()); + } + if points.len() > MAX_CURVE_POINTS { + return Err(format!("at most {MAX_CURVE_POINTS} curve points")); + } + if !points.iter().flatten().all(|v| v.is_finite() && (0.0..=255.0).contains(v)) { + return Err("curve coordinates must be finite and in 0..=255".into()); + } + if points.windows(2).any(|w| w[1][0] - w[0][0] < 1.0) { + return Err("curve inputs must increase by at least one level".into()); + } + Ok(()) +} + +impl GradeWheel { + fn neutral(&self) -> bool { + self.sat == 0.0 && self.lum == 0.0 + } +} + +fn is_linear(curve: &[[f32; 2]]) -> bool { + curve.len() < 2 || curve.iter().all(|p| (p[0] - p[1]).abs() < 1e-3) +} + +impl RawDevelopSettings { + /// Refuses malformed point curves, naming the first bad one. + pub fn validate(&self) -> Result<(), String> { + for (name, curve) in [ + ("pointCurve", &self.point_curve), + ("pointCurveRed", &self.point_curve_red), + ("pointCurveGreen", &self.point_curve_green), + ("pointCurveBlue", &self.point_curve_blue), + ] { + validate_curve(curve).map_err(|e| format!("{name}: {e}"))?; + } + Ok(()) + } + + /// [`validate`](Self::validate) for an edit of `stored` settings: a curve left as stored is + /// accepted, so editing another control of an older Smart Filter still works. + pub fn validate_changes(&self, stored: &Self) -> Result<(), String> { + for (name, curve, kept) in [ + ("pointCurve", &self.point_curve, &stored.point_curve), + ("pointCurveRed", &self.point_curve_red, &stored.point_curve_red), + ("pointCurveGreen", &self.point_curve_green, &stored.point_curve_green), + ("pointCurveBlue", &self.point_curve_blue, &stored.point_curve_blue), + ] { + if curve != kept { + validate_curve(curve).map_err(|e| format!("{name}: {e}"))?; + } + } + Ok(()) + } + + fn wb_neutral(&self) -> bool { + self.temperature == 0.0 && self.tint == 0.0 && self.exposure == 0.0 + } + + fn tone_neutral(&self) -> bool { + [self.contrast, self.highlights, self.shadows, self.texture, self.clarity, self.whites, self.blacks].iter().all(|v| *v == 0.0) + } + + fn hsl_neutral(&self) -> bool { + self.hsl_hue.iter().chain(&self.hsl_sat).chain(&self.hsl_lum).all(|v| *v == 0.0) + } + + fn grade_neutral(&self) -> bool { + self.grade_shadows.neutral() && self.grade_midtones.neutral() && self.grade_highlights.neutral() && self.grade_global.neutral() + } + + fn calibration_neutral(&self) -> bool { + self.shadow_tint == 0.0 && self.calibration_hue.iter().chain(&self.calibration_sat).all(|v| *v == 0.0) + } + + fn curves_neutral(&self) -> bool { + [self.curve_highlights, self.curve_lights, self.curve_darks, self.curve_shadows].iter().all(|v| *v == 0.0) + && [&self.point_curve, &self.point_curve_red, &self.point_curve_green, &self.point_curve_blue].iter().all(|c| is_linear(c)) + } + + /// Whether every control is neutral, so the settings leave the picture as it is. + pub fn is_identity(&self) -> bool { + self.wb_neutral() + && self.calibration_neutral() + && self.tone_neutral() + && self.dehaze == 0.0 + && self.vibrance == 0.0 + && self.saturation == 0.0 + && self.curves_neutral() + && self.hsl_neutral() + && self.grade_neutral() + && self.sharpen_amount == 0.0 + && self.noise_luminance == 0.0 + && self.noise_color == 0.0 + && self.grain_amount == 0.0 + && self.vignette_amount == 0.0 + } +} diff --git a/crates/develop/src/camera_raw/util.rs b/crates/develop/src/camera_raw/util.rs new file mode 100644 index 0000000000..3b93353009 --- /dev/null +++ b/crates/develop/src/camera_raw/util.rs @@ -0,0 +1,66 @@ +//! Parallel row/map helpers, sRGB transfer, bilinear sampling, hash, and box-blur radii +//! matching PhotoCraft's `photo_util` and `fxutil::gauss_box_radii` bit-for-bit. + +pub(crate) use craft_color::{linear_to_srgb, srgb_to_linear}; + +/// Applies `f(y, row)` to each `w * ch`-wide row (in parallel on native targets). +pub(crate) fn par_rows(buf: &mut [T], w: usize, ch: usize, f: impl Fn(usize, &mut [T]) + Sync + Send) { + let stride = (w * ch).max(1); + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + buf.par_chunks_mut(stride).enumerate().for_each(|(y, row)| f(y, row)); + } + #[cfg(target_arch = "wasm32")] + buf.chunks_mut(stride).enumerate().for_each(|(y, row)| f(y, row)); +} + +/// Maps `f` over `0..n` (in parallel on native targets), keeping order. +pub(crate) fn par_map(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + (0..n).into_par_iter().map(f).collect() + } + #[cfg(target_arch = "wasm32")] + (0..n).map(f).collect() +} + +pub(crate) fn hash01(x: i64, y: i64, seed: u64) -> f32 { + let mut z = + (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F) ^ seed.wrapping_mul(0x1656_67B1_9E37_79F9); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^= z >> 31; + (z >> 40) as f32 / (1u64 << 24) as f32 +} + +/// Bilinear sample of channel `c` of a `w × h × ch` buffer, clamped to the edges. +pub(crate) fn bilinear(buf: &[f32], w: usize, h: usize, ch: usize, c: usize, x: f32, y: f32) -> f32 { + let x = x.clamp(0.0, (w - 1) as f32); + let y = y.clamp(0.0, (h - 1) as f32); + let (x0, y0) = (x.floor() as usize, y.floor() as usize); + let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1)); + let (tx, ty) = (x - x0 as f32, y - y0 as f32); + let p = |xx: usize, yy: usize| buf[(yy * w + xx) * ch + c]; + let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx; + let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx; + top + (bot - top) * ty +} + +pub(crate) fn gauss_box_radii(sigma: f32) -> [usize; 3] { + let n = 3.0f32; + let w_ideal = (12.0 * sigma * sigma / n + 1.0).sqrt(); + let mut wl = w_ideal.floor() as i32; + if wl % 2 == 0 { + wl -= 1; + } + let wl = wl.max(1); + let wu = wl + 2; + let m = ((12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0)).round().clamp(0.0, n) as usize; + let mut radii = std::array::from_fn(|i| if i < m { (wl as usize - 1) / 2 } else { (wu as usize - 1) / 2 }); + if radii.iter().all(|&r| r == 0) { + radii[0] = 1; + } + radii +} diff --git a/crates/develop/src/camera_raw/whites_blacks.rs b/crates/develop/src/camera_raw/whites_blacks.rs new file mode 100644 index 0000000000..d39a60d777 --- /dev/null +++ b/crates/develop/src/camera_raw/whites_blacks.rs @@ -0,0 +1,494 @@ +//! Whites and Blacks as Adobe Camera Raw (process version 2012) applies them. +//! +//! Measured as a black box on the Camera Raw Filter of Photoshop 25.4: grey blocks with chosen +//! histograms went through the filter by script and came back exactly; no Adobe code or data +//! was used. +//! +//! - Both are global curves of the grey level, applied after Shadows and Highlights, Whites +//! first. On an image whose darkest and lightest percent reach black and white the curve of a +//! slider value `x` is the measured row at `x` of [`WHITES`] or [`BLACKS`]. +//! - The direction that only compresses (Whites down, Blacks up) is that fixed curve on every +//! image. The direction that clips (Whites up, Blacks down) adapts: the row used is +//! `x · A(BP, WP)`. On the block images BP and WP are their darkest and lightest levels; on +//! photographs Photoshop's amounts follow best with BP the 3rd percentile of the luminance and +//! WP the 99.5th of the brightest channel, and Blacks at least 1.2 times. A low +//! white point makes Whites +100 stronger (up to 2.7 times), a raised black point Blacks +//! (up to 1.45 times at −40). Whites rows past +100 come from images where `A > 1`. +//! - Not reproduced: past −40 Photoshop's Blacks grows faster on images with a raised black +//! point (on one spanning 0.6–1 its −100 blacks out everything below 0.74, here below about +//! 0.15); its curves there are not rows of the full-range family. +//! - Colour: the clipping directions act on each channel, the compressing ones scale the pixel +//! by the curve's change of its luminance (closest to Photoshop on saturated colours). + +use super::Encoding; +use super::util::par_rows; + +/// Grey levels the curves are sampled at: 0, 1/32, …, 1 (sRGB-encoded). +pub(crate) const STEPS: usize = 33; +/// The first row's internal amount; rows are [`ROW_STEP`] apart. +const WHITES_FROM: f32 = -100.0; +const BLACKS_FROM: f32 = -100.0; +const ROW_STEP: f32 = 10.0; +/// The image's points are measured on cells of a copy at most this many pixels across. +pub(crate) const POINTS_SIDE: usize = 256; +/// The black point's quantile of the cells' luminance, the white point's of their brightest +/// channel. +pub(crate) const POINT_QUANTILES: [f32; 2] = [0.03, 0.995]; +/// Internal amounts the sliders reach: Whites, then Blacks. +const WHITES_RANGE: [f32; 2] = [-100.0, 270.0]; +const BLACKS_RANGE: [f32; 2] = [-100.0, 100.0]; + +/// Whites and Blacks' tables and how an image's points choose from them, for another +/// implementation (the GPU preview measures the points after Shadows and Highlights itself). +#[derive(Clone, Copy, Debug)] +pub struct Model { + /// Whites curves over grey levels 0, 1/32, …, 1, at internal amounts `whites_from`, + /// `whites_from + row_step`, …. + pub whites: &'static [[f32; STEPS]], + pub whites_from: f32, + /// Blacks curves, likewise. + pub blacks: &'static [[f32; STEPS]], + pub blacks_from: f32, + pub row_step: f32, + /// Black points and white points of the adaptation tables' rows and columns. + pub black_points: &'static [f32], + pub white_points: &'static [f32], + /// How much the clipping directions adapt (Whites up, Blacks down), by black and white point. + pub whites_adapt: &'static [[f32; 8]; 9], + pub blacks_adapt: &'static [[f32; 8]; 9], + /// The least Blacks adaptation on photographs. + pub photo_blacks: f32, + /// Internal amounts the Whites and Blacks sliders reach. + pub whites_range: [f32; 2], + pub blacks_range: [f32; 2], + /// See `POINTS_SIDE` and `POINT_QUANTILES`. + pub points_side: usize, + pub point_quantiles: [f32; 2], +} + +/// The tables [`amounts`], [`whites_row`] and [`blacks_row`] read. +pub(crate) fn model() -> Model { + Model { + whites: &WHITES, + whites_from: WHITES_FROM, + blacks: &BLACKS, + blacks_from: BLACKS_FROM, + row_step: ROW_STEP, + black_points: &BPS, + white_points: &WPS, + whites_adapt: &AW, + blacks_adapt: &AB, + photo_blacks: PHOTO_BLACKS, + whites_range: WHITES_RANGE, + blacks_range: BLACKS_RANGE, + points_side: POINTS_SIDE, + point_quantiles: POINT_QUANTILES, + } +} +// Measured levels; some happen to lie near π/8 and π/4. +/// Whites curves at internal amounts -100, -90, …, 270 (rows) over grey levels 0, 1/32, …, 1. +#[allow(clippy::approx_constant)] +static WHITES: [[f32; 33]; 38] = [ + [ + 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1523, 0.1817, 0.2107, 0.2391, 0.2671, 0.2946, 0.3215, 0.3480, 0.3738, 0.3995, 0.4256, 0.4517, + 0.4774, 0.5028, 0.5278, 0.5524, 0.5768, 0.6008, 0.6245, 0.6482, 0.6717, 0.6957, 0.7207, 0.7483, 0.7814, 0.8263, 0.8949, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1523, 0.1817, 0.2107, 0.2392, 0.2672, 0.2947, 0.3217, 0.3482, 0.3742, 0.4000, 0.4263, 0.4526, + 0.4785, 0.5042, 0.5296, 0.5548, 0.5797, 0.6044, 0.6291, 0.6539, 0.6789, 0.7046, 0.7317, 0.7617, 0.7969, 0.8425, 0.9074, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1524, 0.1818, 0.2108, 0.2393, 0.2673, 0.2950, 0.3221, 0.3487, 0.3748, 0.4008, 0.4274, 0.4540, + 0.4803, 0.5064, 0.5323, 0.5580, 0.5837, 0.6093, 0.6350, 0.6610, 0.6875, 0.7149, 0.7438, 0.7756, 0.8122, 0.8576, 0.9184, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1524, 0.1818, 0.2109, 0.2395, 0.2677, 0.2954, 0.3227, 0.3495, 0.3759, 0.4022, 0.4291, 0.4561, + 0.4828, 0.5094, 0.5360, 0.5624, 0.5888, 0.6154, 0.6423, 0.6695, 0.6973, 0.7261, 0.7566, 0.7897, 0.8271, 0.8716, 0.9280, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1525, 0.1820, 0.2111, 0.2398, 0.2682, 0.2961, 0.3237, 0.3508, 0.3775, 0.4042, 0.4317, 0.4591, + 0.4864, 0.5136, 0.5408, 0.5680, 0.5953, 0.6229, 0.6508, 0.6791, 0.7082, 0.7382, 0.7698, 0.8037, 0.8412, 0.8843, 0.9365, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0927, 0.1227, 0.1527, 0.1822, 0.2116, 0.2404, 0.2690, 0.2972, 0.3251, 0.3527, 0.3799, 0.4071, 0.4351, 0.4630, + 0.4910, 0.5189, 0.5469, 0.5749, 0.6031, 0.6316, 0.6605, 0.6899, 0.7199, 0.7509, 0.7832, 0.8174, 0.8544, 0.8958, 0.9439, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0927, 0.1229, 0.1529, 0.1827, 0.2122, 0.2414, 0.2702, 0.2989, 0.3272, 0.3553, 0.3831, 0.4110, 0.4396, 0.4682, + 0.4968, 0.5254, 0.5542, 0.5830, 0.6121, 0.6414, 0.6712, 0.7014, 0.7322, 0.7637, 0.7964, 0.8305, 0.8668, 0.9062, 0.9503, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0622, 0.0928, 0.1231, 0.1534, 0.1834, 0.2132, 0.2427, 0.2720, 0.3011, 0.3300, 0.3587, 0.3872, 0.4160, 0.4452, 0.4745, + 0.5038, 0.5332, 0.5627, 0.5923, 0.6221, 0.6522, 0.6826, 0.7134, 0.7447, 0.7765, 0.8092, 0.8429, 0.8781, 0.9155, 0.9559, 1.0000, + ], + [ + 0.0000, 0.0298, 0.0623, 0.0930, 0.1236, 0.1541, 0.1844, 0.2145, 0.2445, 0.2744, 0.3041, 0.3337, 0.3632, 0.3925, 0.4221, 0.4520, 0.4820, + 0.5120, 0.5421, 0.5723, 0.6026, 0.6330, 0.6636, 0.6946, 0.7257, 0.7572, 0.7890, 0.8214, 0.8545, 0.8885, 0.9237, 0.9608, 1.0000, + ], + [ + 0.0000, 0.0298, 0.0624, 0.0934, 0.1242, 0.1551, 0.1858, 0.2164, 0.2470, 0.2775, 0.3080, 0.3383, 0.3687, 0.3989, 0.4293, 0.4600, 0.4906, + 0.5213, 0.5520, 0.5827, 0.6136, 0.6445, 0.6755, 0.7067, 0.7380, 0.7694, 0.8011, 0.8330, 0.8652, 0.8978, 0.9310, 0.9651, 1.0000, + ], + [ + 0.0000, 0.0312, 0.0625, 0.0938, 0.1250, 0.1562, 0.1875, 0.2188, 0.2500, 0.2812, 0.3125, 0.3438, 0.3750, 0.4062, 0.4375, 0.4688, 0.5000, + 0.5312, 0.5625, 0.5938, 0.6250, 0.6562, 0.6875, 0.7188, 0.7500, 0.7812, 0.8125, 0.8438, 0.8750, 0.9062, 0.9375, 0.9688, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0626, 0.0940, 0.1253, 0.1567, 0.1881, 0.2195, 0.2510, 0.2825, 0.3140, 0.3456, 0.3772, 0.4089, 0.4405, 0.4720, 0.5036, + 0.5351, 0.5667, 0.5983, 0.6298, 0.6613, 0.6929, 0.7244, 0.7559, 0.7874, 0.8189, 0.8503, 0.8816, 0.9128, 0.9438, 0.9742, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0627, 0.0941, 0.1257, 0.1573, 0.1890, 0.2208, 0.2526, 0.2846, 0.3167, 0.3488, 0.3811, 0.4134, 0.4456, 0.4777, 0.5098, + 0.5419, 0.5741, 0.6062, 0.6383, 0.6704, 0.7025, 0.7345, 0.7664, 0.7983, 0.8301, 0.8617, 0.8931, 0.9241, 0.9543, 0.9829, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0628, 0.0944, 0.1262, 0.1582, 0.1903, 0.2225, 0.2550, 0.2876, 0.3204, 0.3534, 0.3867, 0.4200, 0.4529, 0.4858, 0.5186, + 0.5516, 0.5845, 0.6174, 0.6502, 0.6830, 0.7157, 0.7482, 0.7807, 0.8131, 0.8451, 0.8769, 0.9082, 0.9385, 0.9673, 0.9928, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0629, 0.0948, 0.1269, 0.1594, 0.1920, 0.2249, 0.2582, 0.2917, 0.3256, 0.3597, 0.3942, 0.4289, 0.4628, 0.4966, 0.5305, + 0.5644, 0.5983, 0.6321, 0.6658, 0.6994, 0.7327, 0.7660, 0.7989, 0.8316, 0.8639, 0.8956, 0.9263, 0.9553, 0.9815, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0631, 0.0953, 0.1280, 0.1610, 0.1944, 0.2282, 0.2625, 0.2973, 0.3325, 0.3683, 0.4045, 0.4407, 0.4758, 0.5109, 0.5460, + 0.5811, 0.6161, 0.6510, 0.6857, 0.7201, 0.7541, 0.7879, 0.8213, 0.8543, 0.8864, 0.9175, 0.9468, 0.9733, 0.9950, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0633, 0.0961, 0.1293, 0.1632, 0.1976, 0.2327, 0.2684, 0.3048, 0.3419, 0.3798, 0.4183, 0.4562, 0.4928, 0.5294, 0.5660, + 0.6024, 0.6387, 0.6748, 0.7104, 0.7456, 0.7803, 0.8145, 0.8480, 0.8807, 0.9121, 0.9417, 0.9684, 0.9907, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0300, 0.0637, 0.0971, 0.1313, 0.1663, 0.2020, 0.2387, 0.2763, 0.3149, 0.3546, 0.3952, 0.4365, 0.4763, 0.5149, 0.5532, 0.5914, + 0.6294, 0.6670, 0.7041, 0.7406, 0.7763, 0.8113, 0.8456, 0.8788, 0.9104, 0.9401, 0.9667, 0.9888, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0300, 0.0641, 0.0984, 0.1338, 0.1703, 0.2079, 0.2468, 0.2870, 0.3286, 0.3717, 0.4161, 0.4602, 0.5024, 0.5430, 0.5833, 0.6232, + 0.6627, 0.7015, 0.7394, 0.7764, 0.8123, 0.8472, 0.8808, 0.9126, 0.9420, 0.9681, 0.9896, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0302, 0.0647, 0.1003, 0.1374, 0.1760, 0.2160, 0.2579, 0.3016, 0.3472, 0.3949, 0.4436, 0.4908, 0.5355, 0.5784, 0.6207, 0.6622, + 0.7029, 0.7424, 0.7806, 0.8176, 0.8530, 0.8868, 0.9185, 0.9474, 0.9726, 0.9926, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0304, 0.0656, 0.1029, 0.1423, 0.1837, 0.2271, 0.2731, 0.3215, 0.3726, 0.4262, 0.4791, 0.5294, 0.5769, 0.6220, 0.6660, 0.7086, + 0.7498, 0.7893, 0.8272, 0.8631, 0.8969, 0.9281, 0.9560, 0.9795, 0.9967, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0305, 0.0679, 0.1094, 0.1509, 0.1968, 0.2459, 0.2956, 0.3510, 0.4094, 0.4680, 0.5248, 0.5781, 0.6278, 0.6742, 0.7195, 0.7624, + 0.8031, 0.8417, 0.8779, 0.9113, 0.9414, 0.9675, 0.9886, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0306, 0.0702, 0.1160, 0.1623, 0.2144, 0.2709, 0.3243, 0.3885, 0.4556, 0.5199, 0.5807, 0.6369, 0.6884, 0.7355, 0.7799, 0.8217, + 0.8606, 0.8964, 0.9288, 0.9570, 0.9803, 0.9958, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0308, 0.0725, 0.1225, 0.1737, 0.2320, 0.2960, 0.3641, 0.4393, 0.5133, 0.5825, 0.6460, 0.7032, 0.7544, 0.8003, 0.8426, 0.8817, + 0.9168, 0.9475, 0.9733, 0.9924, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0322, 0.0751, 0.1303, 0.1918, 0.2594, 0.3348, 0.4189, 0.5044, 0.5841, 0.6565, 0.7208, 0.7771, 0.8262, 0.8692, 0.9074, 0.9408, + 0.9686, 0.9900, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0331, 0.0818, 0.1482, 0.2171, 0.2977, 0.3892, 0.4865, 0.5779, 0.6602, 0.7322, 0.7943, 0.8470, 0.8915, 0.9286, 0.9600, 0.9844, + 0.9996, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0340, 0.0884, 0.1661, 0.2544, 0.3540, 0.4658, 0.5729, 0.6681, 0.7496, 0.8183, 0.8748, 0.9208, 0.9568, 0.9832, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.3356, 0.5799, 0.6166, 0.6166, 0.6166, 0.6166, 0.6624, 0.7556, 0.8321, 0.8935, 0.9411, 0.9755, 0.9970, 0.9998, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.5007, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.1655, 0.1655, 0.2972, 0.4728, 0.6327, 0.7616, 0.8598, 0.9317, 0.9790, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0457, 0.1830, 0.3836, 0.5790, 0.7379, 0.8549, 0.9360, 0.9869, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0520, 0.2329, 0.4864, 0.6989, 0.8449, 0.9403, 0.9884, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0773, 0.3027, 0.6040, 0.8058, 0.9302, 0.9930, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.1454, 0.4738, 0.7615, 0.9074, 0.9908, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0964, 0.5416, 0.8589, 0.9897, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.1538, 0.1538, 0.7080, 0.9596, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.8439, 0.8439, 0.8439, 0.9993, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.9228, 0.9228, 0.9228, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], +]; +/// Blacks curves at internal amounts -100, …, 100 in steps of 10. +#[allow(clippy::approx_constant)] +static BLACKS: [[f32; 33]; 21] = [ + [ + 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0290, 0.0572, 0.0879, 0.1222, 0.1580, 0.1935, 0.2287, 0.2636, 0.2988, 0.3355, 0.3741, + 0.4151, 0.4571, 0.4990, 0.5406, 0.5818, 0.6226, 0.6631, 0.7031, 0.7424, 0.7811, 0.8192, 0.8568, 0.8937, 0.9300, 0.9655, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0000, 0.0000, 0.0015, 0.0363, 0.0640, 0.0956, 0.1300, 0.1651, 0.2000, 0.2345, 0.2686, 0.3026, 0.3369, 0.3727, 0.4105, + 0.4495, 0.4885, 0.5272, 0.5657, 0.6039, 0.6419, 0.6796, 0.7169, 0.7538, 0.7903, 0.8264, 0.8621, 0.8974, 0.9322, 0.9664, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0000, 0.0000, 0.0346, 0.0625, 0.0934, 0.1271, 0.1616, 0.1959, 0.2298, 0.2635, 0.2969, 0.3301, 0.3638, 0.3990, 0.4357, + 0.4727, 0.5094, 0.5460, 0.5824, 0.6187, 0.6547, 0.6906, 0.7262, 0.7615, 0.7965, 0.8313, 0.8657, 0.8998, 0.9336, 0.9671, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0000, 0.0235, 0.0554, 0.0850, 0.1175, 0.1514, 0.1852, 0.2187, 0.2519, 0.2849, 0.3178, 0.3505, 0.3837, 0.4183, 0.4537, + 0.4891, 0.5243, 0.5594, 0.5944, 0.6292, 0.6639, 0.6985, 0.7329, 0.7671, 0.8010, 0.8347, 0.8683, 0.9016, 0.9347, 0.9676, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0020, 0.0438, 0.0724, 0.1035, 0.1365, 0.1699, 0.2030, 0.2359, 0.2686, 0.3011, 0.3336, 0.3659, 0.3986, 0.4327, 0.4669, + 0.5011, 0.5352, 0.5692, 0.6031, 0.6369, 0.6706, 0.7043, 0.7378, 0.7711, 0.8043, 0.8373, 0.8702, 0.9029, 0.9355, 0.9679, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0230, 0.0567, 0.0865, 0.1182, 0.1510, 0.1839, 0.2164, 0.2489, 0.2812, 0.3133, 0.3455, 0.3775, 0.4100, 0.4433, 0.4767, + 0.5100, 0.5433, 0.5765, 0.6096, 0.6426, 0.6756, 0.7086, 0.7414, 0.7741, 0.8067, 0.8392, 0.8716, 0.9039, 0.9361, 0.9682, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0368, 0.0670, 0.0976, 0.1294, 0.1619, 0.1943, 0.2265, 0.2586, 0.2906, 0.3225, 0.3544, 0.3862, 0.4184, 0.4512, 0.4839, + 0.5166, 0.5492, 0.5818, 0.6144, 0.6469, 0.6793, 0.7117, 0.7441, 0.7763, 0.8085, 0.8406, 0.8727, 0.9046, 0.9365, 0.9683, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0444, 0.0749, 0.1058, 0.1377, 0.1699, 0.2020, 0.2339, 0.2657, 0.2975, 0.3292, 0.3609, 0.3926, 0.4245, 0.4568, 0.4891, + 0.5213, 0.5535, 0.5857, 0.6179, 0.6499, 0.6820, 0.7140, 0.7460, 0.7779, 0.8098, 0.8416, 0.8734, 0.9052, 0.9368, 0.9685, 1.0000, + ], + [ + 0.0000, 0.0086, 0.0511, 0.0817, 0.1128, 0.1445, 0.1763, 0.2080, 0.2397, 0.2713, 0.3029, 0.3344, 0.3660, 0.3975, 0.4292, 0.4611, 0.4930, + 0.5249, 0.5567, 0.5886, 0.6204, 0.6522, 0.6839, 0.7157, 0.7475, 0.7791, 0.8108, 0.8424, 0.8740, 0.9056, 0.9371, 0.9686, 1.0000, + ], + [ + 0.0000, 0.0198, 0.0564, 0.0874, 0.1186, 0.1501, 0.1817, 0.2133, 0.2447, 0.2762, 0.3076, 0.3390, 0.3705, 0.4018, 0.4333, 0.4649, 0.4965, + 0.5281, 0.5597, 0.5912, 0.6227, 0.6543, 0.6858, 0.7173, 0.7488, 0.7802, 0.8117, 0.8431, 0.8745, 0.9059, 0.9373, 0.9686, 1.0000, + ], + [ + 0.0000, 0.0312, 0.0625, 0.0938, 0.1250, 0.1562, 0.1875, 0.2188, 0.2500, 0.2812, 0.3125, 0.3438, 0.3750, 0.4062, 0.4375, 0.4688, 0.5000, + 0.5312, 0.5625, 0.5938, 0.6250, 0.6562, 0.6875, 0.7188, 0.7500, 0.7812, 0.8125, 0.8438, 0.8750, 0.9062, 0.9375, 0.9688, 1.0000, + ], + [ + 0.0000, 0.0313, 0.0650, 0.0979, 0.1303, 0.1624, 0.1942, 0.2260, 0.2576, 0.2891, 0.3206, 0.3520, 0.3833, 0.4146, 0.4455, 0.4763, 0.5070, + 0.5378, 0.5684, 0.5991, 0.6298, 0.6605, 0.6912, 0.7219, 0.7526, 0.7833, 0.8141, 0.8450, 0.8758, 0.9067, 0.9377, 0.9688, 1.0000, + ], + [ + 0.0000, 0.0326, 0.0677, 0.1022, 0.1357, 0.1686, 0.2010, 0.2332, 0.2652, 0.2969, 0.3286, 0.3601, 0.3915, 0.4227, 0.4532, 0.4835, 0.5138, + 0.5440, 0.5741, 0.6042, 0.6344, 0.6645, 0.6946, 0.7248, 0.7550, 0.7853, 0.8156, 0.8461, 0.8766, 0.9072, 0.9380, 0.9689, 1.0000, + ], + [ + 0.0000, 0.0341, 0.0706, 0.1066, 0.1413, 0.1749, 0.2079, 0.2405, 0.2728, 0.3048, 0.3366, 0.3682, 0.3996, 0.4307, 0.4608, 0.4906, 0.5203, + 0.5500, 0.5796, 0.6092, 0.6387, 0.6683, 0.6979, 0.7276, 0.7573, 0.7871, 0.8170, 0.8472, 0.8773, 0.9077, 0.9382, 0.9690, 1.0000, + ], + [ + 0.0000, 0.0354, 0.0736, 0.1113, 0.1472, 0.1814, 0.2149, 0.2479, 0.2805, 0.3127, 0.3446, 0.3763, 0.4077, 0.4385, 0.4681, 0.4974, 0.5267, + 0.5558, 0.5849, 0.6139, 0.6429, 0.6720, 0.7011, 0.7303, 0.7595, 0.7889, 0.8184, 0.8481, 0.8780, 0.9081, 0.9384, 0.9690, 1.0000, + ], + [ + 0.0000, 0.0368, 0.0768, 0.1162, 0.1531, 0.1881, 0.2221, 0.2554, 0.2882, 0.3206, 0.3527, 0.3843, 0.4158, 0.4461, 0.4753, 0.5041, 0.5328, + 0.5615, 0.5900, 0.6185, 0.6470, 0.6755, 0.7041, 0.7328, 0.7616, 0.7906, 0.8197, 0.8491, 0.8787, 0.9085, 0.9386, 0.9691, 1.0000, + ], + [ + 0.0000, 0.0381, 0.0802, 0.1214, 0.1593, 0.1949, 0.2293, 0.2630, 0.2961, 0.3286, 0.3607, 0.3924, 0.4236, 0.4536, 0.4823, 0.5106, 0.5388, + 0.5669, 0.5949, 0.6229, 0.6509, 0.6789, 0.7070, 0.7352, 0.7636, 0.7922, 0.8209, 0.8500, 0.8793, 0.9089, 0.9388, 0.9691, 1.0000, + ], + [ + 0.0000, 0.0394, 0.0837, 0.1267, 0.1656, 0.2018, 0.2367, 0.2707, 0.3039, 0.3365, 0.3686, 0.4003, 0.4314, 0.4608, 0.4890, 0.5168, 0.5445, + 0.5721, 0.5996, 0.6271, 0.6546, 0.6822, 0.7098, 0.7375, 0.7655, 0.7937, 0.8221, 0.8509, 0.8799, 0.9092, 0.9390, 0.9692, 1.0000, + ], + [ + 0.0000, 0.0407, 0.0875, 0.1322, 0.1720, 0.2088, 0.2441, 0.2784, 0.3118, 0.3444, 0.3765, 0.4082, 0.4389, 0.4679, 0.4955, 0.5229, 0.5501, + 0.5771, 0.6042, 0.6312, 0.6582, 0.6853, 0.7124, 0.7398, 0.7673, 0.7952, 0.8233, 0.8517, 0.8804, 0.9096, 0.9391, 0.9692, 1.0000, + ], + [ + 0.0000, 0.0421, 0.0915, 0.1379, 0.1786, 0.2160, 0.2516, 0.2861, 0.3196, 0.3523, 0.3844, 0.4159, 0.4462, 0.4747, 0.5019, 0.5287, 0.5554, + 0.5820, 0.6085, 0.6351, 0.6616, 0.6882, 0.7149, 0.7419, 0.7690, 0.7965, 0.8243, 0.8524, 0.8810, 0.9099, 0.9393, 0.9693, 1.0000, + ], + [ + 0.0000, 0.0436, 0.0957, 0.1438, 0.1853, 0.2232, 0.2592, 0.2938, 0.3274, 0.3601, 0.3922, 0.4235, 0.4533, 0.4813, 0.5080, 0.5343, 0.5605, + 0.5866, 0.6127, 0.6387, 0.6648, 0.6910, 0.7173, 0.7439, 0.7707, 0.7978, 0.8253, 0.8532, 0.8815, 0.9102, 0.9394, 0.9693, 1.0000, + ], +]; +const BPS: [f32; 9] = [0.0000, 0.0200, 0.0500, 0.1000, 0.2000, 0.3000, 0.4500, 0.6000, 0.8000]; +const WPS: [f32; 8] = [0.1000, 0.2000, 0.3000, 0.4500, 0.6000, 0.8000, 0.9000, 1.0000]; +static AW: [[f32; 8]; 9] = [ + [1.7750, 2.3875, 2.4000, 2.1625, 1.9438, 1.6125, 1.3875, 1.0000], + [1.8125, 2.5250, 2.3937, 2.1688, 1.9375, 1.6062, 1.3938, 0.9875], + [2.7000, 2.4688, 2.2750, 2.0688, 1.8875, 1.6000, 1.3875, 0.9938], + [2.3250, 2.3250, 2.1875, 1.9750, 1.7937, 1.5188, 1.3250, 1.0437], + [2.0187, 2.0187, 2.0187, 1.8625, 1.7063, 1.4062, 1.2250, 0.9250], + [1.7500, 1.7500, 1.7500, 1.7500, 1.6438, 1.3562, 1.1687, 0.8625], + [1.4937, 1.4937, 1.4937, 1.4937, 1.4937, 1.2875, 1.1000, 0.7875], + [1.1687, 1.1687, 1.1687, 1.1687, 1.1687, 1.1687, 1.0375, 0.7562], + [0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.7562], +]; +static AB: [[f32; 8]; 9] = [ + [0.9938, 0.9812, 1.0000, 1.0125, 0.9563, 0.9688, 1.0437, 1.0000], + [1.0437, 1.0250, 1.0125, 1.0000, 1.0000, 1.0375, 1.0000, 0.9938], + [1.2312, 1.2063, 1.1875, 1.1625, 1.1438, 1.1438, 1.1375, 1.1250], + [1.2500, 1.2500, 1.2312, 1.2125, 1.2125, 1.2375, 1.2375, 1.2375], + [1.1750, 1.1750, 1.1750, 1.1750, 1.2063, 1.2688, 1.3125, 1.3375], + [1.1812, 1.1812, 1.1812, 1.1812, 1.2125, 1.2812, 1.3313, 1.4125], + [1.2375, 1.2375, 1.2375, 1.2375, 1.2375, 1.3062, 1.3562, 1.4375], + [1.3250, 1.3250, 1.3250, 1.3250, 1.3250, 1.3250, 1.3687, 1.4500], + [1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.4312], +]; + +/// A curve row at a fractional internal amount `x`, at grey level `v` (both interpolated). +fn curve(rows: &[[f32; STEPS]], from: f32, x: f32, v: f32) -> f32 { + if v >= 1.0 { + return 1.0; + } + let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32); + let i = (r as usize).min(rows.len() - 2); + let t = r - i as f32; + let at = |row: &[f32; STEPS]| { + let p = v.max(0.0) * (STEPS - 1) as f32; + let j = (p as usize).min(STEPS - 2); + let s = p - j as f32; + row[j] + (row[j + 1] - row[j]) * s + }; + at(&rows[i]) * (1.0 - t) + at(&rows[i + 1]) * t +} + +/// The curve at a fractional internal amount `x` as one row: `curve(rows, from, x, v)` is this +/// row interpolated at `v`, because both interpolations are linear. +fn row_at(rows: &[[f32; STEPS]], from: f32, x: f32) -> [f32; STEPS] { + let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32); + let i = (r as usize).min(rows.len() - 2); + let t = r - i as f32; + std::array::from_fn(|j| rows[i][j] * (1.0 - t) + rows[i + 1][j] * t) +} + +/// The Whites curve at internal amount `x` as a row over grey levels 0, 1/32, …, 1. +pub(crate) fn whites_row(x: f32) -> [f32; STEPS] { + row_at(&WHITES, WHITES_FROM, x) +} + +/// The Blacks curve at internal amount `x` as a row over grey levels 0, 1/32, …, 1. +pub(crate) fn blacks_row(x: f32) -> [f32; STEPS] { + row_at(&BLACKS, BLACKS_FROM, x) +} + +/// Whites at internal amount `x` (−100 … 270) of grey level `v`. +pub(crate) fn whites(v: f32, x: f32) -> f32 { + curve(&WHITES, WHITES_FROM, x, v) +} + +/// Blacks at internal amount `x` (−100 … 100) of grey level `v`. +pub(crate) fn blacks(v: f32, x: f32) -> f32 { + curve(&BLACKS, BLACKS_FROM, x, v) +} + +/// The least Blacks adaptation on photographs. +const PHOTO_BLACKS: f32 = 1.2; + +/// Bilinear lookup of an adaptation table at black point `bp` and white point `wp`. +fn adapt(table: &[[f32; 8]; 9], bp: f32, wp: f32) -> f32 { + let idx = |grid: &[f32], v: f32| { + let v = v.clamp(grid[0], grid[grid.len() - 1]); + let i = grid.windows(2).position(|w| v <= w[1]).unwrap_or(grid.len() - 2); + (i, (v - grid[i]) / (grid[i + 1] - grid[i])) + }; + let (i, s) = idx(&BPS, bp); + let (j, t) = idx(&WPS, wp); + let row = |i: usize| table[i][j] * (1.0 - t) + table[i][j + 1] * t; + row(i) * (1.0 - s) + row(i + 1) * s +} + +/// The internal amounts of the Whites and Blacks sliders (−100 … 100) for an image whose 1st +/// and 99th luminance percentiles are the grey levels `bp` and `wp` (sRGB-encoded). +pub(crate) fn amounts(whites: f32, blacks: f32, bp: f32, wp: f32) -> (f32, f32) { + let w = if whites > 0.0 { whites * adapt(&AW, bp, wp) } else { whites }; + // On photographs Photoshop's Blacks is about 1.2 times the block images' amount even where + // their black point is 0 (ten public-domain photos: 1.08–1.36). + let b = if blacks < 0.0 { blacks * adapt(&AB, bp, wp).max(PHOTO_BLACKS) } else { blacks }; + (w.clamp(WHITES_RANGE[0], WHITES_RANGE[1]), b.clamp(BLACKS_RANGE[0], BLACKS_RANGE[1])) +} + +/// Applies Whites and Blacks (internal amounts `w`, `b`) to straight RGBA pixels (`width` per +/// row) encoded with `enc`. Values above 1 (float documents) keep their excess. +pub(crate) fn apply(px: &mut [[f32; 4]], width: usize, w: f32, b: f32, enc: Encoding) { + if w == 0.0 && b == 0.0 { + return; + } + // A grey level's new level, both sRGB-encoded. + let grey = |v: f32| { + let v = if w != 0.0 { whites(v, w) } else { v }; + if b != 0.0 { blacks(v, b) } else { v } + }; + let per_channel = w > 0.0 || b < 0.0; + par_rows(px, width, 1, |_, row| { + for q in row.iter_mut() { + let lin = [0, 1, 2].map(|c| enc.decode(q[c])); + if per_channel { + for c in 0..3 { + let over = (lin[c] - 1.0).max(0.0); + q[c] = enc.encode(super::srgb_to_linear(grey(super::linear_to_srgb(lin[c].min(1.0)))) + over); + } + } else { + let y = super::luma_linear(lin).max(0.0); + if y <= 1e-7 { + continue; + } + let y2 = super::srgb_to_linear(grey(super::linear_to_srgb(y.min(1.0)))) + (y - 1.0).max(0.0); + let k = y2 / y; + for c in 0..3 { + q[c] = enc.encode(lin[c] * k); + } + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn full_range_rows_match_photoshop() { + // Photoshop 25.4 on a 64-level block image spanning black to white (sRGB levels). + assert!((whites(97.1 / 255.0, 100.0) * 255.0 - 137.4).abs() < 0.6); + assert!((whites(194.3 / 255.0, -100.0) * 255.0 - 167.6).abs() < 0.6); + assert!((blacks(97.1 / 255.0, -100.0) * 255.0 - 60.0).abs() < 0.6); + assert!((blacks(48.6 / 255.0, 100.0) * 255.0 - 67.0).abs() < 0.6); + // The compressing directions keep black and white. + assert_eq!(whites(1.0, -100.0), 1.0); + assert_eq!(blacks(0.0, 100.0), 0.0); + } + + #[test] + fn the_clipping_directions_adapt_to_the_image() { + // A dark, low-contrast image needs more: Whites +50 acts like +94.5 on [0.05, 0.6]. + let (w, _) = amounts(50.0, 0.0, 0.05, 0.6); + assert!((w - 94.5).abs() < 2.0, "{w}"); + // A raised black point strengthens Blacks −40 to −58 on [0.6, 1]. + let (_, b) = amounts(0.0, -40.0, 0.6, 1.0); + assert!((b + 58.0).abs() < 1.0, "{b}"); + // Never below the photographs' 1.2. + assert!((amounts(0.0, -50.0, 0.0, 1.0).1 + 60.0).abs() < 1e-3); + // The compressing directions never adapt. + assert_eq!(amounts(-50.0, 50.0, 0.3, 0.6), (-50.0, 50.0)); + } +} diff --git a/crates/develop/src/colorops.rs b/crates/develop/src/colorops.rs new file mode 100644 index 0000000000..1b1e357fc4 --- /dev/null +++ b/crates/develop/src/colorops.rs @@ -0,0 +1,530 @@ +//! Colour tools in OkLCh on display-linear Rec.2020 values: vibrance, saturation, the 8-band colour +//! mixer, B&W mix, and 3-way colour grading; plus the camera-calibration matrix (scene linear). + +use std::f32::consts::{PI, TAU}; +use std::sync::OnceLock; + +use craft_color::srgb_to_linear; +use craft_color_transform::oklab::{OkLab, lab_to_lch, lch_to_lab}; +use craft_color_transform::{Mat3, REC2020, SRGB}; +use craft_develop_model::{Calibration, DevelopSettings, MAX_POINT_COLORS, MIXER_HUES, PointColor, Treatment, Wheel}; + +fn oklab_2020() -> &'static OkLab { + static M: OnceLock = OnceLock::new(); + M.get_or_init(|| OkLab::for_space(&REC2020)) +} + +#[inline] +fn oklab_from_2020(rgb: [f32; 3]) -> [f32; 3] { + oklab_2020().from_rgb(rgb) +} + +#[inline] +fn oklab_to_2020(lab: [f32; 3]) -> [f32; 3] { + oklab_2020().to_rgb(lab) +} + +fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] { + let c = v * s; + let hp = h.rem_euclid(360.0) / 60.0; + let x = c * (1.0 - (hp % 2.0 - 1.0).abs()); + let (r, g, b) = match hp as u32 { + 0 => (c, x, 0.0), + 1 => (x, c, 0.0), + 2 => (0.0, c, x), + 3 => (0.0, x, c), + 4 => (x, 0.0, c), + _ => (c, 0.0, x), + }; + let m = v - c; + [r + m, g + m, b + m] +} + +/// Whether `s` renders in black and white (B&W treatment or monochrome profile). +#[inline] +pub fn is_bw(s: &DevelopSettings) -> bool { + s.treatment == Treatment::Bw || s.profile.id == "lc.mono" || s.profile.id.starts_with("lc.bw.") +} + +/// Linear Rec.2020 luminance. +#[inline] +pub fn luminance_2020(c: [f32; 3]) -> f32 { + c[0] * 0.2627 + c[1] * 0.6780 + c[2] * 0.0593 +} + +/// OkLCh hue angle (radians) of a pure sRGB colour with HSV hue `deg`. +pub fn oklch_hue_of_srgb_hue(deg: f64) -> f32 { + let c = hsv_to_rgb(deg as f32, 1.0, 1.0); + let lin = c.map(srgb_to_linear); + // Match LightCraft's matrix precision: round only after the full transform. + let rec = SRGB.to_space(&REC2020).apply(lin.map(f64::from)).map(|v| v as f32); + lab_to_lch(oklab_from_2020(rec))[2] +} + +/// OkLCh hue (radians) of each colour-mixer band centre. +pub fn band_hues() -> &'static [f32; 8] { + static H: OnceLock<[f32; 8]> = OnceLock::new(); + H.get_or_init(|| MIXER_HUES.map(oklch_hue_of_srgb_hue)) +} + +#[inline] +fn wrap(a: f32) -> f32 { + (a + PI).rem_euclid(TAU) - PI +} + +/// Partition-of-unity weights of hue `h` over the 8 bands (raised cosine between neighbours). +#[inline] +pub fn band_weights(h: f32) -> [f32; 8] { + let hues = band_hues(); + let mut w = [0.0f32; 8]; + for i in 0..8 { + let a = hues[i]; + let b = hues[(i + 1) % 8]; + let span = wrap(b - a).rem_euclid(TAU); + let d = wrap(h - a).rem_euclid(TAU); + if d <= span { + let t = d / span; + let s = 0.5 - 0.5 * (t * PI).cos(); + w[i] += 1.0 - s; + w[(i + 1) % 8] += s; + break; + } + } + w +} + +/// A colour-grading wheel as an OkLab offset (a, b) and a lightness shift. +#[derive(Clone, Copy, Debug)] +pub struct WheelK { + pub a: f32, + pub b: f32, + pub lum: f32, +} + +/// Number of `f32`s per Point Color sample in [`PointK::words`] (the GPU parameter layout). +pub const POINT_WORDS: usize = 10; + +/// A Point Color sample resolved for the per-pixel stage: the sample (OkLab lightness, chroma, hue +/// in radians), the adjustment (hue rotation in radians, chroma scale − 1, lightness shift, +/// variance factor − 1) and the half-widths of the range box (hue radians, chroma, lightness). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PointK { + pub l: f32, + pub c: f32, + pub h: f32, + pub dh: f32, + pub sat: f32, + pub dl: f32, + pub var: f32, + pub wh: f32, + pub wc: f32, + pub wl: f32, +} + +impl PointK { + pub fn new(p: &PointColor) -> PointK { + let k = (p.range.clamp(0.0, 100.0) / 50.0).max(0.05) as f32; + let f = |v: f64| (v.clamp(0.0, 100.0) / 100.0) as f32; + PointK { + l: p.lum as f32, + c: p.chroma.max(0.0) as f32, + h: (p.hue as f32).to_radians(), + dh: (p.hue_shift.clamp(-100.0, 100.0) / 100.0) as f32 * 0.5, + sat: (p.sat_shift.clamp(-100.0, 100.0) / 100.0) as f32, + dl: (p.lum_shift.clamp(-100.0, 100.0) / 100.0) as f32 * 0.2, + var: (p.variance.clamp(-100.0, 100.0) / 100.0) as f32 * 0.8, + wh: (0.1 + 0.6 * f(p.hue_range)) * k, + wc: (0.02 + 0.12 * f(p.sat_range)) * k, + wl: (0.05 + 0.4 * f(p.lum_range)) * k, + } + } + + pub fn words(&self) -> [f32; POINT_WORDS] { + [self.l, self.c, self.h, self.dh, self.sat, self.dl, self.var, self.wh, self.wc, self.wl] + } + + /// How much an OkLCh colour belongs to this sample's range (0..1, soft edges). + #[inline] + pub fn weight(&self, l: f32, c: f32, h: f32) -> f32 { + // hue is meaningless for near-neutral colours: a chromatic sample ignores them, a + // near-neutral sample selects by chroma and lightness only + let wh = if self.c < 0.02 { 1.0 } else { (1.0 - smooth(0.5 * self.wh, self.wh, wrap(h - self.h).abs())) * smooth(0.005, 0.025, c) }; + if wh <= 0.0 { + return 0.0; + } + let wc = 1.0 - smooth(0.5 * self.wc, self.wc, (c - self.c).abs()); + let wl = 1.0 - smooth(0.5 * self.wl, self.wl, (l - self.l).abs()); + wh * wc * wl + } + + /// Apply this sample's adjustment to an OkLCh colour. + #[inline] + pub fn apply(&self, lch: [f32; 3]) -> [f32; 3] { + let [mut l, mut c, mut h] = lch; + let w = self.weight(l, c, h); + if w <= 0.0 { + return lch; + } + h += w * (self.var * wrap(h - self.h) + self.dh); + c += w * self.var * (c - self.c); + c = (c * (1.0 + w * self.sat)).max(0.0); + l += w * (self.var * (l - self.l) + self.dl); + [l, c, h] + } +} + +/// The colour tools' parameters, resolved once per render (fields are read by the GPU kernel). +#[derive(Clone, Debug)] +pub struct ColorOps { + pub vibrance: f32, + pub saturation: f32, + pub hue: [f32; 8], + pub sat: [f32; 8], + pub lum: [f32; 8], + pub mixer: bool, + /// Point Color samples that change something (applied after the mixer). + pub points: Vec, + pub bw: Option<[f32; 8]>, + /// Wheels (shadows, midtones, highlights, global), blending, balance. + pub grading: Option<([WheelK; 4], f32, f32)>, + /// OkLCh hue of skin tones (protected by vibrance). + pub skin: f32, +} + +fn wheel(w: &Wheel) -> WheelK { + let h = oklch_hue_of_srgb_hue(w.hue); + let s = (w.sat / 100.0) as f32 * 0.09; + WheelK { a: s * h.cos(), b: s * h.sin(), lum: (w.lum / 100.0) as f32 * 0.12 } +} + +impl ColorOps { + pub fn new(s: &DevelopSettings) -> ColorOps { + let bands = s.mixer.bands(); + let g = &s.grading; + ColorOps { + vibrance: (s.color.vibrance / 100.0) as f32, + saturation: (s.color.saturation / 100.0) as f32, + hue: bands.map(|b| (b.hue / 100.0) as f32 * 0.5), + sat: bands.map(|b| (b.sat / 100.0) as f32), + lum: bands.map(|b| (b.lum / 100.0) as f32 * 0.18), + mixer: !s.mixer.is_neutral(), + points: if is_bw(s) { + Vec::new() + } else { + s.point_colors.iter().take(MAX_POINT_COLORS).filter(|p| !p.is_neutral()).map(PointK::new).collect() + }, + bw: is_bw(s).then(|| s.bw_mix.bands().map(|v| (v / 100.0) as f32)), + grading: (!g.is_neutral()).then(|| { + ( + [wheel(&g.shadows), wheel(&g.midtones), wheel(&g.highlights), wheel(&g.global)], + (g.blending / 100.0) as f32, + (g.balance / 100.0) as f32, + ) + }), + skin: oklch_hue_of_srgb_hue(25.0), + } + } + + pub fn is_identity(&self) -> bool { + self.vibrance == 0.0 && self.saturation == 0.0 && !self.mixer && self.points.is_empty() && self.bw.is_none() && self.grading.is_none() + } + + /// `local_sat` (−1..1) and `local_hue` (radians) come from masks. + #[inline] + pub fn apply(&self, rgb: [f32; 3], local_sat: f32, local_hue: f32) -> [f32; 3] { + if self.is_identity() && local_sat == 0.0 && local_hue == 0.0 { + return rgb; + } + let lab = oklab_from_2020(rgb); + // only chroma changes (vibrance / saturation, maybe grading): scale a, b directly — the same + // result as the OkLCh round trip without its sin / cos (and atan2 unless vibrance needs the hue) + if !self.mixer && self.points.is_empty() && self.bw.is_none() && local_hue == 0.0 { + let mut lab = lab; + let c0 = (lab[1] * lab[1] + lab[2] * lab[2]).sqrt(); + let mut c = c0; + if self.vibrance != 0.0 { + let low = 1.0 - (c / 0.22).clamp(0.0, 1.0); + let skin = if self.vibrance > 0.0 { 1.0 - 0.6 * (-(wrap(lab[2].atan2(lab[1]) - self.skin) / 0.35).powi(2)).exp() } else { 1.0 }; + c *= (1.0 + self.vibrance * low * low * skin * 1.2).max(0.0); + } + if self.saturation != 0.0 || local_sat != 0.0 { + c *= (1.0 + self.saturation + local_sat).max(0.0); + } + if c0 > 0.0 { + let k = c / c0; + lab[1] *= k; + lab[2] *= k; + } + return self.grade(lab); + } + let [mut l, mut c, mut h] = lab_to_lch(lab); + if self.mixer { + let w = band_weights(h); + let (mut dh, mut ds, mut dl) = (0.0, 0.0, 0.0); + for i in 0..8 { + dh += w[i] * self.hue[i]; + ds += w[i] * self.sat[i]; + dl += w[i] * self.lum[i]; + } + let chroma_w = (c / 0.12).min(1.0); + h += dh * chroma_w; + c *= (1.0 + ds).max(0.0); + l += dl * chroma_w * l.max(0.05).sqrt(); + } + for p in &self.points { + [l, c, h] = p.apply([l, c, h]); + } + if self.vibrance != 0.0 { + let low = 1.0 - (c / 0.22).clamp(0.0, 1.0); + let skin = if self.vibrance > 0.0 { 1.0 - 0.6 * (-(wrap(h - self.skin) / 0.35).powi(2)).exp() } else { 1.0 }; + c *= (1.0 + self.vibrance * low * low * skin * 1.2).max(0.0); + } + if self.saturation != 0.0 || local_sat != 0.0 { + c *= (1.0 + self.saturation + local_sat).max(0.0); + } + h += local_hue; + if let Some(bw) = &self.bw { + let w = band_weights(h); + let mix: f32 = (0..8).map(|i| w[i] * bw[i]).sum(); + l = (l + mix * (c / 0.2).min(1.0) * 0.25).max(0.0); + c = 0.0; + } + self.grade(lch_to_lab([l, c, h])) + } + + /// Colour grading on OkLab, then back to linear Rec.2020. + #[inline] + fn grade(&self, mut lab: [f32; 3]) -> [f32; 3] { + if let Some((wheels, blending, balance)) = &self.grading { + let m = 0.5 - balance * 0.25; + let width = 0.15 + blending * 0.5; + let ws = 1.0 - smooth(m - width, m + width * 0.25, lab[0]); + let wh = smooth(m - width * 0.25, m + width, lab[0]); + let wm = (1.0 - ws - wh).max(0.0); + for (k, wt) in wheels.iter().zip([ws, wm, wh, 1.0]) { + lab[1] += k.a * wt; + lab[2] += k.b * wt; + lab[0] += k.lum * wt; + } + } + oklab_to_2020(lab) + } +} + +/// Hue rotation (OkLCh radians) of a calibration primary at ±100. +pub const CALIB_HUE: f32 = 0.5; +/// Chroma scale of a calibration primary at ±100 (`1 ± CALIB_SAT`). +pub const CALIB_SAT: f32 = 0.6; + +/// The calibration panel's primaries as a white-preserving 3×3 matrix on linear Rec.2020 (row-major): +/// each primary is rotated in OkLCh hue and scaled in chroma at constant OkLab lightness, then the +/// columns are rescaled so that neutral (1, 1, 1) maps to itself. `None` when neutral. +pub fn calibration_matrix(c: &Calibration) -> Option<[[f32; 3]; 3]> { + let prim = c.primaries(); + if prim.iter().all(|(h, s)| *h == 0.0 && *s == 0.0) { + return None; + } + let mut p = [[0.0f64; 3]; 3]; + for (i, (hue, sat)) in prim.iter().enumerate() { + let mut e = [0.0f32; 3]; + e[i] = 1.0; + let [l, ch, h] = lab_to_lch(oklab_from_2020(e)); + let h2 = h + (hue.clamp(-100.0, 100.0) / 100.0) as f32 * CALIB_HUE; + let c2 = ch * (1.0 + (sat.clamp(-100.0, 100.0) / 100.0) as f32 * CALIB_SAT); + let q = oklab_to_2020(lch_to_lab([l, c2, h2])); + for (r, row) in p.iter_mut().enumerate() { + row[i] = q[r] as f64; + } + } + let m = Mat3(p); + let k = m.inverse()?.apply([1.0, 1.0, 1.0]); + Some(std::array::from_fn(|r| std::array::from_fn(|col| (p[r][col] * k[col]) as f32))) +} + +/// Shadows-tint strength at ±100: the green channel's relative change in deep shadows. +pub const SHADOW_TINT: f32 = 0.3; + +/// Calibration in scene-linear light (before tone mapping): the primaries matrix, then the shadows +/// tint (green ↔ magenta, weighted towards dark tones, luminance kept). Skip tint when either +/// luminance is nonpositive so negative scene-linear samples cannot be inverted or amplified. +#[inline] +pub fn calibrate(c: [f32; 3], m: Option<&[[f32; 3]; 3]>, shadow_tint: f32) -> [f32; 3] { + let mut c = c; + if let Some(m) = m { + c = std::array::from_fn(|r| (m[r][0] * c[0] + m[r][1] * c[1] + m[r][2] * c[2]).max(0.0)); + } + if shadow_tint != 0.0 { + let y0 = luminance_2020(c); + if y0 > 0.0 { + let w = 1.0 - smooth(-5.0, -0.5, (y0.max(1e-7) / 0.18).log2()); + let tinted = [c[0], c[1] * (1.0 - SHADOW_TINT * shadow_tint * w).max(0.0), c[2]]; + let y1 = luminance_2020(tinted); + if y1 > 0.0 { + c = tinted.map(|v| v * y0 / y1.max(1e-9)); + } + } + } + c +} + +#[inline] +fn smooth(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_color_transform::oklab::lab_to_lch; + + #[test] + fn weights_partition_unity() { + for i in 0..360 { + let h = (i as f32).to_radians() - PI; + let w = band_weights(h); + let s: f32 = w.iter().sum(); + assert!((s - 1.0).abs() < 1e-4, "{i}: {s}"); + } + // at a band centre, that band dominates + let w = band_weights(band_hues()[5]); + assert!(w[5] > 0.99); + } + + #[test] + fn neutral_is_identity() { + let ops = ColorOps::new(&DevelopSettings::default()); + assert!(ops.is_identity()); + assert_eq!(ops.apply([0.2, 0.3, 0.4], 0.0, 0.0), [0.2, 0.3, 0.4]); + } + + #[test] + fn saturation_and_bw() { + let mut s = DevelopSettings::default(); + s.color.saturation = -100.0; + let g = ColorOps::new(&s).apply([0.4, 0.1, 0.05], 0.0, 0.0); + assert!((g[0] - g[1]).abs() < 1e-3 && (g[1] - g[2]).abs() < 1e-3, "{g:?}"); + let mut s = DevelopSettings { treatment: Treatment::Bw, ..Default::default() }; + let ops = ColorOps::new(&s); + let b = ops.apply([0.05, 0.1, 0.5], 0.0, 0.0); + assert!((b[0] - b[2]).abs() < 1e-3); + // raising blue in the B&W mix brightens blue things + s.bw_mix.blue = 80.0; + let b2 = ColorOps::new(&s).apply([0.05, 0.1, 0.5], 0.0, 0.0); + assert!(b2[1] > b[1]); + } + + #[test] + fn mixer_targets_its_band() { + let mut s = DevelopSettings::default(); + s.mixer.blue.sat = -100.0; + let ops = ColorOps::new(&s); + let blue = [0.02, 0.05, 0.4]; + let red = [0.4, 0.03, 0.02]; + let cb = lab_to_lch(oklab_from_2020(ops.apply(blue, 0.0, 0.0)))[1]; + let cr0 = lab_to_lch(oklab_from_2020(red))[1]; + let cr = lab_to_lch(oklab_from_2020(ops.apply(red, 0.0, 0.0)))[1]; + assert!(cb < 0.02, "{cb}"); + assert!((cr - cr0).abs() < 0.01); + } + + #[test] + fn calibration_keeps_white_and_moves_primaries() { + assert!(calibration_matrix(&Calibration::default()).is_none()); + let cal = Calibration { red_hue: 60.0, blue_sat: -50.0, ..Default::default() }; + let m = calibration_matrix(&cal).unwrap(); + let grey = calibrate([0.3, 0.3, 0.3], Some(&m), 0.0); + assert!(grey.iter().all(|v| (v - 0.3).abs() < 1e-4), "{grey:?}"); + // red rotates in hue, blue loses chroma + let red = [0.4, 0.05, 0.03]; + let h0 = lab_to_lch(oklab_from_2020(red))[2]; + let h1 = lab_to_lch(oklab_from_2020(calibrate(red, Some(&m), 0.0)))[2]; + assert!(h1 - h0 > 0.05, "{h0} -> {h1}"); + let blue = [0.03, 0.05, 0.4]; + let c0 = lab_to_lch(oklab_from_2020(blue))[1]; + let c1 = lab_to_lch(oklab_from_2020(calibrate(blue, Some(&m), 0.0)))[1]; + assert!(c1 < c0 * 0.97, "{c0} -> {c1}"); + } + + #[test] + fn shadow_tint_targets_shadows() { + let dark = calibrate([0.01, 0.01, 0.01], None, 1.0); + let bright = calibrate([0.8, 0.8, 0.8], None, 1.0); + assert!(dark[1] < dark[0] * 0.85, "magenta shadows: {dark:?}"); + assert!((bright[1] - bright[0]).abs() < 1e-3, "{bright:?}"); + let y = |c: [f32; 3]| luminance_2020(c); + assert!((y(dark) - 0.01).abs() < 1e-5); + let green = calibrate([0.01, 0.01, 0.01], None, -1.0); + assert!(green[1] > green[0]); + } + + #[test] + fn shadow_tint_skips_nonpositive_luminance_before_or_after_tint() { + let negative = [-0.01; 3]; + assert_eq!(calibrate(negative, None, 1.0), negative); + + // Positive before adjustment, negative after a full green reduction. + let mixed = [-0.006, 0.003, 0.0]; + assert!(luminance_2020(mixed) > 0.0); + assert!(luminance_2020([mixed[0], mixed[1] * 0.7, mixed[2]]) < 0.0); + assert_eq!(calibrate(mixed, None, 1.0), mixed); + } + + #[test] + fn hue_anchors_match_f64_matrix_accumulation() { + let matrix = SRGB.to_space(&REC2020).0; + for deg in (0..360).map(f64::from).chain(MIXER_HUES) { + let lin = hsv_to_rgb(deg as f32, 1.0, 1.0).map(srgb_to_linear).map(f64::from); + let rec = matrix.map(|r| (r[0] * lin[0] + r[1] * lin[1] + r[2] * lin[2]) as f32); + assert_eq!(oklch_hue_of_srgb_hue(deg), lab_to_lch(oklab_from_2020(rec))[2], "hue {deg}"); + } + } + + #[test] + fn point_color_targets_its_range() { + let skin = [0.35, 0.16, 0.09]; + let [l, c, h] = lab_to_lch(oklab_from_2020(skin)); + let sample = + PointColor { lum: l as f64, chroma: c as f64, hue: (h as f64).to_degrees(), hue_shift: 60.0, sat_shift: -50.0, ..Default::default() }; + let mut s = DevelopSettings::default(); + s.point_colors.push(sample); + let ops = ColorOps::new(&s); + let out = lab_to_lch(oklab_from_2020(ops.apply(skin, 0.0, 0.0))); + assert!(out[1] < c * 0.7, "chroma {c} -> {}", out[1]); + assert!(wrap(out[2] - h) > 0.2, "hue {h} -> {}", out[2]); + // far colours are untouched + for far in [[0.02, 0.05, 0.4], [0.05, 0.3, 0.05], [0.3, 0.3, 0.3]] { + let o = ops.apply(far, 0.0, 0.0); + assert!(far.iter().zip(&o).all(|(a, b)| (a - b).abs() < 1e-4), "{far:?} -> {o:?}"); + } + // weight: 1 at the sample, falling to 0 outside the range; a wider range reaches further + let k = PointK::new(&sample); + assert!((k.weight(l, c, h) - 1.0).abs() < 1e-6); + assert_eq!(k.weight(l, c, h + 1.0), 0.0); + let wide = PointK::new(&PointColor { range: 100.0, ..sample }); + assert!(wide.weight(l, c, h + 0.45) > k.weight(l, c, h + 0.45)); + } + + #[test] + fn point_color_variance_compresses_towards_the_sample() { + let p = PointColor { lum: 0.6, chroma: 0.1, hue: 40.0, variance: -100.0, range: 100.0, ..Default::default() }; + let k = PointK::new(&p); + let (h0, near) = (40f32.to_radians(), 40f32.to_radians() + 0.1); + let o = k.apply([0.62, 0.11, near]); + assert!((o[2] - h0).abs() < 0.1 && (o[1] - 0.1).abs() < 0.01 && (o[0] - 0.6).abs() < 0.02, "{o:?}"); + let k = PointK::new(&PointColor { variance: 100.0, ..p }); + let o = k.apply([0.62, 0.11, near]); + assert!(o[2] - h0 > 0.1, "{o:?}"); + } + + #[test] + fn grading_tints_shadows_only() { + let mut s = DevelopSettings::default(); + s.grading.shadows = Wheel { hue: 220.0, sat: 60.0, lum: 0.0 }; + let ops = ColorOps::new(&s); + let dark = ops.apply([0.01, 0.01, 0.01], 0.0, 0.0); + let bright = ops.apply([0.8, 0.8, 0.8], 0.0, 0.0); + assert!(dark[2] > dark[0]); + assert!((bright[2] - bright[0]).abs() < 0.02); + } +} diff --git a/crates/develop/src/crystal.rs b/crates/develop/src/crystal.rs new file mode 100644 index 0000000000..e753549e85 --- /dev/null +++ b/crates/develop/src/crystal.rs @@ -0,0 +1,1093 @@ +//! Crystal-layer film grain, the grain of process V7 and later (`crate::finish::GrainModel`). +//! +//! After the model of Aurélien Pierre, *Stochastic photographic grain synthesis from +//! crystallographic structure simulation* (2023), implemented from the article's description of +//! the method; no code was taken from it or from any implementation. `docs/grain.md` has the +//! method, the calibration and the measurements. +//! +//! - **Emulsion.** A stack of layers. Each layer has one crystal shape (a regular polygon of 3–8 +//! vertices, a random rotation, a log-normal width) and is a Boolean model: Poisson seeds grown +//! into crystals, at the density that leaves half the layer covered ([`FILLING`]). +//! - **Capture.** A point's grain is the number of layers covering it, less its mean: many +//! independent layers of different crystal sizes give dense, soft, cloudy grain. +//! - **Print.** The light a point captures is proportional to the light falling on it, and the +//! print shows less grain towards paper white: the grain is `Y·(1 − Y)` in linear light, so +//! it fades out at black and at white. It is added in the display-encoded domain (first order), +//! where it is symmetric: it neither darkens shadows nor greys blown highlights. +//! +//! **Resolution independence.** The emulsion is drawn once per setting on two periodic tiles +//! (tori) in frame coordinates, at twice the resolution of a 6000 px export ([`PITCH`]). Each +//! output pixel takes the exact mean of the emulsion under its footprint from the tiles' summed +//! area tables (a rotated frame's pixel: of an axis-aligned square of its size), so a preview +//! shows exactly the export's grain box-downscaled to its size, and an +//! export larger than 6000 px still has crystals rather than enlarged pixels. The layers are +//! split between two tori of different sizes ([`TORI`]); their pattern only repeats as a whole +//! after tens of thousands of pixels. +//! +//! **Cost.** Drawing the tiles takes a few milliseconds and is cached per setting +//! ([`CrystalGrain::new`]); a pixel then costs two box sums (16 table reads), on the CPU and in the +//! GPU kernel (`finish.wgsl`, which reads the same tables). + +use std::f64::consts::TAU; +use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError}; + +use crate::raster::par_rows; +use craft_color::srgb_to_linear; +use craft_develop_model::Grain; + +/// Long edge (output pixels) at which grain sizes and strengths are specified: a 24 MP export. +pub const REF_LONG: f64 = 6000.0; +/// Size of a tile pixel in reference pixels: tiles are drawn at twice the reference resolution. +pub const PITCH: f64 = 0.5; +/// Tile pixels per long edge of the frame. +pub const TILE_PER_LONG: f64 = REF_LONG / PITCH; +/// Sides of the two tori (tile pixels: 640 and 567 reference pixels). Layers alternate between +/// them; the sizes share no small factor, so the sum repeats only after 362,880 reference pixels. +pub const TORI: [usize; 2] = [1280, 1134]; +/// Fraction of each layer covered by its crystals. +pub const FILLING: f64 = 0.5; +/// Rows per band when drawing a tile (each band is drawn in parallel). +const BAND: usize = 64; +/// Encoded luminance at which the strength is specified (mid grey, 128 of 255). +const MID_GREY: f32 = 128.0 / 255.0; +/// A footprint this large (tile pixels: a render 24 px long or less) gets no grain. +const MAX_FOOTPRINT: f32 = 500.0; +/// Settings whose tiles are kept (a preview and an export, a few thumbnails). +const CACHE: usize = 4; + +/// The look of a grain setting: what the tiles are drawn from. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CrystalLook { + /// Median crystal width (circumscribed diameter, reference pixels). + pub width: f64, + /// Log standard deviation of the layers' crystal widths. + pub spread: f64, + /// Number of layers. + pub layers: usize, +} + +/// Piecewise-linear interpolation through `(x, y)` knots sorted by `x`, constant outside them. +fn interp(knots: &[(f64, f64)], x: f64) -> f64 { + let (Some(first), Some(last)) = (knots.first(), knots.last()) else { return 0.0 }; + if x <= first.0 { + return first.1; + } + for w in knots.windows(2) { + if let [(x0, y0), (x1, y1)] = *w + && x <= x1 + { + return y0 + (y1 - y0) * (x - x0) / (x1 - x0).max(1e-9); + } + } + last.1 +} + +/// Median crystal width at Roughness 50 by Size (reference pixels), fitted so the grain's width +/// matches Lightroom Classic's (`fit_widths`, `docs/grain.md`). Size 0 is as fine as the model +/// gets: crystals narrower than a pixel, uncorrelated pixels. +const WIDTH_BY_SIZE: [(f64, f64); 6] = [(0.0, 0.55), (10.0, 1.39), (25.0, 2.95), (50.0, 5.17), (75.0, 8.78), (100.0, 12.38)]; +/// Width factor by Roughness. +const WIDTH_BY_ROUGHNESS: [(f64, f64); 3] = [(0.0, 0.734), (50.0, 1.0), (100.0, 1.422)]; +/// Layers by Size: coarser grain averages more layers, so it stays a soft clump texture. +const LAYERS_BY_SIZE: [(f64, f64); 4] = [(0.0, 16.0), (25.0, 31.0), (50.0, 54.0), (100.0, 70.0)]; + +/// Log-width spread every look has on top of Roughness's. The look the tables were chosen from (a +/// prototype on whole-pixel crystals, `docs/grain.md`) rounded crystal widths to whole pixels, +/// which spreads their sizes by about this much; with it, the anti-aliased crystals here have the +/// prototype's texture at every scale, not just its width. +const SPREAD_FLOOR: f64 = 0.45; + +/// A slider value as a number in `0..=100`; `fallback` for NaN. +fn slider(v: f64, fallback: f64) -> f64 { + if v.is_nan() { fallback } else { v.clamp(0.0, 100.0) } +} + +impl CrystalLook { + pub fn new(size: f64, roughness: f64) -> CrystalLook { + let (s, r) = (slider(size, 25.0), slider(roughness, 50.0)); + CrystalLook { + width: interp(&WIDTH_BY_SIZE, s) * interp(&WIDTH_BY_ROUGHNESS, r), + spread: (0.1 + 0.6 * r / 100.0).hypot(SPREAD_FLOOR), + layers: interp(&LAYERS_BY_SIZE, s).round().clamp(2.0, 120.0) as usize, + } + } +} + +/// Grain strength (8-bit levels at mid grey on a 6000 px export) for Amount, Size and Roughness, +/// measured on Lightroom Classic exports (the fit of open PR #1060's `docs/grain.md`). +pub fn strength_levels(amount: f64, size: f64, roughness: f64) -> f64 { + let (s, d) = (slider(size, 25.0), slider(roughness, 50.0) / 100.0 - 0.5); + slider(amount, 0.0) / 100.0 * (2.447 + 1.386 * (-s / 19.88).exp()).exp() * (1.0 - 0.084 * d + 1.6384 * d * d) +} + +// ---- hashing + +#[inline] +fn mix(mut x: u32) -> u32 { + x ^= x >> 16; + x = x.wrapping_mul(0x7feb_352d); + x ^= x >> 15; + x = x.wrapping_mul(0x846c_a68b); + x ^ (x >> 16) +} + +#[inline] +fn hash(a: u32, b: u32, c: u32, d: u32) -> u32 { + mix(mix(mix(mix(a ^ 0x9e37_79b9) ^ b) ^ c.wrapping_mul(0x85eb_ca6b)) ^ d.wrapping_mul(0xc2b2_ae35)) +} + +/// A hash as a number in (0, 1]. +#[inline] +fn unit(h: u32) -> f64 { + (h as f64 + 0.5) / 4_294_967_296.0 +} + +/// The standard normal quantile of `p` in (0, 1) (Acklam's rational approximation, ~1e-9). +fn normal_quantile(p: f64) -> f64 { + const A: [f64; 6] = + [-39.696_830_286_653_76, 220.946_098_424_520_5, -275.928_510_446_968_7, 138.357_751_867_269, -30.664_798_066_147_16, 2.506_628_277_459_239]; + const B: [f64; 5] = [-54.476_098_798_224_06, 161.585_836_858_040_9, -155.698_979_859_886_6, 66.801_311_887_719_72, -13.280_681_552_885_72]; + const C: [f64; 6] = [ + -0.007_784_894_002_430_293, + -0.322_396_458_041_136_5, + -2.400_758_277_161_838, + -2.549_732_539_343_734, + 4.374_664_141_464_968, + 2.938_163_982_698_783, + ]; + const D: [f64; 4] = [0.007_784_695_709_041_462, 0.322_467_129_070_039_8, 2.445_134_137_142_996, 3.754_408_661_907_416]; + let p = p.clamp(1e-12, 1.0 - 1e-12); + let tail = + |q: f64| (((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5]) / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0); + if p < 0.024_25 { + tail((-2.0 * p.ln()).sqrt()) + } else if p > 1.0 - 0.024_25 { + -tail((-2.0 * (1.0 - p).ln()).sqrt()) + } else { + let q = p - 0.5; + let r = q * q; + (((((A[0] * r + A[1]) * r + A[2]) * r + A[3]) * r + A[4]) * r + A[5]) * q + / (((((B[0] * r + B[1]) * r + B[2]) * r + B[3]) * r + B[4]) * r + 1.0) + } +} + +/// The emulsion's layers. Their crystal widths are the `layers` quantiles of the log-normal +/// width distribution, dealt to the layers in an order the seed shuffles: every seed has the same +/// mix of sizes (so the same grain width and strength), in a different arrangement. +fn emulsion(seed: u32, look: &CrystalLook) -> Vec { + let n = look.layers.max(1); + let mut order: Vec<(u32, usize)> = (0..n).map(|l| (hash(seed, l as u32, 0x5047, 0), l)).collect(); + order.sort_unstable(); + let mut rank = vec![0usize; n]; + for (r, &(_, l)) in order.iter().enumerate() { + if let Some(slot) = rank.get_mut(l) { + *slot = r; + } + } + (0..n).map(|l| Layer::new(seed, l as u32, look, normal_quantile((rank.get(l).copied().unwrap_or(0) as f64 + 0.5) / n as f64))).collect() +} + +fn normal(h1: u32, h2: u32) -> f64 { + (-2.0 * unit(h1).ln()).sqrt() * (TAU * unit(h2)).cos() +} + +/// The cumulative distribution of a Poisson count of mean `mu`, up to where it reaches 1 (at +/// most 512 entries; `mu` stays below ~150 here). +fn poisson_cdf(mu: f64) -> Vec { + let mut cdf = Vec::new(); + let mut p = (-mu).exp(); + let mut cum = p; + for k in 1..512u32 { + cdf.push(cum); + if cum >= 1.0 - 1e-12 { + break; + } + p *= mu / k as f64; + cum += p; + } + cdf +} + +/// A Poisson count drawn from its `cdf` by hash `h`. +#[inline] +fn poisson(cdf: &[f64], h: u32) -> usize { + let u = unit(h); + cdf.partition_point(|&c| c < u) +} + +// ---- one layer + +/// A stream of hashes: a Weyl sequence through [`mix`]. +struct Stream(u32); + +impl Stream { + #[inline] + fn next(&mut self) -> u32 { + self.0 = self.0.wrapping_add(0x9e37_79b9); + mix(self.0) + } +} + +/// Sub-pixel positions a crystal centre is rounded to, per axis, when drawn from its [`Stamp`]. +const PHASES: usize = 16; +/// Crystals up to this circumradius (tile pixels) are drawn from a stamp. +const STAMP_R: f64 = 16.0; + +/// A layer's crystal rasterised at every sub-pixel phase of its centre: for a centre at +/// `(X + qx/PHASES, Y + qy/PHASES)` (`X`, `Y` integers) it covers rows `Y + rows[qy].0 ..= Y + +/// rows[qy].1`, and in row `Y + rows[qy].0 + k` the pixels `X + o.0 ..= X + o.1`, with +/// `o = spans[(qy·PHASES + qx)·height + k]`. +/// +/// The same rows as bit masks, for drawing a crystal without a branch per row: phase +/// `p = qy·PHASES + qx` spans pixels `X + extent[p].0 ..= X + extent[p].1`, and its row `k` is +/// `masks[p·height + k]` shifted to `X + extent[p].0` (rows past the phase's own are empty). +/// `masks` is empty when a phase is wider than 64 pixels. +#[derive(Clone, Debug)] +struct Stamp { + rows: [(i32, i32); PHASES], + height: usize, + spans: Vec<(i32, i32)>, + extent: Vec<(i32, i32)>, + masks: Vec, +} + +/// Where [`Layer::draw`] draws: rows `y0..y0 + rows` of a torus of side `t`, `w` words per row, +/// after `margin` scratch rows. +#[derive(Clone, Copy)] +struct Band { + t: usize, + y0: usize, + rows: usize, + w: usize, + margin: usize, +} + +/// One emulsion layer: its crystal (a regular polygon) and seed density, in tile pixels. +#[derive(Clone, Debug)] +struct Layer { + /// The crystal as half-planes, relative to its centre: `x ≥ a + s·y` for each `(a, s)` of + /// `left` (`nl` used), `x ≤ a + s·y` for `right` (`nr` used), `y0 ≤ y ≤ y1`. + left: [(f64, f64); 8], + right: [(f64, f64); 8], + nl: usize, + nr: usize, + y0: f64, + y1: f64, + /// Circumradius. + r: f64, + /// Seeds per tile pixel. + lambda: f64, + seed: u32, + index: u32, + stamp: Option, +} + +/// Crystals narrower than this (tile pixels) cover at most two neighbouring pixel centres: their +/// layer is drawn as independent pixels. +const FINE: f64 = 1.5; + +impl Layer { + /// Layer `index` of the emulsion of `seed`, its crystal width `z` log standard deviations + /// from the median. + fn new(seed: u32, index: u32, look: &CrystalLook, z: f64) -> Layer { + let h = |k: u32| hash(seed, index, k, 0x51ed); + let n = (4.5 + normal(h(1), h(2))).round().clamp(3.0, 8.0) as usize; + let rot = TAU * unit(h(3)); + let width = look.width.max(0.05) * (look.spread * z.clamp(-2.5, 2.5)).exp(); + let r = width / 2.0 / PITCH; + let vert = |k: usize| { + let a = rot + TAU * k as f64 / n as f64; + (r * a.cos(), r * a.sin()) + }; + let mut layer = Layer { + left: [(0.0, 0.0); 8], + right: [(0.0, 0.0); 8], + nl: 0, + nr: 0, + y0: f64::INFINITY, + y1: f64::NEG_INFINITY, + r, + lambda: -(1.0 - FILLING).ln() / (0.5 * n as f64 * r * r * (TAU / n as f64).sin()).max(1e-9), + seed, + index, + stamp: None, + }; + for k in 0..n { + let ((x0, y0), (x1, y1)) = (vert(k), vert(k + 1)); + layer.y0 = layer.y0.min(y0); + layer.y1 = layer.y1.max(y0); + let dy = y1 - y0; + if dy.abs() < 1e-12 { + continue; + } + // counter-clockwise: the inside is left of each edge + let sl = (x1 - x0) / dy; + let line = (x0 - sl * y0, sl); + if dy > 0.0 { + if let Some(slot) = layer.right.get_mut(layer.nr) { + *slot = line; + layer.nr += 1; + } + } else if let Some(slot) = layer.left.get_mut(layer.nl) { + *slot = line; + layer.nl += 1; + } + } + if r <= STAMP_R && 2.0 * r >= FINE { + layer.stamp = Some(layer.stamp()); + } + layer + } + + fn stamp(&self) -> Stamp { + let q = PHASES as f64; + let mut rows = [(0, -1); PHASES]; + for (qy, r) in rows.iter_mut().enumerate() { + let g = qy as f64 / q; + *r = ((g + self.y0 - 0.5).ceil() as i32, (g + self.y1 - 0.5).floor() as i32); + } + let height = rows.iter().map(|(a, b)| (b - a + 1).max(0) as usize).max().unwrap_or(0); + let mut spans = vec![(0, -1); PHASES * PHASES * height]; + for (qy, &(a, b)) in rows.iter().enumerate() { + for k in 0..(b - a + 1).max(0) { + let (xl, xr) = self.span((a + k) as f64 + 0.5 - qy as f64 / q); + for qx in 0..PHASES { + let f = qx as f64 / q; + if let Some(o) = spans.get_mut((qy * PHASES + qx) * height + k as usize) { + *o = ((f + xl - 0.5).ceil() as i32, (f + xr - 0.5).floor() as i32); + } + } + } + } + let mut extent = vec![(0, -1); PHASES * PHASES]; + let mut masks = vec![0u64; PHASES * PHASES * height]; + let mut fits = true; + for (p, e) in extent.iter_mut().enumerate() { + let Some(rows) = spans.get(p * height..(p + 1) * height) else { continue }; + let used = || rows.iter().filter(|(o0, o1)| o0 <= o1); + let (Some(lo), Some(hi)) = (used().map(|o| o.0).min(), used().map(|o| o.1).max()) else { continue }; + *e = (lo, hi); + fits &= hi - lo < 64; + for (m, &(o0, o1)) in masks.iter_mut().skip(p * height).zip(rows) { + if o0 <= o1 && o1 - lo < 64 { + *m = (!0u64 >> (63 - (o1 - o0))) << (o0 - lo); + } + } + } + if !fits { + masks.clear(); + } + Stamp { rows, height, spans, extent, masks } + } + + /// The crystal's horizontal extent at height `y` above its centre (convex: one interval). + #[inline] + fn span(&self, y: f64) -> (f64, f64) { + let lo = self.left.iter().take(self.nl).fold(f64::NEG_INFINITY, |m, &(a, s)| m.max(a + s * y)); + let hi = self.right.iter().take(self.nr).fold(f64::INFINITY, |m, &(a, s)| m.min(a + s * y)); + (lo, hi) + } + + /// Sets the bits of the pixels the layer covers in rows `y0..` of a torus of side `t`: + /// `cover` holds whole rows of `w` words (bit `i % 64` of word `i / 64` is pixel `i`), the + /// band's rows between `margin` rows above and below it (scratch: what lands there is not part + /// of the band; `margin` is at least the stamp's height). + fn draw(&self, t: usize, y0: usize, w: usize, margin: usize, cover: &mut [u64]) { + let rows = (cover.len() / w.max(1)).saturating_sub(2 * margin); + if 2.0 * self.r < FINE { + // each pixel covered with probability FILLING (one half: one random bit) + for (j, row) in cover.chunks_mut(w.max(1)).skip(margin).take(rows).enumerate() { + let mut bits = Stream(hash(self.seed, self.index, (y0 + j) as u32, 0xb175)); + for v in row.iter_mut() { + *v = bits.next() as u64 | (bits.next() as u64) << 32; + } + if let (Some(last), r @ 1..=63) = (row.last_mut(), t % 64) { + *last &= (1u64 << r) - 1; + } + } + return; + } + let tf = t as f64; + let m = (tf / (4.0 * self.r).max(16.0)).floor().clamp(1.0, tf) as i64; + let c = tf / m as f64; + let cdf = poisson_cdf(self.lambda * c * c); + let (lo, hi) = (y0 as f64 - self.r - 1.0, (y0 + rows) as f64 + self.r + 1.0); + for cy in (lo / c).floor() as i64..=(hi / c).floor() as i64 { + let wy = cy.rem_euclid(m) as u32; + for cx in 0..m { + let mut h = Stream(hash(self.seed ^ (self.index << 20), cx as u32, wy, 0xce11)); + for _ in 0..poisson(&cdf, h.next()) { + let (u, v) = (unit(h.next()), unit(h.next())); + self.splat((cx as f64 + u) * c, (cy as f64 + v) * c, Band { t, y0, rows, w, margin }, cover); + } + } + } + } + + /// Marks the pixels whose centres the crystal at (`px`, `py`) covers (see [`Self::draw`]). + #[inline] + fn splat(&self, px: f64, py: f64, band: Band, cover: &mut [u64]) { + let Band { t, y0, rows, w, margin } = band; + if let Some(st) = &self.stamp { + let (bx, by) = (px.floor(), py.floor()); + let (qx, qy) = ((((px - bx) * PHASES as f64) as usize).min(PHASES - 1), (((py - by) * PHASES as f64) as usize).min(PHASES - 1)); + let (bx, by) = (bx as i64, by as i64); + let Some(&(a, b)) = st.rows.get(qy) else { return }; + let (lo, hi) = ((by + a as i64).max(y0 as i64), (by + b as i64).min((y0 + rows) as i64 - 1)); + if hi < lo { + return; + } + // within the torus across: the whole stamp, a fixed number of rows of masks (those + // above or below the band land in the margins) + let p = qy * PHASES + qx; + if let (Some(&(e0, e1)), Some(masks)) = (st.extent.get(p), st.masks.get(p * st.height..(p + 1) * st.height)) { + let (xs, top) = (bx + e0 as i64, by + a as i64 - y0 as i64 + margin as i64); + if xs >= 0 && bx + (e1 as i64) < t as i64 && top >= 0 { + let (word, shift) = ((xs >> 6) as usize, (xs & 63) as u32); + // a bit past the row's last word would be a pixel ≥ t: the high word is then 0 + let start = top as usize * w + word; + for (k, &m) in masks.iter().enumerate() { + let v = (m as u128) << shift; + let i = start + k * w; + if let Some(c) = cover.get_mut(i) { + *c |= v as u64; + } + if let Some(c) = cover.get_mut(i + 1) { + *c |= (v >> 64) as u64; + } + } + return; + } + } + // rows `lo..=hi` of the band, spans `k0..` of the stamp's rows (`hi ≤ by + b`: within its height) + let (k0, n) = ((lo - by - a as i64) as usize, (hi - lo + 1) as usize); + let base = (qy * PHASES + qx) * st.height + k0; + let (r0, r1) = (lo as usize - y0 + margin, hi as usize + 1 - y0 + margin); + let (Some(spans), Some(band)) = (st.spans.get(base..base + n), cover.get_mut(r0 * w..r1 * w)) else { return }; + for (row, &(o0, o1)) in band.chunks_exact_mut(w.max(1)).zip(spans) { + if o0 <= o1 { + set_wrapped(row, t, bx + o0 as i64, bx + o1 as i64); + } + } + return; + } + let first = (py + self.y0 - 0.5).ceil().max(y0 as f64); + let last = (py + self.y1 - 0.5).floor().min((y0 + rows) as f64 - 1.0); + if last < first { + return; + } + for j in first as usize..=last as usize { + let (xl, xr) = self.span(j as f64 + 0.5 - py); + let (i0, i1) = ((px + xl - 0.5).ceil() as i64, (px + xr - 0.5).floor() as i64); + if i1 < i0 { + continue; + } + let Some(row) = cover.get_mut((j - y0 + margin) * w..(j - y0 + margin + 1) * w) else { continue }; + set_wrapped(row, t, i0, i1); + } + } +} + +/// Sets bits `a..=b` (`a ≤ b`) of a row of words. +#[inline] +fn set_bits(row: &mut [u64], a: usize, b: usize) { + let (wa, wb) = (a >> 6, b >> 6); + let (lo, hi) = (!0u64 << (a & 63), !0u64 >> (63 - (b & 63))); + if wa == wb { + if let Some(v) = row.get_mut(wa) { + *v |= lo & hi; + } + return; + } + if let Some(v) = row.get_mut(wa) { + *v |= lo; + } + for v in row.iter_mut().take(wb).skip(wa + 1) { + *v = !0; + } + if let Some(v) = row.get_mut(wb) { + *v |= hi; + } +} + +/// Sets pixels `i0..=i1` of a periodic row of `t` pixels (`i0 ≤ i1`, within one period of +/// `0..t`: the crystal centres are in `0..t`). +#[inline] +fn set_wrapped(row: &mut [u64], t: usize, i0: i64, i1: i64) { + let ti = t as i64; + if i0 >= 0 && i1 < ti { + set_bits(row, i0 as usize, i1 as usize); + return; + } + if t == 0 { + return; + } + if i1 - i0 + 1 >= ti { + set_bits(row, 0, t - 1); + return; + } + let (a, b) = if i0 < 0 { + (i0 + ti, i1 + ti) + } else if i0 >= ti { + (i0 - ti, i1 - ti) + } else { + (i0, i1) + }; + let (a, b) = (a.clamp(0, ti - 1) as usize, b.max(0) as usize); + if b < t { + set_bits(row, a, b); + } else { + set_bits(row, a, t - 1); + set_bits(row, 0, (b - t).min(t - 1)); + } +} + +/// Bit planes of the layer counts (enough for 127 layers per torus). +const PLANES: usize = 7; + +/// Adds one layer's `cover` bits to the bit-sliced counters `planes` (`PLANES × cover.len()`). +#[inline] +fn add_layer(planes: &mut [u64], cover: &[u64]) { + let n = cover.len(); + for (i, &c) in cover.iter().enumerate() { + let mut carry = c; + for p in 0..PLANES { + if carry == 0 { + break; + } + let Some(slot) = planes.get_mut(p * n + i) else { break }; + let s = *slot; + *slot = s ^ carry; + carry &= s; + } + } +} + +// ---- tiles + +/// The emulsion drawn on the two tori: each as a summed-area table of its grain (layer count less +/// its mean), scaled so that the sum of both, averaged over a reference pixel, has unit variance. +pub struct CrystalTile { + pub look: CrystalLook, + /// `(side + 1)²` entries each: `sat[t][y·(side + 1) + x]` = sum over `[0, x) × [0, y)`. + pub sats: [Vec; 2], +} + +impl std::fmt::Debug for CrystalTile { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CrystalTile").field("look", &self.look).finish_non_exhaustive() + } +} + +/// Layer counts of torus `which` (side `t`): `t × t`, row-major. +fn draw_torus(which: usize, t: usize, seed: u32, look: &CrystalLook) -> Vec { + let layers: Vec = emulsion(seed, look).into_iter().filter(|l| l.index as usize % 2 == which).collect(); + let w = t.div_ceil(64); + // scratch rows above and below a band, for the stamps' rows outside it (`Layer::splat`) + let margin = layers.iter().filter_map(|l| l.stamp.as_ref().map(|s| s.height)).max().unwrap_or(0); + let mut count = vec![0u8; t * t]; + par_rows(&mut count, t * BAND, |band, out| { + let rows = out.len() / t.max(1); + let n = rows * w; + let (mut cover, mut planes) = (vec![0u64; n + 2 * margin * w], vec![0u64; PLANES * n]); + for layer in &layers { + cover.fill(0); + layer.draw(t, band * BAND, w, margin, &mut cover); + add_layer(&mut planes, cover.get(margin * w..margin * w + n).unwrap_or_default()); + } + for (j, row) in out.chunks_mut(t.max(1)).enumerate() { + for (i, o) in row.iter_mut().enumerate() { + let (word, bit) = (j * w + i / 64, i % 64); + *o = (0..PLANES).fold(0u8, |c, p| c | ((planes.get(p * n + word).map_or(0, |v| (v >> bit) & 1) as u8) << p)); + } + } + }); + count +} + +/// Integer summed-area table of `count` (`t × t`): `(t + 1)²` entries. +fn summed_area(count: &[u8], t: usize) -> Vec { + let s = t + 1; + let mut sat = vec![0u32; s * s]; + // row prefix sums in parallel, then each row adds the one above + par_rows(&mut sat, s, |y, row| { + let Some(src) = y.checked_sub(1).and_then(|y| count.get(y * t..(y + 1) * t)) else { return }; + let mut acc = 0u32; + for (o, &c) in row.iter_mut().skip(1).zip(src) { + acc += c as u32; + *o = acc; + } + }); + for y in 1..s { + let (above, below) = sat.split_at_mut(y * s); + let (Some(prev), Some(row)) = (above.get((y - 1) * s..), below.get_mut(..s)) else { continue }; + for (o, &p) in row.iter_mut().zip(prev) { + *o = o.wrapping_add(p); + } + } + sat +} + +/// Sum over the reference pixels (2 × 2 tile pixels) of torus `count` (`t × t`, `t` even) of +/// their squared deviation from `mean` (per tile pixel), and the number of reference pixels. +fn reference_square_sum(count: &[u8], t: usize, mean: f64) -> (f64, usize) { + let h = t / 2; + let mut rows = vec![0.0f64; h]; + par_rows(&mut rows, 1, |y, out| { + let (Some(a), Some(b)) = (count.get(2 * y * t..(2 * y + 1) * t), count.get((2 * y + 1) * t..(2 * y + 2) * t)) else { return }; + let mut s = 0.0; + for (&[a0, a1], &[b0, b1]) in a.as_chunks::<2>().0.iter().zip(b.as_chunks::<2>().0) { + let q = (a0 as u32 + a1 as u32 + b0 as u32 + b1 as u32) as f64 / 4.0 - mean; + s += q * q; + } + if let Some(o) = out.first_mut() { + *o = s; + } + }); + (rows.iter().sum(), h * h) +} + +impl CrystalTile { + /// Draws the emulsion of `look` with `seed`, or `None` if it has no grain (no variance). + pub fn new(look: CrystalLook, seed: u32) -> Option { + let [t0, t1] = TORI; + let (c0, c1) = crate::raster::par_join(|| draw_torus(0, t0, seed, &look), || draw_torus(1, t1, seed, &look)); + let mut var = 0.0; + let mut tori = Vec::with_capacity(2); + for (count, t) in [(c0, t0), (c1, t1)] { + let mean = count.iter().map(|&c| c as u64).sum::() as f64 / (t * t).max(1) as f64; + let (sq, n) = reference_square_sum(&count, t, mean); + var += sq / n.max(1) as f64; + tori.push((summed_area(&count, t), t, mean)); + } + if !(var > 1e-12 && var.is_finite()) { + return None; + } + let k = 1.0 / var.sqrt(); + let mut sats = tori.into_iter().map(|(sat, t, mean)| { + let s = t + 1; + let mut out = vec![0.0f32; s * s]; + par_rows(&mut out, s, |y, row| { + for (x, (o, &v)) in row.iter_mut().zip(sat.get(y * s..).unwrap_or_default()).enumerate() { + *o = ((v as f64 - mean * (x * y) as f64) * k) as f32; + } + }); + out + }); + Some(CrystalTile { look, sats: [sats.next()?, sats.next()?] }) + } + + /// Sum of torus `which`'s grain over the box `[x0, x0 + w] × [y0, y0 + w]` (tile pixels, + /// `0 ≤ w < side`), the table bilinearly interpolated: the exact integral of the pixels. + #[inline] + fn box_sum(&self, which: usize, x0: f32, y0: f32, w: f32) -> f32 { + let (Some(sat), Some(&t)) = (self.sats.get(which), TORI.get(which)) else { return 0.0 }; + let tf = t as f32; + let (x0, y0) = (x0 - (x0 / tf).floor() * tf, y0 - (y0 / tf).floor() * tf); + let at = |x: f32, y: f32| integral(sat, t, x, y); + at(x0 + w, y0 + w) - at(x0, y0 + w) - at(x0 + w, y0) + at(x0, y0) + } + + /// Mean grain over the square of side `w` centred on (`x`, `y`) (tile pixels): unit variance + /// at `w` = 2 (a 6000 px render). + #[inline] + pub fn field(&self, x: f32, y: f32, w: f32) -> f32 { + let (x0, y0) = (x - 0.5 * w, y - 0.5 * w); + (self.box_sum(0, x0, y0, w) + self.box_sum(1, x0, y0, w)) / (w * w) + } +} + +/// The table `sat` (side `t + 1`) bilinearly interpolated at (`x`, `y`) in `0..=t`. +#[inline] +fn bilinear(sat: &[f32], t: usize, x: f32, y: f32) -> f32 { + let s = t + 1; + let (i, j) = ((x.max(0.0) as usize).min(t - 1), (y.max(0.0) as usize).min(t - 1)); + let (fx, fy) = (x - i as f32, y - j as f32); + let g = |i: usize, j: usize| sat.get(j * s + i).copied().unwrap_or(0.0); + let a = g(i, j) + (g(i + 1, j) - g(i, j)) * fx; + let b = g(i, j + 1) + (g(i + 1, j + 1) - g(i, j + 1)) * fx; + a + (b - a) * fy +} + +/// The periodic grain's integral over `[0, x) × [0, y)` for `x`, `y` in `0..2t`. +#[inline] +fn integral(sat: &[f32], t: usize, x: f32, y: f32) -> f32 { + let tf = t as f32; + let (wx, wy) = (x >= tf, y >= tf); + let (rx, ry) = (if wx { x - tf } else { x }, if wy { y - tf } else { y }); + let mut v = bilinear(sat, t, rx, ry); + if wx { + v += bilinear(sat, t, tf, ry); + } + if wy { + v += bilinear(sat, t, rx, tf); + } + if wx && wy { + v += bilinear(sat, t, tf, tf); + } + v +} + +/// The integral of torus `sat` (side `t`) over `[0, i) × [0, across)` (`along_x`) or +/// `[0, across) × [0, i)`, for `i` in `0..=t`: the table cut along a line, with the periodic part +/// of `across` folded in (`across` in `0..2t`). +fn line(sat: &[f32], t: usize, along_x: bool, across: f32, out: &mut Vec) { + let (tf, n) = (t as f32, t + 1); + let wrap = across >= tf; + let a = (if wrap { across - tf } else { across }).clamp(0.0, tf); + let j = (a as usize).min(t.saturating_sub(1)); + let f = (a - j as f32) as f64; + out.clear(); + out.resize(n, 0.0); + // entry `i` of table line `k` (a row when cutting along x, a column when along y) + let at = |k: usize, i: usize| if along_x { sat.get(k * n + i) } else { sat.get(i * n + k) }.copied().unwrap_or(0.0) as f64; + for (i, o) in out.iter_mut().enumerate() { + let (p, q) = (at(j, i), at(j + 1, i)); + *o = p + (q - p) * f + if wrap { at(t, i) } else { 0.0 }; + } +} + +/// [`line`] interpolated at `x ≥ 0` (any number of periods along). +#[inline] +fn along(line: &[f64], t: usize, inv_t: f64, x: f64) -> f64 { + let tf = t as f64; + let q = (x * inv_t).floor().max(0.0); + let r = (x - q * tf).clamp(0.0, tf); + let i = (r as usize).min(t.saturating_sub(1)); + let f = r - i as f64; + let (Some(&a), Some(&b), Some(&end)) = (line.get(i), line.get(i + 1), line.get(t)) else { return 0.0 }; + a + (b - a) * f + q * end +} + +impl CrystalTile { + /// The grain of a line of `out.len()` output pixels side by side, each a square of side `w` + /// (tile pixels), the first centred on (`x`, `y`), the next `step` (`±w`) along x (`along_x`) + /// or y. The table is cut once along the line's two box edges; each pixel then costs one + /// interpolation per torus instead of [`Self::field`]'s eight table lookups. + pub fn row_field(&self, x: f32, y: f32, w: f32, step: f32, along_x: bool, out: &mut [f32]) { + out.fill(0.0); + let n = out.len(); + let (pos, across) = if along_x { (x, y) } else { (y, x) }; + let sign = if step < 0.0 { -1.0 } else { 1.0 }; + let first = pos as f64 - 0.5 * step as f64; + let lowest = first.min(first + n as f64 * step as f64); + let (mut near, mut far) = (Vec::new(), Vec::new()); + for (which, &t) in TORI.iter().enumerate() { + let Some(sat) = self.sats.get(which) else { continue }; + let tf = t as f32; + let lo = across - 0.5 * w; + let lo = lo - (lo / tf).floor() * tf; + line(sat, t, along_x, lo, &mut near); + line(sat, t, along_x, lo + w, &mut far); + let shift = (lowest / t as f64).floor() * t as f64; + let inv_t = 1.0 / t as f64; + let edge = |k: usize| { + let e = first + k as f64 * step as f64 - shift; + along(&far, t, inv_t, e) - along(&near, t, inv_t, e) + }; + let mut prev = edge(0); + for (k, o) in out.iter_mut().enumerate() { + let next = edge(k + 1); + *o += (sign * (next - prev)) as f32; + prev = next; + } + } + let area = w * w; + out.iter_mut().for_each(|v| *v /= area); + } +} + +// ---- the render's grain + +/// The crystal grain of one render. +#[derive(Clone, Debug)] +pub struct CrystalGrain { + pub tile: Arc, + /// Encoded-luminance amplitude at unit field and unit tone weight. + pub k: f32, + /// An output pixel's side in tile pixels. + pub foot: f32, +} + +type Key = (u64, u64, u32); + +/// The cache key of the tile of `look` and `seed`. +fn key_of(look: CrystalLook, seed: u32) -> Key { + (look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed) +} +/// Recently drawn tiles (the most recent last). +type Cache = Mutex)>>; +static TILES: Cache = Mutex::new(Vec::new()); + +/// The tile being drawn in the background for a drag ([`tile`]): one at a time. +static DRAWING: Mutex> = Mutex::new(None); + +/// The tile a drawing hands to the renders waiting for it, set when it is drawn. +type Slot = Arc>>; + +/// The tiles being drawn, by cache and key, and the condition their drawers signal when done: a +/// render that misses a tile another is drawing waits for it rather than drawing it again. The +/// drawer hands the tile over in its slot, so the waiters get it even if the cache has evicted it +/// by the time they wake. +static IN_FLIGHT: Mutex> = Mutex::new(Vec::new()); +static DRAWN: Condvar = Condvar::new(); + +/// Marks a tile drawn (or failed) when dropped and wakes the renders waiting for it. +struct Drawing { + id: (usize, Key), + done: Slot, +} + +impl Drawing { + /// Registers the draw of `id` in `busy` (the locked [`IN_FLIGHT`]). + fn register(busy: &mut Vec<((usize, Key), Slot)>, id: (usize, Key)) -> Drawing { + let done = Slot::default(); + busy.push((id, done.clone())); + Drawing { id, done } + } + + /// Hands `t` to the renders waiting for it (they wake when this is dropped). + fn finish(&self, t: &Arc) { + // (already set: only the first tile counts, and every drawing draws the same one) + let _ = self.done.set(t.clone()); + } +} + +impl Drop for Drawing { + fn drop(&mut self) { + IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| *d != self.id); + DRAWN.notify_all(); + } +} + +/// Registers the tile of `id` as being drawn, or `None` if another thread is drawing it. +fn start_drawing(id: (usize, Key)) -> Option { + let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); + if busy.iter().any(|(d, _)| *d == id) { + return None; + } + Some(Drawing::register(&mut busy, id)) +} + +/// The tile of `key` in `cache`. +fn cached(cache: &Cache, key: Key) -> Option> { + let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); + tiles.iter().find(|(k, _)| *k == key).map(|(_, t)| t.clone()) +} + +/// The tile of `look` and `seed`, drawn or from the cache. Unless `wait`, a tile not drawn yet +/// is drawn in the background and the last one drawn for `seed` stands in for it meanwhile: a +/// Size or Roughness drag doesn't wait for every step's tile (tens of milliseconds on a slow +/// CPU), and the full-quality render when it ends waits for the exact one. With no tile cached +/// for `seed` nothing can stand in, so even without `wait` this waits for a draw already running +/// or draws the tile. +fn tile(look: CrystalLook, seed: u32, wait: bool) -> Option> { + tile_in(&TILES, look, seed, wait) +} + +/// [`tile`] with the tiles cached in `cache` (a test's own, which other tests can't evict from). +fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> Option> { + let key = key_of(look, seed); + { + let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((_, t)) = tiles.iter().find(|(k, _)| *k == key) { + return Some(t.clone()); + } + // (wasm has no threads to draw on) + if !wait + && !cfg!(target_arch = "wasm32") + && let Some((_, stand_in)) = tiles.iter().rev().find(|(k, _)| k.2 == seed) + { + let stand_in = stand_in.clone(); + drop(tiles); + draw_in_background(cache, key, look, seed); + return Some(stand_in); + } + } + let id = (std::ptr::from_ref(cache) as usize, key); + // a pool worker draws the tile itself: blocked, it could hold up the drawing it waits for + // (its stack may carry a part of that drawing's parallel work); wasm has no other threads + #[cfg(not(target_arch = "wasm32"))] + let on_worker = rayon::current_thread_index().is_some(); + #[cfg(target_arch = "wasm32")] + let on_worker = true; + let drawing = if !on_worker { + // checked, waited for and registered under one lock: two renders that miss the tile + // together can't both find it neither cached nor being drawn (`cached` takes the cache's + // lock under this one; nothing takes them the other way round) + let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); + let mut waited_for: Option = None; + loop { + if let Some(t) = waited_for.as_ref().and_then(|done| done.get().cloned()).or_else(|| cached(cache, key)) { + return Some(t); + } + let Some((_, done)) = busy.iter().find(|(d, _)| *d == id) else { break }; + waited_for = Some(done.clone()); + busy = DRAWN.wait(busy).unwrap_or_else(PoisonError::into_inner); + } + Some(Drawing::register(&mut busy, id)) + } else { + start_drawing(id) + }; + #[cfg(test)] + if let Some(d) = &drawing { + tests::hold_for_waiters(d); + } + let t = Arc::new(CrystalTile::new(look, seed)?); + if let Some(d) = &drawing { + d.finish(&t); + } + keep(cache, key, t.clone()); + #[cfg(test)] + if let Some(d) = &drawing { + tests::evict_before_waking(cache, d); + } + Some(t) +} + +/// Adds `t` to `cache` (the most recent last). +fn keep(cache: &Cache, key: Key, t: Arc) { + let mut tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); + tiles.retain(|(k, _)| *k != key); + if tiles.len() >= CACHE { + tiles.remove(0); + } + tiles.push((key, t)); +} + +/// Draws the tile of `key` on the thread pool unless another is being drawn (the next render +/// asks again for what it needs then). +fn draw_in_background(cache: &'static Cache, key: Key, look: CrystalLook, seed: u32) { + let marker = { + let mut drawing = DRAWING.lock().unwrap_or_else(PoisonError::into_inner); + if drawing.is_some() { + return; + } + // (`None`: a render is drawing it already) + let Some(marker) = start_drawing((std::ptr::from_ref(cache) as usize, key)) else { return }; + *drawing = Some(key); + marker + }; + spawn_in_background(move || { + if let Some(t) = CrystalTile::new(look, seed) { + let t = Arc::new(t); + marker.finish(&t); + keep(cache, key, t); + } + drop(marker); + *DRAWING.lock().unwrap_or_else(PoisonError::into_inner) = None; + }); +} + +/// Runs `draw` on the background pool. +#[cfg(not(target_arch = "wasm32"))] +fn spawn_in_background(draw: impl FnOnce() + Send + 'static) { + // on a pool of its own: the renders of the drag don't queue behind its parallel bands + match background_pool() { + Some(pool) => pool.spawn(draw), + None => rayon::spawn(draw), + } +} + +#[cfg(target_arch = "wasm32")] +fn spawn_in_background(draw: impl FnOnce() + Send + 'static) { + draw(); +} + +/// Half the cores, for tiles drawn in the background (`None`: the pool couldn't be made). +#[cfg(not(target_arch = "wasm32"))] +fn background_pool() -> Option<&'static rayon::ThreadPool> { + static POOL: OnceLock> = OnceLock::new(); + POOL.get_or_init(|| { + let n = std::thread::available_parallelism().map_or(2, |n| n.get()).div_ceil(2); + rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("grain-tile-{i}")).build().ok() + }) + .as_ref() +} + +/// The tone weight of an encoded channel value `v` (0..1): `Y·dV/dY` of the sRGB curve, i.e. how +/// much `v` moves when the channel's linear light is scaled. +#[inline] +pub fn lift(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.040_45 { v } else { (v + 0.055) / 2.4 } +} + +/// The tone weight at mid grey (what [`CrystalGrain::k`] is calibrated at). +fn mid_weight() -> f32 { + lift(MID_GREY) * (1.0 - srgb_to_linear(MID_GREY)) +} + +impl CrystalGrain { + /// The grain of `g` at `px_per_long` output pixels per long edge (`None`: no grain). + pub fn new(g: &Grain, px_per_long: f64) -> Option { + Self::with(g, px_per_long, true) + } + + /// [`Self::new`] for a draft render (a drag): while its tile is drawn, the last tile drawn for + /// the same seed stands in for it (see `tile`). + pub fn draft(g: &Grain, px_per_long: f64) -> Option { + Self::with(g, px_per_long, false) + } + + fn with(g: &Grain, px_per_long: f64, wait: bool) -> Option { + let levels = strength_levels(g.amount, g.size, g.roughness); + if !(levels > 0.0 && px_per_long.is_finite() && px_per_long > 0.0) { + return None; + } + let foot = (TILE_PER_LONG / px_per_long) as f32; + if !(foot.is_finite() && foot > 0.0 && foot < MAX_FOOTPRINT) { + return None; + } + let tile = tile(CrystalLook::new(g.size, g.roughness), g.seed, wait)?; + Some(CrystalGrain { tile, k: (levels / 255.0) as f32 / mid_weight(), foot }) + } + + /// Display-encoded colour `e` with grain, at frame position (`gx`, `gy`) (fractions of the + /// frame's long edge): the mean over an axis-aligned square footprint centred there, which + /// for a rotated frame's pixel stands in for its rotated footprint (`docs/grain.md`). + #[inline] + pub fn apply(&self, e: [f32; 3], gx: f32, gy: f32) -> [f32; 3] { + if !(gx.is_finite() && gy.is_finite()) { + return e; + } + let tpl = TILE_PER_LONG as f32; + self.apply_field(e, self.tile.field(gx * tpl, gy * tpl, self.foot)) + } + + /// The grain field of a row of `out.len()` pixels whose first centre is at (`gx`, `gy`) and + /// which step (`dx`, `dy`) (fractions of the long edge), when the step is along x or y (an + /// unrotated frame in any orientation) and the pixels are squares of the render's size + /// (`false` otherwise: use [`Self::apply`] per pixel). + pub fn row(&self, gx: f64, gy: f64, dx: f64, dy: f64, out: &mut [f32]) -> bool { + let tpl = TILE_PER_LONG; + let ((sx, sy), w) = ((dx * tpl, dy * tpl), self.foot as f64); + let (step, along_x) = if sy.abs() <= 1e-6 { + (sx, true) + } else if sx.abs() <= 1e-6 { + (sy, false) + } else { + return false; + }; + if !(gx.is_finite() && gy.is_finite() && step.is_finite()) || (step.abs() - w).abs() > 1e-4 * w { + return false; + } + self.tile.row_field((gx * tpl) as f32, (gy * tpl) as f32, self.foot, step as f32, along_x, out); + true + } + + /// Display-encoded colour `e` with grain field value `g` (see [`CrystalTile::field`]). + #[inline] + pub fn apply_field(&self, e: [f32; 3], g: f32) -> [f32; 3] { + let lum = (0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]).clamp(0.0, 1.0); + let k = self.k * g * (1.0 - srgb_to_linear(lum)); + if !k.is_finite() { + return e; + } + e.map(|v| v + k * lift(v)) + } +} + +#[cfg(test)] +#[path = "tests_crystal.rs"] +mod tests; diff --git a/crates/develop/src/curve.rs b/crates/develop/src/curve.rs index 46b0eef6a7..fd26ad4060 100644 --- a/crates/develop/src/curve.rs +++ b/crates/develop/src/curve.rs @@ -4,6 +4,8 @@ //! separated by three split points. Each region contributes a cosine-windowed bump, summed and //! forced monotone. +pub mod compat; + use crate::color::spline::Lut1; use craft_develop_model::ToneCurve; diff --git a/crates/develop/src/curve/compat.rs b/crates/develop/src/curve/compat.rs new file mode 100644 index 0000000000..d4036e9de2 --- /dev/null +++ b/crates/develop/src/curve/compat.rs @@ -0,0 +1,81 @@ +//! Compatibility operations for projects whose stored adjustments use the Gaussian-region +//! tone curve and unit-slope out-of-range sampling. These are not the newer parametric curve. +//! +//! The formulas came from PhotoCraft's Camera Raw Filter, originally written by Brandon Thomas +//! (storytold/photocraft@aa87012aab6d710b1e1d2ff1654a45e58c09d955). + +/// Compile a four-region curve into a monotonically nondecreasing 0…1 table. +/// +/// `splits` and `amounts` are percentages. Splits are clamped individually to 5…95, not +/// reordered; the amounts are not clamped. Keeps the legacy expression order for stored edits. +/// Returns an empty table if fewer than two samples are requested. +pub fn gaussian_region_lut(splits: [f32; 3], amounts: [f32; 4], len: usize) -> Vec { + if len < 2 { + return Vec::new(); + } + let s = splits.map(|v| v.clamp(5.0, 95.0) / 100.0); + let centres = [s[0] / 2.0, (s[0] + s[1]) / 2.0, (s[1] + s[2]) / 2.0, (s[2] + 1.0) / 2.0]; + let widths = [s[0].max(0.1), (s[1] - s[0]).max(0.1), (s[2] - s[1]).max(0.1), (1.0 - s[2]).max(0.1)]; + let mut lut: Vec = (0..len) + .map(|i| { + let x = i as f32 / (len - 1) as f32; + let mut y = x; + for k in 0..4 { + let d = (x - centres[k]) / (widths[k] * 1.2); + let bump = (-d * d * 2.0).exp() * x * (1.0 - x) * 4.0; + y += amounts[k] / 100.0 * 0.25 * bump; + } + y.clamp(0.0, 1.0) + }) + .collect(); + for i in 1..len { + lut[i] = lut[i].max(lut[i - 1]); + } + lut +} + +/// Interpolate a table on 0…1 and extend its endpoints with slope one outside that interval. +/// Returns the input unchanged for a table with fewer than two entries. +pub fn sample_lut_linear_tails(lut: &[f32], value: f32) -> f32 { + if lut.len() < 2 { + return value; + } + if !(0.0..=1.0).contains(&value) { + return if value < 0.0 { value + lut[0] } else { lut[lut.len() - 1] + (value - 1.0) }; + } + let x = value * (lut.len() - 1) as f32; + let i = (x as usize).min(lut.len() - 2); + let t = x - i as f32; + lut[i] + (lut[i + 1] - lut[i]) * t +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gaussian_region_lut_keeps_legacy_saved_curve_samples() { + // Synthetic saved sliders and five samples captured with the legacy formula; values are + // decimal here because the platform exp implementation can round the last bit differently. + let lut = gaussian_region_lut([90.0, 5.0, 120.0], [-92.0, 64.0, -35.0, 91.0], 5); + let old = [0.0, 0.030_084_822, 0.330_180_67, 0.543_366_2, 1.0]; + assert_eq!(lut.len(), old.len()); + for (&new, old) in lut.iter().zip(old) { + assert!((new - old).abs() <= 1.0e-6, "{new} != {old}"); + } + let crest = gaussian_region_lut([25.0, 50.0, 75.0], [1400.0, 0.0, -1200.0, 0.0], 1024); + assert!(crest.windows(2).all(|pair| pair[0] <= pair[1])); + assert_eq!((crest[0], crest[crest.len() - 1]), (0.0, 1.0)); + assert!(gaussian_region_lut([0.0; 3], [0.0; 4], 1).is_empty()); + } + + #[test] + fn sample_lut_linear_tails_keeps_legacy_signed_and_hdr_values() { + let lut = [0.125_f32, 0.15625, 0.75]; + for (value, old) in [(-0.5_f32, -0.375_f32), (0.0, 0.125), (0.25, 0.140625), (0.5, 0.15625), (0.75, 0.453125), (1.0, 0.75), (1.5, 1.25)] { + assert_eq!(sample_lut_linear_tails(&lut, value).to_bits(), old.to_bits()); + } + assert!(sample_lut_linear_tails(&lut, f32::NAN).is_nan()); + assert_eq!(sample_lut_linear_tails(&[], -0.5), -0.5); + } +} diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index e3099235c2..ce376eddc8 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -3,9 +3,25 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod auto; +pub mod camera_raw; pub mod color; +pub mod colorops; +pub mod crystal; pub mod curve; pub mod finish; pub mod inpaint; +pub mod light_v3; +// generated (`light_v3_params.rs`), kept in its own compact layout +#[rustfmt::skip] +pub mod light_v3_params; +pub mod local; +pub mod local_tone; pub mod lut; +pub mod nrc_joint; +#[cfg(test)] +mod nrc_joint_reference; +pub mod profiles; +pub mod raster; +pub mod sensor; pub mod tone; diff --git a/crates/develop/src/light_v3.rs b/crates/develop/src/light_v3.rs new file mode 100644 index 0000000000..079a716585 --- /dev/null +++ b/crates/develop/src/light_v3.rs @@ -0,0 +1,565 @@ +//! Process V4's Contrast and Blacks on the camera-look path (a raw with its camera's tone +//! curve): pointwise operators fitted to how Lightroom's sliders move a photo's tones, applied +//! after the camera curve with V2 Whites. Method, operator family and the fitted constants' provenance: +//! `docs/light-v3.md`; the constants are in [`crate::light_v3_params`] (generated). +//! +//! Each slider is an operator `F_a` on encoded values `v` (linear ProPhoto RGB, D50, Bradford from +//! the D65 working space, through the sRGB transfer curve), anchored at `F_0` = identity: +//! +//! - `a > 0`: `F_a(v) = v + s(a)·D₊(v)`; `a < 0`: `F_a(v) = max(0, v − s(a)·D₋(v))`, with `D` piecewise +//! linear on 12 fixed knots (`D(1) = 0`, and for Contrast `D(0) = 0`) and the amount law +//! `s(t) = ((1 − e^(−t/τ)) / (1 − e^(−1/τ)))^q`, `t = |a|/100`, one `(τ, q)` per sign; +//! - applied per channel ([`Mode::PerChannel`]), to the encoded ProPhoto luminance with linear RGB +//! scaled by the luminance ratio ([`Mode::Luminance`]), or a blend of the two in linear light +//! ([`Mode::Mix`], one weight per sign). +//! +//! The functions here port `Family.curve`, `Family.apply`, `Family.law` of +//! `fit_pointwise.py` (the fitting tool) exactly; [`Fit::unpack`] is its `Family.unpack`. Each +//! active operator is tabulated once per render ([`LUT_N`] entries over `v` in 0..1, interpolated +//! linearly). High-bit-depth CPU exports and the GPU read these tables ([`LightOps`]); 8-bit CPU +//! renders compose per-channel operations over linear input ([`PreviewOps`]). Luminance operations +//! retain the original evaluation, including any preceding per-channel operation. + +use craft_color_transform::{Mat3, PROPHOTO, REC2020}; +use craft_develop_model::{DevelopSettings, Process}; + +use crate::light_v3_params as fitted; + +/// Entries of an operator's table over encoded `v` in 0..=1. +pub const LUT_N: usize = 1024; + +/// Linear ProPhoto RGB luminance (the Y row of ProPhoto → XYZ D50), as the fit computes it. +pub const PRO_Y: [f32; 3] = [0.288_040_2, 0.711_874_1, 0.000_085_7]; + +/// How an operator is applied to a pixel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// To each encoded ProPhoto channel. + PerChannel, + /// To the encoded ProPhoto luminance; linear RGB is scaled by the luminance ratio. + Luminance, + /// `w·PerChannel + (1 − w)·Luminance` in linear light, with a weight per sign. + Mix, +} + +impl Mode { + /// The GPU kernel's code (`LIGHT_MODE` in `crates/gpu/src/params.rs`). + pub fn code(self) -> u32 { + match self { + Mode::PerChannel => 0, + Mode::Luminance => 1, + Mode::Mix => 2, + } + } +} + +/// One slider's fitted parameters, laid out as `fit_pointwise.py`'s `Family`: 11 values of `D₊` at +/// the knots but the last (`D(1) = 0`), 11 of `D₋`, then `ln τ₊, ln q₊, ln τ₋, ln q₋`, then two mix +/// logits (positive, negative amounts) in [`Mode::Mix`]. +#[derive(Clone, Copy, Debug)] +pub struct Fit { + pub mode: Mode, + /// Contrast moves tones both ways around a pivot: its shapes are anchored at black too (`D(0) = 0`). + pub signed: bool, + pub params: &'static [f64], +} + +const KNOTS_N: usize = fitted::KNOTS.len(); + +/// A [`Fit`] unpacked (`Family.unpack`). +#[derive(Clone, Copy, Debug)] +pub struct Unpacked { + pub d_pos: [f64; KNOTS_N], + pub d_neg: [f64; KNOTS_N], + /// `(τ, q)` of the amount law, positive and negative amounts. + pub law_pos: (f64, f64), + pub law_neg: (f64, f64), + /// Mix weights of the per-channel result for positive and negative amounts (1 outside [`Mode::Mix`]). + pub weights: (f64, f64), +} + +fn sigmoid(x: f64) -> f64 { + 1.0 / (1.0 + (-x).exp()) +} + +impl Fit { + /// The parameters unpacked; `None` when their number doesn't fit the layout. + pub fn unpack(&self) -> Option { + let n = KNOTS_N - 1; + let p = self.params; + let mix = self.mode == Mode::Mix; + let len = 2 * n + 4 + if mix { 2 } else { 0 }; + if p.len() != len { + return None; + } + // D(1) = 0 is appended (the last knot stays 0) + let shape = |off: usize| -> Option<[f64; KNOTS_N]> { + let mut d = [0.0; KNOTS_N]; + for (k, slot) in d.iter_mut().take(n).enumerate() { + *slot = *p.get(off + k)?; + } + Some(d) + }; + let (mut d_pos, mut d_neg) = (shape(0)?, shape(n)?); + if self.signed { + d_pos[0] = 0.0; + d_neg[0] = 0.0; + } + let at = |i: usize| p.get(i).copied(); + let i = 2 * n; + let law_pos = (at(i)?.exp(), at(i + 1)?.exp()); + let law_neg = (at(i + 2)?.exp(), at(i + 3)?.exp()); + let weights = if mix { (sigmoid(at(i + 4)?), sigmoid(at(i + 5)?)) } else { (1.0, 1.0) }; + Some(Unpacked { d_pos, d_neg, law_pos, law_neg, weights }) + } +} + +/// The amount law `s(t)` (`Family.law`): 1 at `|a| = 100`, linear as `τ` grows, saturating as it +/// shrinks. +pub fn law((tau, q): (f64, f64), a: f64) -> f64 { + let t = (a.abs() / 100.0).min(1.0); + let tau = tau.clamp(1e-3, 1e3); + ((1.0 - (-t / tau).exp()) / (1.0 - (-1.0 / tau).exp())).powf(q) +} + +/// `numpy.interp(v, KNOTS, d)`: piecewise linear, constant beyond the ends. +fn interp(v: f64, d: &[f64; KNOTS_N]) -> f64 { + let k = &fitted::KNOTS; + if v <= k[0] { + return d[0]; + } + for i in 1..KNOTS_N { + if v <= k[i] { + let t = (v - k[i - 1]) / (k[i] - k[i - 1]); + return d[i - 1] + t * (d[i] - d[i - 1]); + } + } + d[KNOTS_N - 1] +} + +impl Unpacked { + /// `F_a(v)` on an encoded value (`Family.curve`). + pub fn curve(&self, a: f64, v: f64) -> f64 { + if a == 0.0 { + return v; + } + if a > 0.0 { + return v + law(self.law_pos, a) * interp(v, &self.d_pos); + } + (v - law(self.law_neg, a) * interp(v, &self.d_neg)).max(0.0) + } +} + +/// One slider's operator at one amount, tabulated: `lut[i]` is the *linear* value of +/// `F_a(i / (LUT_N − 1))` (decoded with the sRGB curve), made non-decreasing (see [`Operator::new`]). +#[derive(Clone, Debug)] +pub struct Operator { + pub mode: Mode, + /// Weight of the per-channel result ([`Mode::Mix`]; 1 for per channel, 0 for luminance). + pub weight: f32, + pub lut: Box<[f32; LUT_N]>, +} + +impl Operator { + /// `fit` at `amount` (-100..100); `None` at 0 (the identity) or for parameters that do not unpack. + /// + /// The table is the running maximum of `F_a`: where a fitted shape folds back (a `D` rising + /// faster than 1), it is flat instead, so no two tones swap. None of the shipped fits folds. + /// The fitting tool inverts `F` the same way. + pub fn new(fit: &Fit, amount: f64) -> Option { + let a = if amount.is_finite() { amount.clamp(-100.0, 100.0) } else { 0.0 }; + if a == 0.0 { + return None; + } + let u = fit.unpack()?; + let weight = match fit.mode { + Mode::PerChannel => 1.0, + Mode::Luminance => 0.0, + Mode::Mix => (if a > 0.0 { u.weights.0 } else { u.weights.1 }) as f32, + }; + let mut lut = Box::new([0.0f32; LUT_N]); + let mut top = 0.0f64; + for (i, slot) in lut.iter_mut().enumerate() { + let v = i as f64 / (LUT_N - 1) as f64; + top = top.max(u.curve(a, v)); + *slot = srgb_decode(top) as f32; + } + // The negative Blacks fit rounds to exactly 1 in f32. Avoid calculating a luminance + // result that contributes nothing, on both CPU and GPU. + let mode = if weight == 1.0 { + Mode::PerChannel + } else if weight == 0.0 { + Mode::Luminance + } else { + Mode::Mix + }; + Some(Operator { mode, weight, lut }) + } + + /// The table at encoded `v` (clamped to 0..=1), interpolated: linear output. + #[inline] + pub fn eval(&self, v: f32) -> f32 { + let f = v.clamp(0.0, 1.0) * (LUT_N - 1) as f32; + let i = (f as usize).min(LUT_N - 2); + let t = f - i as f32; + self.lut[i] + (self.lut[i + 1] - self.lut[i]) * t + } + + /// One linear value through the operator: values above 1 (HDR renders) pass unchanged, which + /// is continuous because `F_a(1) = 1`; values below 0 (outside ProPhoto's gamut) keep their + /// distance below the image of 0, `F_a(0) + x` (continuous and increasing). This is the + /// per-channel domain: on luminance ([`Self::apply`]) a component above 1 is scaled with its + /// pixel unless the pixel's luminance is above 1. + #[inline] + pub fn channel(&self, x: f32, encode: &impl Fn(f32) -> f32) -> f32 { + if x > 1.0 { + x + } else if x < 0.0 { + self.lut[0] + x + } else { + self.eval(encode(x)) + } + } + + /// The luminance mode: linear ProPhoto `p` scaled by `F` of its luminance over its luminance + /// (unchanged when the luminance is at most 1e-6, or above 1). + #[inline] + fn luminance(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { + let y = PRO_Y[0] * p[0] + PRO_Y[1] * p[1] + PRO_Y[2] * p[2]; + if y.is_nan() || y <= 1e-6 || y > 1.0 { + return p; + } + let r = self.channel(y, encode) / y; + p.map(|c| c * r) + } + + /// The operator on a linear ProPhoto pixel (`Family.apply`). Per channel, each component goes + /// through [`Self::channel`] (one above 1 passes unchanged). On luminance, the pixel is scaled + /// by `F(Y) / Y` as a whole, components above 1 included, and passes unchanged only when `Y` + /// itself is above 1 (or at most 1e-6). Mix blends the two results in linear light, so an HDR + /// component of a pixel with `Y ≤ 1` moves by the luminance part's share. + #[inline] + pub fn apply(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { + match self.mode { + Mode::PerChannel => p.map(|c| self.channel(c, encode)), + Mode::Luminance => self.luminance(p, encode), + Mode::Mix => { + let (a, b) = (p.map(|c| self.channel(c, encode)), self.luminance(p, encode)); + let w = self.weight; + std::array::from_fn(|k| w * a[k] + (1.0 - w) * b[k]) + } + } + } +} + +/// sRGB decoding in f64 (the tables are built in f64, like the fit). +fn srgb_decode(e: f64) -> f64 { + if e <= 0.04045 { e / 12.92 } else { ((e + 0.055) / 1.055).powf(2.4) } +} + +/// Linear Rec.2020 (the working space) → linear ProPhoto RGB (D50, Bradford), and back. +pub fn prophoto_matrices() -> ([[f32; 3]; 3], [[f32; 3]; 3]) { + let to = REC2020.to_space(&PROPHOTO); + let from = to.inverse().unwrap_or(Mat3::IDENTITY); + (to.to_f32(), from.to_f32()) +} + +/// The active operators of a render, in order (Contrast, Blacks), and the conversions to +/// and from the space they work in. Applied after the tone map, chroma scaling and highlight +/// desaturation, before the colour stage (`finish::finish_with`, the GPU's `finish.wgsl`). +#[derive(Clone, Debug)] +pub struct LightOps { + pub ops: Vec, + pub to_pro: [[f32; 3]; 3], + pub from_pro: [[f32; 3]; 3], +} + +/// The fits of Contrast and Blacks, in the order they apply. +pub const FITS: [&Fit; 2] = [&fitted::CONTRAST, &fitted::BLACKS]; + +/// Whether `s` renders with the V4 operators: process V4 or later, a raw source, and its camera tone +/// curve. Other sources keep the tone map's own Contrast and Blacks. +pub fn applies(s: &DevelopSettings, is_raw: bool, has_camera_tone: bool) -> bool { + is_raw && has_camera_tone && s.process.process() >= Process::V4 +} + +impl LightOps { + /// The operators of `s` (see [`applies`]); `None` when they don't apply or every + /// slider is at 0. + pub fn new(s: &DevelopSettings, is_raw: bool, has_camera_tone: bool) -> Option { + if !applies(s, is_raw, has_camera_tone) { + return None; + } + let l = &s.light; + let ops: Vec = FITS.iter().zip([l.contrast, l.blacks]).filter_map(|(f, a)| Operator::new(f, a)).collect(); + if ops.is_empty() { + return None; + } + let (to_pro, from_pro) = prophoto_matrices(); + Some(LightOps { ops, to_pro, from_pro }) + } + + /// The operators on a linear Rec.2020 pixel; `encode`: linear → sRGB-encoded on 0..1 (the + /// exact curve or the shared table, as the render encodes). + #[inline] + pub fn apply(&self, d: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { + let mut p = mul3(&self.to_pro, d); + for op in &self.ops { + p = op.apply(p, encode); + } + mul3(&self.from_pro, p) + } +} + +/// Number of intervals over linear input for 8-bit CPU renders. Deep exports retain [`LightOps`] +/// with the exact sRGB encoder; this approximation is not used for U16 or F32 samples. +const PREVIEW_INTERVALS: usize = 16_384; + +/// An operator with its sRGB encoding and decoding included in one linear-input table. +struct LinearOperator { + black: f32, + white: f32, + // Each linear interval stores [intercept, slope], so a lookup needs no integer-to-float + // conversion or subtraction of neighbouring samples in the pixel loop. + segments: Box<[[f32; 2]; PREVIEW_INTERVALS]>, +} + +impl LinearOperator { + fn new(channel: impl Fn(f32) -> f32) -> Self { + let black = channel(0.0); + let mut previous = black; + let mut segments = Box::new([[0.0; 2]; PREVIEW_INTERVALS]); + for (i, segment) in segments.iter_mut().enumerate() { + let next = channel((i + 1) as f32 / PREVIEW_INTERVALS as f32); + let slope = (next - previous) * PREVIEW_INTERVALS as f32; + let intercept = (previous as f64 - slope as f64 * (i as f64 / PREVIEW_INTERVALS as f64)) as f32; + *segment = [intercept, slope]; + previous = next; + } + Self { black, white: previous, segments } + } + + #[inline(always)] + fn channel(&self, x: f32) -> f32 { + if x >= 1.0 { + if x == 1.0 { self.white } else { x } + } else if x < 0.0 { + self.black + x + } else { + let f = x * PREVIEW_INTERVALS as f32; + let i = (f as u32).min(PREVIEW_INTERVALS as u32 - 1) as usize; + let [intercept, slope] = self.segments[i]; + intercept + slope * x + } + } +} + +/// CPU preview tables for per-channel operations, built once per render. Luminance operations +/// use [`LightOps`] instead, so interpolation cannot change a nearly cancelling luminance sum. +pub struct PreviewOps { + ops: PreviewOperators, + to_pro: [[f32; 4]; 3], + from_pro: [[f32; 4]; 3], +} + +enum PreviewOperators { + PerChannel(LinearOperator), + Separate(Vec), +} + +impl PreviewOps { + pub fn new(exact: &LightOps, encode: &impl Fn(f32) -> f32) -> Option { + let ops = &exact.ops; + // Small per-channel errors can cross the luminance cutoff at 1e-6, or be amplified + // by F(Y) / Y. Keep every preceding operation exact too, including Contrast. + if ops.iter().any(|o| o.mode != Mode::PerChannel) { + return None; + } + // A preceding black lift could carry a negative input across zero. Only fuse when + // preceding operators fix zero, so the composed negative extension remains F(0) + x. + // Contrast fixes zero and negative Blacks is per channel, so their usual pair fuses. + let fuse = ops.iter().take(ops.len().saturating_sub(1)).all(|o| o.lut[0] == 0.0); + let ops = if fuse { + PreviewOperators::PerChannel(LinearOperator::new(|x| ops.iter().fold(x, |x, o| o.channel(x, encode)))) + } else { + PreviewOperators::Separate(ops.iter().map(|o| LinearOperator::new(|x| o.channel(x, encode))).collect()) + }; + let columns = |m: [[f32; 3]; 3]| std::array::from_fn(|i| [m[0][i], m[1][i], m[2][i], 0.0]); + Some(Self { ops, to_pro: columns(exact.to_pro), from_pro: columns(exact.from_pro) }) + } + + // Keep the single-table path in the finish loop. An out-of-line call per pixel saves + // little code here but adds register spills to this otherwise small operation. + #[inline(always)] + pub fn apply(&self, d: [f32; 3]) -> [f32; 3] { + let mut p = mul_preview(&self.to_pro, d); + match &self.ops { + PreviewOperators::PerChannel(op) => p = [op.channel(p[0]), op.channel(p[1]), op.channel(p[2])], + PreviewOperators::Separate(ops) => { + for op in ops { + p = p.map(|c| op.channel(c)); + } + } + } + mul_preview(&self.from_pro, p) + } +} + +/// Padded columns let the compiler multiply the RGB rows together in vector registers. +/// The fourth lane is unused; each RGB row keeps the same arithmetic order as `mul3`. +#[inline(always)] +fn mul_preview(m: &[[f32; 4]; 3], d: [f32; 3]) -> [f32; 3] { + let out: [f32; 4] = std::array::from_fn(|i| m[0][i] * d[0] + m[1][i] * d[1] + m[2][i] * d[2]); + [out[0], out[1], out[2]] +} + +#[inline] +fn mul3(m: &[[f32; 3]; 3], d: [f32; 3]) -> [f32; 3] { + [ + m[0][0] * d[0] + m[0][1] * d[1] + m[0][2] * d[2], + m[1][0] * d[0] + m[1][1] * d[1] + m[1][2] * d[2], + m[2][0] * d[0] + m[2][1] * d[1] + m[2][2] * d[2], + ] +} + +/// `fit_pointwise.py`'s own values for one fit at one amount (generated into +/// [`crate::light_v3_params`]; the tests check the port against them). +#[cfg(test)] +pub struct Reference { + pub amount: f64, + /// `Family.curve` at `light_v3_params::REF_V`. + pub curve: &'static [f64], + /// `Family.apply` on `light_v3_params::REF_PIX` (encoded ProPhoto), where the curve increases. + pub apply: Option<&'static [[f64; 3]]>, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::light_v3_params as fitted; + use craft_color::linear_to_srgb; + use craft_develop_model::Process; + + fn srgb_to_linear(v: f32) -> f32 { + craft_color::srgb_to_linear(v) + } + + fn fits() -> [(&'static str, &'static Fit, &'static [Reference]); 2] { + [("contrast", &fitted::CONTRAST, fitted::CONTRAST_REFERENCE), ("blacks", &fitted::BLACKS, fitted::BLACKS_REFERENCE)] + } + + #[test] + fn applies_respects_process_raw_source_and_camera_tone() { + let v3 = DevelopSettings { process: Process::V3.version(), ..Default::default() }; + let v4 = DevelopSettings { process: Process::V4.version(), ..Default::default() }; + let v8 = DevelopSettings { process: Process::V8.version(), ..Default::default() }; + assert!(!applies(&v3, true, true)); + assert!(!applies(&v4, true, false)); + assert!(!applies(&v4, false, true)); + assert!(applies(&v4, true, true)); + assert!(applies(&v8, true, true)); + } + + #[test] + fn the_shipped_fits_unpack_as_the_family_lays_them_out() { + assert!(std::ptr::eq(FITS[0], &fitted::CONTRAST) && std::ptr::eq(FITS[1], &fitted::BLACKS)); + for (name, fit, _) in fits() { + let u = fit.unpack().unwrap_or_else(|| panic!("{name} doesn't unpack")); + assert_eq!((u.d_pos[11], u.d_neg[11]), (0.0, 0.0), "{name}"); + assert_eq!(fit.signed, name == "contrast"); + if fit.signed { + assert_eq!((u.d_pos[0], u.d_neg[0]), (0.0, 0.0)); + } + assert!([u.law_pos, u.law_neg].iter().all(|(t, q)| t.is_finite() && q.is_finite() && *t > 0.0 && *q > 0.0), "{name}"); + let (w0, w1) = u.weights; + assert!((0.0..=1.0).contains(&w0) && (0.0..=1.0).contains(&w1), "{name}"); + } + assert_eq!(fitted::CONTRAST.mode, Mode::PerChannel); + assert_eq!(fitted::BLACKS.mode, Mode::Mix); + let short = Fit { params: &fitted::CONTRAST.params[..20], ..fitted::CONTRAST }; + assert!(short.unpack().is_none()); + assert!(Operator::new(&short, 50.0).is_none()); + } + + #[test] + fn exact_mix_endpoints_select_only_the_contributing_mode() { + assert_eq!(Operator::new(&fitted::BLACKS, -30.0).unwrap().mode, Mode::PerChannel); + assert_eq!(Operator::new(&fitted::BLACKS, 30.0).unwrap().mode, Mode::Mix); + let mut params = fitted::BLACKS.params.to_vec(); + *params.last_mut().unwrap() = -1000.0; + let fit = Fit { params: Box::leak(params.into_boxed_slice()), ..fitted::BLACKS }; + assert_eq!(Operator::new(&fit, -30.0).unwrap().mode, Mode::Luminance); + } + + #[test] + fn preview_tables_match_exact_operators_over_combined_amounts() { + let mut worst = 0.0f32; + for contrast in [-100.0, -60.0, -30.0, 0.0, 30.0, 60.0, 100.0] { + for blacks in [-100.0, -60.0, -30.0, 0.0, 30.0, 60.0, 100.0] { + let mut s = DevelopSettings::default(); + s.light.contrast = contrast; + s.light.blacks = blacks; + let Some(exact) = LightOps::new(&s, true, true) else { continue }; + let preview = PreviewOps::new(&exact, &linear_to_srgb); + assert_eq!(preview.is_some(), blacks <= 0.0); + for i in 0..=8192 { + let v = i as f32 / 8192.0; + for p in [[v; 3], [v, v * 0.1, v * 0.02], [v * 0.04, v, v * 0.2], [v * 0.1, v * 0.03, v], [v * 3.0, -v * 0.2, v]] { + let a = exact.apply(p, &linear_to_srgb); + let b = preview.as_ref().map_or_else(|| exact.apply(p, &linear_to_srgb), |preview| preview.apply(p)); + for (a, b) in a.into_iter().zip(b) { + let error = (linear_to_srgb(a.clamp(0.0, 1.0)) - linear_to_srgb(b.clamp(0.0, 1.0))).abs() * 255.0; + worst = worst.max(error); + assert!(error <= 1.0, "Contrast {contrast}, Blacks {blacks}, input {p:?}: {error} levels"); + } + } + } + } + } + assert!(worst <= 1.0); + } + + #[test] + fn the_operators_are_fit_pointwise_family() { + for (name, fit, refs) in fits() { + let u = fit.unpack().unwrap(); + assert!(!refs.is_empty()); + let mut worst = 0.0f64; + for r in refs { + for (v, want) in fitted::REF_V.iter().zip(r.curve) { + let got = u.curve(r.amount, *v); + assert!((got - want).abs() < 1e-11, "{name} {} at {v}: {got} vs {want}", r.amount); + } + let Some(apply) = r.apply else { continue }; + let op = Operator::new(fit, r.amount).unwrap(); + for (px, want) in fitted::REF_PIX.iter().zip(apply) { + let lin = px.map(|v| srgb_to_linear(v as f32)); + let got = op.apply(lin, &linear_to_srgb).map(linear_to_srgb); + for k in 0..3 { + worst = worst.max((got[k] as f64 - want[k]).abs()); + } + } + } + assert!(worst < 1e-3, "{name}: {worst}"); + } + } + + #[test] + fn every_operator_is_monotone_and_keeps_white() { + for (name, fit, _) in fits() { + for a in (-100..=100).filter(|a| *a != 0) { + let op = Operator::new(fit, a as f64).unwrap(); + assert!(op.lut[0] >= 0.0, "{name} {a}: F(0) = {}", op.lut[0]); + assert!((op.lut[LUT_N - 1] - 1.0).abs() < 1e-6, "{name} {a}: F(1) = {}", op.lut[LUT_N - 1]); + assert!(op.lut.windows(2).all(|w| w[1] >= w[0]), "{name} {a} decreases"); + let mut prev = f32::MIN; + for i in -50..=1100 { + let x = i as f32 / 1000.0; + let y = op.channel(x, &linear_to_srgb); + assert!(y >= prev, "{name} {a} at {x}: {y} < {prev}"); + prev = y; + } + } + } + } +} diff --git a/crates/develop/src/light_v3_params.rs b/crates/develop/src/light_v3_params.rs new file mode 100644 index 0000000000..c49cfad76d --- /dev/null +++ b/crates/develop/src/light_v3_params.rs @@ -0,0 +1,319 @@ +//! Fitted constants of process V4's Contrast and Blacks ([`crate::light_v3`]). +//! +//! GENERATED from [LightCraft at 08179b9b](https://github.com/storytold/lightcraft/tree/08179b9bc3f75dc54134b1ce402cfd2d0a841b38). +//! In that checkout, run `python3 tools/light_v3_constants.py rust --check` against the upstream file. +//! The [generator](https://github.com/storytold/lightcraft/blob/08179b9bc3f75dc54134b1ce402cfd2d0a841b38/tools/light_v3_constants.py) +//! uses the [committed fits](https://github.com/storytold/lightcraft/tree/08179b9bc3f75dc54134b1ce402cfd2d0a841b38/tools/light_v3_fits) +//! named below and writes `crates/pipeline/src/light_v3_params.rs`. The shared copy only changes this +//! provenance note; keep the generated constants unchanged. +//! +//! The values are fitted to black-box Lightroom exports of one person's Sony ILCE-7CR photos (the exports' +//! pixels only: no Lightroom code, tables or files), each slider against the same photo's Neutral or another +//! amount exported in the same batch, on the tune photos; the check photos were held out. The exports are +//! private; errors are published only with at least three contributing photos. These are our operator family's +//! parameters (`docs/light-v3.md`), not Lightroom's. +//! +//! - Contrast: `tools/light_v3_fits/contrast.json` (fitted as `v2-contrast-pc.json`), mode `pc`; 155 tune pairs on 20 photos, 61 check pairs on 6 photos; +//! sha256 `2f04d078f1866ccb05fc279b493ccab545adbe2ac178b12df9ebc524c79c2ce1`. +//! - Blacks: `tools/light_v3_fits/blacks.json` (fitted as `v2-blacks-mix.json`), mode `mix`; 148 tune pairs on 19 photos, 60 check pairs on 6 photos; +//! sha256 `b8ee89df8f632d9559649fcba917607ade1511ecaa2041f481dd5b73a318c090`. + +use crate::light_v3::{Fit, Mode}; +#[cfg(test)] +use crate::light_v3::Reference; + +/// The family's knots: the displacement shapes are piecewise linear on them. +pub const KNOTS: [f64; 12] = [0.0, 0.02, 0.05, 0.09, 0.14, 0.2, 0.28, 0.38, 0.5, 0.65, 0.82, 1.0]; + +/// `tools/light_v3_fits/contrast.json`. +pub const CONTRAST: Fit = Fit { + mode: Mode::PerChannel, + signed: true, + params: &[ + 9.797174393178826e-18, -0.017053489024880908, -0.04260284838408044, -0.07195939270312468, -0.09738651081071477, + -0.1088504066519633, -0.10140378035603768, -0.06947815571389163, -0.007856500339789655, 0.08463087858854193, 0.1098534938016389, + 0.30583740028604467, -0.05850866310699469, -0.07854274245013221, -0.09074476735486797, -0.0906596002773617, -0.08429179542961336, + -0.07428102082426319, -0.05004459522573259, -0.00906946010144, 0.056653920573147026, 0.09818533983265328, 0.3070552562874873, + 0.10657448975892592, -0.13962415708911588, 0.37724097657204825, + ], +}; + +/// `tools/light_v3_fits/blacks.json`. +pub const BLACKS: Fit = Fit { + mode: Mode::Mix, + signed: false, + params: &[ + 0.0016748697345088984, 0.032126630862752484, 0.07188512588294256, 0.09530584096821723, 0.12925288090794965, 0.12680972925019743, + 0.10913227308994669, 0.10024857312175768, 0.0835198499581404, 0.05136152009684992, 0.02045048232256003, 0.00011845423640374467, + 0.2706623236742467, 0.42355931120492346, 0.37893058797626605, 0.22045052169596244, 0.20955478047682013, 0.2107908996685734, + 0.16685612159796198, 0.13055496600268582, 0.08667135921560576, 0.03499725744978859, 14.344979966519135, 0.1199976090379452, + 6.829791928600096, 0.5956122696562978, 0.6007994346537187, 22.053184691621333, + ], +}; + +/// Where the reference values are taken: encoded values and pixels (encoded ProPhoto). +#[cfg(test)] +pub const REF_V: [f64; 16] = [ + 0.0, 0.004, 0.012, 0.03, 0.07, 0.11, 0.17, 0.25, 0.33, 0.45, 0.58, 0.7, 0.81, 0.9, 0.97, 1.0, +]; +#[cfg(test)] +pub const REF_PIX: [[f64; 3]; 6] = [ + [0.02, 0.05, 0.01], [0.3, 0.25, 0.2], [0.55, 0.5, 0.62], [0.9, 0.85, 0.7], [0.15, 0.4, 0.35], [0.75, 0.97, 0.99], +]; + +/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/contrast.json` (12 significant +/// digits). +#[cfg(test)] +pub const CONTRAST_REFERENCE: &[Reference] = &[ + Reference { + amount: -100.0, + curve: &[ + 0.0, 0.0157017326214, 0.0471051978642, 0.0951866895547, 0.154643754903, 0.200710700524, 0.257475697853, 0.328035061301, + 0.392162808025, 0.47614243307, 0.554016990408, 0.631130956115, 0.71425768483, 0.845452588982, 0.953635776695, 1.0, + ], + apply: Some(&[ + [0.078508663107, 0.12854274245, 0.0392543315535], [0.369433735705, 0.328035061301, 0.28429179543], + [0.537161666543, 0.509069460101, 0.576490755562], [0.845452588982, 0.768178883473, 0.631130956115], + [0.239598299469, 0.443215406038, 0.407315522905], [0.668915832804, 0.953635776695, 0.984545258898], + ]), + }, + Reference { + amount: -63.0, + curve: &[ + 0.0, 0.0117558826379, 0.0352676479138, 0.0732055944278, 0.126101694535, 0.170122852746, 0.227978700093, 0.301721466955, + 0.371201372402, 0.467327147126, 0.562778518405, 0.654353749223, 0.746542204136, 0.86384609598, 0.959153828794, 1.0, + ], + apply: Some(&[ + [0.0587794131897, 0.102057956904, 0.0293897065949], [0.346020527272, 0.301721466955, 0.255868416571], + [0.541490780829, 0.506011218203, 0.591162168506], [0.86384609598, 0.79576914397, 0.654353749223], + [0.209385555774, 0.428643076049, 0.387988602489], [0.696257592365, 0.959153828794, 0.986384609598], + ]), + }, + Reference { + amount: -25.0, + curve: &[ + 0.0, 0.00669797632024, 0.0200939289607, 0.0450295815589, 0.0895156438599, 0.130914451725, 0.19016858264, 0.267991929431, + 0.344332389013, 0.456027454879, 0.574009302137, 0.684121407008, 0.787925448518, 0.887423433092, 0.966227029927, 1.0, + ], + apply: Some(&[ + [0.0334898816012, 0.0681089814742, 0.0167449408006], [0.316008789537, 0.267991929431, 0.219434495337], + [0.547039966578, 0.502091073979, 0.609968416216], [0.887423433092, 0.831135149637, 0.684121407008], + [0.170657974176, 0.409963835778, 0.363214788663], [0.73130506224, 0.966227029927, 0.988742343309], + ]), + }, + Reference { + amount: -4.0, + curve: &[ + 0.0, 0.0042211975466, 0.0126635926398, 0.0312322222928, 0.0716000186917, 0.111714702007, 0.171653550835, 0.251475094729, + 0.331175061939, 0.450494169731, 0.579508843847, 0.698698170259, 0.808190185513, 0.898968891712, 0.969690667514, 1.0, + ], + apply: Some(&[ + [0.021105987733, 0.0514846914124, 0.0105529938665], [0.301312504095, 0.251475094729, 0.201593365611], + [0.549757317317, 0.500171439768, 0.619177545887], [0.898968891712, 0.848453337568, 0.698698170259], + [0.151693674318, 0.400816899693, 0.351083433835], [0.748467268102, 0.969690667514, 0.989896889171], + ]), + }, + Reference { + amount: -1.0, + curve: &[ + 0.0, 0.00403003956988, 0.0120901187096, 0.0301673410408, 0.0702172893598, 0.110232863843, 0.170224559253, 0.250200324153, + 0.330159578421, 0.450067110356, 0.5799332989, 0.699823205971, 0.809754219477, 0.899859971098, 0.96995799133, 1.0, + ], + apply: Some(&[ + [0.0201501978494, 0.0502016274236, 0.0100750989247], [0.300178243652, 0.250200324153, 0.200216385843], + [0.549967042657, 0.500023282251, 0.619888307225], [0.899859971098, 0.849789956648, 0.699823205971], + [0.150230008193, 0.400110938461, 0.350147134934], [0.749791848474, 0.96995799133, 0.98998599711], + ]), + }, + Reference { + amount: 1.0, + curve: &[ + 0.0, 0.00397028327185, 0.0119108498156, 0.0297772142058, 0.0695009210477, 0.109284415638, 0.169101549483, 0.249092158771, + 0.329255569926, 0.449707840731, 0.580361320706, 0.700802007104, 0.810944204495, 0.900531739739, 0.970159521922, 1.0, + ], + apply: Some(&[ + [0.0198514163593, 0.0496288098987, 0.00992570817964], [0.29917212145, 0.249092158771, 0.199051608167], + [0.550200155898, 0.499931547883, 0.620576207118], [0.900531739739, 0.850797609609, 0.700802007104], + [0.149134843694, 0.399484133579, 0.349311202243], [0.750866642282, 0.970159521922, 0.990053173974], + ]), + }, + Reference { + amount: 4.0, + curve: &[ + 0.0, 0.00386276829016, 0.0115883048705, 0.0289711762573, 0.067695255762, 0.106695434805, 0.165850959769, 0.245807593504, + 0.326562225444, 0.44865080988, 0.581668577311, 0.70370366501, 0.814360331887, 0.902455571598, 0.970736671479, 1.0, + ], + apply: Some(&[ + [0.0193138414508, 0.0482858458702, 0.0096569207254], [0.296176860778, 0.245807593504, 0.195620331007], + [0.550924318987, 0.499683888448, 0.622660921742], [0.902455571598, 0.853683357397, 0.70370366501], + [0.146004712278, 0.397617731312, 0.34681913522], [0.754002149954, 0.970736671479, 0.99024555716], + ]), + }, + Reference { + amount: 25.0, + curve: &[ + 0.0, 0.00303130723309, 0.00909392169928, 0.0227377271685, 0.0537312449465, 0.0866736973109, 0.140712707247, 0.220406592954, + 0.305733397543, 0.440476321314, 0.591778172653, 0.726143473036, 0.840778760722, 0.917333416951, 0.975200025085, 1.0, + ], + apply: Some(&[ + [0.0151565361655, 0.0379001091744, 0.00757826808274], [0.273013181027, 0.220406592954, 0.169084742294], + [0.556524593466, 0.497768628155, 0.638782944901], [0.917333416951, 0.876000125426, 0.726143473036], + [0.121798017215, 0.383184014474, 0.327546875221], [0.778250421984, 0.975200025085, 0.991733341695], + ]), + }, + Reference { + amount: 63.0, + curve: &[ + 0.0, 0.00166203669924, 0.00498611009773, 0.0124723297827, 0.0307349682338, 0.0537014072028, 0.0993144142548, 0.178575600043, + 0.271431971089, 0.427014372342, 0.608426903093, 0.763097901214, 0.884285279574, 0.941834618872, 0.982550385662, 1.0, + ], + apply: Some(&[ + [0.00831018349621, 0.0207966223556, 0.00415509174811], [0.234866663076, 0.178575600043, 0.125385281671], + [0.56574726332, 0.494614530364, 0.665333089458], [0.941834618872, 0.912751928309, 0.763097901214], + [0.0819338359776, 0.35941421432, 0.295808843098], [0.818183073196, 0.982550385662, 0.994183461887], + ]), + }, + Reference { + amount: 100.0, + curve: &[ + 0.0, 0.000589302195024, 0.00176790658507, 0.00443005785539, 0.0127188794564, 0.0278697600538, 0.0668815412687, 0.145803734783, + 0.244559031965, 0.416467809921, 0.621470101755, 0.792049294828, 0.918369810554, 0.961029718779, 0.988308915634, 1.0, + ], + apply: Some(&[ + [0.00294651097512, 0.00739715161592, 0.00147325548756], [0.204981344572, 0.145803734783, 0.091149593348], + [0.57297262597, 0.49214349966, 0.686133402803], [0.961029718779, 0.941544578168, 0.792049294828], + [0.0507028398824, 0.340792120182, 0.270944156893], [0.849467711067, 0.988308915634, 0.996102971878], + ]), + }, +]; + +/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/blacks.json` (12 significant +/// digits). +#[cfg(test)] +pub const BLACKS_REFERENCE: &[Reference] = &[ + Reference { + amount: -100.0, + curve: &[ + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0396726450283, 0.141176489367, 0.304319552499, 0.472849624284, 0.62852690601, + 0.771963089505, 0.880557079195, 0.964167123758, 1.0, + ], + apply: Some(&[ + [0.0, 0.0, 0.0], [0.0979960559384, 0.0396726450312, 8.67909201708e-12], [0.434072902922, 0.369445033999, 0.524551919414], + [0.880557079192, 0.820835618793, 0.628526906024], [1.62784132506e-11, 0.239194070991, 0.169963444981], + [0.693725171247, 0.964167123755, 0.988055707915], + ]), + }, + Reference { + amount: -63.0, + curve: &[ + 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0769799089595, 0.159002658298, 0.248306215942, 0.386971900482, 0.533641791607, 0.669077433807, + 0.793543473258, 0.891588093197, 0.967476427959, 1.0, + ], + apply: Some(&[ + [0.0, 0.0, 0.0], [0.212603750827, 0.159002658299, 0.109336909762], [0.49984457601, 0.443515883354, 0.578704745728], + [0.891588093196, 0.837382139795, 0.669077433813], [0.0554085751144, 0.330427917606, 0.27210785935], + [0.72565290629, 0.967476427958, 0.989158809318], + ]), + }, + Reference { + amount: -25.0, + curve: &[ + 0.0, 0.0, 0.0, 0.0039713718625, 0.0375281504298, 0.0844641752827, 0.152600319953, 0.232978681132, 0.314718938796, + 0.438210409673, 0.571328561555, 0.694215843567, 0.806921758549, 0.898426528234, 0.96952795847, 1.0, + ], + apply: Some(&[ + [1.38361828441e-12, 0.0157222994288, 6.91809142207e-13], [0.28365227602, 0.232978681132, 0.183041203846], + [0.540618281274, 0.489434480805, 0.612275601929], [0.898426528233, 0.84763979235, 0.694215843568], + [0.132306397362, 0.386986338539, 0.335430047312], [0.745445804924, 0.96952795847, 0.989842652823], + ]), + }, + Reference { + amount: -4.0, + curve: &[ + 0.0, 0.00384203333958, 0.0115267901451, 0.029063081396, 0.0688311531515, 0.109080820198, 0.169373686394, 0.249387305769, + 0.329449947556, 0.449575625482, 0.579687865532, 0.699791795259, 0.809889196554, 0.899943361788, 0.969983008536, 1.0, + ], + apply: Some(&[ + [0.0192115469507, 0.0487661502866, 0.00960560094376], [0.299411552286, 0.249387305769, 0.199389556317], + [0.549662298498, 0.499619686776, 0.61972195491], [0.899943361788, 0.849915042681, 0.699791795259], + [0.149363106446, 0.399531564189, 0.349475544402], [0.749836068575, 0.969983008536, 0.989994336179], + ]), + }, + Reference { + amount: -1.0, + curve: &[ + 0.0, 0.00398722513591, 0.0119617312187, 0.0299242307978, 0.0699054746135, 0.109925665346, 0.169949349621, 0.249950451029, + 0.32995551691, 0.449965680563, 0.579974757487, 0.69998316235, 0.809991039255, 0.899995419632, 0.96999862589, 1.0, + ], + apply: Some(&[ + [0.0199362373015, 0.0499002177906, 0.009968104698], [0.29995241186, 0.249950451029, 0.199950633032], + [0.549972689865, 0.499969243828, 0.619977514317], [0.899995419632, 0.849993129448, 0.69998316235], + [0.149948494014, 0.399962117299, 0.349957586943], [0.749986742762, 0.96999862589, 0.989999541963], + ]), + }, + Reference { + amount: 1.0, + curve: &[ + 9.31612027339e-06, 0.00404319245864, 0.0121109451354, 0.0302524139772, 0.0704649827756, 0.11060564863, 0.170712147943, + 0.250643898657, 0.330582319062, 0.450503332955, 0.580369162543, 0.700235118441, 0.810123865526, 0.900063195347, 0.970018958604, + 1.0, + ], + apply: Some(&[ + [0.0201752429349, 0.0503888012921, 0.0100906298252], [0.300630744288, 0.250626419466, 0.200631616538], + [0.550429399642, 0.500454032729, 0.620394920846], [0.90007223641, 0.850090998192, 0.700176696162], + [0.150565756988, 0.400578185286, 0.350572708933], [0.750135238759, 0.970032675648, 0.990024911688], + ]), + }, + Reference { + amount: 4.0, + curve: &[ + 4.44679248931e-05, 0.00420616726172, 0.0125295659354, 0.0312048283459, 0.0722194667453, 0.112890896317, 0.17339924135, + 0.253073472246, 0.332779539074, 0.452402520726, 0.581762095353, 0.701122272887, 0.810591237848, 0.900301645519, 0.970090493656, + 1.0, + ], + apply: Some(&[ + [0.0208391227968, 0.0518558616479, 0.0104339209625], [0.303010755867, 0.252990062923, 0.203015330491], + [0.55204964314, 0.502167204295, 0.621885228625], [0.900344802502, 0.850434355079, 0.700843514096], + [0.152703002383, 0.402759872928, 0.352733667786], [0.750645594216, 0.970155972394, 0.990118916658], + ]), + }, + Reference { + amount: 25.0, + curve: &[ + 0.000351031037929, 0.00562749010759, 0.0161804082469, 0.0395109485272, 0.0875205323187, 0.132820816064, 0.19683370592, + 0.274262075537, 0.351941758888, 0.468965565542, 0.593910029809, 0.708859253437, 0.814667248041, 0.902381198134, 0.97071435944, + 1.0, + ], + apply: Some(&[ + [0.0268094892594, 0.0646518089884, 0.0135180994291], [0.323771669718, 0.273605097162, 0.223833590382], + [0.566181459749, 0.517108276593, 0.63489439536], [0.902722015601, 0.853428836176, 0.7066658074], + [0.171494494367, 0.421790810113, 0.371579649929], [0.755101084946, 0.971231540587, 0.990939254456], + ]), + }, + Reference { + amount: 63.0, + curve: &[ + 0.000995014140305, 0.00861319796625, 0.0238495656181, 0.0569592350811, 0.11966278055, 0.174686686427, 0.246061413214, + 0.31877200482, 0.392194957135, 0.503758795817, 0.619428639797, 0.725111974413, 0.823229536124, 0.906749619145, 0.972024885744, + 1.0, + ], + apply: Some(&[ + [0.0404539765541, 0.0915381262658, 0.0205483468996], [0.367405560588, 0.316916949778, 0.267702217691], + [0.595875558955, 0.54849590131, 0.662288333975], [0.907716480454, 0.859719346711, 0.718935705489], + [0.211650252506, 0.461789763271, 0.411168543529], [0.764487032294, 0.973492582642, 0.992665468794], + ]), + }, + Reference { + amount: 100.0, + curve: &[ + 0.00167486973451, 0.0117652219602, 0.0319459264115, 0.0753794625361, 0.153595483426, 0.218884656944, 0.298031305079, + 0.36576131915, 0.434690423106, 0.540490151276, 0.646368740699, 0.742270038399, 0.832268778662, 0.911361379068, 0.97340841372, + 1.0, + ], + apply: Some(&[ + [0.055421940602, 0.119927912612, 0.0288346946948], [0.413495225374, 0.362648809539, 0.314154311953], + [0.627234264731, 0.5816340005, 0.691296631565], [0.912990263469, 0.866360468302, 0.731944464499], + [0.254705410536, 0.504042777472, 0.452962701964], [0.774433618221, 0.975881980047, 0.994492187831], + ]), + }, +]; diff --git a/crates/develop/src/local.rs b/crates/develop/src/local.rs new file mode 100644 index 0000000000..1ba5ee069b --- /dev/null +++ b/crates/develop/src/local.rs @@ -0,0 +1,1407 @@ +//! Scene-linear preparation: white balance + exposure, and the spatial planes the per-pixel stage +//! needs (edge-aware base layer for highlights/shadows, clarity/texture bands, dehaze veil). + +use craft_color_transform::cct::{temp_tint_to_xy, wb_matrix as wb_matrix_checked, xy_to_temp_tint}; +use craft_color_transform::{BRADFORD, Mat3, REC2020, RgbSpace, Xy}; +use craft_develop_model::{DevelopSettings, LocalAdjustments, Mask, Process, WbMode, WbScale}; +use std::sync::Arc; + +use crate::colorops::luminance_2020; +use crate::raster::blur::{gauss_taps, gaussian}; +use crate::raster::{Plane, Rgb32f, par_join, par_rows as for_rows}; + +/// Legacy (V1..V9) unchecked Bradford white-balance matrix. +fn wb_matrix_legacy(space: &RgbSpace, src: Xy) -> Mat3 { + let (Some(s_xyz), Some(d_xyz), Some(inv)) = (src.to_xyz(), space.white.to_xyz(), BRADFORD.inverse()) else { + return Mat3::IDENTITY; + }; + let (s, d) = (BRADFORD.apply(s_xyz), BRADFORD.apply(d_xyz)); + let scale = Mat3::diag(d[0] / s[0], d[1] / s[1], d[2] / s[2]); + let adapt = inv.mul(&scale).mul(&BRADFORD); + space.from_xyz().mul(&adapt).mul(&space.to_xyz()) +} + +/// Render quality for spatial planes (`Draft` caps the Highlights/Shadows base radius). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Quality { + #[default] + Full, + Draft, +} + +/// Source white-balance metadata needed to interpret [`DevelopSettings::wb`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WbSource { + pub raw: bool, + pub as_shot_temp: f64, + pub as_shot_tint: f64, + pub relative_wb: bool, + pub legacy_relative_wb: bool, +} + +impl Default for WbSource { + fn default() -> Self { + Self { raw: false, as_shot_temp: 6500.0, as_shot_tint: 0.0, relative_wb: false, legacy_relative_wb: false } + } +} + +/// White balance (relative to the source's as-shot white) and exposure, in place. +pub fn scene_linear_pre(img: &mut Rgb32f, info: &WbSource, s: &DevelopSettings) { + wb_gain(img, info, s, 2f32.powf(s.light.exposure as f32)); +} + +/// White balance only (exposure is applied by the per-pixel stage). +pub fn white_balance(img: &mut Rgb32f, info: &WbSource, s: &DevelopSettings) { + wb_gain(img, info, s, 1.0); +} + +/// Whether `s` uses the checked Bradford white-balance adaptation (`Process::V10` on) instead +/// of the legacy matrix (V1 to V9, which stay frozen). +pub fn checked_wb(s: &DevelopSettings) -> bool { + s.process.0 >= 10 +} + +/// The white-balance matrix (linear Rec.2020) for the settings, or `None` when the as-shot white +/// is kept. +pub fn wb_matrix_for(info: &WbSource, s: &DevelopSettings) -> Option<[[f32; 3]; 3]> { + wb_matrix_for_with(info, s, None) +} + +/// [`wb_matrix_for`] with an optional camera-space white-balance callback (`rebalance(target_xy)`). +pub fn wb_matrix_for_with(info: &WbSource, s: &DevelopSettings, rebalance: Option<&dyn Fn(Xy) -> Option>) -> Option<[[f32; 3]; 3]> { + let (t, tint) = effective_wb(info, s); + if (t - info.as_shot_temp).abs() < 1e-6 && (tint - info.as_shot_tint).abs() < 1e-6 { + return None; + } + if let Some(m) = rebalance.filter(|_| info.raw && !info.relative_wb).and_then(|f| f(temp_tint_to_xy(t, tint))) { + return Some(m.to_f32()); + } + let checked = checked_wb(s); + let set = if checked { wb_matrix_checked(&REC2020, effective_white(info, s)) } else { wb_matrix_legacy(&REC2020, effective_white(info, s)) }; + let shot = if checked { + wb_matrix_checked(&REC2020, temp_tint_to_xy(info.as_shot_temp, info.as_shot_tint)) + } else { + wb_matrix_legacy(&REC2020, temp_tint_to_xy(info.as_shot_temp, info.as_shot_tint)) + }; + let m = set.mul(&shot.inverse().unwrap_or(Mat3::IDENTITY)); + // Normalize so neutral luminance is preserved (WB shouldn't change exposure). + let g = m.apply([1.0, 1.0, 1.0]); + let y = g[0] * 0.2627 + g[1] * 0.6780 + g[2] * 0.0593; + Some(m.mul(&Mat3::diag(1.0 / y, 1.0 / y, 1.0 / y)).to_f32()) +} + +fn wb_gain(img: &mut Rgb32f, info: &WbSource, s: &DevelopSettings, gain: f32) { + let m = wb_matrix_for(info, s); + let w = img.width; + for_rows(&mut img.data, w, |_, row| { + for p in row.iter_mut() { + let mut c = *p; + if let Some(m) = &m { + c = [ + m[0][0] * c[0] + m[0][1] * c[1] + m[0][2] * c[2], + m[1][0] * c[0] + m[1][1] * c[1] + m[1][2] * c[2], + m[2][0] * c[0] + m[2][1] * c[1] + m[2][2] * c[2], + ]; + } + *p = [(c[0] * gain).max(0.0), (c[1] * gain).max(0.0), (c[2] * gain).max(0.0)]; + } + }); +} + +/// The white balance actually in effect (presets resolve to their Kelvin values for raw files; settings written on +/// the relative scale before a raw's camera matrices reached its white balance give the same colour change on the +/// Kelvin scale, see [`legacy_to_kelvin`]). +pub fn effective_wb(info: &WbSource, s: &DevelopSettings) -> (f64, f64) { + match s.wb.mode { + WbMode::AsShot => (info.as_shot_temp, info.as_shot_tint), + _ if legacy_wb(info, s) => legacy_to_kelvin(s.wb.temp, s.wb.tint, (info.as_shot_temp, info.as_shot_tint)), + m if info.raw && !info.relative_wb => m.preset().unwrap_or((s.wb.temp, s.wb.tint)), + _ => (s.wb.temp, s.wb.tint), + } +} + +/// The source white the render adapts from the as-shot white to: [`effective_wb`] as a chromaticity, except that a +/// white balance still on the relative scale is composed exactly ([`legacy_white`]) rather than read back through +/// its rounded Kelvin / tint. +fn effective_white(info: &WbSource, s: &DevelopSettings) -> Xy { + if legacy_wb(info, s) + && s.wb.mode != WbMode::AsShot + && let Some(xy) = legacy_white(s.wb.temp, s.wb.tint, (info.as_shot_temp, info.as_shot_tint)) + { + return xy; + } + let (t, tint) = effective_wb(info, s); + temp_tint_to_xy(t, tint) +} + +/// Whether `s` holds a white balance written on the relative scale for a source that is edited in Kelvin today. +fn legacy_wb(info: &WbSource, s: &DevelopSettings) -> bool { + info.raw && !info.relative_wb && info.legacy_relative_wb && s.wb.scale == WbScale::Legacy +} + +/// The white that renders exactly as `(temp, tint)` did on the relative scale, where 6500 K / 0 meant *as shot* and +/// the source's real as-shot white is `as_shot`. +/// +/// The relative render adapted the picture from 6500 K / 0 to `(temp, tint)` (Bradford, [`wb_matrix_for`]); the +/// Kelvin render adapts it from `as_shot` to the result. Bradford adaptations are von Kries scalings in one cone +/// space, so they compose exactly: the new white's cone response is the old target's times the as-shot white's +/// over the old reference's, and the two renders give the same matrix (up to the scale the luminance +/// normalisation removes). `None` when the arithmetic has nowhere to go (a non-finite input, a white outside the +/// chromaticity plane). +pub fn legacy_white(temp: f64, tint: f64, as_shot: (f64, f64)) -> Option { + if !(temp.is_finite() && tint.is_finite() && as_shot.0.is_finite() && as_shot.1.is_finite()) { + return None; + } + let cones = |t: f64, tint: f64| temp_tint_to_xy(t, tint).to_xyz().map(|xyz| BRADFORD.apply(xyz)); + let (old, reference, shot) = (cones(temp, tint)?, cones(6500.0, 0.0)?, cones(as_shot.0, as_shot.1)?); + let inverse = BRADFORD.inverse()?; + let mut new = [0.0; 3]; + for i in 0..3 { + if reference[i].abs() < 1e-12 { + return None; + } + new[i] = old[i] * shot[i] / reference[i]; + } + let xy = Xy::from_xyz(inverse.apply(new))?; + (xy.x.is_finite() && xy.y.is_finite() && xy.y > 0.0).then_some(xy) +} + +/// The Kelvin / tint of [`legacy_white`]: what a white balance written on the relative scale reads as, and becomes +/// when it is next edited ([`normalize_wb`]). Exact wherever the white has a Kelvin value (1000–50000 K after the +/// composition; the relative slider reached 2000–13550 K around 6500 K, so only a far-blue as-shot white pushed +/// to the slider's blue end lands beyond, and clamps), to the precision of the Kelvin / tint parametrisation +/// (better than 0.01 % away from its 4000 K seam). Unchanged when the arithmetic has nowhere to go. +pub fn legacy_to_kelvin(temp: f64, tint: f64, as_shot: (f64, f64)) -> (f64, f64) { + if temp == 6500.0 && tint == 0.0 && as_shot.0.is_finite() && as_shot.1.is_finite() { + // the relative scale's as-shot reference, exactly (a Custom value left where As Shot was stays as shot) + return as_shot; + } + match legacy_white(temp, tint, as_shot).map(xy_to_temp_tint) { + Some((t, tint)) if t.is_finite() && tint.is_finite() => (t, tint), + _ => (temp, tint), + } +} + +/// The relative-scale `(temp, tint)` that [`legacy_to_kelvin`] would read as the Kelvin `(temp, tint)` on a source +/// whose real as-shot white is `as_shot`: the inverse of [`legacy_white`]'s composition. It runs the Bradford step +/// backwards — the old target's cone response times the old reference's over the as-shot white's — and reads the +/// result back through [`xy_to_temp_tint`]. `(6500, 0)` is the relative scale's as-shot reference, so the Kelvin +/// white of the source itself maps exactly to it. `None` when the arithmetic has nowhere to go (a non-finite input, +/// a white outside the chromaticity plane, or an as-shot cone response of zero, where the forward step discarded it). +pub fn kelvin_to_legacy(temp: f64, tint: f64, as_shot: (f64, f64)) -> Option<(f64, f64)> { + if !(temp.is_finite() && tint.is_finite() && as_shot.0.is_finite() && as_shot.1.is_finite()) { + return None; + } + if (temp - as_shot.0).abs() < 1e-9 && (tint - as_shot.1).abs() < 1e-9 { + // the source's own white: the relative scale's as-shot reference, exactly + return Some((6500.0, 0.0)); + } + let cones = |t: f64, tint: f64| temp_tint_to_xy(t, tint).to_xyz().map(|xyz| BRADFORD.apply(xyz)); + let (target, reference, shot) = (cones(temp, tint)?, cones(6500.0, 0.0)?, cones(as_shot.0, as_shot.1)?); + let inverse = BRADFORD.inverse()?; + let mut old = [0.0; 3]; + for i in 0..3 { + if shot[i].abs() < 1e-12 { + return None; + } + old[i] = target[i] * reference[i] / shot[i]; + } + let xy = Xy::from_xyz(inverse.apply(old))?; + if !(xy.x.is_finite() && xy.y.is_finite() && xy.y > 0.0) { + return None; + } + let (t, tint) = xy_to_temp_tint(xy); + (t.is_finite() && tint.is_finite()).then_some((t, tint)) +} + +/// Bring the white balance of `d` onto the scale `info` is edited on, before a new value is written into it: on a +/// raw with a Kelvin scale the values are marked Kelvin, and ones still on the relative scale become the Custom +/// Kelvin / tint that renders the same ([`legacy_to_kelvin`]; a preset mode's look is kept as that custom +/// value, since the preset's Kelvin value would be a different look). Elsewhere the scale is cleared, so values +/// edited on a rendered photo or a raw without matrices never pass for Kelvin when pasted onto one that has them. +pub fn normalize_wb(d: &mut DevelopSettings, info: &WbSource) { + if !info.raw || info.relative_wb { + d.wb.scale = WbScale::Legacy; + return; + } + if legacy_wb(info, d) && d.wb.mode != WbMode::AsShot { + let (t, tint) = legacy_to_kelvin(d.wb.temp, d.wb.tint, (info.as_shot_temp, info.as_shot_tint)); + d.wb.temp = t; + d.wb.tint = tint; + d.wb.mode = WbMode::Custom; + } + d.wb.scale = WbScale::Kelvin; +} + +/// Self-guided filter (He et al.) on a single plane with Gaussian windows of `sigma` px. +pub fn guided(p: &Plane, sigma: f32, eps: f32) -> Plane { + let (ma, mb) = guided_coeffs(p, sigma, eps); + guided_apply(p, &ma, &mb) +} + +/// Blurred guided-filter coefficients (mean a, mean b) of `p`; every pass row-parallel, and the +/// two independent blurs of each step run side by side. +fn guided_coeffs(p: &Plane, sigma: f32, eps: f32) -> (Plane, Plane) { + let (mean, corr) = par_join(|| gaussian(p, sigma), || gaussian(&p.map(|v| v * v), sigma)); + let a = corr.zip_map(&mean, |c, m| { + let var = (c - m * m).max(0.0); + var / (var + eps) + }); + let b = mean.zip_map(&a, |m, a| m - a * m); + par_join(|| gaussian(&a, sigma), || gaussian(&b, sigma)) +} + +/// `q = a·p + b` per pixel. Reduced coefficients are sampled with the same separable +/// weights and accumulation order as a bilinear resize, without full-size coefficient planes. +fn guided_apply(p: &Plane, a: &Plane, b: &Plane) -> Plane { + let mut q = Plane::new(p.width, p.height); + let w = p.width; + if (a.width, a.height) != (p.width, p.height) { + use crate::raster::resample::{Filter, weights}; + let wx = weights(a.width, w, Filter::Bilinear); + let wy = weights(a.height, p.height, Filter::Bilinear); + // Bilinear upsampling has at most four taps (including zero-weight boundary taps). + // Keep only those horizontally sampled rows per band, reusing them for neighbouring + // output rows. Scratch scales with width and active bands, not image area. + const BAND: usize = 32; + for_rows(&mut q.data, w.saturating_mul(BAND), |band, rows| { + let mut cache: [(usize, Vec, Vec); 4] = std::array::from_fn(|_| (usize::MAX, vec![0.0; w], vec![0.0; w])); + let mut bias = vec![0.0; w]; + for (dy, row) in rows.chunks_mut(w).enumerate() { + let y = band * BAND + dy; + let (top, ys) = &wy[y]; + bias.fill(0.0); + for (dy, yw) in ys.iter().enumerate() { + let cy = top + dy; + let (cached_y, aa, bb) = &mut cache[cy % 4]; + if *cached_y != cy { + let (ar, br) = (a.row(cy), b.row(cy)); + for ((av, bv), (left, xs)) in aa.iter_mut().zip(bb.iter_mut()).zip(&wx) { + *av = 0.0; + *bv = 0.0; + for (dx, xw) in xs.iter().enumerate() { + *av += ar[left + dx] * xw; + *bv += br[left + dx] * xw; + } + } + *cached_y = cy; + } + for (av, ax) in row.iter_mut().zip(aa) { + *av += *ax * yw; + } + for (bv, bx) in bias.iter_mut().zip(bb) { + *bv += *bx * yw; + } + } + for ((v, pv), bv) in row.iter_mut().zip(p.row(y)).zip(&bias) { + *v = *v * pv + bv; + } + } + }); + return q; + } + for_rows(&mut q.data, w, |y, row| { + for ((v, pv), (av, bv)) in row.iter_mut().zip(p.row(y)).zip(a.row(y).iter().zip(b.row(y))) { + *v = av * pv + bv; + } + }); + q +} + +/// Fast guided filter (He & Sun 2015): coefficients computed on a `s×` subsampled plane and +/// sampled bilinearly at full resolution; the output keeps full-resolution edges. Equivalent to [`guided`] for +/// large windows at a fraction of the cost. +pub fn guided_fast(p: &Plane, sigma: f32, eps: f32) -> Plane { + use crate::raster::resample::{Filter, resize}; + let s = guided_fast_step(sigma); + if s <= 1 { + return guided(p, sigma, eps); + } + let (lw, lh) = (p.width.div_ceil(s).max(1), p.height.div_ceil(s).max(1)); + let lo = resize(p, lw, lh, Filter::Box); + let (ma, mb) = guided_coeffs(&lo, sigma / s as f32, eps); + guided_apply(p, &ma, &mb) +} + +/// Separable median (`2r+1` px along each row, then each column; clamped edges). It keeps the +/// steps between regions where they are and removes features thinner than about `r` px. +pub fn median_hv(p: &Plane, r: usize) -> Plane { + if r == 0 || p.data.is_empty() { + return p.clone(); + } + let rows = |src: &Plane| { + let mut out = Plane::new(src.width, src.height); + for_rows(&mut out.data, src.width, |y, row| median_row(src.row(y), row, r)); + out + }; + transpose(&rows(&transpose(&rows(p)))) +} + +/// Running median of `src` over `2r+1` taps (clamped edges) into `out`: a sorted window that +/// drops the leaving value and inserts the entering one. +fn median_row(src: &[f32], out: &mut [f32], r: usize) { + let n = src.len(); + if n == 0 { + return; + } + let at = |i: isize| total_key(src[i.clamp(0, n as isize - 1) as usize]); + let r_ = r as isize; + let mut win: Vec = (-r_..=r_).map(at).collect(); + win.sort_unstable(); + for (x, o) in out.iter_mut().enumerate() { + *o = f32::from_bits(total_key_inv(win[r])); + let (old, new) = (at(x as isize - r_), at(x as isize + r_ + 1)); + if old != new { + // Ranks by counting the smaller keys in one branch-free pass the compiler vectorizes. + // Binary searches here mispredicted on most steps and, with `remove` + `insert`, cost + // 2.4 s per 24 MP at r = 9 on one core. + let (mut i, mut j) = (0u32, 0u32); + for &v in &win { + i += u32::from(v < old); + j += u32::from(v < new); + } + let (i, j) = (i as usize, j as usize); + // `old` sits at `i`; shift the keys between the two ranks by one over it + if j > i { + win.copy_within(i + 1..j, i); + win[j - 1] = new; + } else { + win.copy_within(j..i, j + 1); + win[j] = new; + } + } + } +} + +/// `v`'s bits as an `i32` that orders like [`f32::total_cmp`] (the same transform it applies), so +/// equal keys are equal bits. +fn total_key(v: f32) -> i32 { + let b = v.to_bits() as i32; + b ^ (((b >> 31) as u32) >> 1) as i32 +} + +/// The bits [`total_key`] came from (the transform is its own inverse: it keeps the sign bit). +fn total_key_inv(k: i32) -> u32 { + (k ^ (((k >> 31) as u32) >> 1) as i32) as u32 +} + +fn transpose(p: &Plane) -> Plane { + let (w, h) = (p.width, p.height); + let mut t = Plane::new(h, w); + for_rows(&mut t.data, h, |x, row| { + for (y, v) in row.iter_mut().enumerate() { + *v = p.data[y * w + x]; + } + }); + t +} + +/// Detail scale of the highlights/shadows base from process V2, as a fraction of the long edge: +/// the base is the edge-aware filter of log luminance without its detail at this radius, so +/// twigs, lines and fine texture brighter or darker than their surroundings take their +/// surroundings' shift (and keep their contrast, as with Exposure) while region boundaries stay +/// sharp (no halos). V1's base is the edge-aware filter of log luminance itself (issue #632). +pub const BASE_DETAIL: f64 = 0.0015; +/// Largest [`base_detail_radius`] (px). +pub const BASE_DETAIL_MAX: usize = 24; + +/// Median radius (px) of the highlights/shadows base at `px_per_long` (see [`BASE_DETAIL`]). +pub fn base_detail_radius(px_per_long: f64) -> usize { + ((BASE_DETAIL * px_per_long).round().max(0.0) as usize).min(BASE_DETAIL_MAX) +} + +/// Median radius (px) of the highlights/shadows base of `s`'s rendering process at `px_per_long`: +/// 0 (no median) under V1, [`base_detail_radius`] from V2 (later processes keep V2's base). +pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { + match s.process.process() { + Process::V1 => 0, + Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 => base_detail_radius(px_per_long), + } +} + +/// The highlights/shadows base layer of log luminance `l`: the fast guided filter ([`BASE_EPS`]) +/// at `detail` px ([`tone_base_detail`]) of its [`detail_free`] plane when `keeps_gaps` +/// ([`base_keeps_gaps`], V8 on), else of its [`median_hv`] (V2 to V7); at 0, of `l` itself (V1). +pub fn tone_base(l: &Plane, sigma: f32, detail: usize, keeps_gaps: bool) -> Plane { + if detail == 0 { + return guided_fast(l, sigma, BASE_EPS); + } + let m = if keeps_gaps { detail_free(l, detail) } else { median_hv(l, detail) }; + guided_fast(&m, sigma, BASE_EPS) +} + +/// Downscale factor of the coarse median in [`detail_free`]: its radius at full size is this many +/// times the fine one's. +pub const BASE_COARSE_STEP: usize = 3; + +/// Log luminance `l` without detail finer than `r` px (the highlights/shadows base of process V8 +/// on takes its edge-aware filter): each value moves toward its [`median_hv`] at `r` only as far as the +/// median of a [`BASE_COARSE_STEP`]× wider neighbourhood agrees (`l` clamped between the two). +/// A twig, line or speck in an even surround has both medians on the surround's side and takes +/// its tone, as #632 wants. The gap between two letter strokes, which a median at `r` fills with the +/// strokes' tone, sits in a wider neighbourhood mostly of the panel's tone: the two medians +/// disagree and the gap keeps its own. The coarse median is taken at `r` of a box-downscaled copy and +/// enlarged bilinearly, like [`guided_fast`]'s coefficients. +pub fn detail_free(l: &Plane, r: usize) -> Plane { + use crate::raster::resample::{Filter, resize}; + if r == 0 || l.data.is_empty() { + return l.clone(); + } + let (w, h) = (l.width, l.height); + let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP).max(1), h.div_ceil(BASE_COARSE_STEP).max(1)); + if (lw, lh) == (w, h) { + // nothing to downscale: both medians are the same + return median_hv(l, r); + } + let lo = median_hv(&resize(l, lw, lh, Filter::Box), r); + // The bilinear enlargement of `lo` (`resize`'s horizontal pass, then its vertical pass taken + // row by row with the same sums) is clamped into `out` as it is made, not stored. + let wide = resize(&lo, w, lh, Filter::Bilinear); + let wy = crate::raster::resample::weights(lh, h, Filter::Bilinear); + let mut out = median_hv(l, r); + for_rows(&mut out.data, w, |y, row| { + let Some((y0, ws)) = wy.get(y) else { return }; + let mut coarse = vec![0.0f32; w]; + for (k, &wt) in ws.iter().enumerate() { + let Some(t) = wide.data.get((y0 + k) * w..(y0 + k + 1) * w) else { continue }; + for (c, &v) in coarse.iter_mut().zip(t) { + *c += v * wt; + } + } + for ((o, &v), &c) in row.iter_mut().zip(l.row(y)).zip(&coarse) { + *o = clamp_between(v, *o, c); + } + }); + out +} + +/// `v` clamped between `a` and `b` (in either order); a NaN bound is ignored, not a panic. +fn clamp_between(v: f32, a: f32, b: f32) -> f32 { + let (lo, hi) = (a.min(b), a.max(b)); + if v < lo { + lo + } else if v > hi { + hi + } else { + v + } +} + +/// Subsampling step of [`guided_fast`] for `sigma` (1 = no subsampling: the plain guided filter). +pub fn guided_fast_step(sigma: f32) -> usize { + (sigma / 3.0).floor().clamp(1.0, 16.0) as usize +} + +/// Luminance noise reduction: guided filter of log luminance (`sigma` px, `eps`), blended by `k`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct NrLum { + pub sigma: f32, + pub eps: f32, + pub k: f32, +} + +/// Colour noise reduction: chromaticity blurred by `sigma` px, mixed in by `t`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct NrColor { + pub sigma: f32, + pub t: f32, +} + +/// Output pixels per pixel of the original photo for an output of `px_per_long` pixels per unit +/// of the long edge of an original `native_long` pixels long, at most 1 (`crate::Plan::detail_scale`). +pub fn detail_scale(px_per_long: f64, native_long: usize) -> f32 { + let k = (px_per_long / native_long.max(1) as f64) as f32; + if k.is_finite() { k.clamp(0.0, 1.0) } else { 1.0 } +} + +/// Smallest radius (px) noise reduction filters a preview with: [`gaussian`] makes no blur below +/// about 0.58 px and one 3-px box from there ([`lightcraft_raster::blur::box_sigma`]). +const NR_MIN_SIGMA: f32 = 1.0; + +/// Below this fade a preview's noise reduction is not drawn at all (less than 1 % of a 1-px blur). +const NR_MIN_BLEND: f32 = 0.01; + +/// Radius and blend weight that stand in for a blur of `sigma` px: below [`NR_MIN_SIGMA`] the +/// smallest blur the filter makes, blended in by the ratio of their variances, which keeps the +/// smoothing's second moment (how much it softens the finest detail) that of `sigma`. +fn nr_radius(sigma: f32) -> (f32, f32) { + if sigma >= NR_MIN_SIGMA { + return (sigma, 1.0); + } + let made = crate::raster::blur::box_sigma(NR_MIN_SIGMA); + (NR_MIN_SIGMA, (sigma / made).powi(2).min(1.0)) +} + +/// Noise-reduction parameters at `scale` output pixels per pixel of the original +/// (`crate::Plan::detail_scale`; see [`denoise`]). Noise lives at the original's pixels, so the +/// radii are the full-size radii times `scale`, and the guided filter's `eps` (the variance it +/// treats as noise) follows the noise variance, which averaging `1/scale × 1/scale` pixels into one +/// multiplies by `scale²`. A radius below `NR_MIN_SIGMA` fades instead (`nr_radius`): previews look like +/// the full-size render scaled down (issue #960). At `scale` 1 these are the full-size parameters. +pub fn nr_params(s: &DevelopSettings, scale: f32) -> (Option, Option) { + let lum = (s.detail.nr_luminance / 100.0) as f32; + let col = (s.detail.nr_color / 100.0) as f32; + let scale = if scale.is_finite() { scale.clamp(0.0, 1.0) } else { 1.0 }; + let l = (lum > 0.0).then(|| nr_radius((1.0 + 2.5 * lum) * scale)).filter(|&(_, w)| w >= NR_MIN_BLEND).map(|(sigma, w)| { + let detail = (s.detail.nr_detail / 100.0) as f32; + let eps = ((0.002 + lum * lum * 0.25 * (1.0 - 0.7 * detail)) * scale * scale).max(1e-7); + NrLum { sigma, eps, k: lum.sqrt() * w } + }); + let smooth = 1.0 + (s.detail.nr_color_smoothness / 100.0) as f32; + let c = (col > 0.0).then(|| nr_radius((1.5 + 6.0 * col) * scale * smooth)).filter(|&(_, w)| w >= NR_MIN_BLEND).map(|(sigma, w)| { + let keep = (s.detail.nr_color_detail / 100.0) as f32 * 0.5; + NrColor { sigma, t: col * (1.0 - keep) * w } + }); + (l, c) +} + +/// Noise reduction at output resolution: luminance via an edge-aware self-guided filter on +/// log-luminance, colour by blurring chromaticity (rgb / Y) and re-applying the original luminance. +/// `scale`: output pixels per pixel of the original ([`nr_params`]). `colour_noise`: the whole +/// frame's noise model for the joint colour NR (`crate::colour_noise`; `None`: measured on `img`). +pub fn denoise(img: &mut Rgb32f, s: &DevelopSettings, scale: f32, colour_noise: Option<&crate::nrc_joint::JointNoise>) { + let (lum, col) = nr_params(s, scale); + if col.is_some() && joint_colour_nr(s) { + apply_nr(img, lum, None); + if let Some(p) = nrc_params(s, scale) { + crate::nrc_joint::denoise(img, &p, (s.detail.nr_color_detail / 100.0) as f32, (s.detail.nr_color / 100.0) as f32, colour_noise); + } + return; + } + apply_nr(img, lum, col); +} + +/// Noise reduction with explicit parameters (see [`denoise`]). +pub fn apply_nr(img: &mut Rgb32f, lum: Option, col: Option) { + let w = img.width; + if let Some(nr) = lum { + let l = img.map(log_lum); + let f = guided(&l, nr.sigma, nr.eps); + for_rows(&mut img.data, w, |y, row| { + for (x, p) in row.iter_mut().enumerate() { + let i = y * w + x; + let d = (f.data[i] - l.data[i]) * nr.k; + let g = d.exp2(); + *p = p.map(|v| v * g); + } + }); + } + if let Some(nr) = col { + let chroma = img.map(|c| { + let y = luminance_2020(c).max(1e-6); + [c[0] / y, c[1] / y, c[2] / y] + }); + let b = gaussian(&chroma, nr.sigma); + for_rows(&mut img.data, w, |y, row| { + for (x, p) in row.iter_mut().enumerate() { + let i = y * w + x; + let yl = luminance_2020(*p); + let c0 = chroma.data[i]; + let cb = b.data[i]; + *p = [0, 1, 2].map(|k| ((c0[k] + (cb[k] - c0[k]) * nr.t) * yl).max(0.0)); + } + }); + } +} + +/// Most samples the noise level of the new colour noise reduction is measured from. The CPU and +/// the GPU sample the same pixels (see `nrc_joint::noise_sample_stride`). +pub const NRC_SAMPLES: usize = 131_072; + +/// One self-guided pass of the new colour noise reduction: Gaussian windows of `sigma` px, the +/// coefficients computed on a plane subsampled by `step`, `eps = k ×` the `pct`-quantile of the +/// local variance. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct NrcPass { + pub sigma: f32, + pub step: usize, + pub k: f32, + pub pct: f32, +} + +/// Parameters of the new colour noise reduction: the offset of the square roots and the passes +/// (fine, then coarse). +#[derive(Clone, Debug, PartialEq)] +pub struct NrcParams { + pub off: f32, + pub passes: Vec, +} + +/// The new colour noise reduction's parameters at `scale` output pixels per pixel of the original +/// (`crate::Plan::detail_scale`), `None` when Color is 0. +pub fn nrc_params(s: &DevelopSettings, scale: f32) -> Option { + let amount = (s.detail.nr_color / 100.0) as f32; + if amount <= 0.0 { + return None; + } + let detail = (s.detail.nr_color_detail / 100.0) as f32; + let smooth = 1.0 + (s.detail.nr_color_smoothness / 100.0) as f32; + let scale = if scale.is_finite() { scale.clamp(0.05, 1.0) } else { 1.0 }; + let sigma = (2.0 + 10.0 * amount) * smooth * scale; + let k = 64.0 * amount * (1.5 - detail); + // the coefficients vary over about sigma: a grid of sigma / 2 holds them + let pass = |sigma: f32| NrcPass { sigma, step: (sigma / 2.0).floor().clamp(1.0, 16.0) as usize, k, pct: 0.2 }; + // fine, then coarse (three times wider); the joint method takes the coarse one's reach + Some(NrcParams { off: 0.003, passes: vec![pass(sigma), pass(sigma * 3.0)] }) +} + +/// Chroma noise variance per channel as a function of the local luminance: `α · Y + β` (shot plus read noise). +#[derive(Clone, Copy, Debug)] +pub struct NrcNoise { + pub alpha: [f32; 3], + pub beta: [f32; 3], +} + +impl NrcNoise { + #[inline] + pub fn var(&self, i: usize, y: f32) -> f32 { + (self.alpha[i] * y.max(0.0) + self.beta[i]).max(1e-14) + } +} + +/// Weighted least squares `v = a · l + b` over `(l, v, weight)` with `a, b ≥ 0`: the free fit if both come out +/// non-negative, else the better of the line through the origin (`b = 0`) and the constant (`a = 0`). +pub fn fit_nonneg_line(pts: &[(f64, f64, f64)]) -> (f64, f64) { + let sw: f64 = pts.iter().map(|p| p.2).sum::().max(1e-300); + let (ml, mv) = (pts.iter().map(|p| p.2 * p.0).sum::() / sw, pts.iter().map(|p| p.2 * p.1).sum::() / sw); + let (cov, vl) = pts.iter().fold((0.0, 0.0), |(c, v), p| (c + p.2 * (p.0 - ml) * (p.1 - mv), v + p.2 * (p.0 - ml) * (p.0 - ml))); + if vl > 0.0 { + let a = cov / vl; + let b = mv - a * ml; + if a >= 0.0 && b >= 0.0 { + return (a, b); + } + } + let sse = |a: f64, b: f64| pts.iter().map(|p| p.2 * (p.1 - a * p.0 - b).powi(2)).sum::(); + let ll: f64 = pts.iter().map(|p| p.2 * p.0 * p.0).sum(); + let origin = if ll > 0.0 { (pts.iter().map(|p| p.2 * p.0 * p.1).sum::() / ll).max(0.0) } else { 0.0 }; + let constant = mv.max(0.0); + if sse(origin, 0.0) < sse(0.0, constant) { (origin, 0.0) } else { (0.0, constant) } +} + +/// Whether `s` gets the joint colour noise reduction (`nrc_joint`, process V6 on), else main's +/// blurred chromaticity. +pub fn joint_colour_nr(s: &DevelopSettings) -> bool { + s.process.process() >= Process::V6 +} + +pub fn log_lum(c: [f32; 3]) -> f32 { + (luminance_2020(c).max(1e-7) / crate::tone::GREY).log2() +} + +/// Spatial planes of one (pre-exposure) image, each tagged with the radius it was computed at. +#[derive(Clone, Default)] +pub struct Planes { + pub key: u64, + /// The image's key without its noise reduction (`Plan::pre_nr_key`). + pub pre_nr: u64, + pub log_l: Option>, + /// Keyed by its radius, process and median radius ([`BaseKey`]). + pub base: Option<(BaseKey, Arc)>, + pub clarity: Option<(u32, Arc)>, + pub texture: Option<(u32, Arc)>, + /// Sharpening blur (exact Gaussian at the sharpen radius). + pub sharpen: Option<(SharpenKey, Arc)>, + /// Dark channel and its airlight. + pub dark: Option<(u32, Arc, f32)>, + /// Blurred chromaticity (local Moiré / Noise). + pub chroma: Option<(u32, Arc)>, +} + +impl Planes { + /// The planes that still fit an image differing from this one only in noise reduction, close + /// enough for a draft: the wide blurs (base, clarity, dehaze, chromaticity). Its `key` matches + /// no image, so only another draft takes them. + pub fn for_other_nr(self) -> Planes { + Planes { key: 0, pre_nr: self.pre_nr, log_l: None, texture: None, sharpen: None, ..self } + } +} + +/// What the highlights/shadows base plane was computed with: its radius (`f32` bits), the +/// rendering process and the median radius ([`tone_base_detail`]). The base differs between +/// processes, so a photo moved to another one (Update to Current Process, undo) recomputes it. +pub type BaseKey = (u32, Process, usize); + +pub type SharpenKey = (u32, Process); + +pub fn sharpen_key(s: &DevelopSettings, sigma: f32) -> SharpenKey { + (sigma.to_bits(), s.process.process()) +} + +/// Whether `s`'s highlights/shadows base takes [`detail_free`] (process V8 on) instead of V2's plain +/// [`median_hv`] (V2 to V7, which shipped with it and stay frozen). +pub fn base_keeps_gaps(s: &DevelopSettings) -> bool { + s.process.process() >= Process::V8 +} + +pub fn pixel_sharpen(s: &DevelopSettings) -> bool { + s.process.process() >= Process::V3 +} + +/// The [`BaseKey`] of a base at `sigma` for `s` (`detail`: [`PlaneSigmas::base_detail`]). +pub fn base_key(s: &DevelopSettings, sigma: f32, detail: usize) -> BaseKey { + (sigma.to_bits(), s.process.process(), detail) +} + +/// Reuse `slot` if it was computed with `key` (a radius's `f32` bits, or a [`BaseKey`]), else +/// compute and store it. +pub fn plane_at(slot: &mut Option<(K, Arc

)>, key: K, f: impl FnOnce() -> P) -> Arc

{ + match slot { + Some((k, p)) if *k == key => p.clone(), + _ => { + let p = Arc::new(f()); + *slot = Some((key, p.clone())); + p + } + } +} + +/// Guided-filter epsilons (EV²) of the highlights/shadows base and the clarity band. +pub const BASE_EPS: f32 = 0.35; +pub const CLARITY_EPS: f32 = 0.8; + +/// Dark channel of a pixel (dehaze). +#[inline] +pub fn dark_of(c: [f32; 3]) -> f32 { + c[0].min(c[1]).min(c[2]) +} + +/// Radius of the local Moiré / colour-noise chromaticity blur, as a fraction of the long edge. +pub const CHROMA_SIGMA: f32 = 0.004; + +/// Radii (px) of the spatial planes the settings need (`None` = not needed). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct PlaneSigmas { + /// Edge-aware base for highlights/shadows ([`tone_base`]: fast guided filter, [`BASE_EPS`]; from + /// process V2 of a median at [`BASE_DETAIL`], from V8 of a detail-free plane). + pub base: Option, + /// Median radius (px) of that base ([`tone_base_detail`]: 0 under V1). + pub base_detail: usize, + /// Clarity band (fast guided filter, [`CLARITY_EPS`]). + pub clarity: Option, + /// Texture / sharpening band (Gaussian). + pub texture: Option, + /// Sharpening blur (exact Gaussian, see [`sharpen_sigma`]). + pub sharpen: Option, + /// Dehaze dark channel (Gaussian). + pub dark: Option, + /// Chromaticity blur for local Moiré / colour noise (Gaussian). + pub chroma: Option, +} + +/// Gaussian sigma (pixels) of the texture / sharpening band at `px_per_long`. +pub fn texture_sigma(px_per_long: f64) -> f32 { + (0.0018 * px_per_long as f32).max(0.6) +} + +/// Sharpening blur radius in output pixels before clamping: Radius (source pixels) times the +/// output pixels per original pixel (`native_long` = the original photo's long edge), so a preview and +/// an export show the same detail at the same displayed scale. +pub fn sharpen_sigma_raw(s: &DevelopSettings, px_per_long: f64, native_long: f64) -> f32 { + let r = s.detail.sharpen_radius; + let radius = if r.is_finite() { r.clamp(0.1, 10.0) } else { 1.0 }; + (radius * px_per_long / native_long.max(1.0)) as f32 +} + +/// Smallest and largest sigma (px) of the sharpening blur. The largest is the most the Gaussian taps +/// support (CPU and GPU share them), so an enlarging export keeps every Radius step distinct. +pub const SHARPEN_SIGMA_MIN: f32 = 0.5; +pub const SHARPEN_SIGMA_MAX: f32 = crate::raster::blur::GAUSS_SIGMA_MAX; + +/// The sharpening blur's sigma for a raw value of [`sharpen_sigma_raw`]. +pub fn sharpen_sigma(raw: f32) -> f32 { + raw.clamp(SHARPEN_SIGMA_MIN, SHARPEN_SIGMA_MAX) +} + +/// Match the continuous Gaussian's Nyquist response below half a pixel, using a representable +/// FIR blur. Blend the correction out between half and one pixel: no jump at the floor, and +/// full-pixel sharpening (including Radius 1 at native size) is unchanged. +pub fn sharpen_gain(raw: f32) -> f32 { + if !raw.is_finite() || raw <= 0.0 { + return 0.0; + } + if raw >= 1.0 { + return 1.0; + } + let taps = gauss_taps(sharpen_sigma(raw)); + let radius = taps.len() / 2; + let response = taps.iter().enumerate().map(|(i, &t)| if (i + radius).is_multiple_of(2) { t } else { -t }).sum::(); + let desired = -(-0.5 * std::f32::consts::PI.powi(2) * raw * raw).exp_m1(); + let ratio = desired / (1.0 - response).max(1e-6); + let blend = ((1.0 - raw) / 0.5).clamp(0.0, 1.0); + 1.0 + (ratio - 1.0) * blend +} + +pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, native_long: f64, q: Quality) -> PlaneSigmas { + let ppl = px_per_long as f32; + // A hidden mask, or one with no components, does not change the picture. Its sliders must + // not pick the tone base Clarity reads (#1214). + let live = |m: &&Mask| m.visible && !m.components.is_empty(); + let local_any = |f: fn(&LocalAdjustments) -> f64| s.masks.iter().filter(live).any(|m| f(&m.adjust) != 0.0); + let tone_active = s.light.highlights != 0.0 + || s.light.shadows != 0.0 + || s.masks.iter().filter(live).any(|m| m.adjust.highlights != 0.0 || m.adjust.shadows != 0.0); + // Edge-aware base at ~1.5% of the long edge (EV² epsilon: edges of > ~0.6 EV are preserved) + // From V2 it is taken of the median at 0.15%: lines and texture finer than that are detail, + // not tone (#632). + let base = tone_active.then(|| { + let sigma = (0.015 * ppl).max(1.0); + if q == Quality::Draft { sigma.min(24.0) } else { sigma } + }); + let clarity = (s.effects.clarity != 0.0 || local_any(|a| a.clarity)).then(|| (0.012 * ppl).max(1.0)); + // local Noise and Defringe read the fine detail band too + let texture = (s.effects.texture != 0.0 + || local_any(|a| a.texture) + || local_any(|a| a.noise) + || (!pixel_sharpen(s) && (s.detail.sharpen_amount != 0.0 || local_any(|a| a.sharpness))) + || s.masks.iter().filter(live).any(|m| m.adjust.defringe > 0.0)) + .then(|| texture_sigma(px_per_long)); + let dark = (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze)).then(|| (0.02 * ppl).max(1.0)); + let chroma = (local_any(|a| a.moire) || s.masks.iter().filter(live).any(|m| m.adjust.noise > 0.0)).then(|| (CHROMA_SIGMA * ppl).max(1.0)); + let base_detail = if base.is_some() { tone_base_detail(s, px_per_long) } else { 0 }; + // V1/V2 keep their texture-band sharpening; only V3 requests the pixel-scale plane. + let sharpen_raw = sharpen_sigma_raw(s, px_per_long, native_long); + let sharpen = (pixel_sharpen(s) && sharpen_gain(sharpen_raw) > 0.0 && (s.detail.sharpen_amount != 0.0 || local_any(|a| a.sharpness))) + .then(|| sharpen_sigma(sharpen_raw)); + PlaneSigmas { base, base_detail, clarity, texture, sharpen, dark, chroma } +} + +/// The airlight is estimated from every `AIRLIGHT_STEP`-th value of the dark channel. +pub const AIRLIGHT_STEP: usize = 7; + +/// Airlight estimate: bright end of the dark channel. +pub fn airlight(dark: &Plane) -> f32 { + airlight_of(dark.data.iter().step_by(AIRLIGHT_STEP).copied().collect()) +} + +/// Airlight from the sampled dark-channel values (see [`airlight`]): their 99.5th percentile. +pub fn airlight_of(mut v: Vec) -> f32 { + if v.is_empty() { + return 1.0; + } + let k = ((v.len() as f32) * 0.995) as usize; + let k = k.min(v.len() - 1); + v.select_nth_unstable_by(k, |a, b| a.total_cmp(b)); + v[k].max(0.05) +} + +#[cfg(test)] +mod tests { + /// Edits saved under V1 to V5 keep main's colour noise reduction (blurred chromaticity); V6 gets + /// the joint method of `nrc_joint`. + #[test] + fn colour_nr_follows_the_process() { + use craft_develop_model::{DevelopSettings, Process}; + let (w, h) = (96usize, 64usize); + let img = Rgb32f::from_fn(w, h, |x, y| { + let n = |c: u32| { + let mut v = (x as u32).wrapping_mul(0x9e37_79b9) ^ (y as u32).wrapping_mul(0x85eb_ca6b) ^ c.wrapping_mul(0xc2b2_ae35) | 1; + v ^= v << 13; + v ^= v >> 17; + v ^= v << 5; + (v as f32 / u32::MAX as f32 - 0.5) * 0.02 + }; + let base = if x < w / 2 { [0.06, 0.03, 0.02] } else { [0.02, 0.04, 0.06] }; + [base[0] + n(1), base[1] + n(2), base[2] + n(3)] + }); + let run = |p: Process| { + let mut s = DevelopSettings { process: p.version(), ..Default::default() }; + s.detail.nr_color = 50.0; + let mut o = img.clone(); + denoise(&mut o, &s, 1.0, None); + o + }; + let (v1, v2, v5, v6) = (run(Process::V1), run(Process::V2), run(Process::V5), run(Process::V6)); + assert!(v1.data == v2.data && v2.data == v5.data, "V1 to V5 share main's colour NR"); + // main's colour NR clamps at 0 and keeps each pixel's luminance; the joint method keeps it too + assert!(v5.data != v6.data, "V6 takes the joint colour NR"); + let mut s = DevelopSettings { process: Process::V6.version(), ..Default::default() }; + s.detail.nr_color = 50.0; + let mut joint = img.clone(); + let p = nrc_params(&s, 1.0).expect("Color 50 has parameters"); + crate::nrc_joint::denoise(&mut joint, &p, (s.detail.nr_color_detail / 100.0) as f32, 0.5, None); + assert!(joint.data == v6.data, "V6 is the joint method"); + } + + /// Float mean of a flat, noisy dark patch over three noise realisations; linear modes assert drift bounds. + #[test] + #[ignore] + fn probe_nrc_mean_drift() { + use craft_develop_model::DevelopSettings; + let (w, h) = (768usize, 768usize); + let mut worst = 0.0f64; + for seed0 in [0x2545_f491_4f6c_dd1du64, 0x9e37_79b9_7f4a_7c15, 0x1234_5678_9abc_def1] { + let mut seed = seed0; + let mut gauss = || { + (0..4) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5 + }) + .sum::() + * 1.732 + }; + for (name, base, sigma) in [ + ("dark warm, blue near 0", [0.006f32, 0.004, 0.0008], [0.002f32, 0.0015, 0.003]), + ("cat-like, red near 0", [0.0015, 0.004, 0.009], [0.004, 0.003, 0.005]), + ] { + let mut img = Rgb32f::new(w, h); + for p in img.data.iter_mut() { + *p = [0, 1, 2].map(|i| base[i] + sigma[i] * gauss()); + } + let mean = |im: &Rgb32f| { + let n = im.data.len() as f64; + [0, 1, 2].map(|i| im.data.iter().map(|p| p[i] as f64).sum::() / n) + }; + let m0 = mean(&img); + for nr in [25.0, 100.0] { + let mut s = DevelopSettings::default(); + s.detail.nr_color = nr; + let mut a = img.clone(); + denoise(&mut a, &s, 1.0, None); + let m = mean(&a); + let clipped0 = mean(&img.map(|p| p.map(|v| v.max(0.0)))); + let sd = |im: &Rgb32f, mm: [f64; 3]| { + [0, 1, 2].map(|i| (im.data.iter().map(|p| (p[i] as f64 - mm[i]).powi(2)).sum::() / im.data.len() as f64).sqrt()) + }; + worst = worst.max([0, 1, 2].iter().map(|&i| (m[i] / m0[i] - 1.0).abs()).fold(0.0, f64::max)); + println!( + "{name} NR {nr}: true mean {m0:.5?}, clipped noisy mean {clipped0:.5?}, after v2 {m:.5?} → {:+.3?} % vs true; noise sd {:.5?} → {:.5?}", + [0, 1, 2].map(|i| 100.0 * (m[i] / m0[i] - 1.0)), + sd(&img, m0), + sd(&a, m) + ); + } + } + } + println!("worst mean deviation {:.4} %", 100.0 * worst); + assert!(worst < 0.0005, "the joint colour NR moved a channel's mean by {:.3} %", 100.0 * worst); + } + + /// PROBE (prints, never fails): what colour NR v2 keeps of real colour. A clean synthetic scene (an + /// equal-luminance red/green edge, a 2 px red line on grey, a saturated blue patch near black, a flat grey + /// patch) plus noise; each measure compares the output with the clean scene. + #[test] + #[ignore] + fn probe_nrc_real_colour() { + use craft_develop_model::DevelopSettings; + let (w, h) = (768usize, 512usize); + let y_of = |c: [f32; 3]| luminance_2020(c); + // two colours of the same luminance 0.03 + let red = [0.08f32, 0.0155, 0.02]; + let green = { + let g = [0.012f32, 0.04, 0.015]; + let k = y_of(red) / y_of(g); + g.map(|v| v * k) + }; + let grey = [0.03f32; 3]; + let blue_dark = [0.001f32, 0.0015, 0.02]; + // a bright saturated green next to black (a lit leaf against a dark background) + let leaf = [0.02f32, 0.12, 0.01]; + let clean = |x: usize, y: usize| -> [f32; 3] { + if y < 256 { + if x < 384 { red } else { green } + } else if x < 384 { + if (190..192).contains(&x) { red } else { grey } + } else if x < 576 { + blue_dark + } else if y < 384 { + grey + } else if x < 672 { + leaf + } else { + [0.0005f32; 3] + } + }; + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut gauss = || { + (0..4) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5 + }) + .sum::() + * 1.732 + }; + let mut img = Rgb32f::new(w, h); + for y in 0..h { + for x in 0..w { + let c = clean(x, y); + // shot + read noise per channel + img.data[y * w + x] = c.map(|v| v + (0.00002 + 0.004 * v.max(0.0)).sqrt() * 0.6 * gauss()); + } + } + let chroma = |c: [f32; 3]| { + let y = y_of(c); + c.map(|v| v - y) + }; + let dist = |a: [f32; 3], b: [f32; 3]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt(); + for nr in [25.0, 100.0] { + let mut s = DevelopSettings::default(); + s.detail.nr_color = nr; + let mut o = img.clone(); + denoise(&mut o, &s, 1.0, None); + let px = |x: usize, y: usize| o.data[y * w + x]; + // edge: chroma error 1..8 px either side, relative to the step between the two colours + let step = dist(chroma(red), chroma(green)); + let mut e = 0.0; + let mut n = 0.0; + for y in 40..216 { + for d in 1..=8 { + for x in [384 - d, 383 + d] { + e += dist(chroma(px(x, y)), chroma(clean(x, y))); + n += 1.0; + } + } + } + // line: share of the line's chroma kept (mean over its rows) + let (mut kept, mut m) = (0.0, 0.0); + for y in 300..480 { + for x in 190..192 { + let c = chroma(px(x, y)); + let r = chroma(red); + let rg = chroma(grey); + let full = [0, 1, 2].map(|i| r[i] - rg[i]); + let got = [0, 1, 2].map(|i| c[i] - rg[i]); + kept += (got[0] * full[0] + got[1] * full[1] + got[2] * full[2]) / (full[0] * full[0] + full[1] * full[1] + full[2] * full[2]); + m += 1.0; + } + } + // saturated blue near black: chroma of the patch's mean kept + let mut acc = [0.0f32; 3]; + let mut cnt = 0.0; + for y in 300..480 { + for x in 420..540 { + acc = [0, 1, 2].map(|i| acc[i] + px(x, y)[i]); + cnt += 1.0; + } + } + let mean = acc.map(|v| v / cnt); + let sat_kept = dist(chroma(mean), [0.0; 3]) / dist(chroma(blue_dark), [0.0; 3]); + // grey: residual chroma noise + let mut sd = 0.0; + let mut k = 0.0; + for y in 270..370 { + for x in 600..760 { + sd += dist(chroma(px(x, y)), [0.0; 3]).powi(2); + k += 1.0; + } + } + let mut sd0 = 0.0; + for y in 270..370 { + for x in 600..760 { + sd0 += dist(chroma(img.data[y * w + x]), [0.0; 3]).powi(2); + } + } + // leaf next to black: chroma kept in the leaf's 12 px next to the black (mean over rows) + let (mut lk, mut ln) = (0.0f32, 0.0f32); + for y in 400..500 { + for x in 660..672 { + let c = chroma(px(x, y)); + let r = chroma(leaf); + lk += (c[0] * r[0] + c[1] * r[1] + c[2] * r[2]) / (r[0] * r[0] + r[1] * r[1] + r[2] * r[2]); + ln += 1.0; + } + } + println!("NR {nr}: leaf next to black keeps {:.0} % of its chroma (12 px next to the black)", 100.0 * lk / ln); + println!( + "NR {nr}: edge error {:.1} % of the step | red line kept {:.0} % | dark blue chroma kept {:.0} % | grey chroma noise {:.5} → {:.5}", + 100.0 * e / n / step, + 100.0 * kept / m, + 100.0 * sat_kept, + (sd0 / k).sqrt(), + (sd / k).sqrt() + ); + } + } + + #[test] + fn nrc_noise_fit_is_non_negative() { + // a falling cloud would give a negative slope: the constant fits instead + let (a, b) = fit_nonneg_line(&[(0.0, 4.0, 1.0), (1.0, 3.0, 1.0), (2.0, 2.0, 1.0)]); + assert!(a == 0.0 && (b - 3.0).abs() < 1e-9); + // a line through a negative intercept: refitted through the origin + let (a, b) = fit_nonneg_line(&[(1.0, 1.0, 1.0), (2.0, 3.0, 1.0), (3.0, 5.0, 1.0)]); + assert!(a > 0.0 && b == 0.0); + // an exact shot + read noise line is found as it is + let (a, b) = fit_nonneg_line(&[(0.0, 2.0, 1.0), (1.0, 5.0, 1.0), (2.0, 8.0, 1.0)]); + assert!((a - 3.0).abs() < 1e-9 && (b - 2.0).abs() < 1e-9); + } + use super::*; + use craft_color_transform::cct::xy_to_uv; + + #[test] + fn guided_preserves_step_edges_and_flattens_texture() { + let p = Plane::from_fn(80, 20, |x, y| if x < 40 { -2.0 } else { 2.0 } + if (x + y) % 2 == 0 { 0.05 } else { -0.05 }); + let q = guided(&p, 4.0, 0.3); + // edge kept + assert!(q.get(35, 10) < -1.5 && q.get(45, 10) > 1.5); + // checkerboard texture removed away from the edge + assert!((q.get(10, 10) - q.get(11, 10)).abs() < 0.02); + } + + #[test] + fn wb_as_shot_is_identity_and_warming_adds_red() { + let s = DevelopSettings::default(); + let info = WbSource::default(); + let mut img = Rgb32f::filled(4, 4, [0.3, 0.3, 0.3]); + scene_linear_pre(&mut img, &info, &s); + assert!((img.get(0, 0)[0] - 0.3).abs() < 1e-6); + let mut warm = s.clone(); + warm.wb.mode = WbMode::Custom; + warm.wb.temp = 9000.0; + let mut img2 = Rgb32f::filled(4, 4, [0.3, 0.3, 0.3]); + scene_linear_pre(&mut img2, &info, &warm); + let c = img2.get(0, 0); + assert!(c[0] > c[2], "{c:?}"); + // luminance preserved + assert!((luminance_2020(c) - 0.3).abs() < 0.01); + } + + #[test] + fn process_v10_uses_checked_wb() { + let mut s = DevelopSettings::default(); + assert!(!checked_wb(&s)); + s.process = craft_develop_model::ProcessVersion(10); + assert!(checked_wb(&s)); + } + + #[test] + fn a_hidden_or_empty_mask_does_not_request_the_tone_base() { + use craft_develop_model::{Mask, MaskComponent, MaskOp, MaskShape}; + use craft_geom::Point; + let shape = MaskShape::Linear { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0) }; + let component = MaskComponent { name: None, op: MaskOp::Add, invert: false, shape }; + let mut s = DevelopSettings::default(); + s.masks.push(Mask { + visible: false, + components: vec![component], + adjust: craft_develop_model::LocalAdjustments { highlights: 40.0, ..Default::default() }, + ..Default::default() + }); + assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_none()); + s.masks[0].visible = true; + s.masks[0].components.clear(); + assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_none()); + s.masks[0].components.push(MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0) }, + }); + assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_some()); + } + + #[test] + fn exposure_doubles() { + let mut s = DevelopSettings::default(); + s.light.exposure = 1.0; + let mut img = Rgb32f::filled(2, 2, [0.1, 0.2, 0.3]); + scene_linear_pre(&mut img, &WbSource::default(), &s); + assert!((img.get(1, 1)[2] - 0.6).abs() < 1e-5); + } + + /// [`kelvin_to_legacy`] inverts [`legacy_to_kelvin`] over the whole relative slider range and back: the + /// round trip returns the start, in both directions, to the precision of the Kelvin / tint parametrisation. + #[test] + fn kelvin_to_legacy_inverts_legacy_to_kelvin() { + for as_shot in [(4986.0, -2.0), (6500.0, 0.0), (3200.0, 14.0), (9500.0, -12.0)] { + // the relative slider's whole reach: temp 0..100 (2000–13550 K around 6500), tint −150..150 + for pct in [0.0, 12.5, 25.0, 50.0, 75.0, 100.0] { + for tint in [-150.0, -40.0, 0.0, 33.0, 150.0] { + let (lt, ltint) = controls_relative(pct, tint); + let (kt, ktint) = legacy_to_kelvin(lt, ltint, as_shot); + // past the Kelvin parametrisation's own reach (its search runs 1000–50000 K) the forward + // conversion has already clamped, so the pair is not expected to come back + if !(1050.0..=49_000.0).contains(&kt) { + continue; + } + let back = kelvin_to_legacy(kt, ktint, as_shot).unwrap(); + let (x1, y1) = xy_to_uv(temp_tint_to_xy(lt, ltint)); + let (x2, y2) = xy_to_uv(temp_tint_to_xy(back.0, back.1)); + // the pair may differ by more than the slider's own step at the extreme corners (the Kelvin + // parametrisation is read back through a search), but never by much, and the white it renders + // is the same + assert!( + (back.0 - lt).abs() <= lt.abs() * 0.01 && (back.1 - ltint).abs() < 0.5, + "as shot {as_shot:?}: relative ({lt}, {ltint}) -> kelvin ({kt}, {ktint}) -> {back:?}" + ); + assert!((x1 - x2).hypot(y1 - y2) < 1e-3, "as shot {as_shot:?}: relative ({lt}, {ltint}) -> kelvin ({kt}, {ktint}) -> {back:?}"); + } + } + // the other direction: every white the relative scale can hold maps back to a pair that renders the same + for kt in [as_shot.0, 2500.0, 4200.0, 6500.0, 12000.0] { + for ktint in [-60.0, 0.0, 45.0] { + let Some((lt, ltint)) = kelvin_to_legacy(kt, ktint, as_shot) else { continue }; + // outside the slider's reach the relative scale has no value for this white: the forward + // conversion would clamp, so the round trip is not expected to close there + if !(2000.0..=13550.0).contains(<) || ltint.abs() > 150.0 { + continue; + } + let (kt2, ktint2) = legacy_to_kelvin(lt, ltint, as_shot); + let (x1, y1) = xy_to_uv(temp_tint_to_xy(kt, ktint)); + let (x2, y2) = xy_to_uv(temp_tint_to_xy(kt2, ktint2)); + assert!( + (x1 - x2).hypot(y1 - y2) < 1e-3, + "as shot {as_shot:?}: kelvin ({kt}, {ktint}) -> relative ({lt}, {ltint}) -> ({kt2}, {ktint2})" + ); + } + } + // the source's own white is the relative scale's as-shot reference, exactly + assert_eq!(kelvin_to_legacy(as_shot.0, as_shot.1, as_shot), Some((6500.0, 0.0))); + } + // the exact inverse of the special case inside legacy_to_kelvin + assert_eq!(kelvin_to_legacy(4986.0, -2.0, (4986.0, -2.0)), Some((6500.0, 0.0))); + assert_eq!(legacy_to_kelvin(6500.0, 0.0, (4986.0, -2.0)), (4986.0, -2.0)); + // hostile numbers answer None, never a panic or a plausible lie + assert_eq!(kelvin_to_legacy(f64::NAN, 0.0, (5000.0, 0.0)), None); + assert_eq!(kelvin_to_legacy(5000.0, f64::INFINITY, (5000.0, 0.0)), None); + assert_eq!(kelvin_to_legacy(5000.0, 0.0, (f64::NAN, 0.0)), None); + } + + /// The relative scale's `(temp, tint)` for a slider temperature at `pct` % (2000–7000 K fill the left half) and tint. + fn controls_relative(pct: f64, tint: f64) -> (f64, f64) { + let t = if pct <= 50.0 { 2000.0 + pct * 100.0 } else { 7000.0 + (pct - 50.0) * 131.0 }; + (t, tint) + } +} + +#[cfg(test)] +mod fast_tests { + use super::*; + + /// [`detail_free`] enlarges the coarse median as it clamps; the result is the plain + /// composition of `resize` and [`median_hv`], bit for bit. + #[test] + fn detail_free_matches_its_reference() { + use crate::raster::resample::{Filter, resize}; + for (w, h) in [(1, 1), (2, 1), (3, 3), (4, 7), (61, 47), (200, 31)] { + let p = Plane::from_fn(w, h, |x, y| ((x * 37 + y * 101) % 23) as f32 * 0.4 - 4.0 + if (x / 5 + y / 7) % 2 == 0 { 2.0 } else { 0.0 }); + for r in [1, 2, 5, 10] { + let fine = median_hv(&p, r); + let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP), h.div_ceil(BASE_COARSE_STEP)); + let coarse = resize(&median_hv(&resize(&p, lw, lh, Filter::Box), r), w, h, Filter::Bilinear); + let want: Vec = (0..w * h).map(|i| clamp_between(p.data[i], fine.data[i], coarse.data[i]).to_bits()).collect(); + let got: Vec = detail_free(&p, r).data.iter().map(|v| v.to_bits()).collect(); + assert_eq!(got, want, "{w}×{h} r={r}"); + } + } + } + + /// CPU highlights/shadows base timings on the #3460 frame size: + /// `cargo test --release -p craft-develop bench_tone_base_cpu -- --ignored --nocapture`. + #[test] + #[ignore] + fn bench_tone_base_cpu() { + let (w, h) = (6960, 4640); + let r = base_detail_radius(w as f64); + let p = Plane::from_fn(w, h, |x, y| ((x * 7 + y * 13) % 1000) as f32 / 250.0 - 6.0 + if (x / 40 + y / 40) % 2 == 0 { 1.0 } else { 0.0 }); + let sigma = 0.015 * w as f32; + let time = |name: &str, f: &dyn Fn() -> Plane| { + let mut ts: Vec = (0..5) + .map(|_| { + let t = std::time::Instant::now(); + std::hint::black_box(f()); + t.elapsed().as_secs_f64() * 1e3 + }) + .collect(); + ts.sort_by(f64::total_cmp); + eprintln!("{name:<20} min {:.1} ms median {:.1} ms", ts[0], ts[2]); + }; + time("median_hv", &|| median_hv(&p, r)); + time("detail_free", &|| detail_free(&p, r)); + time("guided_fast", &|| guided_fast(&p, sigma, BASE_EPS)); + time("tone_base", &|| tone_base(&p, sigma, r, true)); + } + + /// The previous fast path, including its two materialized coefficient resizes. + fn resized_reference(p: &Plane, sigma: f32, eps: f32) -> Plane { + use crate::raster::resample::{Filter, resize}; + let s = guided_fast_step(sigma); + if s <= 1 { + return guided(p, sigma, eps); + } + let lo = resize(p, p.width.div_ceil(s).max(1), p.height.div_ceil(s).max(1), Filter::Box); + let (a, b) = guided_coeffs(&lo, sigma / s as f32, eps); + let (a, b) = (resize(&a, p.width, p.height, Filter::Bilinear), resize(&b, p.width, p.height, Filter::Bilinear)); + Plane::from_fn(p.width, p.height, |x, y| a.get(x, y) * p.get(x, y) + b.get(x, y)) + } + + #[test] + fn sampled_coefficients_match_materialized_resizes() { + for (w, h) in [(0, 0), (1, 1), (1, 19), (23, 1), (2, 3), (17, 13), (64, 48), (161, 119)] { + let planes = [ + Plane::filled(w, h, -3.25), + Plane::from_fn(w, h, |x, y| ((x * 7919 + y * 104729) % 97) as f32 / 7.0 - 8.0), + Plane::from_fn(w, h, |x, y| { + if x == w / 2 && y == h / 2 { + 9.0 + } else if x < w / 2 { + -5.0 + } else { + 2.0 + } + }), + ]; + // Step 1 fallback, every small step, Draft's cap, and the maximum step (16). + for sigma in [0.0, 2.99, 5.99, 6.0, 9.0, 12.0, 24.0, 48.0, 200.0] { + for eps in [BASE_EPS, CLARITY_EPS, 0.0001] { + for p in &planes { + let expected = resized_reference(p, sigma, eps); + let actual = guided_fast(p, sigma, eps); + assert_eq!((actual.width, actual.height), (w, h)); + assert_eq!(actual.data, expected.data, "{w}x{h}, sigma {sigma}, eps {eps}"); + } + } + } + } + } + + #[test] + fn sampled_tone_base_keeps_the_detail_free_plane_before_the_guided_filter() { + let p = Plane::from_fn(73, 51, |x, y| if x % 9 == 0 { 3.0 } else { -4.0 + ((x + y) % 7) as f32 * 0.03 }); + for sigma in [6.0, 24.0, 120.0] { + for detail in [0, 1, 3, BASE_DETAIL_MAX] { + let free = detail_free(&p, detail); + assert_eq!(tone_base(&p, sigma, detail, true).data, resized_reference(&free, sigma, BASE_EPS).data, "{sigma}, {detail}"); + } + } + } + + #[test] + fn fast_guided_close_to_reference() { + let p = Plane::from_fn(160, 120, |x, y| ((x as f32 * 0.13).sin() + (y as f32 * 0.07).cos()) * 2.0 + if x > 80 { 1.5 } else { 0.0 }); + let a = guided(&p, 12.0, 0.3); + let b = guided_fast(&p, 12.0, 0.3); + let err: f32 = a.data.iter().zip(&b.data).map(|(u, v)| (u - v).abs()).sum::() / a.len() as f32; + assert!(err < 0.08, "{err}"); + } +} + +#[cfg(test)] +mod nr_tests { + use super::*; + + #[test] + fn luminance_nr_reduces_noise_keeps_mean() { + let mut img = Rgb32f::from_fn(64, 64, |x, y| { + let n = (((x * 7919 + y * 104729) % 97) as f32 / 97.0 - 0.5) * 0.06; + [0.2 + n; 3] + }); + let var = |im: &Rgb32f| { + let m = im.data.iter().map(|p| p[1]).sum::() / im.len() as f32; + (im.data.iter().map(|p| (p[1] - m).powi(2)).sum::() / im.len() as f32, m) + }; + let (v0, m0) = var(&img); + let mut s = DevelopSettings::default(); + s.detail.nr_luminance = 80.0; + denoise(&mut img, &s, 1.0, None); + let (v1, m1) = var(&img); + assert!(v1 < v0 * 0.5, "{v0} -> {v1}"); + assert!((m1 - m0).abs() < 0.01); + } +} diff --git a/crates/develop/src/local_tone.rs b/crates/develop/src/local_tone.rs new file mode 100644 index 0000000000..079e1b11a7 --- /dev/null +++ b/crates/develop/src/local_tone.rs @@ -0,0 +1,87 @@ +//! The camera's local tone mapping: a raw's DNG `ProfileGainTableMap` (Apple ProRAW), rendered +//! when the photo's Profile option "Camera local tone mapping" is on. Off by default: Lightroom +//! Classic renders ProRAW without it (see `lightcraft_raw::gaintable`). +//! +//! The map is a per-pixel gain that depends on the pixel's position in the raw's active area and +//! on its colour after the baseline exposure (linear ProPhoto). The source the pipeline gets is +//! exactly that colour (scene-linear Rec.2020 after the baseline exposure), so the gain is +//! evaluated here, on the resampled source at output resolution: a preview colours only the pixels +//! it shows. A gain multiplies R, G and B alike, so it commutes with the white balance (a matrix) +//! that follows. Files that also carry a `ProfileLookTable` get the gain after the table instead of +//! before it (DNG 1.7.1); Apple ProRAW has none. + +use craft_color_transform::{D50, D65, PROPHOTO, REC2020, bradford}; + +use crate::raster::{Rgb32f, par_rows}; +use crate::sensor::gaintable::{GainTableMap, GainTableMapApply, SourcePlacement}; + +/// A raw's gain table map and where its developed source sits in the active area. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct LocalTone { + pub map: GainTableMap, + pub placement: SourcePlacement, +} + +/// Multiply the resampled, not yet white-balanced source `img` by the local tone gain at each +/// pixel. For an output pixel `(x, y)`, `active_uv(x, y)` must return normalised (0..=1) +/// coordinates in the EXIF-oriented developed source, not in the raw active area. +/// [`SourcePlacement::active`] undoes the source orientation and maps through the crop to +/// normalised active-area coordinates. Return `None` to leave a blank-canvas pixel unchanged. +pub fn apply(img: &mut Rgb32f, lt: &LocalTone, active_uv: impl Fn(usize, usize) -> Option<(f64, f64)> + Sync) { + let Some(eval) = lt.map.evaluator() else { return }; + let w = img.width; + let to_prophoto = PROPHOTO.from_xyz().mul(&bradford(D65, D50)).mul(&REC2020.to_xyz()).to_f32(); + par_rows(&mut img.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + let Some((u, v)) = active_uv(x, y) else { continue }; + let (ax, ay) = lt.placement.active(u, v); + let m = &to_prophoto; + let q: [f32; 3] = std::array::from_fn(|i| m[i][0] * px[0] + m[i][1] * px[1] + m[i][2] * px[2]); + let g = eval.gain(q, ax, ay); + *px = px.map(|c| c * g); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn local_tone_maps_oriented_source_coordinates_in_full_images_and_tiles() { + // An original synthetic gain grid: the one-sample tables give g = 1 + 2x + 4y. + let lt = LocalTone { + map: GainTableMap { + points_v: 2, + points_h: 2, + points_n: 1, + spacing_v: 1.0, + spacing_h: 1.0, + origin_v: 0.0, + origin_h: 0.0, + weights: [0.0; 5], + gamma: 1.0, + gains: vec![1.0, 3.0, 5.0, 7.0], + }, + placement: SourcePlacement { rect: [0.25, 0.25, 0.5, 0.5], orientation: craft_geom::Orientation::Rotate90 }, + }; + let source_uv = |x, y| match (x, y) { + (2, 1) => Some((0.0, 0.0)), + (3, 1) => Some((1.0, 1.0)), + _ => None, + }; + let pixel = [0.125, 0.25, 0.5]; + let mut full = Rgb32f { width: 4, height: 3, data: vec![pixel; 12] }; + apply(&mut full, <, source_uv); + + let mut expected = vec![pixel; 12]; + // The oriented corners land on opposite crop corners in the active area. + expected[6] = [0.5625, 1.125, 2.25]; // (0.25, 0.75), gain 4.5 + expected[7] = [0.4375, 0.875, 1.75]; // (0.75, 0.25), gain 3.5 + assert_eq!(full.data, expected); + + let mut tile = Rgb32f { width: 2, height: 2, data: vec![pixel; 4] }; + apply(&mut tile, <, |x, y| source_uv(x + 2, y + 1)); + assert_eq!(tile.data, [full.data[6], full.data[7], full.data[10], full.data[11]]); + } +} diff --git a/crates/develop/src/nrc_joint.rs b/crates/develop/src/nrc_joint.rs new file mode 100644 index 0000000000..5fc8a6127d --- /dev/null +++ b/crates/develop/src/nrc_joint.rs @@ -0,0 +1,1194 @@ +//! Linear colour NR with a fixed, denoised joint guide. Strength controls the spatial scale; +//! noise-normalized guide distances control which neighbours can exchange colour. Both chroma +//! components use the same weights. Symmetric fluxes preserve the grid's channel sums, including +//! at its boundaries; no nonnegative clamp or square-root bias correction is involved. + +use crate::colorops::luminance_2020; +use crate::local::{NrcNoise, NrcParams, fit_nonneg_line}; +use crate::raster::{Rgb32f, blur::gaussian, par_rows as for_rows, resample::Filter}; + +/// A pixel sub-rectangle of an image (`x`, `y`, `w`, `h`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PixelWindow { + pub x: usize, + pub y: usize, + pub w: usize, + pub h: usize, +} + +#[derive(Clone, Copy, Debug)] +pub struct JointNoise { + pub model: NrcNoise, + /// Do not extrapolate beyond bands that contain usable noise measurements. + pub ymax: [f32; 3], + pub tolerance: f32, +} + +impl JointNoise { + pub fn var(&self, i: usize, y: f32) -> f32 { + self.model.var(i, y.min(self.ymax[i])) + } +} + +fn yuv(c: [f32; 3]) -> [f32; 3] { + let y = luminance_2020(c); + [y, c[0] - y, c[2] - y] +} + +/// Noise of Y, R-Y and B-Y measured from small high-pass residuals, not the colour variance +/// of a wide smoothing window. The median-square calibration is for Gaussian residuals. +/// Luminance bands with predominantly texture may only lower their weight in the fit: they +/// cannot force a shadow scene's extrapolated highlight noise arbitrarily high. +fn noise_model(img: &Rgb32f) -> JointNoise { + if img.width < 3 || img.height < 3 { + return JointNoise { model: NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }, ymax: [0.0; 3], tolerance: 1.0 }; + } + let mut samples = Vec::new(); + push_samples(img, noise_sample_stride(img.len()), &mut samples); + noise_from_samples(samples) +} + +/// The noise samples of `img` (Y, R-Y, B-Y) every `stride` pixels, in pixel order (see [`noise_model`]). +fn push_samples(img: &Rgb32f, stride: usize, samples: &mut Vec) { + if img.width < 3 || img.height < 3 { + return; + } + for index in (0..img.len()).step_by(stride) { + let (x, y) = (index % img.width, index / img.width); + if x == 0 || y == 0 || x + 1 == img.width || y + 1 == img.height { + continue; + } + let Some(c) = img.data.get(index) else { continue }; + let mut residual = [[0.0f32; 3]; 3]; + let mut brightness = 0.0; + let mut valid = true; + for (scale, delta) in [1usize, 2, 4].into_iter().enumerate() { + // Tiny images use the nearest supported scale rather than extending an edge + // into the noise samples. + let delta = delta.min(x).min(y).min(img.width - x - 1).min(img.height - y - 1); + let neighbours = [index - delta, index + delta, index - delta * img.width, index + delta * img.width]; + let mut m = [0.0f32; 3]; + for n in neighbours { + if let Some(p) = img.data.get(n) { + m = std::array::from_fn(|i| m[i] + 0.25 * p[i]); + } + } + residual[scale] = std::array::from_fn(|i| (c[i] - m[i]).powi(2)); + brightness += m[0] / 3.0; + valid &= c.iter().chain(m.iter()).all(|v| v.is_finite()); + } + if valid { + samples.push((brightness.max(0.0), residual)); + } + } +} + +/// Side of the tiles a frame's noise is measured on (px). +const TILE: usize = 128; +/// Tiles per row and column: many small tiles follow a mostly dark frame's few bright parts better +/// than a few large ones. +const GRID: usize = 12; + +/// The windows of a `full_w × full_h` frame its noise is measured on: the whole frame up to the +/// area of `GRID²` tiles, else `GRID × GRID` tiles spread evenly over it. A windowed render sees +/// only part of the frame; measured on these, every window of it gets the same noise model. +pub fn tiles(full_w: usize, full_h: usize) -> Vec { + if full_w * full_h <= GRID * GRID * TILE * TILE || full_w < 2 * TILE || full_h < 2 * TILE { + return vec![PixelWindow { x: 0, y: 0, w: full_w, h: full_h }]; + } + let at = |n: usize, k: usize| ((n - TILE) as f64 * (k as f64 + 0.5) / GRID as f64).round() as usize; + (0..GRID * GRID).map(|k| PixelWindow { x: at(full_w, k % GRID), y: at(full_h, k / GRID), w: TILE, h: TILE }).collect() +} + +/// The noise model of `tiles` of a frame (linear RGB at output scale, see [`tiles`]): the same +/// measurement as for a whole image, with the samples of all tiles together. +pub fn noise_of_tiles(tiles: &[Rgb32f]) -> JointNoise { + let transformed: Vec = tiles.iter().map(|t| t.map(yuv)).collect(); + let stride = noise_sample_stride(transformed.iter().map(Rgb32f::len).sum()); + let mut samples = Vec::new(); + for t in &transformed { + push_samples(t, stride, &mut samples); + } + if samples.is_empty() { + return JointNoise { model: NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }, ymax: [0.0; 3], tolerance: 1.0 }; + } + noise_from_samples(samples) +} + +/// Distance between the noise samples of a `len`-pixel plane (CPU and GPU take the same pixels). +pub fn noise_sample_stride(len: usize) -> usize { + len.div_ceil(crate::local::NRC_SAMPLES).max(1) | 1 +} + +/// One noise sample: the mean brightness of its neighbourhoods and the squared high-pass residual of +/// Y, R−Y, B−Y at spacings 1, 2 and 4. +pub type NoiseSample = (f32, [[f32; 3]; 3]); + +/// The fitted noise model from the samples, in pixel order (see `noise_model`). +pub fn noise_from_samples(samples: Vec) -> JointNoise { + // Moving a slider re-renders the same image: the last fit is reused for identical samples (64-bit + // hash of their bits and count; the samples alone determine the fit). + static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut hash = 0xcbf2_9ce4_8422_2325u64 ^ samples.len() as u64; + for s in &samples { + for v in std::iter::once(s.0).chain(s.1.iter().flatten().copied()) { + hash = (hash ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3).rotate_left(5); + } + } + if let Some((h, noise)) = *LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + && h == hash + { + return noise; + } + let noise = fit_noise(samples); + *LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((hash, noise)); + noise +} + +fn fit_noise(samples: Vec) -> JointNoise { + // brightness order, ties in pixel order (as a stable sort): sort compact keys (the bits `total_cmp` + // compares by, then the index), then gather + let mut keys: Vec<(i32, u32)> = samples + .iter() + .enumerate() + .map(|(k, s)| { + let bits = s.0.to_bits() as i32; + (bits ^ (((bits >> 31) as u32) >> 1) as i32, k as u32) + }) + .collect(); + keys.sort_unstable(); + let samples: Vec = keys.iter().filter_map(|&(_, k)| samples.get(k as usize).copied()).collect(); + const BANDS: usize = 16; + let per = samples.len().div_ceil(BANDS).max(32); + let mut pts: [Vec<(f64, f64, f64)>; 3] = std::array::from_fn(|_| Vec::new()); + let mut r: Vec = Vec::with_capacity(per); + for band in samples.chunks(per).filter(|b| b.len() >= 32) { + let y = band.iter().map(|p| p.0 as f64).sum::() / band.len() as f64; + for (i, pts) in pts.iter_mut().enumerate() { + let mut variance = 1e-14f64; + for scale in 0..3 { + r.clear(); + r.extend(band.iter().map(|p| p.1[scale][i])); + let middle = r.len() / 2; + let (_, median, _) = r.select_nth_unstable_by(middle, f32::total_cmp); + // Each kernel has norm squared 1.25. Larger spacings recover noise + // hidden by the positive spatial correlations of demosaiced RGB. + variance = variance.max(*median as f64 / (0.454_936_4 * 1.25)); + } + pts.push((y, variance, band.len() as f64)); + } + } + let mut model = NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }; + let mut ymax = [0.0; 3]; + for (i, pts) in pts.iter().enumerate() { + if pts.is_empty() { + continue; + } + let (a, b, top) = robust_line(pts); + ymax[i] = top; + model.alpha[i] = a as f32; + model.beta[i] = (b as f32).max(1e-14); + } + JointNoise { model, ymax, tolerance: 1.0 } +} + +/// The noise line `v = a·y + b` through the bands `(y, variance, weight)` and the brightest band it +/// rests on. Seeded from the darker half, then all bands with a bounded influence for unexpectedly +/// high residuals (foliage etc.); refit rather than clamp the intercept. +pub(crate) fn robust_line(pts: &[(f64, f64, f64)]) -> (f64, f64, f32) { + let (mut a, mut b) = fit_nonneg_line(&pts[..pts.len().div_ceil(2)]); + let mut ymax = 0.0; + for _ in 0..4 { + // A band's weight fades to 0 between 4 and 5 times the fitted noise instead of dropping at + // 4: a band at the bound must not flip in or out with the last bits of the samples (the + // GPU's differ from the CPU's there), which moved the fit by a few percent. + let weighted: Vec<_> = pts + .iter() + .filter_map(|&(y, v, w)| { + let excess = v / (a * y + b).max(1e-14); + let fade = (5.0 - excess).clamp(0.0, 1.0); + (fade > 0.0).then_some((y, v, w * (2.0 / excess.max(2.0)).powi(4) * fade)) + }) + .collect(); + if !weighted.is_empty() { + (a, b) = fit_nonneg_line(&weighted); + ymax = weighted.iter().map(|p| p.0 as f32).fold(0.0, f32::max); + } + } + (a, b, ymax) +} + +/// Squared distance beyond the expected noise in a difference of two guide samples. A small +/// relative luminance allowance lets a smooth surface exchange colour without crossing a +/// significant luminance or isoluminant colour boundary. The guide is fixed across all scales. +/// (The filter runs `distance_run`, the same operations over planes; this per-pair form is its test reference.) +#[cfg(test)] +fn distance(a: [f32; 3], b: [f32; 3], noise: &JointNoise) -> f32 { + let y = 0.5 * (a[0] + b[0]); + let allowance = (0.025 * y.max(0.0)).powi(2); + let terms: [f32; 3] = std::array::from_fn(|i| { + let v = noise.var(i, y); + let excess = ((a[i] - b[i]).powi(2) - v).max(0.0); + // The 3x3 pilot blur reduces uncorrelated noise to 1/9. Keep a conservative + // allowance for correlations left by demosaicing and grid resampling. + // (A difference within the noise adds exactly 0: no division needed.) + if excess == 0.0 { 0.0 } else { excess / (3.0 * noise.tolerance * v + allowance) } + }); + terms.into_iter().sum::() +} + +/// The guide as three planes (Y, R−Y, B−Y): `distance_run` over them vectorises. +struct Planes { + c: [Vec; 3], + w: usize, +} + +impl Planes { + /// `len` pixels of row `y` from column `from`. + fn run(&self, y: usize, from: usize, len: usize) -> Option<[&[f32]; 3]> { + let start = y.checked_mul(self.w)?.checked_add(from)?; + let end = start.checked_add(len)?; + let [a, b, c] = &self.c; + Some([a.get(start..end)?, b.get(start..end)?, c.get(start..end)?]) + } +} + +/// `distance` of each pair of guide pixels `(a[k], b[k])` into `out[k]`, the same operations in the same +/// order (bit for bit), without branches so the compiler can work on several pixels at once. +fn distance_run(a: [&[f32]; 3], b: [&[f32]; 3], noise: &JointNoise, out: &mut [f32]) { + let ([ay, au, av], [by, bu, bv]) = (a, b); + let (alpha, beta, ymax, tolerance) = (noise.model.alpha, noise.model.beta, noise.ymax, noise.tolerance); + for ((((((o, &ay), &au), &av), &by), &bu), &bv) in out.iter_mut().zip(ay).zip(au).zip(av).zip(by).zip(bu).zip(bv) { + let y = 0.5 * (ay + by); + let allowance = (0.025 * y.max(0.0)).powi(2); + // `JointNoise::var`; an excess of 0 divides to exactly 0, as the branch in `distance` gives + let term = |i: usize, d: f32| { + let v = (alpha[i] * y.min(ymax[i]).max(0.0) + beta[i]).max(1e-14); + let excess = (d.powi(2) - v).max(0.0); + excess / (3.0 * tolerance * v + allowance) + }; + *o = term(0, ay - by) + term(1, au - bu) + term(2, av - bv); + } +} + +/// The exchange weight `exp(−max(distance, path))`; exactly 1 when both are 0 (no `exp` needed). +#[inline] +fn weight(distance: f32, path: f32) -> f32 { + let m = distance.max(path); + if m == 0.0 { 1.0 } else { (-m).exp() } +} + +/// `weight(distance, path)` with the path given as exp(−path): min(exp(−distance), that), and no `exp` +/// for a distance of 0. +#[inline] +fn path_weight(distance: f32, path: f32) -> f32 { + if distance == 0.0 { path } else { (-distance).exp().min(path) } +} + +/// Denoise the pilot along a clearly smoother axis at strong edges. An isotropic blur +/// dilutes a two-pixel isoluminant line before the edge decision even sees it. Weak or +/// ambiguous structure uses the isotropic pilot, so noise alone does not protect itself. +/// Written straight into planes (see `Planes`), one row at a time without branches per pixel. +fn pilot(original: &Rgb32f, noise: &JointNoise) -> Planes { + let blurred = gaussian(original, 0.8); + let (w, h) = (original.width, original.height); + let mut planes = Planes { c: std::array::from_fn(|_| vec![0.0; original.len()]), w }; + let [py, pu, pv] = &mut planes.c; + let process_row = |out: &mut Vec<[f32; 3]>, y: usize, ry: &mut [f32], ru: &mut [f32], rv: &mut [f32]| { + let Some(blur) = blurred.data.get(y * w..(y + 1) * w) else { return }; + out.clear(); + out.extend_from_slice(blur); + if y > 0 + && y + 1 < h + && let (Some(up), Some(mid), Some(down)) = + (original.data.get((y - 1) * w..y * w), original.data.get(y * w..(y + 1) * w), original.data.get((y + 1) * w..(y + 2) * w)) + { + // columns 1 .. w − 1: the pixel, its left/right (axis 0) and upper/lower (axis 1) neighbours + for (((o, win), &u), &d) in out.iter_mut().skip(1).zip(mid.windows(3)).zip(up.iter().skip(1)).zip(down.iter().skip(1)) { + let &[l, p, r] = win else { continue }; + let var: [f32; 3] = std::array::from_fn(|i| 9.0 * noise.var(i, p[0])); + let axis = |a: [f32; 3], b: [f32; 3]| { + let m: [f32; 3] = std::array::from_fn(|i| (a[i] + p[i] + b[i]) / 3.0); + let t = |i: usize| ((a[i] - m[i]).powi(2) + (p[i] - m[i]).powi(2) + (b[i] - m[i]).powi(2)) / var[i]; + (m, t(0) + t(1) + t(2)) + }; + let (mh, vh) = axis(l, r); + let (mv, vvar) = axis(u, d); + *o = pilot_pick(*o, mh, vh, mv, vvar); + } + } + for (((c, y), u), v) in out.iter().zip(ry.iter_mut()).zip(ru.iter_mut()).zip(rv.iter_mut()) { + (*y, *u, *v) = (c[0], c[1], c[2]); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + py.par_chunks_mut(w.max(1)) + .zip(pu.par_chunks_mut(w.max(1))) + .zip(pv.par_chunks_mut(w.max(1))) + .enumerate() + .for_each_init(Vec::new, |out, (y, ((ry, ru), rv))| process_row(out, y, ry, ru, rv)); + } + #[cfg(target_arch = "wasm32")] + { + let mut out = Vec::new(); + for (y, ((ry, ru), rv)) in py.chunks_mut(w.max(1)).zip(pu.chunks_mut(w.max(1))).zip(pv.chunks_mut(w.max(1))).enumerate() { + process_row(&mut out, y, ry, ru, rv); + } + } + planes +} + +/// The pilot at one pixel from its isotropic blur `o`, the horizontal mean `mh` and noise-normalised +/// variance `vh`, and the vertical ones `mv`, `vvar`: the mean along the clearly smoother axis where +/// the other is more than 4 times as rough (and above 4), the blur where neither is. The choice fades +/// in between 0.8 and 1.25 times that bound instead of switching at it, so a pixel near the bound +/// takes nearly the same pilot when the noise model moves by a hair. +pub(crate) fn pilot_pick(o: [f32; 3], mh: [f32; 3], vh: f32, mv: [f32; 3], vvar: f32) -> [f32; 3] { + let sv = smoothstep(0.8, 1.25, vh / 4.0f32.max(4.0 * vvar)); + let sh = smoothstep(0.8, 1.25, vvar / 4.0f32.max(4.0 * vh)); + if sv >= 1.0 { + mv + } else if sh >= 1.0 { + mh + } else { + std::array::from_fn(|i| o[i] + (mv[i] - o[i]) * sv + (mh[i] - o[i]) * sh) + } +} + +/// The two chroma components `R − Y`, `B − Y`, or a pair of per-axis values (horizontal, vertical). +type Pair = [f32; 2]; +type PairImage = crate::raster::Image; + +fn rgb2(y: f32, uv: Pair) -> [f32; 3] { + let r = y + uv[0]; + let b = y + uv[1]; + [r, (y - 0.2627 * r - 0.0593 * b) / 0.6780, b] +} + +/// One conservative horizontal/vertical diffusion step. Pair weights are symmetric; the +/// guide is never replaced by the filtered result. Long taps also account for the intervening +/// guide edges, so a wide pass cannot jump over a thin differently coloured object. +/// +/// Per pixel: `out = p`, then the lower neighbour's exchange, then the upper one's, in that order +/// (the order the result depends on, bit for bit). +fn diffuse(src: &PairImage, dst: &mut PairImage, links: &PairImage, delta: usize, vertical: bool, rate: f32) { + if vertical { diffuse_v(src, dst, links, delta, rate) } else { diffuse_h(src, dst, links, delta, rate) } +} + +#[inline(always)] +fn exchange(out: &mut Pair, p: Pair, q: Pair, weight: f32) { + out[0] += weight * (q[0] - p[0]); + out[1] += weight * (q[1] - p[1]); +} + +fn diffuse_h(src: &PairImage, dst: &mut PairImage, links: &PairImage, delta: usize, rate: f32) { + let w = src.width; + for_rows(&mut dst.data, w, |y, out| { + let (Some(s), Some(l)) = (src.data.get(y * w..(y + 1) * w), links.data.get(y * w..(y + 1) * w)) else { return }; + for (x, o) in out.iter_mut().enumerate() { + let p = s[x]; + *o = p; + if x >= delta { + exchange(o, p, s[x - delta], rate * l[x - delta][0]); + } + if x + delta < w { + exchange(o, p, s[x + delta], rate * l[x][0]); + } + } + }); +} + +fn diffuse_v(src: &PairImage, dst: &mut PairImage, links: &PairImage, delta: usize, rate: f32) { + let (w, h) = (src.width, src.height); + for_rows(&mut dst.data, w, |y, out| { + let Some(s) = src.data.get(y * w..(y + 1) * w) else { return }; + out.copy_from_slice(s); + if y >= delta + && let (Some(up), Some(lu)) = (src.data.get((y - delta) * w..(y - delta + 1) * w), links.data.get((y - delta) * w..(y - delta + 1) * w)) + { + for (((o, &p), &q), lk) in out.iter_mut().zip(s).zip(up).zip(lu) { + exchange(o, p, q, rate * lk[1]); + } + } + if y + delta < h + && let (Some(down), Some(ld)) = (src.data.get((y + delta) * w..(y + delta + 1) * w), links.data.get(y * w..(y + 1) * w)) + { + for (((o, &p), &q), lk) in out.iter_mut().zip(s).zip(down).zip(ld) { + exchange(o, p, q, rate * lk[1]); + } + } + }); +} + +/// The diffusion scales for a final spatial `sigma` (in grid pixels) on a `w × h` grid: each step's +/// neighbour distance and rate, in order. CPU and GPU run exactly these. +pub fn scale_plan(sigma: f32, w: usize, h: usize) -> Vec<(usize, f32)> { + let mut plan = Vec::new(); + let mut remaining = sigma * sigma; + let mut delta = 1usize; + while remaining > 0.01 && delta <= w.max(h) { + let rate = (remaining / (4.0 * (delta as f32).powi(2))).min(0.25); + plan.push((delta, rate)); + remaining -= 4.0 * rate * (delta as f32).powi(2); + delta = delta.saturating_mul(2); + } + plan +} + +/// Share of the filtered colour at Color `amount` (0..=1): a ramp up to the default 25. +pub fn strength(amount: f32) -> f32 { + (4.0 * amount).clamp(0.0, 1.0) +} + +/// Edge tolerance at Color Detail `detail` (0..=1). +pub fn tolerance(detail: f32) -> f32 { + (1.5 - detail).clamp(0.5, 1.5) +} + +/// The speck brake at Color `amount` (0..=1): the chroma excess (in noise variances of the two chroma +/// components together) from which a pixel starts to count as a colour speck (fully at twice that), and +/// the largest share of its colour that is replaced. Weak at the default 25 (only extreme specks, at most +/// half), stronger up to 100. Below 25 the final blend (`strength`) fades it out with the rest. +pub fn speck_brake(amount: f32) -> SpeckBrake { + let t = ((amount - 0.25) / 0.75).clamp(0.0, 1.0); + SpeckBrake { threshold: 64.0 - 39.0 * t, share: 0.5 + 0.5 * t } +} + +/// See [`speck_brake`]; `share` 0 turns the brake off. +#[derive(Clone, Copy, Debug)] +pub struct SpeckBrake { + pub threshold: f32, + pub share: f32, +} + +impl SpeckBrake { + pub const OFF: SpeckBrake = SpeckBrake { threshold: f32::INFINITY, share: 0.0 }; +} + +/// The median (mean of the middle two) of 8 values, by an optimal 19-comparator sorting network +/// (the GPU kernel uses the same one). +fn median8(v: [f32; 8]) -> f32 { + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = v; + let cmp = |x: &mut f32, y: &mut f32| { + let (lo, hi) = (x.min(*y), x.max(*y)); + (*x, *y) = (lo, hi); + }; + cmp(&mut a, &mut c); + cmp(&mut b, &mut d); + cmp(&mut e, &mut g); + cmp(&mut f, &mut h); + cmp(&mut a, &mut e); + cmp(&mut b, &mut f); + cmp(&mut c, &mut g); + cmp(&mut d, &mut h); + cmp(&mut a, &mut b); + cmp(&mut c, &mut d); + cmp(&mut e, &mut f); + cmp(&mut g, &mut h); + cmp(&mut c, &mut e); + cmp(&mut d, &mut f); + cmp(&mut b, &mut e); + cmp(&mut d, &mut g); + cmp(&mut b, &mut c); + cmp(&mut d, &mut e); + cmp(&mut f, &mut g); + let _ = (a, b, c, f, g, h); + 0.5 * (d + e) +} + +fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// How much of a pixel's chroma the speck brake replaces by the median of the ring around it, and that +/// median (Y, R−Y, B−Y), from the pixel `p`, the ring `ring` and the rest of the 5 × 5 border `rest`. A +/// speck stands out in colour far beyond the noise, but not in luminance (a star, a lit point or any real +/// small detail almost always has a luminance step), and it is compact: the colour shift does not reach +/// the border (a line or an edge carries it on). Demosaicing spreads high-ISO specks over 2 × 2 to +/// 3 × 3 pixels, which all lie inside. The noise is taken at the ring's mean luminance (a median of it +/// is only needed for the few pixels past the threshold). +fn speck_share(p: [f32; 3], ring: &[[f32; 3]; 8], rest: impl Iterator, noise: &JointNoise, brake: SpeckBrake) -> (f32, [f32; 3]) { + let y = ring.iter().map(|q| q[0]).sum::() / 8.0; + let (vu, vv) = (noise.var(1, y), noise.var(2, y)); + // The medians lie between the ring's least and largest value, so the farther of the two bounds the + // excess from above (rounding keeps that order): most pixels are decided without the medians. + let reach = |c: usize| { + let (lo, hi) = ring.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), q| (lo.min(q[c]), hi.max(q[c]))); + (p[c] - lo).abs().max((p[c] - hi).abs()) + }; + let (bu, bv) = (reach(1), reach(2)); + if bu * bu / vu + bv * bv / vv <= brake.threshold { + return (0.0, [0.0; 3]); + } + let m = [0.0, median8(ring.map(|q| q[1])), median8(ring.map(|q| q[2]))]; + let (du, dv) = (p[1] - m[1], p[2] - m[2]); + let excess = du * du / vu + dv * dv / vv; + if excess <= brake.threshold { + return (0.0, m); + } + let m = [median8(ring.map(|q| q[0])), m[1], m[2]]; + // luminance: full brake up to half the chroma excess, none from 1.5 times it + let dy = p[0] - m[0]; + let luminance = dy * dy / noise.var(0, y); + let alone = ((1.5 * excess - luminance) / excess).clamp(0.0, 1.0); + if alone <= 0.0 { + return (0.0, m); + } + // compactness: the second largest share of the pixel's colour shift that a border pixel also has (a + // line or an edge through the pixel crosses the border at least twice; one noisy border pixel that + // happens to lean the same way does not protect a speck) + let (_, second) = ring + .iter() + .copied() + .chain(rest) + .map(|q| ((q[1] - m[1]) * du / vu + (q[2] - m[2]) * dv / vv) / excess) + .fold((0.0f32, 0.0f32), |(a, b), s| if s > a { (s, a) } else { (a, b.max(s)) }); + let compact = ((0.8 - second) / 0.3).clamp(0.0, 1.0); + (brake.share * smoothstep(brake.threshold, 2.0 * brake.threshold, excess) * alone * compact, m) +} + +/// Replace the chroma of compact colour specks by that of their surroundings (see `speck_share`), in the +/// transformed image (Y, R−Y, B−Y); luminance is never touched. Runs before the guide is built, so a speck +/// is neither kept by the edge-aware weights nor spread by them. +fn despeck(img: &mut Rgb32f, noise: &JointNoise, brake: SpeckBrake) { + if brake.share <= 0.0 || img.width < 5 || img.height < 5 { + return; + } + let (w, h) = (img.width, img.height); + let source = &*img; + let process_row = |y: usize| { + let mut changed = Vec::new(); + let rows: [Option<&[[f32; 3]]>; 5] = std::array::from_fn(|k| source.data.get((y + k - 2) * w..(y + k - 1) * w)); + let [Some(r0), Some(r1), Some(r2), Some(r3), Some(r4)] = rows else { return changed }; + for (x, ((((w0, w1), w2), w3), w4)) in r0.windows(5).zip(r1.windows(5)).zip(r2.windows(5)).zip(r3.windows(5)).zip(r4.windows(5)).enumerate() { + let (&[a0, a1, a2, a3, a4], &[b0, _, _, _, b4], &[c0, _, p, _, c4], &[d0, _, _, _, d4], &[e0, e1, e2, e3, e4]) = (w0, w1, w2, w3, w4) + else { + continue; + }; + // the ring: corners and edge centres of the 5 × 5 square, far enough that a speck spread over + // its direct neighbours by demosaicing does not reach them; the rest of the border: with the + // ring, every thin line or edge through the pixel crosses at least one of the 16 at any angle + let ring = [a0, a2, a4, c0, c4, e0, e2, e4]; + let rest = [a1, a3, b0, b4, d0, d4, e1, e3]; + let (k, m) = speck_share(p, &ring, rest.into_iter(), noise, brake); + if k > 0.0 { + changed.push((y * w + x + 2, [p[1] + k * (m[1] - p[1]), p[2] + k * (m[2] - p[2])])); + } + } + changed + }; + #[cfg(not(target_arch = "wasm32"))] + let changes: Vec> = { + use rayon::prelude::*; + (2..h - 2).into_par_iter().map(process_row).collect() + }; + #[cfg(target_arch = "wasm32")] + let changes: Vec> = (2..h - 2).map(process_row).collect(); + for (index, uv) in changes.into_iter().flatten() { + if let Some(o) = img.data.get_mut(index) { + (o[1], o[2]) = (uv[0], uv[1]); + } + } +} + +/// `noise`: the frame's noise model (see [`noise_of_tiles`]); `None` measures it on `img`. +pub(crate) fn denoise(img: &mut Rgb32f, params: &NrcParams, detail: f32, amount: f32, noise: Option<&JointNoise>) { + // Continuous ramp from zero; from the ordinary default Color=25 onward the spatial + // scale controls the extra smoothing. Noise calibration and edge decisions stay fixed. + denoise_with(img, params, 1, detail, strength(amount), speck_brake(amount), noise); +} + +#[cfg(test)] +fn denoise_grid(img: &mut Rgb32f, params: &NrcParams, step: usize, detail: f32, strength: f32, brake: SpeckBrake) { + denoise_with(img, params, step, detail, strength, brake, None); +} + +fn denoise_with(img: &mut Rgb32f, params: &NrcParams, step: usize, detail: f32, strength: f32, brake: SpeckBrake, noise: Option<&JointNoise>) { + if img.is_empty() || strength <= 0.0 { + return; + } + // A maximum 2x grid keeps colour boundaries visible even at high strength. The old grid + // grew to 16x with the radius, making the colour loss inseparable from slider strength. + let step = if img.width.is_multiple_of(step) && img.height.is_multiple_of(step) { step } else { 1 }; + let (w, h) = (img.width.div_ceil(step), img.height.div_ceil(step)); + // Transform before resampling; negative linear differences are valid throughout. + let mut original = Rgb32f::new(w, h); + if step == 1 { + // the generic loop below with one sample per pixel, same operations (0 + c, / 1) + for_rows(&mut original.data, w, |y, row| { + for (x, p) in row.iter_mut().enumerate() { + if let Some(&c) = img.data.get(y * w + x) { + let c = yuv(c); + *p = c.map(|v| (0.0f32 + v) / 1.0f32); + } + } + }); + } else { + for_rows(&mut original.data, w, |y, row| { + for (x, p) in row.iter_mut().enumerate() { + let mut count = 0.0f32; + for sy in y * step..((y + 1) * step).min(img.height) { + for sx in x * step..((x + 1) * step).min(img.width) { + if let Some(&c) = img.data.get(sy * img.width + sx) { + let c = yuv(c); + *p = std::array::from_fn(|i| p[i] + c[i]); + count += 1.0; + } + } + } + *p = p.map(|v| v / count.max(1.0)); + } + }); + } + let mut noise = match noise { + Some(n) => *n, + None => noise_model(&original), + }; + noise.tolerance = tolerance(detail); + despeck(&mut original, &noise, brake); + let planes = pilot(&original, &noise); + // Working buffers carry the two chroma components only (Y is restored from the image at the end). + let mut filtered: PairImage = original.map(|p| [p[1], p[2]]); + // the full-resolution reconstruction reads Y from `img`: the transformed copy is no longer needed + let original = (step != 1).then_some(original); + let mut scratch = PairImage::new(w, h); + let mut paths = PairImage::new(w, h); + let mut links = PairImage::new(w, h); + // Direct neighbours: the path over one step is the pair's own distance, and its weight is exp(−distance). + // `paths` holds exp(−path), the largest distance along a path, exponentiated: exp(−max(a, b)) is + // min(exp(−a), exp(−b)) bit for bit (exp is monotonic), so longer paths take minima and a weight with + // a new distance of 0 needs no `exp`; a path of 0 (no pair, at the border) is 1. + // the distances of row `y` to the pixels `offset` to the right and `offset` rows down + let row_distances = |y: usize, offset: usize, dh: &mut Vec, dv: &mut Vec| { + let n = w.saturating_sub(offset); + dh.resize(w, 0.0); + dv.resize(w, 0.0); + if let (Some(a), Some(b), Some(out)) = (planes.run(y, 0, n), planes.run(y, offset, n), dh.get_mut(..n)) { + distance_run(a, b, &noise, out); + } + if y + offset < h + && let (Some(a), Some(b)) = (planes.run(y, 0, w), planes.run(y + offset, 0, w)) + { + distance_run(a, b, &noise, dv); + } + }; + let init_row = |(dh, dv): &mut (Vec, Vec), y: usize, prow: &mut [[f32; 2]], lrow: &mut [[f32; 2]]| { + row_distances(y, 1, dh, dv); + for (x, (((out, link), &d0), &d1)) in prow.iter_mut().zip(lrow.iter_mut()).zip(dh.iter()).zip(dv.iter()).enumerate() { + *link = [0.0; 2]; + *out = [1.0; 2]; + if x + 1 < w { + link[0] = weight(d0, d0); + out[0] = link[0]; + } + if y + 1 < h { + link[1] = weight(d1, d1); + out[1] = link[1]; + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + paths + .data + .par_chunks_mut(w) + .zip(links.data.par_chunks_mut(w)) + .enumerate() + .for_each_init(|| (Vec::new(), Vec::new()), |bufs, (y, (prow, lrow))| init_row(bufs, y, prow, lrow)); + } + #[cfg(target_arch = "wasm32")] + { + let mut bufs = (Vec::new(), Vec::new()); + for (y, (prow, lrow)) in paths.data.chunks_mut(w).zip(links.data.chunks_mut(w)).enumerate() { + init_row(&mut bufs, y, prow, lrow); + } + } + // Scale is independent of the edge decision. K has no role in deciding whether a leaf + // is noise. Two dyadic sweeps provide broad smoothing with a fixed number of scales. + let sigma = params.passes.last().map_or(0.0, |p| p.sigma / step as f32); + let plan = scale_plan(sigma, w, h); + for (k, &(delta, rate)) in plan.iter().enumerate() { + for _ in 0..2 { + diffuse(&filtered, &mut scratch, &links, delta, false, rate); + std::mem::swap(&mut filtered, &mut scratch); + diffuse(&filtered, &mut scratch, &links, delta, true, rate); + std::mem::swap(&mut filtered, &mut scratch); + } + let Some(&(next, _)) = plan.get(k + 1) else { break }; + // In one pass: paths of length 2·delta (from the two adjacent delta-length paths, read from + // `paths`, written to `scratch`) and the next scale's pair weights from them. + let old = &paths; + let step_row = |(dh, dv): &mut (Vec, Vec), y: usize, prow: &mut [[f32; 2]], lrow: &mut [[f32; 2]]| { + row_distances(y, next, dh, dv); + let (Some(here), below) = (old.data.get(y * w..(y + 1) * w), old.data.get((y + delta) * w..(y + delta + 1) * w)) else { return }; + for (x, (((out, link), &d0), &d1)) in prow.iter_mut().zip(lrow.iter_mut()).zip(dh.iter()).zip(dv.iter()).enumerate() { + let Some(&p) = here.get(x) else { continue }; + *out = p; + if x + delta < w + && let Some(q) = here.get(x + delta) + { + out[0] = out[0].min(q[0]); + } + if y + delta < h + && let Some(q) = below.and_then(|b| b.get(x)) + { + out[1] = out[1].min(q[1]); + } + *link = [0.0; 2]; + if x + next < w { + link[0] = path_weight(d0, out[0]); + } + if y + next < h { + link[1] = path_weight(d1, out[1]); + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + scratch + .data + .par_chunks_mut(w) + .zip(links.data.par_chunks_mut(w)) + .enumerate() + .for_each_init(|| (Vec::new(), Vec::new()), |bufs, (y, (prow, lrow))| step_row(bufs, y, prow, lrow)); + } + #[cfg(target_arch = "wasm32")] + { + let mut bufs = (Vec::new(), Vec::new()); + for (y, (prow, lrow)) in scratch.data.chunks_mut(w).zip(links.data.chunks_mut(w)).enumerate() { + step_row(&mut bufs, y, prow, lrow); + } + } + std::mem::swap(&mut paths, &mut scratch); + } + drop(scratch); + drop(paths); + drop(links); + match &original { + None => { + let fw = img.width; + for_rows(&mut img.data, fw, |y, row| { + for (x, p) in row.iter_mut().enumerate() { + let Some(&q) = filtered.data.get(y * w + x) else { continue }; + let result = rgb2(luminance_2020(*p), q); + *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); + } + }); + } + Some(original) => { + // Reconstruct only rows. Keep the fine residual with a shared, noise-subtracted + // Wiener share; a flat noisy patch receives no automatic protection from noisy Y. + let mean = gaussian(original, 1.0); + let corr = gaussian(&original.map(|p| p.map(|v| v * v)), 1.0); + let share = corr.zip_map(&mean, |c, m| { + let snr = (1..3).map(|i| ((c[i] - m[i] * m[i]).max(0.0) / noise.var(i, m[0]) - 1.0).max(0.0)).sum::() * 0.5; + [snr / (snr + 8.0); 3] + }); + let share = gaussian(&share, 0.8); + // Resize one output row at a time using the raster resampler's exact pixel centres. + use crate::raster::resample::weights; + let ux = weights(w, img.width, Filter::Bilinear); + let uy = weights(h, img.height, Filter::Bilinear); + let ow = img.width; + for_rows(&mut img.data, ow, |y, row| { + let Some((y0, wy)) = uy.get(y) else { return }; + for (x, p) in row.iter_mut().enumerate() { + let Some((x0, wx)) = ux.get(x) else { continue }; + let (mut f, mut o, mut a) = ([0.0; 2], [0.0; 3], 0.0); + for (j, &dy) in wy.iter().enumerate() { + for (i, &dx) in wx.iter().enumerate() { + let index = (y0 + j) * w + x0 + i; + if let (Some(q), Some(r), Some(s)) = (filtered.data.get(index), original.data.get(index), share.data.get(index)) { + let weight = dx * dy; + f = std::array::from_fn(|c| f[c] + weight * q[c]); + o = std::array::from_fn(|c| o[c] + weight * r[c]); + a += weight * s[0]; + } + } + } + let c = yuv(*p); + let q = [f[0] + a * (c[1] - o[1]), f[1] + a * (c[2] - o[2])]; + let result = rgb2(c[0], q); + *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); + } + }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::local::NrcPass; + + fn params(step: usize) -> NrcParams { + NrcParams { off: 0.003, passes: vec![NrcPass { sigma: 4.0, step, k: 64.0, pct: 0.2 }, NrcPass { sigma: 12.0, step, k: 64.0, pct: 0.2 }] } + } + + fn noisy(clean: &Rgb32f, seed: u64, sigma: f32) -> Rgb32f { + let mut result = clean.clone(); + let mut seed = seed; + for p in &mut result.data { + for v in p { + let mut n = 0.0; + for _ in 0..4 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + n += (seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5; + } + *v += sigma * 1.732 * n; + } + } + result + } + + /// The optimised filter reproduces the reference implementation (8b89526d) bit for bit: same scales, + /// weights, paths and reconstruction, only fewer passes and smaller buffers. + #[test] + fn joint_matches_the_reference_bit_for_bit() { + let mut scene = Rgb32f::new(97, 83); + for (i, p) in scene.data.iter_mut().enumerate() { + let (x, y) = (i % 97, i / 97); + // edges, a thin line, a dark patch and a gradient + *p = if x < 30 { + [0.08, 0.016, 0.02] + } else if x < 32 { + [0.01, 0.05, 0.01] + } else if y < 40 { + [0.0015, 0.004, 0.009] + } else { + [0.02 + 0.001 * x as f32, 0.03, 0.01 + 0.0005 * y as f32] + }; + } + for (w, h) in [(97usize, 83usize), (96, 82), (5, 3), (1, 7)] { + let mut clean = Rgb32f::new(w, h); + for y in 0..h { + for x in 0..w { + clean.data[y * w + x] = scene.data[y * 97 + x]; + } + } + for seed in [0x2545_f491_4f6c_dd1d, 0x9e37_79b9_7f4a_7c15] { + let input = noisy(&clean, seed, 0.004); + for step in [1, 2] { + for (detail, strength, sigma) in [(0.5, 1.0, 12.0), (0.25, 0.6, 4.0), (0.9, 1.0, 27.0)] { + let p = NrcParams { off: 0.003, passes: vec![NrcPass { sigma, step, k: 64.0, pct: 0.2 }] }; + let (mut a, mut b) = (input.clone(), input.clone()); + denoise_grid(&mut a, &p, step, detail, strength, SpeckBrake::OFF); + crate::nrc_joint_reference::denoise_grid(&mut b, &p, step, detail, strength); + for (i, (x, y)) in a.data.iter().zip(&b.data).enumerate() { + for c in 0..3 { + assert!( + x[c].to_bits() == y[c].to_bits(), + "{w}x{h} step {step} sigma {sigma}: pixel {i} channel {c}: {} vs {}", + x[c], + y[c] + ); + } + } + } + } + } + } + } + + /// BENCH (ignored, prints): the optimised filter against the reference on the same 24 MP image, + /// interleaved so both see the same machine load. Median of 3 each. + #[test] + #[ignore] + fn bench_joint_against_reference() { + let (w, h) = (6000usize, 4000usize); + let mut clean = Rgb32f::new(w, h); + for (i, p) in clean.data.iter_mut().enumerate() { + let (x, y) = (i % w, i / w); + *p = if (x / 300 + y / 300) % 2 == 0 { [0.03, 0.02, 0.01] } else { [0.004, 0.006, 0.012] }; + } + let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.004); + let p = NrcParams { off: 0.003, passes: vec![NrcPass { sigma: 27.0, step: 1, k: 64.0, pct: 0.2 }] }; + let (mut new, mut old) = (Vec::new(), Vec::new()); + for _ in 0..3 { + let mut a = input.clone(); + let t = std::time::Instant::now(); + denoise_grid(&mut a, &p, 1, 0.5, 1.0, SpeckBrake::OFF); + new.push(t.elapsed().as_secs_f64()); + let mut b = input.clone(); + let t = std::time::Instant::now(); + crate::nrc_joint_reference::denoise_grid(&mut b, &p, 1, 0.5, 1.0); + old.push(t.elapsed().as_secs_f64()); + } + new.sort_by(f64::total_cmp); + old.sort_by(f64::total_cmp); + println!("joint 24 MP: optimised {:.2} s, reference {:.2} s (medians of {new:.2?} / {old:.2?})", new[1], old[1]); + } + + /// BENCH (ignored, prints): fitting the noise model to 130 000 samples (a 33 MP image's), median of 5. + #[test] + #[ignore] + fn bench_noise_fit() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut rnd = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f32 / (1u64 << 53) as f32 + }; + let samples: Vec = (0..130_000) + .map(|_| { + let y = rnd() * 0.3; + (y, std::array::from_fn(|_| std::array::from_fn(|_| (1e-5 + 1e-4 * y) * rnd() * 2.0))) + }) + .collect(); + let mut times: Vec = (0..5) + .map(|_| { + let s = samples.clone(); + let t = std::time::Instant::now(); + let model = fit_noise(s); + assert!(model.model.beta[0] > 0.0); + t.elapsed().as_secs_f64() * 1e3 + }) + .collect(); + times.sort_by(f64::total_cmp); + println!("noise fit, 130 000 samples: {:.1} ms (of {times:.1?})", times[2]); + } + + /// BENCH (ignored, prints): the speck brake alone against the whole joint filter on one 24 MP image, + /// interleaved. Median of 3 each. + #[test] + #[ignore] + fn bench_speck_brake() { + let (w, h) = (6000usize, 4000usize); + let clean = Rgb32f::from_fn(w, h, |x, y| if (x / 300 + y / 300) % 2 == 0 { [0.03, 0.02, 0.01] } else { [0.004, 0.006, 0.012] }); + let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.004); + let p = NrcParams { off: 0.003, passes: vec![NrcPass { sigma: 27.0, step: 1, k: 64.0, pct: 0.2 }] }; + let transformed = input.map(yuv); + let noise = noise_model(&transformed); + let (mut brake, mut joint) = (Vec::new(), Vec::new()); + for _ in 0..3 { + let mut out = transformed.clone(); + let t = std::time::Instant::now(); + despeck(&mut out, &noise, speck_brake(1.0)); + brake.push(t.elapsed().as_secs_f64()); + let mut a = input.clone(); + let t = std::time::Instant::now(); + denoise_grid(&mut a, &p, 1, 0.5, 1.0, SpeckBrake::OFF); + joint.push(t.elapsed().as_secs_f64()); + } + brake.sort_by(f64::total_cmp); + joint.sort_by(f64::total_cmp); + println!("24 MP: speck brake {:.3} s, joint without it {:.2} s (medians of {brake:.3?} / {joint:.2?})", brake[1], joint[1]); + } + + #[test] + fn joint_keeps_negative_means_luminance_and_reduces_chroma_noise() { + for (w, h) in [(128, 96), (127, 95), (1, 19), (19, 1)] { + let clean = Rgb32f::filled(w, h, [0.006, 0.004, 0.0008]); + for seed in [0x2545_f491_4f6c_dd1d, 0x1234_5678_9abc_def1] { + let input = noisy(&clean, seed, 0.003); + for step in [1, 2] { + let mut output = input.clone(); + denoise_grid(&mut output, ¶ms(step), step, 0.5, 1.0, speck_brake(1.0)); + assert!(output.data.iter().flatten().all(|v| v.is_finite())); + for (a, b) in input.data.iter().zip(&output.data) { + assert!((luminance_2020(*a) - luminance_2020(*b)).abs() < 1e-7); + } + // Thin inputs cannot support a spatial noise estimate; finite/luminance + // checks above still apply, but their sample mean is too noisy for this bound. + if w < 3 || h < 3 { + continue; + } + for c in 0..3 { + let difference = input.data.iter().zip(&output.data).map(|(a, b)| (b[c] - a[c]) as f64).sum::() / input.len() as f64; + assert!(difference.abs() < 2e-6, "step {step}, {w}x{h}, mean error {difference}"); + } + let energy = |im: &Rgb32f| { + im.data + .iter() + .map(|&p| { + let p = yuv(p); + let c = yuv(clean.data[0]); + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2) + }) + .sum::() + / im.len() as f32 + }; + assert!(energy(&output) < 0.08 * energy(&input)); + assert!(output.data.iter().any(|p| p.iter().any(|&v| v < 0.0)), "negative values were clipped"); + } + } + } + } + + #[test] + fn joint_protects_leaf_and_isoluminant_edges_without_chroma_halos() { + let leaf = [0.02, 0.12, 0.01]; + let black = [0.0005; 3]; + let red = [0.08, 0.0155, 0.02]; + let mut green = [0.012, 0.04, 0.015]; + let gain = luminance_2020(red) / luminance_2020(green); + green = green.map(|v| v * gain); + for (left, right) in [(leaf, black), (red, green)] { + let clean = Rgb32f::from_fn(192, 128, |x, _| if x < 96 { left } else { right }); + for seed in [0x2545_f491_4f6c_dd1d, 0x1234_5678_9abc_def1] { + let input = noisy(&clean, seed, 0.003); + for step in [1, 2] { + let mut output = input.clone(); + denoise_grid(&mut output, ¶ms(step), step, 0.5, 1.0, speck_brake(1.0)); + let step_uv = [yuv(left)[1] - yuv(right)[1], yuv(left)[2] - yuv(right)[2]]; + let length = step_uv.iter().map(|v| v * v).sum::().sqrt(); + for x in [92, 93, 98, 99] { + let mut mean = [0.0; 3]; + for y in 16..112 { + let p = yuv(output.get(x, y)); + mean = std::array::from_fn(|i| mean[i] + p[i] / 96.0); + } + let expected = yuv(if x < 96 { left } else { right }); + let error = ((mean[1] - expected[1]).powi(2) + (mean[2] - expected[2]).powi(2)).sqrt() / length; + assert!(error < 0.08, "step {step}, x {x}, colour error {}%", 100.0 * error); + } + } + } + } + } + + #[test] + fn joint_noise_fit_does_not_treat_bright_texture_as_shot_noise() { + let clean = Rgb32f::from_fn(256, 192, |x, y| { + let l = if x < 192 { 0.003 + x as f32 * 0.00002 } else { 0.15 + if (x + y) % 2 == 0 { 0.08 } else { -0.08 } }; + [l; 3] + }); + let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.002).map(yuv); + let model = noise_model(&input); + for i in 0..3 { + assert!(model.var(i, 0.15) < 5.0 * model.var(i, 0.005), "texture dominated noise fit: {model:?}"); + } + } + + #[test] + fn joint_keeps_a_two_pixel_isoluminant_line() { + let grey = [0.03; 3]; + let mut red = [0.08, 0.0155, 0.02]; + let gain = luminance_2020(grey) / luminance_2020(red); + red = red.map(|v| v * gain); + let clean = Rgb32f::from_fn(192, 128, |x, _| if (94..96).contains(&x) { red } else { grey }); + let mut output = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.006); + denoise_grid(&mut output, ¶ms(1), 1, 0.5, 1.0, speck_brake(1.0)); + let reference = yuv(red); + let mut mean = [0.0; 3]; + for y in 16..112 { + for x in 94..96 { + let p = yuv(output.get(x, y)); + mean = std::array::from_fn(|i| mean[i] + p[i] / 192.0); + } + } + let kept = (mean[1] * reference[1] + mean[2] * reference[2]) / (reference[1].powi(2) + reference[2].powi(2)); + assert!(kept > 0.85, "thin line keeps only {}%", 100.0 * kept); + } + + #[test] + fn joint_estimates_correlated_noise_at_a_matching_scale() { + let clean = Rgb32f::filled(256, 192, [0.03; 3]); + let correlated = gaussian(&noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.012), 0.8).map(yuv); + let model = noise_model(&correlated); + for i in 0..3 { + let mean = correlated.data.iter().map(|p| p[i] as f64).sum::() / correlated.len() as f64; + let variance = correlated.data.iter().map(|p| (p[i] as f64 - mean).powi(2)).sum::() / correlated.len() as f64; + let predicted = model.var(i, 0.03) as f64; + assert!(predicted > 0.6 * variance && predicted < 1.6 * variance, "channel {i}: estimated {predicted}, actual {variance}"); + } + } + + /// The speck brake takes the colour out of a compact, isoluminant 2 × 2 speck (as demosaicing leaves + /// them at high ISO), more at Color 100 than at 25, but leaves a coloured star (a luminance peak) alone. + #[test] + fn noise_line_does_not_jump_when_a_band_crosses_the_outlier_bound() { + // The luminance bands of a 640-px preview of demo scene 0 after luminance NR. Its band at + // 0.593 sat at 4 times the first fit: the CPU's samples put it just above, the GPU's just + // below, and the fits came out 2.6 % apart (CPU and GPU renders then differed by 10 levels). + let mut pts: Vec<(f64, f64, f64)> = [ + (0.009, 5.028e-7), + (0.022, 1.554e-4), + (0.063, 1.459e-4), + (0.147, 9.728e-6), + (0.213, 2.701e-5), + (0.272, 5.077e-6), + (0.315, 3.236e-5), + (0.356, 2.531e-5), + (0.390, 5.329e-6), + (0.420, 4.924e-6), + (0.467, 5.453e-5), + (0.530, 1.823e-5), + (0.593, 0.0), + (0.648, 1.501e-8), + (0.667, 1.898e-8), + (0.996, 3.490e-7), + ] + .map(|(y, v)| (y, v, 5649.0)) + .to_vec(); + let (a, b) = fit_nonneg_line(&pts[..pts.len().div_ceil(2)]); + let bound = 4.0 * (a * 0.593 + b); + let mut fit = |k: f64| { + pts[12].1 = bound * k; + robust_line(&pts) + }; + let (below, above) = (fit(1.0 - 1e-6), fit(1.0 + 1e-6)); + assert!((below.1 / above.1 - 1.0).abs() < 1e-4, "{below:?} vs {above:?}"); + assert!((below.0 - above.0).abs() <= 1e-4 * below.0.abs().max(1e-12), "{below:?} vs {above:?}"); + } + + #[test] + fn speck_brake_removes_compact_colour_specks_but_not_stars() { + let dark = [0.004f32; 3]; + let mut magenta = [0.024, 0.0, 0.024]; + magenta[1] = (luminance_2020(dark) - 0.2627 * magenta[0] - 0.0593 * magenta[2]) / 0.6780; + let star = [0.3, 0.2, 0.1]; + let clean = Rgb32f::from_fn(128, 96, |x, y| match (x, y) { + (40..42, 40..42) => magenta, + (90..92, 40..42) => star, + _ => dark, + }); + let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.001); + // share of the object's chroma (against the background) left in its 2 × 2 pixels + let kept = |out: &Rgb32f, x0: usize, colour: [f32; 3]| { + let (r, b) = (yuv(colour), yuv(dark)); + let reference = [r[1] - b[1], r[2] - b[2]]; + let mut mean = [0.0f32; 2]; + for (x, y) in [(x0, 40), (x0 + 1, 40), (x0, 41), (x0 + 1, 41)] { + let p = yuv(out.get(x, y)); + mean = [mean[0] + 0.25 * (p[1] - b[1]), mean[1] + 0.25 * (p[2] - b[2])]; + } + (mean[0] * reference[0] + mean[1] * reference[1]) / (reference[0].powi(2) + reference[1].powi(2)) + }; + let run = |brake| { + let mut out = input.clone(); + denoise_grid(&mut out, ¶ms(1), 1, 0.5, 1.0, brake); + (kept(&out, 40, magenta), kept(&out, 90, star)) + }; + let (off, star_off) = run(SpeckBrake::OFF); + let (weak, _) = run(speck_brake(0.25)); + let (strong, star_strong) = run(speck_brake(1.0)); + assert!(off > 0.5, "without the brake the speck keeps {off}"); + assert!(weak < 0.8 * off && strong < 0.2, "speck kept: off {off}, at 25 {weak}, at 100 {strong}"); + assert!(strong < weak, "the brake is stronger at 100 ({strong}) than at 25 ({weak})"); + assert!((star_strong - star_off).abs() < 0.02, "star colour {star_off} -> {star_strong}"); + } + + /// `distance_run` (planes, no branches) gives `distance` bit for bit. + #[test] + fn distance_run_matches_distance() { + let clean = Rgb32f::from_fn(64, 3, |x, _| [0.002 * x as f32, 0.01, 0.03 - 0.0004 * x as f32]); + let img = noisy(&clean, 0x9e37_79b9_7f4a_7c15, 0.01).map(yuv); + let mut noise = noise_model(&noisy(&Rgb32f::filled(64, 64, [0.02; 3]), 7, 0.004).map(yuv)); + noise.tolerance = 0.7; + let planes = Planes { c: std::array::from_fn(|i| img.data.iter().map(|p| p[i]).collect()), w: 64 }; + let mut out = vec![0.0; 64]; + distance_run(planes.run(0, 0, 64).unwrap(), planes.run(2, 0, 64).unwrap(), &noise, &mut out); + for (x, d) in out.iter().enumerate() { + assert_eq!(d.to_bits(), distance(img.get(x, 0), img.get(x, 2), &noise).to_bits(), "pixel {x}"); + } + } +} diff --git a/crates/develop/src/nrc_joint_reference.rs b/crates/develop/src/nrc_joint_reference.rs new file mode 100644 index 0000000000..b123f41eab --- /dev/null +++ b/crates/develop/src/nrc_joint_reference.rs @@ -0,0 +1,333 @@ +//! TEST ONLY: the joint colour NR as of 8b89526d, kept as the reference the optimised `nrc_joint` +//! must reproduce bit for bit. Changed since only where `nrc_joint` changed its result on purpose: +//! the noise line's outlier bands fade out (`nrc_joint::robust_line`) and the pilot's axis choice +//! fades in (`nrc_joint::pilot_pick`). +//! +//! Linear colour NR with a fixed, denoised joint guide. Strength controls the spatial scale; +//! noise-normalized guide distances control which neighbours can exchange colour. Both chroma +//! components use the same weights. Symmetric fluxes preserve the grid's channel sums, including +//! at its boundaries; no nonnegative clamp or square-root bias correction is involved. + +use crate::colorops::luminance_2020; +use crate::local::{NrcNoise, NrcParams}; +use crate::raster::{Rgb32f, blur::gaussian, par_rows as for_rows, resample::Filter}; + +#[derive(Debug)] +struct JointNoise { + model: NrcNoise, + /// Do not extrapolate beyond bands that contain usable noise measurements. + ymax: [f32; 3], + tolerance: f32, +} + +impl JointNoise { + fn var(&self, i: usize, y: f32) -> f32 { + self.model.var(i, y.min(self.ymax[i])) + } +} + +fn yuv(c: [f32; 3]) -> [f32; 3] { + let y = luminance_2020(c); + [y, c[0] - y, c[2] - y] +} + +fn rgb(y: f32, uv: [f32; 3]) -> [f32; 3] { + let r = y + uv[1]; + let b = y + uv[2]; + [r, (y - 0.2627 * r - 0.0593 * b) / 0.6780, b] +} + +/// Noise of Y, R-Y and B-Y measured from small high-pass residuals, not the colour variance +/// of a wide smoothing window. The median-square calibration is for Gaussian residuals. +/// Luminance bands with predominantly texture may only lower their weight in the fit: they +/// cannot force a shadow scene's extrapolated highlight noise arbitrarily high. +fn noise_model(img: &Rgb32f) -> JointNoise { + const BANDS: usize = 16; + let mut samples = Vec::new(); + let stride = img.len().div_ceil(crate::local::NRC_SAMPLES).max(1) | 1; + if img.width < 3 || img.height < 3 { + return JointNoise { model: NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }, ymax: [0.0; 3], tolerance: 1.0 }; + } + for index in (0..img.len()).step_by(stride) { + let (x, y) = (index % img.width, index / img.width); + if x == 0 || y == 0 || x + 1 == img.width || y + 1 == img.height { + continue; + } + let Some(c) = img.data.get(index) else { continue }; + let mut residual = [[0.0f32; 3]; 3]; + let mut brightness = 0.0; + let mut valid = true; + for (scale, delta) in [1usize, 2, 4].into_iter().enumerate() { + // Tiny images use the nearest supported scale rather than extending an edge + // into the noise samples. + let delta = delta.min(x).min(y).min(img.width - x - 1).min(img.height - y - 1); + let neighbours = [index - delta, index + delta, index - delta * img.width, index + delta * img.width]; + let mut m = [0.0f32; 3]; + for n in neighbours { + if let Some(p) = img.data.get(n) { + m = std::array::from_fn(|i| m[i] + 0.25 * p[i]); + } + } + residual[scale] = std::array::from_fn(|i| (c[i] - m[i]).powi(2)); + brightness += m[0] / 3.0; + valid &= c.iter().chain(m.iter()).all(|v| v.is_finite()); + } + if valid { + samples.push((brightness.max(0.0), residual)); + } + } + samples.sort_by(|a, b| a.0.total_cmp(&b.0)); + let per = samples.len().div_ceil(BANDS).max(32); + let mut pts: [Vec<(f64, f64, f64)>; 3] = std::array::from_fn(|_| Vec::new()); + for band in samples.chunks(per).filter(|b| b.len() >= 32) { + let y = band.iter().map(|p| p.0 as f64).sum::() / band.len() as f64; + for (i, pts) in pts.iter_mut().enumerate() { + let mut variance = 1e-14f64; + for scale in 0..3 { + let mut r: Vec = band.iter().map(|p| p.1[scale][i]).collect(); + let middle = r.len() / 2; + let (_, median, _) = r.select_nth_unstable_by(middle, f32::total_cmp); + // Each kernel has norm squared 1.25. Larger spacings recover noise + // hidden by the positive spatial correlations of demosaiced RGB. + variance = variance.max(*median as f64 / (0.454_936_4 * 1.25)); + } + pts.push((y, variance, band.len() as f64)); + } + } + let mut model = NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }; + let mut ymax = [0.0; 3]; + for (i, pts) in pts.iter().enumerate() { + if pts.is_empty() { + continue; + } + // Seed from the darker half, then include all bands with a bounded influence for + // unexpectedly high residuals (foliage etc.). Refit rather than clamp the intercept. + let (a, b, top) = crate::nrc_joint::robust_line(pts); + ymax[i] = top; + model.alpha[i] = a as f32; + model.beta[i] = (b as f32).max(1e-14); + } + JointNoise { model, ymax, tolerance: 1.0 } +} + +/// Squared distance beyond the expected noise in a difference of two guide samples. A small +/// relative luminance allowance lets a smooth surface exchange colour without crossing a +/// significant luminance or isoluminant colour boundary. The guide is fixed across all scales. +fn distance(a: [f32; 3], b: [f32; 3], noise: &JointNoise) -> f32 { + let y = 0.5 * (a[0] + b[0]); + let allowance = (0.025 * y.max(0.0)).powi(2); + (0..3) + .map(|i| { + let v = noise.var(i, y); + // The 3x3 pilot blur reduces uncorrelated noise to 1/9. Keep a conservative + // allowance for correlations left by demosaicing and grid resampling. + ((a[i] - b[i]).powi(2) - v).max(0.0) / (3.0 * noise.tolerance * v + allowance) + }) + .sum::() +} + +/// Denoise the pilot along a clearly smoother axis at strong edges. An isotropic blur +/// dilutes a two-pixel isoluminant line before the edge decision even sees it. Weak or +/// ambiguous structure uses the isotropic pilot, so noise alone does not protect itself. +fn pilot(original: &Rgb32f, noise: &JointNoise) -> Rgb32f { + let mut guide = gaussian(original, 0.8); + let (w, h) = (original.width, original.height); + for_rows(&mut guide.data, w, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + if x == 0 || y == 0 || x + 1 == w || y + 1 == h { + continue; + } + let index = y * w + x; + let Some(&p) = original.data.get(index) else { continue }; + let mut means = [[0.0f32; 3]; 2]; + let mut variances = [0.0; 2]; + for (axis, offset) in [1, w].into_iter().enumerate() { + let (Some(&a), Some(&b)) = (original.data.get(index - offset), original.data.get(index + offset)) else { continue }; + means[axis] = std::array::from_fn(|i| (a[i] + p[i] + b[i]) / 3.0); + variances[axis] = (0..3) + .map(|i| { + let m = means[axis][i]; + ((a[i] - m).powi(2) + (p[i] - m).powi(2) + (b[i] - m).powi(2)) / (9.0 * noise.var(i, p[0])) + }) + .sum::(); + } + *out = crate::nrc_joint::pilot_pick(*out, means[0], variances[0], means[1], variances[1]); + } + }); + guide +} + +/// One conservative horizontal/vertical diffusion step. Pair weights are symmetric; the +/// guide is never replaced by the filtered result. Long taps also account for the intervening +/// guide edges, so a wide pass cannot jump over a thin differently coloured object. +fn diffuse(src: &Rgb32f, dst: &mut Rgb32f, links: &Rgb32f, delta: usize, vertical: bool, rate: f32) { + let (w, h) = (src.width, src.height); + for_rows(&mut dst.data, w, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let index = y * w + x; + let Some(&p) = src.data.get(index) else { continue }; + *out = p; + let coordinate = if vertical { y } else { x }; + let length = if vertical { h } else { w }; + for neighbour in [coordinate.checked_sub(delta), coordinate.checked_add(delta).filter(|&v| v < length)].into_iter().flatten() { + let ni = if vertical { neighbour * w + x } else { y * w + neighbour }; + let start = coordinate.min(neighbour); + let pi = if vertical { start * w + x } else { y * w + start }; + let (Some(&q), Some(link)) = (src.data.get(ni), links.data.get(pi)) else { continue }; + let weight = rate * link[usize::from(vertical)]; + for i in 1..3 { + out[i] += weight * (q[i] - p[i]); + } + } + } + }); +} + +pub(crate) fn denoise_grid(img: &mut Rgb32f, params: &NrcParams, step: usize, detail: f32, strength: f32) { + if img.is_empty() || strength <= 0.0 { + return; + } + // A maximum 2x grid keeps colour boundaries visible even at high strength. The old grid + // grew to 16x with the radius, making the colour loss inseparable from slider strength. + let step = if img.width.is_multiple_of(step) && img.height.is_multiple_of(step) { step } else { 1 }; + let (w, h) = (img.width.div_ceil(step), img.height.div_ceil(step)); + // Transform before resampling; negative linear differences are valid throughout. + let mut original = Rgb32f::new(w, h); + for_rows(&mut original.data, w, |y, row| { + for (x, p) in row.iter_mut().enumerate() { + let mut count = 0.0f32; + for sy in y * step..((y + 1) * step).min(img.height) { + for sx in x * step..((x + 1) * step).min(img.width) { + if let Some(&c) = img.data.get(sy * img.width + sx) { + let c = yuv(c); + *p = std::array::from_fn(|i| p[i] + c[i]); + count += 1.0; + } + } + } + *p = p.map(|v| v / count.max(1.0)); + } + }); + let mut noise = noise_model(&original); + noise.tolerance = (1.5 - detail).clamp(0.5, 1.5); + let guide = pilot(&original, &noise); + if std::env::var_os("NRV2_DEBUG").is_some() { + eprintln!(" nr joint: {w}x{h}, Y/R-Y/B-Y alpha {:?} beta {:?}, supported Y {:?}", noise.model.alpha, noise.model.beta, noise.ymax); + } + let mut filtered = original.clone(); + let mut scratch = Rgb32f::new(w, h); + let mut paths = Rgb32f::new(w, h); + let mut links = Rgb32f::new(w, h); + for_rows(&mut paths.data, w, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let index = y * w + x; + let Some(&g) = guide.data.get(index) else { continue }; + if x + 1 < w + && let Some(&b) = guide.data.get(index + 1) + { + out[0] = distance(g, b, &noise); + } + if y + 1 < h + && let Some(&b) = guide.data.get(index + w) + { + out[1] = distance(g, b, &noise); + } + } + }); + // Scale is independent of the edge decision. K has no role in deciding whether a leaf + // is noise. Two dyadic sweeps provide broad smoothing with a fixed number of scales. + let sigma = params.passes.last().map_or(0.0, |p| p.sigma / step as f32); + let mut remaining = sigma * sigma; + let mut delta = 1usize; + while remaining > 0.01 && delta <= w.max(h) { + let rate = (remaining / (4.0 * (delta as f32).powi(2))).min(0.25); + // Each symmetric pair weight is evaluated once per scale and reused by both + // diffusion sweeps and both ends of the pair. + for_rows(&mut links.data, w, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let index = y * w + x; + let (Some(&g), Some(path)) = (guide.data.get(index), paths.data.get(index)) else { continue }; + *out = [0.0; 3]; + for (axis, offset, valid) in [(0, delta, x + delta < w), (1, delta * w, y + delta < h)] { + if valid && let Some(&other) = guide.data.get(index + offset) { + out[axis] = (-distance(g, other, &noise).max(path[axis])).exp(); + } + } + } + }); + for _ in 0..2 { + diffuse(&filtered, &mut scratch, &links, delta, false, rate); + std::mem::swap(&mut filtered, &mut scratch); + diffuse(&filtered, &mut scratch, &links, delta, true, rate); + std::mem::swap(&mut filtered, &mut scratch); + } + remaining -= 4.0 * rate * (delta as f32).powi(2); + // Maxima over paths of length 2*delta, using the two adjacent delta-length paths. + // Reuse the diffusion scratch so a long tap costs O(1), irrespective of radius. + for_rows(&mut scratch.data, w, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let index = y * w + x; + let Some(&p) = paths.data.get(index) else { continue }; + *out = p; + if x + delta < w + && let Some(q) = paths.data.get(index + delta) + { + out[0] = out[0].max(q[0]); + } + if y + delta < h + && let Some(q) = paths.data.get(index + delta * w) + { + out[1] = out[1].max(q[1]); + } + } + }); + std::mem::swap(&mut paths, &mut scratch); + delta = delta.saturating_mul(2); + } + drop(scratch); + drop(paths); + drop(links); + if step == 1 { + for (p, q) in img.data.iter_mut().zip(&filtered.data) { + let result = rgb(luminance_2020(*p), *q); + *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); + } + } else { + // Reconstruct only rows. Keep the fine residual with a shared, noise-subtracted + // Wiener share; a flat noisy patch receives no automatic protection from noisy Y. + let mean = gaussian(&original, 1.0); + let corr = gaussian(&original.map(|p| p.map(|v| v * v)), 1.0); + let share = corr.zip_map(&mean, |c, m| { + let snr = (1..3).map(|i| ((c[i] - m[i] * m[i]).max(0.0) / noise.var(i, m[0]) - 1.0).max(0.0)).sum::() * 0.5; + [snr / (snr + 8.0); 3] + }); + let share = gaussian(&share, 0.8); + // Resize one output row at a time using the raster resampler's exact pixel centres. + use crate::raster::resample::weights; + let ux = weights(w, img.width, Filter::Bilinear); + let uy = weights(h, img.height, Filter::Bilinear); + let ow = img.width; + for_rows(&mut img.data, ow, |y, row| { + let Some((y0, wy)) = uy.get(y) else { return }; + for (x, p) in row.iter_mut().enumerate() { + let Some((x0, wx)) = ux.get(x) else { continue }; + let (mut f, mut o, mut a) = ([0.0; 3], [0.0; 3], 0.0); + for (j, &dy) in wy.iter().enumerate() { + for (i, &dx) in wx.iter().enumerate() { + let index = (y0 + j) * w + x0 + i; + if let (Some(q), Some(r), Some(s)) = (filtered.data.get(index), original.data.get(index), share.data.get(index)) { + let weight = dx * dy; + f = std::array::from_fn(|c| f[c] + weight * q[c]); + o = std::array::from_fn(|c| o[c] + weight * r[c]); + a += weight * s[0]; + } + } + } + let c = yuv(*p); + let q = std::array::from_fn(|i| f[i] + a * (c[i] - o[i])); + let result = rgb(c[0], q); + *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); + } + }); + } +} diff --git a/crates/develop/src/profiles.rs b/crates/develop/src/profiles.rs new file mode 100644 index 0000000000..1f7cf6d857 --- /dev/null +++ b/crates/develop/src/profiles.rs @@ -0,0 +1,310 @@ +//! Base rendering profiles. A profile is a look applied *underneath* the user's sliders (the sliders +//! stay at their displayed values); `profile.amount` (0–200 %) scales it. All looks are our own. +//! +//! Every look is a set of *deltas* on the user's settings, each multiplied by the amount: slider +//! offsets (contrast, saturation, colour mixer, B&W mix…), colour-grading wheels (added as colour +//! vectors to the user's wheels) and point-curve fades (black/white output levels composed after +//! the user's point curves). The CPU pipeline and the GPU path both render [`effective`] +//! settings, so a profile needs no kernel of its own. No look adds grain. + +use std::borrow::Cow; + +use craft_develop_model::{DevelopSettings, Treatment, Wheel}; +use craft_geom::Point; + +/// Add a colour-grading wheel (`hue` °, `sat` 0..100, `lum` −100..100) scaled by `k` to `w`, as a +/// colour vector (so a profile's tint combines with the user's instead of replacing it). +fn wheel(w: &mut Wheel, hue: f64, sat: f64, lum: f64, k: f64) { + let (ua, ub) = (w.sat * w.hue.to_radians().cos(), w.sat * w.hue.to_radians().sin()); + let (pa, pb) = (sat * k * hue.to_radians().cos(), sat * k * hue.to_radians().sin()); + let (a, b) = (ua + pa, ub + pb); + let s = a.hypot(b); + if s > 1e-9 { + w.hue = b.atan2(a).to_degrees().rem_euclid(360.0); + } else if w.sat == 0.0 { + w.hue = hue; + } + w.sat = s.clamp(0.0, 100.0); + w.lum = (w.lum + lum * k).clamp(-100.0, 100.0); +} + +/// Fade a point curve: output black level `black` and white level `white` (0..1, moved from the +/// identity by `k`), composed after the user's curve (`y → b + y·(w − b)`). +fn fade(pts: &mut Vec, black: f64, white: f64, k: f64) { + let b = (black * k).clamp(0.0, 0.45); + let w = (1.0 - (1.0 - white) * k).clamp(0.55, 1.0); + if pts.len() < 2 { + *pts = vec![Point::new(0.0, 0.0), Point::new(1.0, 1.0)]; + } + for p in pts.iter_mut() { + p.y = b + p.y.clamp(0.0, 1.0) * (w - b); + } +} + +/// The settings the pipeline actually renders: user settings plus the profile's look. +pub fn effective(s: &DevelopSettings) -> Cow<'_, DevelopSettings> { + let k = (s.profile.amount / 100.0).clamp(0.0, 2.0); + let id = s.profile.id.as_str(); + if id == "lc.color" || id.is_empty() || k == 0.0 { + return Cow::Borrowed(s); + } + let mut e = s.clone(); + let add = |v: &mut f64, d: f64| *v = (*v + d * k).clamp(-100.0, 100.0); + match id { + // ---- Basic + "lc.neutral" => { + add(&mut e.light.contrast, -18.0); + add(&mut e.color.saturation, -10.0); + add(&mut e.light.highlights, -10.0); + add(&mut e.light.shadows, 8.0); + } + "lc.vivid" => { + add(&mut e.light.contrast, 16.0); + add(&mut e.color.saturation, 14.0); + add(&mut e.color.vibrance, 14.0); + add(&mut e.light.blacks, -6.0); + } + "lc.landscape" => { + add(&mut e.light.contrast, 10.0); + add(&mut e.color.vibrance, 10.0); + add(&mut e.mixer.green.sat, 14.0); + add(&mut e.mixer.aqua.sat, 10.0); + add(&mut e.mixer.blue.sat, 14.0); + add(&mut e.mixer.blue.lum, -6.0); + add(&mut e.effects.clarity, 6.0); + } + "lc.portrait" => { + add(&mut e.light.contrast, -6.0); + add(&mut e.mixer.orange.sat, -8.0); + add(&mut e.mixer.orange.lum, 6.0); + add(&mut e.mixer.red.sat, -5.0); + add(&mut e.effects.texture, -6.0); + } + "lc.mono" => { + e.treatment = Treatment::Bw; + add(&mut e.light.contrast, 8.0); + } + // ---- Film + "lc.film.warm-print" => { + add(&mut e.light.contrast, 6.0); + add(&mut e.color.saturation, -4.0); + add(&mut e.mixer.orange.lum, 4.0); + fade(&mut e.curve.master, 0.04, 0.97, k); + wheel(&mut e.grading.highlights, 40.0, 18.0, 0.0, k); + wheel(&mut e.grading.shadows, 25.0, 8.0, 0.0, k); + } + "lc.film.cool-fade" => { + add(&mut e.light.contrast, -8.0); + add(&mut e.color.saturation, -10.0); + fade(&mut e.curve.master, 0.07, 0.95, k); + wheel(&mut e.grading.shadows, 210.0, 16.0, 0.0, k); + wheel(&mut e.grading.highlights, 190.0, 6.0, 0.0, k); + } + "lc.film.golden-hour" => { + add(&mut e.color.vibrance, 10.0); + add(&mut e.curve.highlights, -8.0); + add(&mut e.mixer.orange.sat, 8.0); + add(&mut e.mixer.yellow.hue, -6.0); + wheel(&mut e.grading.global, 45.0, 10.0, 0.0, k); + wheel(&mut e.grading.highlights, 35.0, 20.0, 0.0, k); + } + "lc.film.faded-slide" => { + add(&mut e.light.contrast, 14.0); + add(&mut e.color.vibrance, 8.0); + add(&mut e.color.saturation, 6.0); + add(&mut e.curve.shadows, 10.0); + fade(&mut e.curve.blue, 0.06, 1.0, k); + fade(&mut e.curve.red, 0.0, 0.97, k); + } + // ---- Cinematic + "lc.cine.teal-amber" => { + add(&mut e.light.contrast, 10.0); + add(&mut e.mixer.orange.sat, 6.0); + add(&mut e.mixer.green.hue, 20.0); + add(&mut e.mixer.green.sat, -20.0); + add(&mut e.mixer.blue.hue, -8.0); + wheel(&mut e.grading.shadows, 195.0, 30.0, 0.0, k); + wheel(&mut e.grading.highlights, 38.0, 24.0, 0.0, k); + } + "lc.cine.night-blue" => { + add(&mut e.light.contrast, 12.0); + add(&mut e.color.saturation, -12.0); + add(&mut e.curve.darks, -8.0); + wheel(&mut e.grading.shadows, 220.0, 28.0, -4.0, k); + wheel(&mut e.grading.midtones, 215.0, 10.0, 0.0, k); + } + "lc.cine.desert-heat" => { + add(&mut e.light.contrast, 8.0); + add(&mut e.curve.lights, 6.0); + add(&mut e.mixer.blue.sat, -25.0); + add(&mut e.mixer.aqua.sat, -20.0); + wheel(&mut e.grading.global, 32.0, 16.0, 0.0, k); + wheel(&mut e.grading.highlights, 48.0, 12.0, 0.0, k); + } + "lc.cine.neon-dusk" => { + add(&mut e.light.contrast, 10.0); + add(&mut e.color.vibrance, 18.0); + add(&mut e.mixer.magenta.sat, 12.0); + add(&mut e.mixer.purple.sat, 12.0); + wheel(&mut e.grading.shadows, 265.0, 22.0, 0.0, k); + wheel(&mut e.grading.highlights, 330.0, 14.0, 0.0, k); + } + // ---- Muted + "lc.muted.matte-soft" => { + add(&mut e.light.contrast, -12.0); + add(&mut e.color.saturation, -14.0); + add(&mut e.curve.highlights, -6.0); + fade(&mut e.curve.master, 0.08, 0.96, k); + } + "lc.muted.bleached" => { + add(&mut e.light.contrast, 22.0); + add(&mut e.color.saturation, -38.0); + add(&mut e.curve.lights, 6.0); + add(&mut e.effects.clarity, 8.0); + } + "lc.muted.pastel-haze" => { + add(&mut e.light.contrast, -18.0); + add(&mut e.color.saturation, -20.0); + add(&mut e.color.vibrance, 12.0); + fade(&mut e.curve.master, 0.1, 1.0, k); + wheel(&mut e.grading.highlights, 330.0, 6.0, 0.0, k); + wheel(&mut e.grading.shadows, 200.0, 6.0, 0.0, k); + } + "lc.muted.quiet-green" => { + add(&mut e.light.contrast, -4.0); + add(&mut e.color.saturation, -8.0); + add(&mut e.mixer.green.sat, -30.0); + add(&mut e.mixer.green.hue, -10.0); + add(&mut e.mixer.yellow.sat, -18.0); + add(&mut e.mixer.aqua.sat, -15.0); + fade(&mut e.curve.master, 0.04, 1.0, k); + } + // ---- B&W + "lc.bw.mono-rich" => { + e.treatment = Treatment::Bw; + add(&mut e.light.contrast, 18.0); + add(&mut e.curve.darks, -8.0); + add(&mut e.curve.lights, 6.0); + add(&mut e.bw_mix.red, 8.0); + add(&mut e.bw_mix.orange, 10.0); + add(&mut e.bw_mix.blue, -12.0); + } + "lc.bw.red-filter" => { + e.treatment = Treatment::Bw; + add(&mut e.light.contrast, 12.0); + add(&mut e.bw_mix.red, 40.0); + add(&mut e.bw_mix.orange, 30.0); + add(&mut e.bw_mix.yellow, 10.0); + add(&mut e.bw_mix.green, -20.0); + add(&mut e.bw_mix.aqua, -30.0); + add(&mut e.bw_mix.blue, -45.0); + } + "lc.bw.soft" => { + e.treatment = Treatment::Bw; + add(&mut e.light.contrast, -14.0); + add(&mut e.bw_mix.orange, 12.0); + fade(&mut e.curve.master, 0.06, 0.97, k); + } + "lc.bw.sepia" => { + e.treatment = Treatment::Bw; + add(&mut e.light.contrast, 6.0); + fade(&mut e.curve.master, 0.04, 0.98, k); + wheel(&mut e.grading.shadows, 28.0, 18.0, 0.0, k); + wheel(&mut e.grading.highlights, 45.0, 14.0, 0.0, k); + } + _ => return Cow::Borrowed(s), + } + Cow::Owned(e) +} + +/// Ids of the looks [`effective`] implements (besides the identity `lc.color`). +pub const LOOK_IDS: &[&str] = &[ + "lc.neutral", + "lc.vivid", + "lc.landscape", + "lc.portrait", + "lc.mono", + "lc.film.warm-print", + "lc.film.cool-fade", + "lc.film.golden-hour", + "lc.film.faded-slide", + "lc.cine.teal-amber", + "lc.cine.night-blue", + "lc.cine.desert-heat", + "lc.cine.neon-dusk", + "lc.muted.matte-soft", + "lc.muted.bleached", + "lc.muted.pastel-haze", + "lc.muted.quiet-green", + "lc.bw.mono-rich", + "lc.bw.red-filter", + "lc.bw.soft", + "lc.bw.sepia", +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_profile_is_borrowed_and_others_change_things() { + let s = DevelopSettings::default(); + assert!(matches!(effective(&s), Cow::Borrowed(_))); + for id in LOOK_IDS { + let mut t = s.clone(); + t.profile.id = (*id).into(); + assert_ne!(*effective(&t), t, "{id}"); + t.profile.amount = 0.0; + assert_eq!(*effective(&t), t, "{id} at 0%"); + } + } + + #[test] + fn looks_scale_with_amount_and_never_add_grain() { + let mut s = DevelopSettings::default(); + s.light.contrast = 5.0; + for id in LOOK_IDS { + s.profile.id = (*id).into(); + let at = |a: f64| { + let mut t = s.clone(); + t.profile.amount = a; + effective(&t).into_owned() + }; + let (half, full, double) = (at(50.0), at(100.0), at(200.0)); + // slider deltas are linear in the amount + let d = |e: &DevelopSettings| e.light.contrast - s.light.contrast; + assert!((d(&full) - 2.0 * d(&half)).abs() < 1e-9, "{id}"); + assert!((d(&double) - 2.0 * d(&full)).abs() < 1e-9, "{id}"); + // wheels and point-curve fades grow with the amount + let lift = |e: &DevelopSettings| e.curve.master.first().map_or(0.0, |p| p.y); + for (a, b) in [(&half, &full), (&full, &double)] { + assert!(a.grading.shadows.sat <= b.grading.shadows.sat + 1e-9, "{id}"); + assert!(a.grading.highlights.sat <= b.grading.highlights.sat + 1e-9, "{id}"); + assert!(lift(a) <= lift(b) + 1e-9, "{id}"); + } + if lift(&full) > 0.0 { + assert!((lift(&full) - 2.0 * lift(&half)).abs() < 1e-9, "{id}"); + } + assert_eq!(full.grain, s.grain, "{id} adds no grain"); + assert_eq!(full.profile, s.profile, "{id}"); + } + } + + #[test] + fn wheels_and_fades_compose_with_user_settings() { + let mut s = DevelopSettings::default(); + s.grading.shadows = Wheel { hue: 195.0, sat: 10.0, lum: 0.0 }; + s.curve.master = vec![Point::new(0.0, 0.0), Point::new(0.5, 0.6), Point::new(1.0, 1.0)]; + s.profile.id = "lc.cine.teal-amber".into(); + let e = effective(&s); + assert!((e.grading.shadows.hue - 195.0).abs() < 1e-6 && (e.grading.shadows.sat - 40.0).abs() < 1e-6, "{:?}", e.grading.shadows); + assert_eq!(e.curve.master, s.curve.master, "no fade in this look: the user's curve stays"); + s.profile.id = "lc.muted.matte-soft".into(); + let e = effective(&s); + assert_eq!(e.curve.master.len(), 3, "user points kept"); + let ys: Vec = e.curve.master.iter().map(|p| p.y).collect(); + for (y, want) in ys.iter().zip([0.08, 0.08 + 0.6 * 0.88, 0.96]) { + assert!((y - want).abs() < 1e-9, "{ys:?}"); + } + } +} diff --git a/crates/develop/src/raster/blur.rs b/crates/develop/src/raster/blur.rs new file mode 100644 index 0000000000..10576d70e4 --- /dev/null +++ b/crates/develop/src/raster/blur.rs @@ -0,0 +1,325 @@ +//! Gaussian-like blur by three successive box filters (running sums, O(1) per pixel per pass). + +use super::resample::Pixel; +use super::{Image, par_rows}; + +/// The largest blur sigma (pixels) the box radii are made for. A box wider than any image (the +/// encoders' limit is 65535 px) blurs to the same flat result, and a larger sigma made the box +/// width's square overflow (from about 23 170 px: a panic where overflow is checked, a garbage +/// radius of billions of pixels, i.e. a hung render, where it isn't). +pub const MAX_SIGMA: f32 = 65_536.0; + +/// Box radii approximating a Gaussian of `sigma` with 3 passes (Kovesi / Wells). A sigma that is +/// not a number counts as 0 (no blur); one above [`MAX_SIGMA`] (infinity too) as `MAX_SIGMA`. +pub fn box_radii(sigma: f32) -> [usize; 3] { + let sigma = if sigma.is_nan() { 0.0 } else { sigma.clamp(0.0, MAX_SIGMA) }; + let n = 3.0f32; + let w_ideal = (12.0 * sigma * sigma / n + 1.0).sqrt(); + let mut wl = w_ideal.floor() as i32; + if wl % 2 == 0 { + wl -= 1; + } + let wu = wl + 2; + // (the square in i64: it passes i32 from a box 46 341 px wide) + let m_ideal = (12.0 * sigma * sigma - n * (i64::from(wl) * i64::from(wl)) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0); + let m = m_ideal.round() as i32; + std::array::from_fn(|i| (((if (i as i32) < m { wl } else { wu }) - 1) / 2).max(0) as usize) +} + +/// Standard deviation (px) of the blur [`gaussian`] actually makes for `sigma`: its boxes are +/// whole pixels wide, so small radii snap to a few steps (0 below about 0.58 px, then √(2/3) px for one +/// 3-px box per axis, …). +pub fn box_sigma(sigma: f32) -> f32 { + if sigma.is_nan() || sigma <= 0.3 { + return 0.0; + } + box_radii(sigma) + .iter() + .map(|&r| { + // Square the bounded width independently of the target's pointer size. + let width = 2 * r as u64 + 1; + ((width * width - 1) as f32) / 12.0 + }) + .sum::() + .sqrt() +} + +/// One horizontal box pass over `row` (clamped edges), using `tmp` as scratch. +#[inline] +fn box_row(row: &mut [T], tmp: &mut Vec, r: usize) { + let w = row.len(); + if r == 0 || w == 0 { + return; + } + tmp.clear(); + tmp.extend_from_slice(row); + let s = &tmp[..]; + let last = w - 1; + let inv = 1.0 / (2 * r + 1) as f32; + let mut acc = T::zero(); + // the window [-r, r] with clamped edges: r copies of the first pixel, the pixels 0..=min(r, last), then the + // last pixel for each offset past it (O(w), not O(r), however large the radius) + acc = acc.madd(s[0], r as f32); + for v in &s[..=r.min(last)] { + acc = acc.madd(*v, 1.0); + } + // only when the window reaches past the last pixel: a NaN there must not poison a row it isn't in + if r > last { + acc = acc.madd(s[last], (r - last) as f32); + } + for x in 0..w { + row[x] = T::zero().madd(acc, inv); + acc = acc.madd(s[(x + r + 1).min(last)], 1.0).madd(s[x.saturating_sub(r)], -1.0); + } +} + +/// Rows per parallel band in the vertical pass (each band re-primes its running sums). +pub const BAND: usize = 32; + +/// One vertical box pass `src → dst` (clamped edges): a running sum per column, vectorized across +/// the row, parallel over horizontal bands. Cache-friendly — no transposes. +fn box_v(src: &Image, dst: &mut Image, r: usize) { + let (w, h) = (src.width, src.height); + let inv = 1.0 / (2 * r + 1) as f32; + let last = h - 1; + let row = |y: usize| &src.data[y * w..(y + 1) * w]; + par_rows(&mut dst.data, w * BAND, |band, out| { + let y0 = band * BAND; + let mut acc = vec![T::zero(); w]; + for i in 0..=2 * r { + let yy = (y0 + i).saturating_sub(r).min(last); + for (a, v) in acc.iter_mut().zip(row(yy)) { + *a = a.madd(*v, 1.0); + } + } + for (k, o) in out.chunks_mut(w).enumerate() { + let y = y0 + k; + for (d, a) in o.iter_mut().zip(&acc) { + *d = T::zero().madd(*a, inv); + } + let (add, sub) = (row((y + r + 1).min(last)), row(y.saturating_sub(r))); + for ((a, p), m) in acc.iter_mut().zip(add).zip(sub) { + *a = a.madd(*p, 1.0).madd(*m, -1.0); + } + } + }); +} + +/// The box radii of [`gaussian`] on a `w × h` image (the GPU renderer's twin uses them too), or +/// `None` when the blur leaves the image as it is: `sigma` at most 0.3 or not a number, or an +/// empty image. A sigma wider than twice the image's long side counts as that: a crop a hair +/// wide shown to fit asked the tone and dehaze stages for sigmas of millions of pixels (infinite +/// for a crop of no size), which blur no flatter than that but cost boxes that wide on every row. +pub fn radii_for(sigma: f32, w: usize, h: usize) -> Option<[usize; 3]> { + if sigma.is_nan() || sigma <= 0.3 || w == 0 || h == 0 { + return None; + } + let cap = (w.max(h) as f32 * 2.0).max(1.0); + Some(box_radii(sigma.min(cap))) +} + +/// Blur with Gaussian `sigma` (pixels). `sigma <= 0.3` returns a copy. +pub fn gaussian(img: &Image, sigma: f32) -> Image { + let Some(radii) = radii_for(sigma, img.width, img.height) else { + return img.clone(); + }; + let mut a = img.clone(); + par_rows(&mut a.data, img.width, |_, row| { + let mut tmp = Vec::with_capacity(row.len()); + for r in radii { + box_row(row, &mut tmp, r); + } + }); + let mut b = Image::::new(img.width, img.height); + for r in radii { + if r == 0 { + continue; + } + box_v(&a, &mut b, r); + std::mem::swap(&mut a, &mut b); + } + a +} + +/// Largest sigma [`gauss_taps`] makes taps for (larger ones are clamped to it). The GPU blur reads +/// the same taps, so it is the limit of both paths. +pub const GAUSS_SIGMA_MAX: f32 = 64.0; + +/// Normalized Gaussian taps `[w(-r) .. w(r)]` for `sigma`, `r = ceil(3 sigma)`. +/// +/// An exact kernel, unlike the three-box approximation of [`gaussian`], which cannot represent +/// a sigma under about 0.8 px (its boxes collapse to the identity): sharpening needs those. +pub fn gauss_taps(sigma: f32) -> Vec { + let sigma = if sigma.is_nan() { 0.05 } else { sigma.clamp(0.05, GAUSS_SIGMA_MAX) }; + let r = (3.0 * sigma).ceil() as i32; + let k = -0.5 / (sigma * sigma); + let mut t: Vec = (-r..=r).map(|i| ((i * i) as f32 * k).exp()).collect(); + let sum: f32 = t.iter().sum(); + t.iter_mut().for_each(|v| *v /= sum); + t +} + +/// Separable blur with odd-length symmetric `taps` (clamped edges), see [`gauss_taps`]. +pub fn gaussian_taps(img: &Image, taps: &[f32]) -> Image { + let (w, h) = (img.width, img.height); + if w == 0 || h == 0 || taps.len() < 3 { + return img.clone(); + } + let r = (taps.len() / 2) as isize; + let mut a = Image::::new(w, h); + par_rows(&mut a.data, w, |y, row| { + let src = &img.data[y * w..(y + 1) * w]; + for (x, o) in row.iter_mut().enumerate() { + let mut acc = T::zero(); + for (k, t) in taps.iter().enumerate() { + let xi = (x as isize + k as isize - r).clamp(0, w as isize - 1) as usize; + acc = acc.madd(src[xi], *t); + } + *o = acc; + } + }); + let mut b = Image::::new(w, h); + par_rows(&mut b.data, w, |y, row| { + for (k, t) in taps.iter().enumerate() { + let yi = (y as isize + k as isize - r).clamp(0, h as isize - 1) as usize; + for (o, v) in row.iter_mut().zip(&a.data[yi * w..(yi + 1) * w]) { + *o = o.madd(*v, *t); + } + } + }); + b +} + +#[cfg(test)] +mod tests { + #[test] + fn a_non_finite_last_pixel_stays_out_of_windows_that_do_not_reach_it() { + let mut row = [1.0f32; 8]; + row[7] = f32::NAN; + box_row(&mut row, &mut Vec::new(), 2); + assert!(row[..5].iter().all(|v| v.is_finite()), "{row:?}"); + } + + #[test] + fn fir_gaussian_has_bounded_finite_taps_for_hostile_sigmas() { + for sigma in [f32::NAN, f32::NEG_INFINITY, f32::INFINITY, f32::MAX, -5.0, 0.0, 0.1, 4.0] { + let taps = super::gauss_taps(sigma); + assert!(taps.len() <= 385 && taps.len() % 2 == 1); + assert!(taps.iter().all(|v| v.is_finite() && *v >= 0.0)); + assert!((taps.iter().sum::() - 1.0).abs() < 1e-5); + } + } + + /// The box radii of the formula as it was, for the check below. + fn box_radii_before(sigma: f32) -> [usize; 3] { + let n = 3.0f32; + let w_ideal = (12.0 * sigma * sigma / n + 1.0).sqrt(); + let mut wl = w_ideal.floor() as i32; + if wl % 2 == 0 { + wl -= 1; + } + let wu = wl + 2; + let m_ideal = (12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0); + let m = m_ideal.round() as i32; + std::array::from_fn(|i| (((if (i as i32) < m { wl } else { wu }) - 1) / 2).max(0) as usize) + } + + /// A blur sigma from a degenerate edit or a deep zoom (found by a UI campaign: a render + /// worker's blur with a huge sigma) squared the box width past i32, which panics in a debug + /// build and gave a radius of billions of pixels in a release one. Huge, infinite and NaN + /// sigmas give bounded radii, and a blur with them is quick and stays finite; every sigma that + /// worked before keeps exactly its radii. + #[test] + fn huge_and_non_finite_sigmas_give_bounded_radii() { + for sigma in [26_800.0, 46_341.0, 1e5, 1e9, f32::MAX, f32::INFINITY, f32::NEG_INFINITY, f32::NAN, -5.0] { + let r = box_radii(sigma); + assert!(r.iter().all(|&r| r <= MAX_SIGMA as usize * 2), "{sigma}: {r:?}"); + } + assert_eq!(box_radii(f32::NAN), [0, 0, 0]); + assert_eq!(box_radii(f32::NEG_INFINITY), [0, 0, 0]); + assert_eq!(box_radii(1e9), box_radii(MAX_SIGMA)); + assert_eq!(box_radii(f32::INFINITY), box_radii(MAX_SIGMA)); + // on an image, the blur is at most twice its long side; NaN and tiny sigmas don't blur + assert_eq!(radii_for(3.1e7, 1400, 900), Some(box_radii(2800.0))); + assert_eq!(radii_for(f32::INFINITY, 1400, 900), Some(box_radii(2800.0))); + assert_eq!(radii_for(40.0, 1400, 900), Some(box_radii(40.0)), "an ordinary sigma is as asked"); + assert_eq!(radii_for(f32::NAN, 1400, 900), None); + assert_eq!(radii_for(0.2, 1400, 900), None); + assert_eq!(radii_for(5.0, 0, 900), None); + let p = crate::raster::Plane { width: 4, height: 3, data: (0..12).map(|i| i as f32).collect() }; + let t = std::time::Instant::now(); + for sigma in [1e9, f32::INFINITY, f32::NAN] { + let b = gaussian(&p, sigma); + assert!(b.data.iter().all(|v| v.is_finite()), "{sigma}"); + } + assert!(t.elapsed().as_secs_f64() < 30.0, "a huge sigma's blur is bounded"); + let mut s = 0.0f32; + while s < 23_000.0 { + assert_eq!(box_radii(s), box_radii_before(s), "sigma {s}"); + s = s * 1.013 + 0.07; + } + } + + use super::*; + + #[test] + fn preserves_constant_and_mass() { + let img = Image::::filled(50, 30, 0.7); + let b = gaussian(&img, 4.0); + assert!(b.data.iter().all(|v| (v - 0.7).abs() < 1e-5)); + let mut imp = Image::::new(101, 101); + imp.set(50, 50, 1.0); + let b = gaussian(&imp, 5.0); + let sum: f32 = b.data.iter().sum(); + assert!((sum - 1.0).abs() < 1e-3, "{sum}"); + // peak moved to the centre and symmetric + assert!((b.get(45, 50) - b.get(55, 50)).abs() < 1e-6); + assert!((b.get(50, 45) - b.get(50, 55)).abs() < 1e-6); + } + + #[test] + fn box_sigma_is_the_blur_made() { + assert_eq!(box_sigma(0.3), 0.0); + assert_eq!(box_sigma(0.5), 0.0, "no box wider than 1 px"); + assert!((box_sigma(1.0) - (2.0f32 / 3.0).sqrt()).abs() < 1e-6); + for sigma in [1.0f32, 2.5, 8.0] { + let mut imp = Image::::new(201, 1); + imp.set(100, 0, 1.0); + let b = gaussian(&imp, sigma); + let var: f32 = b.data.iter().enumerate().map(|(i, v)| v * ((i as f32 - 100.0).powi(2))).sum(); + assert!((var.sqrt() - box_sigma(sigma)).abs() < 1e-3, "{sigma}: {} vs {}", var.sqrt(), box_sigma(sigma)); + } + } + + #[test] + fn box_sigma_stays_close_to_the_supported_maximum() { + // No image allocation is needed to exercise the largest supported box. + let actual = box_sigma(MAX_SIGMA); + assert!((actual - MAX_SIGMA).abs() <= 1.0, "{actual}"); + assert_eq!(box_sigma(f32::INFINITY), actual); + } + + #[test] + fn variance_close_to_sigma_squared() { + let mut imp = Image::::new(201, 1); + imp.set(100, 0, 1.0); + let sigma = 8.0; + let b = gaussian(&imp, sigma); + let var: f32 = b.data.iter().enumerate().map(|(i, v)| v * ((i as f32 - 100.0).powi(2))).sum(); + assert!((var.sqrt() - sigma).abs() / sigma < 0.1, "{}", var.sqrt()); + } + + #[test] + fn box_row_matches_the_clamped_window_sum_for_radii_past_the_row() { + for (w, r) in [(1usize, 1usize), (5, 1), (5, 4), (5, 5), (5, 9), (7, 3)] { + let mut row: Vec = (0..w).map(|i| (i * i + 1) as f32).collect(); + let want: Vec = (0..w as isize) + .map(|x| (-(r as isize)..=r as isize).map(|j| row[(x + j).clamp(0, w as isize - 1) as usize]).sum::() / (2 * r + 1) as f32) + .collect(); + box_row(&mut row, &mut Vec::new(), r); + for (a, b) in row.iter().zip(&want) { + assert!((a - b).abs() < 1e-3, "w {w} r {r}: {a} vs {b}"); + } + } + } +} diff --git a/crates/develop/src/raster/histogram.rs b/crates/develop/src/raster/histogram.rs new file mode 100644 index 0000000000..b18c559a61 --- /dev/null +++ b/crates/develop/src/raster/histogram.rs @@ -0,0 +1,268 @@ +//! Histograms of display-encoded images (what the Histogram panel shows). +//! +//! An HDR histogram ([`Histogram::of_hdr`]) keeps the same 256 bins: the first +//! `Histogram::hdr_from` cover SDR black to SDR white (sRGB-encoded, as an SDR histogram), the +//! rest cover the HDR range above SDR white in equal stops. + +use serde::Serialize; + +use super::Rgba8; + +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct Histogram { + pub r: Vec, + pub g: Vec, + pub b: Vec, + pub luma: Vec, + pub total: u32, + /// HDR histograms: the first bin above SDR white, and the stops above SDR white the last bin + /// reaches. `None` for SDR histograms (every bin is SDR). + #[serde(skip_serializing_if = "Option::is_none")] + pub hdr: Option, +} + +/// The HDR part of a [`Histogram`]: bins `from..256` cover `0..stops` stops above SDR white. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HdrBins { + pub from: usize, + pub stops: f32, +} + +impl HdrBins { + /// The bin of a linear value (1 = SDR white; `NaN` and negatives count as black). + pub fn bin(self, v: f32) -> usize { + let last = Histogram::BINS - 1; + // a split outside 2..=last would leave one side without bins (or underflow) + let from = self.from.clamp(2, last); + if v.is_nan() || v <= 0.0 { + return 0; + } + if v <= 1.0 { + let e = craft_color::linear_to_srgb(v); + return ((e * (from - 1) as f32 + 0.5) as usize).min(from - 1); + } + let stops = if self.stops.is_finite() { self.stops.max(1e-3) } else { 1e-3 }; + let t = (v.log2() / stops).clamp(0.0, 1.0); + (from + (t * (last - from) as f32 + 0.5) as usize).min(last) + } +} + +impl Histogram { + pub const BINS: usize = 256; + /// HDR histograms: the first bin above SDR white (SDR takes the left half). + pub const HDR_FROM: usize = Self::BINS / 2; + + fn empty(hdr: Option) -> Histogram { + Histogram { r: vec![0; 256], g: vec![0; 256], b: vec![0; 256], luma: vec![0; 256], total: 0, hdr } + } + + /// Histogram of linear RGB samples (1 = SDR white) reaching `stops` stops above SDR white. + /// `samples` are visited at most ~1 MP of them (evenly strided). + pub fn of_hdr(samples: &[[f32; 3]], stops: f32) -> Histogram { + let bins = HdrBins { from: Self::HDR_FROM, stops }; + let mut h = Self::empty(Some(bins)); + let step = (samples.len() / 1_000_000).max(1); + for c in samples.iter().step_by(step) { + h.r[bins.bin(c[0])] += 1; + h.g[bins.bin(c[1])] += 1; + h.b[bins.bin(c[2])] += 1; + h.luma[bins.bin(0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2])] += 1; + h.total += 1; + } + h + } + + /// HDR histogram of per-pixel bins already computed with `bins` (`[r, g, b, luma]` each), + /// visiting at most ~1 MP of them. + pub fn of_bins(px: impl ExactSizeIterator, bins: HdrBins) -> Histogram { + let mut h = Self::empty(Some(bins)); + let step = (px.len() / 1_000_000).max(1); + for [r, g, b, l] in px.step_by(step) { + h.r[r as usize] += 1; + h.g[g as usize] += 1; + h.b[b as usize] += 1; + h.luma[l as usize] += 1; + h.total += 1; + } + h + } + + /// The histogram as flat words (to cross a worker boundary): r, g, b, luma (256 each), the + /// total, then the first HDR bin (0: SDR) and the HDR stops as `f32` bits. + pub fn to_words(&self) -> Vec { + let mut w = Vec::with_capacity(4 * Self::BINS + 3); + for ch in [&self.r, &self.g, &self.b, &self.luma] { + w.extend(ch.iter().copied().chain(std::iter::repeat(0)).take(Self::BINS)); + } + w.push(self.total); + let (from, stops) = self.hdr.map_or((0, 0.0), |b| (b.from as u32, b.stops)); + w.extend([from, stops.to_bits()]); + w + } + + /// [`Histogram::to_words`] back; also takes the older layout without the HDR words. `None` + /// for anything malformed. + pub fn from_words(w: &[u32]) -> Option { + let n = Self::BINS; + if w.len() != 4 * n + 1 && w.len() != 4 * n + 3 { + return None; + } + let ch = |k: usize| w.get(k * n..(k + 1) * n).map(<[u32]>::to_vec); + let hdr = match (w.get(4 * n + 1), w.get(4 * n + 2)) { + (Some(&from), Some(&bits)) if from > 1 && (from as usize) < n => { + let stops = f32::from_bits(bits); + Some(HdrBins { from: from as usize, stops: if stops.is_finite() && stops > 0.0 { stops } else { 1.0 } }) + } + _ => None, + }; + Some(Histogram { r: ch(0)?, g: ch(1)?, b: ch(2)?, luma: ch(3)?, total: *w.get(4 * n)?, hdr }) + } + + /// Fraction of pixels above SDR white in any channel (0 for SDR histograms). + pub fn above_sdr(&self) -> f32 { + let Some(b) = self.hdr else { return 0.0 }; + if self.total == 0 { + return 0.0; + } + let over = |v: &[u32]| v.iter().skip(b.from).sum::(); + over(&self.r).max(over(&self.g)).max(over(&self.b)) as f32 / self.total as f32 + } + + pub fn of_srgb8(img: &Rgba8) -> Histogram { + let mut h = Self::empty(None); + // Sample at most ~1 MP for speed. + let step = ((img.len() as f64 / 1_000_000.0).sqrt().ceil() as usize).max(1); + for y in (0..img.height).step_by(step) { + for x in (0..img.width).step_by(step) { + let p = img.get(x, y); + h.r[p[0] as usize] += 1; + h.g[p[1] as usize] += 1; + h.b[p[2] as usize] += 1; + let l = (p[0] as u32 * 54 + p[1] as u32 * 183 + p[2] as u32 * 19) >> 8; + h.luma[l.min(255) as usize] += 1; + h.total += 1; + } + } + h + } + + /// Fraction of pixels clipped at black / white in any channel (approximate: per channel max). + pub fn clipping(&self) -> (f32, f32) { + if self.total == 0 { + return (0.0, 0.0); + } + let t = self.total as f32; + let lo = self.r[0].max(self.g[0]).max(self.b[0]) as f32 / t; + let hi = self.r[255].max(self.g[255]).max(self.b[255]) as f32 / t; + (lo, hi) + } + + /// Mean luma in 0..1. + pub fn mean_luma(&self) -> f32 { + if self.total == 0 { + return 0.0; + } + self.luma.iter().enumerate().map(|(i, &c)| i as f32 * c as f32).sum::() / (255.0 * self.total as f32) + } + + /// Luma value (0..1) below which `q` of the pixels fall. + pub fn percentile(&self, q: f32) -> f32 { + if self.total == 0 { + return 0.0; + } + let target = ((q.clamp(0.0, 1.0) * self.total as f32) as u32).max(1); + let mut acc = 0; + for (i, &c) in self.luma.iter().enumerate() { + acc += c; + if acc >= target { + return i as f32 / 255.0; + } + } + 1.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counts_and_stats() { + let img = Rgba8::from_fn(10, 10, |x, _| if x < 5 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + let h = Histogram::of_srgb8(&img); + assert_eq!(h.total, 100); + assert_eq!(h.r[0], 50); + assert_eq!(h.luma[255], 50); + let (lo, hi) = h.clipping(); + assert!((lo - 0.5).abs() < 1e-6 && (hi - 0.5).abs() < 1e-6); + assert!((h.mean_luma() - 0.5).abs() < 1e-3); + assert_eq!(h.percentile(0.25), 0.0); + assert_eq!(h.percentile(0.75), 1.0); + assert_eq!(h.above_sdr(), 0.0); + } + + #[test] + fn percentile_zero_skips_empty_bins() { + let img = Rgba8::from_fn(4, 4, |_, _| [200, 200, 200, 255]); + let h = Histogram::of_srgb8(&img); + // every pixel is in one bin, so every percentile is that bin's luma, never black + assert!(h.percentile(1.0) > 0.0); + assert_eq!(h.percentile(0.0), h.percentile(1.0)); + assert_eq!(h.percentile(0.01), h.percentile(1.0)); + } + + #[test] + fn percentile_of_empty_histogram_is_zero() { + let h = Histogram::of_hdr(&[], 4.0); + assert_eq!(h.percentile(0.0), 0.0); + assert_eq!(h.percentile(0.5), 0.0); + } + + #[test] + fn hdr_bins_split_sdr_and_stops() { + let px = [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [4.0, 4.0, 4.0], [16.0, 16.0, 16.0], [f32::NAN, -1.0, f32::INFINITY]]; + let h = Histogram::of_hdr(&px, 4.0); + let b = h.hdr.unwrap(); + assert_eq!(h.total, 5); + assert_eq!(b.bin(1.0), b.from - 1, "SDR white is the last SDR bin"); + assert_eq!(b.bin(16.0), 255); + assert_eq!(b.bin(1e9), 255); + let two = b.bin(4.0); + assert!(two > b.from && two < 255, "{two}"); + assert_eq!(h.r[0], 2, "black and NaN"); + assert_eq!(h.b[255], 2, "16 and +inf"); + assert!((h.above_sdr() - 0.6).abs() < 1e-6, "{}", h.above_sdr()); + assert_eq!(Histogram::of_hdr(&[], 4.0).above_sdr(), 0.0); + } + + #[test] + fn words_round_trip_and_reject_garbage() { + let img = Rgba8::from_fn(8, 8, |x, y| [(x * 30) as u8, (y * 30) as u8, 9, 255]); + let sdr = Histogram::of_srgb8(&img); + assert_eq!(Histogram::from_words(&sdr.to_words()), Some(sdr.clone())); + let hdr = Histogram::of_hdr(&[[0.5, 2.0, 9.0]], 4.0); + assert_eq!(Histogram::from_words(&hdr.to_words()), Some(hdr)); + // the older layout (no HDR words) is an SDR histogram + assert_eq!(Histogram::from_words(&sdr.to_words()[..1025]), Some(sdr.clone())); + assert_eq!(Histogram::from_words(&[1, 2, 3]), None); + let mut bad = sdr.to_words(); + bad[1025] = 9999; // first HDR bin out of range: SDR + bad[1026] = f32::NAN.to_bits(); + assert_eq!(Histogram::from_words(&bad).unwrap().hdr, None); + bad[1025] = 100; // NaN stops fall back to something drawable + assert_eq!(Histogram::from_words(&bad).unwrap().hdr.unwrap().stops, 1.0); + } + /// A hand-built split outside the bins (any `from`, any `stops`) never panics and stays in range. + #[test] + fn hdr_bins_with_any_split_stay_in_range() { + for from in [0, 1, 2, 128, 255, 256, usize::MAX] { + for stops in [0.0, 3.0, f32::NAN, f32::INFINITY] { + let b = HdrBins { from, stops }; + for v in [f32::NAN, -1.0, 0.0, 0.5, 1.0, 2.0, 1e9] { + assert!(b.bin(v) < Histogram::BINS, "{from} {stops} {v}"); + } + } + } + } +} diff --git a/crates/develop/src/raster/mod.rs b/crates/develop/src/raster/mod.rs new file mode 100644 index 0000000000..dbbf9d55d9 --- /dev/null +++ b/crates/develop/src/raster/mod.rs @@ -0,0 +1,412 @@ +//! Image buffers and basic raster operations for LightCraft. +//! +//! - [`Image`]: interleaved, row-major pixels (`Rgb32f = Image<[f32; 3]>`, `Rgba8 = Image<[u8; 4]>`, +//! `Plane = Image`). +//! - Resampling ([`resample`]): separable Lanczos-3 / Mitchell / box, rayon-parallel; point sampling for warps +//! ([`sample`]: Lanczos-3 held to its neighbours' range). +//! - Blur ([`blur`]): separable Gaussian via repeated box filters (O(1) per pixel in the radius). +//! - Morphology ([`morph`]): square min / max filters (van Herk / Gil-Werman, O(1) per pixel in the radius). +//! - [`Histogram`] of display-encoded RGB + luminance. + +pub mod blur; +pub mod histogram; +pub mod morph; +pub mod resample; +pub mod sample; + +pub use histogram::{HdrBins, Histogram}; + +/// Run `f` over row chunks, in parallel on native targets. +pub fn par_rows(data: &mut [T], row_len: usize, f: impl Fn(usize, &mut [T]) + Sync + Send) { + if row_len == 0 { + return; + } + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + data.par_chunks_mut(row_len).enumerate().for_each(|(y, row)| f(y, row)); + } + #[cfg(target_arch = "wasm32")] + { + data.chunks_mut(row_len).enumerate().for_each(|(y, row)| f(y, row)); + } +} + +/// Run `a` and `b` potentially in parallel (sequentially on wasm32). For +/// independent passes that each scale poorly on their own (small images, short rows). +pub fn par_join(a: impl FnOnce() -> A + Send, b: impl FnOnce() -> B + Send) -> (A, B) { + #[cfg(not(target_arch = "wasm32"))] + { + rayon::join(a, b) + } + #[cfg(target_arch = "wasm32")] + { + (a(), b()) + } +} + +/// Interleaved row-major image. +#[derive(Clone, Debug, PartialEq)] +pub struct Image { + pub width: usize, + pub height: usize, + pub data: Vec, +} + +pub type Rgb32f = Image<[f32; 3]>; +pub type Rgba8 = Image<[u8; 4]>; +pub type Plane = Image; + +impl Image { + pub fn new(width: usize, height: usize) -> Self { + Self { width, height, data: vec![T::default(); width * height] } + } + pub fn filled(width: usize, height: usize, v: T) -> Self { + Self { width, height, data: vec![v; width * height] } + } + pub fn from_fn(width: usize, height: usize, f: impl Fn(usize, usize) -> T) -> Self { + let mut data = Vec::with_capacity(width * height); + for y in 0..height { + for x in 0..width { + data.push(f(x, y)); + } + } + Self { width, height, data } + } + #[inline] + pub fn get(&self, x: usize, y: usize) -> T { + self.data[y * self.width + x] + } + /// Clamped access (edge extension). + #[inline] + pub fn get_clamped(&self, x: isize, y: isize) -> T { + let x = x.clamp(0, self.width as isize - 1) as usize; + let y = y.clamp(0, self.height as isize - 1) as usize; + self.data[y * self.width + x] + } + #[inline] + pub fn set(&mut self, x: usize, y: usize, v: T) { + self.data[y * self.width + x] = v; + } + pub fn row(&self, y: usize) -> &[T] { + &self.data[y * self.width..(y + 1) * self.width] + } + pub fn row_mut(&mut self, y: usize) -> &mut [T] { + &mut self.data[y * self.width..(y + 1) * self.width] + } + pub fn len(&self) -> usize { + self.data.len() + } + pub fn is_empty(&self) -> bool { + self.data.is_empty() + } + /// The image mirrored about its main diagonal (`width` and `height` swap; row-parallel). A + /// buffer shorter than its size reads as `T::default()` where it runs out. + pub fn transpose(&self) -> Self + where + T: Send + Sync, + { + let (w, h) = (self.width, self.height); + let mut t = Image::::new(h, w); + par_rows(&mut t.data, h, |x, row| { + for (y, v) in row.iter_mut().enumerate() { + *v = self.data.get(y * w + x).copied().unwrap_or_default(); + } + }); + t + } + /// [`Self::map`] into the same buffer (no second image in memory). + pub fn map_in_place(&mut self, f: impl Fn(T) -> T + Sync + Send) + where + T: Send, + { + let w = self.width; + par_rows(&mut self.data, w, |_, row| { + for p in row.iter_mut() { + *p = f(*p); + } + }); + } + + pub fn map(&self, f: impl Fn(T) -> U + Sync + Send) -> Image + where + T: Sync, + { + let mut out = Image::::new(self.width, self.height); + let w = self.width; + par_rows(&mut out.data, w, |y, row| { + let src = &self.data[y * w..(y + 1) * w]; + for (o, s) in row.iter_mut().zip(src) { + *o = f(*s); + } + }); + out + } + /// Per-pixel combination of two images of the same size (row-parallel). + pub fn zip_map(&self, other: &Image, f: impl Fn(T, U) -> V + Sync + Send) -> Image + where + T: Sync, + { + assert_eq!((self.width, self.height), (other.width, other.height), "zip_map: size mismatch"); + let mut out = Image::::new(self.width, self.height); + let w = self.width; + par_rows(&mut out.data, w, |y, row| { + let (a, b) = (&self.data[y * w..(y + 1) * w], &other.data[y * w..(y + 1) * w]); + for ((o, s), t) in row.iter_mut().zip(a).zip(b) { + *o = f(*s, *t); + } + }); + out + } + /// Crop to `[x0, x0+w) × [y0, y0+h)` (clamped to the image). + pub fn crop(&self, x0: usize, y0: usize, w: usize, h: usize) -> Self { + let x0 = x0.min(self.width); + let y0 = y0.min(self.height); + let w = w.min(self.width - x0); + let h = h.min(self.height - y0); + let mut data = Vec::with_capacity(w * h); + for y in y0..y0 + h { + data.extend_from_slice(&self.data[y * self.width + x0..y * self.width + x0 + w]); + } + Self { width: w, height: h, data } + } + /// [`Self::crop`] in place: rows move to the front of the same buffer (no second image). + pub fn into_crop(mut self, x0: usize, y0: usize, w: usize, h: usize) -> Self { + let x0 = x0.min(self.width); + let y0 = y0.min(self.height); + let w = w.min(self.width - x0); + let h = h.min(self.height - y0); + for (i, y) in (y0..y0 + h).enumerate() { + let src = y * self.width + x0; + self.data.copy_within(src..src + w, i * w); + } + self.data.truncate(w * h); + Self { width: w, height: h, data: self.data } + } + /// Rotate 90° clockwise. + pub fn rotate_cw(&self) -> Self { + let (w, h) = (self.width, self.height); + Image::from_fn(h, w, |x, y| self.get(y, h - 1 - x)) + } + pub fn rotate_180(&self) -> Self { + let mut d = self.data.clone(); + d.reverse(); + Self { width: self.width, height: self.height, data: d } + } + pub fn flip_h(&self) -> Self { + let mut out = self.clone(); + for y in 0..self.height { + out.row_mut(y).reverse(); + } + out + } + /// Apply an EXIF orientation (stored → displayed). + /// [`Self::oriented`] without a copy when `o` is the identity. + pub fn into_oriented(self, o: craft_geom::Orientation) -> Self { + if o == craft_geom::Orientation::Normal { self } else { self.oriented(o) } + } + + pub fn oriented(&self, o: craft_geom::Orientation) -> Self { + let (flip, turns) = o.to_parts(); + let mut img = if flip { self.flip_h() } else { self.clone() }; + match turns { + 1 => img = img.rotate_cw(), + 2 => img = img.rotate_180(), + 3 => img = img.rotate_180().rotate_cw(), + _ => {} + } + img + } +} + +// Keep the sqrt-spaced 14-bit lookup from LightCraft's raster conversion. The uniform +// craft-color byte lookup makes different quantization choices for some near-black inputs. +#[inline] +fn encode_raster_srgb8(v: f32) -> u8 { + const LAST: usize = (1 << 14) - 1; + static LUT: std::sync::OnceLock<[u8; LAST + 1]> = std::sync::OnceLock::new(); + let lut = LUT.get_or_init(|| { + std::array::from_fn(|i| { + let t = i as f32 / LAST as f32; + (craft_color::linear_to_srgb(t * t) * 255.0 + 0.5) as u8 + }) + }); + let i = (v.clamp(0.0, 1.0).sqrt() * LAST as f32 + 0.5) as usize; + lut[i.min(LAST)] +} + +impl Rgb32f { + /// Bilinear sample at continuous pixel coordinates (pixel centres at +0.5). + #[inline] + pub fn sample_bilinear(&self, x: f32, y: f32) -> [f32; 3] { + // a pixel past the edge reads the edge pixel, so a coordinate held a pixel outside gives + // the same sample; an infinite one (a crop of no size's inverse mapping) then reads the + // edge too, instead of a NaN weight and a neighbour index past isize::MAX + let fx = x.clamp(-1.0, self.width as f32 + 1.0) - 0.5; + let fy = y.clamp(-1.0, self.height as f32 + 1.0) - 0.5; + let x0 = fx.floor(); + let y0 = fy.floor(); + let tx = fx - x0; + let ty = fy - y0; + let (x0, y0) = (x0 as isize, y0 as isize); + let a = self.get_clamped(x0, y0); + let b = self.get_clamped(x0 + 1, y0); + let c = self.get_clamped(x0, y0 + 1); + let d = self.get_clamped(x0 + 1, y0 + 1); + std::array::from_fn(|i| { + let top = a[i] + (b[i] - a[i]) * tx; + let bot = c[i] + (d[i] - c[i]) * tx; + top + (bot - top) * ty + }) + } + + pub fn luminance(&self) -> Plane { + self.map(crate::colorops::luminance_2020) + } + + /// Encode to 8-bit sRGB from linear sRGB values (no gamut conversion). + pub fn to_srgb8(&self) -> Rgba8 { + self.map(|p| [encode_raster_srgb8(p[0]), encode_raster_srgb8(p[1]), encode_raster_srgb8(p[2]), 255]) + } +} + +impl Rgba8 { + /// Raw bytes (RGBA, row-major). + pub fn as_bytes(&self) -> Vec { + self.data.iter().flat_map(|p| *p).collect() + } + pub fn from_bytes(width: usize, height: usize, bytes: &[u8]) -> Option { + if bytes.len() != width * height * 4 { + return None; + } + Some(Self { width, height, data: bytes.as_chunks::<4>().0.iter().map(|c| [c[0], c[1], c[2], c[3]]).collect() }) + } + + /// Build an image from exactly `width * height` RGBA pixels. + /// + /// This copies each pixel once, straight into the image's own buffer, so a caller that already + /// holds a pixel array (an egui `ColorImage`, say) does not need a second full byte vector. + /// `None` for a zero or overflowing size, or a pixel count that is not exactly `width * height`. + pub fn from_pixels(width: usize, height: usize, pixels: impl IntoIterator) -> Option { + if width == 0 || height == 0 { + return None; + } + let expected = width.checked_mul(height)?; + let mut data = Vec::new(); + data.try_reserve_exact(expected).ok()?; + for (i, pixel) in pixels.into_iter().enumerate() { + if i == expected { + return None; + } + data.push(pixel); + } + (data.len() == expected).then_some(Self { width, height, data }) + } + /// Linear Rec.709/sRGB primaries float image from 8-bit sRGB. + pub fn to_linear(&self) -> Rgb32f { + let lut = craft_color::srgb_u8_to_linear_table(); + self.map(|p| [lut[p[0] as usize], lut[p[1] as usize], lut[p[2] as usize]]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_geom::Orientation; + + /// A sample at an infinite coordinate (the inverse mapping of a crop of no size) cast to + /// isize::MAX, and its right / lower neighbour overflowed (a panic where overflow is checked): + /// the neighbours saturate and the edge pixel comes back. + #[test] + fn bilinear_samples_at_infinite_coordinates_read_the_edge() { + let img = Rgb32f::from_fn(3, 2, |x, y| [x as f32, y as f32, 1.0]); + assert_eq!(img.sample_bilinear(f32::INFINITY, f32::INFINITY), [2.0, 1.0, 1.0]); + assert_eq!(img.sample_bilinear(f32::MAX, 0.0), [2.0, 0.0, 1.0]); + assert_eq!(img.sample_bilinear(f32::NEG_INFINITY, f32::NEG_INFINITY), [0.0, 0.0, 1.0]); + assert_eq!(img.sample_bilinear(1.5, 0.5), [1.0, 0.0, 1.0], "an ordinary sample is as before"); + } + + #[test] + fn transpose_swaps_the_axes() { + let p = Plane::from_fn(5, 3, |x, y| (y * 10 + x) as f32); + let t = p.transpose(); + assert_eq!((t.width, t.height), (3, 5)); + assert!((0..3).all(|y| (0..5).all(|x| t.get(y, x) == p.get(x, y)))); + assert_eq!(t.transpose(), p); + // a buffer shorter than its size reads as zero where it runs out, never a panic + let short = Plane { width: 3, height: 2, data: vec![1.0; 4] }; + assert_eq!(short.transpose().data, [1.0, 1.0, 1.0, 0.0, 1.0, 0.0]); + } + + #[test] + fn crop_and_rotate() { + let img = Image::::from_fn(4, 3, |x, y| (y * 10 + x) as u32); + let c = img.crop(1, 1, 2, 2); + assert_eq!(c.data, vec![11, 12, 21, 22]); + // the in-place variants equal the copying ones + for (x, y, w, h) in [(1, 1, 2, 2), (0, 0, 4, 3), (2, 0, 9, 9), (0, 2, 4, 1), (3, 2, 1, 1)] { + assert_eq!(img.clone().into_crop(x, y, w, h), img.crop(x, y, w, h)); + } + for v in 1..=8 { + let o = Orientation::from_exif(v); + assert_eq!(img.clone().into_oriented(o), img.oriented(o)); + } + let mut m = img.clone(); + m.map_in_place(|p| p * 2 + 1); + assert_eq!(m, img.map(|p| p * 2 + 1)); + let r = img.rotate_cw(); + assert_eq!((r.width, r.height), (3, 4)); + // top-left of rotated = bottom-left of original + assert_eq!(r.get(0, 0), 20); + assert_eq!(r.get(2, 0), 0); + assert_eq!(img.rotate_cw().rotate_cw().rotate_cw().rotate_cw(), img); + assert_eq!(img.rotate_cw().rotate_cw(), img.rotate_180()); + } + + #[test] + fn orientation_matches_geom_mapping() { + let img = Image::::from_fn(5, 3, |x, y| (y * 10 + x) as u32); + for v in 1..=8 { + let o = Orientation::from_exif(v); + let out = img.oriented(o); + for (sx, sy) in [(0usize, 0usize), (4, 0), (2, 1), (0, 2)] { + let (dx, dy) = o.map(sx as f64 + 0.5, sy as f64 + 0.5, 5.0, 3.0); + assert_eq!(out.get(dx as usize, dy as usize), img.get(sx, sy), "orientation {v}"); + } + } + } + + #[test] + fn bilinear_at_centres_is_exact() { + let img = Rgb32f::from_fn(3, 3, |x, y| [x as f32, y as f32, 1.0]); + assert_eq!(img.sample_bilinear(1.5, 2.5), [1.0, 2.0, 1.0]); + let m = img.sample_bilinear(1.0, 1.5); + assert!((m[0] - 0.5).abs() < 1e-6); + } + + #[test] + fn raster_srgb8_keeps_lightcraft_float_quantization() { + // Referenced to LightCraft's sqrt-domain conversion, not the 8-bit decode grid. + let samples = [[0.00013, 0.00016, 0.0005], [0.003_130_8, 0.18, 0.5], [-0.1, 1.0, 1.1]]; + let img = Rgb32f::from_fn(samples.len(), 1, |x, _| samples[x]); + assert_eq!(img.to_srgb8().data, [[0, 1, 2, 255], [10, 118, 188, 255], [0, 255, 255, 255]]); + } + + #[test] + fn srgb8_roundtrip() { + let img = Rgba8::from_fn(16, 16, |x, y| [(x * 16) as u8, (y * 16) as u8, 7, 255]); + assert_eq!(img.to_linear().to_srgb8(), img); + assert_eq!(Rgba8::from_bytes(16, 16, &img.as_bytes()).unwrap(), img); + } + + #[test] + fn from_pixels_requires_exactly_the_stated_pixels() { + let img = Rgba8::from_fn(4, 3, |x, y| [x as u8, y as u8, 9, 255]); + let rebuilt = Rgba8::from_pixels(4, 3, img.as_bytes().as_chunks::<4>().0.iter().map(|p| [p[0], p[1], p[2], p[3]])).unwrap(); + assert_eq!(rebuilt, img); + assert!(Rgba8::from_pixels(4, 3, vec![[0, 0, 0, 0]; 11]).is_none(), "too few pixels"); + assert!(Rgba8::from_pixels(4, 3, vec![[0, 0, 0, 0]; 13]).is_none(), "too many pixels"); + assert!(Rgba8::from_pixels(0, 3, std::iter::empty()).is_none()); + assert!(Rgba8::from_pixels(usize::MAX, 2, std::iter::empty()).is_none()); + } +} diff --git a/crates/develop/src/raster/morph.rs b/crates/develop/src/raster/morph.rs new file mode 100644 index 0000000000..8da38d2ca5 --- /dev/null +++ b/crates/develop/src/raster/morph.rs @@ -0,0 +1,187 @@ +//! Grey-scale morphology: square min (erosion) and max (dilation) filters. +//! +//! Separable van Herk / Gil-Werman filters: each 1-D pass splits the (edge-extended) line into +//! blocks of the window's width and keeps a running min from the left and from the right within +//! each block; any window then spans at most two blocks, so its min is the min of one suffix and +//! one prefix value. That is three comparisons per pixel per pass, whatever the radius. +//! +//! Edges are clamped (the edge pixel repeats), which for a min or max is the same as clipping the +//! window to the image. NaNs are skipped like [`f32::min`] does: a window yields NaN only when every +//! value in it is NaN. + +use super::Plane; + +/// Square min filter (erosion) of radius `r`: each output pixel is the minimum over the +/// `(2r+1)²` window around it, clipped to the image. `r == 0` returns a copy. +pub fn min_filter(p: &Plane, r: usize) -> Plane { + filter(p, r, f32::min) +} + +/// Square max filter (dilation) of radius `r` (see [`min_filter`]). +pub fn max_filter(p: &Plane, r: usize) -> Plane { + filter(p, r, f32::max) +} + +fn filter(p: &Plane, r: usize, pick: fn(f32, f32) -> f32) -> Plane { + let (w, h) = (p.width, p.height); + if r == 0 || p.data.is_empty() || p.data.len() != w.saturating_mul(h) { + return p.clone(); + } + let mut out = p.clone(); + rows(&mut out, r, pick); + let mut t = out.transpose(); + rows(&mut t, r, pick); + t.transpose() +} + +/// [`line`] over every row of `p`, in place (row-parallel, one scratch per worker). +fn rows(p: &mut Plane, r: usize, pick: fn(f32, f32) -> f32) { + let w = p.width; + if w == 0 { + return; + } + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + p.data.par_chunks_mut(w).for_each_init(Scratch::default, |s, row| line(row, r, pick, s)); + } + #[cfg(target_arch = "wasm32")] + { + let mut s = Scratch::default(); + p.data.chunks_mut(w).for_each(|row| line(row, r, pick, &mut s)); + } +} + +#[derive(Default)] +struct Scratch { + ext: Vec, + pre: Vec, + suf: Vec, +} + +/// One 1-D pass over `row`, in place. +fn line(row: &mut [f32], r: usize, pick: fn(f32, f32) -> f32, s: &mut Scratch) { + let n = row.len(); + if n == 0 { + return; + } + // a radius past the line covers it all; capping keeps the scratch bounded + let r = r.min(n - 1); + if r == 0 { + return; + } + let k = 2 * r + 1; + // the line with `r` copies of each edge pixel on either side + s.ext.clear(); + s.ext.extend(std::iter::repeat_n(row[0], r)); + s.ext.extend_from_slice(row); + s.ext.extend(std::iter::repeat_n(row[n - 1], r)); + let m = s.ext.len(); + s.pre.clear(); + s.pre.resize(m, 0.0); + s.suf.clear(); + s.suf.resize(m, 0.0); + for (i, &v) in s.ext.iter().enumerate() { + s.pre[i] = if i % k == 0 { v } else { pick(s.pre[i - 1], v) }; + } + for i in (0..m).rev() { + let v = s.ext[i]; + s.suf[i] = if i + 1 == m || (i + 1) % k == 0 { v } else { pick(s.suf[i + 1], v) }; + } + // window [x, x + 2r] of `ext` is output x + for (x, o) in row.iter_mut().enumerate() { + *o = pick(s.suf[x], s.pre[x + 2 * r]); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The definition: min (or max) over the clipped window. + fn naive(p: &Plane, r: usize, max: bool) -> Plane { + let (w, h) = (p.width, p.height); + let pick = |a: f32, b: f32| if max { a.max(b) } else { a.min(b) }; + Plane::from_fn(w, h, |x, y| { + let mut m = p.get(x, y); + for yy in y.saturating_sub(r)..=(y + r).min(h - 1) { + for xx in x.saturating_sub(r)..=(x + r).min(w - 1) { + m = pick(m, p.get(xx, yy)); + } + } + m + }) + } + + /// splitmix64-ish deterministic noise. + fn noise(w: usize, h: usize, seed: u64) -> Plane { + Plane::from_fn(w, h, |x, y| { + let mut z = seed.wrapping_add((y * w + x) as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z ^= z >> 31; + (z % 10_000) as f32 / 10_000.0 + }) + } + + #[test] + fn matches_the_naive_filter() { + for (w, h) in [(1, 1), (1, 9), (9, 1), (7, 5), (31, 17), (64, 40)] { + for r in [1, 2, 3, 5, 8, 20, 100] { + let p = noise(w, h, (w * 131 + h * 7 + r) as u64); + assert_eq!(min_filter(&p, r), naive(&p, r, false), "min {w}x{h} r={r}"); + assert_eq!(max_filter(&p, r), naive(&p, r, true), "max {w}x{h} r={r}"); + } + } + } + + #[test] + fn radius_zero_and_empty_are_copies() { + let p = noise(6, 4, 1); + assert_eq!(min_filter(&p, 0), p); + let e = Plane::new(0, 0); + assert_eq!(min_filter(&e, 3), e); + let e = Plane::new(5, 0); + assert_eq!(max_filter(&e, 3), e); + } + + #[test] + fn radius_past_the_image_is_the_global_extreme() { + let p = noise(13, 7, 3); + let lo = p.data.iter().copied().fold(f32::INFINITY, f32::min); + let hi = p.data.iter().copied().fold(f32::NEG_INFINITY, f32::max); + assert!(min_filter(&p, 1_000_000).data.iter().all(|&v| v == lo)); + assert!(max_filter(&p, usize::MAX).data.iter().all(|&v| v == hi)); + } + + #[test] + fn a_dark_dot_grows_to_the_window() { + let mut p = Plane::filled(11, 11, 1.0); + p.set(5, 5, 0.0); + let q = min_filter(&p, 2); + for y in 0..11 { + for x in 0..11 { + let inside = (3..=7).contains(&x) && (3..=7).contains(&y); + assert_eq!(q.get(x, y), if inside { 0.0 } else { 1.0 }, "({x}, {y})"); + } + } + } + + #[test] + fn nans_are_skipped() { + let mut p = Plane::filled(5, 5, 0.5); + p.set(2, 2, f32::NAN); + p.set(0, 0, 0.25); + let q = min_filter(&p, 1); + assert_eq!(q.get(2, 2), 0.5); + assert_eq!(q.get(1, 1), 0.25); + let all = Plane::filled(3, 3, f32::NAN); + assert!(min_filter(&all, 1).data.iter().all(|v| v.is_nan())); + } + + #[test] + fn a_short_buffer_is_returned_unchanged() { + // a plane whose data doesn't fill its size must not panic + let p = Plane { width: 4, height: 4, data: vec![1.0; 3] }; + assert_eq!(min_filter(&p, 2), p); + } +} diff --git a/crates/develop/src/raster/resample.rs b/crates/develop/src/raster/resample.rs new file mode 100644 index 0000000000..8709e2b152 --- /dev/null +++ b/crates/develop/src/raster/resample.rs @@ -0,0 +1,239 @@ +//! Separable resampling with precomputed filter weights. + +use super::{Image, par_rows}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Filter { + Box, + Bilinear, + Mitchell, + Lanczos3, +} + +impl Filter { + fn support(self) -> f32 { + match self { + Filter::Box => 0.5, + Filter::Bilinear => 1.0, + Filter::Mitchell => 2.0, + Filter::Lanczos3 => 3.0, + } + } + /// The filter's weight at distance `x` (pixels of the source). + pub(crate) fn eval(self, x: f32) -> f32 { + let x = x.abs(); + match self { + Filter::Box => { + if x <= 0.5 { + 1.0 + } else { + 0.0 + } + } + Filter::Bilinear => (1.0 - x).max(0.0), + Filter::Mitchell => { + let (b, c) = (1.0 / 3.0, 1.0 / 3.0); + if x < 1.0 { + ((12.0 - 9.0 * b - 6.0 * c) * x * x * x + (-18.0 + 12.0 * b + 6.0 * c) * x * x + (6.0 - 2.0 * b)) / 6.0 + } else if x < 2.0 { + ((-b - 6.0 * c) * x * x * x + (6.0 * b + 30.0 * c) * x * x + (-12.0 * b - 48.0 * c) * x + (8.0 * b + 24.0 * c)) / 6.0 + } else { + 0.0 + } + } + Filter::Lanczos3 => { + if x < 1e-6 { + 1.0 + } else if x < 3.0 { + let px = std::f32::consts::PI * x; + 3.0 * px.sin() * (px / 3.0).sin() / (px * px) + } else { + 0.0 + } + } + } + } +} + +/// Contributions for each output coordinate: (first source index, weights) — the exact taps +/// [`resize`] uses (GPU kernels upload these tables). +pub fn weights(src: usize, dst: usize, filter: Filter) -> Vec<(usize, Vec)> { + let scale = src as f32 / dst as f32; + let fscale = scale.max(1.0); + let support = filter.support() * fscale; + (0..dst) + .map(|i| { + let center = (i as f32 + 0.5) * scale; + let lo = ((center - support).floor() as isize).max(0) as usize; + let hi = ((center + support).ceil() as usize).min(src); + let mut w: Vec = (lo..hi).map(|j| filter.eval((j as f32 + 0.5 - center) / fscale)).collect(); + let sum: f32 = w.iter().sum(); + if sum.abs() > 1e-8 { + w.iter_mut().for_each(|v| *v /= sum); + } else if !w.is_empty() { + let n = w.len() as f32; + w.iter_mut().for_each(|v| *v = 1.0 / n); + } + (lo, w) + }) + .collect() +} + +/// Pixel types that can be resampled (linear combination). +pub trait Pixel: Copy + Default + Send + Sync { + fn zero() -> Self; + fn madd(self, o: Self, w: f32) -> Self; +} + +impl Pixel for f32 { + fn zero() -> Self { + 0.0 + } + #[inline] + fn madd(self, o: Self, w: f32) -> Self { + self + o * w + } +} + +impl Pixel for [f32; 3] { + fn zero() -> Self { + [0.0; 3] + } + #[inline] + fn madd(self, o: Self, w: f32) -> Self { + [self[0] + o[0] * w, self[1] + o[1] * w, self[2] + o[2] * w] + } +} + +impl Pixel for [f32; 4] { + fn zero() -> Self { + [0.0; 4] + } + #[inline] + fn madd(self, o: Self, w: f32) -> Self { + [self[0] + o[0] * w, self[1] + o[1] * w, self[2] + o[2] * w, self[3] + o[3] * w] + } +} + +/// Resize to `w × h` (separable; horizontal pass then vertical pass, or the other way round when +/// that intermediate would be far larger: widening a tall, narrow strip kept every source row at +/// the new width, gigabytes from a small source). +pub fn resize(img: &Image, w: usize, h: usize, filter: Filter) -> Image { + let (w, h) = (w.max(1), h.max(1)); + if img.width == w && img.height == h { + return img.clone(); + } + if w.saturating_mul(img.height) > img.width.saturating_mul(h).saturating_mul(4) { + return horizontal(&vertical(img, h, filter), w, filter); + } + vertical(&horizontal(img, w, filter), h, filter) +} + +/// Each row resampled to `w` wide. +fn horizontal(img: &Image, w: usize, filter: Filter) -> Image { + let wx = weights(img.width, w, filter); + let mut tmp = Image::::new(w, img.height); + par_rows(&mut tmp.data, w, |y, row| { + let src = img.row(y); + for (x, o) in row.iter_mut().enumerate() { + let (lo, ws) = &wx[x]; + let mut acc = T::zero(); + for (k, wt) in ws.iter().enumerate() { + acc = acc.madd(src[lo + k], *wt); + } + *o = acc; + } + }); + tmp +} + +/// Each column resampled to `h` tall. +fn vertical(img: &Image, h: usize, filter: Filter) -> Image { + let w = img.width; + let wy = weights(img.height, h, filter); + let mut out = Image::::new(w, h); + par_rows(&mut out.data, w, |y, row| { + let (lo, ws) = &wy[y]; + for (k, wt) in ws.iter().enumerate() { + let src = img.row(lo + k); + for (o, s) in row.iter_mut().zip(src) { + *o = o.madd(*s, *wt); + } + } + }); + out +} + +/// Fit within `max_w × max_h` preserving aspect (never upscales). +pub fn fit(img: &Image, max_w: usize, max_h: usize, filter: Filter) -> Image { + let s = (max_w as f64 / img.width as f64).min(max_h as f64 / img.height as f64).min(1.0); + let w = ((img.width as f64 * s).round() as usize).max(1); + let h = ((img.height as f64 * s).round() as usize).max(1); + resize(img, w, h, filter) +} + +/// 2× box downsample (pyramid level). +pub fn half(img: &Image) -> Image { + let w = img.width.div_ceil(2).max(1); + let h = img.height.div_ceil(2).max(1); + let mut out = Image::::new(w, h); + par_rows(&mut out.data, w, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let (sx, sy) = (2 * x as isize, 2 * y as isize); + *o = T::zero() + .madd(img.get_clamped(sx, sy), 0.25) + .madd(img.get_clamped(sx + 1, sy), 0.25) + .madd(img.get_clamped(sx, sy + 1), 0.25) + .madd(img.get_clamped(sx + 1, sy + 1), 0.25); + } + }); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn widening_a_tall_strip_resamples_its_columns_first() { + // 1 × 400 000 to 4000 × 8: horizontal-first kept 400 000 rows of 4000 (25 GB of RGBA f32) + let mut strip = Image::<[f32; 4]>::new(1, 400_000); + strip.data.iter_mut().for_each(|p| *p = [0.25, 0.5, 0.75, 1.0]); + let out = resize(&strip, 4000, 8, Filter::Mitchell); + assert_eq!((out.width, out.height), (4000, 8)); + assert!(out.data.iter().all(|p| (p[1] - 0.5).abs() < 1e-3), "a flat strip stays flat"); + } + + #[test] + fn constant_image_stays_constant() { + let img = Image::::filled(37, 21, 0.42); + for f in [Filter::Box, Filter::Bilinear, Filter::Mitchell, Filter::Lanczos3] { + for (w, h) in [(10, 7), (80, 40), (37, 21), (1, 1)] { + let r = resize(&img, w, h, f); + assert!(r.data.iter().all(|v| (v - 0.42).abs() < 1e-5), "{f:?} {w}x{h}"); + } + } + } + + #[test] + fn downscale_preserves_mean() { + let img = Image::::from_fn(64, 64, |x, y| ((x * 7 + y * 3) % 11) as f32 / 10.0); + let mean = img.data.iter().sum::() / img.len() as f32; + let r = resize(&img, 16, 16, Filter::Lanczos3); + let m2 = r.data.iter().sum::() / r.len() as f32; + assert!((mean - m2).abs() < 0.01); + let hh = half(&img); + assert_eq!((hh.width, hh.height), (32, 32)); + let m3 = hh.data.iter().sum::() / hh.len() as f32; + assert!((mean - m3).abs() < 1e-5); + } + + #[test] + fn fit_keeps_aspect() { + let img = Image::::new(4000, 3000); + let r = fit(&img, 400, 400, Filter::Box); + assert_eq!((r.width, r.height), (400, 300)); + let small = fit(&Image::::new(10, 5), 400, 400, Filter::Box); + assert_eq!((small.width, small.height), (10, 5)); + } +} diff --git a/crates/develop/src/raster/sample.rs b/crates/develop/src/raster/sample.rs new file mode 100644 index 0000000000..e300fe855a --- /dev/null +++ b/crates/develop/src/raster/sample.rs @@ -0,0 +1,154 @@ +//! Point sampling at continuous coordinates for geometric warps (alignment, projections). +//! +//! [`Rgb32f::sample_lanczos3`] interpolates with a 6 × 6 Lanczos-3 kernel. Bilinear sampling (the +//! [`Rgb32f::sample_bilinear`] next to it) averages two pixels at a half-pixel offset: a [½ ½] +//! filter that passes nothing at the Nyquist frequency, so a frame warped by a fraction of a pixel +//! loses its finest detail. Lanczos-3 keeps most of it. Its negative lobes would overshoot next to +//! a hard edge (a clipped highlight, a star), so each sample is held to the range of the 4 × 4 +//! pixels around it, channel by channel: in smooth areas and fine texture that range holds the +//! interpolated value anyway (a 2 × 2 range would cut the peaks of texture near Nyquist that fall +//! between pixels), and at an edge the overshoot goes. + +use std::sync::OnceLock; + +use super::Rgb32f; +use super::resample::Filter; + +/// Phases of a pixel the kernel's taps are tabulated for. +const PHASES: usize = 1024; + +/// The six Lanczos-3 weights (summing to 1) for a sample `t` (0..1) past the third of the six +/// pixels it reads: pixel `k` (0..6) is at distance `t + 2 − k`. +pub fn lanczos3_taps(t: f32) -> [f32; 6] { + static TABLE: OnceLock> = OnceLock::new(); + let table = TABLE.get_or_init(|| { + (0..=PHASES) + .map(|i| { + let t = i as f32 / PHASES as f32; + let w: [f32; 6] = std::array::from_fn(|k| Filter::Lanczos3.eval(t + 2.0 - k as f32)); + let s: f32 = w.iter().sum(); + w.map(|v| v / s) + }) + .collect() + }); + let i = if t.is_finite() { (t.clamp(0.0, 1.0) * PHASES as f32).round() as usize } else { 0 }; + table.get(i).copied().unwrap_or([0.0, 0.0, 1.0, 0.0, 0.0, 0.0]) +} + +impl Rgb32f { + /// Lanczos-3 sample at continuous pixel coordinates (pixel centres at +0.5), held to the range + /// of the 4 × 4 pixels around it (see the module docs). Past the edges the edge pixels repeat; + /// a coordinate that isn't finite reads the nearest edge, as [`Rgb32f::sample_bilinear`] does. + pub fn sample_lanczos3(&self, x: f32, y: f32) -> [f32; 3] { + let (w, h) = (self.width, self.height); + if w == 0 || h == 0 { + return [0.0; 3]; + } + let fx = x.clamp(-1.0, w as f32 + 1.0) - 0.5; + let fy = y.clamp(-1.0, h as f32 + 1.0) - 0.5; + let (fx, fy) = (if fx.is_finite() { fx } else { 0.0 }, if fy.is_finite() { fy } else { 0.0 }); + let (x0, y0) = (fx.floor(), fy.floor()); + let (wx, wy) = (lanczos3_taps(fx - x0), lanczos3_taps(fy - y0)); + let (x0, y0) = (x0 as isize, y0 as isize); + let col: [usize; 6] = std::array::from_fn(|k| (x0 + k as isize - 2).clamp(0, w as isize - 1) as usize); + let row: [usize; 6] = std::array::from_fn(|k| (y0 + k as isize - 2).clamp(0, h as isize - 1) as usize * w); + let px = |r: usize, c: usize| self.data.get(r + c).copied().unwrap_or_default(); + let mut acc = [0f32; 3]; + // and the range of the 4 × 4 pixels around the sample (taps 1 to 4 on each axis) + let mut lo = [f32::INFINITY; 3]; + let mut hi = [f32::NEG_INFINITY; 3]; + for (j, (r, &wr)) in row.iter().zip(&wy).enumerate() { + let mut line = [0f32; 3]; + for (i, (&c, &wc)) in col.iter().zip(&wx).enumerate() { + let p = px(*r, c); + for ch in 0..3 { + line[ch] += wc * p[ch]; + } + if (1..5).contains(&i) && (1..5).contains(&j) { + for ch in 0..3 { + lo[ch] = lo[ch].min(p[ch]); + hi[ch] = hi[ch].max(p[ch]); + } + } + } + for ch in 0..3 { + acc[ch] += wr * line[ch]; + } + } + // no finite pixel in the 4 × 4 range (NaN all around): nothing to hold the sample to + std::array::from_fn(|ch| if lo[ch] <= hi[ch] { acc[ch].clamp(lo[ch], hi[ch]) } else { acc[ch] }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// High-pass energy of a row-wise pattern: the mean squared second difference. + fn hp(img: &Rgb32f) -> f64 { + let w = img.width; + let mut s = 0.0; + let mut n = 0; + for y in 4..img.height - 4 { + for x in 4..w - 4 { + let v = |dx: isize| img.get((x as isize + dx) as usize, y)[1] as f64; + s += (2.0 * v(0) - v(-1) - v(1)).powi(2); + n += 1; + } + } + s / n as f64 + } + + #[test] + fn taps_sum_to_one_and_hit_pixels_exactly() { + for t in [0.0, 0.1, 0.5, 0.77, 1.0] { + let w = lanczos3_taps(t); + assert!((w.iter().sum::() - 1.0).abs() < 1e-5); + } + let w = lanczos3_taps(0.0); + assert!((w[2] - 1.0).abs() < 1e-5 && w.iter().enumerate().all(|(k, v)| k == 2 || v.abs() < 1e-5)); + assert_eq!(lanczos3_taps(f32::NAN), lanczos3_taps(0.0)); + } + + /// A fine pattern moved by half a pixel: bilinear keeps cos²(π f) of its high-pass energy (a + /// third at 0.3 cycles per pixel), Lanczos-3 twice that, and nearly all of it at 0.2. + #[test] + fn a_half_pixel_shift_keeps_fine_detail() { + for (f, lanczos_min, over_bilinear) in [(0.2f32, 0.9, 1.3), (0.3, 0.65, 1.9)] { + let img = Rgb32f::from_fn(64, 16, |x, _| [0.5 + 0.4 * (x as f32 * f * std::f32::consts::TAU).sin(); 3]); + let shifted = |s: &dyn Fn(f32, f32) -> [f32; 3]| Rgb32f::from_fn(64, 16, |x, y| s(x as f32 + 1.0, y as f32 + 0.5)); + let bil = shifted(&|x, y| img.sample_bilinear(x, y)); + let lan = shifted(&|x, y| img.sample_lanczos3(x, y)); + let (e0, eb, el) = (hp(&img), hp(&bil), hp(&lan)); + assert!(el > lanczos_min * e0, "{f} c/px: lanczos {el} vs {e0}"); + assert!(el > over_bilinear * eb, "{f} c/px: lanczos {el} vs bilinear {eb}"); + } + } + + /// Next to a hard edge Lanczos-3 would overshoot; the sample stays within its neighbours. + #[test] + fn no_overshoot_at_a_hard_edge() { + let img = Rgb32f::from_fn(16, 4, |x, _| if x < 8 { [0.0; 3] } else { [1.0; 3] }); + for i in 0..160 { + let v = img.sample_lanczos3(i as f32 * 0.1, 2.0); + assert!((0.0..=1.0).contains(&v[0]), "{v:?} at {}", i as f32 * 0.1); + } + // pixel centres come back exactly + assert_eq!(img.sample_lanczos3(8.5, 1.5), [1.0; 3]); + assert_eq!(img.sample_lanczos3(7.5, 1.5), [0.0; 3]); + } + + #[test] + fn edges_and_odd_coordinates_never_panic() { + let img = Rgb32f::from_fn(3, 2, |x, y| [x as f32, y as f32, 1.0]); + for (x, y) in [(f32::INFINITY, f32::INFINITY), (f32::NEG_INFINITY, 0.0), (f32::NAN, f32::NAN), (f32::MAX, -1e30), (-5.0, 9.0)] { + let v = img.sample_lanczos3(x, y); + assert!(v.iter().all(|c| c.is_finite()), "{v:?}"); + } + assert_eq!(Rgb32f::new(0, 0).sample_lanczos3(1.0, 1.0), [0.0; 3]); + // pixels that are all NaN (a damaged float file) give a NaN sample, never a panic + let nan = Rgb32f::from_fn(8, 8, |_, _| [f32::NAN; 3]); + assert!(nan.sample_lanczos3(4.3, 4.6).iter().all(|v| v.is_nan())); + assert_eq!(img.sample_lanczos3(0.5, 0.5), [0.0, 0.0, 1.0]); + } +} diff --git a/crates/develop/src/sensor/binned.rs b/crates/develop/src/sensor/binned.rs new file mode 100644 index 0000000000..a56fa0788f --- /dev/null +++ b/crates/develop/src/sensor/binned.rs @@ -0,0 +1,442 @@ +//! Reduced-size development straight from the mosaic ("superpixel" binning). +//! +//! When the caller needs an image at most half (or a third, a quarter…) of the sensor size — a +//! 2560 px loupe preview or a grid thumbnail of a 24 MP raw — demosaicing the full mosaic and then +//! downscaling throws most of the work away. Instead every `k × k` block of CFA samples becomes one +//! output pixel whose channels are the means of the block's samples of that colour. Every block must +//! contain all three colours (Bayer: `k` even; X-Trans: `k` a multiple of 3). There is no +//! interpolation, so there are no demosaicing artefacts; the colour planes are offset by less than +//! one output pixel, which is invisible at these scales. +//! +//! Clipping is decided per sample, before averaging. [`RawImage::develop_binned_masked`] keeps every +//! channel the mean of its samples and says, per output pixel, which colours had a sample at or above +//! `clip` (for `crate::highlight::reconstruct_masked`, which rebuilds them with the mean as a lower +//! bound). A specular point that clips one green sample of the 32 in an 8 × 8 block thus counts as +//! partly clipped without the block's green jumping to the clip level, which would read as a green +//! speckle once reconstructed. [`RawImage::develop_binned`] instead gives such a channel the block's +//! maximum sample of the colour, so that plain value thresholds see it as clipped. + +use super::{Normalized, RawData, RawDevelopExt, RawImage, Rect, Result, Rgb32f, cfa_valid, deferred_linearization_table}; + +// Cap the precomputed colour bytes, not image size or the supported block size. +const PHASE_COLOUR_BYTES: usize = 4 * 1024 * 1024; +type PhaseLayout = (Vec, [f32; 3]); + +/// Does at least one `k × k` block fit the active area, with single-plane CFA data and R, G +/// and B present in every block phase? Bayer also requires an even `k`. +pub fn can_bin(raw: &RawImage, k: usize) -> bool { + if k < 2 || k > raw.active_area.width || k > raw.active_area.height { + return false; + } + let Some(cfa) = &raw.cfa else { return false }; + if raw.cpp != 1 || (raw.pixel_aspect - 1.0).abs() >= 0.01 || !cfa_valid(cfa) || (cfa.is_bayer() && !k.is_multiple_of(2)) { + return false; + } + // Repeating a CFA period cannot add a colour to the phase's coverage. + (0..cfa.height).all(|j| { + (0..cfa.width).all(|i| { + let mut colours = 0u8; + for dy in 0..k.min(cfa.height) { + for dx in 0..k.min(cfa.width) { + colours |= 1 << cfa.color_at(i + dx, j + dy).min(2); + } + } + colours == 0b111 + }) + }) +} + +/// Like [`RawDevelopExt::develop`] at `1/k` of the size (camera RGB, white = 1.0, default crop applied, +/// not oriented). +pub fn develop_binned(raw: &RawImage, k: usize, clip: f32) -> Result> { + Ok(bin(raw, k, clip, true)?.map(|(img, _)| img)) +} + +/// Like [`develop_binned`], with every channel the mean of its block's samples, and the clip mask. +pub fn develop_binned_masked(raw: &RawImage, k: usize, clip: f32) -> Result)>> { + bin(raw, k, clip, false) +} + +/// The binned image and its clip mask; `keep_max`: a channel with a clipped sample takes the +/// block's maximum sample of the colour instead of the mean. +fn bin(raw: &RawImage, k: usize, clip: f32, keep_max: bool) -> Result)>> { + bin_with_phase_budget(raw, k, clip, keep_max, PHASE_COLOUR_BYTES) +} + +fn bin_with_phase_budget(raw: &RawImage, k: usize, clip: f32, keep_max: bool, phase_budget: usize) -> Result)>> { + raw.validate()?; + if !can_bin(raw, k) || !raw.opcodes.list3.is_empty() { + return Ok(None); + } + let Some(cfa) = &raw.cfa else { return Ok(None) }; + let a = raw.active_area; + // bin the default crop (relative to the active area) only + let c = raw.crop.clipped(a.width, a.height); + let c = if c.width < k || c.height < k { Rect::new(0, 0, a.width, a.height) } else { c }; + let (bw, bh) = (c.width / k, c.height / k); + if bw == 0 || bh == 0 { + return Ok(None); + } + // Opcode lists and a deferred table need the full normalization path. Plain files are + // normalized row by row so a preview does not allocate another full-resolution buffer. + let norm: Option = if raw.opcodes.list1.is_empty() && raw.opcodes.list2.is_empty() && deferred_linearization_table(raw).is_none() { + None + } else { + Some(raw.normalized()?) + }; + let cfa = cfa.shifted(a.x, a.y); + let range = raw.white_at(0) - raw.black.mean(); + let scale = if range > 0.0 { 1.0 / range } else { 1.0 }; + let uniform_black = raw.black.delta_h.is_empty() && raw.black.delta_v.is_empty() && raw.black.values.iter().all(|&v| v == raw.black.values[0]); + let black0 = raw.black.at(0, 0, 0, 1); + let (pw, ph) = (cfa.width, cfa.height); + let layouts = phase_layouts(&cfa, k, phase_budget); + let wlen = bw * k; + let mut out = Rgb32f::new(bw, bh); + let mut mask = vec![0u8; bw * bh]; + let process_row = |by: usize, row: &mut [[f32; 3]], mrow: &mut [u8]| { + // the block row's k sample rows, normalised + let mut rows = vec![0f32; k * wlen]; + for dy in 0..k { + let y = c.y + by * k + dy; + let dst = &mut rows[dy * wlen..(dy + 1) * wlen]; + match (&norm, &raw.data) { + (Some(nm), _) => dst.copy_from_slice(&nm.data[y * nm.width + c.x..][..wlen]), + (None, RawData::U16(d)) if uniform_black => { + let src = &d[(a.y + y) * raw.width + a.x + c.x..][..wlen]; + for (o, &v) in dst.iter_mut().zip(src) { + *o = (v as f32 - black0) * scale; + } + } + (None, data) => { + let base = (a.y + y) * raw.width + a.x + c.x; + for (x, o) in dst.iter_mut().enumerate() { + *o = (data.get(base + x) - raw.black.at(c.x + x, y, 0, 1)) * scale; + } + } + } + } + let py = (c.y + by * k) % ph; + for (bx, (px, m)) in row.iter_mut().zip(mrow.iter_mut()).enumerate() { + let phase_x = (c.x + bx * k) % pw; + let (sum, max, inv) = if let Some(layouts) = &layouts { + let (layout, inv) = &layouts[py * pw + phase_x]; + let (mut sum, mut max) = ([0f32; 3], [f32::MIN; 3]); + for dy in 0..k { + let src = &rows[dy * wlen + bx * k..][..k]; + for (&v, &col) in src.iter().zip(&layout[dy * k..(dy + 1) * k]) { + let col = col as usize; + sum[col] += v; + max[col] = max[col].max(v); + } + } + (sum, max, *inv) + } else { + periodic_block(&rows[bx * k..], wlen, k, &cfa, (phase_x, py)) + }; + for ch in 0..3 { + let clipped = max[ch] >= clip; + px[ch] = if clipped && keep_max { max[ch] } else { sum[ch] * inv[ch] }; + *m |= u8::from(clipped) << ch; + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.data.par_chunks_mut(bw).zip(mask.par_chunks_mut(bw)).enumerate().for_each(|(by, (row, mrow))| process_row(by, row, mrow)); + } + #[cfg(target_arch = "wasm32")] + { + for (by, (row, mrow)) in out.data.chunks_mut(bw).zip(mask.chunks_mut(bw)).enumerate() { + process_row(by, row, mrow); + } + } + Ok(Some((out, mask))) +} + +fn phase_layouts(cfa: &super::Cfa, k: usize, budget: usize) -> Option> { + let (pw, ph) = (cfa.width, cfa.height); + // There are at most 16 × 16 phase descriptors; the variable payload is one byte per sample. + let bytes = k.checked_mul(k)?.checked_mul(pw)?.checked_mul(ph)?; + if bytes > budget { + return None; + } + Some( + (0..ph) + .flat_map(|j| (0..pw).map(move |i| (i, j))) + .map(|(i, j)| { + let (layout, count) = block_layout(cfa, i, j, k); + (layout, count.map(|n| 1.0 / n.max(1) as f32)) + }) + .collect(), + ) +} + +/// Accumulate in the same row-major order as the precomputed layout, using one CFA row at a time. +fn periodic_block(rows: &[f32], stride: usize, k: usize, cfa: &super::Cfa, phase: (usize, usize)) -> ([f32; 3], [f32; 3], [f32; 3]) { + let (phase_x, phase_y) = phase; + let (pw, ph) = (cfa.width, cfa.height); + let (mut sum, mut max, mut count) = ([0f32; 3], [f32::MIN; 3], [0u32; 3]); + for dy in 0..k { + let src = &rows[dy * stride..][..k]; + // The CFA was shifted to the active area's origin; both stored origin offsets are zero. + let start = ((phase_y + dy) % ph) * pw; + let colours = cfa.pattern[start..start + pw].iter().cycle().skip(phase_x); + for (&v, &col) in src.iter().zip(colours) { + let col = col.min(2) as usize; + sum[col] += v; + max[col] = max[col].max(v); + count[col] += 1; + } + } + (sum, max, count.map(|n| 1.0 / n.max(1) as f32)) +} + +/// Colours of the `k × k` samples of a block whose corner sits at pattern position `(i, j)` +/// (row-major) and the count of each colour. +fn block_layout(cfa: &super::Cfa, i: usize, j: usize, k: usize) -> (Vec, [u32; 3]) { + let mut n = [0u32; 3]; + let l: Vec = (0..k * k) + .map(|t| { + let c = cfa.color_at(i + t % k, j + t / k).min(2); + n[c as usize] += 1; + c + }) + .collect(); + (l, n) +} + +#[cfg(test)] +mod tests { + use super::super::demosaic::mosaic_from_rgb; + use super::super::*; + use super::*; + + fn raw_from(n: &Normalized, black: f32, white: f32) -> RawImage { + let data = n.data.iter().map(|&v| (v * (white - black) + black).round() as u16).collect(); + RawImage { + format: RawFormat::Dng, + width: n.width, + height: n.height, + cpp: 1, + data: RawData::U16(data), + cfa: n.cfa.clone(), + bits: 14, + black: BlackLevel::uniform(black), + white: vec![white], + active_area: Rect::new(0, 0, n.width, n.height), + crop: Rect::new(0, 0, n.width, n.height), + orientation: craft_raw::Orientation::Normal, + color: ColorData::default(), + wb_multipliers: None, + linearized: false, + linearization_table: None, + pixel_aspect: 1.0, + opcodes: OpcodeLists::default(), + camera: Default::default(), + cinema: Default::default(), + lens_metadata: Default::default(), + level_sources: Default::default(), + notices: Default::default(), + } + } + + /// Omit the writer's WhiteLevel entry from this generated little-endian TIFF without moving + /// offsets or payloads. This forces the actual decoder to infer white from the table maximum. + fn omit_white_level(dng: &mut [u8]) { + assert_eq!(&dng[..4], b"II*\0"); + let ifd = u32::from_le_bytes(dng[4..8].try_into().unwrap()) as usize; + let count = u16::from_le_bytes(dng[ifd..ifd + 2].try_into().unwrap()); + let entries = ifd + 2; + let end = entries + 12 * usize::from(count); + let white = (entries..end) + .step_by(12) + .find(|&i| u16::from_le_bytes(dng[i..i + 2].try_into().unwrap()) == 50_717) + .expect("the generated DNG has a WhiteLevel entry"); + dng.copy_within(white + 12..end + 4, white); + dng[ifd..ifd + 2].copy_from_slice(&(count - 1).to_le_bytes()); + } + + #[test] + fn deferred_linearization_runs_after_opcode_list_one_before_normalizing() { + use craft_raw::opcodes::Area; + use craft_raw::{DngCompression, DngWriteOptions}; + + let mosaic = Normalized { width: 4, height: 4, cpp: 1, data: vec![1.0; 16], cfa: Cfa::bayer("RGGB") }; + let mut stored = raw_from(&mosaic, 0.0, 1.0); + stored.white = vec![65535.0]; // deliberately different from the table maximum + stored.linearization_table = Some(vec![0, 20, 100, 200]); + let area = Area { top: 0, left: 0, bottom: 4, right: 4, plane: 0, planes: 1, row_pitch: 1, col_pitch: 1 }; + stored.opcodes.list1.push(Opcode::MapTable { area, table: vec![0, 2, 2, 3] }); + let options = DngWriteOptions { compression: DngCompression::Uncompressed, ..Default::default() }; + let mut dng = craft_raw::write_dng(&stored, &options).unwrap(); + omit_white_level(&mut dng); + let raw = craft_raw::decode(&dng).unwrap(); + assert_eq!(raw.data, RawData::U16(vec![1; 16])); + assert!(!raw.linearized); + assert_eq!(raw.opcodes.list1, stored.opcodes.list1); + assert_eq!(raw.linearization_table.as_deref(), Some([0, 20, 100, 200].as_slice())); + assert_eq!(raw.white, vec![200.0]); + + // Stored 1 → OpcodeList1 code 2 → table value 100 → 100/200 = 0.5. + // No LUT gives 0.01; applying it before List1 instead gives 3/200 = 0.015. + let normalized = raw.normalized().unwrap(); + assert_eq!(normalized.data, vec![0.5; 16]); + let (preview, clipped) = raw.develop_binned_masked(2, 0.25).unwrap().unwrap(); + assert_eq!(preview.data, vec![[0.5; 3]; 4]); + assert_eq!(clipped, vec![0b111; 4]); + + let mut no_table = raw.clone(); + no_table.linearization_table = None; + assert!(no_table.normalized().unwrap().data.iter().all(|&v| (v - 0.01).abs() < 1e-6)); + + // A List1 opcode can produce a fractional code; 2.75 rounds to 3, not 2. + let mut fractional = raw.clone(); + fractional.opcodes.list1 = vec![Opcode::MapPolynomial { area, coefficients: vec![0.0, 2.75] }]; + assert_eq!(fractional.normalized().unwrap().data, vec![1.0; 16]); + + // A stale table on a float input must not turn linear samples into integer codes. + let mut floats = raw.clone(); + floats.opcodes.list1.clear(); + floats.data = RawData::F32(vec![50.0; 16]); + assert_eq!(floats.normalized().unwrap().data, vec![0.25; 16]); + + // Public callers can also construct a pending integer table without List1. + let mut pending = raw; + pending.opcodes.list1.clear(); + let (preview, _) = pending.develop_binned_masked(2, 0.25).unwrap().unwrap(); + assert!(preview.data.iter().flatten().all(|&v| (v - 0.1).abs() < 1e-6)); + + // Without List1, decode already applied the table. Develop must not apply it again. + stored.opcodes.list1.clear(); + let mut dng = craft_raw::write_dng(&stored, &options).unwrap(); + omit_white_level(&mut dng); + let decoded = craft_raw::decode(&dng).unwrap(); + assert!(decoded.linearized); + assert_eq!(decoded.data, RawData::U16(vec![20; 16])); + assert!(decoded.normalized().unwrap().data.iter().all(|&v| (v - 0.1).abs() < 1e-6)); + } + + #[test] + fn binning_matches_block_means_and_keeps_clipping() { + let img = Rgb32f::from_fn(24, 18, |x, y| [0.1 + x as f32 * 0.01, 0.2 + y as f32 * 0.01, 0.3]); + let mut raw = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("GRBG").unwrap()), 512.0, 16383.0); + assert!(raw.can_bin(2) && raw.can_bin(4) && !raw.can_bin(3)); + let b = raw.develop_binned(2, 0.99).unwrap().unwrap(); + assert_eq!((b.width, b.height), (12, 9)); + let p = b.get(3, 2); + // red sample of block (3,2) under GRBG is at (7,4); blue at (6,5); greens average (6,4)+(7,5) + assert!((p[0] - img.get(7, 4)[0]).abs() < 1e-3, "{p:?}"); + assert!((p[2] - 0.3).abs() < 1e-3); + assert!((p[1] - (img.get(6, 4)[1] + img.get(7, 5)[1]) / 2.0).abs() < 1e-3); + // a single clipped green sample keeps the block's green clipped + if let RawData::U16(d) = &mut raw.data { + d[4 * 24 + 6] = 16383; + } + assert!(raw.develop_binned(2, 0.99).unwrap().unwrap().get(3, 2)[1] >= 0.99); + // default crop is honoured at the binned scale + raw.crop = Rect::new(2, 2, 20, 12); + let c = raw.develop_binned(2, 0.99).unwrap().unwrap(); + assert_eq!((c.width, c.height), (10, 6)); + // X-Trans: 3×3 blocks hold all colours, 2×2 don't + let x = raw_from(&mosaic_from_rgb(&img, &Cfa::xtrans()), 0.0, 1000.0); + assert!(x.can_bin(3) && x.can_bin(6) && !x.can_bin(2)); + let xb = x.develop_binned(3, 0.99).unwrap().unwrap(); + assert_eq!((xb.width, xb.height), (8, 6)); + assert!((xb.get(4, 3)[2] - 0.3).abs() < 2e-3); + } + + #[test] + fn binning_requires_a_complete_block_in_the_active_area() { + let img = Rgb32f::filled(12, 10, [0.25, 0.5, 0.75]); + let mut raw = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("RGGB").unwrap()), 0.0, 4096.0); + raw.active_area = Rect::new(2, 2, 8, 6); + raw.crop = Rect::new(0, 0, 8, 6); + assert!(raw.can_bin(6)); + let binned = raw.develop_binned(6, 0.99).unwrap().unwrap(); + assert_eq!((binned.width, binned.height), (1, 1)); + assert_eq!(binned.data, vec![[0.25, 0.5, 0.75]]); + assert!(!can_bin(&raw, 8)); + assert!(!raw.can_bin(8)); + assert!(raw.develop_binned(8, 0.99).unwrap().is_none()); + assert!(raw.develop_binned_masked(8, 0.99).unwrap().is_none()); + } + + #[test] + fn binned_phase_budget_preserves_xtrans_pixels_and_clip_masks() { + let img = Rgb32f::from_fn(23, 21, |x, y| if (x, y) == (7, 4) { [1.0; 3] } else { [x as f32 / 64.0, y as f32 / 64.0, (x + y) as f32 / 64.0] }); + let mut raw = raw_from(&mosaic_from_rgb(&img, &Cfa::xtrans()), 0.0, 4096.0); + raw.active_area = Rect::new(1, 1, 21, 19); + raw.crop = Rect::new(1, 2, 17, 15); + let k = 5; + let cfa = raw.cfa.as_ref().unwrap().shifted(raw.active_area.x, raw.active_area.y); + assert!(phase_layouts(&cfa, k, PHASE_COLOUR_BYTES).is_some()); + assert!(phase_layouts(&cfa, k, 0).is_none()); + let compare = |keep_max| { + let (fast, fast_mask) = bin_with_phase_budget(&raw, k, 0.875, keep_max, PHASE_COLOUR_BYTES).unwrap().unwrap(); + let (bounded, bounded_mask) = bin_with_phase_budget(&raw, k, 0.875, keep_max, 0).unwrap().unwrap(); + assert_eq!((fast.width, fast.height), (3, 3)); + assert_eq!((fast.width, fast.height), (bounded.width, bounded.height)); + let bits = |img: &Rgb32f| img.data.iter().map(|p| p.map(f32::to_bits)).collect::>(); + assert_eq!(bits(&fast), bits(&bounded)); + assert_eq!(fast_mask, bounded_mask); + assert_eq!(fast_mask.iter().filter(|&&m| m != 0).count(), 1); + fast.get(1, 0) + }; + assert_ne!(compare(false), compare(true)); + } + + /// Issue #548: specular points that clip one green sample in some 8 × 8 blocks of a grey surface. + /// Taking the block's maximum makes those blocks' green the clip level, which reconstruction then + /// keeps (a green speckle); the masked binning keeps the mean and marks the green as clipped. + #[test] + fn clipping_is_decided_before_averaging() { + let img = Rgb32f::filled(64, 64, [0.3, 0.3, 0.3]); + let mut raw = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("RGGB").unwrap()), 0.0, 4095.0); + if let RawData::U16(d) = &mut raw.data { + // one green sample (RGGB: odd column of an even row) in every other block + for by in 0..8 { + for bx in (by % 2..8).step_by(2) { + d[(by * 8 + 2) * 64 + bx * 8 + 3] = 4095; + } + } + } + let wb = [1.0f32; 3]; + let (mut masked, mask) = raw.develop_binned_masked(8, 0.99).unwrap().unwrap(); + assert_eq!(mask.len(), 64); + assert_eq!(mask.iter().filter(|&&m| m == highlight::CLIPPED_G).count(), 32); + assert!(mask.iter().all(|&m| m & (highlight::CLIPPED_R | highlight::CLIPPED_B) == 0)); + // the clipped block's green is its mean: (31 · 0.3 + 1) / 32 + assert!((masked.get(0, 0)[1] - (31.0 * 0.3 + 1.0) / 32.0).abs() < 1e-3, "{:?}", masked.get(0, 0)); + assert_eq!(highlight::reconstruct_masked(&mut masked, wb, 0.99, [1.0; 3], &mask), 32); + let green = |img: &Rgb32f| img.data.iter().map(|p| p[1] / p[0]).fold(0.0f32, f32::max); + // (no more than the mean itself: the clipped sample counts at the clip level) + assert!(green(&masked) < 1.08, "green excess {}", green(&masked)); + // the maximum rule: a green speckle at the clip level + let mut max = raw.develop_binned(8, 0.99).unwrap().unwrap(); + assert!(max.get(0, 0)[1] >= 0.99); + highlight::reconstruct(&mut max, wb, 0.99); + assert!(green(&max) > 3.0, "{}", green(&max)); + // without clipped samples both are the same plain means, and the mask is empty + let clean = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("RGGB").unwrap()), 0.0, 4095.0); + let (a, m) = clean.develop_binned_masked(8, 0.99).unwrap().unwrap(); + assert!(m.iter().all(|&v| v == 0)); + assert!(a.data == clean.develop_binned(8, 0.99).unwrap().unwrap().data); + } + + #[test] + fn binning_matches_demosaic_downscaled_on_smooth_images() { + let img = Rgb32f::from_fn(64, 48, |x, y| [0.2 + 0.3 * (x as f32 / 64.0), 0.4 - 0.2 * (y as f32 / 48.0), 0.25]); + let raw = raw_from(&mosaic_from_rgb(&img, &Cfa::bayer("RGGB").unwrap()), 0.0, 4095.0); + let b = raw.develop_binned(2, 0.99).unwrap().unwrap(); + let full = crate::raster::resample::half(&raw.develop(Method::Ahd).unwrap()); + for y in 2..b.height - 2 { + for x in 2..b.width - 2 { + for c in 0..3 { + assert!((b.get(x, y)[c] - full.get(x, y)[c]).abs() < 0.01, "({x},{y})"); + } + } + } + } +} diff --git a/crates/develop/src/sensor/chart_table.rs b/crates/develop/src/sensor/chart_table.rs new file mode 100644 index 0000000000..a1a9f64013 --- /dev/null +++ b/crates/develop/src/sensor/chart_table.rs @@ -0,0 +1,30 @@ +// Camera colour matrices fitted to our own photographs of a ColorChecker Classic (post-November-2014 formulation), +// for cameras with no published spectral sensitivities. Kept by hand: each row's capture, fit and checks are in +// clean-room/crw/10-chart-calibration.md (scripts local-only). Reference colours: X-Rite's published L*a*b* (D50) for +// the chart, as packaged by colour-science (BSD-3-Clause). No number comes from Adobe or from a GPL raw decoder. +use craft_color_transform::Mat3; + +/// Measured dual-illuminant colour calibration for a camera model. +#[derive(Clone, Copy, Debug)] +pub struct Camera { + pub make: &'static str, + pub model: &'static str, + pub illuminant: [u16; 2], + pub color_matrix: [Mat3; 2], + pub forward_matrix: [Mat3; 2], +} + +#[rustfmt::skip] +pub const CAMERAS: &[Camera] = &[ + // Canon EOS D60 (CRW), the maintainer's body, ISO 100. Matrix 1: one ~2,900 K tungsten bulb, 11 frames, filed as + // Standard Illuminant A; matrix 2: direct afternoon sun, ~4,850 K, 20 frames, filed as D50 (both temperatures from + // the camera's own white-balance presets). Fitted on chromaticity with neutral held at D50 (the sunlit chart was + // unevenly lit): CIEDE2000 mean 2.42 / 1.70 on the 24 patches, 2.74 / 1.97 leaving each patch out. + Camera { + make: "Canon", + model: "EOS D60", + illuminant: [17, 23], + color_matrix: [Mat3([[0.950961, -0.345297, 0.112165], [-0.545579, 1.400621, 0.558365], [-0.123107, 0.222004, 1.026236]]), Mat3([[0.609694, -0.127035, -0.045387], [-0.461201, 1.16644, 0.337283], [-0.115992, 0.229363, 0.791647]])], + forward_matrix: [Mat3([[0.763921, 0.183562, 0.016813], [0.268545, 0.944022, -0.212567], [0.100742, -0.431647, 1.15601]]), Mat3([[0.757277, 0.190573, 0.016446], [0.291782, 1.009128, -0.300909], [0.026419, -0.264451, 1.063137]])], + }, +]; diff --git a/crates/develop/src/sensor/color.rs b/crates/develop/src/sensor/color.rs new file mode 100644 index 0000000000..480a97d9d5 --- /dev/null +++ b/crates/develop/src/sensor/color.rs @@ -0,0 +1,454 @@ +//! DNG colour model (Adobe DNG Specification 1.7, chapter 6 "Mapping Camera Color Space to CIE XYZ Space"). +//! +//! - `ColorMatrix1/2` (XYZ → reference camera) and `CameraCalibration1/2` / `ForwardMatrix1/2` are interpolated +//! between the two calibration illuminants by inverse correlated colour temperature of the white point. +//! - `XYZtoCamera = AnalogBalance · CameraCalibration · ColorMatrix`. +//! - White balance multipliers are the reciprocal of the camera neutral for the chosen white. +//! - Camera → XYZ(D50): through `ForwardMatrix` when present, else the inverse of `XYZtoCamera` followed by +//! Bradford adaptation from the white to D50. +//! - The as-shot white comes from `AsShotWhiteXY`, or `AsShotNeutral` converted to xy by the spec's iteration. +//! +//! Cameras without a colour matrix (non-DNG files until our own calibration DB exists) use a generic +//! "camera RGB ≈ linear sRGB" model and are flagged with `matrix_is_fallback`. + +use super::{ColorData, Mat3, RawImage}; +use craft_color_transform::{D50, D65, REC2020, SRGB, Xy, bradford, cct}; +use craft_raw::Matrix3; +use serde::{Deserialize, Serialize}; + +/// Correlated colour temperature (K) of an Exif `LightSource` / DNG `CalibrationIlluminant` code. +pub fn illuminant_temperature(code: u16) -> Option { + Some(match code { + 1 | 4 | 9 => 5500.0, + 2 | 14 => 4150.0, + 3 => 2850.0, + 10 => 6500.0, + 11 => 7500.0, + 12 => 6430.0, + 13 => 5000.0, + 15 => 3450.0, + 16 => 2940.0, + 17 => 2856.0, + 18 => 4874.0, + 19 => 6774.0, + 20 => 5503.0, + 21 => 6504.0, + 22 => 7504.0, + 23 => 5003.0, + 24 => 3200.0, + _ => return None, + }) +} + +fn lerp(a: &Mat3, b: &Mat3, g: f64) -> Mat3 { + let mut r = [[0.0; 3]; 3]; + for i in 0..3 { + for j in 0..3 { + r[i][j] = g * a.0[i][j] + (1.0 - g) * b.0[i][j]; + } + } + Mat3(r) +} + +/// Weight of calibration 1 for white `xy` (1 = use matrix 1 only). +pub fn illuminant_weight(color: &ColorData, white: Xy) -> f64 { + let t = cct::xy_to_temp_tint(white).0; + let (t1, t2) = (illuminant_temperature(color.illuminant[0]).unwrap_or(2856.0), illuminant_temperature(color.illuminant[1]).unwrap_or(6504.0)); + if (t1 - t2).abs() < 1.0 { + return 1.0; + } + let g = (1.0 / t - 1.0 / t2) / (1.0 / t1 - 1.0 / t2); + g.clamp(0.0, 1.0) +} + +fn interp(pair: &[Option; 2], g: f64) -> Option { + match pair { + [Some(a), Some(b)] => Some(lerp(&Mat3(*a), &Mat3(*b), g)), + [Some(a), None] | [None, Some(a)] => Some(Mat3(*a)), + [None, None] => None, + } +} + +/// `AnalogBalance · CameraCalibration` for white `xy`. +fn ab_cc(color: &ColorData, g: f64) -> Mat3 { + let ab = color.analog_balance.map(|a| Mat3::diag(a[0], a[1], a[2])).unwrap_or(Mat3::IDENTITY); + let cc = interp(&color.camera_calibration, g).unwrap_or(Mat3::IDENTITY); + ab.mul(&cc) +} + +/// Whether the file carries a usable colour matrix. +pub fn has_matrix(color: &ColorData) -> bool { + color.color_matrix.iter().any(|m| m.is_some()) +} + +/// `XYZtoCamera` for white `xy` (fallback: XYZ → linear sRGB). +pub fn xyz_to_camera(color: &ColorData, white: Xy) -> Mat3 { + let g = illuminant_weight(color, white); + match interp(&color.color_matrix, g) { + Some(cm) => ab_cc(color, g).mul(&cm), + None => SRGB.from_xyz(), + } +} + +/// Camera neutral (raw camera values of a neutral surface under white `xy`), normalised to max 1. +pub fn camera_neutral(color: &ColorData, white: Xy) -> [f64; 3] { + let Some(xyz) = white.to_xyz() else { return [1.0; 3] }; + let n = xyz_to_camera(color, white).apply(xyz); + let mx = n.iter().cloned().fold(f64::MIN, f64::max); + if mx > 0.0 { n.map(|v| v / mx) } else { [1.0; 3] } +} + +/// White-balance multipliers for white `xy` (reciprocal camera neutral, minimum 1). +pub fn wb_multipliers(color: &ColorData, white: Xy) -> [f64; 3] { + let n = camera_neutral(color, white); + let m = n.map(|v| if v > 1e-9 { 1.0 / v } else { 1.0 }); + let mn = m.iter().cloned().fold(f64::MAX, f64::min); + m.map(|v| v / mn) +} + +/// Convert a camera neutral to a white xy (DNG spec iteration: xy → XYZtoCamera(xy) → xy until stable). +pub fn neutral_to_xy(color: &ColorData, neutral: [f64; 3]) -> Xy { + let mut xy = D50; + for _ in 0..50 { + let Some(inv) = xyz_to_camera(color, xy).inverse() else { return xy }; + let xyz = inv.apply(neutral); + let Some(next) = Xy::from_xyz(xyz) else { return xy }; + if !(next.x.is_finite() && next.y.is_finite()) || next.y <= 0.0 { + return xy; + } + let next = Xy::new(next.x.clamp(0.1, 0.7), next.y.clamp(0.1, 0.7)); + let done = (next.x - xy.x).abs() < 1e-9 && (next.y - xy.y).abs() < 1e-9; + xy = next; + if done { + break; + } + } + xy +} + +/// The as-shot white point: `AsShotWhiteXY`, `AsShotNeutral`, vendor multipliers, else D65. +pub fn as_shot_white_xy(raw: &RawImage) -> Xy { + as_shot_white(&raw.color, raw.wb_multipliers) +} + +/// [`as_shot_white_xy`] from a header-only [`super::RawInfo`]. +pub fn as_shot_white_xy_of(info: &super::RawInfo) -> Xy { + as_shot_white(&info.color, info.wb_multipliers) +} + +/// The as-shot white from colour tags and vendor multipliers alone (see [`as_shot_white_xy`]). +pub fn as_shot_white_of(c: &ColorData, wb_multipliers: Option<[f32; 3]>) -> Xy { + as_shot_white(c, wb_multipliers) +} + +fn as_shot_white(c: &ColorData, wb_multipliers: Option<[f32; 3]>) -> Xy { + if let Some([x, y]) = c.as_shot_white_xy { + return Xy::new(x, y); + } + if let Some(n) = c.as_shot_neutral { + return neutral_to_xy(c, n); + } + if let Some(m) = wb_multipliers.filter(|m| m.iter().all(|v| *v > 0.0 && v.is_finite())) { + return neutral_to_xy(c, [1.0 / m[0] as f64, 1.0 / m[1] as f64, 1.0 / m[2] as f64]); + } + D65 +} + +/// Camera (raw, not white balanced) → XYZ relative to D50, for scene white `xy`. +pub fn camera_to_xyz_d50(color: &ColorData, white: Xy) -> Mat3 { + let g = illuminant_weight(color, white); + if has_matrix(color) + && let Some(fm) = interp(&color.forward_matrix, g) + { + let abcc = ab_cc(color, g); + if let Some(abcc_inv) = abcc.inverse() { + let n = camera_neutral(color, white); + let rn = abcc_inv.apply(n); + if rn.iter().all(|v| *v > 1e-9) { + return fm.mul(&Mat3::diag(1.0 / rn[0], 1.0 / rn[1], 1.0 / rn[2])).mul(&abcc_inv); + } + } + } + let cam_to_xyz = xyz_to_camera(color, white).inverse().unwrap_or(Mat3::IDENTITY); + bradford(white, D50).mul(&cam_to_xyz) +} + +/// Everything the pipeline needs to go from raw camera RGB to the working space. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct CameraTransform { + /// White-balanced camera RGB → linear Rec.2020 D65; maps (1, 1, 1) to (1, 1, 1). + pub matrix: Mat3, + /// Per-channel white-balance multipliers applied before `matrix` (minimum 1). + pub wb: [f32; 3], + pub white_xy: Xy, + /// No colour matrix was available: a generic camera ≈ sRGB model was used. + pub matrix_is_fallback: bool, + pub baseline_exposure: f64, +} + +/// Camera transform for white `wb_xy`: `rec2020 = matrix · (wb ⊙ camera)`. +pub fn camera_transform(raw: &RawImage, wb_xy: Xy) -> CameraTransform { + camera_transform_of(&raw.color, wb_xy) +} + +/// [`camera_transform`] from the colour tags alone. +pub fn camera_transform_of(color: &ColorData, wb_xy: Xy) -> CameraTransform { + let fallback = !has_matrix(color); + let wb = wb_multipliers(color, wb_xy); + let to_d50 = camera_to_xyz_d50(color, wb_xy); + let m = REC2020.from_xyz().mul(&bradford(D50, D65)).mul(&to_d50).mul(&Mat3::diag(1.0 / wb[0], 1.0 / wb[1], 1.0 / wb[2])); + let white = m.apply([1.0; 3]); + let k = (white[0] + white[1] + white[2]) / 3.0; + let matrix = if k.abs() > 1e-12 { Mat3(m.0.map(|r| r.map(|v| v / k))) } else { m }; + CameraTransform { matrix, wb: wb.map(|v| v as f32), white_xy: wb_xy, matrix_is_fallback: fallback, baseline_exposure: color.baseline_exposure } +} + +/// Linear Rec.2020 → linear Rec.2020 matrix that re-develops pixels developed with the camera +/// transform for white `from` as if developed for white `to`: the camera's own colour model is +/// evaluated at the new white (camera-space white balance, DNG spec ch. 6), as Lightroom does, so +/// a neutral lit by `to` comes out neutral. `None` when the tags have no colour matrix or the +/// transform is singular. +pub fn rebalance(color: &ColorData, from: Xy, to: Xy) -> Option { + if !has_matrix(color) { + return None; + } + let (a, b) = (camera_transform_of(color, from), camera_transform_of(color, to)); + let ratio = Mat3::diag(f64::from(b.wb[0] / a.wb[0]), f64::from(b.wb[1] / a.wb[1]), f64::from(b.wb[2] / a.wb[2])); + Some(b.matrix.mul(&ratio).mul(&a.matrix.inverse()?)) +} + +/// The white under which `rgb` (linear Rec.2020, developed with the camera transform for white +/// `developed_for`) is a neutral: the white [`rebalance`] must re-develop for to make it neutral +/// (white-balance picker, auto white balance). `None` without a colour matrix, or when `rgb` maps +/// to a non-positive camera value. +pub fn neutral_white(color: &ColorData, developed_for: Xy, rgb: [f64; 3]) -> Option { + if !has_matrix(color) { + return None; + } + let a = camera_transform_of(color, developed_for); + let balanced = a.matrix.inverse()?.apply(rgb); + let camera: [f64; 3] = std::array::from_fn(|i| balanced[i] / f64::from(a.wb[i])); + camera.iter().all(|v| v.is_finite() && *v > 0.0).then(|| neutral_to_xy(color, camera)) +} + +/// `(matrix, multipliers)` with `rec2020 = matrix · (multipliers ⊙ camera)`, linear Rec.2020 D65. +pub fn camera_to_rec2020(raw: &RawImage, wb_xy: Xy) -> (Mat3, [f32; 3]) { + let t = camera_transform(raw, wb_xy); + (t.matrix, t.wb) +} + +/// Grey-world white balance estimate (multipliers, min 1) from camera RGB, ignoring clipped and very dark pixels. +pub fn grey_world(img: &crate::raster::Rgb32f) -> [f32; 3] { + let mut s = [0f64; 3]; + let step = (img.data.len() / 200_000).max(1); + for p in img.data.iter().step_by(step) { + if p.iter().all(|&v| v > 0.02 && v < 0.95) { + for c in 0..3 { + s[c] += p[c] as f64; + } + } + } + if s.iter().any(|&v| v <= 0.0) { + return [1.0; 3]; + } + let m = [s[1] / s[0], 1.0, s[1] / s[2]]; + let mn = m.iter().cloned().fold(f64::MAX, f64::min); + m.map(|v| (v / mn) as f32) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A plausible camera: XYZ → camera matrix (rows sum to something sensible), invertible. + fn cam_a() -> Matrix3 { + [[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]] + } + fn cam_b() -> Matrix3 { + [[0.7, 0.3, -0.1], [-0.35, 1.3, 0.1], [0.05, -0.2, 1.0]] + } + + fn color_single(m: Matrix3, ill: u16) -> ColorData { + ColorData { illuminant: [ill, 0], color_matrix: [Some(m), None], ..Default::default() } + } + + fn raw_with(color: ColorData) -> RawImage { + RawImage { + format: super::super::RawFormat::Dng, + width: 1, + height: 1, + cpp: 1, + data: super::super::RawData::U16(vec![0]), + cfa: None, + bits: 16, + black: Default::default(), + white: vec![65535.0], + active_area: super::super::Rect::new(0, 0, 1, 1), + crop: super::super::Rect::new(0, 0, 1, 1), + orientation: Default::default(), + color, + wb_multipliers: None, + linearized: false, + linearization_table: None, + pixel_aspect: 1.0, + opcodes: Default::default(), + camera: Default::default(), + cinema: Default::default(), + lens_metadata: Default::default(), + level_sources: Default::default(), + notices: Default::default(), + } + } + + fn close(a: [f64; 3], b: [f64; 3], tol: f64) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() < tol) + } + + #[test] + fn neutral_maps_to_white_and_primaries_are_recovered() { + let raw = raw_with(color_single(cam_a(), 21)); + let t = camera_transform(&raw, D65); + assert!(!t.matrix_is_fallback); + // a surface with XYZ = Rec.2020 red primary under D65, seen by the camera + let red_xyz = REC2020.to_xyz().apply([1.0, 0.0, 0.0]); + let cam = Mat3(cam_a()).apply(red_xyz); + let wbd = [cam[0] * t.wb[0] as f64, cam[1] * t.wb[1] as f64, cam[2] * t.wb[2] as f64]; + let out = t.matrix.apply(wbd); + let k = out[0]; + assert!(close([out[0] / k, out[1] / k, out[2] / k], [1.0, 0.0, 0.0], 1e-6), "{out:?}"); + // white + let n = Mat3(cam_a()).apply(D65.to_xyz().unwrap()); + let wbd = [n[0] * t.wb[0] as f64, n[1] * t.wb[1] as f64, n[2] * t.wb[2] as f64]; + let out = t.matrix.apply(wbd); + assert!((out[0] - out[1]).abs() < 1e-6 && (out[1] - out[2]).abs() < 1e-6, "{out:?}"); + assert!(close(t.matrix.apply([1.0; 3]), [1.0; 3], 1e-12)); + assert!(t.wb.iter().cloned().fold(f32::MAX, f32::min) == 1.0); + } + + #[test] + fn dual_illuminant_interpolation() { + let color = ColorData { illuminant: [17, 21], color_matrix: [Some(cam_a()), Some(cam_b())], ..Default::default() }; + assert!((illuminant_weight(&color, cct::temp_tint_to_xy(2856.0, 0.0)) - 1.0).abs() < 0.01); + assert!(illuminant_weight(&color, cct::temp_tint_to_xy(6504.0, 0.0)) < 0.01); + assert_eq!(illuminant_weight(&color, cct::temp_tint_to_xy(10000.0, 0.0)), 0.0); + let mid = cct::temp_tint_to_xy(4000.0, 0.0); + let g = illuminant_weight(&color, mid); + let expect = (1.0 / 4000.0 - 1.0 / 6504.0) / (1.0 / 2856.0 - 1.0 / 6504.0); + assert!((g - expect).abs() < 0.02, "{g} vs {expect}"); + let m = xyz_to_camera(&color, mid); + let l = lerp(&Mat3(cam_a()), &Mat3(cam_b()), g); + assert!(close(m.0[0], l.0[0], 1e-12)); + } + + #[test] + fn neutral_xy_roundtrip() { + let color = ColorData { + illuminant: [17, 21], + color_matrix: [Some(cam_a()), Some(cam_b())], + analog_balance: Some([1.0, 1.05, 0.98]), + ..Default::default() + }; + for t in [2600.0, 3200.0, 4500.0, 5500.0, 7000.0, 9000.0] { + for tint in [-10.0, 0.0, 15.0] { + let xy = cct::temp_tint_to_xy(t, tint); + let n = camera_neutral(&color, xy); + let back = neutral_to_xy(&color, n); + assert!((back.x - xy.x).abs() < 1e-6 && (back.y - xy.y).abs() < 1e-6, "{t} {tint}: {back:?} vs {xy:?}"); + } + } + let mut raw = raw_with(color.clone()); + raw.color.as_shot_neutral = Some(camera_neutral(&color, cct::temp_tint_to_xy(3300.0, 5.0))); + let xy = as_shot_white_xy(&raw); + let (t, tint) = cct::xy_to_temp_tint(xy); + assert!((t - 3300.0).abs() < 5.0 && (tint - 5.0).abs() < 0.5, "{t} {tint}"); + raw.color.as_shot_white_xy = Some([D50.x, D50.y]); + assert_eq!(as_shot_white_xy(&raw), D50); + } + + #[test] + fn forward_matrix_path_agrees_with_color_matrix_path() { + let a = Mat3(cam_a()); + let n = a.apply(D65.to_xyz().unwrap()); + let fm = bradford(D65, D50).mul(&a.inverse().unwrap()).mul(&Mat3::diag(n[0], n[1], n[2])); + // DNG forward matrices map (1,1,1) to D50 white (with Y=1): normalise like a real file would + let w = fm.apply([1.0; 3]); + let s = D50.to_xyz().unwrap()[1] / w[1]; + let fm = fm.0.map(|r| r.map(|v| v * s)); + let cm_only = camera_transform(&raw_with(color_single(cam_a(), 21)), D65); + let mut with_fm = color_single(cam_a(), 21); + with_fm.forward_matrix = [Some(fm), None]; + let fm_t = camera_transform(&raw_with(with_fm), D65); + for i in 0..3 { + assert!(close(cm_only.matrix.0[i], fm_t.matrix.0[i], 1e-9), "{:?} vs {:?}", cm_only.matrix, fm_t.matrix); + } + assert_eq!(cm_only.wb, fm_t.wb); + } + + #[test] + fn camera_calibration_and_analog_balance_are_respected() { + // AB · CC scales channels: the neutral must scale accordingly + let mut c = color_single(cam_a(), 21); + let base = camera_neutral(&c, D65); + c.camera_calibration = [Some(Mat3::diag(1.0, 0.5, 1.0).0), None]; + let n = camera_neutral(&c, D65); + assert!((n[1] / n[0] - 0.5 * base[1] / base[0]).abs() < 1e-9); + } + + #[test] + fn fallback_without_matrix() { + let mut raw = raw_with(ColorData::default()); + raw.wb_multipliers = Some([2.0, 1.0, 1.5]); + let xy = as_shot_white_xy(&raw); + let t = camera_transform(&raw, xy); + assert!(t.matrix_is_fallback); + assert!((t.wb[0] / t.wb[1] - 2.0).abs() < 1e-3 && (t.wb[2] / t.wb[1] - 1.5).abs() < 1e-3, "{:?}", t.wb); + let t = camera_transform(&raw, D65); + let expect = SRGB.to_space(&REC2020); + for i in 0..3 { + assert!(close(t.matrix.0[i], expect.0[i], 1e-6)); + } + assert_eq!(camera_to_rec2020(&raw, D65).1, [1.0, 1.0, 1.0]); + } + + #[test] + fn illuminant_codes() { + assert_eq!(illuminant_temperature(21), Some(6504.0)); + assert_eq!(illuminant_temperature(17), Some(2856.0)); + assert_eq!(illuminant_temperature(0), None); + assert_eq!(illuminant_temperature(255), None); + } + + /// Camera-space white balance: re-developing for another white turns a neutral lit by that + /// white neutral (the camera's own matrices, interpolated for the new white, say how); the same + /// white is the identity; without a colour matrix there is nothing to re-evaluate. + #[test] + fn rebalance_redevelops_for_the_new_white() { + let color = ColorData { illuminant: [17, 21], color_matrix: [Some(cam_a()), Some(cam_b())], ..Default::default() }; + let (from, to) = (cct::temp_tint_to_xy(5500.0, 0.0), cct::temp_tint_to_xy(3200.0, 10.0)); + let a = camera_transform_of(&color, from); + // a grey card lit by `to`, as the camera records it, developed for `from`: warm + let n = camera_neutral(&color, to); + let developed = a.matrix.apply(std::array::from_fn(|i| n[i] * a.wb[i] as f64)); + assert!(developed[0] > 1.2 * developed[2], "{developed:?}"); + let out = rebalance(&color, from, to).unwrap().apply(developed); + assert!(close(out.map(|v| v / out[1]), [1.0; 3], 1e-6), "{out:?}"); + let same = rebalance(&color, from, from).unwrap(); + assert!((0..3).all(|r| close(same.0[r], Mat3::IDENTITY.0[r], 1e-9)), "{same:?}"); + assert!(rebalance(&ColorData::default(), from, to).is_none()); + // and back: the developed grey card names the white it was lit by + let white = neutral_white(&color, from, developed).unwrap(); + assert!((white.x - to.x).abs() < 1e-6 && (white.y - to.y).abs() < 1e-6, "{white:?} vs {to:?}"); + assert!(neutral_white(&color, from, [-1.0, 0.5, 0.5]).is_none()); + assert!(neutral_white(&ColorData::default(), from, developed).is_none()); + } + + #[test] + fn grey_world_balances() { + let img = crate::raster::Rgb32f::from_fn(20, 20, |x, _| { + let v = 0.2 + 0.02 * x as f32; + [v * 0.5, v, v * 0.8] + }); + let m = grey_world(&img); + assert!((m[0] - 2.0).abs() < 1e-3 && (m[1] - 1.0).abs() < 1e-6 && (m[2] - 1.25).abs() < 1e-3, "{m:?}"); + } +} diff --git a/crates/develop/src/sensor/demosaic.rs b/crates/develop/src/sensor/demosaic.rs new file mode 100644 index 0000000000..b0f825818b --- /dev/null +++ b/crates/develop/src/sensor/demosaic.rs @@ -0,0 +1,396 @@ +//! Demosaicing: CFA mosaic → camera RGB ([`Rgb32f`]), values as normalised (white = 1.0). +//! +//! Methods (all from published descriptions, see the README): +//! - [`Method::Bilinear`] — average of same-colour neighbours (drafts / thumbnails); works for any pattern. +//! - [`Method::Ppg`] — Patterned Pixel Grouping (Chuan-kai Lin): gradient-selected green, colour-difference R/B. +//! - [`Method::Ahd`] — Adaptive Homogeneity-Directed (Hirakawa & Parks, IEEE TIP 2005): horizontal/vertical +//! candidates chosen per pixel by CIELab homogeneity. The quality default for Bayer sensors. +//! - Non-Bayer patterns (X-Trans, …) always use `xtrans::directional`, our own edge-weighted colour-difference +//! interpolation. +//! +//! Every method reproduces a constant-colour mosaic exactly. + +mod ahd; +pub(super) mod bilinear; +mod ppg; +mod xtrans; + +use super::{Cfa, Normalized, Rect, Rgb32f}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Method { + Bilinear, + Ppg, + #[default] + Ahd, +} + +pub(super) fn mosaic_method(cfa: &Cfa, w: usize, h: usize, method: Method) -> Method { + if (w < 4 || h < 4) && cfa.is_bayer() { Method::Bilinear } else { method } +} + +/// Mirror-reflected access to a single-plane mosaic (reflection keeps Bayer parity: −k → k, w−1+k → w−1−k). +#[derive(Clone, Copy)] +pub(crate) struct Mosaic<'a> { + pub w: usize, + pub h: usize, + pub data: &'a [f32], + pub cfa: &'a Cfa, +} + +#[inline] +pub(crate) fn reflect(i: isize, n: usize) -> usize { + if i >= 0 && (i as usize) < n { + return i as usize; + } + let n = n as isize; + if n == 1 { + return 0; + } + let period = 2 * (n - 1); + let mut i = i.rem_euclid(period); + if i >= n { + i = period - i; + } + i as usize +} + +/// `v` clamped between `a` and `b`: `v.clamp(a.min(b), a.max(b))`, except that it returns `v` as is when both +/// bounds are NaN (NaN samples in a float raw), where `f32::clamp` panics. +#[inline] +pub(crate) fn clamp_between(v: f32, a: f32, b: f32) -> f32 { + let (lo, hi) = (a.min(b), a.max(b)); + if lo <= hi { v.clamp(lo, hi) } else { v } +} + +impl Mosaic<'_> { + #[inline] + pub fn get(&self, x: isize, y: isize) -> f32 { + self.data[reflect(y, self.h) * self.w + reflect(x, self.w)] + } + #[inline] + pub fn color(&self, x: isize, y: isize) -> u8 { + self.cfa.color_at(reflect(x, self.w), reflect(y, self.h)) + } +} + +/// Demosaic normalised raw data. `cpp == 3` data is returned as is; monochrome data is replicated to grey. +pub fn demosaic(n: &Normalized, method: Method) -> Rgb32f { + let (w, h) = (n.width, n.height); + if w == 0 || h == 0 { + return Rgb32f::new(w, h); + } + match (&n.cfa, n.cpp) { + (_, 3) => Rgb32f { width: w, height: h, data: n.data.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect() }, + // four colours develop from their first three; narrower data (refused by `RawImage::validate`, issue #1511) + // repeats its last sample instead of reading past the pixel + (_, cpp) if cpp != 1 => Rgb32f { + width: w, + height: h, + data: n + .data + .chunks_exact(cpp.max(1)) + .map(|c| { + let s = |i: usize| c.get(i).or(c.last()).copied().unwrap_or(0.0); + [s(0), s(1), s(2)] + }) + .collect(), + }, + (None, _) => Rgb32f { width: w, height: h, data: n.data.iter().map(|&v| [v; 3]).collect() }, + (Some(cfa), _) => { + let m = Mosaic { w, h, data: &n.data, cfa }; + match mosaic_method(cfa, w, h, method) { + Method::Bilinear => bilinear::bilinear(&m), + _ if !cfa.is_bayer() => xtrans::directional(&m), + Method::Ppg => ppg::ppg(&m), + Method::Ahd => ahd::ahd(&m), + } + } + } +} + +/// [`demosaic`] with [`Method::Ahd`] of the window `r` alone, for Bayer mosaics (`None` for any other data, or a +/// window not inside the mosaic): the same pixels as demosaicing it all and cropping that to `r`, without +/// demosaicing the rest or copying the window out of it. +pub(crate) fn ahd_window(n: &Normalized, r: Rect) -> Option { + let (w, h) = (n.width, n.height); + let cfa = n.cfa.as_ref()?; + let inside = r.x.checked_add(r.width).is_some_and(|e| e <= w) && r.y.checked_add(r.height).is_some_and(|e| e <= h); + if n.cpp != 1 || !cfa.is_bayer() || w < 4 || h < 4 || n.data.len() != w * h || r.width == 0 || r.height == 0 || !inside { + return None; + } + let m = Mosaic { w, h, data: &n.data, cfa }; + Some(ahd::ahd_window(&m, r.x, r.y, r.width, r.height)) +} + +/// Build a mosaic from an RGB image by sampling each pixel's CFA colour (for tests and synthetic data). +pub fn mosaic_from_rgb(img: &Rgb32f, cfa: &Cfa) -> Normalized { + let data = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).map(|(x, y)| img.get(x, y)[cfa.color_at(x, y) as usize]).collect(); + Normalized { width: img.width, height: img.height, cpp: 1, data, cfa: Some(cfa.clone()) } +} + +/// Peak signal-to-noise ratio (dB, peak 1.0) between two images over an interior region (`border` pixels excluded). +pub fn psnr(a: &Rgb32f, b: &Rgb32f, border: usize) -> f64 { + let mut se = 0.0f64; + let mut n = 0usize; + for y in border..a.height.saturating_sub(border) { + for x in border..a.width.saturating_sub(border) { + let (p, q) = (a.get(x, y), b.get(x, y)); + for c in 0..3 { + se += ((p[c] - q[c]) as f64).powi(2); + n += 1; + } + } + } + if n == 0 || se == 0.0 { + return f64::INFINITY; + } + 10.0 * (1.0 / (se / n as f64)).log10() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn smooth_scene(w: usize, h: usize) -> Rgb32f { + Rgb32f::from_fn(w, h, |x, y| { + let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32); + [0.2 + 0.6 * fx * fy, 0.3 + 0.4 * (fx * 3.0).sin().abs() * 0.5 + 0.2 * fy, 0.1 + 0.5 * (1.0 - fx) * (0.5 + 0.5 * (fy * 5.0).cos())] + }) + } + + /// A photo-like scene: sharp luminance structure (disc, stripes, diagonal edge, fine texture) modulating a + /// smoothly varying colour — edges are mostly luminance edges, as in natural images. + fn edgy_scene(w: usize, h: usize) -> Rgb32f { + Rgb32f::from_fn(w, h, |x, y| { + let (fx, fy) = (x as f32, y as f32); + let d = ((fx - w as f32 * 0.35).powi(2) + (fy - h as f32 * 0.4).powi(2)).sqrt(); + let lum = if d < w as f32 * 0.18 { + 0.85 + } else if x > w * 2 / 3 && (y / 3) % 2 == 0 { + 0.15 + } else if fx + fy * 0.5 > w as f32 * 1.1 { + 0.7 + } else { + 0.35 + 0.1 * ((fx * 0.7).sin() * (fy * 0.9).cos()) + }; + let tint = [0.9 + 0.1 * (fx / w as f32), 0.8, 0.55 + 0.3 * (fy / h as f32)]; + [lum * tint[0], lum * tint[1], lum * tint[2]] + }) + } + + fn run(img: &Rgb32f, cfa: &Cfa, m: Method) -> Rgb32f { + demosaic(&mosaic_from_rgb(img, cfa), m) + } + + #[test] + fn constant_colour_is_exact_for_all_methods_and_phases() { + let img = Rgb32f::filled(17, 13, [0.3, 0.55, 0.8]); + for pat in ["RGGB", "BGGR", "GRBG", "GBRG"] { + let cfa = Cfa::bayer(pat).unwrap(); + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let out = run(&img, &cfa, m); + for p in &out.data { + for c in 0..3 { + assert!((p[c] - img.data[0][c]).abs() < 1e-5, "{pat} {m:?} {p:?}"); + } + } + } + } + let out = run(&Rgb32f::filled(19, 14, [0.3, 0.55, 0.8]), &Cfa::xtrans(), Method::Ahd); + assert!(out.data.iter().all(|p| (p[0] - 0.3).abs() < 1e-5 && (p[1] - 0.55).abs() < 1e-5 && (p[2] - 0.8).abs() < 1e-5)); + } + + /// A window demosaiced alone is the same, bit for bit, as that part of the whole picture: at the edges and + /// corners (where the mosaic is reflected), in the middle, across tile seams, at every CFA phase. + #[test] + fn ahd_window_is_the_crop_of_the_whole() { + let img = edgy_scene(300, 270); + for pat in ["RGGB", "GBRG"] { + let n = mosaic_from_rgb(&img, &Cfa::bayer(pat).unwrap()); + let whole = demosaic(&n, Method::Ahd); + for r in + [Rect::new(0, 0, 300, 270), Rect::new(0, 0, 7, 5), Rect::new(1, 3, 298, 266), Rect::new(121, 130, 140, 9), Rect::new(293, 263, 7, 7)] + { + let part = ahd_window(&n, r).unwrap(); + let want = whole.clone().into_crop(r.x, r.y, r.width, r.height); + assert_eq!((part.width, part.height), (r.width, r.height)); + assert!(part.data.iter().zip(&want.data).all(|(a, b)| a.map(f32::to_bits) == b.map(f32::to_bits)), "{pat} {r:?}"); + } + assert!(ahd_window(&n, Rect::new(1, 0, 300, 270)).is_none(), "a window past the mosaic is refused"); + } + } + + #[test] + fn known_samples_are_preserved() { + let img = edgy_scene(40, 32); + let cfa = Cfa::bayer("GRBG").unwrap(); + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let out = run(&img, &cfa, m); + for y in 0..32 { + for x in 0..40 { + let c = cfa.color_at(x, y) as usize; + assert!((out.get(x, y)[c] - img.get(x, y)[c]).abs() < 1e-6, "{m:?}"); + } + } + } + } + + #[test] + fn psnr_thresholds_and_ranking() { + let smooth = smooth_scene(96, 80); + let edgy = edgy_scene(96, 80); + let cfa = Cfa::bayer("RGGB").unwrap(); + let p = |img: &Rgb32f, m| psnr(img, &run(img, &cfa, m), 4); + let (sb, sp, sa) = (p(&smooth, Method::Bilinear), p(&smooth, Method::Ppg), p(&smooth, Method::Ahd)); + assert!(sb > 38.0 && sp > 38.0 && sa > 38.0, "smooth: bilinear {sb:.1} ppg {sp:.1} ahd {sa:.1}"); + let (eb, ep, ea) = (p(&edgy, Method::Bilinear), p(&edgy, Method::Ppg), p(&edgy, Method::Ahd)); + eprintln!("smooth: bilinear {sb:.1} ppg {sp:.1} ahd {sa:.1}; edgy: bilinear {eb:.1} ppg {ep:.1} ahd {ea:.1}"); + assert!(eb > 20.0, "edgy bilinear {eb:.1}"); + assert!(ep > eb + 6.0, "ppg {ep:.1} vs bilinear {eb:.1}"); + assert!(ea > eb + 6.0, "ahd {ea:.1} vs bilinear {eb:.1}"); + let xt = Cfa::xtrans(); + let xp = psnr(&edgy, &run(&edgy, &xt, Method::Ahd), 6); + let xb = psnr(&edgy, &run(&edgy, &xt, Method::Bilinear), 6); + assert!(xp > 20.0 && xp >= xb - 0.5, "xtrans directional {xp:.1} bilinear {xb:.1}"); + } + + /// Mean anisotropy of a demosaiced picture's fine luminance detail: per pixel, how much more its 3 × 3 high-pass + /// correlates with its horizontal neighbours than with its vertical ones (or the reverse). Noise has none; the + /// short horizontal and vertical strokes of a maze pattern have a lot. + fn anisotropy(img: &Rgb32f) -> f64 { + let (w, h) = (img.width, img.height); + let lum: Vec = img.data.iter().map(|p| 0.25 * p[0] + 0.5 * p[1] + 0.25 * p[2]).collect(); + let mean3 = |x: usize, y: usize| (0..9).map(|k| lum[(y + k / 3 - 1) * w + x + k % 3 - 1]).sum::() / 9.0; + let hp: Vec = + (0..w * h).map(|i| if i % w == 0 || i % w == w - 1 || i < w || i >= w * (h - 1) { 0.0 } else { lum[i] - mean3(i % w, i / w) }).collect(); + let (mut sum, mut n) = (0f64, 0f64); + for y in 2..h - 2 { + for x in 2..w - 2 { + let i = y * w + x; + sum += f64::from((hp[i] * (hp[i - 1] + hp[i + 1] - hp[i - w] - hp[i + w])).abs()); + n += 1.0; + } + } + sum / n + } + + #[test] + fn flat_noise_does_not_turn_into_a_maze() { + // a flat grey patch with sensor-like noise: AHD picked horizontal or vertical candidates per pixel by a + // homogeneity count that noise alone decides, so the picture became short horizontal and vertical strokes + let (w, h) = (192, 160); + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut noise = || { + // sum of four uniforms ≈ Gaussian, σ ≈ 0.02 + (0..4) + .map(|_| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 40) as f32 / (1u64 << 24) as f32 - 0.5 + }) + .sum::() + * 0.035 + }; + let cfa = Cfa::bayer("RGGB").unwrap(); + let data = (0..w * h).map(|_| 0.2 + noise()).collect(); + let n = Normalized { width: w, height: h, cpp: 1, data, cfa: Some(cfa) }; + let (ahd, bilinear) = (anisotropy(&demosaic(&n, Method::Ahd)), anisotropy(&demosaic(&n, Method::Bilinear))); + eprintln!("anisotropy: ahd {ahd:.3e}, bilinear {bilinear:.3e}"); + // the hard choice gave about 11 times bilinear's, the blend about 7.5 times + assert!(ahd < 9.0 * bilinear, "ahd {ahd:.3e} bilinear {bilinear:.3e}"); + } + + #[test] + fn tiny_and_degenerate_inputs() { + let cfa = Cfa::bayer("RGGB").unwrap(); + for (w, h) in [(1, 1), (2, 2), (3, 5), (5, 3), (1, 7)] { + let img = Rgb32f::filled(w, h, [0.5; 3]); + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let out = run(&img, &cfa, m); + assert_eq!((out.width, out.height), (w, h)); + assert!(out.data.iter().all(|p| p.iter().all(|v| v.is_finite()))); + } + } + let n = Normalized { width: 2, height: 1, cpp: 1, data: vec![0.2, 0.4], cfa: None }; + assert_eq!(demosaic(&n, Method::Ahd).data, vec![[0.2; 3], [0.4; 3]]); + let n = Normalized { width: 1, height: 1, cpp: 3, data: vec![0.1, 0.2, 0.3], cfa: None }; + assert_eq!(demosaic(&n, Method::Ahd).data, vec![[0.1, 0.2, 0.3]]); + } + + #[test] + fn a_nan_sample_spreads_no_further_than_the_chosen_candidate_takes_it() { + // vertical stripes: the vertical candidate wins outright beside them, and the horizontal one, which reads two + // samples to each side, is the only one that sees a NaN two columns away + let img = Rgb32f::from_fn(32, 24, |x, _| if (x / 2) % 2 == 0 { [0.2, 0.3, 0.25] } else { [0.7, 0.8, 0.6] }); + let cfa = Cfa::bayer("RGGB").unwrap(); + let mut n = mosaic_from_rgb(&img, &cfa); + n.data[12 * 32 + 16] = f32::NAN; + let out = demosaic(&n, Method::Ahd); + let bad = out.data.iter().filter(|p| p.iter().any(|v| !v.is_finite())).count(); + // the pixels that read the NaN sample themselves, as many as the outright pick gave; the blend made it 33 + assert!(bad <= 9, "{bad} pixels not finite"); + } + + #[test] + fn non_finite_samples_do_not_panic() { + // regression: NaN samples (a float DNG) gave AHD and PPG NaN bounds for `f32::clamp`, which panics + let cfa = Cfa::bayer("RGGB").unwrap(); + let mut patchy = mosaic_from_rgb(&edgy_scene(24, 20), &cfa); + for (i, v) in patchy.data.iter_mut().enumerate() { + let (x, y) = (i % 24, i / 24); + if (8..12).contains(&x) && (6..10).contains(&y) { + *v = f32::NAN; + } else if i % 7 == 0 { + *v = if i % 2 == 0 { f32::INFINITY } else { f32::NEG_INFINITY }; + } + } + let all_nan = Normalized { width: 9, height: 7, cpp: 1, data: vec![f32::NAN; 63], cfa: Some(cfa) }; + for n in [&patchy, &all_nan] { + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let out = demosaic(n, m); + assert_eq!((out.width, out.height), (n.width, n.height), "{m:?}"); + } + } + // without NaN bounds it is the `f32::clamp` it replaced, bit for bit (finite results stay identical) + let vals = [f32::NEG_INFINITY, -3e38, -2.5, -0.0, 0.0, 1e-40, 0.5, 1.0, 3e38, f32::INFINITY]; + for v in vals { + for a in vals { + for b in vals { + assert_eq!(clamp_between(v, a, b).to_bits(), v.clamp(a.min(b), a.max(b)).to_bits(), "{v} {a} {b}"); + } + } + } + } + + #[test] + fn reflect_indices() { + assert_eq!(reflect(-1, 5), 1); + assert_eq!(reflect(-2, 5), 2); + assert_eq!(reflect(5, 5), 3); + assert_eq!(reflect(6, 5), 2); + assert_eq!(reflect(3, 1), 0); + assert_eq!(reflect(-7, 2), 1); + } + + #[test] + #[ignore] + fn throughput() { + let (w, h) = (6000, 4000); + let img = smooth_scene(w, h); + let cfa = Cfa::bayer("RGGB").unwrap(); + let n = mosaic_from_rgb(&img, &cfa); + for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { + let t = std::time::Instant::now(); + let _ = demosaic(&n, m); + let s = t.elapsed().as_secs_f64(); + println!("{m:?}: {:.1} MP/s ({:.0} ms for 24 MP)", (w * h) as f64 / 1e6 / s, s * 1e3); + } + let n = mosaic_from_rgb(&img, &Cfa::xtrans()); + let t = std::time::Instant::now(); + let _ = demosaic(&n, Method::Ahd); + println!("X-Trans directional: {:.1} MP/s", (w * h) as f64 / 1e6 / t.elapsed().as_secs_f64()); + } +} diff --git a/crates/develop/src/sensor/demosaic/ahd.rs b/crates/develop/src/sensor/demosaic/ahd.rs new file mode 100644 index 0000000000..6960573e3a --- /dev/null +++ b/crates/develop/src/sensor/demosaic/ahd.rs @@ -0,0 +1,190 @@ +//! Adaptive Homogeneity-Directed demosaicing (K. Hirakawa, T. W. Parks, "Adaptive homogeneity-directed +//! demosaicing algorithm", IEEE Trans. Image Processing 14(3), 2005), implemented from the paper: +//! +//! 1. Interpolate green horizontally and vertically (5-tap filter [−¼ ½ ½ ½ −¼] across the missing site, +//! clamped to the two adjacent greens), giving two candidate green planes. +//! 2. Complete each candidate with red/blue by colour-difference (C − G) interpolation. +//! 3. Convert both candidates to CIELab and measure, per pixel, how many of its 4 neighbours lie within the +//! adaptive luminance / chrominance tolerances (ε_L, ε_C from the paper) — the homogeneity. +//! 4. Sum homogeneity over a 3×3 window and pick the more homogeneous candidate. The paper picks one outright; +//! we blend the two by how far apart their sums are (see [`BLEND`]), so a clear edge still takes one candidate. +//! +//! Work is done in overlapping tiles (bounded memory, rayon-parallel), one band of tiles at a time written +//! straight into the output. Each step runs only where the tile's output depends on it: the choice reads the +//! homogeneity 1 pixel around the tile, which reads Lab 2 pixels around, the candidates read the greens 3 +//! pixels around, and those read the mosaic 5 pixels around, inside the `MARGIN`. + +use super::super::Rgb32f; +use super::Mosaic; + +const TILE: usize = 128; +const MARGIN: usize = 6; +/// Difference of the two candidates' 3×3 homogeneity sums (each 0–36) from which the more homogeneous one is taken +/// alone; closer sums blend the two linearly, equal sums half and half. In a flat, noisy area noise alone decides +/// which sum is larger, and picking outright turned the noise into short horizontal and vertical strokes (a maze, +/// coloured where white balance is strong). 12 keeps the PSNR of the outright pick on the edge tests. +const BLEND: f32 = 12.0; + +pub(crate) fn ahd(m: &Mosaic) -> Rgb32f { + ahd_window(m, 0, 0, m.w, m.h) +} + +/// The `w × h` pixels at (`x`, `y`) of [`ahd`]'s picture (inside the mosaic), demosaiced alone: every pixel comes +/// from the mosaic around it, so they are the same as when the whole picture is demosaiced and then cropped. +pub(crate) fn ahd_window(m: &Mosaic, x: usize, y: usize, w: usize, h: usize) -> Rgb32f { + let mut out = Rgb32f::new(w, h); + if w == 0 || h == 0 { + return out; + } + // one row of tiles per task, its tiles in parallel too, written straight into the picture + let process_band = |ty: usize, band: &mut [[f32; 3]]| { + let (y0, th) = (y + ty * TILE, band.len() / w.max(1)); + #[cfg(not(target_arch = "wasm32"))] + let tiles: Vec<(usize, usize, Vec<[f32; 3]>)> = { + use rayon::prelude::*; + (0..w.div_ceil(TILE)) + .into_par_iter() + .map(|tx| { + let (x0, tw) = (tx * TILE, TILE.min(w - tx * TILE)); + (x0, tw, tile(m, x + x0, y0, tw, th)) + }) + .collect() + }; + #[cfg(target_arch = "wasm32")] + let tiles: Vec<(usize, usize, Vec<[f32; 3]>)> = (0..w.div_ceil(TILE)) + .map(|tx| { + let (x0, tw) = (tx * TILE, TILE.min(w - tx * TILE)); + (x0, tw, tile(m, x + x0, y0, tw, th)) + }) + .collect(); + for (x0, tw, px) in tiles { + for (row, src) in band.chunks_exact_mut(w).zip(px.chunks_exact(tw)) { + row[x0..x0 + tw].copy_from_slice(src); + } + } + }; + crate::raster::par_rows(&mut out.data, (w * TILE).max(1), process_band); + out +} + +/// Linear camera RGB (treated as sRGB/D65 primaries for the homogeneity metric only) → CIELab. +#[inline] +fn lab(p: [f32; 3]) -> [f32; 3] { + let x = (0.4124 * p[0] + 0.3576 * p[1] + 0.1805 * p[2]) / 0.95047; + let y = 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; + let z = (0.0193 * p[0] + 0.1192 * p[1] + 0.9505 * p[2]) / 1.08883; + #[inline] + fn f(t: f32) -> f32 { + if t > 0.008856 { t.cbrt() } else { 7.787 * t + 16.0 / 116.0 } + } + let (fx, fy, fz) = (f(x), f(y), f(z)); + [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)] +} + +fn tile(m: &Mosaic, x0: usize, y0: usize, tw: usize, th: usize) -> Vec<[f32; 3]> { + let (bw, bh) = (tw + 2 * MARGIN, th + 2 * MARGIN); + let n = bw * bh; + let (ox, oy) = (x0 as isize - MARGIN as isize, y0 as isize - MARGIN as isize); + let mut mos = vec![0f32; n]; + let mut col = vec![0u8; n]; + for (y, (mrow, crow)) in mos.chunks_exact_mut(bw).zip(col.chunks_exact_mut(bw)).enumerate() { + let ry = super::reflect(oy + y as isize, m.h); + if ox >= 0 && ox as usize + bw <= m.w { + // inside the image: the row as it is, and its colours repeating with the pattern + let x0 = ry * m.w + ox as usize; + mrow.copy_from_slice(&m.data[x0..x0 + bw]); + let period: Vec = (0..m.cfa.width).map(|k| m.cfa.color_at(ox as usize + k, ry)).collect(); + for (c, &p) in crow.iter_mut().zip(period.iter().cycle()) { + *c = p; + } + } else { + for x in 0..bw { + mrow[x] = m.get(ox + x as isize, oy + y as isize); + crow[x] = m.color(ox + x as isize, oy + y as isize); + } + } + } + // flat indices of the pixels `d` or more from the buffer's edge, row by row + let inner = |d: usize| (d..bh - d).flat_map(move |y| y * bw + d..y * bw + bw - d); + // 1. directional greens + let mut gh = vec![0f32; n]; + let mut gv = vec![0f32; n]; + for i in inner(MARGIN - 3) { + let c = mos[i]; + if col[i] == 1 { + gh[i] = c; + gv[i] = c; + continue; + } + let (l, r) = (mos[i - 1], mos[i + 1]); + let est = (l + r) * 0.5 + (2.0 * c - mos[i - 2] - mos[i + 2]) * 0.25; + gh[i] = super::clamp_between(est, l, r); + let (u, d) = (mos[i - bw], mos[i + bw]); + let est = (u + d) * 0.5 + (2.0 * c - mos[i - 2 * bw] - mos[i + 2 * bw]) * 0.25; + gv[i] = super::clamp_between(est, u, d); + } + // 2. full candidates, and 3. their Lab + // (`p` with channel `c` set to `v`, in registers: writing channels through an index and reading the pixel + // back for its Lab stalled on store forwarding) + let set = |p: [f32; 3], c: u8, v: f32| [if c == 0 { v } else { p[0] }, if c == 1 { v } else { p[1] }, if c >= 2 { v } else { p[2] }]; + let complete = |g: &[f32]| -> (Vec<[f32; 3]>, Vec<[f32; 3]>) { + let mut rgb = vec![[0f32; 3]; n]; + let mut lab_of = vec![[0f32; 3]; n]; + for i in inner(MARGIN - 2) { + let own = col[i]; + let gvv = g[i]; + let d = |j: usize| mos[j] - g[j]; + let p = if own == 1 { + let p = set([0.0, gvv, 0.0], col[i + 1], gvv + (d(i - 1) + d(i + 1)) * 0.5); + set(p, col[i + bw], gvv + (d(i - bw) + d(i + bw)) * 0.5) + } else { + let p = set([0.0, gvv, 0.0], own, mos[i]); + set(p, 2 - own, gvv + (d(i - bw - 1) + d(i - bw + 1) + d(i + bw - 1) + d(i + bw + 1)) * 0.25) + }; + rgb[i] = p; + lab_of[i] = lab(p); + } + (rgb, lab_of) + }; + let (rh, lh) = complete(&gh); + let (rv, lv) = complete(&gv); + // homogeneity + let dl = |a: &[f32; 3], b: &[f32; 3]| (a[0] - b[0]).abs(); + let dc = |a: &[f32; 3], b: &[f32; 3]| (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2); + let mut hh = vec![0u8; n]; + let mut hv = vec![0u8; n]; + for i in inner(MARGIN - 1) { + // left, right, up, down + let (l, r, u, d) = (i - 1, i + 1, i - bw, i + bw); + let (a, b) = (lh[i], lv[i]); + let dlh = [dl(&a, &lh[l]), dl(&a, &lh[r]), dl(&a, &lh[u]), dl(&a, &lh[d])]; + let dch = [dc(&a, &lh[l]), dc(&a, &lh[r]), dc(&a, &lh[u]), dc(&a, &lh[d])]; + let dlv = [dl(&b, &lv[l]), dl(&b, &lv[r]), dl(&b, &lv[u]), dl(&b, &lv[d])]; + let dcv = [dc(&b, &lv[l]), dc(&b, &lv[r]), dc(&b, &lv[u]), dc(&b, &lv[d])]; + let eps_l = dlh[0].max(dlh[1]).min(dlv[2].max(dlv[3])); + let eps_c = dch[0].max(dch[1]).min(dcv[2].max(dcv[3])); + hh[i] = (0..4).map(|k| u8::from(dlh[k] <= eps_l && dch[k] <= eps_c)).sum(); + hv[i] = (0..4).map(|k| u8::from(dlv[k] <= eps_l && dcv[k] <= eps_c)).sum(); + } + // 4. choose + let mut out = Vec::with_capacity(tw * th); + for i in inner(MARGIN) { + let (mut sh, mut sv) = (0u32, 0u32); + for j in [i - bw - 1, i - bw, i - bw + 1, i - 1, i, i + 1, i + bw - 1, i + bw, i + bw + 1] { + sh += hh[j] as u32; + sv += hv[j] as u32; + } + let wh = (0.5 + (sh as f32 - sv as f32) / (2.0 * BLEND)).clamp(0.0, 1.0); + // a candidate taken alone is copied, and one that isn't finite (beside a float raw's NaN sample) is left out, + // so the other's value doesn't become 0 · NaN + let finite = |p: &[f32; 3]| p.iter().all(|v| v.is_finite()); + out.push(if wh >= 1.0 || !finite(&rv[i]) { + rh[i] + } else if wh <= 0.0 || !finite(&rh[i]) { + rv[i] + } else { + [0, 1, 2].map(|c| rh[i][c] * wh + rv[i][c] * (1.0 - wh)) + }); + } + out +} diff --git a/crates/develop/src/sensor/demosaic/bilinear.rs b/crates/develop/src/sensor/demosaic/bilinear.rs new file mode 100644 index 0000000000..268b0bd6fe --- /dev/null +++ b/crates/develop/src/sensor/demosaic/bilinear.rs @@ -0,0 +1,115 @@ +//! Bilinear demosaicing for any CFA pattern: each missing colour is the mean of the same-colour samples in the +//! 3×3 neighbourhood (5×5 when the 3×3 has none, as happens in some non-Bayer layouts). + +use super::Mosaic; +use crate::raster::par_rows; +use crate::sensor::highlight::{CLIPPED_BITS, FROM_CLIPPED_BITS}; +use crate::sensor::{Rect, Rgb32f}; + +type PhaseTaps = [Vec<(isize, isize)>; 3]; + +/// Offsets (dx, dy) of same-colour neighbours for each pattern position and colour. +fn neighbour_table(m: &Mosaic) -> Vec { + let cfa = m.cfa; + let mut table = Vec::with_capacity(cfa.width * cfa.height); + for py in 0..cfa.height { + for px in 0..cfa.width { + let mut per: [Vec<(isize, isize)>; 3] = Default::default(); + for (c, list) in per.iter_mut().enumerate() { + for r in [1isize, 2] { + for dy in -r..=r { + for dx in -r..=r { + let (x, y) = (px as isize + dx + 6 * cfa.width as isize, py as isize + dy + 6 * cfa.height as isize); + if cfa.color_at(x as usize, y as usize) as usize == c { + list.push((dx, dy)); + } + } + } + if !list.is_empty() { + break; + } + } + } + table.push(per); + } + } + table +} + +/// Visit the samples that contribute to a missing channel, in interpolation order. +#[inline] +fn for_each_tap(m: &Mosaic, table: &[PhaseTaps], x: usize, y: usize, c: usize, mut visit: impl FnMut(f32)) { + let cfa = m.cfa; + if x >= 2 && y >= 2 && x + 2 < m.w && y + 2 < m.h { + let entry = &table[(y % cfa.height) * cfa.width + (x % cfa.width)]; + for &(dx, dy) in &entry[c] { + visit(m.data[(y as isize + dy) as usize * m.w + (x as isize + dx) as usize]); + } + return; + } + for r in [1isize, 2] { + let mut found = false; + for dy in -r..=r { + for dx in -r..=r { + let (nx, ny) = (x as isize + dx, y as isize + dy); + if m.color(nx, ny) as usize == c { + visit(m.get(nx, ny)); + found = true; + } + } + } + if found { + break; + } + } +} + +pub(crate) fn bilinear(m: &Mosaic) -> Rgb32f { + let (w, h) = (m.w, m.h); + let table = neighbour_table(m); + let cfa = m.cfa; + let mut out = Rgb32f::new(w, h); + par_rows(&mut out.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + let own = cfa.color_at(x, y) as usize; + for (c, channel) in px.iter_mut().enumerate() { + if c == own { + *channel = m.data[y * w + x]; + continue; + } + let (mut s, mut n) = (0.0f32, 0u32); + for_each_tap(m, &table, x, y, c, |v| { + s += v; + n += 1; + }); + *channel = if n > 0 { s / n as f32 } else { m.data[y * w + x] }; + } + } + }); + out +} + +pub(in crate::sensor) fn clip_mask(m: &Mosaic, crop: Rect, clip: f32) -> Vec { + let table = neighbour_table(m); + let mut mask = vec![0; crop.width * crop.height]; + par_rows(&mut mask, crop.width, |oy, row| { + let y = crop.y + oy; + for (ox, bits) in row.iter_mut().enumerate() { + let x = crop.x + ox; + let own = m.cfa.color_at(x, y) as usize; + if m.data[y * m.w + x] >= clip { + *bits = CLIPPED_BITS[own]; + continue; + } + // Each channel uses only its own taps, so leave the measured-colour field unset. + for (c, bit) in FROM_CLIPPED_BITS.into_iter().enumerate().filter(|&(c, _)| c != own) { + for_each_tap(m, &table, x, y, c, |v| { + if v >= clip { + *bits |= bit; + } + }); + } + } + }); + mask +} diff --git a/crates/develop/src/sensor/demosaic/ppg.rs b/crates/develop/src/sensor/demosaic/ppg.rs new file mode 100644 index 0000000000..e3eb167430 --- /dev/null +++ b/crates/develop/src/sensor/demosaic/ppg.rs @@ -0,0 +1,89 @@ +//! Patterned Pixel Grouping (after Chuan-kai Lin's published description of the method). +//! +//! 1. Green at red/blue sites: four directional gradients (same-colour difference ×2 plus the green difference +//! across the site); the estimate along the flattest direction is the nearer green weighted 3:1 with the far +//! one plus a same-colour Laplacian correction, clamped to the two greens of that direction. +//! 2. Red/blue at green sites: colour-difference (C − G) average of the two same-colour neighbours. +//! 3. Blue at red sites (and red at blue): colour-difference average along the diagonal with the smaller +//! gradient (both diagonals when equal). + +use super::super::Rgb32f; +use super::Mosaic; +use crate::raster::par_rows; + +/// Green plane with PPG estimates at non-green sites. +pub(crate) fn green_plane(m: &Mosaic) -> Vec { + let (w, h) = (m.w, m.h); + let mut g = vec![0f32; w * h]; + par_rows(&mut g, w, |y, row| { + let y = y as isize; + for (x, o) in row.iter_mut().enumerate() { + let x = x as isize; + let c = m.get(x, y); + if m.color(x, y) == 1 { + *o = c; + continue; + } + let (gn, gs, gw, ge) = (m.get(x, y - 1), m.get(x, y + 1), m.get(x - 1, y), m.get(x + 1, y)); + let (cn, cs, cw, ce) = (m.get(x, y - 2), m.get(x, y + 2), m.get(x - 2, y), m.get(x + 2, y)); + let dv = (gn - gs).abs(); + let dh = (gw - ge).abs(); + let grads = [(cn - c).abs() * 2.0 + dv, (cs - c).abs() * 2.0 + dv, (cw - c).abs() * 2.0 + dh, (ce - c).abs() * 2.0 + dh]; + let mut best = 0; + for i in 1..4 { + if grads[i] < grads[best] { + best = i; + } + } + let (near, far, cfar) = match best { + 0 => (gn, gs, cn), + 1 => (gs, gn, cs), + 2 => (gw, ge, cw), + _ => (ge, gw, ce), + }; + let est = (near * 3.0 + far + c - cfar) * 0.25; + *o = super::clamp_between(est, near, far); + } + }); + g +} + +pub(crate) fn ppg(m: &Mosaic) -> Rgb32f { + let (w, h) = (m.w, m.h); + let g = green_plane(m); + let gg = |x: isize, y: isize| g[super::reflect(y, h) * w + super::reflect(x, w)]; + let mut out = Rgb32f::new(w, h); + par_rows(&mut out.data, w, |y, row| { + let y = y as isize; + for (x, px) in row.iter_mut().enumerate() { + let x = x as isize; + let own = m.color(x, y) as usize; + let gv = gg(x, y); + px[1] = gv; + if own == 1 { + // horizontal neighbours carry one colour, vertical the other + let ch = m.color(x + 1, y) as usize; + let cv = m.color(x, y + 1) as usize; + let hval = gv + ((m.get(x - 1, y) - gg(x - 1, y)) + (m.get(x + 1, y) - gg(x + 1, y))) * 0.5; + let vval = gv + ((m.get(x, y - 1) - gg(x, y - 1)) + (m.get(x, y + 1) - gg(x, y + 1))) * 0.5; + px[ch] = hval; + px[cv] = vval; + } else { + px[own] = m.get(x, y); + let other = 2 - own; + let d = |dx: isize, dy: isize| m.get(x + dx, y + dy) - gg(x + dx, y + dy); + let ne = (m.get(x + 1, y - 1) - m.get(x - 1, y + 1)).abs() + (gg(x + 1, y - 1) - gv).abs() + (gg(x - 1, y + 1) - gv).abs(); + let nw = (m.get(x - 1, y - 1) - m.get(x + 1, y + 1)).abs() + (gg(x - 1, y - 1) - gv).abs() + (gg(x + 1, y + 1) - gv).abs(); + let diff = if ne < nw { + (d(1, -1) + d(-1, 1)) * 0.5 + } else if nw < ne { + (d(-1, -1) + d(1, 1)) * 0.5 + } else { + (d(1, -1) + d(-1, 1) + d(-1, -1) + d(1, 1)) * 0.25 + }; + px[other] = gv + diff; + } + } + }); + out +} diff --git a/crates/develop/src/sensor/demosaic/xtrans.rs b/crates/develop/src/sensor/demosaic/xtrans.rs new file mode 100644 index 0000000000..f12ab4b8e9 --- /dev/null +++ b/crates/develop/src/sensor/demosaic/xtrans.rs @@ -0,0 +1,283 @@ +//! Demosaicing for non-Bayer patterns (Fujifilm X-Trans and others): our own edge-weighted colour-difference +//! interpolation. +//! +//! 1. Green at non-green sites: robust weighted mean of the green samples in the 3×3 neighbourhood (5×5 if +//! none), each weighted by `1 / (ε + |g − median|)` so samples across an edge contribute little. +//! 2. Red and blue everywhere: `G(p) + Σ w_q (C(q) − G(q)) / Σ w_q` over same-colour samples `q` in the 5×5 +//! neighbourhood, with `w_q = 1 / (d²(p, q) · (ε + |G(q) − G(p)|))` — spatially close samples on the same +//! side of an edge dominate. + +use super::super::Rgb32f; +use super::Mosaic; +use crate::raster::par_rows; + +const EPS: f32 = 1e-3; + +type OffsetList = Vec<(isize, isize)>; + +/// Same-colour neighbour offsets for every pattern phase, in scan order (so sums run in the same +/// order as a plain 2-D loop and interior pixels match border pixels bit for bit). +struct Offsets { + pw: usize, + ph: usize, + /// Per phase: green offsets at radius 1, then those at radius 2 (ring order as the loop below). + green: Vec<(OffsetList, OffsetList)>, + /// Per phase and colour (0 = red, 1 = blue): 5×5 offsets of that colour. + rb: Vec<[OffsetList; 2]>, +} + +impl Offsets { + fn new(m: &Mosaic) -> Offsets { + let (pw, ph) = (m.cfa.width.max(1), m.cfa.height.max(1)); + // phases are evaluated far from the borders (pattern coordinates wrap) + let col = |x: isize, y: isize| m.cfa.color_at(x.rem_euclid(pw as isize) as usize, y.rem_euclid(ph as isize) as usize); + let mut green = Vec::new(); + let mut rb = Vec::new(); + for py in 0..ph as isize { + for px in 0..pw as isize { + let ring = |r: isize| { + let mut v = Vec::new(); + for dy in -r..=r { + for dx in -r..=r { + if (dx != 0 || dy != 0) && col(px + dx, py + dy) == 1 { + v.push((dx, dy)); + } + } + } + v + }; + green.push((ring(1), ring(2))); + let of = |c: u8| { + let mut v = Vec::new(); + for dy in -2isize..=2 { + for dx in -2isize..=2 { + if col(px + dx, py + dy) == c { + v.push((dx, dy)); + } + } + } + v + }; + rb.push([of(0), of(2)]); + } + } + Offsets { pw, ph, green, rb } + } + #[inline] + fn phase(&self, x: usize, y: usize) -> usize { + (y % self.ph) * self.pw + x % self.pw + } +} + +/// Robust weighted mean of `vals` around their median. +#[inline] +fn robust_mean(vals: &[f32]) -> f32 { + let mut sorted = [0f32; 24]; + let sorted = &mut sorted[..vals.len()]; + sorted.copy_from_slice(vals); + sorted.sort_unstable_by(|a, b| a.total_cmp(b)); + let med = sorted[sorted.len() / 2]; + let (mut s, mut ws) = (0.0f32, 0.0f32); + for &v in vals { + let wt = 1.0 / (EPS + (v - med).abs()); + s += wt * v; + ws += wt; + } + s / ws +} + +fn green(m: &Mosaic, off: &Offsets) -> Vec { + let (w, h) = (m.w, m.h); + let mut g = vec![0f32; w * h]; + par_rows(&mut g, w, |y, row| { + let interior_y = y >= 2 && y + 2 < h; + let yi = y as isize; + let mut vals: Vec = Vec::with_capacity(24); + for (x, o) in row.iter_mut().enumerate() { + if interior_y && x >= 2 && x + 2 < w { + // fast path: precomputed offsets, no reflection + let ph = off.phase(x, y); + let i = y * w + x; + if m.cfa.color_at(x, y) == 1 { + *o = m.data[i]; + continue; + } + let (r1, r2) = &off.green[ph]; + let ring = if r1.is_empty() { r2 } else { r1 }; + if ring.is_empty() { + *o = m.data[i]; + continue; + } + vals.clear(); + vals.extend(ring.iter().map(|&(dx, dy)| m.data[(i as isize + dy * w as isize + dx) as usize])); + *o = robust_mean(&vals); + continue; + } + let x = x as isize; + if m.color(x, yi) == 1 { + *o = m.get(x, yi); + continue; + } + vals.clear(); + for r in [1isize, 2] { + for dy in -r..=r { + for dx in -r..=r { + if (dx != 0 || dy != 0) && m.color(x + dx, yi + dy) == 1 { + vals.push(m.get(x + dx, yi + dy)); + } + } + } + if !vals.is_empty() { + break; + } + } + if vals.is_empty() { + *o = m.get(x, yi); + continue; + } + *o = robust_mean(&vals); + } + }); + g +} + +pub(crate) fn directional(m: &Mosaic) -> Rgb32f { + let (w, h) = (m.w, m.h); + let off = Offsets::new(m); + let g = green(m, &off); + let gg = |x: isize, y: isize| g[super::reflect(y, h) * w + super::reflect(x, w)]; + let mut out = Rgb32f::new(w, h); + par_rows(&mut out.data, w, |y, row| { + let interior_y = y >= 2 && y + 2 < h; + let yi = y as isize; + for (x, px) in row.iter_mut().enumerate() { + if interior_y && x >= 2 && x + 2 < w { + let i = y * w + x; + let own = m.cfa.color_at(x, y) as usize; + let gp = g[i]; + px[1] = gp; + let lists = &off.rb[off.phase(x, y)]; + for (li, c) in [0usize, 2].into_iter().enumerate() { + if c == own { + px[c] = m.data[i]; + continue; + } + let (mut s, mut ws) = (0.0f32, 0.0f32); + for &(dx, dy) in &lists[li] { + let j = (i as isize + dy * w as isize + dx) as usize; + let gq = g[j]; + let d2 = (dx * dx + dy * dy) as f32; + let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); + s += wt * (m.data[j] - gq); + ws += wt; + } + px[c] = if ws > 0.0 { gp + s / ws } else { gp }; + } + continue; + } + let x = x as isize; + let own = m.color(x, yi) as usize; + let gp = gg(x, yi); + px[1] = gp; + for c in [0usize, 2] { + if c == own { + px[c] = m.get(x, yi); + continue; + } + let (mut s, mut ws) = (0.0f32, 0.0f32); + for dy in -2isize..=2 { + for dx in -2isize..=2 { + if m.color(x + dx, yi + dy) as usize != c { + continue; + } + let gq = gg(x + dx, yi + dy); + let d2 = (dx * dx + dy * dy) as f32; + let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); + s += wt * (m.get(x + dx, yi + dy) - gq); + ws += wt; + } + } + px[c] = if ws > 0.0 { gp + s / ws } else { gp }; + } + } + }); + out +} + +#[cfg(test)] +mod tests { + use super::super::Cfa; + use super::*; + + /// The straightforward per-pixel formulation (reflection at every access): the precomputed + /// interior path must match it bit for bit. + fn reference(m: &Mosaic) -> Rgb32f { + let (w, h) = (m.w, m.h); + let mut g = vec![0f32; w * h]; + for y in 0..h as isize { + for x in 0..w as isize { + let o = &mut g[y as usize * w + x as usize]; + if m.color(x, y) == 1 { + *o = m.get(x, y); + continue; + } + let mut vals = Vec::new(); + for r in [1isize, 2] { + for dy in -r..=r { + for dx in -r..=r { + if (dx != 0 || dy != 0) && m.color(x + dx, y + dy) == 1 { + vals.push(m.get(x + dx, y + dy)); + } + } + } + if !vals.is_empty() { + break; + } + } + *o = if vals.is_empty() { m.get(x, y) } else { robust_mean(&vals) }; + } + } + let gg = |x: isize, y: isize| g[super::super::reflect(y, h) * w + super::super::reflect(x, w)]; + Rgb32f::from_fn(w, h, |x, y| { + let (x, y) = (x as isize, y as isize); + let own = m.color(x, y) as usize; + let gp = gg(x, y); + let mut px = [0f32, gp, 0.0]; + for c in [0usize, 2] { + if c == own { + px[c] = m.get(x, y); + continue; + } + let (mut s, mut ws) = (0.0f32, 0.0f32); + for dy in -2isize..=2 { + for dx in -2isize..=2 { + if m.color(x + dx, y + dy) as usize == c { + let gq = gg(x + dx, y + dy); + let wt = 1.0 / ((dx * dx + dy * dy) as f32 * (EPS + (gq - gp).abs())); + s += wt * (m.get(x + dx, y + dy) - gq); + ws += wt; + } + } + } + px[c] = if ws > 0.0 { gp + s / ws } else { gp }; + } + px + }) + } + + #[test] + fn fast_path_is_bit_exact() { + let cfa = Cfa::xtrans().shifted(1, 2); + let (w, h) = (37, 29); + let mut seed = 12345u32; + let data: Vec = (0..w * h) + .map(|_| { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 + }) + .collect(); + let m = Mosaic { w, h, data: &data, cfa: &cfa }; + let (a, b) = (directional(&m), reference(&m)); + assert!(a.data.iter().zip(&b.data).all(|(p, q)| p.map(f32::to_bits) == q.map(f32::to_bits))); + } +} diff --git a/crates/develop/src/sensor/gaintable.rs b/crates/develop/src/sensor/gaintable.rs new file mode 100644 index 0000000000..94634b3dfb --- /dev/null +++ b/crates/develop/src/sensor/gaintable.rs @@ -0,0 +1,267 @@ +//! DNG `ProfileGainTableMap` (tag 52525, DNG 1.6) and `ProfileGainTableMap2` (tag 52544, DNG 1.7): +//! a coarse grid of 1D gain tables carrying the maker's local tone mapping. Apple ProRAW has one. +//! +//! We read and write the tag (a DNG export keeps it) but don't render it by default: Lightroom +//! Classic renders Apple ProRAW without the map (see `crate::profile`), and so do we. The photo's +//! "camera local tone mapping" option renders it ([`GainTableMap::gain`], applied by the pipeline), +//! as the camera itself does. +//! +//! Applying it (DNG 1.7.1, `ProfileGainTableMap` → "Description"): +//! +//! - the four tables around a position are interpolated bilinearly; outside the grid the edge +//! tables are replicated. Positions are relative to the active area at pixel centres; +//! - the table input `clamp((R, G, B, min, max) · weights, 0, 1) ^ gamma` is computed in linear +//! RIMM (ProPhoto) after the baseline exposure; +//! - the gain is the table looked up linearly at `input × MapPointsN` ("multiply the table input +//! value by MapPointsN to compute the floating-point table index"), clamped to the last point, +//! and multiplies R, G and B. Results may exceed 1 and aren't clipped. +//! +//! - The grid has `MapPointsV × MapPointsH` tables of `MapPointsN` gains. Its origin and spacing +//! are relative to the active area (1.0 = the active area's height or width). +//! - The table input is the dot product of (R, G, B, min, max) with the tag's five weights; +//! version 2 then raises it to the tag's `Gamma`. +//! - Version 2 stores gains as u8 or u16 (mapped linearly onto `GainMin..=GainMax`), f16 or f32. +//! It takes precedence over version 1 when both are present. +//! +//! Malformed tags are ignored: a wrong size, zero or huge dimensions, non-finite or negative gains, +//! non-positive spacing, or gamma outside 0.25..=4. +//! +//! Byte order: the tag's fields are TIFF types (LONG, DOUBLE, FLOAT, …), and neither DNG 1.6 nor +//! 1.7.1 gives this tag a byte order of its own, as they do for opcode lists and +//! `OriginalRawFileData` (always big-endian). What applies is the general rule of the DNG 1.6 +//! specification ("DNG Format Overview" → "Byte Order", worded the same in 1.7.1): +//! +//! > DNG readers are required to support either byte order, even for files from a particular +//! > camera model. +//! +//! (, "DNG Specification".) So we read +//! the fields in the file's byte order, and fall back to big-endian for writers that followed the +//! opcode-list convention. A read in the wrong order can't pass for a valid map: one of +//! `MapPointsV` / `MapPointsH` is below 256 (their product is at most `MAX_TABLES`), so swapped +//! it is at least 2^24 and the size checks reject it. We write in the file's byte order. + +pub use craft_raw::gaintable::GainTableMap; +use serde::{Deserialize, Serialize}; + +/// Applying a gain table map (the map, and reading and writing its tag, is `craft-raw`'s). +pub trait GainTableMapApply { + /// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM) + /// colour after the baseline exposure. 1.0 for a map that can't be evaluated. For many pixels, + /// [`Self::evaluator`] once and [`GainEval::gain`] per pixel. + fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32; + /// The map ready to evaluate per pixel, or `None` when it can't be (inconsistent sizes). + fn evaluator(&self) -> Option>; +} + +/// Applying the map (see the module docs). Index arithmetic saturates and every lookup is +/// checked: the fields are public and the struct is deserializable, so a hand-built or damaged map +/// must not overflow or panic, whatever it holds. +impl GainTableMapApply for GainTableMap { + /// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM) + /// colour after the baseline exposure. 1.0 for a map that can't be evaluated. For many pixels, + /// [`Self::evaluator`] once and [`GainEval::gain`] per pixel. + fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 { + self.evaluator().map_or(1.0, |e| e.gain(p, x, y)) + } + + /// The map ready to evaluate per pixel, or `None` when it can't be (inconsistent sizes). + fn evaluator(&self) -> Option> { + let n = self.points_n; + let tables = self.points_v.saturating_mul(self.points_h); + if n == 0 || tables == 0 || tables.saturating_mul(n) != self.gains.len() { + return None; + } + let axis = |points: usize, origin: f64, spacing: f64| Axis { + last: points.saturating_sub(1), + origin, + // (a degenerate axis replicates its first table) + inv: if points > 1 && spacing.is_finite() && spacing > 0.0 { 1.0 / spacing } else { 0.0 }, + }; + Some(GainEval { map: self, v: axis(self.points_v, self.origin_v, self.spacing_v), h: axis(self.points_h, self.origin_h, self.spacing_h) }) + } +} + +/// One grid axis, prepared: last table index, origin and inverse spacing (0: one table). +#[derive(Clone, Copy, Debug)] +struct Axis { + last: usize, + origin: f64, + inv: f64, +} + +impl Axis { + /// The cell at relative position `pos`: (first table, second table, weight of the second). + /// Outside the grid the edge table is replicated. + #[inline] + fn cell(self, pos: f64) -> (usize, usize, f32) { + if self.last == 0 || self.inv == 0.0 { + return (0, 0, 0.0); + } + let f = (pos - self.origin) * self.inv; + let f = if f.is_nan() { 0.0 } else { f.clamp(0.0, self.last as f64) }; + // (≥ 0: `as` truncates like `floor`, which isn't inlined on baseline x86-64) + let i0 = (f as usize).min(self.last); + let i1 = i0.saturating_add(1).min(self.last); + (i0, i1, (f - i0 as f64) as f32) + } +} + +/// Grid cell along one axis (see [`Axis::cell`]). +#[cfg(test)] +fn cell(pos: f64, origin: f64, spacing: f64, points: usize) -> (usize, usize, f32) { + let inv = if points > 1 && spacing.is_finite() && spacing > 0.0 { 1.0 / spacing } else { 0.0 }; + Axis { last: points.saturating_sub(1), origin, inv }.cell(pos) +} + +/// A [`GainTableMap`] prepared for evaluating many pixels. +#[derive(Clone, Copy, Debug)] +pub struct GainEval<'a> { + map: &'a GainTableMap, + v: Axis, + h: Axis, +} + +impl GainEval<'_> { + /// [`GainTableMapApply::gain`]. + #[inline] + pub fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 { + let m = self.map; + let (v0, v1, fv) = self.v.cell(y); + let (h0, h1, fh) = self.h.cell(x); + // one fractional index for the four tables (≥ 0, so `as` truncates) + let n = m.points_n; + let last = n - 1; + let idx = (input(m, p) * n as f32).min(last as f32); + let i0 = (idx as usize).min(last); + let i1 = i0.saturating_add(1).min(last); + let t = idx - i0 as f32; + // (v ≤ points_v − 1, h ≤ points_h − 1 and i ≤ n − 1, with points_v·points_h·n = gains.len() + // checked by `evaluator`: none of this overflows, and `get` still guards each read) + let at = |v: usize, h: usize| { + let table = m.gains.get((v * m.points_h + h) * n..).unwrap_or(&[]); + let g0 = table.get(i0).copied().unwrap_or(1.0); + let g1 = table.get(i1).copied().unwrap_or(1.0); + g0 + (g1 - g0) * t + }; + let (a, b, c, d) = (at(v0, h0), at(v0, h1), at(v1, h0), at(v1, h1)); + let top = a + (b - a) * fh; + let bottom = c + (d - c) * fh; + let g = top + (bottom - top) * fv; + if g.is_finite() { g.max(0.0) } else { 1.0 } + } +} + +/// The table input for `p` (linear ProPhoto, after the baseline exposure). +#[inline] +fn input(m: &GainTableMap, p: [f32; 3]) -> f32 { + let w = &m.weights; + let lo = p[0].min(p[1]).min(p[2]); + let hi = p[0].max(p[1]).max(p[2]); + let x = w[0] * p[0] + w[1] * p[1] + w[2] * p[2] + w[3] * lo + w[4] * hi; + let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }; + if m.gamma == 1.0 { x } else { x.powf(m.gamma) } +} + +/// Where the pixels of a developed source sit in the raw's active area, for [`GainTableMapApply::gain`]. +/// The source is the default crop of the active area (`rect`, relative to the active area), +/// then EXIF-`orientation`ed. Resolution independent. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct SourcePlacement { + /// x, y, width, height of the developed crop, relative to the active area. + pub rect: [f64; 4], + /// The EXIF orientation applied to the developed crop. + pub orientation: craft_geom::Orientation, +} + +impl SourcePlacement { + /// Relative active-area position of normalized (0..1) coordinates of the oriented source. + pub fn active(&self, u: f64, v: f64) -> (f64, f64) { + let (u, v) = self.orientation.inverse().map(u, v, 1.0, 1.0); + let [x, y, w, h] = self.rect; + (x + u * w, y + v * h) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn map(dims: [usize; 3], spacing: [f64; 2], origin: [f64; 2], weights: [f32; 5], gains: Vec) -> GainTableMap { + let [points_v, points_h, points_n] = dims; + let [spacing_v, spacing_h] = spacing; + let [origin_v, origin_h] = origin; + GainTableMap { points_v, points_h, points_n, spacing_v, spacing_h, origin_v, origin_h, weights, gamma: 1.0, gains } + } + + const LUMA: [f32; 5] = [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0, 0.0, 0.0]; + + #[test] + fn gain_follows_the_table_input_at_input_times_n() { + // one table of 3 points: index = input × 3 (DNG 1.7.1), clamped to the last point + let m = map([1, 1, 3], [1.0, 1.0], [0.0, 0.0], LUMA, vec![1.0, 2.0, 3.0]); + assert_eq!(m.gain([0.0; 3], 0.5, 0.5), 1.0); + assert!((m.gain([1.0 / 3.0; 3], 0.5, 0.5) - 2.0).abs() < 1e-5, "index 1"); + assert!((m.gain([1.0 / 6.0; 3], 0.5, 0.5) - 1.5).abs() < 1e-5, "index 0.5: linear in the table"); + assert!((m.gain([0.9; 3], 0.5, 0.5) - 3.0).abs() < 1e-5, "index 2.7 clamps to the last point"); + // min/max weights and gamma: input = max(R, G, B)², two points + let mut m = map([1, 1, 2], [1.0, 1.0], [0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0], vec![1.0, 3.0]); + m.gamma = 2.0; + // max 0.5 → 0.25 → index 0.5 → ×2 + assert!((m.gain([0.1, 0.5, 0.2], 0.0, 0.0) - 2.0).abs() < 1e-5); + } + + #[test] + fn tables_interpolate_across_the_grid_and_replicate_at_the_edges() { + // 1 × 2 constant tables at x = 0.25 (×1) and x = 0.75 (×3) + let m = map([1, 2, 1], [1.0, 0.5], [0.0, 0.25], LUMA, vec![1.0, 3.0]); + let g = |x: f64| m.gain([0.2; 3], x, 0.5); + assert!((g(0.25) - 1.0).abs() < 1e-5 && (g(0.5) - 2.0).abs() < 1e-5 && (g(0.75) - 3.0).abs() < 1e-5); + assert!((g(0.0) - 1.0).abs() < 1e-5 && (g(1.0) - 3.0).abs() < 1e-5); + assert!((g(-10.0) - 1.0).abs() < 1e-5 && (g(10.0) - 3.0).abs() < 1e-5); + // vertically too: 2 × 1 at y = 0 (×1) and y = 1 (×2) + let m = map([2, 1, 1], [1.0, 1.0], [0.0, 0.0], LUMA, vec![1.0, 2.0]); + assert!((m.gain([0.2; 3], 0.5, 0.25) - 1.25).abs() < 1e-5); + } + + #[test] + fn hand_built_maps_never_panic() { + // review on #273: `(i0 + 1).min(points - 1)` overflowed for points_v = usize::MAX at +inf + let mut m = map([usize::MAX, 1, 1], [1.0, 1.0], [0.0, 0.0], LUMA, vec![2.0]); + assert_eq!(m.gain([0.5; 3], 0.5, f64::INFINITY), 1.0, "inconsistent sizes: no gain"); + for (v, h, n, len) in [(usize::MAX, 1, 1, 1), (1, usize::MAX, usize::MAX, 3), (0, 0, 0, 0), (2, 2, 0, 0), (1, 1, 2, 1)] { + m.points_v = v; + m.points_h = h; + m.points_n = n; + m.gains = vec![2.0; len]; + for spacing in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e-300] { + m.spacing_v = spacing; + m.spacing_h = spacing; + for p in [[0.5; 3], [f32::NAN; 3], [f32::INFINITY, 0.0, -1.0], [1e30; 3]] { + for (x, y) in [(0.5, 0.5), (f64::INFINITY, f64::NEG_INFINITY), (f64::NAN, f64::NAN)] { + assert!(m.gain(p, x, y).is_finite()); + } + } + } + } + // the grid cell itself saturates (the reviewer's case, reached directly) + assert_eq!(cell(f64::INFINITY, 0.0, 1.0, usize::MAX), (usize::MAX - 1, usize::MAX - 1, 0.0)); + assert_eq!(cell(f64::NEG_INFINITY, 0.0, 1.0, usize::MAX).0, 0); + // a consistent map with a huge grid and positions far outside it + let m = map([1, 1, 2], [1e-300, 1e-300], [0.0, 0.0], [f32::MAX; 5], vec![1.0, 4.0]); + assert!(m.gain([1e30; 3], f64::INFINITY, -f64::INFINITY).is_finite()); + } + + #[test] + fn placement_undoes_crop_and_orientation() { + // the source is the right half of the active area, rotated 90° clockwise + let p = SourcePlacement { rect: [0.5, 0.0, 0.5, 1.0], orientation: craft_geom::Orientation::Rotate90 }; + // the oriented source's top-left came from the crop's bottom-left + let (x, y) = p.active(0.0, 0.0); + assert!((x - 0.5).abs() < 1e-12 && (y - 1.0).abs() < 1e-12, "{x} {y}"); + // its top-right came from the crop's top-left + let (x, y) = p.active(1.0, 0.0); + assert!((x - 0.5).abs() < 1e-12 && y.abs() < 1e-12, "{x} {y}"); + let plain = SourcePlacement { rect: [0.0, 0.0, 1.0, 1.0], orientation: craft_geom::Orientation::Normal }; + assert_eq!(plain.active(0.25, 0.75), (0.25, 0.75)); + } +} diff --git a/crates/develop/src/sensor/highlight.rs b/crates/develop/src/sensor/highlight.rs new file mode 100644 index 0000000000..50732bf38c --- /dev/null +++ b/crates/develop/src/sensor/highlight.rs @@ -0,0 +1,633 @@ +//! Clip-aware highlight handling on demosaiced camera RGB (before white balance, white level = 1.0). +//! +//! - [`clip_neutral`]: white-balance-aware clipping so that sensor-clipped areas render neutral instead of +//! magenta/cyan (each channel limited to the smallest white-balanced clip level). +//! - [`reconstruct`] / [`reconstruct_with`]: where only some channels are clipped, rebuild them from the +//! unclipped channels using the chromaticity of reliable unclipped content nearby (bright, away from edges and +//! from the clipped pixels themselves; diffused into the clipped region coarse to fine) unless both the pixel's +//! own channels and the clipped surface's colour just below its clip (the rim) contradict it, and neutral where +//! there is none within reach. Right past the rim, the rim's colour carries on. Fully clipped pixels become +//! neutral at the brightest plausible level; partly clipped ones fade into it on their way from the first channel +//! clipping to the last, pale ones from the start. +//! - [`reconstruct_masked`]: also uses clipping information from the original mosaic, for binned and full-size images. +//! +//! Why the care: the white-balance gains push clipped channels apart (green clips first, red and blue keep +//! rising), so whatever colour the rebuilt pixels carry is hidden at Neutral only by the tone map's roll-off to +//! white. Any darkening (Highlights, negative Exposure or Whites) brings it out. Three things used to leak colour +//! in: the chromaticity of whatever unclipped pixel happened to be nearest (dark foliage, purple and green +//! fringes along branches, pixels demosaiced from clipped neighbours); a colour model that does not render the +//! camera's white-balanced neutral as neutral (a look fitted to the camera's JPEG, a camera profile); and, in a +//! pale partly clipped sky, the colour of another reliable surface (bright foliage) and the sky's own faint +//! colour, which darkening and a camera profile turned teal. + +use crate::raster::{Rgb32f, par_rows}; +#[cfg(not(target_arch = "wasm32"))] +use rayon::prelude::*; + +/// Clip every channel of `wb ⊙ img` at `min_c(wb_c) · clip` — i.e. at the lowest channel's clip level after WB — +/// then divide the multipliers back out. `clip` is the sensor clip in normalised units (≈ 1.0). +pub fn clip_neutral(img: &mut Rgb32f, wb: [f32; 3], clip: f32) { + let limit = wb.iter().cloned().fold(f32::MAX, f32::min) * clip; + for p in &mut img.data { + for c in 0..3 { + p[c] = (p[c] * wb[c]).min(limit) / wb[c]; + } + } +} + +/// Unclipped pixels lend their chromaticity in proportion to how close they come to clipping (their largest +/// channel, relative to the clip level): from nothing below `SOURCE_LO` to fully above `SOURCE_HI`. Dark content +/// (foliage, branches, buildings against a clipped sky) says nothing about the sky's colour. +const SOURCE_LO: f32 = 0.25; +const SOURCE_HI: f32 = 0.6; +/// Sources on a strong edge (a 3 × 3 half-resolution neighbour brighter or darker by this many stops) are +/// left out, fading from `EDGE_LO` to `EDGE_HI`: edge pixels mix two surfaces and carry lens fringes. +const EDGE_LO: f32 = 0.15; +const EDGE_HI: f32 = 0.4; +/// Source cells within this many half-resolution cells of a clipped pixel are left out: their channels were +/// demosaiced partly from clipped samples. (At least 1: the same neighbourhood tells which cells clipped +/// pixels sample.) +const MARGIN: usize = 1; +/// Weight of the coarser estimate against a cell's own sources when the pyramid is pushed back down (in units +/// of source density: a cell half covered by full-weight sources counts 0.5). +const PRIOR: f32 = 0.01; +/// The rebuilt colour fades to neutral where reliable content covers less than `SUPPORT` of the surroundings at +/// every scale up to `REACH` of the long edge (so previews and exports agree), gradually, as the coverage of the +/// widest one falls: a clipped sky between bare branches is better white than the colour of a river far away. +const REACH: f32 = 1.0 / 4.0; +const SUPPORT: f32 = 0.05; +/// An unclipped channel above `FLOOR_LO` of its clip level counts more and more as the clip floor it is about to +/// become (see [`reconstruct_with`]). +const FLOOR_LO: f32 = 0.75; +/// A clipped pixel takes its estimated colour (reliable colour around, or the neutral guess) only as far as it is +/// brighter (or otherwise unlike) the unclipped pixels nearest its clip: the "rim", unclipped pixels above `RIM_LO` +/// of the clip level, weighted towards the clip, the clipped surface's own colour just below it. Up to `NEAR_RIM` +/// stops past the rim (the rim is an average, a little below the clip) it is rebuilt with the rim's colour, and +/// over the next `DEPTH` stops it goes over to the estimate, so a surface runs into clipping without a step +/// whatever its colour and whatever lent the estimate; well past it, or where the rim is another surface (its +/// colour differs; a clipped channel differs by at least as much as it lies above the rim's), the estimate applies. +const RIM_LO: f32 = 0.85; +const NEAR_RIM: f32 = 0.03; +const DEPTH: f32 = 0.2; +/// Reliable colour counts less and less as both the pixel's own channels (see [`contradiction`]) and the rim's +/// colour contradict it, by `AGREE.0` to `AGREE.1` stops: it is another surface's, like bright foliage below a pale +/// sky, whose green would turn the sky teal. (Either alone can be wrong: a pixel's own channels are noisy and +/// can't speak for the channels that clipped, and the rim can be another surface, like a white window frame +/// around a bright view.) +const AGREE: (f32, f32) = (0.15, 0.4); +/// On the way from the first channel clipping to the last, a partly clipped pixel's brightness goes over to the +/// clipped neutral's in the second half, and so does the colour of a strongly coloured one (saturation relative to +/// the white above `PALE.1`). A pale one's colour (below `PALE.0`) goes over from the start: the few per cent of +/// colour left in a pale sky once a channel clipped is as much the estimate's error as the sky's, and darkening +/// shows it. +const PALE: (f32, f32) = (0.2, 0.4); +/// Minimum brightness ratio against reconstruction by value. Its inverse limits brightening in saturated colours. +const CONTINUITY: f32 = 0.8; +/// Weights for comparing white-balanced brightness. +const LUMA: [f32; 3] = [0.2126, 0.7152, 0.0722]; + +#[inline] +fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// One level of a pyramid, `w × h` cells of `N - 1` values and a weight. Pulled: per cell the weighted sums of +/// the values and the weight, as densities (per pixel of the cell). Pushed: the estimated values, and still the +/// weight. The chromaticity pyramid holds red and blue chromaticity, the rim pyramid white-balanced RGB. +struct Level { + w: usize, + h: usize, + cells: Vec<[f32; N]>, +} + +/// Bilinear sample of a level at the centre of pixel `(x, y)` of a grid `scale` times finer. +#[inline] +fn sample(l: &Level, scale: f32, x: usize, y: usize) -> [f32; N] { + let (cv, cw, ch) = (&l.cells, l.w, l.h); + let fx = ((x as f32 + 0.5) / scale - 0.5).clamp(0.0, cw.saturating_sub(1) as f32); + let fy = ((y as f32 + 0.5) / scale - 0.5).clamp(0.0, ch.saturating_sub(1) as f32); + let (x0, y0) = (fx.floor() as usize, fy.floor() as usize); + let (x1, y1) = ((x0 + 1).min(cw.saturating_sub(1)), (y0 + 1).min(ch.saturating_sub(1))); + let (tx, ty) = (fx - x0 as f32, fy - y0 as f32); + let g = |xx: usize, yy: usize| cv.get(yy * cw + xx).copied().unwrap_or([0.0; N]); + let (a, b, c, d) = (g(x0, y0), g(x1, y0), g(x0, y1), g(x1, y1)); + std::array::from_fn(|k| { + let top = a[k] + (b[k] - a[k]) * tx; + let bot = c[k] + (d[k] - c[k]) * tx; + top + (bot - top) * ty + }) +} + +/// The half-resolution source level of `img`: every `2 × 2` block's source-weighted chromaticity sums, with +/// blocks near clipped pixels or on strong edges left out. Also returns, per cell, whether a clipped pixel lies +/// in its row within [`MARGIN`] cells (the vertical half of that test is left to the readers). +fn sources(img: &Rgb32f, wb: [f32; 3], clip: f32, clipped: &impl Clipped) -> (Level<3>, Vec) { + let (w, h) = (img.width, img.height); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + // per cell: [red sum, blue sum, weight] densities, luminance, whether it holds a clipped pixel + let mut cells = vec![[0f32; 3]; cw * ch]; + let mut lum = vec![0f32; cw * ch]; + let mut near = vec![false; cw * ch]; + let process_row = |y: usize, crow: &mut [[f32; 3]], lrow: &mut [f32], nrow: &mut [bool]| { + let mut touched = vec![false; cw]; + let row = |r: usize| img.data.get(r * w..(r + 1) * w).unwrap_or(&[]); + let (r0, r1) = (row(2 * y), row(2 * y + 1)); + let lo = SOURCE_LO * clip; + for x in 0..cw { + let (mut a, mut sum, mut n, mut hit) = ([0f32; 3], 0f32, 0usize, false); + let span = 2 * x..(2 * x + 2).min(w); + let (i0, i1) = (2 * y * w + 2 * x, (2 * y + 1) * w + 2 * x); + let pixels = r0.get(span.clone()).unwrap_or(&[]).iter().zip(i0..).chain(r1.get(span).unwrap_or(&[]).iter().zip(i1..)); + for (p, i) in pixels { + let q = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]; + let s = q[0].max(0.0) + q[1].max(0.0) + q[2].max(0.0); + sum += s; + n += 1; + let top = p[0].max(p[1]).max(p[2]); + if clipped(i, p).iter().any(|&c| c) { + hit = true; + continue; + } + if top > lo && s > 1e-4 { + let b = smoothstep(SOURCE_LO, SOURCE_HI, top / clip) / s; + a[0] += b * q[0].max(0.0); + a[1] += b * q[2].max(0.0); + a[2] += b * s; + } + } + let k = 1.0 / n.max(1) as f32; + crow[x] = a.map(|v| v * k); + lrow[x] = (sum * k).max(1e-6); + touched[x] = hit; + } + for (x, nr) in nrow.iter_mut().enumerate() { + *nr = touched.get(x.saturating_sub(MARGIN)..=(x + MARGIN).min(cw - 1)).is_some_and(|t| t.iter().any(|&t| t)); + } + }; + #[cfg(not(target_arch = "wasm32"))] + cells.par_chunks_mut(cw).zip(lum.par_chunks_mut(cw)).zip(near.par_chunks_mut(cw)).enumerate().for_each(|(y, ((crow, lrow), nrow))| { + process_row(y, crow, lrow, nrow); + }); + #[cfg(target_arch = "wasm32")] + for (y, ((crow, lrow), nrow)) in cells.chunks_mut(cw).zip(lum.chunks_mut(cw)).zip(near.chunks_mut(cw)).enumerate() { + process_row(y, crow, lrow, nrow); + } + // leave out cells near clipped pixels and on strong edges (luminance ratios to the neighbours) + let (lum, near_ref) = (&lum, &near); + let (edge_lo, edge_hi) = (EDGE_LO.exp2(), EDGE_HI.exp2()); + par_rows(&mut cells, cw, |y, row| { + let (ya, yb) = (y.saturating_sub(MARGIN), (y + MARGIN).min(ch - 1)); + let (ea, eb) = (y.saturating_sub(1), (y + 1).min(ch - 1)); + for (x, cell) in row.iter_mut().enumerate() { + if cell[2] <= 0.0 { + continue; + } + if (ya..=yb).any(|yy| near_ref.get(yy * cw + x).copied().unwrap_or(false)) { + *cell = [0.0; 3]; + continue; + } + let l = lum.get(y * cw + x).copied().unwrap_or(1.0); + let (xa, xb) = (x.saturating_sub(1), (x + 1).min(cw - 1)); + let (mut lo, mut hi) = (l, l); + for yy in ea..=eb { + for &v in lum.get(yy * cw + xa..=yy * cw + xb).unwrap_or(&[]) { + lo = lo.min(v); + hi = hi.max(v); + } + } + let keep = 1.0 - smoothstep(edge_lo, edge_hi, (hi / l).max(l / lo)); + *cell = cell.map(|v| v * keep); + } + }); + (Level { w: cw, h: ch, cells }, near) +} + +/// The quarter-resolution rim level of `img`: every `4 × 4` block's white-balanced RGB of its unclipped pixels +/// above [`RIM_LO`] of the clip level, weighted (steeply) towards the clip, as densities. Pixels next to clipped +/// ones (`margin`, by half-resolution cell) are left out, like the colour sources: they were demosaiced partly from +/// clipped samples, and lens fringes along clipped content would pass for its colour. +fn rim(img: &Rgb32f, wb: [f32; 3], clip: f32, clipped: &impl Clipped, margin: &(dyn Fn(usize, usize) -> bool + Sync)) -> Level<4> { + let (w, h) = (img.width, img.height); + let (cw, ch) = (w.div_ceil(4), h.div_ceil(4)); + let mut cells = vec![[0f32; 4]; cw * ch]; + par_rows(&mut cells, cw, |y, row| { + for (x, cell) in row.iter_mut().enumerate() { + let (mut a, mut n) = ([0f32; 4], 0usize); + for sy in 4 * y..(4 * y + 4).min(h) { + for (i, p) in img.data.get(sy * w + 4 * x..sy * w + (4 * x + 4).min(w)).unwrap_or(&[]).iter().enumerate() { + n += 1; + let top = p[0].max(p[1]).max(p[2]) / clip; + if !(RIM_LO..1.0).contains(&top) || margin((4 * x + i) / 2, sy / 2) || clipped(sy * w + 4 * x + i, p).iter().any(|&c| c) { + continue; + } + let k = ((top - RIM_LO) / (1.0 - RIM_LO)).powi(4); + for c in 0..3 { + a[c] += k * p[c] * wb[c]; + } + a[3] += k; + } + } + *cell = a.map(|v| v / n.max(1) as f32); + } + }); + Level { w: cw, h: ch, cells } +} + +/// The next coarser level: each `2 × 2` block's mean densities. +fn pull(l: &Level) -> Level { + let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2)); + let mut cells = vec![[0f32; N]; w * h]; + par_rows(&mut cells, w, |y, row| { + for (x, cell) in row.iter_mut().enumerate() { + let (mut s, mut n) = ([0f32; N], 0usize); + for (sx, sy) in [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)] { + if let Some(c) = (sx < l.w && sy < l.h).then(|| l.cells.get(sy * l.w + sx)).flatten() { + for k in 0..N { + s[k] += c[k]; + } + n += 1; + } + } + *cell = s.map(|v| v / n.max(1) as f32); + } + }); + Level { w, h, cells } +} + +/// The estimated values of the cells of `levels[0]` that `needed` marks (all of them when `None`), and of every +/// cell of the coarser levels: each level's own sources blended with the next coarser estimate. The top level is +/// its own sources' weighted mean (normalised: however sparse they are in a large empty picture, the empty part +/// never pulls the estimate anywhere), and `empty` (at zero weight) when it has none at all. +fn push(levels: &mut [Level], empty: [f32; N], needed: Option<&(dyn Fn(usize, usize) -> bool + Sync)>) { + let estimate = |cell: [f32; N], prior: [f32; N]| -> [f32; N] { + let weight = cell[N - 1]; + let d = weight + PRIOR; + std::array::from_fn(|k| if k + 1 == N { weight } else { (cell[k] + PRIOR * prior[k]) / d }) + }; + let Some(last) = levels.last_mut() else { return }; + last.cells.iter_mut().for_each(|c| { + let weight = c[N - 1]; + *c = if weight > 0.0 { std::array::from_fn(|k| if k + 1 == N { weight } else { c[k] / weight }) } else { empty }; + }); + for i in (0..levels.len().saturating_sub(1)).rev() { + let (fine, coarse) = levels.split_at_mut(i + 1); + let (Some(fine), Some(coarse)) = (fine.last_mut(), coarse.first()) else { continue }; + let w = fine.w; + let needed = needed.filter(|_| i == 0); + par_rows(&mut fine.cells, w, |y, row| { + for (x, cell) in row.iter_mut().enumerate() { + if needed.is_some_and(|f| !f(x, y)) { + continue; + } + *cell = estimate(*cell, sample(coarse, 2.0, x, y)); + } + }); + } +} + +/// How many stops two chromaticities differ by in any channel ratio. +fn unlike(a: [f32; 3], b: [f32; 3]) -> f32 { + let ratio = |i: usize, j: usize| (a[i].max(1e-6) * b[j].max(1e-6)) / (a[j].max(1e-6) * b[i].max(1e-6)); + [(0, 1), (0, 2), (1, 2)].iter().map(|&(i, j)| ratio(i, j).log2().abs()).fold(0.0f32, f32::max) +} + +/// How far channel `c` of a pixel (sensor values `p`, clipped channels `cl`) only bounds its true value from below: +/// fully once clipped, and increasingly from `FLOOR_LO` of the clip on, so that nothing compared with it jumps where +/// it clips. +fn bound(p: [f32; 3], cl: [bool; 3], clip: f32, c: usize) -> f32 { + if cl[c] { 1.0 } else { smoothstep(FLOOR_LO, 1.0, p[c] / clip) } +} + +/// How many stops a pixel's channels contradict chromaticity `r`. A saturated channel sets a lower bound. +/// Channels with unknown values do not constrain the estimate. +fn contradiction(p: [f32; 3], q: [f32; 3], clipping: Clipping, r: [f32; 3], clip: f32) -> f32 { + let (mut lo, mut hi) = (f32::INFINITY, 0f32); + for c in 0..3 { + if clipping.unknown(c) { + continue; + } + let level = q[c] / r[c].max(1e-3); + hi = hi.max(level); + let w = bound(p, clipping.clipped, clip, c); + if r[c] > 1e-3 && w < 1.0 { + lo = lo.min(level / (1.0 - w)); + } + } + if hi > 0.0 && lo > 0.0 && lo.is_finite() { (hi / lo).log2().max(0.0) } else { 0.0 } +} + +/// Rebuild a pixel at chromaticity `r` using its known, unclipped channels to estimate the level. +/// Keep those channels and use saturated values as lower bounds. +fn rebuild(p: [f32; 3], q: [f32; 3], clipping: Clipping, r: [f32; 3], clip: f32, max_level: f32) -> Option<[f32; 3]> { + // The white-balanced channel sum the unclipped channels imply: their mean, except that a channel about to clip + // counts more and more as the floor it is about to become (continuous with the neighbours where it has). + let (mut sum, mut near_clip, mut k) = (0f32, 0f32, 0usize); + for c in 0..3 { + if !clipping.clipped[c] && r[c] > 1e-3 { + let s = q[c] / r[c]; + sum += s; + near_clip = near_clip.max(s * smoothstep(FLOOR_LO, 1.0, p[c] / clip)); + k += 1; + } + } + if k == 0 { + return None; + } + // Two clipped channels must not be left at their clip levels: those differ by the white-balance gains (green + // clips first), and the pair would show as magenta or red. They keep the estimate's ratio instead, at the level + // that lifts each to its clip (no channel above the clipped neutral), and so does a channel about to clip (the + // same floor, so nothing jumps where it clips). + let floor = (0..3).filter(|&c| clipping.saturated[c]).map(|c| q[c] / r[c].max(1e-3)).fold(0.0f32, f32::max); + let top = r[0].max(r[1]).max(r[2]).max(1e-3); + let sum = (sum / k as f32).max(near_clip.max(floor).min(max_level / top)); + Some(std::array::from_fn(|c| match (clipping.clipped[c], clipping.saturated[c]) { + (true, true) => q[c].max(sum * r[c]), + (true, false) => sum * r[c], + _ => q[c], + })) +} + +/// Reconstruct partially clipped channels, with a neutral that is neutral in camera RGB. See +/// [`reconstruct_with`]. +pub fn reconstruct(img: &mut Rgb32f, wb: [f32; 3], clip: f32) -> usize { + reconstruct_with(img, wb, clip, [1.0; 3]) +} + +/// Reconstruct partially clipped channels. `clip` is the sensor clip level in normalised units (use slightly +/// below 1.0, e.g. 0.99), `wb` the white-balance multipliers that will be applied afterwards, `white` the +/// white-balanced camera RGB that the colour model applied afterwards renders neutral (`[1, 1, 1]` for a model +/// that maps the white-balanced neutral to neutral), scaled to the brightness that `[1, 1, 1]` renders at. +/// Fully clipped pixels become `white` times the brightest plausible level; partly clipped ones take the +/// chromaticity of reliable unclipped content nearby, and that of `white` where there is none. +/// Returns the number of pixels that had at least one clipped channel; the others are left exactly as they were. +pub fn reconstruct_with(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3]) -> usize { + rebuild_clipped(img, wb, clip, white, &|_, p| Clipping::from_values(p, clip)) +} + +/// Bits of a [`reconstruct_masked`] mask entry: which channels of the pixel had a clipped sample (saturated: their +/// value is a lower bound of the true one). +pub const CLIPPED_R: u8 = 1; +pub const CLIPPED_G: u8 = 2; +pub const CLIPPED_B: u8 = 4; +/// Bits of a [`reconstruct_masked`] mask entry for the colours of nearby clipped samples that can affect interpolation. +/// In a directional mask, a clipped sample of the measured colour can still affect the interpolated channels. +pub const FROM_CLIPPED_R: u8 = 8; +pub const FROM_CLIPPED_G: u8 = 16; +pub const FROM_CLIPPED_B: u8 = 32; +/// Bits 6 and 7 of a directional [`reconstruct_masked`] mask entry: the measured colour plus one. +/// Binned and bilinear masks leave this field at zero. +pub const MEASURED_SHIFT: u8 = 6; + +pub(super) const CLIPPED_BITS: [u8; 3] = [CLIPPED_R, CLIPPED_G, CLIPPED_B]; +pub(super) const FROM_CLIPPED_BITS: [u8; 3] = [FROM_CLIPPED_R, FROM_CLIPPED_G, FROM_CLIPPED_B]; + +/// [`reconstruct_with`] for a binned image ([`super::RawDevelopExt::develop_binned_masked`]): its values are block +/// means, and `mask` (one entry per pixel, bits [`CLIPPED_R`], [`CLIPPED_G`], [`CLIPPED_B`]) says which colours +/// had a clipped sample in the block. Those channels count as clipped with their mean as the lower bound of their +/// true value, so one clipped specular sample among many unclipped ones neither escapes reconstruction nor +/// (as the block's maximum would) lifts the channel to the clip level, which reads as a coloured speckle (#548). +/// +/// For a full-size demosaic ([`super::RawDevelopExt::develop_balanced_masked`]), the mask records the colours +/// of clipped samples that can affect interpolation. In a directional mask, it also records the measured +/// colour so reconstruction can treat only the interpolated channels below clip as unknown. A dependency on the +/// measured colour alone triggers that treatment when every channel is below clip. This preserves partly clipped +/// detail when another channel is already saturated. A bilinear mask marks each interpolated channel separately. +/// Interpolated values at or above clip still count as lower bounds. +/// Reconstruction uses the known channels and limits brightness changes near strongly coloured highlights. +/// +/// A mask of the wrong length is ignored (clipping is then told by the values alone). +pub fn reconstruct_masked(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], mask: &[u8]) -> usize { + if mask.len() != img.data.len() { + return reconstruct_with(img, wb, clip, white); + } + rebuild_clipped(img, wb, clip, white, &|i, p| masked(mask[i], p, clip)) +} + +#[derive(Clone, Copy)] +struct Clipping { + /// Channels to rebuild, including saturated channels and interpolated values of unknown accuracy. + clipped: [bool; 3], + saturated: [bool; 3], +} + +impl Clipping { + fn from_values(p: &[f32; 3], clip: f32) -> Self { + let saturated = p.map(|v| v >= clip); + Self { clipped: saturated, saturated } + } + + fn unknown(self, c: usize) -> bool { + self.clipped[c] && !self.saturated[c] + } +} + +#[inline] +fn masked(m: u8, p: &[f32; 3], clip: f32) -> Clipping { + let bit = |b: u8| m & b != 0; + let saturated = std::array::from_fn(|c| p[c] >= clip || bit(CLIPPED_BITS[c])); + let mut unknown: [bool; 3] = std::array::from_fn(|c| bit(FROM_CLIPPED_BITS[c]) && !saturated[c]); + if let Some(own) = ((m >> MEASURED_SHIFT) as usize).checked_sub(1).filter(|&c| !saturated[c]) { + let from_measured_colour = std::mem::take(&mut unknown[own]); + if unknown.iter().any(|&u| u) || (from_measured_colour && !saturated.iter().any(|&c| c)) { + unknown = std::array::from_fn(|c| c != own && !saturated[c]); + } + } + Clipping { clipped: std::array::from_fn(|c| saturated[c] || unknown[c]), saturated } +} + +/// Which channels of pixel `i` (values `p`) need to be rebuilt. +trait Clipped: Fn(usize, &[f32; 3]) -> [bool; 3] + Sync {} +impl [bool; 3] + Sync> Clipped for F {} + +fn rebuild_clipped(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], classify: &(impl Fn(usize, &[f32; 3]) -> Clipping + Sync)) -> usize { + let (w, h) = (img.width, img.height); + let clipped = |i, p: &[f32; 3]| classify(i, p).clipped; + #[cfg(not(target_arch = "wasm32"))] + let count = img.data.par_iter().enumerate().filter(|(i, p)| clipped(*i, p).iter().any(|&c| c)).count(); + #[cfg(target_arch = "wasm32")] + let count = img.data.iter().enumerate().filter(|(i, p)| clipped(*i, p).iter().any(|&c| c)).count(); + if count == 0 || w == 0 || h == 0 { + return 0; + } + // a white far from the camera's neutral (or not a number) is a broken colour model: keep the camera's + let plausible = white.iter().all(|v| v.is_finite() && (1.0 / 16.0..=16.0).contains(v)); + let white = if plausible { white } else { [1.0; 3] }; + let total = white[0] + white[1] + white[2]; + let neutral = [white[0] / total, white[1] / total, white[2] / total]; + // A clipped pixel is never a source, so its chromaticity is always the bilinear sample of the + // half-resolution estimate: the pyramid starts there, straight from the image. + let (first, near) = sources(img, wb, clip, &clipped); + let mut levels = vec![first]; + while let Some(l) = levels.last().filter(|l| l.w > 1 || l.h > 1) { + let next = pull(l); + levels.push(next); + } + // a clipped pixel samples the cells within one of its own, which are within one of a clipped cell + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + let needed = |x: usize, y: usize| (y.saturating_sub(1)..=(y + 1).min(ch - 1)).any(|yy| near.get(yy * cw + x).copied().unwrap_or(false)); + push(&mut levels, [neutral[0], neutral[2], 0.0], Some(&needed)); + // How much reliable content lies around each needed cell: its density at any scale up to [`REACH`] (level + // i's cells span 2^i cells of level 0). Near reliable content some fine level is dense with it; far from it + // only the widest one may still hold a little, and the trust fades with that. Kept in the third entry of the + // level 0 estimates, which clipped pixels sample with their colour. + let reach = REACH * w.max(h) as f32 / 2.0; + let widest = (0..levels.len()).find(|&i| (1u64 << i.min(62)) as f32 >= reach).unwrap_or(levels.len().saturating_sub(1)); + if let Some((first, coarser)) = levels.split_first_mut() { + let support: Vec<(&Level<3>, f32)> = coarser.iter().take(widest).enumerate().map(|(i, l)| (l, (1u64 << (i + 1).min(62)) as f32)).collect(); + let fw = first.w; + par_rows(&mut first.cells, fw, |y, row| { + for (x, cell) in row.iter_mut().enumerate() { + if !needed(x, y) { + continue; + } + let mut t = 0f32; + for &(l, scale) in &support { + t = t.max(smoothstep(0.0, SUPPORT, sample(l, scale, x, y)[2])); + if t >= 1.0 { + break; + } + } + cell[2] = t; + } + }); + } + let Some(field) = levels.first() else { return count }; + // the rim (level 0 of its pyramid holds the estimate), if there is one anywhere at all + let rims = { + let mut levels = vec![rim(img, wb, clip, &clipped, &needed)]; + while let Some(l) = levels.last().filter(|l| l.w > 1 || l.h > 1) { + let next = pull(l); + levels.push(next); + } + push(&mut levels, [0.0; 4], None); + Some(levels).filter(|levels| levels.last().is_some_and(|top| top.cells.iter().any(|c| c[3] > 0.0))) + }; + let rim_field = rims.as_ref().and_then(|l| l.first()); + let max_level = wb.iter().cloned().fold(0.0f32, f32::max) * clip; + let solve = |x: usize, y: usize, p: [f32; 3], clipping: Clipping| -> [f32; 3] { + let q = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]; + let known_top = || (0..3).filter(|&c| !clipping.unknown(c)).map(|c| q[c]).fold(0.0f32, f32::max); + // rebuilt with the colour of the reliable content around, and with neutral, blended by how much of it + // there is and how well the pixel agrees with it (blending the results, not the colours, keeps the + // estimate consistent with the pixel's own unclipped channels all the way) + let e = sample(field, 2.0, x, y); + let borrowed = [e[0], 1.0 - e[0] - e[1], e[1]]; + let edge = rim_field.map(|rim| sample(rim, 4.0, x, y)); + let mut trust = e[2].clamp(0.0, 1.0); + if trust > 0.0 { + let mut off = contradiction(p, q, clipping, borrowed, clip); + if off > AGREE.0 { + off = off.min(edge.map_or(0.0, |edge| { + let s = edge[0] + edge[1] + edge[2]; + if s > 1e-6 { unlike([edge[0] / s, edge[1] / s, edge[2] / s], borrowed) } else { 0.0 } + })); + } + trust *= 1.0 - smoothstep(AGREE.0, AGREE.1, off); + } + // either applies only as far as the pixel lies past the rim nearest its clip (in any channel); nearer, the + // pixel is rebuilt with the rim's colour + let at_rim = edge.and_then(|edge| { + // stops between pixel and rim in each channel; a clipped channel's true value lies at least as far + // above the rim's as its clip, and no further below (see [`bound`]) + let ratio = (0..3) + .map(|c| { + if clipping.unknown(c) { + return 1.0; + } + let (a, b) = (q[c].max(1e-12), edge[c].max(1e-12)); + if a >= b { + return a / b; + } + match bound(p, clipping.clipped, clip, c) { + w if w <= 0.0 => b / a, + w if w >= 1.0 => 1.0, + w => (b / a).powf(1.0 - w), + } + }) + .fold(1.0f32, f32::max); + let past = ratio.log2().min(64.0); + let k = smoothstep(NEAR_RIM, NEAR_RIM + DEPTH, past); + let s = edge[0] + edge[1] + edge[2]; + (k < 1.0 && s > 1e-6).then(|| rebuild(p, q, clipping, [edge[0] / s, edge[1] / s, edge[2] / s], clip, max_level)).flatten().map(|a| (a, k)) + }); + let past_rim = |b: [f32; 3]| -> [f32; 3] { + let Some((a, k)) = at_rim else { return b }; + std::array::from_fn(|c| a[c] + (b[c] - a[c]) * k) + }; + let local = (trust > 0.0).then(|| rebuild(p, q, clipping, borrowed, clip, max_level)).flatten().map(past_rim); + let plain = (trust < 1.0).then(|| rebuild(p, q, clipping, neutral, clip, max_level)).flatten().map(past_rim); + let mut out = match (local, plain) { + (Some(a), Some(b)) => std::array::from_fn(|c| b[c] + (a[c] - b[c]) * trust), + (Some(a), None) | (None, Some(a)) => a, + (None, None) => { + let v = known_top().max(max_level); + white.map(|c| c * v) + } + }; + // Fade into the fully clipped neutral on the way from the first channel clipping (no change: continuous + // with the unclipped neighbours) to the last one clipping (all of it: continuous with the fully clipped + // ones). The way is measured in stops: how far the rebuilt clipped channels lie above their clip, + // against how far the lowest unclipped channel still lies below its own. + let above = (0..3).filter(|&c| clipping.saturated[c]).map(|c| (out[c] / q[c].max(1e-9)).max(1.0).log2()).fold(0.0f32, f32::max); + let lowest = (0..3).filter(|&c| !clipping.clipped[c]).map(|c| p[c]).fold(f32::MAX, f32::min); + let below = (clip / lowest.max(1e-6)).log2().max(0.0); + let way = if above > 0.0 && lowest < clip { above / (above + below) } else { 0.0 }; + // The brightness goes over in the second half of the way, and so does the colour of a strongly coloured + // pixel; a pale one's goes over from the start ([`PALE`]). + let u = [out[0] / white[0], out[1] / white[1], out[2] / white[2]]; + let (lo, hi) = (u[0].min(u[1]).min(u[2]), u[0].max(u[1]).max(u[2])); + let saturation = if hi > 0.0 && hi.is_finite() { 1.0 - lo.max(0.0) / hi } else { 1.0 }; + let start = 0.5 * smoothstep(PALE.0, PALE.1, saturation); + let (t_level, t_colour) = (smoothstep(0.5, 1.0, way), smoothstep(start, start + 0.5, way)); + if t_colour > 0.0 { + let level = (out[0] + out[1] + out[2]) / total; + let full = known_top().max(max_level); + let v = level + (full - level) * t_level; + out = std::array::from_fn(|c| out[c] + (white[c] * v - out[c]) * t_colour); + } + out + }; + par_rows(&mut img.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + let p = *px; + let clipping = classify(y * w + x, &p); + if !clipping.clipped.iter().any(|&b| b) { + continue; + } + let mut out = solve(x, y, p, clipping); + if (0..3).any(|c| clipping.unknown(c)) { + // Rebuilding a highlight from its weakest channel can make its rim too dark. + // Use the value-based estimate when the mask causes a large brightness drop. + // Also limit brightening, with more room in pale areas where the mask removes colour fringes. + let by_value = Clipping::from_values(&p, clip); + let alt = if by_value.clipped.iter().any(|&b| b) { solve(x, y, p, by_value) } else { [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]] }; + let luma = |c: [f32; 3]| LUMA[0] * c[0] + LUMA[1] * c[1] + LUMA[2] * c[2]; + let ratio = luma(out) / luma(alt).max(1e-9); + let coloured = || { + // how strongly coloured the reliable content around is, and the rim nearest the clip + let e = sample(field, 2.0, x, y); + let around = [[e[0], 1.0 - e[0] - e[1], e[1]]].into_iter().chain(rim_field.map(|rim| { + let e = sample(rim, 4.0, x, y); + [e[0], e[1], e[2]] + })); + around + .map(|c| { + let u = [c[0] / white[0], c[1] / white[1], c[2] / white[2]]; + let (lo, hi) = (u[0].min(u[1]).min(u[2]), u[0].max(u[1]).max(u[2])); + if hi > 1e-9 && hi.is_finite() { smoothstep(PALE.0, PALE.1, 1.0 - lo.max(0.0) / hi) } else { 0.0 } + }) + .fold(0.0f32, f32::max) + }; + if !ratio.is_finite() || ratio < CONTINUITY || (ratio > 1.0 / CONTINUITY && ratio.log2() * coloured() > -CONTINUITY.log2()) { + out = alt; + } + } + *px = [out[0] / wb[0], out[1] / wb[1], out[2] / wb[2]]; + } + }); + count +} + +#[cfg(test)] +mod tests; diff --git a/crates/develop/src/sensor/highlight/tests.rs b/crates/develop/src/sensor/highlight/tests.rs new file mode 100644 index 0000000000..3386e5d73d --- /dev/null +++ b/crates/develop/src/sensor/highlight/tests.rs @@ -0,0 +1,346 @@ +use super::*; + +/// Daylight-like multipliers: green clips first, red and blue keep rising. +const WB: [f32; 3] = [2.5, 1.0, 1.6]; + +fn balanced(p: [f32; 3]) -> [f32; 3] { + [p[0] * WB[0], p[1] * WB[1], p[2] * WB[2]] +} + +fn sensor(q: [f32; 3]) -> [f32; 3] { + [q[0] / WB[0], q[1] / WB[1], q[2] / WB[2]].map(|v| v.min(1.0)) +} + +fn chroma(q: [f32; 3]) -> [f32; 3] { + let s = q[0] + q[1] + q[2]; + q.map(|v| v / s) +} + +/// A pale blue sky whose green channel clipped, an unclipped strip of the same sky along the top, and a dark +/// branch with purple fringes on both sides standing in the clipped part (white-balanced sky colour returned). +fn branch_scene() -> (Rgb32f, [f32; 3]) { + let sky = [1.10, 1.25, 1.45]; + let img = Rgb32f::from_fn(192, 128, |x, y| { + sensor(if y < 24 { + sky.map(|v| v * 0.7) + } else if (90..100).contains(&x) && y >= 40 { + [0.06, 0.05, 0.03] + } else if (x == 89 || x == 100) && y >= 40 { + [0.75, 0.25, 0.96] + } else { + sky + }) + }); + (img, sky) +} + +/// How far chromaticity `got` lies off the way from `from` to neutral (largest channel difference to the +/// nearest point of that way). +fn off_the_way_to_neutral(got: [f32; 3], from: [f32; 3]) -> f32 { + let d: [f32; 3] = std::array::from_fn(|c| 1.0 / 3.0 - from[c]); + let len = d.iter().map(|v| v * v).sum::(); + let t = if len > 0.0 { ((0..3).map(|c| (got[c] - from[c]) * d[c]).sum::() / len).clamp(0.0, 1.0) } else { 0.0 }; + (0..3).map(|c| (got[c] - (from[c] + d[c] * t)).abs()).fold(0.0, f32::max) +} + +/// Issue #523: the clipped sky beside a branch took the colour of the branch's fringes and of the branch +/// itself (magenta, green), which any darkening of the highlights then showed. Beside the branch it is now the +/// clipped sky away from it: the sky's colour, on its way to neutral. +#[test] +fn fringes_and_dark_branches_do_not_tint_a_clipped_sky() { + let (mut img, sky) = branch_scene(); + assert!(reconstruct(&mut img, WB, 0.99) > 0); + let mut worst = 0f32; + for y in 40..128 { + let away = chroma(balanced(img.get(30, y))); + assert!(away == chroma(balanced(img.get(170, y))), "row {y}"); + let off = off_the_way_to_neutral(away, chroma(sky)); + assert!(off < 0.005, "row {y}: the clipped sky {away:?} is not the sky's colour on its way to neutral ({off})"); + for x in [84, 86, 88, 101, 103, 105] { + let got = chroma(balanced(img.get(x, y))); + worst = worst.max((0..3).map(|c| (got[c] - away[c]).abs()).fold(0.0, f32::max)); + } + } + assert!(worst < 0.01, "clipped sky beside the branch is off the sky away from it by {worst}"); +} + +/// A warm light with red and green clipped: left at their clip levels the pair reads red-magenta (the white +/// balance multiplies red's clip level by 2.5, green's by 1). +#[test] +fn two_clipped_channels_are_not_left_at_their_clip_levels() { + let light = [3.5, 2.6, 0.8]; + let mut img = Rgb32f::from_fn(64, 64, |x, y| { + let d = ((x as f32 - 32.0).powi(2) + (y as f32 - 32.0).powi(2)).sqrt(); + if d < 20.0 { sensor(light) } else { [0.02; 3] } + }); + reconstruct(&mut img, WB, 0.99); + let q = balanced(img.get(32, 32)); + assert!((q[2] - 0.8).abs() < 0.1, "the unclipped channel is about kept: {q:?}"); + let ratio = q[1] / q[0]; + assert!((0.6..=1.05).contains(&ratio), "green / red {ratio} ({q:?}): not a warm white"); +} + +#[test] +fn fully_clipped_pixels_follow_the_colour_model_white() { + let white = [1.03, 0.98, 1.06]; + let mut img = Rgb32f::filled(8, 8, [1.0; 3]); + img.data[0] = [0.3, 0.6, 0.4]; + reconstruct_with(&mut img, WB, 0.99, white); + let q = balanced(img.get(4, 4)); + let k = q[1] / white[1]; + assert!((0..3).all(|c| (q[c] - white[c] * k).abs() < 1e-4 * k), "{q:?} is not along {white:?}"); + assert!(k >= 2.5 * 0.99 - 1e-4, "clipped neutral at least as bright as the highest clip level: {k}"); + assert_eq!(img.data[0], [0.3, 0.6, 0.4]); + // a white that cannot be right falls back to camera neutral, and nothing overflows + for bad in [[f32::NAN, 1.0, 1.0], [2.5e38, 0.74, 0.74], [1.0, 0.0, 1.0], [40.0, 1.0, 1.0]] { + let mut img = Rgb32f::filled(4, 4, [1.0; 3]); + img.data[0] = [1.0, 1.0, 0.5]; + reconstruct_with(&mut img, WB, 0.99, bad); + let q = balanced(img.get(1, 1)); + assert!((q[0] - q[1]).abs() < 1e-4 && (q[2] - q[1]).abs() < 1e-4, "{bad:?}: {q:?}"); + assert!(img.data.iter().flatten().all(|v| v.is_finite()), "{bad:?}"); + } +} + +/// Red rises through its clip level across a sky whose green and blue clipped: the rebuilt colour changes +/// smoothly (no edge where red clips too) and arrives at the clipped neutral. +#[test] +fn rebuilt_colour_is_continuous_as_more_channels_clip() { + let blue = [1.0, 1.3, 1.9]; + let img0 = Rgb32f::from_fn(240, 40, |x, y| { + if y < 8 { + return sensor(blue.map(|v| v * 0.5)); // unclipped sky: the source of colour + } + let level = 0.6 + 2.2 * x as f32 / 239.0; // red at 0.24 to 1.12 of its clip level + sensor([level * WB[0] * 0.4, 1.6, 2.0]) + }); + let mut img = img0.clone(); + reconstruct(&mut img, WB, 0.99); + let row: Vec<[f32; 3]> = (0..240).map(|x| chroma(balanced(img.get(x, 30)))).collect(); + let step = row.windows(2).map(|w| (0..3).map(|c| (w[1][c] - w[0][c]).abs()).fold(0.0, f32::max)).fold(0.0, f32::max); + assert!(step < 0.01, "largest chromaticity step between neighbours {step}"); + let end = row[239]; + assert!(end.iter().all(|v| (v - 1.0 / 3.0).abs() < 1e-3), "fully clipped end {end:?}"); +} + +/// A smooth pink ramp (`[0.9k, k, 0.8k]`, k from 0.8 to 1.35) whose green clips first, then red, then blue, +/// in `rows` of a `h`-row picture that is otherwise near black: the rebuilt middle row, and where green first +/// clips on it. +fn rebuilt_ramp(rows: std::ops::Range, h: usize) -> (Vec<[f32; 3]>, usize) { + let (w, k0, k1) = (1600usize, 0.8f32, 1.35f32); + let k = |x: usize| k0 + (k1 - k0) * x as f32 / (w - 1) as f32; + let img0 = Rgb32f::from_fn(w, h, |x, y| if rows.contains(&y) { [0.9 * k(x), k(x), 0.8 * k(x)].map(|v| v.min(1.0)) } else { [0.01; 3] }); + let mut img = img0.clone(); + reconstruct(&mut img, WB, 0.99); + let y = (rows.start + rows.end) / 2; + let row: Vec<[f32; 3]> = (0..w).map(|x| balanced(img.get(x, y))).collect(); + (row, (0..w).find(|&x| img0.get(x, y)[1] >= 0.99).unwrap_or(0)) +} + +/// No channel changes by more than `at_clip` (relative) where green first clips, nor by 3 % anywhere. +fn assert_continuous(row: &[[f32; 3]], first: usize, at_clip: f32, case: &str) { + // across the first clip the colour carries on as it was (the sensor's own colour, not a fade) + let (a, b) = (row[first - 1], row[first]); + assert!((0..3).all(|c| (b[c] / a[c] - 1.0).abs() < at_clip), "{case}, first clip: {a:?} then {b:?}"); + let worst = row.windows(2).map(|p| (0..3).map(|c| (p[1][c] / p[0][c] - 1.0).abs()).fold(0.0, f32::max)).fold(0.0, f32::max); + // (a smooth ramp moves 0.04 % per pixel here; the rebuilt colour turns faster where it leaves the colour of + // the unclipped part for neutral, but never by a step) + assert!(worst < 0.03, "{case}: largest relative step between neighbours {worst}"); +} + +/// The rebuilt colour has no step anywhere along the ramp: not where green first clips (the neutral fade starts +/// from nothing there), nor where red does, nor where the last channel clips (the fade ends at the fully +/// clipped neutral). +#[test] +fn rebuilt_ramp_is_continuous_from_the_first_clip_to_the_last() { + let (row, first) = rebuilt_ramp(0..32, 32); + assert_continuous(&row, first, 0.002, "full ramp"); +} + +/// The same ramp as a thin line on near black has no reliable colour around (every pixel of it is on a strong +/// edge), so its clipped part falls back to the neutral guess. That guess only applies as far as the line runs +/// past its own unclipped part: no step where it first clips, however thin the line and however much dark +/// background surrounds it. +#[test] +fn thin_line_without_reliable_colour_is_continuous_where_it_clips() { + for height in [32usize, 512, 1024] { + for width in [1usize, 4, 16] { + let top = (height - width) / 2; + let (row, first) = rebuilt_ramp(top..top + width, height); + assert_continuous(&row, first, 0.002, &format!("{width} rows of {height}")); + // and well past the first clip the neutral guess has taken over (green as high as red and blue imply) + let far = row[1500]; + assert!(far[1] > 0.95 * far[2], "{width} rows of {height}: {far:?}"); + } + } +} + +/// Issue #523 (a river photo darkened by Highlights -75): a pale cyan-blue sky (`[1, 1.07, 1.2]` white-balanced) +/// brightening from left to right through the point where green clips (and later blue), above bright +/// yellow-green foliage, with thin dark branches standing in its lower half. Its rebuilt colour used to lean +/// green to teal: the foliage lent its colour to the sky (green rebuilt from it), with a step where green first +/// clips, and the sky kept its own pale colour where Lightroom shows white. +#[test] +fn pale_sky_by_dark_branches_and_foliage_is_not_tinted() { + let sky = [1.0, 1.07, 1.2]; + let (w, h) = (320usize, 96usize); + let k = |x: usize| 0.7 * (1.2 * x as f32 / (w - 1) as f32).exp2(); + let branches = [150usize, 200, 250]; + let on_branch = |x: usize| branches.iter().any(|&b| (b.saturating_sub(1)..=b + 2).contains(&x)); + let img0 = Rgb32f::from_fn(w, h, |x, y| { + sensor(if y >= 72 { + [0.5, 0.6, 0.22] + } else if y >= 40 && branches.iter().any(|&b| x == b || x == b + 1) { + [0.1, 0.09, 0.04] + } else { + sky.map(|v| v * k(x)) + }) + }); + let mut img = img0.clone(); + reconstruct(&mut img, WB, 0.99); + let at = |x: usize, y: usize| chroma(balanced(img.get(x, y))); + let first = (0..w).find(|&x| img0.get(x, 20)[1] >= 0.99).unwrap_or(0); + assert!(first > 0 && first < 150); + let diff = |a: [f32; 3], b: [f32; 3]| (0..3).map(|c| (a[c] - b[c]).abs()).fold(0.0, f32::max); + for y in [20, 50] { + // no step where green clips + let step = diff(at(first - 1, y), at(first, y)); + assert!(step < 0.001, "row {y}: step of {step} where green clips"); + for x in first..w { + // nothing but the sky's colour on its way to neutral (no green from the foliage)... + let off = off_the_way_to_neutral(at(x, y), chroma(sky)); + assert!(on_branch(x) || off < 0.005, "row {y}, x {x}: {:?} is off the sky's way to neutral by {off}", at(x, y)); + // ... the same beside the branches as above them ... + let beside = diff(at(x, y), at(x, 20)); + assert!(on_branch(x) || beside < 0.005, "row {y}, x {x}: {:?} beside a branch, {:?} above", at(x, y), at(x, 20)); + } + // ... and neutral well before the last channel clips (the sky is 0.7 stops past green's clip there) + let end = at(w - 1, y); + assert!(end.iter().all(|v| (v - 1.0 / 3.0).abs() < 0.002), "row {y}: {end:?} at the end"); + } +} + +#[test] +fn unclipped_pixels_are_left_exactly() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut rnd = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 40) as f32 / (1u64 << 24) as f32 + }; + for (w, h) in [(1, 1), (3, 1), (7, 5), (64, 48), (129, 77)] { + let noise: Vec = (0..w * h).map(|_| rnd()).collect(); + let img = Rgb32f::from_fn(w, h, |x, y| { + let t = ((x as f32 * 0.21).sin() + (y as f32 * 0.17).cos()) * 0.5; + let base = [0.5 + 0.4 * t, 0.45 - 0.2 * t, 0.3 + 0.1 * t]; + match noise[y * w + x] { + r if r < 0.1 => [1.0; 3], + r if r < 0.4 => [1.0, base[1] * 1.6, base[2]], + r if r > 0.995 => [0.0, 0.0, 0.00001], + _ => base, + } + }); + let mut out = img.clone(); + let n = reconstruct_with(&mut out, [2.1, 1.0, 1.6], 0.99, [1.02, 0.99, 1.05]); + let clipped = img.data.iter().filter(|p| p.iter().any(|&v| v >= 0.99)).count(); + assert_eq!(n, clipped); + for (a, b) in img.data.iter().zip(&out.data) { + if a.iter().all(|&v| v < 0.99) { + assert_eq!(a, b, "{w}×{h}"); + } else { + assert!(b.iter().all(|v| v.is_finite() && *v >= 0.0), "{w}×{h}: {b:?}"); + } + } + } +} + +#[test] +fn clip_neutral_makes_clipped_white_neutral() { + let wb = [2.0, 1.0, 1.5]; + let mut img = Rgb32f::filled(2, 1, [1.0, 1.0, 1.0]); + img.data[1] = [0.2, 0.3, 0.4]; + clip_neutral(&mut img, wb, 1.0); + let p = img.data[0]; + let q = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]; + assert!((q[0] - q[1]).abs() < 1e-6 && (q[1] - q[2]).abs() < 1e-6); + assert_eq!(img.data[1], [0.2, 0.3, 0.4]); +} + +#[test] +fn reconstruct_restores_clipped_channel() { + // a warm gradient whose red channel clips at its bright end + let truth = Rgb32f::from_fn(256, 16, |x, _| { + let v = 0.3 + 1.0 * x as f32 / 255.0; + [v * 1.0, v * 0.6, v * 0.35] + }); + let mut img = truth.map(|p| p.map(|v| v.min(1.0))); + let first = (0..256).find(|&x| img.get(x, 8)[0] >= 0.999).unwrap(); + // near the unclipped gradient (within the reach of its colour) red is rebuilt from it + let err = |img: &Rgb32f| -> f32 { (first..first + 12).map(|x| (img.get(x, 8)[0] - truth.get(x, 8)[0]).abs()).sum() }; + let before = err(&img); + let n = reconstruct(&mut img, [1.0, 1.0, 1.0], 0.999); + assert!(n > 0); + let after = err(&img); + assert!(after < before * 0.2, "before {before} after {after}"); + // unclipped pixels untouched + assert_eq!(img.get(0, 0), truth.get(0, 0)); + assert_eq!(img.get(first - 1, 8), truth.get(first - 1, 8)); +} + +#[test] +fn fully_clipped_and_no_clipping() { + let mut img = Rgb32f::filled(4, 4, [1.0; 3]); + assert_eq!(reconstruct(&mut img, [2.0, 1.0, 1.5], 0.99), 16); + let p = img.data[0]; + assert!((p[0] * 2.0 - p[1]).abs() < 1e-5 && (p[2] * 1.5 - p[1]).abs() < 1e-5); + let mut img = Rgb32f::filled(4, 4, [0.5; 3]); + assert_eq!(reconstruct(&mut img, [2.0, 1.0, 1.5], 0.99), 0); + let mut empty = Rgb32f::new(0, 0); + assert_eq!(reconstruct(&mut empty, [1.0; 3], 0.99), 0); +} + +/// `cargo test --release -p lightcraft-raw --lib -- --ignored bench_reconstruct --nocapture` +#[test] +#[ignore] +fn bench_reconstruct() { + let img = Rgb32f::from_fn(6000, 4000, |x, y| { + let v = 0.4 + 0.8 * ((x as f32 * 0.003).sin() * (y as f32 * 0.002).cos()).abs(); + [v.min(1.0), (v * 0.7).min(1.0), (v * 0.5).min(1.0)] + }); + let ms = (0..3) + .map(|_| { + let mut i = img.clone(); + let t = std::time::Instant::now(); + reconstruct(&mut i, [2.0, 1.0, 1.5], 0.99); + t.elapsed().as_secs_f64() * 1e3 + }) + .fold(f64::MAX, f64::min); + eprintln!("reconstruct 24 MP: {ms:.0} ms"); +} + +/// A mask decides which channels are clipped (their values are lower bounds), whatever their values; the +/// unmarked pixels are left as they were; a mask of another size leaves clipping to the values. +#[test] +fn a_mask_marks_the_clipped_channels() { + let base = Rgb32f::from_fn(32, 32, |x, _| if x >= 16 { [0.2, 0.5, 0.25] } else { [0.5, 0.5, 0.5] }); + let mask: Vec = (0..32 * 32).map(|i| if i % 32 >= 16 { CLIPPED_R } else { 0 }).collect(); + let mut img = base.clone(); + assert_eq!(reconstruct_masked(&mut img, [1.0; 3], 0.99, [1.0; 3], &mask), 512); + for (p, b) in img.data.iter().zip(&base.data) { + assert!(p.iter().all(|v| v.is_finite()), "{p:?}"); + if b[0] == 0.5 { + assert_eq!(p, b); + } else { + // red rebuilt from at least its mean, the others kept + assert!(p[0] >= 0.2 && p[1] == 0.5 && p[2] == 0.25, "{p:?}"); + } + } + // red is rebuilt above its mean, towards the neighbours' neutral (as far as the pixel's own blue agrees) + assert!(img.get(24, 16)[0] > 0.3, "{:?}", img.get(24, 16)); + // the values alone see nothing clipped here, nor does a mask of another size + let mut plain = base.clone(); + assert_eq!(reconstruct(&mut plain, [1.0; 3], 0.99), 0); + assert_eq!(reconstruct_masked(&mut plain, [1.0; 3], 0.99, [1.0; 3], &mask[1..]), 0); + assert!(plain.data == base.data); +} diff --git a/crates/develop/src/sensor/mod.rs b/crates/develop/src/sensor/mod.rs new file mode 100644 index 0000000000..f7f20ab0aa --- /dev/null +++ b/crates/develop/src/sensor/mod.rs @@ -0,0 +1,353 @@ +//! Sensor-stage RAW development over [`craft_raw::RawImage`]: black/white normalization, +//! DNG `OpcodeList1/2/3`, Bayer (AHD, PPG, Bilinear) & X-Trans demosaicing, clip-aware highlight +//! reconstruction, DNG colour matrices, `ProfileGainTableMap` evaluation, and binned previews. + +pub mod binned; +pub mod chart_table; +pub mod color; +pub mod demosaic; +pub mod gaintable; +pub mod highlight; +pub mod opcodes; + +pub use craft_color_transform::Mat3; +pub use craft_raw::opcodes::{Opcode, OpcodeLists}; +pub use craft_raw::{BlackLevel, Cfa, ColorData, MAX_SAMPLES, RawData, RawError, RawFormat, RawImage, RawInfo, Rect, Result, stretched_height}; +pub use demosaic::{Method, demosaic}; + +use crate::raster::resample::{Filter, resize}; +use crate::raster::{Rgb32f, par_rows}; +#[cfg(not(target_arch = "wasm32"))] +use rayon::prelude::*; + +/// Checked product of input-derived dimensions, in u64 so it cannot wrap on 32-bit or 64-bit +/// targets. Returns `None` on overflow, zero, or when the product exceeds [`MAX_SAMPLES`]. +pub fn checked_pixel_count(width: u64, height: u64) -> Option { + width.checked_mul(height).filter(|&n| n > 0 && n <= MAX_SAMPLES as u64) +} + +/// A CFA pattern this crate can address: 1 to 16 sites a side, one colour index per site. +pub fn cfa_valid(c: &Cfa) -> bool { + c.width > 0 && c.height > 0 && c.width <= 16 && c.height <= 16 && c.pattern.len() == c.width * c.height +} + +/// Black-subtracted, white-normalised data covering the active area. +#[derive(Clone, Debug, PartialEq)] +pub struct Normalized { + pub width: usize, + pub height: usize, + pub cpp: usize, + /// Nominal range [0, 1] (values may exceed 1 above white or be negative from noise). + pub data: Vec, + /// CFA anchored at (0, 0) of this buffer. + pub cfa: Option, +} + +// DNG 1.7.1, chapters 5 and 7: the integer lookup follows OpcodeList1 and precedes +// black/white normalization. The decoder has normally applied it already. +fn deferred_linearization_table(raw: &RawImage) -> Option<&[u16]> { + if raw.linearized || !matches!(raw.data, RawData::U16(_)) { + return None; + } + raw.linearization_table.as_deref().filter(|table| !table.is_empty()) +} + +/// Sensor development operations on [`craft_raw::RawImage`]. +pub trait RawDevelopExt { + fn validate(&self) -> Result<()>; + fn white_at(&self, s: usize) -> f32; + fn normalized(&self) -> Result; + /// Develop camera RGB with the demosaic on the sensor's original colour scale. + fn develop(&self, method: Method) -> Result; + /// Demosaic after applying white balance `wb` to the mosaic, with gains relative to green. + /// Directional interpolation then sees little colour difference across a neutral edge. + /// The returned RGB is back on the sensor's scale for highlight reconstruction and colour conversion. + /// Bilinear, monochrome and already demosaiced data use the same path as [`Self::develop`]. + /// Unusable gains or samples also fall back to that path. + fn develop_balanced(&self, method: Method, wb: [f32; 3]) -> Result; + /// [`Self::develop_balanced`] with a per-pixel sensor clip mask for [`highlight::reconstruct_masked`]. + /// The mask uses the normalised sensor threshold `clip` and covers the default crop. + /// The mask is absent for an unclipped mosaic, data without a single-plane CFA, `OpcodeList3`, + /// or a pixel-aspect correction that changes the output grid. + fn develop_balanced_masked(&self, method: Method, wb: [f32; 3], clip: f32) -> Result<(Rgb32f, Option>)>; + fn finish_demosaiced(&self, rgb: Rgb32f) -> Rgb32f; + fn develop_crop(&self, width: usize, height: usize) -> Rect; + fn can_bin(&self, k: usize) -> bool; + fn develop_binned(&self, k: usize, clip: f32) -> Result>; + fn develop_binned_masked(&self, k: usize, clip: f32) -> Result)>>; +} + +impl RawDevelopExt for RawImage { + fn validate(&self) -> Result<()> { + if self.width == 0 || self.height == 0 || !(1..=4).contains(&self.cpp) { + return Err(RawError::Corrupt("bad dimensions".into())); + } + if self.cpp == 2 { + return Err(RawError::Unsupported("2 samples per pixel".into())); + } + let expected = checked_pixel_count(self.width as u64, self.height as u64) + .and_then(|n| n.checked_mul(self.cpp as u64)) + .ok_or_else(|| RawError::Corrupt("data length mismatch".into()))?; + let actual = u64::try_from(self.data.len()).map_err(|_| RawError::Corrupt("data length mismatch".into()))?; + if actual != expected { + return Err(RawError::Corrupt("data length mismatch".into())); + } + if let Some(c) = &self.cfa + && (!cfa_valid(c) || c.pattern.iter().any(|&p| p > 2)) + { + return Err(RawError::Unsupported(format!("CFA pattern {}", c.name()))); + } + let a = self.active_area; + let fits = |x: usize, len: usize, limit: usize| x.checked_add(len).is_some_and(|end| end <= limit); + if a.width == 0 || a.height == 0 || !fits(a.x, a.width, self.width) || !fits(a.y, a.height, self.height) { + return Err(RawError::Corrupt("active area outside image".into())); + } + Ok(()) + } + + fn white_at(&self, s: usize) -> f32 { + self.white.get(s).or_else(|| self.white.first()).copied().unwrap_or(65535.0) + } + + fn normalized(&self) -> Result { + self.validate()?; + let (w, cpp) = (self.width, self.cpp); + let a = self.active_area; + let stage1: Option> = if self.opcodes.list1.is_empty() { + None + } else { + let mut v: Vec = (0..self.data.len()).map(|i| self.data.get(i)).collect(); + opcodes::apply_list(&self.opcodes.list1, &mut v, self.width, self.height, cpp, self.cfa.as_ref(), 65535.0); + Some(v) + }; + let table = deferred_linearization_table(self); + let src = |i: usize| { + let code = stage1.as_ref().map_or_else(|| self.data.get(i), |v| v[i]); + if let Some(table) = table + && code.is_finite() + { + // The LUT is indexed by unsigned integer codes. List1's scratch buffer + // uses floats, so round to the nearest code at the lookup boundary. + let index = usize::from(code.round() as u16).min(table.len() - 1); + f32::from(table[index]) + } else { + code + } + }; + let scale: Vec = (0..cpp) + .map(|s| { + let range = self.white_at(s) - self.black.mean(); + if range > 0.0 { 1.0 / range } else { 1.0 } + }) + .collect(); + let mut out = vec![0f32; a.width * a.height * cpp]; + let row_len = a.width * cpp; + crate::raster::par_rows(&mut out, row_len, |y, row| { + let base = ((a.y + y) * w + a.x) * cpp; + for x in 0..a.width { + for s in 0..cpp { + let v = src(base + x * cpp + s); + let b = self.black.at(x, y, s, cpp); + let n = (v - b) * scale[s]; + row[x * cpp + s] = if n.is_finite() { n } else { 0.0 }; + } + } + }); + let cfa = self.cfa.as_ref().map(|c| c.shifted(a.x, a.y)); + opcodes::apply_list(&self.opcodes.list2, &mut out, a.width, a.height, cpp, cfa.as_ref(), 1.0); + Ok(Normalized { width: a.width, height: a.height, cpp, data: out, cfa }) + } + + fn develop(&self, method: Method) -> Result { + Ok(develop_full(self, self.normalized()?, method, None)) + } + + fn develop_balanced(&self, method: Method, wb: [f32; 3]) -> Result { + Ok(develop_full(self, self.normalized()?, method, Some(wb))) + } + + fn develop_balanced_masked(&self, method: Method, wb: [f32; 3], clip: f32) -> Result<(Rgb32f, Option>)> { + let n = self.normalized()?; + let mask = clip_mask(self, &n, method, clip); + Ok((develop_full(self, n, method, Some(wb)), mask)) + } + + fn finish_demosaiced(&self, mut rgb: Rgb32f) -> Rgb32f { + opcodes::apply_list3(&self.opcodes.list3, &mut rgb); + let c = self.develop_crop(rgb.width, rgb.height); + let rgb = + if c.x == 0 && c.y == 0 && c.width == rgb.width && c.height == rgb.height { rgb } else { rgb.into_crop(c.x, c.y, c.width, c.height) }; + stretched(self, rgb) + } + + fn develop_crop(&self, width: usize, height: usize) -> Rect { + let c = self.crop.clipped(width, height); + if c.width == 0 || c.height == 0 { Rect::new(0, 0, width, height) } else { c } + } + + fn can_bin(&self, k: usize) -> bool { + binned::can_bin(self, k) + } + + fn develop_binned(&self, k: usize, clip: f32) -> Result> { + binned::develop_binned(self, k, clip) + } + + fn develop_binned_masked(&self, k: usize, clip: f32) -> Result)>> { + binned::develop_binned_masked(self, k, clip) + } +} + +fn develop_full(raw: &RawImage, mut n: Normalized, method: Method, wb: Option<[f32; 3]>) -> Rgb32f { + let gains = wb.and_then(balance_gains).filter(|&gains| scale_mosaic(&mut n, method, gains)); + let window = + if raw.opcodes.list3.is_empty() && method == Method::Ahd { demosaic::ahd_window(&n, raw.develop_crop(n.width, n.height)) } else { None }; + let windowed = window.is_some(); + let mut rgb = window.unwrap_or_else(|| demosaic(&n, method)); + drop(n); + if let Some(gains) = gains { + par_rows(&mut rgb.data, rgb.width, |_, row| { + for p in row { + p[0] /= gains[0]; + p[2] /= gains[2]; + } + }); + } + if windowed { stretched(raw, rgb) } else { raw.finish_demosaiced(rgb) } +} + +fn balance_gains(wb: [f32; 3]) -> Option<[f32; 3]> { + // A factor of 64 in either direction is already wider than camera white balances. + const MAX_GAIN: f32 = 64.0; + if !wb.iter().all(|v| v.is_finite() && *v > 0.0) { + return None; + } + let gains = [wb[0] / wb[1], 1.0, wb[2] / wb[1]]; + (gains != [1.0; 3] && gains.iter().all(|g| (1.0 / MAX_GAIN..=MAX_GAIN).contains(g))).then_some(gains) +} + +fn scale_mosaic(n: &mut Normalized, method: Method, gains: [f32; 3]) -> bool { + let Some(cfa) = n.cfa.as_ref().filter(|_| n.cpp == 1) else { return false }; + if demosaic::mosaic_method(cfa, n.width, n.height, method) == Method::Bilinear { + return false; + } + + // Leave room for demosaic arithmetic and the division back to camera RGB, even for float DNGs. + // Check the whole mosaic before scaling it so the fallback can reuse the normalised data. + let largest_factor = gains.into_iter().map(|g| g.max(1.0 / g)).fold(1.0f32, f32::max); + let limit = 1e30 / largest_factor; + let fits = |v: &f32| v.abs() <= limit; + #[cfg(not(target_arch = "wasm32"))] + let safe = n.data.par_iter().all(fits); + #[cfg(target_arch = "wasm32")] + let safe = n.data.iter().all(fits); + if !safe { + return false; + } + par_rows(&mut n.data, n.width, |y, row| { + let period: Vec = (0..cfa.width).map(|x| gains[cfa.color_at(x, y) as usize]).collect(); + for (sample, gain) in row.iter_mut().zip(period.iter().cycle()) { + *sample *= gain; + } + }); + true +} + +fn clip_mask(raw: &RawImage, n: &Normalized, method: Method, clip: f32) -> Option> { + use highlight::{CLIPPED_BITS, FROM_CLIPPED_BITS}; + + // This radius covers samples read directly by the directional interpolators. Estimates + // that build on interpolated green can depend on samples farther away. + const REACH: usize = 2; + + let cfa = n.cfa.as_ref().filter(|_| n.cpp == 1)?; + let (w, h) = (n.width, n.height); + let crop = raw.develop_crop(w, h); + if !clip.is_finite() || clip <= 0.0 || !raw.opcodes.list3.is_empty() || stretched_height(crop.height, raw.pixel_aspect) != crop.height { + return None; + } + let is_clipped = |v: &f32| *v >= clip; + #[cfg(not(target_arch = "wasm32"))] + let has_clip = n.data.par_iter().any(is_clipped); + #[cfg(target_arch = "wasm32")] + let has_clip = n.data.iter().any(is_clipped); + if !has_clip { + return None; + } + if demosaic::mosaic_method(cfa, w, h, method) == Method::Bilinear { + let mosaic = demosaic::Mosaic { w, h, data: &n.data, cfa }; + return Some(demosaic::bilinear::clip_mask(&mosaic, crop, clip)); + } + + // Collect clipped colours within reach horizontally, then combine those rows for each output pixel. + let mut rows = vec![0u8; w * h]; + par_rows(&mut rows, w, |y, row| { + let samples = &n.data[y * w..(y + 1) * w]; + let clipped: Vec = + samples.iter().enumerate().map(|(x, v)| if is_clipped(v) { FROM_CLIPPED_BITS[cfa.color_at(x, y) as usize] } else { 0 }).collect(); + for (x, bits) in row.iter_mut().enumerate() { + *bits = clipped[x.saturating_sub(REACH)..=(x + REACH).min(w - 1)].iter().fold(0, |a, b| a | b); + } + }); + let mut mask = vec![0u8; crop.width * crop.height]; + par_rows(&mut mask, crop.width, |oy, out| { + let y = crop.y + oy; + for yy in y.saturating_sub(REACH)..=(y + REACH).min(h - 1) { + let start = yy * w + crop.x; + out.iter_mut().zip(&rows[start..start + crop.width]).for_each(|(o, s)| *o |= s); + } + for (ox, bits) in out.iter_mut().enumerate() { + let x = crop.x + ox; + let colour = cfa.color_at(x, y); + if is_clipped(&n.data[y * w + x]) { + // Keep the interpolated values around a clipped measurement. They can carry thin dark detail. + *bits = CLIPPED_BITS[colour as usize]; + } else if *bits != 0 { + // A same-colour sample can affect the other channels through the green estimates. + *bits |= (colour + 1) << highlight::MEASURED_SHIFT; + } + } + }); + Some(mask) +} + +fn stretched(raw: &RawImage, rgb: Rgb32f) -> Rgb32f { + let h = stretched_height(rgb.height, raw.pixel_aspect); + if h == rgb.height { + return rgb; + } + resize(&rgb, rgb.width, h, Filter::Mitchell) +} + +#[cfg(test)] +mod checked_arithmetic_tests { + use super::*; + + #[test] + fn checked_pixel_count_wrap_inputs_rejected() { + assert_eq!(checked_pixel_count(65536, 65536), None); + assert_eq!(checked_pixel_count(65536, 65537), None); + assert_eq!(checked_pixel_count(u64::from(u32::MAX), 2), None); + assert_eq!(checked_pixel_count(1 << 40, 1 << 40), None); + } + + #[test] + fn checked_pixel_count_over_cap_rejected() { + assert_eq!(checked_pixel_count((1 << 30) + 1, 1), None); + assert_eq!(checked_pixel_count(1, (1 << 30) + 1), None); + } + + #[test] + fn checked_pixel_count_at_cap_accepted() { + assert_eq!(checked_pixel_count(1 << 30, 1), Some(1 << 30)); + assert_eq!(checked_pixel_count(1 << 15, 1 << 15), Some(1 << 30)); + } + + #[test] + fn checked_pixel_count_small_accepted() { + assert_eq!(checked_pixel_count(100, 100), Some(10_000)); + assert_eq!(checked_pixel_count(1, 1), Some(1)); + assert_eq!(checked_pixel_count(0, 100), None); + assert_eq!(checked_pixel_count(100, 0), None); + } +} diff --git a/crates/develop/src/sensor/opcodes.rs b/crates/develop/src/sensor/opcodes.rs new file mode 100644 index 0000000000..0ef3cefa04 --- /dev/null +++ b/crates/develop/src/sensor/opcodes.rs @@ -0,0 +1,333 @@ +//! DNG opcode lists (`OpcodeList1/2/3`, DNG 1.7 chapter 7). Opcode lists are always big-endian. +//! +//! Parsed (by `craft-raw`): every opcode (unknown ones are kept as [`Opcode::Unknown`]). Applied: `WarpRectilinear`, +//! `WarpRectilinear2` (opcode 14, DNG 1.6; see [`Opcode::WarpRectilinear2`]), `FixVignetteRadial`, +//! `FixBadPixelsConstant`, `FixBadPixelsList`, `MapTable`, `MapPolynomial`, `GainMap`, `DeltaPerRow/Column`, +//! `ScalePerRow/Column`. `TrimBounds` and `WarpFisheye` are recorded but not applied. +//! +//! Opcodes run in list order, except for the DNG 1.6 skip rule ([`applied_ops`]): a `WarpRectilinear` or +//! `WarpFisheye` that immediately follows an *optional* `WarpRectilinear2` is skipped (the older opcode is the +//! fallback for readers that don't know opcode 14). +//! +//! Value convention: list 1 runs on raw sample values (16-bit scale), lists 2 and 3 on values normalised to +//! [0, 1]; table/polynomial/delta opcodes are defined on the normalised range and are rescaled accordingly. + +pub use craft_raw::opcodes::{Area, Opcode, OpcodeLists, WR2_LEN, applied_ops, parse_list, wr2_factor, write_list}; + +use super::{Cfa, Rgb32f}; + +/// Whether [`apply_list`] / [`apply_list3`] implement `op`. +pub fn is_applied(op: &Opcode) -> bool { + !matches!(op, Opcode::Unknown { .. } | Opcode::TrimBounds { .. } | Opcode::WarpFisheye { .. }) +} + +fn area_iter(a: &Area, w: usize, h: usize, cpp: usize) -> impl Iterator + '_ { + let (t, l) = (a.top as usize, a.left as usize); + let (b, r) = ((a.bottom as usize).min(h), (a.right as usize).min(w)); + let (p0, p1) = (a.plane as usize, (a.plane as usize + a.planes.max(1) as usize).min(cpp)); + (t..b.max(t)) + .step_by(a.row_pitch.max(1) as usize) + .flat_map(move |y| (l..r.max(l)).step_by(a.col_pitch.max(1) as usize).flat_map(move |x| (p0..p1.max(p0)).map(move |p| (x, y, p)))) +} + +struct GainMapGrid<'a> { + points: [usize; 2], + spacing: [f64; 2], + origin: [f64; 2], + planes: usize, + gains: &'a [f32], +} + +impl GainMapGrid<'_> { + fn sample_at(&self, position: [f64; 2], plane: usize) -> f32 { + let [pv, ph] = self.points; + let mp = self.planes; + let p = plane.min(mp - 1); + let fy = if self.spacing[0] > 0.0 { ((position[0] - self.origin[0]) / self.spacing[0]).clamp(0.0, (pv - 1) as f64) } else { 0.0 }; + let fx = if self.spacing[1] > 0.0 { ((position[1] - self.origin[1]) / self.spacing[1]).clamp(0.0, (ph - 1) as f64) } else { 0.0 }; + let (y0, x0) = (fy.floor() as usize, fx.floor() as usize); + let (y1, x1) = ((y0 + 1).min(pv - 1), (x0 + 1).min(ph - 1)); + let (ty, tx) = ((fy - y0 as f64) as f32, (fx - x0 as f64) as f32); + let g = |y: usize, x: usize| self.gains[(y * ph + x) * mp + p]; + let top = g(y0, x0) + (g(y0, x1) - g(y0, x0)) * tx; + let bot = g(y1, x0) + (g(y1, x1) - g(y1, x0)) * tx; + top + (bot - top) * ty + } +} + +/// Radius normaliser: distance from the centre to the farthest image corner. +pub(crate) fn max_radius(cx: f64, cy: f64, w: f64, h: f64) -> f64 { + [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)].iter().map(|&(x, y)| (x - cx).hypot(y - cy)).fold(0.0, f64::max).max(1e-9) +} + +/// Most pixels one bad-pixel opcode repairs (the list is 64 MB, `fix_pixels`' set about twice that). Uncapped, a +/// mosaic equal to `FixBadPixelsConstant`'s constant, or one `FixBadPixelsList` rectangle over the image, lists +/// every pixel: tens of GB at [`crate::MAX_SAMPLES`]. Pixels past the cap, in list order, are left as they are. +const MAX_BAD_PIXELS: usize = 1 << 22; + +/// Apply a list to an interleaved `w × h × cpp` buffer. `cfa` (when the data is a mosaic) is used by the +/// bad-pixel opcodes. `scale` is the value of 1.0 in the buffer: 65535 for list 1 (raw 16-bit values), 1 for +/// lists 2 and 3 (normalised values). +/// Whole-image passes one opcode list may cost, all its ops together (a real DNG's list is a +/// handful of gain maps and tables). Ops past it, in list order, are left out: a list repeating a +/// full-image polynomial thousands of times was billions of evaluations on an ordinary raw. +const MAX_LIST_PASSES: usize = 32; + +/// Sample visits `op` costs on a `w × h × cpp` buffer (coefficient evaluations for a polynomial). +fn op_cost(op: &Opcode, w: usize, h: usize, cpp: usize) -> usize { + let visits = |a: &Area| { + let rows = (a.bottom as usize).min(h).saturating_sub(a.top as usize).div_ceil(a.row_pitch.max(1) as usize); + let cols = (a.right as usize).min(w).saturating_sub(a.left as usize).div_ceil(a.col_pitch.max(1) as usize); + let planes = (a.plane as usize).saturating_add(a.planes.max(1) as usize).min(cpp).saturating_sub(a.plane as usize); + rows.saturating_mul(cols).saturating_mul(planes) + }; + match op { + Opcode::MapPolynomial { area, coefficients } => visits(area).saturating_mul(coefficients.len().max(1)), + Opcode::MapTable { area, .. } + | Opcode::GainMap { area, .. } + | Opcode::DeltaPerRow { area, .. } + | Opcode::DeltaPerColumn { area, .. } + | Opcode::ScalePerRow { area, .. } + | Opcode::ScalePerColumn { area, .. } => visits(area), + // `apply_list` does nothing for these, so they spend none of the budget + Opcode::Unknown { .. } + | Opcode::TrimBounds { .. } + | Opcode::WarpFisheye { .. } + | Opcode::WarpRectilinear { .. } + | Opcode::WarpRectilinear2 { .. } => 0, + _ => w.saturating_mul(h).saturating_mul(cpp), + } +} + +pub fn apply_list(list: &[Opcode], buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, scale: f32) { + let mut budget = w.saturating_mul(h).saturating_mul(cpp).max(1).saturating_mul(MAX_LIST_PASSES); + for op in list { + let cost = op_cost(op, w, h, cpp); + if cost > budget { + continue; + } + budget -= cost; + match op { + Opcode::MapTable { area, table } => { + let n = table.len(); + for (x, y, p) in area_iter(area, w, h, cpp) { + let v = &mut buf[(y * w + x) * cpp + p]; + let idx = ((*v / scale * 65535.0).round().max(0.0) as usize).min(n - 1); + *v = table[idx] as f32 / 65535.0 * scale; + } + } + Opcode::MapPolynomial { area, coefficients } => { + for (x, y, p) in area_iter(area, w, h, cpp) { + let v = &mut buf[(y * w + x) * cpp + p]; + let t = (*v / scale) as f64; + let r = coefficients.iter().rev().fold(0.0, |acc, &c| acc * t + c); + *v = r as f32 * scale; + } + } + Opcode::GainMap { area, points_v, points_h, spacing, origin, map_planes, gains } => { + let grid = GainMapGrid { + points: [*points_v as usize, *points_h as usize], + spacing: *spacing, + origin: *origin, + planes: *map_planes as usize, + gains, + }; + for (x, y, p) in area_iter(area, w, h, cpp) { + let rv = y as f64 / h as f64; + let rh = x as f64 / w as f64; + let g = grid.sample_at([rv, rh], p - area.plane as usize); + buf[(y * w + x) * cpp + p] *= g; + } + } + Opcode::DeltaPerRow { area, deltas } | Opcode::DeltaPerColumn { area, deltas } => { + let per_row = matches!(op, Opcode::DeltaPerRow { .. }); + for (x, y, p) in area_iter(area, w, h, cpp) { + let i = + if per_row { (y - area.top as usize) / area.row_pitch as usize } else { (x - area.left as usize) / area.col_pitch as usize }; + if let Some(d) = deltas.get(i) { + buf[(y * w + x) * cpp + p] += d * scale; + } + } + } + Opcode::ScalePerRow { area, scales } | Opcode::ScalePerColumn { area, scales } => { + let per_row = matches!(op, Opcode::ScalePerRow { .. }); + for (x, y, p) in area_iter(area, w, h, cpp) { + let i = + if per_row { (y - area.top as usize) / area.row_pitch as usize } else { (x - area.left as usize) / area.col_pitch as usize }; + if let Some(s) = scales.get(i) { + buf[(y * w + x) * cpp + p] *= s; + } + } + } + Opcode::FixVignetteRadial { k, center } => { + let (cx, cy) = (center[0] * w as f64, center[1] * h as f64); + let m = max_radius(cx, cy, w as f64, h as f64); + for y in 0..h { + for x in 0..w { + let r2 = ((x as f64 + 0.5 - cx).powi(2) + (y as f64 + 0.5 - cy).powi(2)) / (m * m); + let g = 1.0 + r2 * (k[0] + r2 * (k[1] + r2 * (k[2] + r2 * (k[3] + r2 * k[4])))); + for p in 0..cpp { + buf[(y * w + x) * cpp + p] *= g as f32; + } + } + } + } + Opcode::FixBadPixelsConstant { constant, .. } => { + let c = (*constant as f64 / 65535.0 * scale as f64) as f32; + let bad: Vec<(usize, usize)> = + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| cpp == 1 && buf[y * w + x] == c).take(MAX_BAD_PIXELS).collect(); + fix_pixels(buf, w, h, cpp, cfa, &bad); + } + Opcode::FixBadPixelsList { points, rects, .. } => { + let mut bad: Vec<(usize, usize)> = + points.iter().map(|&(r, c)| (c as usize, r as usize)).filter(|&(x, y)| x < w && y < h).take(MAX_BAD_PIXELS).collect(); + 'rects: for r in rects { + let [t, l, b, rr] = r.map(|v| v as usize); + for y in t..b.min(h) { + for x in l..rr.min(w) { + if bad.len() >= MAX_BAD_PIXELS { + break 'rects; + } + bad.push((x, y)); + } + } + } + fix_pixels(buf, w, h, cpp, cfa, &bad); + } + _ => {} + } + } +} + +/// Replace listed pixels with the mean of the nearest same-colour neighbours that are not themselves bad. +fn fix_pixels(buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, bad: &[(usize, usize)]) { + if bad.is_empty() { + return; + } + let mut is_bad = std::collections::HashSet::with_capacity(bad.len()); + for &b in bad { + is_bad.insert(b); + } + let step: isize = match cfa { + Some(c) if c.width == 2 && c.height == 2 => 2, + Some(c) => c.width.max(c.height) as isize, + None => 1, + }; + for &(x, y) in bad { + for p in 0..cpp { + let mut sum = 0.0; + let mut n = 0; + for (dx, dy) in [(-step, 0), (step, 0), (0, -step), (0, step), (-step, -step), (step, step), (-step, step), (step, -step)] { + let (nx, ny) = (x as isize + dx, y as isize + dy); + if nx < 0 || ny < 0 || nx >= w as isize || ny >= h as isize || is_bad.contains(&(nx as usize, ny as usize)) { + continue; + } + sum += buf[(ny as usize * w + nx as usize) * cpp + p]; + n += 1; + } + if n > 0 { + buf[(y * w + x) * cpp + p] = sum / n as f32; + } + } + } +} + +/// Most full-image passes of one `OpcodeList3`: every warp record is a full-image allocation and resample +/// pass and every bad-pixel record a full flatten-and-rebuild, and a hostile record may repeat either +/// thousands of times. Real DNGs carry at most a couple; passes past the cap are skipped. +const MAX_LIST3_PASSES: usize = 8; + +/// Apply `OpcodeList3` (on the demosaiced RGB image, values normalised to [0, 1]). +pub fn apply_list3(list: &[Opcode], img: &mut Rgb32f) { + if list.is_empty() { + return; + } + let (w, h) = (img.width, img.height); + let mut passes = 0usize; + for op in applied_ops(list) { + match op { + Opcode::WarpRectilinear { planes, center } => { + if passes < MAX_LIST3_PASSES { + passes += 1; + *img = warp_rectilinear(img, planes, *center); + } + } + Opcode::WarpRectilinear2 { planes, center, reciprocal, .. } => { + if passes < MAX_LIST3_PASSES { + passes += 1; + *img = warp_rectilinear2(img, planes, *center, *reciprocal); + } + } + Opcode::WarpFisheye { .. } | Opcode::TrimBounds { .. } | Opcode::Unknown { .. } => {} + other => { + if passes >= MAX_LIST3_PASSES { + continue; + } + passes += 1; + let mut flat: Vec = img.data.iter().flat_map(|p| *p).collect(); + apply_list(std::slice::from_ref(other), &mut flat, w, h, 3, None, 1.0); + for (d, c) in img.data.iter_mut().zip(flat.as_chunks::<3>().0) { + *d = [c[0], c[1], c[2]]; + } + } + } + } +} + +/// DNG `WarpRectilinear`: for each output pixel, the source position is the radial + tangential model around the +/// optical centre, with coordinates normalised by the distance to the farthest corner. +pub fn warp_rectilinear(img: &Rgb32f, planes: &[[f64; 6]], center: [f64; 2]) -> Rgb32f { + let (w, h) = (img.width, img.height); + let (cx, cy) = (center[0] * (w as f64 - 1.0), center[1] * (h as f64 - 1.0)); + let m = max_radius(cx, cy, w as f64 - 1.0, h as f64 - 1.0); + let mut out = Rgb32f::new(w, h); + let coef = |p: usize| planes[p.min(planes.len() - 1)]; + crate::raster::par_rows(&mut out.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + for (c, v) in px.iter_mut().enumerate() { + let [kr0, kr1, kr2, kr3, kt0, kt1] = coef(c); + let dx = (x as f64 - cx) / m; + let dy = (y as f64 - cy) / m; + let r2 = dx * dx + dy * dy; + let f = kr0 + r2 * (kr1 + r2 * (kr2 + r2 * kr3)); + let sx = dx * f + kt0 * 2.0 * dx * dy + kt1 * (r2 + 2.0 * dx * dx); + let sy = dy * f + kt1 * 2.0 * dx * dy + kt0 * (r2 + 2.0 * dy * dy); + let (fx, fy) = (cx + m * sx, cy + m * sy); + *v = img.sample_bilinear(fx as f32 + 0.5, fy as f32 + 0.5)[c]; + } + } + }); + out +} + +/// DNG 1.6 `WarpRectilinear2`: the `WarpRectilinear` geometry (centre and normalisation as there), with the radial +/// factor of [`wr2_factor`] in place of the even polynomial in `r²`. A pixel whose factor is not finite stays put. +pub fn warp_rectilinear2(img: &Rgb32f, planes: &[[f64; WR2_LEN]], center: [f64; 2], reciprocal: bool) -> Rgb32f { + let (w, h) = (img.width, img.height); + let Some(last) = planes.len().checked_sub(1) else { return img.clone() }; + let mut out = Rgb32f::new(w, h); + let (cx, cy) = (center[0] * (w as f64 - 1.0), center[1] * (h as f64 - 1.0)); + let m = max_radius(cx, cy, w as f64 - 1.0, h as f64 - 1.0); + crate::raster::par_rows(&mut out.data, w, |y, row| { + for (x, px) in row.iter_mut().enumerate() { + for (c, v) in px.iter_mut().enumerate() { + let Some(k) = planes.get(c.min(last)) else { continue }; + let dx = (x as f64 - cx) / m; + let dy = (y as f64 - cy) / m; + let r2 = dx * dx + dy * dy; + let (sx, sy) = match wr2_factor(k, reciprocal, r2.sqrt()) { + Some(f) => { + (dx * f + k[15] * 2.0 * dx * dy + k[16] * (r2 + 2.0 * dx * dx), dy * f + k[16] * 2.0 * dx * dy + k[15] * (r2 + 2.0 * dy * dy)) + } + None => (dx, dy), + }; + let (fx, fy) = (cx + m * sx, cy + m * sy); + *v = img.sample_bilinear(fx as f32 + 0.5, fy as f32 + 0.5)[c]; + } + } + }); + out +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/develop/src/sensor/opcodes/tests.rs b/crates/develop/src/sensor/opcodes/tests.rs new file mode 100644 index 0000000000..c97b81eead --- /dev/null +++ b/crates/develop/src/sensor/opcodes/tests.rs @@ -0,0 +1,471 @@ +use super::*; + +pub(crate) struct ListWriter(pub Vec, pub u32); + +impl ListWriter { + pub fn new() -> Self { + ListWriter(Vec::new(), 0) + } + pub fn op(&mut self, id: u32, params: &[u8]) -> &mut Self { + for v in [id, 0x01030000, 0, params.len() as u32] { + self.0.extend_from_slice(&v.to_be_bytes()); + } + self.0.extend_from_slice(params); + self.1 += 1; + self + } + pub fn finish(&self) -> Vec { + let mut v = self.1.to_be_bytes().to_vec(); + v.extend_from_slice(&self.0); + v + } +} + +pub(crate) fn be(vals: &[f64]) -> Vec { + vals.iter().flat_map(|v| v.to_be_bytes()).collect() +} +pub(crate) fn area(a: [u32; 8]) -> Vec { + a.iter().flat_map(|v| v.to_be_bytes()).collect() +} + +/// Warp and bad-pixel records each cost a full-image pass, and a hostile `OpcodeList3` repeats them +/// thousands of times ([`MAX_LIST3_PASSES`] bounds the multiplier); identity warps below the cap must +/// still apply, exactly, so the same image comes out. +#[test] +fn list3_pass_cap_skips_repeated_records() { + let mut img = Rgb32f::new(8, 6); + for (i, px) in img.data.iter_mut().enumerate() { + *px = [i as f32 / 2.0, (i % 8) as f32, (i / 8) as f32]; + } + let orig: Vec<[f32; 3]> = img.data.clone(); + let list: Vec = + (0..MAX_LIST3_PASSES * 5).map(|_| Opcode::WarpRectilinear { planes: vec![[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }).collect(); + apply_list3(&list, &mut img); + assert_eq!(img.data, orig, "identity warps change nothing, and the cap skips the repeated rest"); + + // a real warp below the cap is still applied + let one = [Opcode::WarpRectilinear { planes: vec![[2.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }]; + apply_list3(&one, &mut img); + assert_ne!(img.data, orig, "a genuine warp record is not skipped"); +} + +#[test] +fn parse_and_apply_area_ops() { + let (w, h) = (4usize, 3usize); + let mut gm = area([0, 0, 3, 4, 0, 1, 1, 1]); + for v in [2u32, 2] { + gm.extend_from_slice(&v.to_be_bytes()); + } + gm.extend(be(&[1.0, 1.0, 0.0, 0.0])); + gm.extend_from_slice(&1u32.to_be_bytes()); + for g in [1.0f32, 2.0, 1.0, 2.0] { + gm.extend_from_slice(&g.to_be_bytes()); + } + let mut dpr = area([0, 0, 3, 4, 0, 1, 1, 1]); + dpr.extend_from_slice(&3u32.to_be_bytes()); + for d in [0.0f32, 0.1, 0.2] { + dpr.extend_from_slice(&d.to_be_bytes()); + } + let mut poly = area([0, 0, 3, 4, 0, 1, 1, 2]); + poly.extend_from_slice(&1u32.to_be_bytes()); + poly.extend(be(&[0.0, 2.0])); + let blob = ListWriter::new().op(9, &gm).op(10, &dpr).op(8, &poly).op(99, &[1, 2, 3]).finish(); + let list = parse_list(&blob); + assert_eq!(list.len(), 4); + assert!(matches!(list[3], Opcode::Unknown { id: 99, .. })); + assert!(list[..3].iter().all(is_applied)); + let mut buf = vec![0.25f32; w * h]; + apply_list(&list, &mut buf, w, h, 1, None, 1.0); + // gain map: horizontal ramp 1 → 2 across relative x 0..1 (x / w) + let expect = |x: usize, y: usize| { + let g = 1.0 + x as f32 / w as f32; + let v = 0.25 * g + [0.0, 0.1, 0.2][y]; + if x.is_multiple_of(2) { v * 2.0 } else { v } + }; + for y in 0..h { + for x in 0..w { + assert!((buf[y * w + x] - expect(x, y)).abs() < 1e-6, "{x},{y}: {} vs {}", buf[y * w + x], expect(x, y)); + } + } +} + +#[test] +fn map_table_raw_scale_and_bad_pixels() { + let mut t = area([0, 0, 2, 2, 0, 1, 1, 1]); + t.extend_from_slice(&3u32.to_be_bytes()); + for v in [0u16, 30000, 65535] { + t.extend_from_slice(&v.to_be_bytes()); + } + let list = parse_list(&ListWriter::new().op(7, &t).finish()); + let mut buf = vec![0.0, 1.0 / 65535.0, 2.0 / 65535.0, 0.5]; + apply_list(&list, &mut buf, 2, 2, 1, None, 1.0); + assert_eq!(buf[0], 0.0); + assert!((buf[1] - 30000.0 / 65535.0).abs() < 1e-7); + assert_eq!(buf[3], 1.0); + + let mut p = vec![]; + for v in [7u32, 0] { + p.extend_from_slice(&v.to_be_bytes()); + } + let list = parse_list(&ListWriter::new().op(4, &p).finish()); + let cfa = Cfa::bayer("RGGB").unwrap(); + let mut img: Vec = (0..36).map(|i| 100.0 + (i % 6) as f32).collect(); + img[2 * 6 + 2] = 7.0; + apply_list(&list, &mut img, 6, 6, 1, Some(&cfa), 65535.0); + assert_eq!(img[2 * 6 + 2], 102.0); +} + +/// A mosaic equal to the bad-pixel constant, or one rectangle over the whole image, used to list every pixel as +/// bad: w × h entries (plus a set of them), tens of GB at the decoder's size limit. Here the rows between a good +/// first row (500) and a good last row (900) are bad: 2052 rows of 2048 pixels, four rows more than the 1 << 22 +/// cap. Row 1, within the cap, is repaired from the first row; the second-last row, past the cap, must be left +/// as it is (uncapped, it was rewritten from the last row). +fn assert_bad_pixels_capped(op: Opcode) { + let (w, h) = (2048, 2054); + let mut buf = vec![0.0f32; w * h]; + buf[..w].fill(500.0); + buf[(h - 1) * w..].fill(900.0); + apply_list(&[op], &mut buf, w, h, 1, None, 65535.0); + assert!(buf[w..2 * w].iter().all(|&v| v == 500.0), "row 1 (within the cap) not repaired: {:?}", &buf[w..w + 4]); + let past = &buf[(h - 2) * w..(h - 1) * w]; + assert!(past.iter().all(|&v| v == 0.0), "a row past the cap was rewritten: {:?}", &past[..4]); +} + +#[test] +fn bad_pixels_constant_is_capped() { + assert_bad_pixels_capped(Opcode::FixBadPixelsConstant { constant: 0, bayer_phase: 0 }); +} + +#[test] +fn bad_pixels_list_is_capped_inside_a_rectangle() { + // top, left, bottom, right: every row but the first and the last + assert_bad_pixels_capped(Opcode::FixBadPixelsList { bayer_phase: 0, points: vec![], rects: vec![[1, 0, 2053, 2048]] }); +} + +#[test] +fn vignette_and_warp_identity() { + let mut img = Rgb32f::from_fn(9, 7, |x, y| [x as f32 / 9.0, y as f32 / 7.0, 0.5]); + let orig = img.clone(); + let mut p = be(&[0.0; 5]); + p.extend(be(&[0.5, 0.5])); + let mut warp = 1u32.to_be_bytes().to_vec(); + warp.extend(be(&[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5])); + let list = parse_list(&ListWriter::new().op(3, &p).op(1, &warp).finish()); + assert_eq!(list.len(), 2); + apply_list3(&list, &mut img); + for (a, b) in img.data.iter().zip(&orig.data) { + for c in 0..3 { + assert!((a[c] - b[c]).abs() < 1e-5); + } + } + // positive k0 brightens the corners more than the centre + let mut p = be(&[1.0, 0.0, 0.0, 0.0, 0.0]); + p.extend(be(&[0.5, 0.5])); + let list = parse_list(&ListWriter::new().op(3, &p).finish()); + let mut flat = Rgb32f::filled(9, 9, [0.5; 3]); + apply_list3(&list, &mut flat); + assert!(flat.get(0, 0)[0] > 0.85 && (flat.get(4, 4)[0] - 0.5).abs() < 0.01, "{:?}", flat.get(0, 0)); +} + +#[test] +fn warp_barrel_moves_pixels_outward() { + let img = Rgb32f::from_fn(31, 31, |x, y| if x == 24 && y == 15 { [1.0; 3] } else { [0.0; 3] }); + // source radius = r (1 + k r²) with k < 0 → content moves outward + let out = warp_rectilinear(&img, &[[1.0, -0.6, 0.0, 0.0, 0.0, 0.0]], [0.5, 0.5]); + let (bx, _) = (0..31).map(|x| (x, out.get(x, 15)[0])).fold((0, 0.0), |a, b| if b.1 > a.1 { b } else { a }); + assert!(bx >= 25, "{bx}"); +} + +#[test] +fn write_parse_roundtrip() { + let a = Area { top: 1, left: 2, bottom: 30, right: 40, plane: 0, planes: 3, row_pitch: 1, col_pitch: 2 }; + let list = vec![ + Opcode::WarpRectilinear { planes: vec![[1.0, 0.01, -0.002, 0.0, 1e-4, -2e-4]; 3], center: [0.5, 0.49] }, + Opcode::WarpFisheye { planes: vec![[1.0, 0.1, 0.0, 0.0]], center: [0.5, 0.5] }, + Opcode::FixVignetteRadial { k: [0.1, 0.2, 0.0, 0.0, 0.0], center: [0.5, 0.5] }, + Opcode::FixBadPixelsConstant { constant: 0, bayer_phase: 1 }, + Opcode::FixBadPixelsList { bayer_phase: 0, points: vec![(3, 4)], rects: vec![[1, 1, 2, 2]] }, + Opcode::TrimBounds { top: 1, left: 1, bottom: 9, right: 9 }, + Opcode::MapTable { area: a, table: vec![0, 100, 65535] }, + Opcode::MapPolynomial { area: a, coefficients: vec![0.0, 1.0, -0.1] }, + Opcode::GainMap { area: a, points_v: 2, points_h: 1, spacing: [1.0, 1.0], origin: [0.0, 0.0], map_planes: 1, gains: vec![1.0, 1.5] }, + Opcode::DeltaPerRow { area: a, deltas: vec![0.1, 0.2] }, + Opcode::DeltaPerColumn { area: a, deltas: vec![0.3] }, + Opcode::ScalePerRow { area: a, scales: vec![1.1] }, + Opcode::ScalePerColumn { area: a, scales: vec![0.9, 1.0] }, + Opcode::WarpRectilinear2 { + planes: vec![wr2_set(&[(0, 0.5), (3, 0.1)]), wr2_set(&[(0, 0.25)])], + center: [0.5, 0.49], + reciprocal: true, + optional: true, + }, + Opcode::Unknown { id: 77, flags: 1, params: vec![1, 2, 3] }, + ]; + assert_eq!(parse_list(&write_list(&list)), list); +} + +#[test] +fn truncated_lists_do_not_panic() { + let mut gm = area([0, 0, 3, 4, 0, 1, 1, 1]); + gm.extend_from_slice(&[0xff; 64]); + let blob = ListWriter::new().op(9, &gm).op(5, &[0xff; 12]).op(1, &[0, 0, 0, 9]).finish(); + for n in 0..blob.len() { + let l = parse_list(&blob[..n]); + let mut buf = vec![0.5f32; 12]; + apply_list(&l, &mut buf, 4, 3, 1, None, 1.0); + } +} + +/// `WarpRectilinear2` parameter bytes (spec 1.6.0.0: N, then per set kr0..kr14, kt0, kt1, min/max valid radius, +/// then the centre and `reciprocalRadial`). +fn wr2_params(sets: &[[f64; WR2_LEN]], center: [f64; 2], reciprocal: u32) -> Vec { + let mut p = (sets.len() as u32).to_be_bytes().to_vec(); + for s in sets { + p.extend(be(s)); + } + p.extend(be(¢er)); + p.extend_from_slice(&reciprocal.to_be_bytes()); + p +} + +fn wr2_set(kr: &[(usize, f64)]) -> [f64; WR2_LEN] { + let mut k = [0.0; WR2_LEN]; + for &(i, v) in kr { + k[i] = v; + } + k[18] = 1.0; + k +} + +#[test] +fn warp_rectilinear2_parses_the_spec_layout() { + let mut k = wr2_set(&[(0, 1.0), (1, 0.25), (14, -2.0)]); + k[15] = 0.001; + k[16] = -0.002; + k[17] = 0.1; + k[18] = 0.9; + let blob = ListWriter::new().op(14, &wr2_params(&[k, wr2_set(&[(0, 1.0)])], [0.5, 0.25], 1)).finish(); + let list = parse_list(&blob); + assert_eq!( + list, + vec![Opcode::WarpRectilinear2 { planes: vec![k, wr2_set(&[(0, 1.0)])], center: [0.5, 0.25], reciprocal: true, optional: false }] + ); + assert!(is_applied(&list[0]) && list[0].is_lens_correction()); + // written back as opcode 14, version 1.6.0.0, optional flag kept + let again = vec![Opcode::WarpRectilinear2 { planes: vec![k], center: [0.5, 0.5], reciprocal: false, optional: true }]; + let bytes = write_list(&again); + assert_eq!(bytes.get(4..8), Some(&14u32.to_be_bytes()[..])); + assert_eq!(bytes.get(8..12), Some(&0x0106_0000u32.to_be_bytes()[..])); + assert_eq!(parse_list(&bytes), again); +} + +#[test] +fn warp_rectilinear2_identity_leaves_the_image() { + let img = Rgb32f::from_fn(21, 15, |x, y| [x as f32 / 21.0, y as f32 / 15.0, 0.25]); + for reciprocal in [false, true] { + let mut i = img.clone(); + let p = wr2_params(&[wr2_set(&[(0, 1.0)])], [0.5, 0.5], reciprocal as u32); + apply_list3(&parse_list(&ListWriter::new().op(14, &p).finish()), &mut i); + for (a, b) in i.data.iter().zip(&img.data) { + for c in 0..3 { + assert!((a[c] - b[c]).abs() < 1e-5, "{a:?} {b:?}"); + } + } + } +} + +#[test] +fn warp_rectilinear2_matches_warp_rectilinear_on_even_terms() { + // kr0 + kr2 r^2 + kr4 r^4 is WarpRectilinear's kr0 + kr1 r^2 + kr2 r^4 + let img = Rgb32f::from_fn(31, 31, |x, y| [(x * 7 % 13) as f32 / 13.0, (y * 5 % 11) as f32 / 11.0, ((x + y) % 4) as f32 / 4.0]); + let a = warp_rectilinear(&img, &[[1.0, -0.3, 0.1, 0.0, 0.01, -0.02]], [0.5, 0.5]); + let mut k = wr2_set(&[(0, 1.0), (2, -0.3), (4, 0.1)]); + k[15] = 0.01; + k[16] = -0.02; + let b = warp_rectilinear2(&img, &[k], [0.5, 0.5], false); + for (p, q) in a.data.iter().zip(&b.data) { + for c in 0..3 { + assert!((p[c] - q[c]).abs() < 1e-5); + } + } + // odd terms, the reciprocal and the valid-radius clamp give the factor the spec defines + let k = wr2_set(&[(0, 1.0), (1, 0.5)]); + assert_eq!(wr2_factor(&k, false, 0.5), Some(1.25)); + assert_eq!(wr2_factor(&k, true, 0.5), Some(0.8)); + let mut k = k; + k[18] = 0.5; // max_valid_radius + assert_eq!(wr2_factor(&k, false, 0.9), Some(1.25)); + k[17] = 0.25; // min_valid_radius + assert_eq!(wr2_factor(&k, false, 0.0), Some(1.125)); + assert_eq!(wr2_factor(&wr2_set(&[]), true, 0.3), None, "1 / 0"); +} + +#[test] +fn malformed_warp_rectilinear2_is_unknown_not_a_panic() { + let good = wr2_params(&[wr2_set(&[(0, 1.0)])], [0.5, 0.5], 0); + let is_wr2 = |p: &[u8]| matches!(parse_list(&ListWriter::new().op(14, p).finish()).as_slice(), [Opcode::WarpRectilinear2 { .. }]); + assert!(is_wr2(&good)); + // every truncation and any trailing byte + for n in 0..good.len() { + assert!(!is_wr2(&good[..n]), "{n}"); + } + assert!(!is_wr2(&[&good[..], &[0u8][..]].concat())); + // N = 0, N too big for the data, N beyond the plane limit + for n in [0u32, 2, 5, u32::MAX] { + let mut p = good.clone(); + p[..4].copy_from_slice(&n.to_be_bytes()); + assert!(!is_wr2(&p), "N = {n}"); + } + // non-finite or absurd values, in a coefficient, the valid range and the centre + let patch = |at: usize, v: f64| { + let mut p = good.clone(); + p[at..at + 8].copy_from_slice(&v.to_be_bytes()); + p + }; + for (at, v) in [ + (4, f64::NAN), + (4 + 8, f64::INFINITY), + (4 + 8 * 3, 1e300), + (4 + 8 * 17, -0.5), + (4 + 8 * 18, 1.5), + (4 + 8 * 17, 1.0), + (4 + 19 * 8, f64::NAN), + (4 + 19 * 8 + 8, 1e30), + ] { + assert!(!is_wr2(&patch(at, v)), "{at} {v}"); + } + // refused ones stay Unknown and are not applied + let list = parse_list(&ListWriter::new().op(14, &good[..10]).finish()); + assert!(matches!(list.as_slice(), [Opcode::Unknown { id: 14, .. }])); + let mut img = Rgb32f::filled(5, 5, [0.5; 3]); + apply_list3(&list, &mut img); + assert_eq!(img.get(2, 2), [0.5; 3]); + // a hostile but accepted set (huge radial terms) still gives a finite image + let k = wr2_set(&[(0, 1.0), (14, 1e9), (13, -1e9)]); + let img = Rgb32f::from_fn(9, 9, |x, y| [x as f32 / 9.0, y as f32 / 9.0, 0.5]); + for reciprocal in [false, true] { + let out = warp_rectilinear2(&img, &[k], [0.5, 0.5], reciprocal); + assert!(out.data.iter().all(|p| p.iter().all(|v| v.is_finite()))); + } +} + +#[test] +fn warp_list_order_and_the_optional_skip_rule() { + let wr2 = |optional| Opcode::WarpRectilinear2 { planes: vec![wr2_set(&[(0, 1.0)])], center: [0.5, 0.5], reciprocal: false, optional }; + let wr = Opcode::WarpRectilinear { planes: vec![[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }; + let fish = Opcode::WarpFisheye { planes: vec![[1.0, 0.0, 0.0, 0.0]], center: [0.5, 0.5] }; + let vig = Opcode::FixVignetteRadial { k: [0.0; 5], center: [0.5, 0.5] }; + let d = std::mem::discriminant::; + let ids = |l: &[Opcode]| applied_ops(l).map(d).collect::>(); + // WarpRectilinear2 (optional) then WarpRectilinear / WarpFisheye: the second is skipped + assert_eq!(ids(&[wr2(true), wr.clone()]), vec![d(&wr2(true))]); + assert_eq!(ids(&[wr2(true), fish.clone()]), vec![d(&wr2(true))]); + // not optional: both run, in list order + assert_eq!(ids(&[wr2(false), wr.clone()]), vec![d(&wr2(false)), d(&wr)]); + // only the opcode immediately after is skipped + assert_eq!(ids(&[wr2(true), vig.clone(), wr.clone()]), vec![d(&wr2(true)), d(&vig), d(&wr)]); + // two in a row: both run, and the WarpRectilinear after the optional second one is skipped + assert_eq!(ids(&[wr2(true), wr2(true), wr.clone()]), vec![d(&wr2(true)); 2]); + // a WarpRectilinear before the WarpRectilinear2 runs, in list order + assert_eq!(ids(&[wr.clone(), wr2(true)]), vec![d(&wr), d(&wr2(true))]); + // the same from bytes: an optional (flag 1) opcode 14 followed by opcode 1 + let w2 = wr2_params(&[wr2_set(&[(0, 1.0)])], [0.5, 0.5], 0); + let mut one = 1u32.to_be_bytes().to_vec(); + one.extend(be(&[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5])); + let mut blob = 2u32.to_be_bytes().to_vec(); + for (id, flags, p) in [(14u32, 1u32, &w2), (1, 1, &one)] { + for v in [id, 0x0106_0000, flags, p.len() as u32] { + blob.extend_from_slice(&v.to_be_bytes()); + } + blob.extend_from_slice(p); + } + let list = parse_list(&blob); + assert_eq!(list.len(), 2); + assert_eq!(applied_ops(&list).count(), 1); + // a refused (Unknown) opcode 14 triggers no skip + let bad = Opcode::Unknown { id: 14, flags: 1, params: vec![] }; + assert!(applied_ops(&[bad, wr]).any(|o| matches!(o, Opcode::WarpRectilinear { .. }))); +} + +/// `cropped` re-expresses a lens correction for a crop: the corrected crop is the crop of the corrected whole. A +/// linear ramp makes bilinear sampling exact, so only the borders (where the warp reaches past the crop) differ. +#[test] +fn cropped_lens_corrections_correct_the_crop_like_the_whole() { + let (w, h) = (90usize, 64usize); + let crop = super::super::Rect::new(7, 5, 70, 50); + let ramp = Rgb32f::from_fn(w, h, |x, y| [0.002 * x as f32 + 0.001 * y as f32 + 0.1, 0.3 + 0.0015 * y as f32, 0.2]); + let mut wr2 = [0.0; WR2_LEN]; + wr2[..5].copy_from_slice(&[1.0, 0.01, -0.03, 0.0, 0.01]); + wr2[15] = 0.002; + wr2[16] = -0.001; + wr2[17] = 0.05; + wr2[18] = 0.9; + let warps = [ + Opcode::WarpRectilinear { planes: vec![[0.97, 0.04, -0.01, 0.002, 0.003, -0.002]], center: [0.47, 0.53] }, + Opcode::WarpRectilinear2 { planes: vec![wr2], center: [0.52, 0.46], reciprocal: false, optional: true }, + Opcode::WarpRectilinear2 { planes: vec![wr2], center: [0.52, 0.46], reciprocal: true, optional: false }, + ]; + for op in &warps { + let mut whole = ramp.clone(); + apply_list3(std::slice::from_ref(op), &mut whole); + let re = op.cropped(w, h, crop).unwrap(); + let mut part = ramp.clone().into_crop(crop.x, crop.y, crop.width, crop.height); + apply_list3(std::slice::from_ref(&re), &mut part); + let mut worst = 0f32; + for y in 6..crop.height - 6 { + for x in 6..crop.width - 6 { + let (a, b) = (whole.data[(y + crop.y) * w + x + crop.x], part.data[y * crop.width + x]); + worst = (0..3).map(|c| (a[c] - b[c]).abs()).fold(worst, f32::max); + } + } + assert!(worst < 1e-4, "{op:?} → {re:?}: {worst}"); + } + // the vignette, in the warps' centre convention the develop pipeline reads it with + let gain = |k: &[f64; 5], c: [f64; 2], w: usize, h: usize, x: f64, y: f64| { + let (aw, ah) = (w as f64 - 1.0, h as f64 - 1.0); + let (px, py) = (c[0] * aw, c[1] * ah); + let r2 = ((x - px).powi(2) + (y - py).powi(2)) / max_radius(px, py, aw, ah).powi(2); + 1.0 + (0..5).map(|i| k[i] * r2.powi(i as i32 + 1)).sum::() + }; + let (k, center) = ([-0.3, 0.1, -0.05, 0.02, -0.01], [0.45, 0.55]); + let Some(Opcode::FixVignetteRadial { k: k2, center: c2 }) = (Opcode::FixVignetteRadial { k, center }).cropped(w, h, crop) else { + panic!("vignette") + }; + for (x, y) in [(0.0, 0.0), (69.0, 49.0), (33.5, 20.0), (69.0, 0.0), (12.0, 40.0)] { + let (a, b) = (gain(&k, center, w, h, x + crop.x as f64, y + crop.y as f64), gain(&k2, c2, crop.width, crop.height, x, y)); + assert!((a - b).abs() < 1e-12, "({x}, {y}): {a} vs {b}"); + } + // no change for a full-frame "crop"; nothing for other opcodes, tiny images or a crop past the edge + assert_eq!(warps[0].cropped(w, h, super::super::Rect::new(0, 0, w, h)).unwrap(), warps[0]); + assert!(Opcode::TrimBounds { top: 0, left: 0, bottom: 2, right: 2 }.cropped(w, h, crop).is_none()); + assert!(warps[0].cropped(1, h, super::super::Rect::new(0, 0, 1, h)).is_none()); + assert!(warps[0].cropped(w, h, super::super::Rect::new(30, 0, 70, 50)).is_none()); + assert!(warps[0].cropped(w, h, super::super::Rect::new(usize::MAX, 0, 70, 50)).is_none()); +} + +/// Ten thousand full-image polynomials (a few hundred KB of opcode data): the list is held to +/// `MAX_LIST_PASSES` passes of work, the first ones applied and the rest left out. +#[test] +fn a_list_repeating_full_image_work_stops_at_its_budget() { + let (w, h) = (64usize, 48usize); + let a = Area { top: 0, left: 0, bottom: h as u32, right: w as u32, plane: 0, planes: 1, row_pitch: 1, col_pitch: 1 }; + // v + 0.001 each, two coefficients: each costs two passes + let list = vec![Opcode::MapPolynomial { area: a, coefficients: vec![0.001, 1.0] }; 10_000]; + let mut buf = vec![0.0f32; w * h]; + apply_list(&list, &mut buf, w, h, 1, None, 1.0); + let applied = (buf[0] / 0.001).round() as usize; + assert_eq!(applied, MAX_LIST_PASSES / 2, "{}", buf[0]); + assert!(buf.iter().all(|v| *v == buf[0])); +} + +/// Opcodes `apply_list` does nothing for spend none of the budget: a later real one still runs. +#[test] +fn ops_that_apply_nothing_cost_no_budget() { + let (w, h) = (8usize, 8usize); + let a = Area { top: 0, left: 0, bottom: h as u32, right: w as u32, plane: 0, planes: 1, row_pitch: 1, col_pitch: 1 }; + let mut list = vec![Opcode::Unknown { id: 9999, flags: 0, params: Vec::new() }; 4 * MAX_LIST_PASSES]; + list.push(Opcode::MapPolynomial { area: a, coefficients: vec![0.5, 1.0] }); + let mut buf = vec![0.0f32; w * h]; + apply_list(&list, &mut buf, w, h, 1, None, 1.0); + assert_eq!(buf[0], 0.5); +} diff --git a/crates/develop/src/tests_crystal.rs b/crates/develop/src/tests_crystal.rs new file mode 100644 index 0000000000..672a598c54 --- /dev/null +++ b/crates/develop/src/tests_crystal.rs @@ -0,0 +1,662 @@ +use super::*; + +/// The draws [`hold_for_waiters`] holds, by cache: how many renders wait for each, and how many +/// draws are left to hold. +static HOLDS: Mutex> = Mutex::new(Vec::new()); + +/// Holds the draw of `d` until the renders [`HOLDS`] names for its cache are waiting for it (each +/// holds a clone of its slot, as do the drawing and its in-flight entry), so a test can make +/// renders miss a tile together. +pub(super) fn hold_for_waiters(d: &Drawing) { + let waiters = { + let mut holds = HOLDS.lock().unwrap_or_else(PoisonError::into_inner); + let Some(h) = holds.iter_mut().find(|h| h.0 == d.id.0 && h.2 > 0) else { return }; + h.2 -= 1; + h.1 + }; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while Arc::strong_count(&d.done) < 2 + waiters { + assert!(std::time::Instant::now() < deadline, "the renders never waited"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +/// The caches [`evict_before_waking`] empties. +static EVICTS: Mutex> = Mutex::new(Vec::new()); + +/// Empties `cache` if [`EVICTS`] names it, after its drawer `d` has cached its tile and before it +/// wakes the renders waiting for it, as other renders' tiles can push it out in that gap. +pub(super) fn evict_before_waking(cache: &Cache, d: &Drawing) { + if EVICTS.lock().unwrap_or_else(PoisonError::into_inner).contains(&d.id.0) { + cache.lock().unwrap_or_else(PoisonError::into_inner).clear(); + } +} + +/// Waits until `n` renders wait for the draw of `d`. +fn until_waiting(d: &Drawing, n: usize) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while Arc::strong_count(&d.done) < 2 + n { + assert!(std::time::Instant::now() < deadline, "the renders never waited"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +/// The field rendered at `long` px per long edge on an `n × n` patch starting at pixel `origin`. +fn patch(tile: &CrystalTile, long: f64, n: usize, origin: usize) -> Vec { + let w = (TILE_PER_LONG / long) as f32; + (0..n * n).map(|k| tile.field(((origin + k % n) as f32 + 0.5) * w, ((origin + k / n) as f32 + 0.5) * w, w)).collect() +} + +fn std(v: &[f32]) -> f64 { + let m = v.iter().map(|&x| x as f64).sum::() / v.len() as f64; + (v.iter().map(|&x| (x as f64 - m).powi(2)).sum::() / v.len() as f64).sqrt() +} + +/// Lag (px) at which the autocorrelation (mean of horizontal and vertical) falls to ½. +fn half_width(v: &[f32], n: usize) -> f64 { + let m = v.iter().map(|&x| x as f64).sum::() / v.len() as f64; + let d: Vec = v.iter().map(|&x| x as f64 - m).collect(); + let var = d.iter().map(|x| x * x).sum::() / d.len() as f64; + let corr = |k: usize, horizontal: bool| { + let mut s = 0.0; + let mut c = 0usize; + for y in 0..n - if horizontal { 0 } else { k } { + for x in 0..n - if horizontal { k } else { 0 } { + let b = if horizontal { y * n + x + k } else { (y + k) * n + x }; + s += d[y * n + x] * d[b]; + c += 1; + } + } + s / c as f64 / var + }; + let mut out = 0.0; + for horizontal in [true, false] { + let mut prev = 1.0; + let mut w = 16.0; + for k in 1..16 { + let c = corr(k, horizontal); + if c <= 0.5 { + w = k as f64 - 1.0 + (prev - 0.5) / (prev - c).max(1e-9); + break; + } + prev = c; + } + out += w / 2.0; + } + out +} + +fn tile_of(size: f64, roughness: f64) -> Arc { + tile(CrystalLook::new(size, roughness), 7, true).expect("a tile") +} + +#[test] +fn reference_render_has_unit_variance_and_no_mean() { + let t = tile_of(25.0, 50.0); + let v = patch(&t, REF_LONG, 600, 37); + let m = v.iter().map(|&x| x as f64).sum::() / v.len() as f64; + assert!((std(&v) - 1.0).abs() < 0.05, "std {}", std(&v)); + assert!(m.abs() < 0.03, "mean {m}"); +} + +#[test] +fn small_render_is_the_downscaled_reference() { + for (size, rough) in [(0.0, 50.0), (25.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] { + let t = tile_of(size, rough); + for k in [2usize, 4, 8] { + let full = patch(&t, REF_LONG, 120 * k, 0); + let n = 120; + let down: Vec = (0..n * n) + .map(|q| { + let (x, y) = (q % n, q / n); + let mut s = 0.0; + for dy in 0..k { + for dx in 0..k { + s += full[(y * k + dy) * n * k + x * k + dx]; + } + } + s / (k * k) as f32 + }) + .collect(); + let small = patch(&t, REF_LONG / k as f64, n, 0); + let worst = down.iter().zip(&small).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(worst < 2e-3, "size {size} roughness {rough} 1/{k}: differs by {worst}"); + } + } +} + +#[test] +fn strength_matches_the_target_at_mid_grey() { + for (a, s, r) in [(50.0, 25.0, 50.0), (25.0, 25.0, 50.0), (50.0, 0.0, 50.0), (50.0, 100.0, 50.0), (50.0, 25.0, 0.0)] { + let g = CrystalGrain::new(&Grain { amount: a, size: s, roughness: r, seed: 3 }, REF_LONG).expect("grain"); + let n = 500; + let lum: Vec = (0..n * n) + .map(|k| { + let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5); + let e = g.apply([MID_GREY; 3], x / REF_LONG as f32, y / REF_LONG as f32); + (0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]) * 255.0 + }) + .collect(); + let want = strength_levels(a, s, r); + assert!((std(&lum) / want - 1.0).abs() < 0.06, "{a}/{s}/{r}: {} levels, want {want}", std(&lum)); + } +} + +#[test] +fn tones_keep_their_mean() { + // the strongest settings in the shadows; near white, strong grain clips at 255 like any grain + let cases = [ + (100.0, 0.0, &[5.0f32, 20.0, 40.0, 60.0, 128.0, 255.0][..]), + (50.0, 0.0, &[200.0, 245.0][..]), + (50.0, 25.0, &[20.0, 128.0, 245.0, 255.0][..]), + ]; + for (amount, size, levels) in cases { + let g = CrystalGrain::new(&Grain { amount, size, roughness: 50.0, seed: 3 }, REF_LONG).expect("grain"); + for &level in levels { + let n = 400; + let mut sum = 0.0f64; + for k in 0..n * n { + let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5); + let e = g.apply([level / 255.0; 3], x / REF_LONG as f32, y / REF_LONG as f32); + sum += (e[1].clamp(0.0, 1.0) * 255.0) as f64; + } + let shift = sum / (n * n) as f64 - level as f64; + assert!(shift.abs() < 0.5, "{amount}/{size}: level {level} moved {shift:+.2}"); + } + } +} + +#[test] +fn hostile_settings_render_finite_or_no_grain() { + let bad = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1e9, 1e9, 0.0]; + for &a in &bad { + for &s in &bad { + for &ppl in &[f64::NAN, 0.0, -5.0, 1.0, 24.0, 1e12, 6000.0] { + let g = Grain { amount: if a == 0.0 { 50.0 } else { a }, size: s, roughness: s, seed: u32::MAX }; + if let Some(c) = CrystalGrain::new(&g, ppl) { + for (x, y) in [(0.0, 0.0), (-3.5, 1e7), (f32::NAN, 0.2), (0.5, f32::INFINITY), (1.0, 0.6667)] { + let e = c.apply([0.5, 0.2, 0.9], x, y); + assert!(e.iter().all(|v| v.is_finite()), "{g:?} at {ppl}: {e:?}"); + } + } + } + } + } +} + +#[test] +fn seed_picks_the_pattern() { + let look = CrystalLook::new(25.0, 50.0); + let (Some(a), Some(c)) = (tile(look, 1, true), tile(look, 2, true)) else { panic!("tiles") }; + assert_ne!(patch(&a, REF_LONG, 64, 0), patch(&c, REF_LONG, 64, 0)); +} + +/// A tile drawn again (its cache entry evicted, another process, an export after a preview) is the +/// same to the bit, however many threads draw it. These draw directly: through [`tile`], the second +/// would be the first one out of the cache. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_tile_draws_the_same_every_time() { + let look = CrystalLook::new(25.0, 50.0); + let one_thread = rayon::ThreadPoolBuilder::new().num_threads(1).build().expect("a pool"); + let (Some(a), Some(b)) = (CrystalTile::new(look, 1), one_thread.install(|| CrystalTile::new(look, 1))) else { panic!("tiles") }; + assert!(a.sats == b.sats, "the same seed drew different tiles"); +} + +/// Every seed has the same mix of crystal sizes, dealt to the layers in its own order. +#[test] +fn seeds_share_the_mix_of_crystal_sizes() { + let look = CrystalLook::new(50.0, 80.0); + let radii = |seed| emulsion(seed, &look).iter().map(|l| l.r).collect::>(); + let sorted = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v + }; + let (a, b) = (radii(1), radii(2)); + assert_eq!(a.len(), look.layers); + assert_eq!(a, radii(1), "the same seed deals the same order"); + assert_ne!(a, b, "another seed deals another order"); + assert_eq!(sorted(a), sorted(b)); + assert_eq!(emulsion(1, &CrystalLook { layers: 0, ..look }).len(), 1, "an emulsion has a layer"); +} + +#[test] +fn sliders_clamp_and_fall_back() { + let look = CrystalLook::new; + assert_eq!(look(f64::NAN, f64::NAN), look(25.0, 50.0), "NaN is the default"); + assert_eq!(look(-1e9, f64::NEG_INFINITY), look(0.0, 0.0)); + assert_eq!(look(1e9, f64::INFINITY), look(100.0, 100.0)); + // the ends of the tables + assert_eq!((look(0.0, 50.0).width, look(0.0, 50.0).layers), (0.55, 16)); + assert_eq!((look(100.0, 50.0).width, look(100.0, 50.0).layers), (12.38, 70)); + assert_eq!(look(100.0, 0.0).width, 12.38 * 0.734); + assert_eq!(look(100.0, 100.0).width, 12.38 * 1.422); + assert!(look(25.0, 100.0).spread > look(25.0, 0.0).spread); + + let default = strength_levels(50.0, 25.0, 50.0); + assert_eq!(strength_levels(f64::NAN, 25.0, 50.0), 0.0, "a NaN Amount is no grain"); + assert_eq!(strength_levels(-5.0, 25.0, 50.0), 0.0); + assert_eq!(strength_levels(50.0, f64::NAN, f64::NAN), default); + assert_eq!(strength_levels(1e9, 25.0, 50.0), 2.0 * default); + assert_eq!(strength_levels(50.0, -1e9, 50.0), strength_levels(50.0, 0.0, 50.0)); + assert_eq!(strength_levels(50.0, 25.0, f64::INFINITY), strength_levels(50.0, 25.0, 100.0)); + // Lightroom Classic's at the ends of each slider (`docs/grain.md`) + for (want, (a, s, r)) in [(23.08, (50.0, 0.0, 50.0)), (5.83, (50.0, 100.0, 50.0)), (12.42, (50.0, 25.0, 0.0)), (11.68, (50.0, 25.0, 100.0))] { + let got = strength_levels(a, s, r); + assert!((got / want - 1.0).abs() < 0.01, "{a}/{s}/{r}: {got}, want {want}"); + } +} + +#[test] +fn interp_is_linear_between_knots_and_constant_outside() { + let knots = [(0.0, 1.0), (10.0, 3.0), (20.0, 2.0)]; + for (x, want) in [(-5.0, 1.0), (0.0, 1.0), (5.0, 2.0), (10.0, 3.0), (15.0, 2.5), (20.0, 2.0), (99.0, 2.0)] { + assert_eq!(interp(&knots, x), want, "at {x}"); + } + assert_eq!(interp(&[], 5.0), 0.0); + assert_eq!(interp(&[(3.0, 7.0)], 5.0), 7.0); +} + +#[test] +fn normal_quantile_matches_the_table() { + for (p, z) in [(0.5, 0.0), (0.975, 1.959_963_985), (0.841_344_746, 1.0), (0.001, -3.090_232_306), (1e-6, -4.753_424_309)] { + assert!((normal_quantile(p) - z).abs() < 1e-7, "at {p}: {}, want {z}", normal_quantile(p)); + assert!((normal_quantile(1.0 - p) + z).abs() < 1e-7, "at 1 - {p}"); + } + // increasing across the approximation's joins (0.02425 and its mirror), finite at the ends + let sweep: Vec = (0..=1000).map(|k| normal_quantile(k as f64 / 1000.0)).collect(); + assert!(sweep.iter().all(|z| z.is_finite())); + assert!(sweep.windows(2).all(|w| w[0] < w[1])); +} + +#[test] +fn poisson_counts_have_the_mean_and_variance_of_mu() { + let n = 40_000u32; + for mu in [0.5, 4.0, 40.0, 150.0] { + let cdf = poisson_cdf(mu); + assert!(cdf.windows(2).all(|w| w[0] <= w[1]), "mu {mu}: the distribution must not fall"); + assert!(cdf.last().is_some_and(|&c| c >= 1.0 - 1e-12), "mu {mu}: the distribution must reach 1"); + let draws: Vec = (0..n).map(|i| poisson(&cdf, mix(i)) as f64).collect(); + let mean = draws.iter().sum::() / n as f64; + let var = draws.iter().map(|d| (d - mean).powi(2)).sum::() / n as f64; + assert!((mean - mu).abs() < 4.0 * (mu / n as f64).sqrt(), "mu {mu}: mean {mean}"); + assert!((var / mu - 1.0).abs() < 0.05, "mu {mu}: variance {var}"); + } +} + +#[test] +fn poisson_stays_in_range_at_the_ends() { + for h in [0, u32::MAX] { + assert_eq!(poisson(&poisson_cdf(0.0), h), 0, "mean 0 is never a crystal"); + // past what the model uses, e^-mu underflows: a capped count, not a panic + assert!(poisson(&poisson_cdf(1e6), h) <= 512); + assert_eq!(poisson(&[], h), 0); + } +} + +#[test] +fn summed_area_matches_brute_force() { + let t = 7; + let count: Vec = (0..t * t).map(|i| (mix(i as u32) % 71) as u8).collect(); + let sat = summed_area(&count, t); + assert_eq!(sat.len(), (t + 1) * (t + 1)); + for y in 0..=t { + for x in 0..=t { + let want: u32 = (0..y).flat_map(|j| (0..x).map(move |i| (i, j))).map(|(i, j)| count[j * t + i] as u32).sum(); + assert_eq!(sat[y * (t + 1) + x], want, "[0, {x}) × [0, {y})"); + } + } +} + +/// Boxes against the emulsion's own pixels (each table's counts, less their mean, scaled to unit +/// variance as [`CrystalTile::new`] does), integrated by hand. Whole and fractional boxes, across +/// the torus's seams, at negative coordinates and periods away. +#[test] +fn box_sum_is_the_integral_of_the_emulsion() { + let (look, seed) = (CrystalLook::new(25.0, 50.0), 7); + let tile = CrystalTile::new(look, seed).expect("a tile"); + let counts = [0, 1].map(|which| draw_torus(which, TORI[which], seed, &look)); + let means: [f64; 2] = [0, 1].map(|w| counts[w].iter().map(|&c| c as f64).sum::() / (TORI[w] * TORI[w]) as f64); + let var: f64 = [0, 1] + .map(|w| { + let (sq, n) = reference_square_sum(&counts[w], TORI[w], means[w]); + sq / n as f64 + }) + .iter() + .sum(); + let k = 1.0 / var.sqrt(); + // The overlap of the cell at `i` with `[a, a + w]`. + let overlap = |i: i64, a: f64, w: f64| ((i + 1) as f64).min(a + w) - (i as f64).max(a); + let integral_by_hand = |which: usize, x0: f32, y0: f32, w: f32| { + let (x0, y0, w, t) = (x0 as f64, y0 as f64, w as f64, TORI[which] as i64); + let mut sum = 0.0; + for j in y0.floor() as i64..(y0 + w).ceil() as i64 { + for i in x0.floor() as i64..(x0 + w).ceil() as i64 { + let c = counts[which][(j.rem_euclid(t) * t + i.rem_euclid(t)) as usize] as f64; + sum += (c - means[which]) * k * overlap(i, x0, w) * overlap(j, y0, w); + } + } + sum + }; + for which in [0, 1] { + let t = TORI[which] as f32; + for (x0, y0, w) in [ + (0.0, 0.0, 2.0), + (100.0, 200.0, 37.0), + (3.25, 7.5, 2.0), + (10.6, 11.3, 0.7), + (50.5, 60.25, 400.0), + (t - 1.5, 20.0, 4.0), + (20.0, t - 1.5, 4.0), + (t - 0.5, t - 0.25, 31.0), + (-1.5, -2.25, 8.0), + (3.0 * t + 12.5, -2.0 * t + 40.5, 8.0), + ] { + let (got, want) = (tile.box_sum(which, x0, y0, w) as f64, integral_by_hand(which, x0, y0, w)); + let area = (w * w) as f64; + assert!((got - want).abs() / area < 2e-3, "torus {which}, ({x0}, {y0}) side {w}: {got} vs {want}"); + } + } + // the field is the two tori's mean, centred on its position + let (x, y, w) = (640.25, 1133.5, 3.0); + let want = (integral_by_hand(0, x - 0.5 * w, y - 0.5 * w, w) + integral_by_hand(1, x - 0.5 * w, y - 0.5 * w, w)) / (w * w) as f64; + assert!((tile.field(x, y, w) as f64 - want).abs() < 2e-3, "field {} vs {want}", tile.field(x, y, w)); +} + +/// A render under the footprint limit gets grain, one at or past it none, whatever else it asks. +#[test] +fn only_a_render_past_the_footprint_limit_loses_its_grain() { + let g = Grain { amount: 50.0, size: 25.0, roughness: 50.0, seed: 3 }; + let limit = TILE_PER_LONG / MAX_FOOTPRINT as f64; + assert_eq!(limit, 24.0); + for none in [limit, limit - 1.0, 1.0, 0.0, -5.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(CrystalGrain::new(&g, none).is_none(), "{none} px per long edge"); + } + assert_eq!(CrystalGrain::new(&g, limit + 1.0).expect("grain").foot, 480.0); + assert_eq!(CrystalGrain::new(&g, REF_LONG).expect("grain").foot, 2.0); + assert!(CrystalGrain::new(&Grain { amount: 0.0, ..g }, REF_LONG).is_none(), "no grain at Amount 0"); +} + +/// A draft (a Size or Roughness drag) doesn't wait for a new tile: the last tile of the seed stands +/// in while the new one is drawn in the background, and then the drag gets it. A render that +/// waits always gets the exact tile, as does a draft for a seed with no tile yet. +#[test] +fn a_drag_takes_the_last_tile_while_the_next_is_drawn() { + // a cache of its own: other tests' tiles (through any V7 render) would evict from the shared one + static OWN: Cache = Mutex::new(Vec::new()); + let tile = |look, seed, wait| tile_in(&OWN, look, seed, wait); + let (seed, fresh) = (0x0d4a_0001, 0x0d4a_0002); + let (a, b) = (CrystalLook::new(30.0, 50.0), CrystalLook::new(31.0, 50.0)); + let exact = |look: CrystalLook, seed: u32| patch(&CrystalTile::new(look, seed).expect("tile"), REF_LONG, 32, 0); + let first = tile(a, seed, true).expect("tile"); + assert_eq!(first.look, a); + let stand_in = tile(b, seed, false).expect("tile"); + assert_eq!(stand_in.look, a, "the draft waited for its tile"); + // the drag's next renders get the new tile once it is drawn + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + let drawn = loop { + let t = tile(b, seed, false).expect("tile"); + if t.look == b { + break t; + } + assert!(std::time::Instant::now() < deadline, "the background tile never arrived"); + std::thread::sleep(std::time::Duration::from_millis(5)); + }; + assert_eq!(patch(&drawn, REF_LONG, 32, 0), exact(b, seed)); + assert_eq!(patch(&tile(b, seed, true).expect("tile"), REF_LONG, 32, 0), exact(b, seed)); + // nothing drawn for this seed: nothing to stand in, the draft draws it + assert_eq!(patch(&tile(a, fresh, false).expect("tile"), REF_LONG, 32, 0), exact(a, fresh)); +} + +/// A render that misses a tile another thread is drawing waits for that tile rather than drawing +/// it a second time. +#[test] +fn a_render_waits_for_a_tile_being_drawn() { + static OWN: Cache = Mutex::new(Vec::new()); + let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0003); + let key = key_of(look, seed); + let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet"); + let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true)); + until_waiting(&marker, 1); + let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile")); + keep(&OWN, key, drawn.clone()); + drop(marker); + let got = render.join().expect("render thread").expect("tile"); + assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); +} + +/// A render waiting for a tile gets it from its drawer even when the cache evicted it before the +/// render woke. +#[test] +fn a_waiting_render_gets_the_tile_the_cache_evicted() { + static OWN: Cache = Mutex::new(Vec::new()); + let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0004); + let key = key_of(look, seed); + let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet"); + let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true)); + until_waiting(&marker, 1); + let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile")); + marker.finish(&drawn); + keep(&OWN, key, drawn.clone()); + // other renders' tiles push it out of the cache before the waiter wakes + // (each its own tile: a waiter that took another key's would fail the check below) + for other in 1..=CACHE as u32 { + keep(&OWN, key_of(look, seed + other), Arc::new(CrystalTile::new(look, seed + other).expect("tile"))); + } + assert!(cached(&OWN, key).is_none(), "the tile is still cached"); + drop(marker); + let got = render.join().expect("render thread").expect("tile"); + assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); +} + +/// A render waiting for a tile another render is drawing gets the drawer's tile even when the +/// cache drops it before the waiter wakes. +#[test] +fn a_render_drawing_a_tile_hands_it_to_its_waiter() { + static OWN: Cache = Mutex::new(Vec::new()); + let id = std::ptr::from_ref(&OWN) as usize; + // the first render's draw (only: a second would be the waiter drawing it again) waits for the + // second render to wait for it, and the cache empties before the second wakes + HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((id, 1, 1)); + EVICTS.lock().unwrap_or_else(PoisonError::into_inner).push(id); + let (look, seed) = (CrystalLook::new(0.0, 50.0), 0x0d4a_0005); + let renders: Vec<_> = (0..2).map(|_| std::thread::spawn(move || tile_in(&OWN, look, seed, true))).collect(); + let got: Vec<_> = renders.into_iter().map(|r| r.join().expect("render thread").expect("tile")).collect(); + assert!(cached(&OWN, key_of(look, seed)).is_none(), "the cache kept the tile"); + assert!(Arc::ptr_eq(&got[0], &got[1]), "the waiter drew the tile again"); +} + +/// Renders that miss the same tile together draw it once: the first registers the draw and the +/// others wait for it, as no gap lets a second render find it neither cached nor being drawn. +/// The first draw is held until the other renders all wait for it, so the misses overlap. +#[test] +fn renders_that_miss_a_tile_together_draw_it_once() { + static OWN: Cache = Mutex::new(Vec::new()); + const N: usize = 8; + // the first render's draw waits for the other seven to miss the tile too + const SEEDS: u32 = 40; + HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((std::ptr::from_ref(&OWN) as usize, N - 1, SEEDS as usize)); + let look = CrystalLook::new(0.0, 50.0); + for seed in 0x0d4a_1000..0x0d4a_1000 + SEEDS { + let start = Arc::new(std::sync::Barrier::new(N)); + let renders: Vec<_> = (0..N) + .map(|_| { + let start = start.clone(); + std::thread::spawn(move || { + start.wait(); + tile_in(&OWN, look, seed, true) + }) + }) + .collect(); + let got: Vec<_> = renders.into_iter().map(|r| r.join().expect("render thread").expect("tile")).collect(); + assert!(got.iter().all(|t| Arc::ptr_eq(t, &got[0])), "seed {seed:#x}: a render drew the tile again"); + } +} + +/// Grain width (autocorrelation half-width at mid grey, 6000 px) at Lightroom Classic's +/// measured settings (open PR #1060's table); Size 0 is as fine as uncorrelated pixels get (0.5). +#[test] +fn width_matches_lightroom_classic() { + let lrc = [(0.0, 50.0, 0.5), (25.0, 50.0, 1.13), (100.0, 50.0, 3.38), (25.0, 0.0, 0.86), (25.0, 100.0, 1.54)]; + for (s, r, want) in lrc { + let got = half_width(&patch(&tile_of(s, r), REF_LONG, 360, 0), 360); + assert!((got / want - 1.0).abs() < 0.1, "size {s} roughness {r}: width {got:.3}, want {want}"); + } +} + +/// Prints how long drawing a tile takes per setting (`--ignored --nocapture`, alone). +#[test] +#[ignore] +fn tile_timing_report() { + for (s, r) in [(0.0, 50.0), (10.0, 50.0), (25.0, 50.0), (50.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0), (100.0, 100.0)] { + let look = CrystalLook::new(s, r); + let mut best = f64::INFINITY; + for seed in 0..5 { + let start = std::time::Instant::now(); + let t = CrystalTile::new(look, 100 + seed); + best = best.min(start.elapsed().as_secs_f64() * 1e3); + assert!(t.is_some()); + } + eprintln!("size {s:>5} roughness {r:>5}: {best:.1} ms ({:?})", look); + } +} + +/// Fits the median crystal width per Size (Roughness 50) and the Roughness factors at Size 25 to +/// Lightroom Classic's grain widths (`--ignored --nocapture`; paste into the look tables). +#[test] +#[ignore] +fn fit_widths() { + let width_of = |look: CrystalLook| { + let mut w = 0.0; + for seed in [11, 12] { + let t = CrystalTile::new(look, seed).expect("tile"); + w += half_width(&patch(&t, REF_LONG, 360, 0), 360) / 2.0; + } + w + }; + let fit = |s: f64, r: f64, want: f64| { + let base = CrystalLook::new(s, r); + let (mut lo, mut hi) = (0.05f64, 40.0f64); + for _ in 0..18 { + let mid = (lo * hi).sqrt(); + if width_of(CrystalLook { width: mid, ..base }) < want { lo = mid } else { hi = mid } + } + let d = (lo * hi).sqrt(); + (d, width_of(CrystalLook { width: d, ..base })) + }; + for (s, want) in [(0.0, 0.43), (10.0, 0.71), (25.0, 1.13), (50.0, 1.70), (75.0, 2.54), (100.0, 3.38)] { + let (d, got) = fit(s, 50.0, want); + eprintln!("size {s}: width {d:.3} gives {got:.3} (want {want})"); + } + let (d50, _) = fit(25.0, 50.0, 1.13); + for (r, want) in [(0.0, 0.86), (100.0, 1.54)] { + let (d, got) = fit(25.0, r, want); + eprintln!("roughness {r}: factor {:.3} gives {got:.3} (want {want})", d / d50); + } +} + +/// Autocorrelation at lags 1–4 and the strength kept by box downscales of 2–16 (relative), of +/// candidate looks (`--ignored --nocapture`): compares a look's texture with a reference's. +#[test] +#[ignore] +fn texture_report() { + let profile = |look: CrystalLook| { + let n = 512; + let (mut acf, mut down) = ([0.0; 4], [0.0; 4]); + for seed in [21, 22] { + let t = CrystalTile::new(look, seed).expect("tile"); + let v = patch(&t, REF_LONG, n, 0); + let s0 = std(&v); + for (k, a) in acf.iter_mut().enumerate() { + let lag = k + 1; + let mut s = 0.0f64; + for y in 0..n { + for x in 0..n - lag { + s += (v[y * n + x] * v[y * n + x + lag] + v[x * n + y] * v[(x + lag) * n + y]) as f64; + } + } + *a += s / (2 * n * (n - lag)) as f64 / (s0 * s0) / 2.0; + } + for (k, d) in down.iter_mut().enumerate() { + let f = 2usize << k; + let m = n / f; + let b: Vec = (0..m * m) + .map(|q| { + let (x, y) = (q % m * f, q / m * f); + (0..f * f).map(|i| v[(y + i / f) * n + x + i % f]).sum::() / (f * f) as f32 + }) + .collect(); + *d += std(&b) / s0 / 2.0; + } + } + (acf, down) + }; + for (s, r) in [(25.0, 50.0), (50.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] { + let (a, d) = profile(CrystalLook::new(s, r)); + eprintln!( + "size {s} roughness {r}: acf {:.2} {:.2} {:.2} {:.2} down {:.2} {:.2} {:.2} {:.3}", + a[0], a[1], a[2], a[3], d[0], d[1], d[2], d[3] + ); + } +} + +/// A row computed with shared box edges equals the per-pixel boxes: any size, mirrored rows, rows +/// across the tori's seams and far from the origin. +#[test] +fn row_field_matches_per_pixel_field() { + let t = tile_of(25.0, 50.0); + for (w, sign, x, y) in [ + (2.0f32, 1.0f32, 3.3f32, 7.9f32), + (2.0, -1.0, 9000.2, 1275.0), + (8.0, 1.0, 11990.0, 2260.5), + (0.7, 1.0, 1279.6, 0.1), + (31.0, -1.0, 400.0, 1133.9), + ] { + for along_x in [true, false] { + let mut row = vec![0.0f32; 700]; + t.row_field(x, y, w, sign * w, along_x, &mut row); + for (k, &v) in row.iter().enumerate() { + let d = sign * w * k as f32; + let want = if along_x { t.field(x + d, y, w) } else { t.field(x, y + d, w) }; + assert!((v - want).abs() < 2e-3, "w {w} sign {sign} x {along_x} from ({x}, {y}), pixel {k}: {v} vs {want}"); + } + } + } +} + +/// Per-pixel cost of the grain on one thread (`--ignored --nocapture`). +#[test] +#[ignore] +fn pixel_cost_report() { + let g = CrystalGrain::new(&Grain { amount: 50.0, size: 25.0, roughness: 50.0, seed: 1 }, REF_LONG).expect("grain"); + let (w, h) = (4000usize, 600usize); + let mut sink = 0.0f32; + let t0 = std::time::Instant::now(); + for y in 0..h { + for x in 0..w { + sink += g.tile.field((x as f32 + 0.5) * 2.0, (y as f32 + 0.5) * 2.0, 2.0); + } + } + let per_pixel = t0.elapsed().as_secs_f64() / (w * h) as f64 * 1e9; + let mut row = vec![0.0; w]; + let t1 = std::time::Instant::now(); + for y in 0..h { + g.tile.row_field(1.0, (y as f32 + 0.5) * 2.0, 2.0, 2.0, true, &mut row); + sink += row[7]; + } + let per_row = t1.elapsed().as_secs_f64() / (w * h) as f64 * 1e9; + let t3 = std::time::Instant::now(); + for y in 0..h { + g.tile.row_field((y as f32 + 0.5) * 2.0, 1.0, 2.0, 2.0, false, &mut row); + sink += row[7]; + } + eprintln!("column {:.1} ns/px", t3.elapsed().as_secs_f64() / (w * h) as f64 * 1e9); + let t2 = std::time::Instant::now(); + for y in 0..h { + for x in 0..w { + sink += g.apply_field([0.4, 0.5, 0.6], (x + y) as f32 * 1e-4)[1]; + } + } + let tone = t2.elapsed().as_secs_f64() / (w * h) as f64 * 1e9; + eprintln!("field {per_pixel:.1} ns/px, row {per_row:.1} ns/px, tone {tone:.1} ns/px ({sink})"); +} diff --git a/crates/develop/tests/it/balanced.rs b/crates/develop/tests/it/balanced.rs new file mode 100644 index 0000000000..4c85843041 --- /dev/null +++ b/crates/develop/tests/it/balanced.rs @@ -0,0 +1,655 @@ +//! Original synthetic RAW scenes from storytold/lightcraft#1463, generated in these tests. + +use craft_develop::raster::Rgb32f; +use craft_develop::sensor::{Method, RawDevelopExt, highlight}; +use craft_raw::opcodes::{Opcode, OpcodeLists}; +use craft_raw::{BlackLevel, Cfa, ColorData, Orientation, RawData, RawFormat, RawImage, Rect}; + +/// Daylight-like as-shot multipliers (a Sony body's are about 2.6 : 1 : 1.85). +const DAYLIGHT: [f32; 3] = [2.5, 1.0, 1.6]; +const CLIP: f32 = 0.99; + +/// A floating-point raw (black 0, white 1) whose mosaic samples `scene` (white-balanced RGB) through `cfa`, divided +/// by `wb` as a sensor records it, and clipped at the white level. +fn raw_of(w: usize, h: usize, cfa: &Cfa, wb: [f32; 3], scene: impl Fn(usize, usize) -> [f32; 3]) -> RawImage { + let data = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let c = cfa.color_at(x, y) as usize; + (scene(x, y)[c] / wb[c]).min(1.0) + }) + .collect(); + RawImage { + format: RawFormat::Dng, + width: w, + height: h, + cpp: 1, + data: RawData::F32(data), + cfa: Some(cfa.clone()), + bits: 16, + black: BlackLevel::uniform(0.0), + white: vec![1.0], + active_area: Rect::new(0, 0, w, h), + crop: Rect::new(0, 0, w, h), + orientation: Orientation::Normal, + color: ColorData::default(), + wb_multipliers: None, + linearized: true, + pixel_aspect: 1.0, + lens_metadata: Default::default(), + opcodes: OpcodeLists::default(), + linearization_table: None, + camera: Default::default(), + cinema: Default::default(), + level_sources: Default::default(), + notices: Default::default(), + } +} + +/// What the decode does after the demosaic, up to the colour matrix: clipped highlights rebuilt, white balance. +fn finish(mut img: Rgb32f, wb: [f32; 3]) -> Rgb32f { + highlight::reconstruct(&mut img, wb, CLIP); + finish_wb(img, wb) +} + +fn layouts() -> Vec<(String, Cfa, Method)> { + let mut v = Vec::new(); + for name in ["RGGB", "BGGR", "GRBG", "GBRG"] { + for m in [Method::Ahd, Method::Ppg] { + v.push((format!("{name} {m:?}"), Cfa::bayer(name).unwrap(), m)); + } + } + v.push(("X-Trans directional".into(), Cfa::xtrans(), Method::Ahd)); + v.push(("X-Trans directional (shifted)".into(), Cfa::xtrans().shifted(2, 3), Method::Ahd)); + v +} + +#[test] +fn balanced_demosaic_returns_constant_colour_on_the_sensor_scale() { + let colours = [[0.3f32, 0.55, 0.8], [0.02, 0.9, 0.4], [0.7, 0.7, 0.7]]; + let wbs = [DAYLIGHT, [1.3, 1.0, 3.1], [2.0, 1.2, 1.5], [1.0; 3]]; + let mut cases = layouts(); + for name in ["RGGB", "GBRG"] { + cases.push((format!("{name} Bilinear"), Cfa::bayer(name).unwrap(), Method::Bilinear)); + } + for (name, cfa, method) in &cases { + for colour in colours { + for wb in wbs { + // the colour as camera RGB, i.e. what the mosaic holds + let raw = raw_of(23, 19, cfa, [1.0; 3], |_, _| colour); + let out = raw.develop_balanced(*method, wb).unwrap(); + for p in &out.data { + for c in 0..3 { + assert!((p[c] - colour[c]).abs() <= 1e-6 * colour[c].max(1.0), "{name} wb {wb:?}: {p:?} for {colour:?}"); + } + } + } + } + } +} + +#[test] +fn every_sample_keeps_its_own_value() { + let cfa = Cfa::bayer("GRBG").unwrap(); + let raw = raw_of(40, 32, &cfa, [1.0; 3], |x, y| { + let v = 0.05 + 0.9 * (((x * 7 + y * 13) % 17) as f32 / 17.0); + [v * 0.6, v, v * 0.8] + }); + let n = raw.normalized().unwrap(); + for m in [Method::Ahd, Method::Ppg] { + let out = raw.develop_balanced(m, DAYLIGHT).unwrap(); + for y in 0..32 { + for x in 0..40 { + let (c, s) = (cfa.color_at(x, y) as usize, n.data[y * 40 + x]); + assert!((out.get(x, y)[c] - s).abs() <= 1e-6, "{m:?} ({x}, {y})"); + } + } + } +} + +#[test] +fn unsupported_white_balance_inputs_keep_the_plain_develop_result() { + let cfa = Cfa::bayer("RGGB").unwrap(); + let raw = raw_of(30, 22, &cfa, DAYLIGHT, |x, y| { + let v = if (x / 5 + y / 4) % 2 == 0 { 0.08 } else { 0.9 }; + [v, v * 0.9, v * 1.1] + }); + for method in [Method::Ahd, Method::Ppg] { + let plain = raw.develop(method).unwrap(); + // multipliers count relative to green: equal ones are no white balance at all + // (and finite multipliers whose ratios would overflow the scaled mosaic or the division back, review of #1328) + for wb in [ + [1.0; 3], + [2.0; 3], + [f32::NAN, 1.0, 1.0], + [0.0, 1.0, 1.5], + [2.0, -1.0, 1.5], + [f32::INFINITY, 1.0, 1.0], + [f32::MAX, 1.0, 1.0], + [1e-40, 1.0, 1.0], + [f32::MIN_POSITIVE, 1.0, 1.0], + [1e20, 1.0, 1e-20], + [f32::MAX, f32::MIN_POSITIVE, 1.0], + ] { + assert_eq!(raw.develop_balanced(method, wb).unwrap(), plain, "{method:?} {wb:?}"); + } + // Strong finite gains still balance when the samples fit. + for wb in [[16.0, 1.0, 1.0 / 16.0], [2.0, 4.0, 3.0]] { + let out = raw.develop_balanced(method, wb).unwrap(); + assert_ne!(out, plain, "{method:?} {wb:?}"); + assert!(out.data.iter().flatten().all(|v| v.is_finite()), "{method:?} {wb:?}"); + } + } + // bilinear interpolates each colour on its own: nothing to balance + assert_eq!(raw.develop_balanced(Method::Bilinear, DAYLIGHT).unwrap(), raw.develop(Method::Bilinear).unwrap()); + // already demosaiced and monochrome data are left alone + let mut mono = raw.clone(); + mono.cfa = None; + assert_eq!(mono.develop_balanced(Method::Ahd, DAYLIGHT).unwrap(), mono.develop(Method::Ahd).unwrap()); + + let mut linear = mono; + linear.cpp = 3; + linear.data = RawData::F32([0.2, 0.6, 0.8].repeat(linear.width * linear.height)); + assert_eq!(linear.develop_balanced(Method::Ahd, DAYLIGHT).unwrap(), linear.develop(Method::Ahd).unwrap()); +} + +/// What the lens makes of a sharp `scene` (white-balanced level, sampled at sub-pixel positions): each pixel the +/// mean of 4 × 4 points of its area, then a blur of about one pixel (binomial [1 4 6 4 1] / 16 each way: a good lens +/// and the sensor's microlenses). Any sharper and a single sample holds detail no demosaic can place. +fn photograph(w: usize, h: usize, scene: impl Fn(f32, f32) -> f32) -> Vec { + let area: Vec = (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + (0..16).map(|k| scene(x + ((k % 4) as f32 + 0.5) / 4.0, y + ((k / 4) as f32 + 0.5) / 4.0)).sum::() / 16.0 + }) + .collect(); + let blur = |v: &[f32], dx: isize, dy: isize| -> Vec { + (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as isize, (i / w) as isize); + let at = |k: isize| v[(y + k * dy).clamp(0, h as isize - 1) as usize * w + (x + k * dx).clamp(0, w as isize - 1) as usize]; + (at(-2) + 4.0 * at(-1) + 6.0 * at(0) + 4.0 * at(1) + at(2)) / 16.0 + }) + .collect() + }; + blur(&blur(&area, 1, 0), 0, 1) +} + +/// Issue #1328: on a dark neutral surface, neutral specular points of 1 to 3 px bright enough to clip green (the +/// brightest clip every channel). Around them, the pixels with nothing clipped must stay neutral after highlight +/// reconstruction and white balance: no channel below half the pixel's mean, none negative. Demosaiced from the +/// unbalanced mosaic, red (or blue) beside a point fell to about zero or below: green and cyan rims, on 16 to 38 % +/// of these pixels. +#[test] +fn specular_points_have_no_coloured_rims() { + let (w, h) = (96usize, 72usize); + // (x, y, size, white-balanced level): green clips at 1, blue at 1.6, red at 2.5 + let mut points = Vec::new(); + for (i, level) in [2.0f32, 4.0, 8.0].into_iter().enumerate() { + for (j, size) in [1.0f32, 2.0, 3.0].into_iter().enumerate() { + for k in 0..2 { + points.push((8.0 + j as f32 * 30.0 + k as f32 * 12.6, 9.0 + i as f32 * 22.0 + k as f32 * 7.3, size, level)); + } + } + } + let light = + photograph(w, h, |x, y| points.iter().find(|&&(px, py, s, _)| (px..px + s).contains(&x) && (py..py + s).contains(&y)).map_or(0.04, |p| p.3)); + let near = |x: usize, y: usize| { + let (x, y) = (x as f32, y as f32); + points.iter().any(|&(px, py, s, _)| x + 3.0 > px && x < px + s + 2.0 && y + 3.0 > py && y < py + s + 2.0) + }; + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + // what the scene is about: green clipped at most points, every channel at the brightest + let n = raw.normalized().unwrap(); + let clipped = |c: u8| (0..w * h).filter(|&i| cfa.color_at(i % w, i / w) == c && n.data[i] >= 1.0).count(); + assert!(clipped(1) >= 20 && clipped(0) >= 2 && clipped(2) >= 4, "{name}: clipped R G B {} {} {}", clipped(0), clipped(1), clipped(2)); + let developed = raw.develop_balanced(method, DAYLIGHT).unwrap(); + let unclipped: Vec = developed.data.iter().map(|p| p.iter().all(|&v| v < CLIP)).collect(); + let out = finish(developed, DAYLIGHT); + // X-Trans: its directional weights already keep colour differences from crossing an edge, and it has the + // same few pale pixels (a channel at 0.3 to 0.5 of the mean) either way + let floor = if cfa.is_bayer() { 0.5 } else { 0.25 }; + let (mut rim, mut bad) = (0, Vec::new()); + for y in 0..h { + for x in 0..w { + if !near(x, y) || !unclipped[y * w + x] { + continue; + } + rim += 1; + let p = out.get(x, y); + let mean = (p[0] + p[1] + p[2]) / 3.0; + if p.iter().any(|&v| v < 0.0 || v < floor * mean) { + bad.push((x, y, p)); + } + } + } + assert!(rim > 0, "{name}: {rim} rim pixels"); + assert!(bad.is_empty(), "{name}: {} of {rim} rim pixels coloured, e.g. {:?}", bad.len(), &bad[..bad.len().min(4)]); + } +} + +/// Issue #1328: sharp neutral white-on-dark edges with nothing clipped (straight, diagonal, round, a 1 px line). +/// The pixels along them must stay nearly neutral after white balance. From the unbalanced mosaic their colour +/// spread (largest minus smallest channel) averaged 6 % of the edge's contrast on Bayer layouts (0.2 % to 0.7 % +/// balanced), with yellow, green, cyan or magenta outlines up to 36 %. +#[test] +fn sharp_neutral_edges_stay_neutral() { + let (w, h) = (96usize, 80usize); + let (dark, bright) = (0.03f32, 0.85f32); + let shape = |x: f32, y: f32| { + let disc = (x - 70.0).powi(2) + (y - 24.0).powi(2) < 13.5f32.powi(2); + let bar = (10.0..30.0).contains(&x) && (8.0..40.0).contains(&y); + let slant = y > 46.0 && x * 0.6 + y > 70.0 && x < 60.0; + let line = (80.0..81.0).contains(&x) && y > 46.0; + disc || bar || slant || line + }; + let light = photograph(w, h, |x, y| if shape(x, y) { bright } else { dark }); + // pixels within 1 px of an edge + let inside = |x: usize, y: usize| shape(x as f32 + 0.5, y as f32 + 0.5); + let edge = |x: usize, y: usize| (x - 1..=x + 1).any(|xx| (y - 1..=y + 1).any(|yy| inside(xx, yy) != inside(x, y))); + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + let out = finish(raw.develop_balanced(method, DAYLIGHT).unwrap(), DAYLIGHT); + let (mut n, mut worst, mut sum) = (0, 0f32, 0f32); + for y in 2..h - 2 { + for x in 2..w - 2 { + if !edge(x, y) { + continue; + } + let p = out.get(x, y); + assert!(p.iter().all(|&v| v >= 0.0), "{name}: negative channel at ({x}, {y}): {p:?}"); + let spread = (p[0].max(p[1]).max(p[2]) - p[0].min(p[1]).min(p[2])) / (bright - dark); + worst = worst.max(spread); + sum += spread; + n += 1; + } + } + let mean = sum / n as f32; + assert!(n > 0, "{name}: {n} edge pixels"); + // X-Trans: our directional method's own green interpolation softens edges (mean 9 %, worst 43 %, and + // negative channels, unbalanced) + let (mean_max, worst_max) = if cfa.is_bayer() { (0.02, 0.15) } else { (0.085, 0.35) }; + assert!(mean < mean_max && worst < worst_max, "{name}: edge colour spread mean {mean:.3}, worst {worst:.3}"); + } +} + +/// Large clipped areas on bright and dark neutral surfaces can leave magenta rims. The mask lets highlight +/// reconstruction rebuild the unknown interpolated channels and keep the surrounding pixels neutral. +#[test] +fn clipped_areas_have_no_coloured_rims() { + let (w, h) = (96usize, 72usize); + let lamp = |x: f32, y: f32| (x - 30.0).powi(2) + (y - 36.0).powi(2) < 14.0f32.powi(2) || ((62.0..80.0).contains(&x) && (20.0..52.0).contains(&y)); + let light = photograph(w, h, |x, y| { + if lamp(x, y) { + 6.0 + } else if x < 48.0 { + 0.7 + } else { + 0.05 + } + }); + // within 3 px of the clipped area, unclipped in the scene + let rim = |x: usize, y: usize| { + !lamp(x as f32 + 0.5, y as f32 + 0.5) + && (x.saturating_sub(3)..=(x + 3).min(w - 1)) + .any(|xx| (y.saturating_sub(3)..=(y + 3).min(h - 1)).any(|yy| lamp(xx as f32 + 0.5, yy as f32 + 0.5))) + }; + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + let (mut img, mask) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + highlight::reconstruct_masked(&mut img, DAYLIGHT, CLIP, [1.0; 3], &mask.expect("clipped samples")); + let img = finish_wb(img, DAYLIGHT); + let (mut n, mut worst, mut sum) = (0, 0f32, 0f32); + for y in 2..h - 2 { + for x in 2..w - 2 { + if !rim(x, y) { + continue; + } + let p = img.get(x, y); + let mean = (p[0] + p[1] + p[2]) / 3.0; + let spread = (p[0].max(p[1]).max(p[2]) - p[0].min(p[1]).min(p[2])) / mean.max(1e-3); + worst = worst.max(spread); + sum += spread; + n += 1; + } + } + let mean = sum / n as f32; + assert!(n > 0, "{name}: {n} rim pixels"); + // (told by value: mean 7 to 17 %, worst 80 %; demosaiced unbalanced, channels below zero). X-Trans: a few + // pixels at the lamp's edge where green interpolates just above the clip and red overshoots + let worst_max = if cfa.is_bayer() { 0.6 } else { 0.8 }; + assert!( + mean < 0.03 && worst < worst_max, + "{name}: colour spread around the clipped area mean {mean:.3}, worst {worst:.3} of the pixel's mean" + ); + } +} + +#[test] +fn the_clip_mask_marks_the_colours_interpolated_from_clipped_samples() { + let cfa = Cfa::bayer("RGGB").unwrap(); + let (w, h) = (16usize, 12usize); + let mut raw = raw_of(w, h, &cfa, [1.0; 3], |_, _| [0.3; 3]); + // Place clipped green and red samples at known CFA sites, then develop with an offset crop. + if let RawData::F32(d) = &mut raw.data { + d[4 * w + 5] = 1.0; + d[8 * w + 10] = 1.0; + } + raw.crop = Rect::new(1, 1, 14, 10); + let (img, mask) = raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap(); + assert_eq!(img, raw.develop_balanced(Method::Ahd, DAYLIGHT).unwrap(), "the same picture"); + let mask = mask.unwrap(); + assert_eq!(mask.len(), img.data.len()); + let at = |x: usize, y: usize| mask[(y - raw.crop.y) * img.width + x - raw.crop.x]; + assert_eq!(at(5, 4), highlight::CLIPPED_G, "the saturated green site"); + assert_eq!(at(10, 8), highlight::CLIPPED_R, "the saturated red site"); + assert_eq!(at(4, 4), highlight::FROM_CLIPPED_G | (1 << highlight::MEASURED_SHIFT), "red beside saturated green"); + assert_eq!(at(11, 8), highlight::FROM_CLIPPED_R | (2 << highlight::MEASURED_SHIFT), "green beside saturated red"); + assert_ne!(at(5, 6) & highlight::FROM_CLIPPED_G, 0, "clipped green can affect the other channels at this green site"); + assert_eq!(at(2, 8), 0, "a site away from both clipped samples"); + // An unclipped mosaic or an OpcodeList3 needs no mask. + let clean = raw_of(w, h, &cfa, [1.0; 3], |_, _| [0.3; 3]); + assert!(clean.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap().1.is_none()); + raw.opcodes.list3.push(Opcode::FixVignetteRadial { k: [0.0; 5], center: [0.5, 0.5] }); + assert!(raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap().1.is_none()); +} + +#[test] +fn ppg_clip_mask_marks_same_colour_dependencies() { + let cfa = Cfa::bayer("RGGB").unwrap(); + let wb = [1.0; 3]; + let mut raw = raw_of(16, 12, &cfa, wb, |x, y| { + let level = match (x, y) { + (5, 4) | (6, 3) => 0.26, + (7, 4) => 0.35, + (8, 4) => 0.4, + (6, 5) => 0.49, + _ => 0.3, + }; + [level; 3] + }); + let clean = raw.develop(Method::Ppg).unwrap().get(6, 4); + if let RawData::F32(samples) = &mut raw.data { + samples[4 * raw.width + 4] = 1.0; + } + let (mut image, mask) = raw.develop_balanced_masked(Method::Ppg, wb, CLIP).unwrap(); + let changed = image.get(6, 4); + assert!(changed[1] > clean[1] && changed.iter().all(|&v| v < CLIP)); + let mask = mask.unwrap(); + let entry = mask[4 * image.width + 6]; + assert_ne!(entry & highlight::FROM_CLIPPED_R, 0, "the clipped red sample changed interpolated green"); + assert_eq!(entry >> highlight::MEASURED_SHIFT, cfa.color_at(6, 4) + 1); + assert_eq!(mask[4 * image.width + 10], 0, "no clipped sample is within reach"); + highlight::reconstruct_masked(&mut image, wb, CLIP, wb, &mask); + assert_eq!(image.get(6, 4)[0], clean[0], "reconstruction keeps measured red"); + assert_ne!(image.get(6, 4)[1], changed[1], "reconstruction can use measured red to rebuild green"); +} + +#[test] +fn bilinear_clip_mask_marks_only_actual_taps() { + let cfa = Cfa::bayer("RGGB").unwrap(); + for (width, method) in [(16, Method::Bilinear), (3, Method::Ahd), (3, Method::Ppg)] { + let raw = raw_of(width, 10, &cfa, [1.0; 3], |x, y| if (x, y) == (0, 2) { [1.0; 3] } else { [0.21, 0.15, 0.11] }); + let (mut image, mask) = raw.develop_balanced_masked(method, [1.0; 3], CLIP).unwrap(); + let mask = mask.unwrap(); + let clean = image.get(2, 3); + let blue = image.get(1, 2)[2]; + highlight::reconstruct_masked(&mut image, [1.0; 3], CLIP, [1.0; 3], &mask); + assert_eq!(image.get(2, 3), clean, "the clipped red sample is outside these bilinear taps"); + assert_eq!(mask[3 * width + 2], 0); + assert_eq!(mask[2 * width + 1] & highlight::FROM_CLIPPED_R, highlight::FROM_CLIPPED_R); + assert_eq!(image.get(1, 2)[2], blue, "blue interpolation uses its own samples"); + } +} + +#[test] +fn bilinear_clip_mask_keeps_the_wider_taps_for_sparse_cfas() { + let cfa = Cfa { width: 6, height: 1, pattern: vec![0, 1, 1, 1, 2, 1], origin_x: 0, origin_y: 0 }; + let raw = raw_of(12, 10, &cfa, [1.0; 3], |x, y| if (x, y) == (0, 2) { [1.0; 3] } else { [0.21, 0.15, 0.11] }); + let (_, mask) = raw.develop_balanced_masked(Method::Bilinear, DAYLIGHT, CLIP).unwrap(); + let mask = mask.unwrap(); + assert_ne!(mask[2 * raw.width + 2] & highlight::FROM_CLIPPED_R, 0, "the closest red taps are two columns away"); +} + +/// Review of #1328: dark twigs and wires against a clipped sky (every channel clipped around them) keep their level. +/// A pixel's own CFA sample is measured: a clipped neighbour of the same colour says nothing about it, and the colours +/// interpolated from clipped samples are unknown, not lower bounds. Taken as lower bounds (with the pixel's own colour +/// marked as clipped by its neighbours), the line's pixels were rebuilt as the brightest neutral and the lines vanished. +#[test] +fn dark_lines_against_a_clipped_sky_keep_their_level() { + let (w, h) = (96usize, 72usize); + let sky = 3.0f32; + // lines 3, 4 and 6 px wide (across, down, slanted) and a blob, at the level of dark bark + let dark = |x: f32, y: f32| { + (20.0..23.0).contains(&x) + || (30.0..34.0).contains(&y) + || ((x - y * 0.5 - 50.0).abs() < 3.0 && y < 60.0) + || (x - 78.0).powi(2) + (y - 56.0).powi(2) < 25.0 + }; + let light = photograph(w, h, |x, y| if dark(x, y) { 0.05 } else { sky }); + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + let (mut img, mask) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + highlight::reconstruct_masked(&mut img, DAYLIGHT, CLIP, [1.0; 3], &mask.expect("clipped samples")); + let out = finish_wb(img, DAYLIGHT); + let (mut n, mut lifted, mut worst) = (0, Vec::new(), 0f32); + for y in 3..h - 3 { + for x in 3..w - 3 { + // what the lens let through is well below green's clip: the sensor measured it + let level = light[y * w + x]; + if level > 0.5 { + continue; + } + n += 1; + let p = out.get(x, y); + let mean = (p[0] + p[1] + p[2]) / 3.0; + worst = worst.max(mean / level); + if mean > 2.0 * level + 0.05 { + lifted.push((x, y, level, p)); + } + } + } + assert!(n > 0, "{name}: {n} line pixels"); + assert!( + lifted.is_empty(), + "{name}: {} of {n} dark pixels lifted (worst {worst:.1}x), e.g. {:?}", + lifted.len(), + &lifted[..lifted.len().min(3)] + ); + } +} + +/// White balance only (what [`finish`] does after the reconstruction it runs itself). +fn finish_wb(mut img: Rgb32f, wb: [f32; 3]) -> Rgb32f { + img.data.iter_mut().for_each(|p| *p = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]); + img +} + +/// Review of #1328: twigs a pixel or two wide against a clipped sky stay continuous lines at about the level the lens +/// let through. Their pixels are partly clipped (green clips at the twig's centre, red and blue don't), so marking the +/// interpolated channels of the pixels whose own sample clipped as unknown broke them into dots: those pixels were +/// rebuilt as clipped white between dark ones (0.44 stop from one twig pixel to the next, unbalanced 0.04). +#[test] +fn thin_twigs_against_a_clipped_sky_stay_continuous() { + let (w, h) = (96usize, 72usize); + let dark = |x: f32, y: f32| { + (20.0..21.0).contains(&x) + || (40.0..41.5).contains(&x) + || (60.0..62.0).contains(&x) + || (30.0..31.5).contains(&y) + || (x - y * 0.4 - 70.0).abs() < 0.8 + }; + let light = photograph(w, h, |x, y| if dark(x, y) { 0.05 } else { 3.0 }); + let level = |p: [f32; 3]| ((p[0] + p[1] + p[2]) / 3.0).min(3.0); + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, |x, y| [light[y * w + x]; 3]); + let (mut img, mask) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + highlight::reconstruct_masked(&mut img, DAYLIGHT, CLIP, [1.0; 3], &mask.expect("clipped samples")); + let out = finish_wb(img, DAYLIGHT); + // twig pixels (the lens let through less than 2 of the sky's 3): the error of their level, and the change from + // one to the next along the twig + let (mut n, mut err, mut jump, mut nj) = (0, 0f32, 0f32, 0); + for y in 4..h - 4 { + for x in 4..w - 4 { + let l = light[y * w + x]; + if l >= 2.0 { + continue; + } + let m = level(out.get(x, y)).max(1e-3); + err += (m / l).log2().abs(); + n += 1; + for (xx, yy) in [(x + 1, y), (x, y + 1)] { + let l2 = light[yy * w + xx]; + if l2 < 2.0 && (l2 / l - 1.0).abs() < 0.1 { + jump += (level(out.get(xx, yy)).max(1e-3) / m).log2().abs(); + nj += 1; + } + } + } + } + let (err, jump) = (err / n as f32, jump / nj as f32); + assert!(n > 0 && nj > 0, "{name}: {n} twig pixels, {nj} pairs"); + // (unbalanced: 0.19 / 0.04 stop on Bayer, 0.29 / 0.17 on X-Trans) + let (err_max, jump_max) = if cfa.is_bayer() { (0.25, 0.12) } else { (0.35, 0.25) }; + assert!(err < err_max && jump < jump_max, "{name}: twig level off by {err:.3} stop, {jump:.3} stop from pixel to pixel"); + } +} + +/// Round 2 review of #1328: strongly coloured highlights (a warm sun clipping red, or red and green, or every +/// channel at its core; red, yellow and green light tubes) keep their brightness just inside their bright edges. +/// Rebuilding a pixel's interpolated channels from its measured one alone (blue, at an orange sun's edge) with the +/// colour of the content around made a dark checkerboard line there: a CC0 sunset's pixel went from Y 0.87 to 0.21. +#[test] +fn coloured_highlights_keep_their_brightness_at_the_edges() { + let (w, h) = (96usize, 80usize); + // (tint, white-balanced level): an orange sun clipping red only, red and green, and every channel; light tubes + let suns = [([1.0f32, 0.3, 0.06], 3.0f32), ([1.0, 0.45, 0.08], 4.0), ([1.0, 0.5, 0.12], 40.0)]; + let tubes = [([1.0f32, 0.15, 0.1], 3.5f32), ([1.0, 0.85, 0.15], 2.6), ([0.25, 1.0, 0.4], 2.0)]; + let scenes = suns.map(|(tint, level)| (tint, level, true)).into_iter().chain(tubes.map(|(tint, level)| (tint, level, false))); + let lum = |p: [f32; 3]| 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; + for (tint, level, sun) in scenes { + let scene_name = if sun { "sun" } else { "tube" }; + let scene = |x: f32, y: f32| { + if sun { + let radius = ((x - 48.0).powi(2) + (y - 40.0).powi(2)).sqrt(); + let k = if radius < 16.0 { 1.0 } else { (-(radius - 16.0) / 3.0).exp() }; + (k, 0.03) + } else { + let distance = (x - 30.0).abs().min((x - 0.5 * y - 45.0).abs() / 1.118); + let k = if distance < 2.0 { 1.0 } else { 0.15 * (-(distance - 2.0) / 2.0).exp() }; + (k, 0.02) + } + }; + let lights: [Vec; 3] = std::array::from_fn(|c| { + photograph(w, h, |x, y| { + let (strength, background) = scene(x, y); + tint[c] * level * strength + background + }) + }); + let truth = |x: usize, y: usize| -> [f32; 3] { std::array::from_fn(|c| lights[c][y * w + x]) }; + for (name, cfa, method) in layouts() { + let raw = raw_of(w, h, &cfa, DAYLIGHT, truth); + let (mut img, mask) = raw.develop_balanced_masked(method, DAYLIGHT, CLIP).unwrap(); + let mut by_value = img.clone(); + highlight::reconstruct(&mut by_value, DAYLIGHT, CLIP); + highlight::reconstruct_masked(&mut img, DAYLIGHT, CLIP, [1.0; 3], &mask.expect("clipped samples")); + let (out, by_value) = (finish_wb(img, DAYLIGHT), finish_wb(by_value, DAYLIGHT)); + // pixels the sensor measured in every channel (well below each clip), within 3 px of a clipped sample: + // their brightness must stay near what the lens let through + let clipped = |x: usize, y: usize| (0..3).any(|c| truth(x, y)[c] / DAYLIGHT[c] >= 1.0); + let (mut n, mut dark, mut dark_by_value) = (0, Vec::new(), 0); + for y in 3..h - 3 { + for x in 3..w - 3 { + let t = truth(x, y); + if (0..3).any(|c| t[c] / DAYLIGHT[c] > 0.9) || !(x - 3..=x + 3).any(|xx| (y - 3..=y + 3).any(|yy| clipped(xx, yy))) { + continue; + } + n += 1; + let ratio = |p: [f32; 3]| lum(p) / lum(t).max(1e-4); + let masked_ratio = ratio(out.get(x, y)); + let value_ratio = ratio(by_value.get(x, y)); + assert!( + masked_ratio.is_finite() && value_ratio.is_finite(), + "{scene_name} {tint:?} x{level}, {name} at ({x}, {y}): masked ratio {masked_ratio}, by-value ratio {value_ratio}" + ); + if masked_ratio < 0.6 { + dark.push((x, y, masked_ratio)); + } + if value_ratio < 0.6 { + dark_by_value += 1; + } + } + } + assert!(n > 0, "{scene_name} {tint:?} x{level}, {name}: {n} edge pixels"); + if !cfa.is_bayer() { + // X-Trans darkens a few pixels inside thin red and yellow tubes told by value too (as main does); the + // mask may add a few more, never many + assert!( + dark.len() <= dark_by_value + n / 30, + "{scene_name} {tint:?} x{level}, {name}: {} of {n} edge pixels darkened ({dark_by_value} by value)", + dark.len() + ); + continue; + } + assert!( + dark.is_empty(), + "{scene_name} {tint:?} x{level}, {name}: {} of {n} edge pixels darkened ({dark_by_value} by value), e.g. {:?}", + dark.len(), + &dark[..dark.len().min(3)] + ); + } + } +} + +/// Round 2 review of #1328: finite but huge samples (a floating-point DNG holding 1e37) must not overflow once +/// balanced: the gains are applied only when every sample times the largest of them, and divided back by the +/// smallest, stays far inside `f32`; otherwise the mosaic is demosaiced unbalanced, as `develop` does (finite here). +/// Just inside that bound the gains apply, and every demosaic stays finite. +#[test] +fn huge_float_samples_develop_unbalanced_rather_than_overflow() { + let mut raw = raw_of(24, 20, &Cfa::bayer("RGGB").unwrap(), [1.0; 3], |_, _| [0.1; 3]); + raw.data = RawData::F32(vec![1e37; 24 * 20]); + raw.bits = 32; + let bytes = craft_raw::write_dng(&raw, &craft_raw::DngWriteOptions::default()).unwrap(); + let decoded = craft_raw::decode(&bytes).unwrap(); + for method in [Method::Ahd, Method::Ppg] { + let plain = decoded.develop(method).unwrap(); + assert!(plain.data.iter().flatten().all(|v| v.is_finite()), "{method:?} unbalanced"); + for wb in [[64.0, 1.0, 1.0], [1.0, 1.0, 1.0 / 64.0], DAYLIGHT] { + let out = decoded.develop_balanced(method, wb).unwrap(); + assert!(out.data.iter().flatten().all(|v| v.is_finite()), "{method:?} {wb:?}"); + assert_eq!(out, plain, "{method:?} {wb:?}: develops unbalanced"); + } + } + // just inside the bound the gains apply, and every demosaic stays finite on samples that large + for (name, cfa, method) in layouts() { + let (w, h) = (36usize, 36usize); + let mut raw = raw_of(w, h, &cfa, [1.0; 3], |_, _| [0.1; 3]); + raw.data = RawData::F32((0..w * h).map(|i| if (i % w + 2 * (i / w)) % 5 < 2 { 1.5e28 } else { 0.0 }).collect()); + let plain = raw.develop(method).unwrap(); + for wb in [[64.0, 1.0, 1.0], [1.0, 1.0, 1.0 / 64.0]] { + let out = raw.develop_balanced(method, wb).unwrap(); + assert!(out.data.iter().flatten().all(|v| v.is_finite()), "{name} {wb:?}"); + assert_ne!(out, plain, "{name} {wb:?}: balanced"); + } + } +} + +/// Pixel-aspect correction changes the developed grid, so mosaic positions cannot mark it. +#[test] +fn non_square_pixels_keep_the_stretched_grid_without_a_mosaic_clip_mask() { + let cfa = Cfa::bayer("RGGB").unwrap(); + let mut raw = raw_of(24, 18, &cfa, DAYLIGHT, |_, _| [3.0; 3]); + let (square, mask) = raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap(); + assert_eq!(mask.unwrap().len(), square.data.len()); + for aspect in [2.0, 0.5] { + raw.pixel_aspect = aspect; + let (image, mask) = raw.develop_balanced_masked(Method::Ahd, DAYLIGHT, CLIP).unwrap(); + assert_eq!(image.width, square.width); + assert_eq!(image.height > square.height, aspect > 1.0); + assert_ne!(image.height, square.height); + assert!(mask.is_none(), "the mosaic grid is not the stretched grid"); + assert_eq!(image, raw.develop_balanced(Method::Ahd, DAYLIGHT).unwrap()); + } +} diff --git a/crates/develop/tests/it/main.rs b/crates/develop/tests/it/main.rs new file mode 100644 index 0000000000..3812b39e23 --- /dev/null +++ b/crates/develop/tests/it/main.rs @@ -0,0 +1 @@ +mod balanced; diff --git a/crates/drawingml/src/xmlx.rs b/crates/drawingml/src/xmlx.rs index 27fa58dc7d..ccc8a90ec6 100644 --- a/crates/drawingml/src/xmlx.rs +++ b/crates/drawingml/src/xmlx.rs @@ -266,56 +266,7 @@ fn rec_mc(el: &mut El, depth: usize, keep: &dyn Fn(&El) -> bool) { let mut out = Vec::with_capacity(el.children.len()); for c in std::mem::take(&mut el.children) { match c { - Node::El(ac_el) if ac_el.is(ac) => { - if keep(&ac_el) { - out.push(Node::El(ac_el)); - continue; - } - let choice = ac_el.children(Local("Choice")).find(|ch| { - let requires = ch.attr_local("Requires").unwrap_or(""); - let req_ok = requires.split_whitespace().all(|r| SUPPORTED_MC.contains(&r)); - let modelled = !ch.elements().any(|e| e.is(Local("contentPart"))) && (!requires.contains("cx1") || chartex_readable(ch)); - req_ok && modelled - }); - if let Some(b) = choice.or_else(|| ac_el.child(Local("Fallback"))) { - // The branch's namespace declarations (the first usable one of each name, - // in order), indexed by prefix once: each child then looks up the prefixes - // it uses instead of scanning every declaration. - let mut decls: Vec<(&String, &String)> = Vec::new(); - // An oversized declaration still shadows an outer one of its name: its - // content is left unbound rather than bound to the outer namespace. - let mut by_prefix: HashMap<&str, Option> = HashMap::new(); - for (k, v) in b.attrs.iter().chain(ac_el.attrs.iter()) { - let prefix = if k == "xmlns" { Some("") } else { k.strip_prefix("xmlns:") }; - if let Some(p) = prefix - && !by_prefix.contains_key(p) - { - by_prefix.insert(p, (v.len() <= MAX_NS_VALUE).then_some(decls.len())); - if v.len() <= MAX_NS_VALUE { - decls.push((k, v)); - } - } - } - for n in &b.children { - if let Node::El(e) = n { - // Carry the declarations from the branch that its content uses - // (all of them per child made children x declarations copies). - let used = used_prefixes(e); - let have: HashSet<&str> = e.attrs.iter().map(|(a, _)| a.as_str()).collect(); - let mut wanted: Vec = std::iter::once("") - .chain(used.iter().copied()) - .filter_map(|p| by_prefix.get(p).copied().flatten()) - .filter(|&i| decls.get(i).is_some_and(|(k, _)| !have.contains(k.as_str()))) - .collect(); - wanted.sort_unstable(); - wanted.dedup(); - let mut e = e.clone(); - e.attrs.extend(wanted.into_iter().filter_map(|i| decls.get(i)).map(|(k, v)| ((*k).clone(), (*v).clone()))); - out.push(Node::El(e)); - } - } - } - } + Node::El(ac_el) if ac_el.is(ac) => append_mc(ac_el, &mut out, depth, keep), other => out.push(other), } } @@ -326,6 +277,63 @@ fn rec_mc(el: &mut El, depth: usize, keep: &dyn Fn(&El) -> bool) { } } +fn append_mc(mut ac_el: El, out: &mut Vec, depth: usize, keep: &dyn Fn(&El) -> bool) { + if depth > MAX_DEPTH || keep(&ac_el) { + out.push(Node::El(ac_el)); + return; + } + let choice = ac_el.children.iter().position(|node| { + let Node::El(ch) = node else { return false }; + if !ch.is(Local("Choice")) { + return false; + } + let requires = ch.attr_local("Requires").unwrap_or(""); + let req_ok = requires.split_whitespace().all(|r| SUPPORTED_MC.contains(&r)); + let modelled = !ch.elements().any(|e| e.is(Local("contentPart"))) && (!requires.contains("cx1") || chartex_readable(ch)); + req_ok && modelled + }); + let index = choice.or_else(|| ac_el.children.iter().position(|node| matches!(node, Node::El(e) if e.is(Local("Fallback"))))); + let Some(Node::El(branch)) = index.and_then(|i| ac_el.children.get_mut(i)) else { return }; + + // Index branch declarations by prefix once. An oversized declaration still shadows an + // outer one of its name, even though its value will not be copied. + let mut decls: Vec<(&String, &String)> = Vec::new(); + let mut by_prefix: HashMap<&str, Option> = HashMap::new(); + for (k, v) in branch.attrs.iter().chain(ac_el.attrs.iter()) { + let prefix = if k == "xmlns" { Some("") } else { k.strip_prefix("xmlns:") }; + if let Some(p) = prefix + && !by_prefix.contains_key(p) + { + by_prefix.insert(p, (v.len() <= MAX_NS_VALUE).then_some(decls.len())); + if v.len() <= MAX_NS_VALUE { + decls.push((k, v)); + } + } + } + + for node in std::mem::take(&mut branch.children) { + let Node::El(mut e) = node else { continue }; + // Carry only declarations the child uses, in their original order. + let used = used_prefixes(&e); + let have: HashSet<&str> = e.attrs.iter().map(|(a, _)| a.as_str()).collect(); + let mut wanted: Vec = std::iter::once("") + .chain(used.iter().copied()) + .filter_map(|p| by_prefix.get(p).copied().flatten()) + .filter(|&i| decls.get(i).is_some_and(|(k, _)| !have.contains(k.as_str()))) + .collect(); + wanted.sort_unstable(); + wanted.dedup(); + e.attrs.extend(wanted.into_iter().filter_map(|i| decls.get(i)).map(|(k, v)| ((*k).clone(), (*v).clone()))); + + if e.is(Local("AlternateContent")) { + // The final child walk visits contents, so resolve a promoted wrapper here. + append_mc(e, out, depth + 1, keep); + } else { + out.push(Node::El(e)); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -417,6 +425,23 @@ mod tests { /// The branch's own declaration of a prefix wins over the `AlternateContent`'s; an oversized /// one still shadows it (its content stays unbound); a child's own declaration is left alone. + #[test] + fn direct_nested_mc_branches_keep_namespace_precedence() { + let mut root = parse( + br#" + + + + + + "#, + ) + .unwrap(); + resolve_mc(&mut root); + let item = root.child(Local("item")).unwrap(); + assert_eq!(item.to_xml(), r#""#); + } + #[test] fn mc_branch_declarations_keep_their_precedence() { let long = "u".repeat(MAX_NS_VALUE + 1); diff --git a/crates/eps/src/ai_lex.rs b/crates/eps/src/ai_lex.rs new file mode 100644 index 0000000000..05c24b6623 --- /dev/null +++ b/crates/eps/src/ai_lex.rs @@ -0,0 +1,588 @@ +//! Scanner for Adobe Illustrator editing-data streams: PostScript-like tokens read line by line. +//! +//! - A line starting with `%_` holds tokens like any other line (they are marked [`Token::hidden`]: +//! readers of the printed format skip them as comments). +//! - Any other line starting with `%` is a [`Tok::Comment`] (the section markers). +//! - `%_` later in a line starts tokens too, hidden (a pseudo-comment operator after its +//! operands, as a gradient stop's `… 50 100 %_Bs`: AI7 spec §1.4.3); any other `%` later in a +//! line starts a comment that is skipped, but for a line of hex digits after `%_` (a hidden +//! blend's record), a hidden [`Tok::Comment`]. +//! - The binary image data after `%%BeginData:` is one [`Tok::Data`]; the binary preview of a placed +//! file is one [`Tok::Preview`]. +//! - A document included whole (`%%BeginDocument:` … `%%EndDocument` lines, DSC 3.0 p. 68, nested +//! ones counted, the counted payloads of `%%BeginData:` and `%%BeginBinary:` inside skipped) is +//! one [`Tok::Document`]. + +/// A token from an Illustrator editing-data stream. +#[derive(Clone, Debug, PartialEq)] +pub enum Tok<'a> { + Num(f64), + /// A literal `(…)` string, escapes undone. + Str(Vec), + /// A hexadecimal `<…>` string. + Hex(Vec), + /// A literal `/name`. + Name(&'a [u8]), + /// An operator (any other word, `[` and `]` included). + Word(&'a [u8]), + /// A comment line, without its first `%`. + Comment(&'a [u8]), + /// An image's samples: what follows `XI` in a `%%BeginData:` section. + Data(&'a [u8]), + /// A placed file's preview: what is between `%AI26_BeginPlacedObjectPreview` and its end. + Preview(&'a [u8]), + /// A document included whole: what is between `%%BeginDocument:`'s line and the line of the + /// `%%EndDocument` that ends it, or `None` when none does (the rest of the data is skipped). + Document(Option<&'a [u8]>), +} + +/// A scanned token together with whether it came from a hidden `%_` line or suffix. +#[derive(Clone, Debug, PartialEq)] +pub struct Token<'a> { + pub tok: Tok<'a>, + /// Read from a `%_` line. + pub hidden: bool, +} + +/// A placed file's preview (binary): (begin, end) markers. +const PREVIEW: (&[u8], &[u8]) = (b"%AI26_BeginPlacedObjectPreview", b"%AI26_EndPlacedObjectPreview"); +/// A placed file's markers, which a hidden one has on `%_` lines. +const PLACE: [&[u8]; 2] = [b"%AI5_BeginPlace", b"%AI5_EndPlace"]; +/// A path's note comments, also read on `%_` lines. +const NOTES: [&[u8]; 3] = [b"%AI3_Note:", b"%%Note:", b"%AI5_NoteMore:"]; +/// The markers around a placed file's relative folder, which a hidden one has on `%_` lines too. +const RELATIVE: [&[u8]; 2] = [b"%AI28_BeginPlacedRelativePath", b"%AI28_EndPlacedRelativePath"]; +/// A document included whole: (begin, end) markers. +const DOCUMENT: (&[u8], &[u8]) = (b"%%BeginDocument", b"%%EndDocument"); + +fn find(hay: &[u8], needle: &[u8]) -> Option { + if needle.is_empty() { + return Some(0); + } + hay.windows(needle.len()).position(|w| w == needle) +} + +fn hex_decode(bytes: &[u8]) -> Option> { + let mut out = Vec::with_capacity(bytes.len() / 2); + let mut high: Option = None; + for &b in bytes { + if is_space(b) { + continue; + } + let v = char::from(b).to_digit(16)? as u8; + match high.take() { + Some(h) => out.push((h << 4) | v), + None => high = Some(v), + } + } + if let Some(h) = high { + out.push(h << 4); + } + Some(out) +} + +/// The line of `src` before the one that starts at `at`, without its line end, when it ends within +/// [`OPERAND_LINE`] bytes of `at` and is no longer than that. +fn previous_line(src: &[u8], at: usize) -> Option<&[u8]> { + let before = src.get(at.saturating_sub(OPERAND_LINE)..at)?; + let end = before.iter().rposition(|b| !is_eol(*b))? + 1; + let start = before.get(..end)?.iter().rposition(|b| is_eol(*b))? + 1; + before.get(start..end) +} + +/// The longest line of an image's `XI` operands looked at. +const OPERAND_LINE: usize = 1024; + +/// How many bytes the alpha channel of an image whose `XI` operands are on `line` takes (`[matrix] +/// llx lly urx ury w h bits type alpha …`, `%_` before them in a hidden object): a byte a pixel when +/// the alpha count isn't 0, else none (or when the operands aren't of that shape). +fn alpha_bytes(line: &[u8]) -> usize { + let line = line.strip_prefix(b"%_").unwrap_or(line); + let Some(after) = line.iter().rposition(|b| *b == b']').and_then(|i| line.get(i + 1..)) else { return 0 }; + let nums: Vec = std::str::from_utf8(after).unwrap_or_default().split_whitespace().take(9).map_while(|w| w.parse().ok()).collect(); + match (nums.get(4), nums.get(5), nums.get(8)) { + // At most the pixels the reader reads an image with. + (Some(&w), Some(&h), Some(&a)) if a > 0.0 && w >= 1.0 && h >= 1.0 && w * h <= (1u64 << 25) as f64 => (w * h) as usize, + _ => 0, + } +} + +/// Where in `w` the `%%EndData` that ends an image's samples starts: the first one on a line whose +/// next line is `XH` (`%_XH` in a hidden object), as an image's is; else the first one that a line +/// end, or the end of `w`, follows. +fn end_data(w: &[u8]) -> Option { + const MARK: &[u8] = b"%%EndData"; + let mut first = None; + let mut at = 0; + while let Some(i) = w.get(at..).and_then(|r| find(r, MARK)) { + let i = at + i; + let rest = w.get(i + MARK.len()..).unwrap_or_default(); + if rest.first().is_none_or(|b| matches!(b, b'\r' | b'\n')) { + let next = rest.strip_prefix(b"\r").unwrap_or(rest); + let next = next.strip_prefix(b"\n").unwrap_or(next); + let next = next.strip_prefix(b"%_").unwrap_or(next); + if next.starts_with(b"XH") { + return Some(i); + } + first = first.or(Some(i)); + } + at = i + 1; + } + first +} + +fn is_space(b: u8) -> bool { + matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0') +} + +fn is_delim(b: u8) -> bool { + matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') +} + +fn is_eol(b: u8) -> bool { + matches!(b, b'\r' | b'\n') +} + +/// Scanner for Illustrator editing-data byte slices. +pub struct Lexer<'a> { + src: &'a [u8], + pos: usize, + /// The current line started with `%_`. + hidden: bool, +} + +impl<'a> Lexer<'a> { + pub fn new(src: &'a [u8]) -> Self { + Self { src, pos: 0, hidden: false } + } + + fn peek(&self) -> Option { + self.src.get(self.pos).copied() + } + + /// The data from where the next token is looked for. + pub fn rest(&self) -> &'a [u8] { + self.src.get(self.pos..).unwrap_or_default() + } + + fn at_line_start(&self) -> bool { + self.pos == 0 || self.src.get(self.pos - 1).is_some_and(|b| is_eol(*b)) + } + + /// The rest of the current line (without its end), the position moved past it. + fn line(&mut self) -> &'a [u8] { + let rest = self.rest(); + let n = rest.iter().position(|b| is_eol(*b)).unwrap_or(rest.len()); + self.pos += n; + rest.get(..n).unwrap_or_default() + } + + /// [`Self::line`], the position moved past its end too (`\r`, `\n` or `\r\n`). + fn whole_line(&mut self) -> &'a [u8] { + let line = self.line(); + if self.peek() == Some(b'\r') { + self.pos += 1; + } + if self.peek() == Some(b'\n') { + self.pos += 1; + } + line + } + + /// Where the next token is looked for. + pub fn offset(&self) -> usize { + self.pos + } + + /// Look for the next token at `pos` again (the end of the data at most). + pub fn seek(&mut self, pos: usize) { + self.pos = pos.min(self.src.len()); + } + + /// The data from `from` to `to` (empty where that isn't in it). + pub fn slice(&self, from: usize, to: usize) -> &'a [u8] { + self.src.get(from..to).unwrap_or_default() + } + + /// Skip past the next `needle` (the end of data that isn't tokens) → what was skipped. + pub fn skip_past(&mut self, needle: &[u8]) -> &'a [u8] { + let rest = self.rest(); + let n = find(rest, needle).map_or(rest.len(), |i| i + needle.len()); + self.pos += n; + rest.get(..n).unwrap_or_default() + } + + /// The next token; `None` at the end. + pub fn next_token(&mut self) -> Option> { + loop { + let b = self.peek()?; + if is_eol(b) { + self.pos += 1; + self.hidden = false; + continue; + } + if is_space(b) { + self.pos += 1; + continue; + } + if b == b'%' { + let start = self.at_line_start(); + // A pseudo-comment: `%_` at the line's start, or after operands. + if self.rest().starts_with(b"%_") && (start || self.rest().get(2).is_some_and(|b| b.is_ascii_alphabetic())) { + self.pos += 2; + self.hidden = true; + continue; + } + // Right after `%_` a section still starts (a hidden image's data, #1264). + let prefixed = self.hidden && self.pos >= 2 && self.src.get(self.pos - 2..self.pos) == Some(b"%_"); + let line = self.line(); + if (start || prefixed) + && let Some(t) = self.special(line) + { + return Some(Token { hidden: prefixed, ..t }); + } + if start { + return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: false }); + } + // So does a hidden placed file: its `~` ends what `%_%AI5_BeginPlace` begins. And a + // hidden path's note. + if prefixed && PLACE.iter().chain(&NOTES).chain(&RELATIVE).any(|m| line.starts_with(m)) { + return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: true }); + } + // And a line of hex digits, as a hidden blend's record is written (`%_%4443…` + // after its `XP`), like the plain one on `%` lines. + let digits = line.get(1..).unwrap_or_default(); + if prefixed && !digits.trim_ascii_end().is_empty() && digits.trim_ascii_end().iter().all(u8::is_ascii_hexdigit) { + return Some(Token { tok: Tok::Comment(digits), hidden: true }); + } + // A comment later in a line. + continue; + } + let hidden = self.hidden; + self.pos += 1; + let tok = match b { + b'(' => Tok::Str(self.string()), + b'<' => { + let rest = self.rest(); + let end = rest.iter().position(|b| *b == b'>').unwrap_or(rest.len()); + self.pos += (end + 1).min(rest.len()); + // Malformed digits read as an empty string. + Tok::Hex(rest.get(..end).and_then(hex_decode).unwrap_or_default()) + } + b'[' | b']' | b'{' | b'}' | b')' | b'>' => Tok::Word(self.src.get(self.pos - 1..self.pos).unwrap_or_default()), + b'/' => Tok::Name(self.word()), + _ => { + self.pos -= 1; + let w = self.word(); + match number(w) { + Some(v) => Tok::Num(v), + None => Tok::Word(w), + } + } + }; + return Some(Token { tok, hidden }); + } + } + + /// The token a comment line stands for when it starts a section read differently: image data + /// (`%%BeginData:` followed by `XI`), a placed file's preview and skipped binary sections. + fn special(&mut self, line: &'a [u8]) -> Option> { + if line.starts_with(PREVIEW.0) { + let from = self.pos; + let after = find(self.rest(), PREVIEW.1).map_or(self.src.len(), |i| self.pos + i); + self.pos = after; + self.line(); + return Some(Token { tok: Tok::Preview(self.slice(from, after)), hidden: false }); + } + if line.starts_with(DOCUMENT.0) { + return Some(Token { tok: Tok::Document(self.document()), hidden: false }); + } + let n = line.strip_prefix(b"%%BeginData:")?; + let n: usize = std::str::from_utf8(n).ok()?.split_whitespace().next()?.parse().ok()?; + // The count starts after the comment's line end character (a following `\n` counts). + let from = self.pos + 1; + let region = self.src.get(from..)?; + let mut skip = region.iter().take_while(|b| is_space(**b)).count(); + // A hidden object's section is on `%_` lines up to its samples: `%_XI`, then `%_%%EndData`. + let hidden = region.get(skip..)?.starts_with(b"%_XI"); + if hidden { + skip += 2; + } else if !region.get(skip..)?.starts_with(b"XI") { + return None; + } + let mut data = from + skip + 2; + match (self.src.get(data), self.src.get(data + 1)) { + (Some(b'\r'), Some(b'\n')) => data += 2, + (Some(b'\r' | b'\n'), _) => data += 1, + _ => {} + } + // The count leaves out an alpha channel: the data ends where `%%EndData` starts, the first one + // that a line end or the end of the data follows (samples can hold the marker's bytes). + let declared = from.saturating_add(n).min(self.src.len()).max(data); + // The alpha channel the line before gives the image (its `XI` operands) follows the counted + // samples: the marker is looked for after it. + let line_start = self.pos.saturating_sub(line.len()); + let line_start = if line_start >= 2 && self.src.get(line_start - 2..line_start) == Some(b"%_") { line_start - 2 } else { line_start }; + let alpha = previous_line(self.src, line_start).map_or(0, alpha_bytes); + let start = if alpha > 0 { declared.saturating_add(alpha).saturating_sub(2) } else { declared.saturating_sub(4) }.max(data); + let stop = declared.saturating_add(n.saturating_mul(2)).saturating_add(64).max(start.saturating_add(64)).min(self.src.len()); + let end = match self.src.get(start..stop).and_then(end_data) { + Some(i) => start + i, + None => declared, + }; + self.pos = end; + let samples = self.src.get(data..end).unwrap_or_default(); + let samples = if hidden { samples.strip_suffix(b"%_").unwrap_or(samples) } else { samples }; + Some(Token { tok: Tok::Data(samples), hidden: false }) + } + + /// After a `%%BeginDocument:` line: the document up to the start of the `%%EndDocument` line + /// that ends it, the position moved past that line. A `%%BeginDocument:` line inside starts a + /// nested document, and the bytes a `%%BeginData:` or `%%BeginBinary:` line inside counts are + /// skipped (DSC 3.0 pp. 68 and 72): a marker in them ends nothing. `None` when no line ends it: + /// the position moves to the end of the data. + fn document(&mut self) -> Option<&'a [u8]> { + // The rest of the `%%BeginDocument:` line is its end; the line after the document starts + // tokens afresh (not hidden unless it starts with `%_`). + self.whole_line(); + self.hidden = false; + let from = self.pos; + let mut depth = 0usize; + while self.pos < self.src.len() { + let start = self.pos; + // A hidden object's document is on `%_` lines. + let line = self.whole_line(); + let line = line.strip_prefix(b"%_").unwrap_or(line); + if line.starts_with(DOCUMENT.1) { + if depth == 0 { + return Some(self.slice(from, start)); + } + depth -= 1; + } else if line.starts_with(DOCUMENT.0) { + depth = depth.saturating_add(1); + } else if let Some(n) = line.strip_prefix(b"%%BeginData:").or_else(|| line.strip_prefix(b"%%BeginBinary:")) { + self.skip_counted(n); + } + } + None + } + + /// Skip what a `%%BeginData:` or `%%BeginBinary:` comment counts (`n`, its text after the + /// colon): `count [type [Bytes|Lines]]`, bytes unless it says `Lines`. + fn skip_counted(&mut self, n: &[u8]) { + let mut words = std::str::from_utf8(n).unwrap_or_default().split_whitespace(); + let Some(count) = words.next().and_then(|c| c.parse::().ok()) else { return }; + if words.nth(1).is_some_and(|unit| unit.eq_ignore_ascii_case("lines")) { + for _ in 0..count { + if self.pos >= self.src.len() { + break; + } + self.whole_line(); + } + } else { + // The count starts after the comment's line end, which `document` has passed. + self.pos = self.pos.saturating_add(count).min(self.src.len()); + } + } + + /// A regular token's characters. + fn word(&mut self) -> &'a [u8] { + let start = self.pos; + while let Some(b) = self.peek() { + if is_space(b) || is_delim(b) { + break; + } + self.pos += 1; + } + self.src.get(start..self.pos).unwrap_or_default() + } + + /// A literal string after its `(` (an unterminated one ends with the data). + fn string(&mut self) -> Vec { + let mut out = vec![]; + let mut depth = 0usize; + while let Some(b) = self.peek() { + self.pos += 1; + match b { + b'(' => { + depth += 1; + out.push(b); + } + b')' if depth == 0 => break, + b')' => { + depth -= 1; + out.push(b); + } + b'\\' => { + let Some(e) = self.peek() else { break }; + self.pos += 1; + match e { + b'n' => out.push(b'\n'), + b'r' => out.push(b'\r'), + b't' => out.push(b'\t'), + b'b' => out.push(8), + b'f' => out.push(12), + b'\r' => { + if self.peek() == Some(b'\n') { + self.pos += 1; + } + } + b'\n' => {} + b'0'..=b'7' => { + let mut v = u32::from(e - b'0'); + for _ in 0..2 { + match self.peek() { + Some(d @ b'0'..=b'7') => { + v = v * 8 + u32::from(d - b'0'); + self.pos += 1; + } + _ => break, + } + } + out.push((v & 0xff) as u8); + } + other => out.push(other), + } + } + _ => out.push(b), + } + } + out + } +} + +/// A finite number token (`12`, `-3.5`, `.5`, `1e-3`), or `None`. +pub fn number(w: &[u8]) -> Option { + let first = *w.first()?; + if !(first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.')) { + return None; + } + if w.iter().any(|b| b.is_ascii_alphabetic() && !matches!(b, b'e' | b'E')) { + return None; + } + let v: f64 = std::str::from_utf8(w).ok()?.parse().ok()?; + v.is_finite().then_some(v) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn all(src: &[u8]) -> Vec> { + let mut l = Lexer::new(src); + std::iter::from_fn(|| l.next_token()).collect() + } + + fn t(tok: Tok<'_>, hidden: bool) -> Token<'_> { + Token { tok, hidden } + } + + #[test] + fn hidden_lines_and_comments() { + let toks = all(b"%AI5_BeginLayer\r\n1 (a\\)b) Ln\r%_/X : ;\n0 %_BS\n<4142>\n"); + assert_eq!( + toks, + vec![ + t(Tok::Comment(b"AI5_BeginLayer"), false), + t(Tok::Num(1.0), false), + t(Tok::Str(b"a)b".to_vec()), false), + t(Tok::Word(b"Ln"), false), + t(Tok::Name(b"X"), true), + t(Tok::Word(b":"), true), + t(Tok::Word(b";"), true), + t(Tok::Num(0.0), false), + // A pseudo-comment operator after its operands. + t(Tok::Word(b"BS"), true), + t(Tok::Hex(b"AB".to_vec()), false), + ] + ); + } + + #[test] + fn a_percent_later_in_a_line_is_a_comment_unless_an_operator_follows_it() { + let toks = all(b"1 % a note (\n2 %_Bs\n3 %_ 4\n"); + let words: Vec<_> = toks.iter().map(|t| (t.tok.clone(), t.hidden)).collect(); + assert_eq!(words, [(Tok::Num(1.0), false), (Tok::Num(2.0), false), (Tok::Word(b"Bs"), true), (Tok::Num(3.0), false)]); + // A hidden line of hex digits (a hidden blend's record) is a comment; other text after + // `%_%` stays skipped. + let toks = all(b"%_%44434241\n%_% not hex\n%_%\n1\n"); + assert_eq!(toks, [t(Tok::Comment(b"44434241"), true), t(Tok::Num(1.0), false)]); + } + + #[test] + fn image_data_is_one_token() { + // The count starts after the comment's `\r`: `\nXI\n` and 3 samples; an alpha channel + // after them isn't counted. + let src = b"[1 0 0 1 0 0] XI\r\n%%BeginData: 7\r\nXI\n(%)A%%EndData\r\nXH\r\n"; + let toks = all(src); + assert!(toks.contains(&t(Tok::Data(b"(%)A"), false)), "{toks:?}"); + assert_eq!(toks.last(), Some(&t(Tok::Word(b"XH"), false))); + // #1264: on `%_` lines too, where the samples would otherwise be read as tokens. + let toks = all(b"%_[1 0 0 1 0 0] XI\r%_%%BeginData: 7\rXI\n(U)A%%EndData\r%_XH\ru\r"); + assert!(toks.contains(&t(Tok::Data(b"(U)A"), true)), "{toks:?}"); + assert_eq!(toks.last(), Some(&t(Tok::Word(b"u"), false)), "{toks:?}"); + // A section of hex lines is comments. + let toks = all(b"%%BeginData: 9 Hex Bytes\r\n%00FF\r\n%%EndData\r\n1\r\n"); + assert_eq!(toks.last(), Some(&t(Tok::Num(1.0), false))); + // On `%_` lines (an opacity mask's image, say) too: a `(` in the samples starts no string. + let toks = all(b"%_XI\r%_%%BeginData: 4\r%_XI\r(\x00\x00\x00%_%%EndData\r%_XH\r1\r"); + assert!(toks.contains(&t(Tok::Data(b"(\x00\x00\x00"), true)), "{toks:?}"); + assert_eq!(toks.last(), Some(&t(Tok::Num(1.0), false))); + } + + #[test] + fn binary_sections_are_one_token() { + let toks = all(b"%AI26_BeginPlacedObjectPreview\r\n2 1 (\x00\xff\r\n%AI26_EndPlacedObjectPreview\r\nN\r\n"); + assert_eq!(toks, vec![t(Tok::Preview(b"\r\n2 1 (\x00\xff\r\n"), false), t(Tok::Word(b"N"), false)]); + let toks = all(b"%%BeginDocument: a.eps\n(\x00 frobnicate\n%%EndDocument\nN\n"); + assert_eq!(toks, vec![t(Tok::Document(Some(b"(\x00 frobnicate\n")), false), t(Tok::Word(b"N"), false)]); + // One that doesn't end takes the rest. + assert_eq!(all(b"%AI26_BeginPlacedObjectPreview\r1 (").len(), 1); + } + + #[test] + fn an_included_document_ends_at_its_own_end_line() { + // A nested document, `%%EndDocument` later in a line and in counted data end nothing; `\r\n`, + // `\r` and `\n` lines alike. + let body = b"1 0 0 setrgbcolor\r\n%%BeginDocument: inner.eps\r(%%EndDocument) pop\r%%EndDocument\r\n\ + %%BeginData: 14 Binary Bytes\n%%EndDocument\n%%BeginBinary: 14\n%%EndDocument\n\ + %%BeginData: 1 Hex Lines\n%%EndDocument\n"; + let mut src = b"%%BeginDocument: outer.eps\r\n".to_vec(); + src.extend_from_slice(body); + src.extend_from_slice(b"%%EndDocument\r\n~\r\n"); + assert_eq!(all(&src), vec![t(Tok::Document(Some(body)), false), t(Tok::Word(b"~"), false)]); + // On a hidden object's `%_` lines. + let toks = all(b"%_%%BeginDocument: a.eps\r%_1 0 0 setrgbcolor\r%_%%EndDocument\r%_~\r"); + assert_eq!(toks, vec![t(Tok::Document(Some(b"%_1 0 0 setrgbcolor\r")), true), t(Tok::Word(b"~"), true)]); + // The line after it is hidden only when it starts with `%_`. + let toks = all(b"%_%%BeginDocument: a.eps\r%_%%EndDocument\rN\r"); + assert_eq!(toks, vec![t(Tok::Document(Some(b"")), true), t(Tok::Word(b"N"), false)]); + } + + #[test] + fn an_included_document_that_doesnt_end_takes_the_rest() { + for src in [&b"%%BeginDocument: a.eps\n%%BeginDocument: b.eps\n%%EndDocument\n~\n"[..], b"%%BeginDocument: a.eps\n%%BeginData: 99999999999\n"] + { + assert_eq!(all(src), vec![t(Tok::Document(None), false)]); + } + } + + #[test] + fn skip_past_data() { + let mut l = Lexer::new(b"/Binary : /ASCII85Decode ,\r\n%_(abc[%\r\n%x~>\r\n%_; 1"); + for _ in 0..4 { + l.next_token(); + } + assert_eq!(l.skip_past(b"~>"), b"\r\n%_(abc[%\r\n%x~>"); + assert_eq!(l.next_token().map(|t| t.tok), Some(Tok::Word(b";"))); + assert_eq!(l.next_token().map(|t| t.tok), Some(Tok::Num(1.0))); + } + + #[test] + fn hostile_input_ends() { + for src in [&b"(unterminated \\"[..], b"<12", b"%%BeginData: 99999999999\r\nXI", b"%%BeginData: 5\rXI\r", b"/", b"1e999 nan"] { + let toks = all(src); + assert!(toks.len() < 10); + } + } +} diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index c9a2574f57..45b58cb859 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -15,6 +15,7 @@ //! against the file, scans are bounded, and nothing panics. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod ai_lex; pub mod ascii85; mod container; mod dsc; diff --git a/crates/exr/Cargo.toml b/crates/exr/Cargo.toml index c277635284..7221a6858c 100644 --- a/crates/exr/Cargo.toml +++ b/crates/exr/Cargo.toml @@ -13,12 +13,14 @@ workspace = true [features] # Reading and writing pixels through the `exr` crate (BSD-3-Clause). The naming and Cryptomatte # modules need none of it. -decode = ["dep:exr", "dep:half", "dep:thiserror", "dep:flate2"] +decode = ["dep:exr", "dep:half", "dep:thiserror", "zlib-inflate"] +# Bounded scanline inflation without the full EXR pixel reader. +zlib-inflate = ["dep:flate2"] [dependencies] serde_json = { workspace = true } exr = { version = "1.73", default-features = false, optional = true } half = { version = "2", optional = true } thiserror = { workspace = true, optional = true } -# zlib for deep ZIPS chunks, which the `exr` crate does not read. +# zlib for scanline payloads and deep ZIPS chunks, which the `exr` crate does not read. flate2 = { version = "1", default-features = false, features = ["rust_backend"], optional = true } diff --git a/crates/exr/src/decode.rs b/crates/exr/src/decode.rs index 9dd5903316..1ec050565f 100644 --- a/crates/exr/src/decode.rs +++ b/crates/exr/src/decode.rs @@ -115,13 +115,7 @@ impl Limits { } } -/// How a channel's samples are stored. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SampleType { - F16, - F32, - U32, -} +pub use crate::SampleType; impl SampleType { pub(crate) fn of(t: ExrSample) -> Self { diff --git a/crates/exr/src/deep.rs b/crates/exr/src/deep.rs index ad2ab00b5a..2196d1d776 100644 --- a/crates/exr/src/deep.rs +++ b/crates/exr/src/deep.rs @@ -24,6 +24,7 @@ use half::f16; use crate::channels::ColorLayout; use crate::decode::{Error, Limits, Result, SampleType, check_previews}; +use crate::scanline; fn err(e: impl std::fmt::Display) -> Error { Error::Malformed(e.to_string()) @@ -152,49 +153,6 @@ fn seek_to(cur: &mut Cursor<&[u8]>, pos: u64) -> Result<()> { // --- decompression ---------------------------------------------------------------------------- -/// Undo the ZIP predictor: each byte was stored as its difference to the previous byte plus -/// 128 (so a zero difference is 0x80), modulo 256. Applies to the sample-count table and the -/// sample data alike. -fn differences_to_samples(buf: &mut [u8]) { - if let Some(&first) = buf.first() { - let mut prev = i16::from(first); - for b in buf.iter_mut().skip(1) { - let s = (prev + i16::from(*b) - 128) as u8; - prev = i16::from(s); - *b = s; - } - } -} - -/// Undo the ZIP half-split: the stream is `[first half][second half]` with the second half -/// holding every second byte of the original; weave them back together. The scratch copy is -/// allocated fallibly, so a buffer that passed `max_bytes` but not the allocator is an error. -fn interleave_byte_blocks(buf: &mut [u8]) -> Result<()> { - let half = buf.len().div_ceil(2); - let mut out = alloc_zeroed::(buf.len())?; - let mut k = 0usize; - for i in 0..buf.len() / 2 { - let (a, b) = (buf.get(i).copied(), buf.get(half + i).copied()); - if let (Some(a), Some(b), Some(pair)) = (a, b, out.get_mut(k..k + 2)) { - if let Some(byte) = pair.first_mut() { - *byte = a; - } - if let Some(byte) = pair.get_mut(1) { - *byte = b; - } - } - k += 2; - } - if buf.len() % 2 == 1 && half > 0 { - let last = buf.get(half - 1).copied(); - if let (Some(last), Some(slot)) = (last, out.get_mut(k)) { - *slot = last; - } - } - buf.copy_from_slice(&out); - Ok(()) -} - /// Make room in `out` for `extra` more bytes, `limit` in all. Grows by doubling like `Vec`, /// but never reserves past `limit`: callers admit exactly that size against `max_bytes`, and /// plain doubling reserved up to twice as much. Fallible, so a failed allocation is an error. @@ -211,38 +169,8 @@ fn reserve_up_to(out: &mut Vec, extra: usize, limit: usize, what: &str) -> R Ok(()) } -/// OpenEXR RLE tokens: a negative byte `n` means `-n` literal bytes follow, a non-negative -/// byte `n` means the next byte repeats `n + 1` times (as `ImfRle.cpp` and the `exr` crate). -fn rle_decode(src: &[u8], expected: usize, what: &str) -> Result> { - let mut out = Vec::new(); - reserve_up_to(&mut out, expected.min(1 << 20), expected, what)?; - let mut i = 0; - while i < src.len() { - let count = src[i] as i8; - i += 1; - let n = if count < 0 { (-(count as i32)) as usize } else { count as usize + 1 }; - if out.len().saturating_add(n) > expected { - return Err(err(format!("{what}: RLE data expands past {expected} bytes"))); - } - reserve_up_to(&mut out, n, expected, what)?; - if count < 0 { - let end = i.saturating_add(n); - let run = src.get(i..end.min(src.len())).ok_or_else(|| err(format!("{what}: RLE run points past the compressed data")))?; - if run.len() != n { - return Err(err(format!("{what}: RLE run points past the compressed data"))); - } - out.extend_from_slice(run); - i = end; - } else { - let b = src.get(i).copied().ok_or_else(|| err(format!("{what}: RLE run points past the compressed data")))?; - i += 1; - out.resize(out.len() + n, b); - } - } - if out.len() != expected { - return Err(err(format!("{what}: RLE data expands to {} bytes, expected {expected}", out.len()))); - } - Ok(out) +fn scanline_error(what: &str, error: std::io::Error) -> Error { + if error.kind() == std::io::ErrorKind::OutOfMemory { Error::LimitExceeded(format!("{what}: {error}")) } else { err(format!("{what}: {error}")) } } /// Decompress `what` to exactly `expected` bytes. Like flat blocks, a payload that already @@ -258,10 +186,7 @@ fn decompress(compression: Compression, packed: &[u8], expected: usize, what: &s Compression::Uncompressed => Err(err(format!("{what}: expected {expected} uncompressed bytes, found {}", packed.len()))), Compression::RLE => { // Like ZIPS, RLE runs over the predicted, byte-split stream. - let mut out = rle_decode(packed, expected, what)?; - differences_to_samples(&mut out); - interleave_byte_blocks(&mut out)?; - Ok(out) + scanline::decode_rle(packed, expected).map_err(|error| scanline_error(what, error)) } Compression::ZIP1 => { // Inflate straight into `out`, grown with `reserve_up_to` rather than by @@ -290,9 +215,7 @@ fn decompress(compression: Compression, packed: &[u8], expected: usize, what: &s if out.len() != expected { return Err(err(format!("{what}: zlib data expands to {} bytes, expected {expected}", out.len()))); } - differences_to_samples(&mut out); - interleave_byte_blocks(&mut out)?; - Ok(out) + scanline::undo_byte_prediction(out).map_err(|error| scanline_error(what, error)) } other => Err(unsup(format!("deep data with {other:?} compression (NONE, RLE and ZIPS are supported)"))), } diff --git a/crates/exr/src/lib.rs b/crates/exr/src/lib.rs index c59fb7a95f..833bd79910 100644 --- a/crates/exr/src/lib.rs +++ b/crates/exr/src/lib.rs @@ -20,11 +20,25 @@ //! - `stream`: one flat scan-line part read block by block, for pictures larger than memory. //! - `cryptomatte_samples`: a file's Cryptomatte layers and their per-pixel (ID, coverage) ranks. +/// Bounded RLE expansion and inverse byte prediction for EXR blocks. +pub mod scanline; + /// Scanline OpenEXR writer using a caller-supplied linearization table. pub mod rgba8; -/// RFC 1950/1951 compressor for ZIP-compressed EXR chunks. +/// RFC 1950/1951 compression and bounded inflation for EXR chunks. pub mod zlib; +/// Bounded reconstruction of inflated PXR24 scanline blocks. +pub mod pxr24; + +/// How a channel's samples are stored. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SampleType { + F16, + F32, + U32, +} + pub mod channels; pub mod cryptomatte; #[cfg(feature = "decode")] diff --git a/crates/exr/src/pxr24.rs b/crates/exr/src/pxr24.rs new file mode 100644 index 0000000000..396db5c308 --- /dev/null +++ b/crates/exr/src/pxr24.rs @@ -0,0 +1,118 @@ +use crate::SampleType; + +/// Shape of a PXR24 block with full-resolution channels in file order. +#[derive(Clone, Copy, Debug)] +pub struct Layout<'a> { + width: usize, + rows: usize, + channels: &'a [SampleType], + inflated_len: usize, + output_len: usize, +} + +impl<'a> Layout<'a> { + /// Check the dimensions and byte counts against the caller's plain output limit. + pub fn new(width: usize, rows: usize, channels: &'a [SampleType], max_output: usize) -> Option { + if width == 0 || rows == 0 || channels.is_empty() { + return None; + } + let area = width.checked_mul(rows)?; + let (inflated_pixel, output_pixel) = channels.iter().try_fold((0usize, 0usize), |(inflated, output), &channel| { + let (planes, plain) = sample_bytes(channel); + Some((inflated.checked_add(planes)?, output.checked_add(plain)?)) + })?; + let inflated_len = inflated_pixel.checked_mul(area)?; + let output_len = output_pixel.checked_mul(area)?; + (output_len <= max_output).then_some(Self { width, rows, channels, inflated_len, output_len }) + } + + /// Exact number of bytes required from the zlib reader. + pub fn inflated_len(self) -> usize { + self.inflated_len + } + + /// Reconstruct little-endian samples in row, channel and pixel order. + /// + /// Each scanline and channel starts a new horizontal predictor. The stored + /// 24 bits of a FLOAT sample become its high bits, with eight low zero bits. + /// Returns `None` when the plane length is wrong or allocation fails. + pub fn unpack(self, mut input: &[u8]) -> Option> { + if input.len() != self.inflated_len { + return None; + } + let mut output = Vec::new(); + output.try_reserve_exact(self.output_len).ok()?; + for _ in 0..self.rows { + for &channel in self.channels { + let (planes, plain) = sample_bytes(channel); + let (line, rest) = input.split_at_checked(self.width * planes)?; + input = rest; + let mut sample = 0u32; + for x in 0..self.width { + let delta = line[x..].iter().step_by(self.width).fold(0u32, |value, &byte| (value << 8) | u32::from(byte)); + sample = sample.wrapping_add(delta); + let bytes = match channel { + SampleType::F32 => (sample << 8).to_le_bytes(), + SampleType::F16 | SampleType::U32 => sample.to_le_bytes(), + }; + output.extend_from_slice(&bytes[..plain]); + } + } + } + Some(output) + } +} + +fn sample_bytes(channel: SampleType) -> (usize, usize) { + match channel { + SampleType::F16 => (2, 2), + SampleType::F32 => (3, 4), + SampleType::U32 => (4, 4), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const MIXED: [SampleType; 3] = [SampleType::F16, SampleType::F32, SampleType::U32]; + + #[test] + fn mixed_types_wrap_and_reset_across_rows() { + #[rustfmt::skip] + let planes = [ + 0xff, 0x00, 0xfe, 0x03, + 0x7f, 0xff, 0x01, 0xfe, 0x23, 0xdd, + 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xf0, 0x30, + 0x01, 0xff, 0x02, 0xfe, + 0x00, 0xff, 0x00, 0xff, 0x01, 0xfe, + 0x12, 0xff, 0x34, 0xff, 0x56, 0xff, 0x78, 0xff, + ]; + #[rustfmt::skip] + let expected = [ + 0xfe, 0xff, 0x01, 0x00, + 0x00, 0x23, 0x01, 0x7f, 0x00, 0x00, 0x00, 0x7f, + 0xf0, 0xff, 0xff, 0xff, 0x20, 0x00, 0x00, 0x00, + 0x02, 0x01, 0x00, 0x01, + 0x00, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, + 0x78, 0x56, 0x34, 0x12, 0x77, 0x56, 0x34, 0x12, + ]; + let layout = Layout::new(2, 2, &MIXED, expected.len()); + assert_eq!(layout.map(Layout::inflated_len), Some(planes.len())); + assert_eq!(layout.and_then(|layout| layout.unpack(&planes)).as_deref(), Some(expected.as_slice())); + } + + #[test] + fn rejects_invalid_shapes_and_plane_lengths() { + assert!(Layout::new(0, 1, &MIXED, 40).is_none()); + assert!(Layout::new(1, 0, &MIXED, 40).is_none()); + assert!(Layout::new(1, 1, &[], 40).is_none()); + assert!(Layout::new(usize::MAX, 2, &MIXED, usize::MAX).is_none()); + assert!(Layout::new(usize::MAX, 1, &MIXED, usize::MAX).is_none()); + assert!(Layout::new(2, 2, &MIXED, 39).is_none()); + let short = Layout::new(2, 2, &MIXED, 40).and_then(|layout| layout.unpack(&[0; 35])); + let long = Layout::new(2, 2, &MIXED, 40).and_then(|layout| layout.unpack(&[0; 37])); + assert!(short.is_none()); + assert!(long.is_none()); + } +} diff --git a/crates/exr/src/scanline.rs b/crates/exr/src/scanline.rs new file mode 100644 index 0000000000..c9edb1097f --- /dev/null +++ b/crates/exr/src/scanline.rs @@ -0,0 +1,92 @@ +//! Byte transforms shared by flat and deep OpenEXR blocks. + +use std::io::{Error, ErrorKind, Result}; + +/// Expand a compressed RLE block to exactly `expected` bytes and undo its +/// byte prediction. The caller checks its chunk limit and handles blocks +/// stored uncompressed before calling this function. +pub fn decode_rle(mut packed: &[u8], expected: usize) -> Result> { + let mut out = Vec::new(); + while let Some((&count, rest)) = packed.split_first() { + let count = count as i8; + let literal = count < 0; + let run = if literal { usize::from(count.unsigned_abs()) } else { count as usize + 1 }; + let Some(end) = out.len().checked_add(run).filter(|&end| end <= expected) else { + return Err(Error::new(ErrorKind::InvalidData, format!("RLE data expands past {expected} bytes"))); + }; + let (data, next) = rest + .split_at_checked(if literal { run } else { 1 }) + .ok_or_else(|| Error::new(ErrorKind::UnexpectedEof, "RLE run points past the compressed data"))?; + + if end > out.capacity() { + let target = out.capacity().saturating_mul(2).max(end).min(expected); + out.try_reserve_exact(target - out.len()) + .map_err(|_| Error::new(ErrorKind::OutOfMemory, format!("cannot allocate {target} RLE bytes")))?; + } + if literal { + out.extend_from_slice(data); + } else if let Some(&value) = data.first() { + out.resize(end, value); + } + packed = next; + } + if out.len() != expected { + return Err(Error::new(ErrorKind::InvalidData, format!("RLE data expands to {} bytes, expected {expected}", out.len()))); + } + undo_byte_prediction(out) +} + +/// Undo RLE/ZIP's byte differences and even/odd split, returning the bytes +/// in their original order. The scratch allocation is fallible and no larger +/// than the already bounded decompressed block. +pub fn undo_byte_prediction(mut bytes: Vec) -> Result> { + if let Some((&mut first, differences)) = bytes.split_first_mut() { + let mut previous = first; + for byte in differences { + *byte = previous.wrapping_add(*byte).wrapping_sub(128); + previous = *byte; + } + } + + let (even, odd) = bytes.split_at(bytes.len().div_ceil(2)); + let mut out = Vec::new(); + out.try_reserve_exact(bytes.len()).map_err(|_| Error::new(ErrorKind::OutOfMemory, format!("cannot allocate {} elements", bytes.len())))?; + for (&even, &odd) in even.iter().zip(odd) { + out.extend([even, odd]); + } + out.extend_from_slice(&even[odd.len()..]); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rle_reverses_wrapping_prediction_and_an_odd_byte_split() { + // Literal 50, repeated delta 128 three times, then three literals. + let rle = [255, 50, 2, 128, 253, 100, 250, 129]; + let expected = [50, 22, 50, 144, 50, 145, 50]; + assert_eq!(decode_rle(&rle, 7).unwrap(), expected); + assert_eq!(undo_byte_prediction(vec![50, 128, 128, 128, 100, 250, 129]).unwrap(), expected); + } + + #[test] + fn rle_handles_maximum_literal_and_repeat_counts() { + let mut rle = vec![128]; + rle.extend([128; 128]); + rle.extend([127, 128]); + assert_eq!(decode_rle(&rle, 256).unwrap(), [128; 256]); + } + + #[test] + fn rle_refuses_short_input_and_wrong_output_sizes() { + for block in [[255], [1]] { + assert_eq!(decode_rle(&block, 2).unwrap_err().kind(), ErrorKind::UnexpectedEof); + } + assert_eq!(decode_rle(&[1, 128], 1).unwrap_err().kind(), ErrorKind::InvalidData); + assert_eq!(decode_rle(&[0, 128], 2).unwrap_err().kind(), ErrorKind::InvalidData); + // A truncated stream does not reserve the declared output size up front. + assert_eq!(decode_rle(&[0, 128], usize::MAX).unwrap_err().kind(), ErrorKind::InvalidData); + } +} diff --git a/crates/exr/src/zlib.rs b/crates/exr/src/zlib.rs index a38bd0b466..c31123330a 100644 --- a/crates/exr/src/zlib.rs +++ b/crates/exr/src/zlib.rs @@ -40,6 +40,39 @@ pub fn zlib(data: &[u8], tables: &mut Tables) -> Vec { w.out } +/// Inflate a zlib-wrapped scanline payload to exactly `expected` bytes. The caller +/// derives that size from the chunk's geometry and applies its chunk limit first. +/// The legacy scanline reader allows an absent or invalid Adler-32 trailer. The +/// zlib header and the complete DEFLATE payload are still required. +#[cfg(feature = "zlib-inflate")] +pub fn inflate_exact_without_checksum(src: &[u8], expected: usize) -> std::io::Result> { + use flate2::{Decompress, FlushDecompress, Status}; + use std::io::{Error, ErrorKind}; + + let [cmf, flg, deflate @ ..] = src else { + return Err(Error::new(ErrorKind::UnexpectedEof, "truncated zlib header")); + }; + let (cmf, flg) = (*cmf, *flg); + if cmf & 0x0f != 8 || cmf >> 4 > 7 || !u16::from_be_bytes([cmf, flg]).is_multiple_of(31) { + return Err(Error::new(ErrorKind::InvalidData, "not a zlib stream")); + } + if flg & 0x20 != 0 { + return Err(Error::new(ErrorKind::InvalidData, "zlib preset dictionary")); + } + + // One extra byte distinguishes overflow from an exactly full output buffer + // while leaving room for the inflater to finish the stream. + let capacity = expected.checked_add(1).ok_or_else(|| Error::other("zlib output size overflow"))?; + let mut output = Vec::new(); + output.try_reserve_exact(capacity).map_err(Error::other)?; + let mut inflater = Decompress::new(false); + let status = inflater.decompress_vec(deflate, &mut output, FlushDecompress::Finish).map_err(|e| Error::new(ErrorKind::InvalidData, e))?; + if status != Status::StreamEnd || output.len() != expected { + return Err(Error::new(ErrorKind::InvalidData, "incomplete or wrong-size zlib output")); + } + Ok(output) +} + /// Adler-32 (RFC 1950 §9); 5552 bytes is the longest run that cannot overflow the sums. fn adler32(data: &[u8]) -> u32 { let (mut a, mut b) = (1_u32, 0_u32); @@ -473,6 +506,32 @@ fn rle_lengths(lens: &[u8]) -> Vec<(u8, u8)> { mod tests { use super::*; + #[cfg(feature = "zlib-inflate")] + #[test] + fn exact_inflate_keeps_scanline_checksum_compatibility() { + let expected = vec![0x42; 4096]; + let mut stream = zlib(&expected, &mut Tables::default()); + let footer_start = stream.len() - 4; + assert_eq!(inflate_exact_without_checksum(&stream, expected.len()).unwrap(), expected); + stream[footer_start..].fill(0); + assert_eq!(inflate_exact_without_checksum(&stream, expected.len()).unwrap(), expected); + assert_eq!(inflate_exact_without_checksum(&stream[..footer_start], expected.len()).unwrap(), expected); + } + + #[cfg(feature = "zlib-inflate")] + #[test] + fn exact_inflate_refuses_incomplete_and_wrong_length_streams() { + let stream = zlib(&[0x42; 4096], &mut Tables::default()); + assert!(inflate_exact_without_checksum(&stream, 4095).is_err()); + assert!(inflate_exact_without_checksum(&stream, 4097).is_err()); + assert!(inflate_exact_without_checksum(&stream, usize::MAX).is_err()); + assert!(inflate_exact_without_checksum(&stream[..stream.len() - 6], 4096).is_err()); + assert!(inflate_exact_without_checksum(&stream[1..], 4096).is_err()); + let mut dictionary_header = stream; + dictionary_header[..2].copy_from_slice(&[0x78, 0x20]); + assert!(inflate_exact_without_checksum(&dictionary_header, 4096).is_err()); + } + /// A minimal inflater (RFC 1951), only to check the encoder; returns None on any error. pub(crate) fn inflate(z: &[u8]) -> Option> { let (cmf, flg) = (*z.first()?, *z.get(1)?); diff --git a/crates/gif/src/frames.rs b/crates/gif/src/frames.rs index 12ae37ddac..526598576d 100644 --- a/crates/gif/src/frames.rs +++ b/crates/gif/src/frames.rs @@ -7,7 +7,7 @@ //! decoding then stops at [`FrameLimits::max_frames`] frames or [`FrameLimits::max_bytes`] of kept //! pictures, or at the first damaged frame after the first, and [`Animation::stop`] says which. -use std::io::Cursor; +use std::io::{self, BufReader, Cursor, Read, Seek, SeekFrom}; use image::codecs::gif::GifDecoder; use image::{AnimationDecoder, ImageDecoder}; @@ -75,7 +75,7 @@ pub struct Animation { pub enum FrameError { /// Not a GIF, or the first frame does not decode. Malformed(String), - /// The canvas is over [`FrameLimits::max_canvas_bytes`] or more than the file can hold. + /// A configured budget cannot fit the first frame, or the file cannot back its canvas. LimitExceeded(String), } @@ -96,7 +96,9 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result limits.max_frames { Some(true) } else if info.complete { @@ -117,8 +119,12 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result limits.max_bytes { + return Err(FrameError::LimitExceeded(format!("the first frame needs {canvas} retained bytes but the limit is {}", limits.max_bytes))); + } let malformed = |e: image::ImageError| FrameError::Malformed(e.to_string()); - let mut decoder = GifDecoder::new(Cursor::new(bytes)).map_err(malformed)?; + let input = DecoderInput { bytes: Cursor::new(bytes), text_controls }; + let mut decoder = GifDecoder::new(BufReader::new(input)).map_err(malformed)?; let mut il = image::Limits::default(); il.max_alloc = Some(max_decode_bytes); decoder.set_limits(il).map_err(malformed)?; @@ -126,6 +132,35 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result { + bytes: Cursor<&'a [u8]>, + text_controls: Vec, +} + +impl Read for DecoderInput<'_> { + fn read(&mut self, output: &mut [u8]) -> io::Result { + let start = usize::try_from(self.bytes.position()).unwrap_or(usize::MAX); + let count = self.bytes.read(output)?; + if count == 0 { + return Ok(0); + } + let end = start + count; + let first = self.text_controls.partition_point(|&offset| offset + 4 <= start); + for &offset in self.text_controls[first..].iter().take_while(|&&offset| offset < end) { + output[offset.saturating_sub(start)..(offset + 4).min(end) - start].fill(0); + } + Ok(count) + } +} + +impl Seek for DecoderInput<'_> { + fn seek(&mut self, position: SeekFrom) -> io::Result { + self.bytes.seek(position) + } +} + /// Reads the optional ICC application extension without decoding frame pixels. As in the image /// decoder, a malformed optional profile is ignored and returned as `None`. pub fn icc_profile(bytes: &[u8]) -> Option> { @@ -218,6 +253,52 @@ mod tests { a.frames.iter().map(|f| (f.rgba[0], f.delay_ms)).collect() } + #[test] + fn plain_text_control_does_not_change_the_decoded_images() { + let mut bytes = Vec::new(); + { + let mut encoder = gif::Encoder::new(&mut bytes, 2, 2, &[255, 0, 0, 0, 0, 255]).unwrap(); + for (index, delay, transparent) in [(0, 23, Some(0)), (1, 7, None)] { + let frame = gif::Frame { + width: 2, + height: 2, + delay, + transparent, + dispose: gif::DisposalMethod::Previous, + buffer: vec![index; 4].into(), + ..gif::Frame::default() + }; + encoder.write_frame(&frame).unwrap(); + } + } + let first_image = crate::scan(&bytes, 1).unwrap().frames[0].offset; + let text = [0x21, 0x01, 12, 0, 0, 0, 0, 2, 0, 2, 0, 1, 1, 1, 0, 1, b'X', 0]; + bytes.splice(first_image..first_image, text); + + let animation = read_frames(&bytes, &FrameLimits::default()).unwrap(); + assert_eq!(animation.frames.len(), 2); + let first = &animation.frames[0]; + assert_eq!((&first.rgba[..4], first.delay_ms), (&[255, 0, 0, 255][..], 0)); + let second = &animation.frames[1]; + assert_eq!((&second.rgba[..4], second.delay_ms), (&[0, 0, 255, 255][..], 70)); + } + + #[test] + fn text_control_can_span_decoder_reads() { + let bytes: Vec = (1..=16).collect(); + let mut input = DecoderInput { bytes: Cursor::new(&bytes), text_controls: vec![3, 10] }; + let mut prefix = [0; 5]; + input.read_exact(&mut prefix).unwrap(); + assert_eq!(prefix, [1, 2, 3, 0, 0]); + let mut tail = Vec::new(); + input.read_to_end(&mut tail).unwrap(); + assert_eq!(tail, [0, 0, 8, 9, 10, 0, 0, 0, 0, 15, 16]); + input.seek(SeekFrom::Start(6)).unwrap(); + let mut around = [0; 4]; + input.read_exact(&mut around).unwrap(); + assert_eq!(around, [0, 8, 9, 10]); + } + #[test] fn every_frame_with_its_delay() { let a = read_frames(&gif(&[(10, 5), (200, 10), (10, 0)]), &FrameLimits::default()).unwrap(); @@ -313,6 +394,19 @@ mod tests { ); } + #[test] + fn retained_byte_budget_must_fit_one_frame() { + let bytes = gif(&[(10, 5), (200, 10)]); + let first_frame_bytes = 3 * 2 * 4; + let limits = FrameLimits { max_bytes: first_frame_bytes - 1, ..FrameLimits::default() }; + assert!(matches!(read_frames(&bytes, &limits), Err(FrameError::LimitExceeded(_)))); + + let limits = FrameLimits { max_bytes: first_frame_bytes, ..limits }; + let animation = read_frames(&bytes, &limits).unwrap(); + assert_eq!(reds(&animation), [(10, 50)]); + assert_eq!(animation.stop, Stop::ByteLimit); + } + #[test] fn merged_frames_still_report_the_decode_frame_limit() { let bytes = gif(&[(10, 5), (10, 7), (200, 1)]); diff --git a/crates/gif/src/lib.rs b/crates/gif/src/lib.rs index 816f90d0d6..f239cb6980 100644 --- a/crates/gif/src/lib.rs +++ b/crates/gif/src/lib.rs @@ -107,6 +107,12 @@ fn skip_sub_blocks(b: &[u8], mut at: usize) -> Option { /// `None` when `bytes` is not a GIF or ends inside its Logical Screen Descriptor. A file that /// breaks off later gives what was read, with [`Info::complete`] false. pub fn scan(bytes: &[u8], max_frames: usize) -> Option { + scan_with_text_controls(bytes, max_frames, |_| {}) +} + +// Report the control payloads that the image decoder would carry past a text block +// to an image without a control of its own. +fn scan_with_text_controls(bytes: &[u8], max_frames: usize, mut text_control: impl FnMut(usize)) -> Option { let b = bytes; if !sniff(b) { return None; @@ -116,8 +122,10 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option { b.get(12)?; let mut info = Info { width, height, global_table: packed & 0x80 != 0, frames: Vec::new(), complete: false, loop_count: None }; let mut at = 13 + table_len(packed); - // What the last Graphic Control Extension said, for the next image. + // What the last Graphic Control Extension said, for the next rendering block. let (mut delay_cs, mut transparent, mut disposal) = (0u16, None, 0u8); + let mut control_offset = None; + let mut text_control_offset = None; // Each step either finishes the walk or moves `at` forward, so this ends with the file. let mut step = || -> Option { match *b.get(at)? { @@ -132,6 +140,8 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option { delay_cs = u16_at(b, body + 2)?; transparent = (flags & 0x01 != 0).then_some(*b.get(body + 4)?); disposal = (flags >> 2) & 7; + control_offset = Some(body + 1); + text_control_offset = None; } // Application Extension NETSCAPE2.0 (or ANIMEXTS1.0): sub-block 3, 1, loop count. if label == 0xFF @@ -141,6 +151,13 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option { info.loop_count = u16_at(b, body + 14); } at = skip_sub_blocks(b, body)?; + // GIF89a §12: a Plain Text Extension consumes the pending graphic control. + if label == 0x01 { + (delay_cs, transparent, disposal) = (0, None, 0); + if let Some(offset) = control_offset.take() { + text_control_offset = Some(offset); + } + } Some(true) } // Image Descriptor: separator, left, top, width, height, packed fields, then the @@ -162,6 +179,10 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option { local_table: packed & 0x80 != 0, }); (delay_cs, transparent, disposal) = (0, None, 0); + control_offset = None; + if let Some(offset) = text_control_offset.take() { + text_control(offset); + } at = skip_sub_blocks(b, (at + 10).checked_add(table_len(packed))?.checked_add(1)?)?; Some(true) } diff --git a/crates/gif/src/tests.rs b/crates/gif/src/tests.rs index 6a776eb50e..b2d5eaf2fe 100644 --- a/crates/gif/src/tests.rs +++ b/crates/gif/src/tests.rs @@ -75,6 +75,42 @@ fn the_first_frames_table_and_transparent_entry() { assert_eq!(palette(&gif(&l, Some(9), None)), Some((l.to_vec(), None))); } +#[test] +fn graphic_control_ends_at_plain_text() { + let mut bytes = Vec::new(); + let colors = [0, 0, 0, 255, 0, 0]; + { + let mut encoder = gif::Encoder::new(&mut bytes, 2, 2, &colors).unwrap(); + let frame = gif::Frame { + width: 2, + height: 2, + delay: 23, + transparent: Some(1), + dispose: gif::DisposalMethod::Previous, + buffer: std::borrow::Cow::Borrowed(&[0; 4]), + ..gif::Frame::default() + }; + encoder.write_frame(&frame).unwrap(); + } + let image_start = scan(&bytes, 1).unwrap().frames[0].offset; + // A comment does not consume the control that precedes it. + let comment = [0x21, 0xfe, 1, b'x', 0]; + bytes.splice(image_start..image_start, comment); + let before = scan(&bytes, 1).unwrap(); + let first = before.frames[0]; + assert_eq!((first.delay_cs, first.transparent, first.disposal), (23, Some(1), 3)); + assert_eq!(palette(&bytes).unwrap().1, Some(1)); + + // A 2×2 plain text grid with 1×1 cells and one character consumes it. + let text = [0x21, 0x01, 12, 0, 0, 0, 0, 2, 0, 2, 0, 1, 1, 1, 0, 1, b'X', 0]; + bytes.splice(first.offset..first.offset, text); + let after = scan(&bytes, 1).unwrap(); + assert!(after.complete); + let first = after.frames[0]; + assert_eq!((first.delay_cs, first.transparent, first.disposal), (0, None, 0)); + assert_eq!(palette(&bytes).unwrap(), (vec![[0, 0, 0], [255, 0, 0]], None)); +} + #[test] fn no_table_or_not_a_gif_is_none() { assert_eq!(palette(&gif(&[], None, None)), None, "no table at all"); diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 46d5103426..bab74d2860 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -43,7 +43,7 @@ zune-core = "0.5" jpeg-encoder = "0.6" craft-jpeg = { workspace = true } craft-metadata = { workspace = true } -craft-tiff = { workspace = true } +craft-tiff = { workspace = true, features = ["plain-rgba16"] } zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] } craft-heif = { workspace = true, optional = true } craft-jxl = { workspace = true, optional = true, features = ["decode"] } diff --git a/crates/image-codecs/src/codecs/tiff.rs b/crates/image-codecs/src/codecs/tiff.rs index 0f53bb3dab..dc537d2fd9 100644 --- a/crates/image-codecs/src/codecs/tiff.rs +++ b/crates/image-codecs/src/codecs/tiff.rs @@ -257,6 +257,11 @@ macro_rules! custom_colortype { use PhotometricInterpretation as PI; +/// Encode plain classic RGBA16 TIFF for callers that need the legacy file layout. +pub fn encode_plain_rgba16(width: u32, height: u32, samples: &[u16]) -> Result, CodecError> { + craft_tiff::plain::encode_rgba16(width, height, samples).map_err(|error| CodecError::encode(F, error)) +} + mod bands; mod decode; mod encode; diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index f43dae32c0..ea143d708c 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -454,10 +454,11 @@ pub fn detect(bytes: &[u8]) -> Option { return Some(Format::Hdr); } if b.len() >= 12 && &b[4..8] == b"ftyp" { - if is_avif_ftyp(b) { + let prefix = &b[..b.len().min(64)]; + if is_avif_ftyp(prefix) { return Some(Format::Avif); } - if is_heif_ftyp(b) { + if is_heif_ftyp(prefix) { return Some(Format::Heif); } } @@ -505,11 +506,21 @@ pub fn detect(bytes: &[u8]) -> Option { None } -/// The `ftyp` brands: the major brand, then the compatible ones (the minor version between them is skipped). -fn ftyp_brands(b: &[u8]) -> impl Iterator { - let size = u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize; - let end = size.clamp(12, b.len().min(64)); - b[8..end].as_chunks::<4>().0.iter().enumerate().filter(|(i, _)| *i != 1).map(|(_, c)| c) +/// The major brand and complete compatible brands in a leading ISO-BMFF `ftyp` box. +/// +/// Pass at most the bytes the caller wants to inspect. A missing box or incomplete major +/// brand yields an empty iterator. For sniffing, a declared size below 12 still permits the +/// major brand. Compatible brands stop at the declared box end or the available prefix, +/// whichever comes first. This does not validate the full box. +pub fn ftyp_brands(prefix: &[u8]) -> impl Iterator + Clone { + let brands = match prefix.first_chunk::<12>() { + Some(header) if &header[4..8] == b"ftyp" => { + let size = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize; + &prefix[8..size.clamp(12, prefix.len())] + } + _ => &[], + }; + brands.as_chunks::<4>().0.iter().enumerate().filter(|(i, _)| *i != 1).map(|(_, brand)| brand) } fn is_avif_ftyp(b: &[u8]) -> bool { diff --git a/crates/image-codecs/src/jpeg_probe.rs b/crates/image-codecs/src/jpeg_probe.rs index 869ae1f691..71b80f687f 100644 --- a/crates/image-codecs/src/jpeg_probe.rs +++ b/crates/image-codecs/src/jpeg_probe.rs @@ -74,6 +74,14 @@ fn be16(b: &[u8], at: usize) -> Option { /// `segment_span` covers the `0xFF` marker byte through the end of the segment payload. pub fn walk_jpeg_segments<'a>( bytes: &'a [u8], + visit: impl FnMut(u8, Range, &'a [u8]) -> Result, +) -> Result<(), JpegProbeError> { + walk_segments(bytes, false, visit) +} + +fn walk_segments<'a>( + bytes: &'a [u8], + stop_at_non_marker: bool, mut visit: impl FnMut(u8, Range, &'a [u8]) -> Result, ) -> Result<(), JpegProbeError> { if bytes.len() < 4 || bytes[0] != 0xFF || bytes[1] != 0xD8 { @@ -82,6 +90,9 @@ pub fn walk_jpeg_segments<'a>( let mut i = 2usize; while let Some(&byte) = bytes.get(i) { if byte != 0xFF { + if stop_at_non_marker { + break; + } i += 1; continue; } @@ -115,6 +126,27 @@ pub fn walk_jpeg_segments<'a>( Ok(()) } +/// EXIF orientation from the first complete APP1 segment prefixed with `Exif\0\0`. +/// +/// Requires consecutive marker prefixes before SOS or EOI. Returns 1 if the +/// first EXIF segment has no readable orientation, or if none is found before +/// the header ends or becomes unreadable. Unlike [`walk_jpeg_segments`], this +/// does not resynchronize past bytes outside a segment. For compatibility, +/// even a marker code of zero is treated as an unknown length-bearing marker. +pub fn strict_exif_orientation(bytes: &[u8]) -> u16 { + let mut orientation = 1; + let _ = walk_segments(bytes, true, |marker, _, segment| { + if marker == 0xE1 + && let Some(exif) = segment.strip_prefix(b"Exif\0\0") + { + orientation = crate::exif_orientation(exif); + return Ok(JpegVisit::Stop); + } + Ok(JpegVisit::Continue) + }); + orientation +} + /// Parse JFIF APP0 density `(x_dpi, y_dpi)` when unit is inches (1) or centimetres (2) and both /// axes are positive. pub fn jfif_dpi(seg: &[u8]) -> Option<(f64, f64)> { @@ -193,6 +225,32 @@ pub fn probe_jpeg(bytes: &[u8]) -> Result { mod tests { use super::*; + #[test] + fn strict_orientation_reads_the_first_exif_app1_before_the_scan() { + const ORIENTATION_6: &[u8] = b"II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0"; + let mut header = Vec::from(b"\xFF\xD8\xFF\xE1\0\x05XMP".as_slice()); + let app1: &[u8] = b"\xFF\xFF\xE1\0\x22Exif\0\0"; + header.extend_from_slice(app1); + header.extend_from_slice(ORIENTATION_6); + assert_eq!(strict_exif_orientation(&header), 6); + // Preserve the legacy placement scanner’s treatment of a zero marker code. + let mut zero_marker = Vec::from(b"\xFF\xD8\xFF\x00\x00\x02".as_slice()); + zero_marker.extend_from_slice(&header[2..]); + assert_eq!(strict_exif_orientation(&zero_marker), 6); + + let mut interrupted = vec![0xff, 0xd8, 0x01]; + interrupted.extend_from_slice(&header[2..]); + assert_eq!(strict_exif_orientation(&interrupted), 1); + + let mut after_scan = Vec::from(b"\xFF\xD8\xFF\xDA".as_slice()); + after_scan.extend_from_slice(&header[2..]); + assert_eq!(strict_exif_orientation(&after_scan), 1); + + let mut untagged_first = Vec::from(b"\xFF\xD8\xFF\xE1\0\x16Exif\0\0II\x2a\0\x08\0\0\0\0\0\0\0\0\0".as_slice()); + untagged_first.extend_from_slice(&header[2..]); + assert_eq!(strict_exif_orientation(&untagged_first), 1); + } + #[test] fn jpeg_probe_preserves_error_diagnostics() { assert_eq!(probe_jpeg(b"\x89PNG").unwrap_err(), JpegProbeError::NotJpeg); diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index 2a91dc6ea8..a5e572f36d 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -53,13 +53,16 @@ pub use crate::codecs::png::{ encode_pq as encode_png_pq, palette as png_palette, stereo as png_stereo, }; pub use crate::codecs::tiff::{ - PhotoshopTags as TiffPhotoshopTags, TiffBands, photoshop_tags as tiff_photoshop_tags, writes_little_endian as tiff_writes_little_endian, + PhotoshopTags as TiffPhotoshopTags, TiffBands, encode_plain_rgba16 as encode_tiff_plain_rgba16, photoshop_tags as tiff_photoshop_tags, + writes_little_endian as tiff_writes_little_endian, }; pub use crate::codecs::tiff_ifd::{ExtraSampleKind, InkSet, TiffInfo, TiffPage, TiffPageKind}; pub use crate::error::CodecError; pub use crate::exif_color::{EXIF_COLOR_SPACE_SRGB, exif_color_space}; pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_with}; -pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Detection, Format, FormatCaps, PrefixDetector, caps, detect, detect_prefix, from_extension}; +pub use crate::format::{ + ASYMMETRIC_EXCEPTIONS, Detection, Format, FormatCaps, PrefixDetector, caps, detect, detect_prefix, from_extension, ftyp_brands, +}; pub use crate::image::{ ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, ExtraSample, Image, MAX_EXTRA_SAMPLES, Metadata, SampleType, convert_samples, diff --git a/crates/image-codecs/src/png_probe.rs b/crates/image-codecs/src/png_probe.rs index e7af74334b..7c27f966bb 100644 --- a/crates/image-codecs/src/png_probe.rs +++ b/crates/image-codecs/src/png_probe.rs @@ -1,4 +1,5 @@ //! Header-only PNG inspection without inflating image data. +pub use crate::resolution_probe::png_pixels_per_meter as pixels_per_meter; use crate::{CodecError, Format}; fn err(message: &str) -> CodecError { CodecError::malformed(Format::Png, message) diff --git a/crates/image-codecs/src/raw_metadata.rs b/crates/image-codecs/src/raw_metadata.rs index 916a0078ac..17192bccc9 100644 --- a/crates/image-codecs/src/raw_metadata.rs +++ b/crates/image-codecs/src/raw_metadata.rs @@ -1,4 +1,4 @@ -//! Explicit verbatim EXIF and JPEG APP metadata helpers for callers that preserve stored orientation. +//! Explicit PNG density and sRGB, verbatim EXIF and JPEG APP metadata helpers for encoded images. //! Normal encoder APIs still normalize metadata for upright pixels; callers opt in to these helpers. use crate::{CodecError, Format}; @@ -100,15 +100,128 @@ fn jpeg_exif_payload(jpeg: &[u8]) -> Option> { } } +const PNG_IHDR_END: usize = 33; + +/// A complete PNG pHYs chunk in pixels per metre, including the length, type and CRC. +/// +/// Both axes must be nonzero. The caller chooses the conversion from PPI to raw pixels per metre. +/// The payload follows [PNG Third Edition, pHYs](https://www.w3.org/TR/png-3/#11pHYs). +pub fn png_pixels_per_meter_chunk((x, y): (u32, u32)) -> Result<[u8; 21], CodecError> { + if x == 0 || y == 0 { + return Err(error(Format::Png, "PNG density requires two nonzero axes")); + } + let mut chunk = [0; 21]; + chunk[..4].copy_from_slice(&9u32.to_be_bytes()); + chunk[4..8].copy_from_slice(b"pHYs"); + chunk[8..12].copy_from_slice(&x.to_be_bytes()); + chunk[12..16].copy_from_slice(&y.to_be_bytes()); + chunk[16] = 1; + let crc = crc32fast::hash(&chunk[4..17]); + chunk[17..].copy_from_slice(&crc.to_be_bytes()); + Ok(chunk) +} + +/// Insert one pHYs chunk after IHDR and remove the old density chunks through IEND. +/// +/// The PNG signature and chunk boundaries must be intact through a zero-length IEND. +/// The rewrite preserves all other bytes, including trailing bytes, and leaves existing CRCs +/// and image data as supplied. It bounds the returned file by `max_bytes` and never inflates pixels. +pub fn with_png_pixels_per_meter(png: &[u8], resolution: (u32, u32), max_bytes: usize) -> Result, CodecError> { + let density = png_pixels_per_meter_chunk(resolution)?; + rewrite_png_header_chunk(png, b"pHYs", &density, max_bytes, "PNG density rewrite") +} + +/// Rendering intent stored in a PNG sRGB chunk. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum SrgbRenderingIntent { + Perceptual = 0, + RelativeColorimetric = 1, + Saturation = 2, + AbsoluteColorimetric = 3, +} + +/// Insert one sRGB chunk after IHDR and remove old sRGB declarations through IEND. +/// +/// The source must already contain sRGB samples. Images with an ICC or cICP color +/// declaration or conflicting legacy gamma or chromaticities are refused. +/// The output is bounded by `max_bytes`. Pixel and other chunk bytes are preserved. +pub fn with_png_srgb(png: &[u8], intent: SrgbRenderingIntent, max_bytes: usize) -> Result, CodecError> { + let mut chunk = [0; 13]; + chunk[..4].copy_from_slice(&1u32.to_be_bytes()); + chunk[4..8].copy_from_slice(b"sRGB"); + chunk[8] = intent as u8; + let crc = crc32fast::hash(&chunk[4..9]); + chunk[9..].copy_from_slice(&crc.to_be_bytes()); + rewrite_png_header_chunk(png, b"sRGB", &chunk, max_bytes, "PNG sRGB rewrite") +} + +fn rewrite_png_header_chunk(png: &[u8], kind: &[u8; 4], replacement: &[u8], max_bytes: usize, operation: &str) -> Result, CodecError> { + let header = png + .get(..PNG_IHDR_END) + .filter(|h| h.starts_with(b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR")) + .ok_or_else(|| CodecError::malformed(Format::Png, "PNG signature or IHDR is missing"))?; + + let mut at = PNG_IHDR_END; + let mut removed = 0; + let end = loop { + let chunk = png_chunk_at(png, at).ok_or_else(|| CodecError::malformed(Format::Png, "truncated PNG chunk or missing IEND"))?; + if chunk.len() - 12 > i32::MAX as usize { + return Err(CodecError::malformed(Format::Png, "PNG chunk length exceeds 31 bits")); + } + at += chunk.len(); + match &chunk[4..8] { + name if name == kind => removed += chunk.len(), + b"iCCP" | b"cICP" if kind == b"sRGB" => return Err(error(Format::Png, "PNG already declares an ICC or cICP color profile")), + b"gAMA" if kind == b"sRGB" && &chunk[8..chunk.len() - 4] != 45_455u32.to_be_bytes().as_slice() => { + return Err(error(Format::Png, "PNG gAMA is incompatible with sRGB")); + } + b"cHRM" if kind == b"sRGB" => { + // PNG Third Edition, table 17. The encoded values are scaled by 100,000. + const SRGB_CHROMATICITIES: [u32; 8] = [31_270, 32_900, 64_000, 33_000, 30_000, 60_000, 15_000, 6_000]; + if &chunk[8..chunk.len() - 4] != SRGB_CHROMATICITIES.map(u32::to_be_bytes).as_flattened() { + return Err(error(Format::Png, "PNG cHRM is incompatible with sRGB")); + } + } + b"IEND" if chunk.len() == 12 => break at, + b"IEND" => return Err(CodecError::malformed(Format::Png, "nonempty IEND")), + _ => {} + } + }; + let size = (png.len() - removed) + .checked_add(replacement.len()) + .filter(|&size| size <= max_bytes) + .ok_or_else(|| CodecError::LimitExceeded(format!("{operation} byte budget")))?; + let mut out = Vec::new(); + out.try_reserve_exact(size).map_err(|_| CodecError::LimitExceeded(format!("{operation} allocation")))?; + out.extend_from_slice(header); + out.extend_from_slice(replacement); + let (datastream, trailing) = png.split_at(end); + let mut at = PNG_IHDR_END; + while let Some(chunk) = png_chunk_at(datastream, at) { + if &chunk[4..8] != kind { + out.extend_from_slice(chunk); + } + at += chunk.len(); + } + out.extend_from_slice(trailing); + Ok(out) +} + +fn png_chunk_at(png: &[u8], at: usize) -> Option<&[u8]> { + let rest = png.get(at..)?; + let size = u32::from_be_bytes(*rest.first_chunk()?) as usize; + rest.get(..size.checked_add(12)?) +} + /// Replace the existing PNG eXIf chunk, preserving the other chunks and recomputing its CRC. /// No chunk is inserted when one is absent. pub fn replace_png_exif(png: &mut Vec, exif: &[u8]) -> Result<(), CodecError> { let len = u32::try_from(exif.len()).map_err(|_| error(Format::Png, "EXIF too large"))?; let mut p = 8usize; - while let Some(bytes) = p.checked_add(4).and_then(|end| png.get(p..end)) { - let size = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize; - let Some(end) = p.checked_add(12).and_then(|v| v.checked_add(size)).filter(|end| *end <= png.len()) else { break }; - if png.get(p + 4..p + 8) == Some(b"eXIf") { + while let Some(existing) = png_chunk_at(png, p) { + let end = p + existing.len(); + if &existing[4..8] == b"eXIf" { let mut chunk = Vec::new(); chunk.extend_from_slice(&len.to_be_bytes()); chunk.extend_from_slice(b"eXIf"); @@ -305,6 +418,130 @@ mod tests { assert_eq!(no_marker, before); } + #[test] + fn png_density_chunk_uses_raw_values_and_the_expected_crc() { + let expected = b"\0\0\0\x09pHYs\0\0\x2e\x23\0\0\x17\x12\x01\x95\x42\xe6\xdb"; + assert_eq!(&png_pixels_per_meter_chunk((11_811, 5_906)).unwrap(), expected); + assert!(png_pixels_per_meter_chunk((0, 5_906)).is_err()); + assert!(png_pixels_per_meter_chunk((11_811, 0)).is_err()); + } + + #[test] + fn png_density_edit_replaces_duplicates_and_keeps_encoded_bytes() { + let image = crate::Image::from_u8(2, 1, crate::ChannelLayout::Rgb, vec![19, 33, 51, 98, 80, 61]).unwrap(); + let png = crate::encode(&image, Format::Png, &crate::EncodeOptions::default()).unwrap(); + let old_density = b"\0\0\0\x09pHYs\0\0\x2e\x23\0\0\x17\x12\x01\x95\x42\xe6\xdb"; + let trail = b"container trailer"; + let iend = png.len() - 12; + // The second obsolete density occurs too late. The rewrite leaves one legal chunk. + let input = [&png[..33], old_density, &png[33..iend], old_density, &png[iend..], trail].concat(); + let resolution = (200_003, 93_511); + let added = png_pixels_per_meter_chunk(resolution).unwrap(); + let expected = [&png[..33], &added, &png[33..], trail].concat(); + let edited = with_png_pixels_per_meter(&input, resolution, expected.len()).unwrap(); + assert_eq!(edited, expected); + assert_eq!(crate::png_probe::pixels_per_meter(&edited), Some(resolution)); + let original = crate::decode(&png).unwrap(); + let changed = crate::decode(&edited[..edited.len() - trail.len()]).unwrap(); + assert_eq!(changed.data(), original.data()); + assert!(matches!(with_png_pixels_per_meter(&input, resolution, expected.len() - 1), Err(CodecError::LimitExceeded(_)))); + assert_eq!(with_png_pixels_per_meter(&edited, resolution, edited.len()).unwrap(), edited); + } + + #[test] + fn png_density_edit_rejects_truncation_and_limits_insertion() { + let image = crate::Image::from_u8(1, 1, crate::ChannelLayout::Rgb, vec![10, 20, 30]).unwrap(); + let png = crate::encode(&image, Format::Png, &crate::EncodeOptions::default()).unwrap(); + let resolution = (2_835, 2_836); + for end in 0..png.len() { + assert!(with_png_pixels_per_meter(&png[..end], resolution, usize::MAX).is_err(), "prefix {end}"); + } + let mut damaged = png.clone(); + damaged[0] = 0; + assert!(with_png_pixels_per_meter(&damaged, resolution, usize::MAX).is_err()); + assert!(with_png_pixels_per_meter(&png, (0, 300), usize::MAX).is_err()); + assert!(matches!(with_png_pixels_per_meter(&png, resolution, png.len() + 20), Err(CodecError::LimitExceeded(_)))); + let edited = with_png_pixels_per_meter(&png, resolution, png.len() + 21).unwrap(); + assert_eq!(edited.len(), png.len() + 21); + assert_eq!(crate::png_probe::pixels_per_meter(&edited), Some(resolution)); + } + + #[test] + fn png_srgb_rewrite_replaces_duplicates_and_preserves_the_encoded_image() { + let image = crate::Image::from_u8(2, 1, crate::ChannelLayout::Rgba, vec![19, 33, 51, 127, 98, 80, 61, 255]).unwrap(); + let plain = crate::encode(&image, Format::Png, &crate::EncodeOptions::default()).unwrap(); + let old = b"\0\0\0\x01sRGB\0\xae\xce\x1c\xe9"; + let density = png_pixels_per_meter_chunk((11_811, 5_906)).unwrap(); + let iend = plain.len() - 12; + let trailer = b"container trailer"; + let input = [&plain[..33], old, &density, &plain[33..iend], old, &plain[iend..], trailer].concat(); + for (intent, expected_chunk) in [ + (SrgbRenderingIntent::Perceptual, old), + (SrgbRenderingIntent::RelativeColorimetric, b"\0\0\0\x01sRGB\x01\xd9\xc9\x2c\x7f"), + (SrgbRenderingIntent::Saturation, b"\0\0\0\x01sRGB\x02\x40\xc0\x7d\xc5"), + (SrgbRenderingIntent::AbsoluteColorimetric, b"\0\0\0\x01sRGB\x03\x37\xc7\x4d\x53"), + ] { + let expected = [&plain[..33], expected_chunk, &density, &plain[33..], trailer].concat(); + let edited = with_png_srgb(&input, intent, expected.len()).unwrap(); + assert_eq!(edited, expected); + assert_eq!(with_png_srgb(&edited, intent, edited.len()).unwrap(), edited); + assert_eq!(crate::png_probe::pixels_per_meter(&edited), Some((11_811, 5_906))); + let decoded = crate::decode(&edited[..edited.len() - trailer.len()]).unwrap(); + assert_eq!(decoded.data(), image.data()); + } + } + + #[test] + fn png_srgb_rewrite_rejects_profile_conflicts_truncation_and_output_overflow() { + let image = crate::Image::from_u8(1, 1, crate::ChannelLayout::Rgb, vec![15, 20, 35]).unwrap(); + let plain = crate::encode(&image, Format::Png, &crate::EncodeOptions::default()).unwrap(); + let intent = SrgbRenderingIntent::Perceptual; + for end in 0..plain.len() { + assert!(with_png_srgb(&plain[..end], intent, usize::MAX).is_err(), "prefix {end}"); + } + for kind in [b"iCCP", b"cICP"] { + let bytes = [&plain[..33], b"\0\0\0\0", kind, &crc32fast::hash(kind).to_be_bytes(), &plain[33..]].concat(); + assert!(matches!(with_png_srgb(&bytes, intent, usize::MAX), Err(CodecError::Encode { .. }))); + } + assert!(matches!(with_png_srgb(&plain, intent, plain.len() + 12), Err(CodecError::LimitExceeded(_)))); + assert_eq!(with_png_srgb(&plain, intent, plain.len() + 13).unwrap().len(), plain.len() + 13); + } + + #[test] + fn png_srgb_rewrite_requires_compatible_legacy_color_chunks() { + fn chunk(kind: &[u8; 4], payload: &[u8]) -> Vec { + let mut bytes = (payload.len() as u32).to_be_bytes().to_vec(); + bytes.extend_from_slice(kind); + bytes.extend_from_slice(payload); + let crc = crc32fast::hash(&bytes[4..]); + bytes.extend_from_slice(&crc.to_be_bytes()); + bytes + } + + let image = crate::Image::from_u8(1, 1, crate::ChannelLayout::Rgb, vec![15, 20, 35]).unwrap(); + let plain = crate::encode(&image, Format::Png, &crate::EncodeOptions::default()).unwrap(); + let (header, rest) = plain.split_at(33); + let gamma = chunk(b"gAMA", &45_455u32.to_be_bytes()); + let standard = [31_270u32, 32_900, 64_000, 33_000, 30_000, 60_000, 15_000, 6_000]; + let chroma = chunk(b"cHRM", &standard.map(u32::to_be_bytes).concat()); + let compatible = [header, &gamma, &chroma, rest].concat(); + let intent = SrgbRenderingIntent::Perceptual; + let marker = b"\0\0\0\x01sRGB\0\xae\xce\x1c\xe9"; + assert_eq!(with_png_srgb(&compatible, intent, usize::MAX).unwrap(), [header, marker, &gamma, &chroma, rest].concat()); + + let other_gamma = chunk(b"gAMA", &45_454u32.to_be_bytes()); + let mut other_chroma = standard; + other_chroma[7] += 1; + let other_chroma = chunk(b"cHRM", &other_chroma.map(u32::to_be_bytes).concat()); + let incomplete_chroma = chunk(b"cHRM", &standard[..7].iter().flat_map(|value| value.to_be_bytes()).collect::>()); + let conflicts = [(&other_gamma, &chroma), (&gamma, &other_chroma), (&gamma, &incomplete_chroma)]; + let rejected = conflicts.map(|(g, c)| { + let incompatible = [header, g, c, rest].concat(); + matches!(with_png_srgb(&incompatible, intent, usize::MAX), Err(CodecError::Encode { .. })) + }); + assert_eq!(rejected, [true; 3]); + } + #[test] fn jpeg_segments_keep_order_and_enforce_limits() { let parts = jpeg_segments(JpegMetadata { exif: Some(EXIF), xmp: Some(""), icc: Some(&[1, 2]), ppi: Some(300) }).unwrap(); diff --git a/crates/image-codecs/src/resolution_probe.rs b/crates/image-codecs/src/resolution_probe.rs index 87729f18ec..7363e45a74 100644 --- a/crates/image-codecs/src/resolution_probe.rs +++ b/crates/image-codecs/src/resolution_probe.rs @@ -69,14 +69,19 @@ fn le_i32(b: &[u8], at: usize) -> Option { Some(i32::from_le_bytes(b.get(at..at.checked_add(4)?)?.try_into().ok()?)) } -fn png_phys(bytes: &[u8]) -> Option<(f32, f32)> { +/// Raw PNG `pHYs` pixels per metre `(x, y)` before any DPI snapping, when the chunk precedes +/// `IDAT`/`IEND` within the shared chunk limit, has unit `1` (metre), and both axes are nonzero. +pub fn png_pixels_per_meter(bytes: &[u8]) -> Option<(u32, u32)> { + if !bytes.starts_with(PNG_SIGNATURE) { + return None; + } let mut pos = PNG_SIGNATURE.len(); for _ in 0..MAX_CHUNKS { let len = usize::try_from(be_u32(bytes, pos)?).ok()?; let data = pos.checked_add(8)?; match bytes.get(pos.checked_add(4)?..data)? { // A `pHYs` chunk holds exactly nine bytes; the whole chunk, CRC included, must be there. - b"pHYs" if len == 9 => return bytes.get(data..data.checked_add(13)?).and_then(|chunk| phys(chunk.get(..9)?)), + b"pHYs" if len == 9 => return bytes.get(data..data.checked_add(13)?).and_then(|chunk| phys_ppm(chunk.get(..9)?)), b"pHYs" => return None, b"IDAT" | b"IEND" => return None, _ => pos = data.checked_add(len)?.checked_add(4)?, @@ -85,15 +90,20 @@ fn png_phys(bytes: &[u8]) -> Option<(f32, f32)> { None } +fn png_phys(bytes: &[u8]) -> Option<(f32, f32)> { + let (x, y) = png_pixels_per_meter(bytes)?; + Some((png::dpi_of_ppm(x), png::dpi_of_ppm(y))) +} + /// `pHYs`: pixels per unit in x and y, then the unit (1 = metre; 0 = aspect ratio only). -fn phys(data: &[u8]) -> Option<(f32, f32)> { +fn phys_ppm(data: &[u8]) -> Option<(u32, u32)> { let (x, y) = (be_u32(data, 0)?, be_u32(data, 4)?); // As the decoder does: a zero count, or a unit other than the metre, records no resolution, // so the `eXIf` resolution can still answer. if *data.get(8)? != 1 || x == 0 || y == 0 { return None; } - Some((png::dpi_of_ppm(x), png::dpi_of_ppm(y))) + Some((x, y)) } /// The resolution of a PNG's `eXIf` chunk, read by the decoder's own header probe. diff --git a/crates/image-codecs/src/resolution_probe_tests.rs b/crates/image-codecs/src/resolution_probe_tests.rs index 1a650ec3f3..a7a8d549d3 100644 --- a/crates/image-codecs/src/resolution_probe_tests.rs +++ b/crates/image-codecs/src/resolution_probe_tests.rs @@ -301,3 +301,21 @@ fn png_zero_phys_leaves_the_exif_resolution() { assert_eq!(file_resolution(&png(&[zero(0, 0), exif.clone()])), Some((600.0, 600.0))); assert_eq!(file_resolution(&png(&[zero(11_811, 0), exif])), Some((600.0, 600.0))); } + +#[test] +fn png_pixels_per_meter_preserves_raw_values_and_shared_chunk_limit() { + assert_eq!(crate::png_probe::pixels_per_meter(&png(&[phys(1181, 2362, 1)])), Some((1181, 2362))); + assert_eq!(crate::png_probe::pixels_per_meter(&png(&[phys(1181, 1181, 0)])), None); + assert_eq!(crate::png_probe::pixels_per_meter(&png(&[phys(0, 1181, 1)])), None); + assert_eq!(crate::png_probe::pixels_per_meter(b"not a png"), None); + assert_eq!(crate::png_probe::pixels_per_meter(&png(&[png_chunk(b"IDAT", &[]), phys(1181, 1181, 1)])), None); + + let text = png_chunk(b"tEXt", b"k\x00v"); + let mut at_limit = vec![text.clone(); super::MAX_CHUNKS - 2]; + at_limit.push(phys(1181, 1181, 1)); + assert_eq!(crate::png_probe::pixels_per_meter(&png(&at_limit)), Some((1181, 1181))); + + let mut past_limit = vec![text; super::MAX_CHUNKS - 1]; + past_limit.push(phys(1181, 1181, 1)); + assert_eq!(crate::png_probe::pixels_per_meter(&png(&past_limit)), None); +} diff --git a/crates/image-codecs/tests/it/detect_caps.rs b/crates/image-codecs/tests/it/detect_caps.rs index ee9ccda515..36b09ac264 100644 --- a/crates/image-codecs/tests/it/detect_caps.rs +++ b/crates/image-codecs/tests/it/detect_caps.rs @@ -108,6 +108,34 @@ fn detect_heif_brands() { assert_eq!(detect(b"\0\0\0\x14ftypqt \0\0\0\0qt "), None, "QuickTime is not HEIF"); } +#[test] +fn ftyp_brands_respect_prefix_and_declared_bounds() { + let mut prefix = *b"\0\0\0\x1cftypisomavifavismif1xx"; + for end in 0..12 { + assert!(ftyp_brands(&prefix[..end]).next().is_none(), "prefix length {end}"); + } + assert!(ftyp_brands(b"\0\0\0\x0cmdatheic").next().is_none()); + assert!(ftyp_brands(&prefix).eq([b"isom", b"avis", b"mif1"])); + assert!(ftyp_brands(&prefix[..18]).eq([b"isom"])); + + prefix[..4].copy_from_slice(&20u32.to_be_bytes()); + assert!(ftyp_brands(&prefix).eq([b"isom", b"avis"])); + prefix[..4].copy_from_slice(&8u32.to_be_bytes()); + assert!(ftyp_brands(&prefix).eq([b"isom"])); +} + +#[test] +fn detect_ftyp_keeps_its_short_brand_scan() { + let mut prefix = [0; 68]; + prefix[..12].copy_from_slice(b"\0\0\0\x44ftypheic"); + prefix[64..68].copy_from_slice(b"avif"); + assert!(ftyp_brands(&prefix).any(|brand| brand == b"avif")); + assert_eq!(detect(&prefix), Some(Format::Heif)); + + prefix[60..64].copy_from_slice(b"avif"); + assert_eq!(detect(&prefix), Some(Format::Avif)); +} + #[test] fn caps_are_internally_consistent() { for f in Format::ALL { diff --git a/crates/media-source/Cargo.toml b/crates/media-source/Cargo.toml index 3edda0b2e8..ea9f5fd83a 100644 --- a/crates/media-source/Cargo.toml +++ b/crates/media-source/Cargo.toml @@ -10,12 +10,16 @@ repository.workspace = true [lints] workspace = true +[features] +y4m = ["dep:craft-y4m"] + [dependencies] craft-audio = { workspace = true } craft-color = { workspace = true } craft-frame = { workspace = true } craft-media = { workspace = true } craft-time = { workspace = true } +craft-y4m = { workspace = true, optional = true } serde = { workspace = true } thiserror = { workspace = true } diff --git a/crates/media-source/src/cancel.rs b/crates/media-source/src/cancel.rs new file mode 100644 index 0000000000..41654d51c4 --- /dev/null +++ b/crates/media-source/src/cancel.rs @@ -0,0 +1,111 @@ +//! Cooperative cancellation of media requests. +//! +//! A request worker installs a flag with [`with_cancel`]. Readers poll [`cancelled`] at +//! their existing interruption points and can return [`crate::MediaError::Cancelled`]. +//! Use [`Context`] to carry the same flag to another worker. + +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +thread_local! { + static CURRENT: RefCell>> = const { RefCell::new(None) }; +} + +/// Run `f` with this cancellation flag, restoring the preceding state when the scope ends. +pub fn with_cancel(flag: &Arc, f: impl FnOnce() -> R) -> R { + Context(Some(Arc::clone(flag))).run(f) +} + +/// Whether the flag installed on this thread has been set. An empty context is never cancelled. +pub fn cancelled() -> bool { + CURRENT.with_borrow(|flag| flag.as_ref().is_some_and(|flag| flag.load(Ordering::Relaxed))) +} + +/// A captured cancellation scope that can be carried to another thread. +/// +/// It holds the flag itself, so cancellation after capture is visible to the worker. +/// A default context has no flag. +#[derive(Clone, Default)] +pub struct Context(Option>); + +impl Context { + /// Capture this thread's current cancellation scope. + pub fn current() -> Self { + Self(CURRENT.with_borrow(Clone::clone)) + } + + /// Run `f` with this context, even when empty. Restore the previous context on return or unwind. + pub fn run(self, f: impl FnOnce() -> R) -> R { + struct Restore(Option>); + + impl Drop for Restore { + fn drop(&mut self) { + CURRENT.with_borrow_mut(|flag| *flag = self.0.take()); + } + } + + let _restore = Restore(CURRENT.with_borrow_mut(|flag| std::mem::replace(flag, self.0))); + f() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn live_flag_is_scoped_and_nested_contexts_can_mask_it() { + let outer = Arc::new(AtomicBool::new(false)); + let inner = Arc::new(AtomicBool::new(false)); + assert!(!cancelled()); + with_cancel(&outer, || { + assert!(!cancelled()); + outer.store(true, Ordering::Relaxed); + assert!(cancelled()); + with_cancel(&inner, || assert!(!cancelled())); + assert!(cancelled()); + Context::default().run(|| assert!(!cancelled())); + assert!(cancelled()); + }); + assert!(!cancelled()); + } + + #[test] + fn unwind_restores_the_enclosing_flag() { + let outer = Arc::new(AtomicBool::new(false)); + let inner = Arc::new(AtomicBool::new(true)); + with_cancel(&outer, || { + let result = std::panic::catch_unwind(|| with_cancel(&inner, || panic!("request failed"))); + assert!(result.is_err()); + assert!(!cancelled()); + outer.store(true, Ordering::Relaxed); + assert!(cancelled()); + }); + assert!(!cancelled()); + } + + #[test] + fn captured_flag_is_live_on_the_worker_and_restores_its_context() { + let request = Arc::new(AtomicBool::new(false)); + let context = with_cancel(&request, Context::current); + request.store(true, Ordering::Relaxed); + + std::thread::spawn(move || { + let worker = Arc::new(AtomicBool::new(false)); + with_cancel(&worker, || { + assert!(context.clone().run(cancelled)); + assert!(!cancelled()); + let result = std::panic::catch_unwind(|| context.run(|| panic!("delegate failed"))); + assert!(result.is_err()); + assert!(!cancelled()); + worker.store(true, Ordering::Relaxed); + assert!(cancelled()); + }); + assert!(!cancelled()); + }) + .join() + .unwrap(); + assert!(!cancelled()); + } +} diff --git a/crates/media-source/src/lib.rs b/crates/media-source/src/lib.rs index c27aea6889..909fdbaad1 100644 --- a/crates/media-source/src/lib.rs +++ b/crates/media-source/src/lib.rs @@ -26,6 +26,10 @@ use craft_media::ByteSource; use craft_time::{FrameRate, Tick}; use serde::{Deserialize, Serialize}; +pub mod cancel; +#[cfg(feature = "y4m")] +pub mod y4m; + /// Errors from opening or reading a media source. #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] pub enum MediaError { diff --git a/crates/media-source/src/y4m.rs b/crates/media-source/src/y4m.rs new file mode 100644 index 0000000000..89a014c713 --- /dev/null +++ b/crates/media-source/src/y4m.rs @@ -0,0 +1,171 @@ +//! Indexed, range-backed YUV4MPEG2 playback over the shared parser. +//! +//! Adapted to the shared source and frame types from FilmCraft's in-house `Y4mSource`; +//! see the repository's attribution for source history. + +use std::sync::Arc; + +use craft_audio::AudioBuffer; +use craft_color::{ColorInfo, Range}; +use craft_frame::{Chroma, PixelData, VideoFrame, default_matrix}; +use craft_time::{FrameRate, Tick}; +use craft_y4m::{Error, Layout, Limits, Stream, samples_u16}; + +use crate::{DEFAULT_MAX_MEDIA_BYTES, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result, SharedBytes, VideoStreamInfo, read_range}; + +pub use craft_y4m::sniff; + +/// Y4M video whose frame payloads are read on demand from an indexed byte source. +pub struct Y4mSource { + source: SharedBytes, + stream: Stream, + info: MediaInfo, + rate: FrameRate, +} + +impl Y4mSource { + /// Index complete pictures without loading the video. A picture larger than the shared + /// byte-reader allocation ceiling is reported as unsupported before this source is returned. + pub fn open(name: &str, source: SharedBytes) -> Result { + let len = source.len(); + let mut read_error = None; + let stream = Stream::open( + len, + |offset, len| match read_range(&*source, offset, len) { + Ok(bytes) if bytes.len() == len => Some(bytes), + Ok(_) => { + // The parser already clips requests to the length snapshotted at open. + // A shorter read here is an I/O failure, not a known incomplete tail. + read_error = Some(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "short read while indexing Y4M")); + None + } + Err(err) => { + read_error = Some(err); + None + } + }, + &Limits::default(), + ); + if let Some(err) = read_error { + return Err(MediaError::Io(format!("{name}: Y4M: {err}"))); + } + let stream = stream.map_err(|err| match err { + Error::UnsupportedColourSpace(c) => MediaError::Unsupported(format!("{name}: Y4M colour space {c}")), + Error::LimitExceeded(limit) => MediaError::Unsupported(format!("{name}: Y4M exceeds its {limit} limit")), + Error::Malformed(reason) => MediaError::Decode(format!("{name}: Y4M: {reason}")), + })?; + if stream.frame_bytes > DEFAULT_MAX_MEDIA_BYTES { + return Err(MediaError::Unsupported(format!("{name}: Y4M frame exceeds the media buffer limit"))); + } + + let header = &stream.header; + let (width, height) = (header.width, header.height); + let rate = header.frame_rate.map_or(FrameRate::FPS_25, |(n, d)| FrameRate::new(n, d)); + let color = ColorInfo { + matrix: default_matrix(width, height), + range: if header.full_range { Range::Full } else { Range::Limited }, + ..ColorInfo::REC709 + }; + let duration = picture_time(stream.frames.len(), rate); + let bitrate = (stream.frame_bytes as u64 * 8).checked_mul(rate.num as u64).map(|bits| bits / rate.den as u64); + let info = MediaInfo { + name: name.into(), + kind: MediaKind::Movie, + duration, + video: Some(VideoStreamInfo { + width, + height, + frame_rate: rate, + par: header.pixel_aspect.unwrap_or((1, 1)), + codec: "Uncompressed YUV".into(), + pixel_format: layout_label(header.layout), + color, + has_alpha: header.layout.alpha, + bitrate, + hdr: None, + }), + audio_streams: Vec::new(), + container: "Y4M".into(), + start_timecode: None, + file_size: Some(len), + }; + Ok(Self { source, stream, info, rate }) + } + + fn picture(&self, index: usize) -> Result { + let (Some(payload), Some(info)) = (self.stream.frame(index), self.info.video.as_ref()) else { + return Err(MediaError::Decode("Y4M: frame index out of range".into())); + }; + let len = self.stream.frame_bytes; + let bytes = read_range(&*self.source, payload.start, len).map_err(|err| MediaError::Decode(format!("Y4M: {err}")))?; + if bytes.len() != len { + return Err(MediaError::Decode("Y4M: incomplete frame payload".into())); + } + + let header = &self.stream.header; + let layout = header.layout; + let planes = header.planes(); + let grey = header.chroma_samples(craft_y4m::Chroma::C420); + let chroma = layout.chroma.map(chroma).unwrap_or(Chroma::C420); + let data = if layout.bits == 8 { + let y = Arc::new(bytes[planes.y].to_vec()); + let (cb, cr) = if layout.chroma.is_some() { + (Arc::new(bytes[planes.cb].to_vec()), Arc::new(bytes[planes.cr].to_vec())) + } else { + let neutral = Arc::new(vec![128; grey]); + (neutral.clone(), neutral) + }; + let alpha = layout.alpha.then(|| Arc::new(bytes[planes.alpha].to_vec())); + PixelData::Yuv8 { planes: [y, cb, cr], chroma, alpha } + } else { + let plane = |range: std::ops::Range| Arc::new(samples_u16(&bytes[range], layout.bits)); + let y = plane(planes.y); + let (cb, cr) = if layout.chroma.is_some() { + (plane(planes.cb), plane(planes.cr)) + } else { + let neutral = Arc::new(vec![1 << (layout.bits - 1); grey]); + (neutral.clone(), neutral) + }; + PixelData::Yuv16 { planes: [y, cb, cr], chroma, bits: layout.bits, alpha: None } + }; + Ok(VideoFrame { width: info.width, height: info.height, data, color: info.color, par: info.par, pts: picture_time(index, self.rate) }) + } +} + +impl MediaSource for Y4mSource { + fn info(&self) -> &MediaInfo { + &self.info + } + + fn video_frame(&self, req: FrameRequest) -> Result> { + let last = self.stream.frames.len().saturating_sub(1); + let index = usize::try_from(self.rate.frame_at(req.time.max(Tick::ZERO))).unwrap_or(last).min(last); + self.picture(index).map(Arc::new) + } + + fn audio(&self, _start: i64, _frames: usize, _sample_rate: u32) -> Result { + Err(MediaError::NoStream("audio")) + } +} + +fn picture_time(index: usize, rate: FrameRate) -> Tick { + // The parser's default frame-count cap is below i64::MAX on every target. + // Round up to the same boundary used by frame_at, within Tick resolution and range. + rate.tick_of(index as i64) +} + +fn chroma(chroma: craft_y4m::Chroma) -> Chroma { + match chroma { + craft_y4m::Chroma::C420 => Chroma::C420, + craft_y4m::Chroma::C422 => Chroma::C422, + craft_y4m::Chroma::C444 => Chroma::C444, + } +} + +fn layout_label(layout: Layout) -> String { + match (layout.chroma, layout.alpha) { + (None, _) => format!("Monochrome {}-bit", layout.bits), + (Some(_), true) => format!("YUVA 4:4:4:4 {}-bit", layout.bits), + (Some(subsampling), false) => format!("YUV {} {}-bit", chroma(subsampling).label(), layout.bits), + } +} diff --git a/crates/media-source/tests/it/main.rs b/crates/media-source/tests/it/main.rs new file mode 100644 index 0000000000..94659dc7dd --- /dev/null +++ b/crates/media-source/tests/it/main.rs @@ -0,0 +1,2 @@ +#[cfg(feature = "y4m")] +mod y4m; diff --git a/crates/media-source/tests/it/y4m.rs b/crates/media-source/tests/it/y4m.rs new file mode 100644 index 0000000000..95b06a7431 --- /dev/null +++ b/crates/media-source/tests/it/y4m.rs @@ -0,0 +1,205 @@ +use std::io; +use std::sync::{Arc, Mutex}; + +use craft_color::{ColorInfo, Matrix, Range}; +use craft_frame::{Chroma, PixelData}; +use craft_media::ByteSource; +use craft_media_source::y4m::{Y4mSource, sniff}; +use craft_media_source::{DEFAULT_MAX_MEDIA_BYTES, FrameRequest, MediaError, MediaKind, MediaSource, SharedBytes}; +use craft_time::{FrameRate, Tick}; + +type TestResult = std::result::Result>; + +struct Tracked { + prefix: Vec, + length: u64, + fail_at: Option, + shrink_after: Option<(usize, u64)>, + reads: Mutex>, +} + +impl Tracked { + fn new(bytes: Vec, length: u64) -> Arc { + Arc::new(Self { prefix: bytes, length, fail_at: None, shrink_after: None, reads: Mutex::new(Vec::new()) }) + } + + fn take_reads(&self) -> Vec<(u64, usize)> { + std::mem::take(&mut *self.reads.lock().unwrap_or_else(std::sync::PoisonError::into_inner)) + } +} + +impl ByteSource for Tracked { + fn len(&self) -> u64 { + if let Some((reads, length)) = self.shrink_after + && self.reads.lock().unwrap_or_else(std::sync::PoisonError::into_inner).len() >= reads + { + return length; + } + self.length + } + + fn read_at(&self, offset: u64, out: &mut [u8]) -> io::Result<()> { + self.reads.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((offset, out.len())); + if self.fail_at.is_some_and(|at| offset <= at && at < offset.saturating_add(out.len() as u64)) { + return Err(io::Error::other("injected second Y4M delimiter read failure")); + } + let start = usize::try_from(offset).map_err(io::Error::other)?; + let available = self.prefix.get(start..).unwrap_or_default(); + let n = out.len().min(available.len()); + out[..n].copy_from_slice(&available[..n]); + out[n..].fill(0); + Ok(()) + } +} + +#[test] +fn plays_exact_odd_10_bit_frames_on_cfr_boundaries() -> TestResult<()> { + // Original deterministic Y4M: 3x3 luma and two 2x2 chroma planes, independently authored. + let first = [64u16, 65, 66, 67, 68, 69, 70, 71, 72, 401, 402, 403, 404, 601, 602, 603, 604]; + let second = [721u16, 722, 723, 724, 725, 726, 727, 728, 729, 801, 802, 803, 804, 201, 202, 203, 204]; + let mut bytes = b"YUV4MPEG2 W3 H3 F30000:1001 A4:3 C420p10 XCOLORRANGE=FULL\nFRAME\n".to_vec(); + let at_first = bytes.len() as u64; + bytes.extend(first.into_iter().flat_map(u16::to_le_bytes)); + bytes.extend_from_slice(b"FRAME Xtest\n"); + let at_second = bytes.len() as u64; + bytes.extend(second.into_iter().flat_map(u16::to_le_bytes)); + bytes.extend_from_slice(b"FRAME\n\x01\x02"); + let length = bytes.len() as u64; + let reader = Tracked::new(bytes, length); + let input: SharedBytes = reader.clone(); + let source = Y4mSource::open("odd.y4m", input)?; + let info = source.info(); + let video = info.video.as_ref().ok_or("expected Y4M video")?; + let period = Tick(8_475_667_200); + let color = ColorInfo { matrix: Matrix::Bt601, range: Range::Full, ..ColorInfo::REC709 }; + assert_eq!((info.kind, info.duration, info.file_size), (MediaKind::Movie, Tick(2 * period.0), Some(length))); + assert_eq!(info.container, "Y4M"); + assert!(info.start_timecode.is_none() && !info.has_audio()); + assert!(matches!(source.audio(0, 2, 48_000), Err(MediaError::NoStream("audio")))); + assert_eq!((video.width, video.height, video.par), (3, 3, (4, 3))); + assert_eq!((video.frame_rate, video.color), (FrameRate::new(30_000, 1_001), color)); + assert_eq!(video.codec, "Uncompressed YUV"); + assert!(!video.has_alpha); + + assert!(reader.take_reads().into_iter().all(|(_, len)| len <= 128)); + for (ask, pts, offset, expected) in [ + (Tick(-1), Tick::ZERO, at_first, first), + (Tick(period.0 - 1), Tick::ZERO, at_first, first), + (period, period, at_second, second), + (Tick(3 * period.0), period, at_second, second), + (Tick::ZERO, Tick::ZERO, at_first, first), + ] { + let frame = source.video_frame(FrameRequest { time: ask, scale: 0.5 })?; + assert_eq!((frame.pts, frame.par, frame.color, frame.width, frame.height), (pts, (4, 3), color, 3, 3)); + let PixelData::Yuv16 { planes, chroma, bits, alpha } = &frame.data else { + return Err("expected YUV16, not a converted RGB frame".into()); + }; + assert_eq!((*chroma, *bits, alpha.is_none()), (Chroma::C420, 10, true)); + assert_eq!(planes.each_ref().map(|plane| plane.as_slice()), [&expected[..9], &expected[9..13], &expected[13..]]); + assert_eq!(reader.take_reads(), vec![(offset, 34)]); + } + Ok(()) +} + +#[test] +fn defaults_and_special_planes_remain_distinct() -> TestResult<()> { + let cases = [ + (b"YUV4MPEG2 W1 H1 Cmono\nFRAME\n\x31".as_slice(), Chroma::C420, [0x31, 128, 128], None), + (b"YUV4MPEG2 W1 H1 C444alpha\nFRAME\n\x45\x67\x89\xab".as_slice(), Chroma::C444, [0x45, 0x67, 0x89], Some(0xab)), + ]; + for (bytes, expected_chroma, expected, expected_alpha) in cases { + let memory: Arc<[u8]> = bytes.into(); + let source = Y4mSource::open("one.y4m", Arc::new(memory))?; + let video = source.info().video.as_ref().ok_or("expected Y4M video")?; + assert_eq!((source.info().duration, video.frame_rate, video.par), (Tick::from_units(1, 25), FrameRate::FPS_25, (1, 1))); + assert_eq!(video.color.range, Range::Limited); + assert_eq!(video.has_alpha, expected_alpha.is_some()); + let frame = source.video_frame(FrameRequest::full(Tick::ZERO))?; + let PixelData::Yuv8 { planes, chroma, alpha } = &frame.data else { + return Err("expected YUV8".into()); + }; + assert_eq!(*chroma, expected_chroma); + assert_eq!(planes.each_ref().map(|plane| plane.as_slice()), expected.each_ref().map(std::slice::from_ref)); + assert_eq!(alpha.as_ref().map(|plane| plane.as_slice()), expected_alpha.as_ref().map(std::slice::from_ref)); + } + Ok(()) +} + +#[test] +fn declines_unknown_and_oversize_without_reading_payloads() { + assert!(!sniff(b"YUV4MPEG2x")); + let unknown: Arc<[u8]> = b"YUV4MPEG2 W2 H2 C411\nFRAME\n".as_slice().into(); + assert!(sniff(&unknown)); + assert!(matches!(Y4mSource::open("unknown.y4m", Arc::new(unknown)), Err(MediaError::Unsupported(_)))); + + // 2^26 pixels, 6 bytes per pixel: within the parser's pixel limit, but above the + // source's byte-allocation ceiling. Model the payload length; allocate only its header. + let prefix = b"YUV4MPEG2 W8192 H8192 C444p16\nFRAME\n".to_vec(); + let frame_bytes = 8192u64 * 8192 * 6; + assert!(frame_bytes > DEFAULT_MAX_MEDIA_BYTES as u64); + let length = prefix.len() as u64 + frame_bytes; + let reader = Tracked::new(prefix, length); + let input: SharedBytes = reader.clone(); + assert!(matches!(Y4mSource::open("large.y4m", input), Err(MediaError::Unsupported(_)))); + let reads = reader.take_reads(); + assert!(!reads.is_empty() && reads.into_iter().all(|(_, len)| len <= 128)); +} + +fn sparse_mono_pair() -> (Vec, u64, u64, u64) { + let header = b"YUV4MPEG2 W16 H16 Cmono\n"; + let mut prefix = header.to_vec(); + prefix.extend_from_slice(b"FRAME\n"); + prefix.resize(prefix.len() + 256, 0); + let at_second = prefix.len() as u64; + prefix.extend_from_slice(b"FRAME\n"); + let length = prefix.len() as u64 + 256; + (prefix, header.len() as u64, at_second, length) +} + +#[test] +fn index_preserves_second_frame_delimiter_io_error() -> TestResult<()> { + let (prefix, first, second, length) = sparse_mono_pair(); + // Only the read starting at the second delimiter fails; the payload was in bounds. + let reader = Arc::new(Tracked { prefix, length, fail_at: Some(second), shrink_after: None, reads: Mutex::new(Vec::new()) }); + let input: SharedBytes = reader.clone(); + let result = Y4mSource::open("unreadable.y4m", input); + assert_eq!(reader.take_reads(), vec![(0, 128), (first, 128), (second, 128)]); + let Err(MediaError::Io(message)) = result else { + return Err("a second delimiter read failure must not silently shorten the video".into()); + }; + assert!(message.contains("injected second Y4M delimiter read failure")); + Ok(()) +} + +#[test] +fn index_reports_short_read_when_source_shrinks_mid_open() -> TestResult<()> { + let (prefix, first, second, length) = sparse_mono_pair(); + // The opener and the first two range reads see the original extent. The allocator + // observes the shrink on the next range, just two bytes into the second delimiter. + let reader = Arc::new(Tracked { prefix, length, fail_at: None, shrink_after: Some((2, second + 2)), reads: Mutex::new(Vec::new()) }); + let input: SharedBytes = reader.clone(); + let result = Y4mSource::open("shrunk.y4m", input); + assert_eq!(reader.take_reads(), vec![(0, 128), (first, 128), (second, 2)]); + let Err(MediaError::Io(message)) = result else { + return Err("a short read from a changing source must not silently shorten the video".into()); + }; + assert!(message.contains("short read while indexing Y4M")); + Ok(()) +} + +#[test] +fn nonintegral_tick_pts_selects_the_frame_it_labels() -> TestResult<()> { + let bytes: Arc<[u8]> = b"YUV4MPEG2 W1 H1 F31:1 Cmono\nFRAME\n\x11FRAME\n\x22".as_slice().into(); + let source = Y4mSource::open("fractional-ticks.y4m", Arc::new(bytes))?; + let second_tick = Tick(8_194_064_517); + assert_eq!(source.info().duration, Tick(16_388_129_033)); + for (ask, pts, luma) in [(Tick(second_tick.0 - 1), Tick::ZERO, 0x11), (second_tick, second_tick, 0x22)] { + let frame = source.video_frame(FrameRequest::full(ask))?; + let PixelData::Yuv8 { planes, .. } = &frame.data else { + return Err("expected YUV8".into()); + }; + assert_eq!(frame.pts, pts); + assert_eq!(planes[0].as_slice(), &[luma]); + } + Ok(()) +} diff --git a/crates/media/src/avi/framed_audio.rs b/crates/media/src/avi/framed_audio.rs new file mode 100644 index 0000000000..189495ed62 --- /dev/null +++ b/crates/media/src/avi/framed_audio.rs @@ -0,0 +1,211 @@ +//! AVI audio chunk boundaries need not match MPEG audio or AC-3 frame boundaries. + +use std::io; + +use super::{ByteSource, Chunk, Error, Result}; +use crate::mpegts::{Codec, FrameInfo, frame_bytes, frame_info}; + +// Indexed chunks can refer to the same file bytes repeatedly. Bound even +// the concatenated length, before making any reads through that index. +const MAX_SCAN_BYTES: u64 = 256 << 20; +const WINDOW: usize = 16 << 10; +const HEADER: usize = 8; + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +struct Position { + chunk: usize, + offset: u32, +} + +impl Position { + fn take(&mut self, chunks: &[Chunk], count: usize) -> Option<(u64, usize)> { + while let Some(chunk) = chunks.get(self.chunk) { + if self.offset < chunk.size { + let start = chunk.offset.checked_add(u64::from(self.offset))?; + let len = count.min((chunk.size - self.offset) as usize); + self.offset += len as u32; + return Some((start, len)); + } + self.chunk += 1; + self.offset = 0; + } + None + } + + fn skip(&mut self, chunks: &[Chunk], mut count: usize) -> Result<()> { + while count != 0 { + let (_, len) = self.take(chunks, count).ok_or_else(short_range)?; + count -= len; + } + Ok(()) + } + + fn read(mut self, source: &(impl ByteSource + ?Sized), chunks: &[Chunk], mut dst: &mut [u8]) -> Result<()> { + while !dst.is_empty() { + let (offset, len) = self.take(chunks, dst.len()).ok_or_else(short_range)?; + let (current, rest) = dst.split_at_mut(len); + source.read_at(offset, current)?; + dst = rest; + } + Ok(()) + } +} + +fn short_range() -> Error { + Error::Io(io::ErrorKind::UnexpectedEof.into()) +} + +/// A complete compressed audio packet in the logical concatenation of an AVI stream's chunks. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct FramedAudioPacket { + start: Position, + len: usize, + /// Sample information from the frame header, when it was readable. + pub info: Option, +} + +impl FramedAudioPacket { + /// Read exactly the packet bytes using the same chunk table used to find the packet. + pub fn read(self, source: &(impl ByteSource + ?Sized), chunks: &[Chunk]) -> Result> { + let mut bytes = Vec::new(); + bytes.try_reserve_exact(self.len).map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?; + bytes.resize(self.len, 0); + self.start.read(source, chunks, &mut bytes)?; + Ok(bytes) + } +} + +/// Walk MPEG audio or AC-3 packets across the chunks of one AVI audio stream. +/// +/// The iterator uses a fixed-size window and leaves packet index storage to +/// the caller. It skips unrecognized bytes, omits incomplete frames and +/// stops after reporting a source read error. The scan admits at most four +/// times the source size in logical chunks, with a 256 MiB ceiling. +pub fn framed_audio_packets<'a>( + source: &'a (impl ByteSource + ?Sized), + chunks: &'a [Chunk], + codec: &'a Codec, +) -> Result> + 'a> { + if !matches!(codec, Codec::MpegAudio | Codec::Ac3 | Codec::Eac3) { + return Err(Error::Invalid("unsupported framed AVI audio codec".into())); + } + let budget = source.len().saturating_mul(4).min(MAX_SCAN_BYTES) as usize; + let total = chunks + .iter() + .try_fold(0usize, |sum, chunk| sum.checked_add(chunk.size as usize).filter(|&n| n <= budget)) + .ok_or_else(|| Error::Invalid("AVI framed audio exceeds the scan budget".into()))?; + let mut window = [0; WINDOW]; + let (mut base, mut len, mut pos) = (0usize, 0usize, 0usize); + let mut cursor = Position::default(); + + Ok(std::iter::from_fn(move || { + while pos < total { + let want = HEADER.min(total - pos); + let have = (base + len).saturating_sub(pos); + if have < want { + // Retain a partial header before loading the next window, so + // no chunk bytes are read twice during the scan. + window.copy_within(len - have..len, 0); + base = pos; + len = WINDOW.min(total - pos); + let mut reader = cursor; + if let Err(error) = reader.skip(chunks, have).and_then(|()| reader.read(source, chunks, &mut window[have..len])) { + pos = total; + return Some(Err(error)); + } + } + let head = &window[pos - base..pos - base + want]; + let packet = frame_bytes(codec, head).filter(|&size| size > 0 && size <= total - pos).map(|size| FramedAudioPacket { + start: cursor, + len: size, + info: frame_info(codec, head), + }); + let advance = packet.map_or(1, |packet| packet.len); + if let Err(error) = cursor.skip(chunks, advance) { + pos = total; + return Some(Err(error)); + } + pos += advance; + if let Some(packet) = packet { + return Some(Ok(packet)); + } + } + None + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + struct Source { + bytes: Vec, + read: Cell, + } + + impl ByteSource for Source { + fn len(&self) -> u64 { + self.bytes.len() as u64 + } + + fn read_at(&self, offset: u64, out: &mut [u8]) -> io::Result<()> { + self.read.set(self.read.get() + out.len()); + self.bytes.read_at(offset, out) + } + } + + fn interleave_padding(logical: &[u8], lengths: &[usize]) -> (Source, Vec) { + let mut chunks = Vec::new(); + let mut bytes = Vec::new(); + let mut pos = 0; + for length in lengths.iter().copied().chain(std::iter::once(logical.len())) { + let count = length.min(logical.len() - pos); + chunks.push(Chunk { offset: bytes.len() as u64, size: count as u32, key: true }); + bytes.extend_from_slice(&logical[pos..pos + count]); + bytes.push(0xff); // Bytes between the AVI chunks must not enter the stream. + pos += count; + } + (Source { bytes, read: Cell::new(0) }, chunks) + } + + #[test] + fn split_mpeg_header_and_packet_match_the_original_bytes() { + // Original frame framing, with 128 kb/s Layer III at 48 kHz. + let mut packet = vec![0x12; 384]; + packet[..4].copy_from_slice(&[0xff, 0xfb, 0x94, 0xc0]); + let mut logical = vec![0x22; WINDOW - 3]; + logical.extend_from_slice(&packet); + logical.extend_from_slice(&packet); + logical.extend_from_slice(&packet[..20]); // Incomplete last frame. + let (source, chunks) = interleave_padding(&logical, &[WINDOW - 2, 0, 1, 19, 128]); + let found = framed_audio_packets(&source, &chunks, &Codec::MpegAudio).unwrap().collect::>>().unwrap(); + assert_eq!(source.read.get(), logical.len(), "the small window never rereads bytes"); + assert_eq!(found.len(), 2); + for frame in found { + assert_eq!(frame.info.unwrap().samples, 1152); + assert_eq!(frame.read(&source, &chunks).unwrap(), packet); + } + } + + #[test] + fn ac3_frame_spans_separate_chunks() { + // Original AC-3 test header for a 128-byte, 48 kHz stereo frame. + let mut packet = vec![0; 128]; + packet[..8].copy_from_slice(&[0x0b, 0x77, 0, 0, 0, 0x40, 0x40, 0]); + let (source, chunks) = interleave_padding(&packet, &[1, 6, 2]); + let mut scan = framed_audio_packets(&source, &chunks, &Codec::Ac3).unwrap(); + let frame = scan.next().unwrap().unwrap(); + assert_eq!(frame.info.map(|info| (info.sample_rate, info.channels, info.samples)), Some((48_000, 2, 1536))); + assert_eq!(frame.read(&source, &chunks).unwrap(), packet); + assert!(scan.next().is_none()); + } + + #[test] + fn repeated_index_ranges_cannot_expand_the_scan_budget() { + let source = Source { bytes: vec![0; 64], read: Cell::new(0) }; + let chunks = [Chunk { offset: 0, size: 64, key: true }; 5]; + assert!(matches!(framed_audio_packets(&source, &chunks, &Codec::MpegAudio), Err(Error::Invalid(_)))); + assert_eq!(source.read.get(), 0); + } +} diff --git a/crates/media/src/avi/mod.rs b/crates/media/src/avi/mod.rs index 69e9197058..d813063d30 100644 --- a/crates/media/src/avi/mod.rs +++ b/crates/media/src/avi/mod.rs @@ -18,12 +18,16 @@ #![warn(missing_docs)] +#[cfg(feature = "mpegts")] +mod framed_audio; mod mux; #[cfg(test)] mod mux_tests; #[cfg(test)] mod tests; +#[cfg(feature = "mpegts")] +pub use framed_audio::{FramedAudioPacket, framed_audio_packets}; pub use mux::{AudioSpec, AudioTiming, AviWriter, MuxOptions, StreamSpec, VideoSpec}; pub use crate::source::{ByteSource, ReadSeekSource}; diff --git a/crates/media/src/isobmff/mod.rs b/crates/media/src/isobmff/mod.rs index 142a606d6e..83897d0c0b 100644 --- a/crates/media/src/isobmff/mod.rs +++ b/crates/media/src/isobmff/mod.rs @@ -18,6 +18,7 @@ mod config_fields; mod demux; mod error; mod mux; +mod rtmd; pub use crate::source::{ByteSource, ReadSeekSource}; pub use bytes::FourCc; @@ -30,3 +31,4 @@ pub use config_fields::{avcc_length_size, dac3_layout, dec3_layout, esds_object_ pub use demux::{Edit, Metadata, Mp4File, Sample, SampleGroup, Track, TrackKind, open}; pub use error::{Error, Result}; pub use mux::{Brand, FragmentedWriter, Mp4Writer, TrackConfig, WriteSample, WriterOptions}; +pub use rtmd::{SONY_RTMD_TIMECODE_PREFIX_LEN, SonyRtmdTimecode, parse_sony_rtmd_timecode}; diff --git a/crates/media/src/isobmff/rtmd.rs b/crates/media/src/isobmff/rtmd.rs new file mode 100644 index 0000000000..f8ed30bbd8 --- /dev/null +++ b/crates/media/src/isobmff/rtmd.rs @@ -0,0 +1,81 @@ +//! Sony XAVC timed metadata's recorded-timecode fields. +//! +//! Wire layout and accepted labels follow the existing Craft implementation in FilmCraft +//! (crates/codecs/src/mp4.rs and its synthetic mp4_rtmd integration tests, revision 3f137a7e). +//! This parser does not choose a sample or determine a track's presentation origin. + +/// Bytes needed from the start of a Sony real-time metadata sample. +pub const SONY_RTMD_TIMECODE_PREFIX_LEN: usize = 18; + +/// A Sony real-time metadata timecode label, before conversion to a frame count. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SonyRtmdTimecode { + /// Hour within the day. + pub hours: u8, + /// Minute within the hour. + pub minutes: u8, + /// Second within the minute. + pub seconds: u8, + /// Frame label within the second. + pub frames: u8, + /// Whether the sample signals drop-frame numbering. + pub drop_frame: bool, +} + +/// Read the recorded label from a Sony `rtmd` sample prefix. +/// +/// `frame_base` is the nominal integer frame count per second for the associated video; +/// `supports_drop_frame` says whether its rate supports drop-frame numbering. Preserve the +/// recorded flag even for a rate that does not support it. Reject skipped labels only when +/// drop-frame numbering applies; choosing a timeline origin is the caller's responsibility. +pub fn parse_sony_rtmd_timecode(prefix: &[u8], frame_base: u32, supports_drop_frame: bool) -> Option { + let &[hours, minutes, seconds, flag, frames] = prefix.get(13..SONY_RTMD_TIMECODE_PREFIX_LEN)? else { return None }; + let drop_frame = flag != 0; + if hours >= 24 || minutes >= 60 || seconds >= 60 || u32::from(frames) >= frame_base { + return None; + } + if drop_frame && supports_drop_frame && seconds == 0 && !minutes.is_multiple_of(10) && u32::from(frames) < frame_base / 15 { + return None; + } + Some(SonyRtmdTimecode { hours, minutes, seconds, frames, drop_frame }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sony_rtmd_parses_only_the_fixed_prefix() { + let mut prefix = [0u8; SONY_RTMD_TIMECODE_PREFIX_LEN + 1]; + prefix[13..18].copy_from_slice(&[3, 37, 12, 0, 34]); + prefix[18] = 255; + let expected = Some(SonyRtmdTimecode { hours: 3, minutes: 37, seconds: 12, frames: 34, drop_frame: false }); + assert_eq!(parse_sony_rtmd_timecode(&prefix[..17], 60, true), None); + assert_eq!(parse_sony_rtmd_timecode(&prefix[..18], 60, true), expected); + assert_eq!(parse_sony_rtmd_timecode(&prefix, 60, true), expected); + } + + #[test] + fn sony_rtmd_rejects_out_of_range_labels() { + for (index, value) in [(13, 24), (14, 60), (15, 60), (17, 24)] { + let mut prefix = [0; 18]; + prefix[index] = value; + assert_eq!(parse_sony_rtmd_timecode(&prefix, 24, false), None); + } + assert_eq!(parse_sony_rtmd_timecode(&[0; 18], 0, false), None); + } + + #[test] + fn sony_rtmd_drop_frame_labels_follow_the_rate() { + let mut prefix = [0; 18]; + // Any nonzero flag is retained. At 59.94 the first four labels at minute one are skipped. + prefix[13..18].copy_from_slice(&[0, 1, 0, 2, 3]); + assert_eq!(parse_sony_rtmd_timecode(&prefix, 60, true), None); + assert!(parse_sony_rtmd_timecode(&prefix, 24, false).is_some_and(|code| code.drop_frame)); + prefix[17] = 4; + assert!(parse_sony_rtmd_timecode(&prefix, 60, true).is_some_and(|code| code.frames == 4 && code.drop_frame)); + prefix[14] = 10; + prefix[17] = 0; + assert!(parse_sony_rtmd_timecode(&prefix, 60, true).is_some_and(|code| code.frames == 0)); + } +} diff --git a/crates/metafile/src/canvas.rs b/crates/metafile/src/canvas.rs index 34e36e0a7c..acb09bcad8 100644 --- a/crates/metafile/src/canvas.rs +++ b/crates/metafile/src/canvas.rs @@ -306,7 +306,7 @@ pub(crate) enum Raw { } impl Raw { - fn set_region(&mut self, region: RawClip) { + pub(crate) fn set_region(&mut self, region: RawClip) { match self { Raw::Path { region: slot, .. } | Raw::Pattern { region: slot, .. } diff --git a/crates/metafile/src/emf.rs b/crates/metafile/src/emf.rs index 39aff6d057..929a2b5fa3 100644 --- a/crates/metafile/src/emf.rs +++ b/crates/metafile/src/emf.rs @@ -30,7 +30,7 @@ pub(crate) fn is_emf(b: Bytes) -> bool { /// The picture frame: `rclFrame` (0.01 mm) mapped to device units through `szlDevice` and /// `szlMillimeters`, sized in points. Without a usable frame, the device bounds stand in (1 unit = 1 point). -pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { +pub(crate) fn parse(input: Bytes, depth: u8) -> Result<(Canvas, Option), Error> { if !is_emf(input) { return Err(Error::BadHeader); } @@ -45,7 +45,7 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { if let Some(px_mm) = device_px_per_mm(input) { cv.set_device_mm(px_mm); } - let mut plus = crate::emfplus::Plus::new(); + let mut plus = crate::emfplus::Plus::new(depth); plus.frame = frame.as_ref().map(|f| f.rect); let mut parsed = 0usize; let mut pos = hsize.max(88); @@ -77,22 +77,15 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { } /// Device pixels per millimetre on each axis, from `szlDevice` (72) and the device's size: -/// `szlMicrometers` (100) when the header has that extension (a header of 108 bytes or more) and +/// `szlMicrometers` (100) when the fixed header includes that extension and /// it is set, which is a thousand times finer, else `szlMillimeters` (80). fn device_px_per_mm(input: Bytes) -> Option<(f64, f64)> { - let (dw, dh) = (input.i32(72)?, input.i32(76)?); - if dw <= 0 || dh <= 0 { - return None; - } - if input.u32(4)? >= 108 - && let (Some(uw), Some(uh)) = (input.u32(100), input.u32(104)) - && uw > 0 - && uh > 0 - { - return Some((f64::from(dw) * 1000.0 / f64::from(uw), f64::from(dh) * 1000.0 / f64::from(uh))); - } - let (mw, mh) = (input.i32(80)?, input.i32(84)?); - (mw > 0 && mh > 0).then(|| (f64::from(dw) / f64::from(mw), f64::from(dh) / f64::from(mh))) + let facts = crate::units::emf_device(input)?; + let (dw, dh) = (f64::from(facts.pixels.0), f64::from(facts.pixels.1)); + Some(match facts.physical_size { + crate::EmfPhysicalSize::Micrometres(w, h) => (dw * 1000.0 / f64::from(w), dh * 1000.0 / f64::from(h)), + crate::EmfPhysicalSize::Millimetres(w, h) => (dw / f64::from(w), dh / f64::from(h)), + }) } /// The frame from `rclFrame` (offset 24), `szlDevice` (72) and `szlMillimeters` (80) in the header. diff --git a/crates/metafile/src/emfplus.rs b/crates/metafile/src/emfplus.rs index 505149371f..f507924bcc 100644 --- a/crates/metafile/src/emfplus.rs +++ b/crates/metafile/src/emfplus.rs @@ -178,13 +178,9 @@ enum ImageData { Meta(Picture), } -thread_local! { - /// Nesting depth of metafile images being parsed, so a file of nested metafiles cannot run - /// the stack out. - static NESTING: std::cell::Cell = const { std::cell::Cell::new(0) }; -} /// Metafile images inside metafile images, at most. -pub(crate) const MAX_NESTING: usize = 3; +#[cfg(test)] +pub(crate) const MAX_NESTING: usize = crate::MAX_NESTED_DEPTH as usize; #[derive(Clone)] enum Obj { @@ -241,12 +237,14 @@ pub(crate) struct Plus { object_bytes: usize, stack: Vec, partial: Option, + /// Nesting depth of the outer metafile being played. + depth: u8, /// The picture frame in device units (`[x, y, w, h]`), what Clear paints. pub frame: Option<[f64; 4]>, } impl Plus { - pub fn new() -> Self { + pub fn new(depth: u8) -> Self { Plus { dual: false, gdi: false, @@ -260,6 +258,7 @@ impl Plus { object_bytes: 0, stack: Vec::new(), partial: None, + depth, frame: None, } } @@ -645,7 +644,7 @@ impl Plus { let room = p.total.saturating_sub(p.data.len()); p.data.extend_from_slice(&chunk[..chunk.len().min(room)]); if p.data.len() >= p.total { - let obj = parse_object(p.kind, Bytes(&p.data)); + let obj = parse_object(p.kind, Bytes(&p.data), self.depth); self.store(p.id, obj, canvas_used); } else { self.partial = Some(p); @@ -659,11 +658,11 @@ impl Plus { { let room = p.total.saturating_sub(p.data.len()); p.data.extend_from_slice(&r.0[..r.0.len().min(room)]); - let obj = parse_object(kind, Bytes(&p.data)); + let obj = parse_object(kind, Bytes(&p.data), self.depth); self.store(id, obj, canvas_used); return Some(()); } - let obj = parse_object(kind, r); + let obj = parse_object(kind, r, self.depth); self.store(id, obj, canvas_used); Some(()) } @@ -1074,13 +1073,13 @@ fn matrix(r: Bytes, off: usize) -> Option { floats::<6>(r, off) } -fn parse_object(kind: u16, r: Bytes) -> Option { +fn parse_object(kind: u16, r: Bytes, depth: u8) -> Option { match kind { 1 => brush(r, 0).map(Obj::Brush).or_else(|| lost_texture(r).then_some(Obj::LostBrush)), 2 => pen(r), 3 => path(r).map(Obj::Path), 4 => region(r), - 5 => Some(image(r).map_or_else(|| Obj::LostImage(bitmap_size(r)), |i| Obj::Image(Arc::new(i)))), + 5 => Some(image(r, depth).map_or_else(|| Obj::LostImage(bitmap_size(r)), |i| Obj::Image(Arc::new(i)))), 6 => font(r), 7 => Some(Obj::Format(Format { flags: r.u32(4)?, align: r.u32(12)?, line_align: r.u32(16)? })), _ => None, @@ -1097,7 +1096,7 @@ fn brush(r: Bytes, off: usize) -> Option { let bflags = d.u32(0)?; let wrap = d.u32(4)?; let (xf, off) = if bflags & 0x2 != 0 { (matrix(d, 8)?, 32) } else { (IDENTITY, 8) }; - let ImageData::Bitmap(img) = image(d.tail(off)?)? else { return None }; + let ImageData::Bitmap(img) = image(d.tail(off)?, crate::MAX_NESTED_DEPTH)? else { return None }; Some(Fill::Texture { img: Arc::new(img), wrap, xf }) } 3 => path_gradient(d), @@ -1447,26 +1446,22 @@ fn font(r: Bytes) -> Option { /// An image object: a bitmap of raw pixels or a compressed (PNG, JPEG, GIF…) file, or a nested /// metafile. -fn image(r: Bytes) -> Option { +fn image(r: Bytes, depth: u8) -> Option { match r.u32(4)? { 1 => bitmap(r).map(ImageData::Bitmap), - 2 => metafile(r).map(ImageData::Meta), + 2 => metafile(r, depth).map(ImageData::Meta), _ => None, } } /// A metafile image: type, size, then a WMF (placeable or not) or EMF file, parsed as a picture. -fn metafile(r: Bytes) -> Option { +fn metafile(r: Bytes, depth: u8) -> Option { let size = r.u32(12)? as usize; let data = r.slice(16, size).or_else(|| r.tail(16).map(|t| t.0))?; - let depth = NESTING.with(std::cell::Cell::get); - if depth >= MAX_NESTING { + if depth >= crate::MAX_NESTED_DEPTH { return None; } - NESTING.with(|n| n.set(depth + 1)); - let pic = crate::parse_nested(data).ok(); - NESTING.with(|n| n.set(depth)); - pic + crate::parse_nested(data, depth + 1).ok() } /// The size in pixels of a bitmap image object, read from its header (a compressed one's from the @@ -1820,7 +1815,7 @@ mod cost_tests { #[test] fn an_object_is_not_stored_past_what_the_canvas_already_holds() { - let mut plus = Plus::new(); + let mut plus = Plus::new(0); let path = || Some(Obj::Path(vec![Op::Z; 1000])); plus.store(0, path(), crate::MAX_BYTES - 100); assert!(plus.objects[0].is_none() && plus.object_bytes == 0); @@ -1830,7 +1825,7 @@ mod cost_tests { #[test] fn an_image_or_texture_past_the_byte_budget_is_counted() { - let (mut plus, mut cv) = (Plus::new(), Canvas::new()); + let (mut plus, mut cv) = (Plus::new(0), Canvas::new()); let img = || Rgba { w: 4, h: 4, px: vec![0; 64] }; plus.store(0, Some(Obj::Image(Arc::new(ImageData::Bitmap(img())))), crate::MAX_BYTES); assert!(matches!(plus.objects[0], Some(Obj::LostImage(Some((4, 4)))))); @@ -1854,7 +1849,7 @@ mod cost_tests { #[test] fn pieces_of_a_continued_object_count_against_the_shared_budget() { - let (mut plus, mut cv) = (Plus::new(), Canvas::new()); + let (mut plus, mut cv) = (Plus::new(0), Canvas::new()); // Image object (kind 5), id 0, continued: 1000 bytes announced, 100 delivered. let mut rec = 1000u32.to_le_bytes().to_vec(); rec.extend([0u8; 100]); @@ -1864,7 +1859,7 @@ mod cost_tests { #[test] fn current_and_saved_clips_count_against_the_shared_budget() { - let (mut plus, mut cv) = (Plus::new(), Canvas::new()); + let (mut plus, mut cv) = (Plus::new(0), Canvas::new()); let pts = vec![(0.0, 0.0); 1000]; plus.clip = Some(pts.clone()); plus.stack.push(Saved { id: 1, world: IDENTITY, page: 1.0, clip: Some(pts) }); diff --git a/crates/metafile/src/eof.rs b/crates/metafile/src/eof.rs new file mode 100644 index 0000000000..965360391e --- /dev/null +++ b/crates/metafile/src/eof.rs @@ -0,0 +1,79 @@ +use crate::Kind; +const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; + +/// Whether the stream stops before an EOF record header is recognizable. +/// +/// This is a diagnostic, not validation: a recognizable EOF header ends +/// the scan even if its payload is incomplete. A parser's resource-limit +/// status is independent of this result. +pub fn ends_early(bytes: &[u8], kind: Kind) -> bool { + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let mut at = match kind { + Kind::Emf => 0, + Kind::Wmf => { + let start = if u32_at(0) == Some(PLACEABLE_KEY) { 22 } else { 0 }; + let Some(words) = u16_at(start + 2) else { return true }; + start + usize::from(words) * 2 + } + }; + loop { + let size = match kind { + Kind::Emf => { + let (Some(kind), Some(size)) = (u32_at(at), u32_at(at.saturating_add(4))) else { return true }; + if kind == 14 { + return false; + } + // Records are a multiple of 4 bytes long; reading stops at one that isn't. + if !size.is_multiple_of(4) { + return true; + } + size as usize + } + Kind::Wmf => { + let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) else { return true }; + if function == 0 { + return false; + } + (words as usize).saturating_mul(2) + } + }; + if size < 6 { + return true; + } + at = at.saturating_add(size); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn emf_eof_header_is_enough_but_other_records_need_aligned_lengths() { + let mut bytes = [1u32, 8, 14, 20].into_iter().flat_map(u32::to_le_bytes).collect::>(); + assert!(!ends_early(&bytes, Kind::Emf)); + assert!(ends_early(&bytes[..12], Kind::Emf)); + bytes[4] = 9; + assert!(ends_early(&bytes, Kind::Emf)); + bytes[4] = 40; + assert!(ends_early(&bytes, Kind::Emf)); + } + + #[test] + fn wmf_eof_follows_standard_and_placeable_headers() { + for prefix in [0usize, 22] { + let mut bytes = vec![0u8; prefix + 18]; + if prefix == 22 { + bytes[..4].copy_from_slice(&PLACEABLE_KEY.to_le_bytes()); + } + bytes[prefix + 2] = 9; + bytes.extend_from_slice(&[5, 0, 0, 0, 0, 0]); + assert!(!ends_early(&bytes, Kind::Wmf)); + assert!(ends_early(&bytes[..bytes.len() - 1], Kind::Wmf)); + let function = bytes.len() - 2; + bytes[function] = 1; + assert!(ends_early(&bytes, Kind::Wmf)); + } + } +} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 26a406d312..a8732562a9 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -26,10 +26,13 @@ mod cliprect; mod dib; mod emf; mod emfplus; +mod eof; mod geom; +pub mod pict; mod place; mod size; mod text; +mod units; mod wmf; #[cfg(feature = "write")] @@ -43,10 +46,13 @@ use std::sync::Arc; use bytes::Bytes; use canvas::Raw; +pub use eof::ends_early; use geom::{Op, P}; +pub use pict::{is_pict, parse as parse_pict}; pub use place::{MAX_BITMAP_SIDE, PlacedClip, PlacedItem, bez_path, crop_window}; pub use size::size; pub use text::{Font, HAlign, SYMBOL_CHARSET, Text, VAlign}; +pub use units::{EmfDevice, EmfPhysicalSize, UnitFacts, unit_facts}; /// Items kept from one file. Past the cap the parse stops and keeps what it has. pub(crate) const MAX_ITEMS: usize = 200_000; @@ -60,6 +66,8 @@ pub(crate) const MAX_STACK: usize = 1024; pub(crate) const MAX_PATH_OPS: usize = 2_000_000; /// Bytes of path ops and pixels kept from one file (about 256 MB). pub(crate) const MAX_BYTES: usize = 256 * 1024 * 1024; +/// Maximum metafile nesting depth (EMF+ metafile images and WMF-wrapped EMFs). +pub(crate) const MAX_NESTED_DEPTH: u8 = 3; /// A parsed metafile. Items use coordinates in `0..width` and `0..height`, y down. #[derive(Debug, Clone, PartialEq, Default)] @@ -228,6 +236,8 @@ pub enum Seg { pub enum Error { #[error("not a WMF or EMF file")] NotMetafile, + #[error("not a PICT file")] + NotPict, #[error("metafile header is truncated or invalid")] BadHeader, #[error("metafile has no readable records")] @@ -244,18 +254,43 @@ pub(crate) struct Frame { /// Parses a WMF (placeable or plain) or EMF file. pub fn parse(bytes: &[u8]) -> Result { dib::set_decode_budget(dib::MAX_DECODE_PIXELS); - parse_nested(bytes) + parse_nested(bytes, 0) } /// [`parse`] for a metafile inside the one being parsed: it draws on the same budgets. -pub(crate) fn parse_nested(bytes: &[u8]) -> Result { +pub(crate) fn parse_nested(bytes: &[u8], depth: u8) -> Result { + if depth > MAX_NESTED_DEPTH { + return Err(Error::NoRecords); + } let b = Bytes(bytes); let (cv, frame) = if emf::is_emf(b) { - emf::parse(b)? + emf::parse(b, depth)? } else if wmf::is_wmf(b) { // A WMF converted from an EMF can carry the original in MFCOMMENT escapes; Office draws - // the WMF's own records (its dx rounding shows), so the copy is not used. - wmf::parse(b)? + // the WMF's own records (its dx rounding shows), so the copy is used only when the outer + // WMF produces no drawing items of its own. + let mut parsed = wmf::parse(b)?; + if parsed.cv.items.is_empty() { + if parsed.embedded_emf_capped { + parsed.cv.truncated_inside = true; + } else if let Some(emf_bytes) = parsed.embedded_emf.as_deref() + && emf::is_emf(Bytes(emf_bytes)) + { + if depth >= MAX_NESTED_DEPTH { + parsed.cv.truncated_inside = true; + } else if let Ok(mut pic) = parse_nested(emf_bytes, depth + 1) { + pic.skipped_records = pic.skipped_records.saturating_add(parsed.cv.skipped); + pic.truncated |= parsed.cv.full() || parsed.cv.truncated_inside; + pic.dropped_images = pic.dropped_images.saturating_add(parsed.cv.dropped_images); + pic.ignored_clips = pic.ignored_clips.saturating_add(parsed.cv.ignored_clips); + pic.unplayed_raster_ops = pic.unplayed_raster_ops.saturating_add(parsed.cv.unplayed_raster_ops); + return Ok(pic); + } + } + } + (parsed.cv, parsed.frame) + } else if pict::is_pict(bytes) { + return pict::parse_nested(bytes); } else { return Err(Error::NotMetafile); }; @@ -294,7 +329,7 @@ pub fn sniff(bytes: &[u8]) -> Option { /// Maps device-space output into the picture frame. Without a usable frame the frame is the bounding /// box of the drawing, so the origin is still the top-left of what was drawn. -fn build(raw: Vec, frame: Option) -> Picture { +pub(crate) fn build(raw: Vec, frame: Option) -> Picture { let frame = frame.filter(|f| f.rect.iter().all(|v| v.is_finite()) && f.rect[2] > 0.0 && f.rect[3] > 0.0); let (rect, size) = match frame { Some(f) => (f.rect, f.size.unwrap_or((f.rect[2], f.rect[3]))), diff --git a/crates/metafile/src/pict.rs b/crates/metafile/src/pict.rs new file mode 100644 index 0000000000..41cf6653be --- /dev/null +++ b/crates/metafile/src/pict.rs @@ -0,0 +1,1481 @@ +//! QuickDraw pictures (PICT, versions 1 and 2), played into neutral metafile items by the opcodes +//! and data lengths of Apple's *Imaging With QuickDraw*, appendix A. +//! +//! A PICT file holds 512 bytes of application data before the picture; a picture on its own (as a +//! `PICT` resource holds it) reads too. A unit is a point, and the picture frame defines the drawing +//! bounds; an extended version 2 header's source rectangle is mapped onto the frame. + +use std::collections::HashMap; +use std::sync::Arc; + +use kurbo::{Affine, BezPath, PathEl, Point, Rect, Vec2}; + +use crate::canvas::{Raw, RawClip, RawTile}; +use crate::dib::Rgba; +use crate::geom::Op; +use crate::text::{Font, HAlign, Text, VAlign}; +use crate::{Cap, Error, Frame, Join, LineStyle, MAX_BYTES, MAX_ITEMS, MAX_PIXELS, Picture, clip, dib, f}; + +/// The application data before the picture in a PICT file. +const FILE_HEADER: usize = 512; +/// Most opcodes one picture plays (a small file can't keep the reader busy for minutes). +const MAX_OPS: usize = 1 << 22; +/// Most rectangles one region breaks into. +const MAX_RECTS: usize = 1 << 16; +/// Steps the regions of one picture may take to read (each inversion point and band costs some). +const MAX_REGION_WORK: u64 = 1 << 28; +/// Most bytes the unpacked rows of one image may hold. +const MAX_ROW_BYTES: u64 = 1 << 28; +/// Most bytes the unpacked rows of one picture's images and patterns may hold together. +const MAX_FILE_ROW_BYTES: u64 = 1 << 30; +/// Most bytes a row may hold past what its pixels need. +const ROW_SLACK: usize = 64; +/// Most pixels, and bytes of unpacked rows, a pixel pattern may hold. +const MAX_PATTERN_PIXELS: usize = 1 << 16; +const MAX_PATTERN_ROW_BYTES: usize = 1 << 20; +/// Curves made for ovals and arcs are this close to the true curve, points. +const TOLERANCE: f64 = 0.01; +/// Pen style flags: square and flat ends. +const SQUARE: u32 = 0x100; +const FLAT: u32 = 0x200; + +/// Big-endian reads from a slice, never past its end. +struct Be<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> Be<'a> { + fn new(data: &'a [u8], pos: usize) -> Self { + Self { data, pos } + } + fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { + let end = self.pos.checked_add(n)?; + let b = self.data.get(self.pos..end)?; + self.pos = end; + Some(b) + } + fn array(&mut self) -> Option<[u8; N]> { + let b = self.bytes(N)?; + b.try_into().ok() + } + fn skip(&mut self, n: usize) -> Option<()> { + let end = self.pos.checked_add(n)?; + if end <= self.data.len() { + self.pos = end; + Some(()) + } else { + None + } + } + fn u8(&mut self) -> Option { + self.array().map(|[b]: [u8; 1]| b) + } + fn u16(&mut self) -> Option { + self.array().map(u16::from_be_bytes) + } + fn i16(&mut self) -> Option { + self.array().map(i16::from_be_bytes) + } + fn u32(&mut self) -> Option { + self.array().map(u32::from_be_bytes) + } + fn i32(&mut self) -> Option { + self.array().map(i32::from_be_bytes) + } + fn point(&mut self) -> Option { + let v = self.i16()?; + let h = self.i16()?; + Some(Point::new(h.into(), v.into())) + } + fn size(&mut self) -> Option { + self.point().map(|p| Vec2::new(p.x, p.y)) + } + fn rect(&mut self) -> Option { + let (top, left, bottom, right) = (self.i16()?, self.i16()?, self.i16()?, self.i16()?); + Some(Rect::new(left.into(), top.into(), right.into(), bottom.into())) + } + fn rgb(&mut self) -> Option<[u8; 3]> { + let [r, g, b] = [self.u16()?, self.u16()?, self.u16()?]; + Some([r, g, b].map(|c| (c >> 8) as u8)) + } +} + +/// Where a picture is, its frame and whether it is version 2. +struct Header { + frame: Rect, + v2: bool, + ops: usize, +} + +/// The picture whose `picSize` is at `at`, if a version opcode follows its frame. +fn header(bytes: &[u8], at: usize) -> Option

{ + let mut r = Be::new(bytes, at.checked_add(2)?); + let frame = r.rect()?; + let (v2, ops) = match r.array::<2>()? { + [0x11, 0x01] => (false, r.pos), + [0x00, 0x11] if r.array::<4>()? == [0x02, 0xFF, 0x0C, 0x00] => (true, at.checked_add(10)?), + _ => return None, + }; + (frame.width() > 0.0 && frame.height() > 0.0).then_some(Header { frame, v2, ops }) +} + +/// The picture of a file (after its application data), else the picture `bytes` start with. +fn find(bytes: &[u8]) -> Option
{ + let v2_at_512 = header(bytes, FILE_HEADER).filter(|h| h.v2); + let v2_at_0 = header(bytes, 0).filter(|h| h.v2); + v2_at_512.or(v2_at_0).or_else(|| header(bytes, FILE_HEADER)).or_else(|| header(bytes, 0)) +} + +/// The size in points from the PICT header when valid. +pub(crate) fn header_size(bytes: &[u8]) -> Option<(f32, f32)> { + let h = find(bytes)?; + let w = f(h.frame.width())?; + let h = f(h.frame.height())?; + (w > 0.0 && h > 0.0).then_some((w, h)) +} + +/// Do `bytes` hold a picture, after a file's application data or on their own? +pub fn is_pict(bytes: &[u8]) -> bool { + find(bytes).is_some() +} + +#[derive(Clone, Debug)] +enum Pat { + Bits([u8; 8]), + Rgb([u8; 3]), + Tile(Arc), +} + +enum PaintChoice { + Solid([u8; 3]), + Tile(Arc), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Verb { + Frame, + Paint, + Erase, + Invert, + Fill, +} + +fn verb(op: u16) -> Option { + match op & 7 { + 0 => Some(Verb::Frame), + 1 => Some(Verb::Paint), + 2 => Some(Verb::Erase), + 3 => Some(Verb::Invert), + 4 => Some(Verb::Fill), + _ => None, + } +} + +fn old_color(c: u32) -> [u8; 3] { + match c { + 30 => [255; 3], + 69 => [255, 255, 0], + 137 => [255, 0, 255], + 205 => [255, 0, 0], + 273 => [0, 255, 255], + 341 => [0, 255, 0], + 409 => [0, 0, 255], + _ => [0; 3], + } +} + +fn mix(a: [u8; 3], b: [u8; 3], t: f64) -> [u8; 3] { + let m = |x: u8, y: u8| (f64::from(x) * t + f64::from(y) * (1.0 - t)).round() as u8; + [m(a[0], b[0]), m(a[1], b[1]), m(a[2], b[2])] +} + +fn mac_roman(b: u8) -> char { + const HIGH: [char; 128] = [ + 'Ä', 'Å', 'Ç', 'É', 'Ñ', 'Ö', 'Ü', 'á', 'à', 'â', 'ä', 'ã', 'å', 'ç', 'é', 'è', // + 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ñ', 'ó', 'ò', 'ô', 'ö', 'õ', 'ú', 'ù', 'û', 'ü', // + '†', '°', '¢', '£', '§', '•', '¶', 'ß', '®', '©', '™', '´', '¨', '≠', 'Æ', 'Ø', // + '∞', '±', '≤', '≥', '¥', 'µ', '∂', '∑', '∏', 'π', '∫', 'ª', 'º', 'Ω', 'æ', 'ø', // + '¿', '¡', '¬', '√', 'ƒ', '≈', '∆', '«', '»', '…', '\u{A0}', 'À', 'Ã', 'Õ', 'Œ', 'œ', // + '–', '—', '“', '”', '‘', '’', '÷', '◊', 'ÿ', 'Ÿ', '⁄', '€', '‹', '›', 'fi', 'fl', // + '‡', '·', '‚', '„', '‰', 'Â', 'Ê', 'Á', 'Ë', 'È', 'Í', 'Î', 'Ï', 'Ì', 'Ó', 'Ô', // + '\u{F8FF}', 'Ò', 'Ú', 'Û', 'Ù', 'ı', 'ˆ', '˜', '¯', '˘', '˙', '˚', '¸', '˝', '˛', 'ˇ', + ]; + match b { + 0x80.. => HIGH.get(usize::from(b - 0x80)).copied().unwrap_or(char::REPLACEMENT_CHARACTER), + _ => char::from(b), + } +} + +fn font_family(id: u16) -> &'static str { + match id { + 0 => "Chicago", + 1 | 3 => "Geneva", + 2 => "New York", + 4 => "Monaco", + 20 => "Times", + 21 => "Helvetica", + 22 => "Courier", + 23 => "Symbol", + _ => "", + } +} + +fn bez_to_ops(bp: &BezPath) -> Vec { + let mut ops = Vec::with_capacity(bp.elements().len()); + for el in bp.elements() { + match el { + PathEl::MoveTo(p) => ops.push(Op::M((p.x, p.y))), + PathEl::LineTo(p) => ops.push(Op::L((p.x, p.y))), + PathEl::QuadTo(p1, p2) => { + let last = match ops.last() { + Some(Op::M(p) | Op::L(p) | Op::C(_, _, p)) => *p, + _ => (0.0, 0.0), + }; + let c1 = (last.0 + 2.0 / 3.0 * (p1.x - last.0), last.1 + 2.0 / 3.0 * (p1.y - last.1)); + let c2 = (p2.x + 2.0 / 3.0 * (p1.x - p2.x), p2.y + 2.0 / 3.0 * (p1.y - p2.y)); + ops.push(Op::C(c1, c2, (p2.x, p2.y))); + } + PathEl::CurveTo(p1, p2, p3) => ops.push(Op::C((p1.x, p1.y), (p2.x, p2.y), (p3.x, p3.y))), + PathEl::ClosePath => ops.push(Op::Z), + } + } + ops +} + +fn round_rect(r: Rect, rx: f64, ry: f64) -> BezPath { + let r = Rect::new(r.x0.min(r.x1), r.y0.min(r.y1), r.x0.max(r.x1), r.y0.max(r.y1)); + let (rx, ry) = ((rx / 2.0).abs().min(r.width() / 2.0), (ry / 2.0).abs().min(r.height() / 2.0)); + if rx <= 0.0 || ry <= 0.0 { + let mut bp = BezPath::new(); + bp.move_to((r.x0, r.y0)); + bp.line_to((r.x1, r.y0)); + bp.line_to((r.x1, r.y1)); + bp.line_to((r.x0, r.y1)); + bp.close_path(); + return bp; + } + let s = ry / rx; + let squeezed = Rect::new(r.x0 * s, r.y0, r.x1 * s, r.y1); + let mut bp = BezPath::new(); + let rr = kurbo::RoundedRect::new(squeezed.x0, squeezed.y0, squeezed.x1, squeezed.y1, ry); + for el in kurbo::Shape::path_elements(&rr, TOLERANCE) { + bp.push(el); + } + bp.apply_affine(Affine::scale_non_uniform(1.0 / s, 1.0)); + bp +} + +fn arc(r: Rect, start: i16, sweep: i16, wedge: bool) -> BezPath { + let c = r.center(); + let radii = Vec2::new(r.width() / 2.0, r.height() / 2.0); + let mut bp = BezPath::new(); + if sweep == 0 { + return bp; + } + let a0 = (f64::from(start) - 90.0).to_radians(); + let sweep = f64::from(sweep).clamp(-360.0, 360.0).to_radians(); + let arc = kurbo::Arc { center: c, radii, start_angle: a0, sweep_angle: sweep, x_rotation: 0.0 }; + if wedge { + bp.move_to(c); + bp.line_to(c + Vec2::new(radii.x * a0.cos(), radii.y * a0.sin())); + for el in arc.append_iter(TOLERANCE) { + bp.push(el); + } + bp.close_path(); + } else { + for el in kurbo::Shape::path_elements(&arc, TOLERANCE) { + bp.push(el); + } + } + bp +} + +fn rects_path(rects: &[Rect]) -> BezPath { + let mut bp = BezPath::new(); + for r in rects { + bp.move_to((r.x0, r.y0)); + bp.line_to((r.x1, r.y0)); + bp.line_to((r.x1, r.y1)); + bp.line_to((r.x0, r.y1)); + bp.close_path(); + } + bp +} + +fn spend(work: &mut u64, n: usize) -> bool { + match work.checked_sub(n as u64) { + Some(left) => { + *work = left; + true + } + None => false, + } +} + +fn region(r: &mut Be, work: &mut u64) -> Option<(Vec, bool)> { + let size = usize::from(r.u16()?); + let mut b = Be::new(r.bytes(size.checked_sub(2)?)?, 0); + let bbox = b.rect()?; + if size <= 10 { + let whole = bbox.width() > 0.0 && bbox.height() > 0.0; + return Some((if whole { vec![bbox] } else { vec![] }, true)); + } + Some(bands(&mut b, work).map_or((vec![], false), |rects| (rects, true))) +} + +fn bands(b: &mut Be, work: &mut u64) -> Option> { + let mut out: Vec = vec![]; + let mut active: Vec = vec![]; + let mut last_band = 0; + let mut prev_y = 0.0; + loop { + let y = b.i16()?; + if y == 0x7FFF { + break; + } + let y = f64::from(y); + let spans: Vec<(f64, f64)> = active.as_chunks::<2>().0.iter().map(|[a, b]| (f64::from(*a), f64::from(*b))).collect(); + if !spans.is_empty() && y > prev_y { + if !spend(work, spans.len().saturating_add(1)) { + return None; + } + let prev = out.get_mut(last_band..).unwrap_or_default(); + let same = prev.len() == spans.len() && prev.iter().zip(&spans).all(|(r, (x0, x1))| r.x0 == *x0 && r.x1 == *x1 && r.y1 == prev_y); + if same { + prev.iter_mut().for_each(|r| r.y1 = y); + } else { + last_band = out.len(); + out.extend(spans.iter().map(|&(x0, x1)| Rect::new(x0, prev_y, x1, y))); + if out.len() > MAX_RECTS { + return None; + } + } + } + prev_y = y; + loop { + let x = b.i16()?; + if x == 0x7FFF { + break; + } + if !spend(work, active.len().saturating_add(1)) { + return None; + } + match active.binary_search(&x) { + Ok(i) => { + active.remove(i); + } + Err(i) => active.insert(i, x), + } + } + } + Some(out) +} + +fn skip(op: u16, r: &mut Be) -> Option<()> { + let n = match op { + 0x00 | 0x17..=0x19 | 0x1C | 0x1E | 0xB0..=0xCF | 0x8000..=0x80FF => 0, + 0x04 => 1, + 0x03 | 0x05 | 0x08 | 0x0D | 0x11 | 0x15 | 0x16 | 0xA0 => 2, + 0x06 | 0x07 | 0x0B | 0x0C | 0x0E | 0x0F => 4, + 0x1A | 0x1B | 0x1D | 0x1F => 6, + 0x02 | 0x09 | 0x0A | 0x10 => 8, + 0x24..=0x27 | 0x2C..=0x2F | 0x92..=0x97 | 0x9C..=0x9F | 0xA2..=0xAF => usize::from(r.u16()?), + 0x0100..=0x7FFF => usize::from(op >> 8).saturating_mul(2), + _ => usize::try_from(r.u32()?).ok()?, + }; + r.skip(n) +} + +struct PixMap { + row_bytes: usize, + bounds: Rect, + size: u16, + pack: u16, + cmps: u16, + palette: Option>, + packed: bool, +} + +impl PixMap { + fn read(r: &mut Be, pixmap: bool, direct: bool) -> Option { + let raw = r.u16()?; + let mut pm = PixMap { row_bytes: usize::from(raw & 0x3FFF), bounds: r.rect()?, size: 1, pack: 0, cmps: 1, palette: None, packed: true }; + if pixmap || raw & 0x8000 != 0 { + r.skip(2)?; + pm.pack = r.u16()?; + r.skip(14)?; + pm.size = r.u16()?; + pm.cmps = r.u16()?; + r.skip(14)?; + if !direct { + pm.palette = Some(color_table(r)?); + } + } + Some(pm) + } + + fn dims(&self) -> Option<(usize, usize)> { + let (w, h) = (self.bounds.width(), self.bounds.height()); + (w > 0.0 && h > 0.0).then_some((w as usize, h as usize)) + } + + fn packing(&self) -> u16 { + match (self.size, self.pack) { + (32, 0) => 4, + (16, 0) => 3, + (_, p) => p, + } + } + + fn raw_rows(&self) -> bool { + !self.packed || self.row_bytes < 8 || self.packing() == 1 || (self.size == 32 && self.packing() == 2) + } + + fn row_len(&self, w: usize) -> usize { + match self.packing() { + 4 if self.size == 32 && self.row_bytes >= 8 => w.saturating_mul(usize::from(self.cmps)), + 2 if self.size == 32 => (self.row_bytes / 4).saturating_mul(3), + _ => self.row_bytes, + } + } + + fn decodable(&self, w: usize) -> bool { + let need = match self.size { + 1 | 2 | 4 | 8 => (w.saturating_mul(usize::from(self.size))).div_ceil(8), + 16 if matches!(self.packing(), 0 | 1 | 3) => 2 * w, + 32 if self.packing() == 4 && self.row_bytes >= 8 => { + if !matches!(self.cmps, 3 | 4) { + return false; + } + w.saturating_mul(usize::from(self.cmps)) + } + 32 if self.packing() == 2 => 3 * w, + 32 if matches!(self.packing(), 0 | 1) || (self.packing() == 4 && self.row_bytes < 8) => 4 * w, + _ => return false, + }; + (need..=need.saturating_add(ROW_SLACK)).contains(&self.row_len(w)) + } + + fn rows(&self, r: &mut Be, w: usize, h: usize, keep: bool) -> Option<(Vec, bool)> { + let len = self.row_len(w); + let unit = if self.packing() == 3 { 2 } else { 1 }; + let mut out = vec![]; + let mut ok = true; + let mut keep = keep; + for _ in 0..h { + if self.raw_rows() { + let row = r.bytes(len)?; + if keep { + out.extend_from_slice(row); + } + continue; + } + let n = if self.row_bytes > 250 { usize::from(r.u16()?) } else { usize::from(r.u8()?) }; + let packed = r.bytes(n)?; + if keep && !unpack(packed, len, unit, &mut out) { + ok = false; + keep = false; + out = vec![]; + } + } + Some((out, ok)) + } + + fn pixel(&self, row: &[u8], x: usize, w: usize, fg: [u8; 3], bg: [u8; 3]) -> Option<[u8; 3]> { + let at = |i: usize| row.get(i).copied(); + match self.size { + 1 | 2 | 4 | 8 => { + let bits = usize::from(self.size); + let shift = 8 - bits - x * bits % 8; + let index = usize::from((at(x * bits / 8)? >> shift) & ((1u16 << bits) - 1) as u8); + match &self.palette { + Some(p) => p.get(index).copied(), + None => Some(if index == 0 { bg } else { fg }), + } + } + 16 => { + let v = u16::from_be_bytes([at(2 * x)?, at(2 * x + 1)?]); + let c = |s: u16| (((v >> s) & 31) * 255 / 31) as u8; + Some([c(10), c(5), c(0)]) + } + _ if self.packing() == 4 && self.row_bytes >= 8 => { + let first = usize::from(self.cmps).checked_sub(3)?; + Some([at(first * w + x)?, at((first + 1) * w + x)?, at((first + 2) * w + x)?]) + } + _ if self.packing() == 2 => Some([at(3 * x)?, at(3 * x + 1)?, at(3 * x + 2)?]), + _ => Some([at(4 * x + 1)?, at(4 * x + 2)?, at(4 * x + 3)?]), + } + } + + fn to_rgba(&self, data: &[u8], w: usize, h: usize, fg: [u8; 3], bg: [u8; 3]) -> Option { + let len = self.row_len(w); + let mut pixels = Vec::with_capacity(w.saturating_mul(h).saturating_mul(4)); + for y in 0..h { + let row = data.get(y * len..(y + 1) * len)?; + for x in 0..w { + pixels.extend_from_slice(&self.pixel(row, x, w, fg, bg)?); + pixels.push(255); + } + } + Some(Rgba { w, h, px: pixels }) + } +} + +fn color_table(r: &mut Be) -> Option> { + r.skip(4)?; + let flags = r.u16()?; + let n = usize::from(r.u16()?).saturating_add(1); + let mut palette = vec![[0u8; 3]; 256]; + for i in 0..n { + let value = usize::from(r.u16()?); + let c = r.rgb()?; + if let Some(e) = palette.get_mut(if flags & 0x8000 != 0 { i } else { value }) { + *e = c; + } + } + Some(palette) +} + +fn unpack(data: &[u8], len: usize, unit: usize, out: &mut Vec) -> bool { + let start = out.len(); + let mut i = 0; + while out.len().saturating_sub(start) < len { + let Some(&n) = data.get(i) else { + return false; + }; + i += 1; + let n = n as i8; + if n >= 0 { + let k = (n as usize + 1).saturating_mul(unit); + if out.len().saturating_sub(start).saturating_add(k) > len { + return false; + } + let Some(lit) = data.get(i..i + k) else { + return false; + }; + out.extend_from_slice(lit); + i += k; + } else if n != -128 { + let count = (1 - isize::from(n)) as usize; + let total = count.saturating_mul(unit); + if out.len().saturating_sub(start).saturating_add(total) > len { + return false; + } + let Some(v) = data.get(i..i + unit) else { + return false; + }; + for _ in 0..count { + out.extend_from_slice(v); + } + i += unit; + } + } + out.len().saturating_sub(start) == len +} + +fn crop(img: Rgba, src: Rect) -> Option<(Rgba, Rect)> { + let (w, h) = (img.w, img.h); + let s = Rect::new(src.x0.min(src.x1), src.y0.min(src.y1), src.x0.max(src.x1), src.y0.max(src.y1)); + let clamp = |v: f64, max: usize| if v.is_finite() { v.round().clamp(0.0, max as f64) as usize } else { 0 }; + let (x0, y0, x1, y1) = (clamp(s.x0, w), clamp(s.y0, h), clamp(s.x1, w), clamp(s.y1, h)); + if x1 <= x0 || y1 <= y0 { + return None; + } + let in_bounds = Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64); + if (x0, y0, x1, y1) == (0, 0, w, h) { + return Some((img, in_bounds)); + } + let mut px = Vec::with_capacity((x1 - x0).saturating_mul(y1 - y0).saturating_mul(4)); + for y in y0..y1 { + let row = y * w * 4; + if let Some(p) = img.px.get(row + x0 * 4..row + x1 * 4) { + px.extend_from_slice(p); + } + } + Some((Rgba { w: x1 - x0, h: y1 - y0, px }, in_bounds)) +} + +struct Pict { + items: Vec, + frame: Rect, + base: Affine, + origin: Vec2, + fg: [u8; 3], + bg: [u8; 3], + pen: Vec2, + pen_mode: u16, + pen_pat: Pat, + fill_pat: Pat, + back_pat: Pat, + oval: Vec2, + pen_loc: Point, + font: u16, + face: u8, + text_size: i16, + text_loc: Point, + names: HashMap, + last: [Rect; 4], + region_work: u64, + row_bytes_left: u64, + pixels_left: u64, + clip: Option>, + pending: BezPath, + pending_pen: Option<([u8; 3], f64)>, + skipped_records: u32, + truncated: bool, + dropped_images: u32, + ignored_clips: u32, + unplayed_raster_ops: u32, + used_bytes: usize, +} + +impl Pict { + fn new(frame: Rect) -> Self { + let base = Affine::translate(-frame.origin().to_vec2()); + Self { + items: Vec::new(), + frame, + base, + origin: Vec2::ZERO, + fg: [0; 3], + bg: [255; 3], + pen: Vec2::new(1.0, 1.0), + pen_mode: 8, + pen_pat: Pat::Bits([0xFF; 8]), + fill_pat: Pat::Bits([0xFF; 8]), + back_pat: Pat::Bits([0; 8]), + oval: Vec2::ZERO, + pen_loc: Point::ZERO, + font: 0, + face: 0, + text_size: 0, + text_loc: Point::ZERO, + names: HashMap::new(), + last: [Rect::ZERO; 4], + region_work: MAX_REGION_WORK, + row_bytes_left: MAX_FILE_ROW_BYTES, + pixels_left: MAX_PIXELS as u64, + clip: None, + pending: BezPath::new(), + pending_pen: None, + skipped_records: 0, + truncated: false, + dropped_images: 0, + ignored_clips: 0, + unplayed_raster_ops: 0, + used_bytes: 0, + } + } + + fn xf(&self) -> Affine { + self.base * Affine::translate(-self.origin) + } + + fn push(&mut self, raw: Raw) { + self.push_raw(raw, false); + } + + fn push_raw(&mut self, mut raw: Raw, keep_region: bool) { + if self.items.len() >= MAX_ITEMS { + if matches!(raw, Raw::Bitmap { .. }) { + self.dropped_images = self.dropped_images.saturating_add(1); + } + self.truncated = true; + return; + } + if !keep_region { + if self.clip.as_ref().is_some_and(Vec::is_empty) { + return; + } + raw.set_region(RawClip { rects: self.clip.clone(), paths: Vec::new() }); + } + let region_cost = match &raw { + Raw::Path { region, .. } | Raw::Pattern { region, .. } | Raw::Bitmap { region, .. } | Raw::Text { region, .. } => { + region.rects.as_ref().map_or(0, |c| c.len().saturating_mul(std::mem::size_of::<[f64; 4]>())) + } + }; + let cost = match &raw { + Raw::Path { ops, .. } => ops.capacity().saturating_mul(std::mem::size_of::()).saturating_add(64), + Raw::Pattern { ops, .. } => ops.capacity().saturating_mul(std::mem::size_of::()).saturating_add(64), + Raw::Bitmap { img, .. } => img.px.capacity(), + Raw::Text { text: t, .. } => { + t.text.capacity().saturating_add(t.dx.capacity().saturating_mul(4)).saturating_add(t.font.family.capacity()).saturating_add(128) + } + } + .saturating_add(region_cost); + if self.used_bytes.saturating_add(cost) > MAX_BYTES { + if matches!(raw, Raw::Bitmap { .. }) { + self.dropped_images = self.dropped_images.saturating_add(1); + } + self.truncated = true; + return; + } + self.used_bytes += cost; + self.items.push(raw); + } + + fn charge(&mut self, pm: &PixMap, w: usize, h: usize) -> bool { + let bytes = (pm.row_len(w) as u64).saturating_mul(h as u64); + let Some(rows_left) = self.row_bytes_left.checked_sub(bytes) else { return false }; + let (Ok(wide), Ok(high)) = (u32::try_from(w), u32::try_from(h)) else { return false }; + let pixels = (wide as u64).saturating_mul(high as u64); + let Some(px_left) = self.pixels_left.checked_sub(pixels) else { return false }; + self.row_bytes_left = rows_left; + self.pixels_left = px_left; + true + } + + fn op(&mut self, op: u16, r: &mut Be) -> Option<()> { + if !matches!(op, 0x20..=0x23) { + self.flush(); + } + match op { + 0x01 => self.clip(r), + 0x0C => self.move_origin(r), + 0x20..=0x23 => self.line(op, r), + 0x28..=0x2B => self.text(op, r), + 0x2C => self.font_name(r), + 0x30..=0x6F => self.shape(op, r), + 0x70..=0x77 => self.poly(verb(op), r), + 0x80..=0x87 => self.region_shape(verb(op), r), + 0x78..=0x7F | 0x88..=0x8F => Some(()), + 0x90 | 0x91 | 0x98..=0x9B => self.bits(op, r), + 0xA1 => { + r.skip(2)?; + let n = usize::from(r.u16()?); + r.skip(n) + } + 0x0C00 => self.header(r), + 0x8200 => self.quicktime(r), + _ => self.state(op, r), + } + } + + fn state(&mut self, op: u16, r: &mut Be) -> Option<()> { + match op { + 0x00 | 0x11 | 0xA0 => return skip(op, r), + 0x02 => self.back_pat = Pat::Bits(r.array()?), + 0x03 => self.font = r.u16()?, + 0x04 => self.face = r.u8()?, + 0x07 => self.pen = r.size()?, + 0x08 => self.pen_mode = r.u16()?, + 0x09 => self.pen_pat = Pat::Bits(r.array()?), + 0x0A => self.fill_pat = Pat::Bits(r.array()?), + 0x0B => self.oval = r.size()?, + 0x0D => self.text_size = r.i16()?, + 0x0E => self.fg = old_color(r.u32()?), + 0x0F => self.bg = old_color(r.u32()?), + 0x12 => self.back_pat = self.pix_pat(r)?, + 0x13 => self.pen_pat = self.pix_pat(r)?, + 0x14 => self.fill_pat = self.pix_pat(r)?, + 0x1A => self.fg = r.rgb()?, + 0x1B => self.bg = r.rgb()?, + _ => { + self.skipped_records = self.skipped_records.saturating_add(1); + return skip(op, r); + } + } + Some(()) + } + + fn header(&mut self, r: &mut Be) -> Option<()> { + let mut b = Be::new(r.bytes(24)?, 0); + if b.i16() == Some(-2) + && let Some(src) = b.skip(10).and_then(|()| b.rect()) + && src.width() > 0.0 + && src.height() > 0.0 + { + let k = Vec2::new(self.frame.width() / src.width(), self.frame.height() / src.height()); + self.base = Affine::scale_non_uniform(k.x, k.y) * Affine::translate(-src.origin().to_vec2()); + } + Some(()) + } + + fn move_origin(&mut self, r: &mut Be) -> Option<()> { + let (dh, dv) = (r.i16()?, r.i16()?); + self.origin += Vec2::new(dh.into(), dv.into()); + Some(()) + } + + fn pix_pat(&mut self, r: &mut Be) -> Option { + let kind = r.u16()?; + let bits: [u8; 8] = r.array()?; + match kind { + 1 => { + let pm = PixMap::read(r, true, false)?; + let (w, h) = pm.dims()?; + let small = w * h <= MAX_PATTERN_PIXELS && pm.row_len(w) * h <= MAX_PATTERN_ROW_BYTES; + let keep = small && pm.decodable(w) && self.charge(&pm, w, h); + let (data, _) = pm.rows(r, w, h, keep)?; + if let Some(img) = keep.then(|| pm.to_rgba(&data, w, h, self.fg, self.bg)).flatten() { + let px = img.px.as_chunks::<4>().0; + if px.windows(2).any(|w| w[0] != w[1]) { + Some(Pat::Tile(Arc::new(RawTile { w: img.w, h: img.h, px: img.px, cell: 1.0 }))) + } else if let Some(first) = px.first() { + Some(Pat::Rgb([first[0], first[1], first[2]])) + } else { + Some(Pat::Bits(bits)) + } + } else { + Some(Pat::Bits(bits)) + } + } + 2 => Some(Pat::Rgb(r.rgb()?)), + _ => Some(Pat::Bits(bits)), + } + } + + fn pat_paint(&self, pat: &Pat) -> PaintChoice { + match pat { + Pat::Rgb(c) => PaintChoice::Solid(*c), + Pat::Tile(tile) => PaintChoice::Tile(tile.clone()), + Pat::Bits(b) => { + if *b == [0; 8] { + PaintChoice::Solid(self.bg) + } else if *b == [0xFF; 8] { + PaintChoice::Solid(self.fg) + } else { + let mut px = Vec::with_capacity(64 * 4); + for row in b { + for bit in 0..8 { + let is_fg = (row & (0x80 >> bit)) != 0; + let c = if is_fg { self.fg } else { self.bg }; + px.extend([c[0], c[1], c[2], 255]); + } + } + PaintChoice::Tile(Arc::new(RawTile { w: 8, h: 8, px, cell: 1.0 })) + } + } + } + } + + fn pat_color(&self, pat: &Pat) -> [u8; 3] { + match pat { + Pat::Rgb(c) => *c, + Pat::Tile(tile) => { + let px = tile.px.as_chunks::<4>().0; + let n = px.len().max(1) as u64; + let mut sum = [0u64; 3]; + for p in px { + sum[0] += u64::from(p[0]); + sum[1] += u64::from(p[1]); + sum[2] += u64::from(p[2]); + } + [(sum[0] / n) as u8, (sum[1] / n) as u8, (sum[2] / n) as u8] + } + Pat::Bits(b) => { + let ones: u32 = b.iter().map(|x| x.count_ones()).sum(); + mix(self.fg, self.bg, f64::from(ones) / 64.0) + } + } + } + + fn pen_color(&mut self) -> [u8; 3] { + if !matches!(self.pen_mode, 0 | 8) { + self.unplayed_raster_ops = self.unplayed_raster_ops.saturating_add(1); + } + self.pat_color(&self.pen_pat) + } + + fn area_paint(&mut self, verb: Verb) -> Option { + let pat = match verb { + Verb::Paint => { + if !matches!(self.pen_mode, 0 | 8) { + self.unplayed_raster_ops = self.unplayed_raster_ops.saturating_add(1); + } + self.pen_pat.clone() + } + Verb::Erase => self.back_pat.clone(), + Verb::Fill => self.fill_pat.clone(), + Verb::Frame | Verb::Invert => return None, + }; + Some(self.pat_paint(&pat)) + } + + fn has_pen(&self) -> bool { + self.pen.x > 0.0 && self.pen.y > 0.0 + } + + fn fill_paint(&mut self, mut bp: BezPath, paint: PaintChoice, even_odd: bool) { + bp.apply_affine(self.xf()); + let ops = bez_to_ops(&bp); + if ops.len() < 2 { + return; + } + let region = RawClip { rects: self.clip.clone(), paths: Vec::new() }; + match paint { + PaintChoice::Solid(color) => { + self.push(Raw::Path { + ops, + fill: Some([color[0], color[1], color[2], 255]), + stroke: None, + line: LineStyle::default(), + even_odd, + region, + }); + } + PaintChoice::Tile(tile) => { + self.push(Raw::Pattern { ops, even_odd, tile, region }); + } + } + } + + fn push_stroke(&mut self, bp: BezPath, color: [u8; 3], width: f64, cap: Cap) { + let ops = bez_to_ops(&bp); + if ops.len() < 2 { + return; + } + self.push(Raw::Path { + ops, + fill: None, + stroke: Some(([color[0], color[1], color[2], 255], width)), + line: LineStyle { cap, join: Join::Miter, miter_limit: 10.0, dash: Vec::new() }, + even_odd: false, + region: RawClip { rects: self.clip.clone(), paths: Vec::new() }, + }); + } + + fn fill(&mut self, bp: BezPath, color: [u8; 3], even_odd: bool) { + self.fill_paint(bp, PaintChoice::Solid(color), even_odd); + } + + fn scale_factor(&self) -> f64 { + let c = self.xf().as_coeffs(); + (c[0].abs() + c[3].abs()) / 2.0 + } + + fn stroke(&mut self, mut bp: BezPath, color: [u8; 3], ends: u32) { + let width = (self.pen.x + self.pen.y) / 2.0 * self.scale_factor(); + let cap = match ends { + FLAT => Cap::Flat, + SQUARE => Cap::Square, + _ => Cap::Round, + }; + bp.apply_affine(self.xf()); + self.push_stroke(bp, color, width, cap); + } + + fn frame(&mut self, r: Rect, outline: impl Fn(Rect, Vec2) -> BezPath, ends: u32) { + if !self.has_pen() { + return; + } + let color = self.pen_color(); + let half = self.pen / 2.0; + let inner = Rect::new(r.x0 + half.x, r.y0 + half.y, r.x1 - half.x, r.y1 - half.y); + if inner.width() <= 0.0 || inner.height() <= 0.0 { + return self.fill(outline(r, self.oval), color, false); + } + self.stroke(outline(inner, self.oval - self.pen), color, ends); + } + + fn shape(&mut self, op: u16, r: &mut Be) -> Option<()> { + let family = op >> 4; + let slot = usize::from(family.checked_sub(3)?); + let rect = if op & 8 != 0 { self.last.get(slot).copied()? } else { r.rect()? }; + let angles = if family == 6 { Some((r.i16()?, r.i16()?)) } else { None }; + let Some(verb) = verb(op) else { return Some(()) }; + if let Some(l) = self.last.get_mut(slot) { + *l = rect; + } + if rect.width() <= 0.0 || rect.height() <= 0.0 { + return Some(()); + } + let outline = move |r: Rect, oval: Vec2, wedge: bool| match family { + 3 => { + let mut bp = BezPath::new(); + bp.move_to((r.x0, r.y0)); + bp.line_to((r.x1, r.y0)); + bp.line_to((r.x1, r.y1)); + bp.line_to((r.x0, r.y1)); + bp.close_path(); + bp + } + 4 => round_rect(r, oval.x, oval.y), + 5 => kurbo::Shape::to_path(&kurbo::Ellipse::from_rect(r), TOLERANCE), + _ => angles.map_or_else(BezPath::new, |(start, sweep)| arc(r, start, sweep, wedge)), + }; + match verb { + Verb::Frame => self.frame(rect, |r, oval| outline(r, oval, false), if family == 6 { FLAT } else { SQUARE }), + Verb::Invert => { + self.skipped_records = self.skipped_records.saturating_add(1); + } + _ => { + if let Some(paint) = self.area_paint(verb) { + self.fill_paint(outline(rect, self.oval, true), paint, false); + } + } + } + Some(()) + } + + fn poly(&mut self, verb: Option, r: &mut Be) -> Option<()> { + let size = usize::from(r.u16()?); + let mut b = Be::new(r.bytes(size.checked_sub(2)?)?, 8); + let Some(verb) = verb else { return Some(()) }; + let mut pts = vec![]; + while let Some(p) = b.point() { + pts.push(p); + } + let Some((first, rest)) = pts.split_first() else { return Some(()) }; + let closed = pts.len() > 2 && pts.first() == pts.last(); + match verb { + Verb::Frame if self.has_pen() => { + let half = self.pen / 2.0; + let mut bp = BezPath::new(); + bp.move_to(*first + half); + for p in rest { + bp.line_to(*p + half); + } + if closed { + bp.close_path(); + } + let color = self.pen_color(); + self.stroke(bp, color, SQUARE); + } + Verb::Frame => {} + Verb::Invert => { + self.skipped_records = self.skipped_records.saturating_add(1); + } + _ => { + let mut bp = BezPath::new(); + bp.move_to(*first); + for p in rest { + bp.line_to(*p); + } + bp.close_path(); + if let Some(paint) = self.area_paint(verb) { + self.fill_paint(bp, paint, true); + } + } + } + Some(()) + } + + fn read_region(&mut self, r: &mut Be) -> Option> { + let (rects, whole) = region(r, &mut self.region_work)?; + if !whole { + return None; + } + Some(rects) + } + + fn region_shape(&mut self, verb: Option, r: &mut Be) -> Option<()> { + let Some(rects) = self.read_region(r) else { + self.skipped_records = self.skipped_records.saturating_add(1); + return Some(()); + }; + let Some(verb) = verb.filter(|_| !rects.is_empty()) else { return Some(()) }; + match verb { + Verb::Frame if self.has_pen() => { + let half = self.pen / 2.0; + let color = self.pen_color(); + if rects.len() == 1 { + let r = rects[0]; + let inner = Rect::new(r.x0 + half.x, r.y0 + half.y, r.x1 - half.x, r.y1 - half.y); + if inner.width() <= 0.0 || inner.height() <= 0.0 { + self.fill(rects_path(&[r]), color, false); + } else { + self.stroke(rects_path(&[inner]), color, SQUARE); + } + } else { + let outer_rects: Vec<[f64; 4]> = rects.iter().map(|r| [r.x0, r.y0, r.x1, r.y1]).collect(); + let inner_rects: Vec<[f64; 4]> = rects + .iter() + .filter_map(|r| { + let (x0, y0, x1, y1) = (r.x0 + half.x, r.y0 + half.y, r.x1 - half.x, r.y1 - half.y); + (x1 > x0 && y1 > y0).then_some([x0, y0, x1, y1]) + }) + .collect(); + let diff = clip::combine(Some(outer_rects), inner_rects, clip::RGN_DIFF, None).unwrap_or_default(); + let diff_rects: Vec = diff.into_iter().map(|[x0, y0, x1, y1]| Rect::new(x0, y0, x1, y1)).collect(); + self.fill(rects_path(&diff_rects), color, false); + } + } + Verb::Frame => {} + Verb::Invert => { + self.skipped_records = self.skipped_records.saturating_add(1); + } + _ => { + if let Some(paint) = self.area_paint(verb) { + self.fill_paint(rects_path(&rects), paint, false); + } + } + } + Some(()) + } + + fn clip(&mut self, r: &mut Be) -> Option<()> { + let (mut rects, whole) = region(r, &mut self.region_work)?; + if !whole { + self.ignored_clips = self.ignored_clips.saturating_add(1); + return Some(()); + } + if rects.is_empty() { + let corner = Point::new(self.frame.x0, self.frame.y0); + rects.push(Rect::from_points(corner, corner)); + } + let mut mapped = Vec::with_capacity(rects.len()); + for r in rects { + let p0 = self.xf() * Point::new(r.x0, r.y0); + let p1 = self.xf() * Point::new(r.x1, r.y1); + let (x0, x1) = (p0.x.min(p1.x), p0.x.max(p1.x)); + let (y0, y1) = (p0.y.min(p1.y), p0.y.max(p1.y)); + if [x0, y0, x1, y1].iter().all(|v| v.is_finite()) { + mapped.push([x0, y0, x1, y1]); + } + } + if mapped.len() > clip::MAX_CLIP_RECTS { + self.ignored_clips = self.ignored_clips.saturating_add(1); + } + mapped.truncate(clip::MAX_CLIP_RECTS); + self.clip = Some(mapped); + Some(()) + } + + fn flush(&mut self) { + if !self.pending.elements().is_empty() { + let bp = std::mem::take(&mut self.pending); + if let Some((color, width)) = self.pending_pen.take() { + self.push_stroke(bp, color, width, Cap::Square); + } + } + } + + fn line(&mut self, op: u16, r: &mut Be) -> Option<()> { + let delta = |r: &mut Be| Some(Vec2::new(f64::from(r.u8()? as i8), f64::from(r.u8()? as i8))); + let (from, to) = match op { + 0x20 => (r.point()?, r.point()?), + 0x21 => (self.pen_loc, r.point()?), + 0x22 => { + let a = r.point()?; + (a, a + delta(r)?) + } + _ => (self.pen_loc, self.pen_loc + delta(r)?), + }; + self.pen_loc = to; + if !self.has_pen() { + return Some(()); + } + let color = self.pen_color(); + if from == to { + self.flush(); + let mut bp = BezPath::new(); + let p0 = from; + let p1 = from + self.pen; + bp.move_to((p0.x, p0.y)); + bp.line_to((p1.x, p0.y)); + bp.line_to((p1.x, p1.y)); + bp.line_to((p0.x, p1.y)); + bp.close_path(); + self.fill(bp, color, false); + return Some(()); + } + let width = (self.pen.x + self.pen.y) / 2.0 * self.scale_factor(); + let pen = (color, width); + if self.pending_pen != Some(pen) { + self.flush(); + self.pending_pen = Some(pen); + } + if self.items.len() >= MAX_ITEMS { + self.truncated = true; + return Some(()); + } + let half = self.pen / 2.0; + let xf = self.xf(); + let (a, b) = (xf * (from + half), xf * (to + half)); + if self.pending.elements().last().and_then(|e| match e { + PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(*p), + _ => None, + }) != Some(a) + { + self.pending.move_to(a); + } + self.pending.line_to(b); + Some(()) + } + + fn text(&mut self, op: u16, r: &mut Be) -> Option<()> { + match op { + 0x28 => self.text_loc = r.point()?, + 0x29 => self.text_loc.x += f64::from(r.u8()?), + 0x2A => self.text_loc.y += f64::from(r.u8()?), + _ => { + self.text_loc.x += f64::from(r.u8()?); + self.text_loc.y += f64::from(r.u8()?); + } + } + let n = usize::from(r.u8()?); + let s: String = r.bytes(n)?.iter().map(|&b| mac_roman(b)).filter(|c| !c.is_control() && *c != '\0').collect(); + if s.trim().is_empty() { + return Some(()); + } + let size = if self.text_size > 0 { self.text_size as f32 } else { 12.0 }; + let face = self.names.get(&self.font).cloned().unwrap_or_else(|| font_family(self.font).to_string()); + let font = Font { + family: face, + height: -size, + width: 0.0, + weight: if self.face & 1 != 0 { 700 } else { 400 }, + italic: self.face & 2 != 0, + underline: self.face & 4 != 0, + strike: false, + charset: 0, + }; + let pt = self.xf() * self.text_loc; + let c = self.xf().as_coeffs(); + let transform = [c[0], c[1], c[2], c[3], pt.x, pt.y]; + self.push(Raw::Text { + text: Box::new(Text { + transform, + text: s, + dx: Vec::new(), + font, + color: [self.fg[0], self.fg[1], self.fg[2], 255], + background: None, + h_align: HAlign::Left, + v_align: VAlign::Baseline, + clip: None, + region: None, + clips: Vec::new(), + }), + region: RawClip { rects: self.clip.clone(), paths: Vec::new() }, + }); + Some(()) + } + + fn font_name(&mut self, r: &mut Be) -> Option<()> { + let n = usize::from(r.u16()?); + let mut b = Be::new(r.bytes(n)?, 0); + if let Some(id) = b.u16() + && let Some(len) = b.u8() + && let Some(name) = b.bytes(usize::from(len)) + { + let name: String = name.iter().map(|&c| mac_roman(c)).collect(); + self.names.insert(id, name.trim().to_string()); + } + Some(()) + } + + fn bits(&mut self, op: u16, r: &mut Be) -> Option<()> { + let direct = matches!(op, 0x9A | 0x9B); + if direct { + r.skip(4)?; + } + let mut pm = PixMap::read(r, direct, direct)?; + pm.packed = op >= 0x98; + let (src, dst, mode) = (r.rect()?, r.rect()?, r.u16()?); + let mask = if op & 1 != 0 { + match self.read_region(r) { + Some(m) => Some(m), + None => { + self.ignored_clips = self.ignored_clips.saturating_add(1); + None + } + } + } else { + None + }; + let (w, h) = pm.dims()?; + let (wide, high) = (w as u64, h as u64); + let fits = wide.saturating_mul(high) <= MAX_PIXELS as u64 && (pm.row_len(w) as u64).saturating_mul(high) <= MAX_ROW_BYTES; + let readable = pm.decodable(w); + let keep = fits && readable && self.charge(&pm, w, h); + let (data, ok) = pm.rows(r, w, h, keep)?; + if !keep { + self.dropped_images = self.dropped_images.saturating_add(1); + return Some(()); + } + let Some(mut img) = pm.to_rgba(&data, w, h, self.fg, self.bg).filter(|_| ok) else { + self.dropped_images = self.dropped_images.saturating_add(1); + return Some(()); + }; + self.transfer(&mut img, mode, pm.size == 1 && pm.palette.is_none()); + if dst.width() <= 0.0 || dst.height() <= 0.0 || mask.as_ref().is_some_and(Vec::is_empty) { + return Some(()); + } + self.image(img, src - pm.bounds.origin().to_vec2(), dst, mask); + Some(()) + } + + fn image(&mut self, img: Rgba, src: Rect, dest: Rect, mask: Option>) { + let Some((cropped, in_bounds)) = crop(img, src) else { + return; + }; + let (sw, sh) = (src.width(), src.height()); + if sw <= 0.0 || sh <= 0.0 { + return; + } + let kx = dest.width() / sw; + let ky = dest.height() / sh; + let sub_dest = Rect::new( + dest.x0 + (in_bounds.x0 - src.x0) * kx, + dest.y0 + (in_bounds.y0 - src.y0) * ky, + dest.x0 + (in_bounds.x1 - src.x0) * kx, + dest.y0 + (in_bounds.y1 - src.y0) * ky, + ); + let (w, h) = (cropped.w as f64, cropped.h as f64); + let xf = Affine::translate(sub_dest.origin().to_vec2()) * Affine::scale_non_uniform(sub_dest.width() / w, sub_dest.height() / h); + self.image_xf(cropped, xf, mask); + } + + fn image_xf(&mut self, img: Rgba, xf: Affine, mask: Option>) { + if img.w == 0 || img.h == 0 { + return; + } + let xf_doc = self.xf() * xf; + if !xf_doc.as_coeffs().iter().all(|v| v.is_finite()) || xf_doc.determinant().abs() < 1e-12 { + return; + } + let (w, h) = (img.w as f64, img.h as f64); + let unit_xf = xf_doc * Affine::scale_non_uniform(w, h); + let a = unit_xf * Point::new(0.0, 0.0); + let b = unit_xf * Point::new(1.0, 1.0); + let ux = unit_xf * Point::new(1.0, 0.0); + let uy = unit_xf * Point::new(0.0, 1.0); + let xs = [a.x, b.x, ux.x, uy.x]; + let ys = [a.y, b.y, ux.y, uy.y]; + let x0 = xs.iter().copied().fold(f64::INFINITY, f64::min); + let x1 = xs.iter().copied().fold(f64::NEG_INFINITY, f64::max); + let y0 = ys.iter().copied().fold(f64::INFINITY, f64::min); + let y1 = ys.iter().copied().fold(f64::NEG_INFINITY, f64::max); + let rect = [x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0)]; + + let (region, keep_region) = if let Some(mask_rects) = mask { + let mut mapped = Vec::with_capacity(mask_rects.len()); + for r in mask_rects { + let p0 = self.xf() * Point::new(r.x0, r.y0); + let p1 = self.xf() * Point::new(r.x1, r.y1); + if let Some(norm) = clip::normalize([p0.x, p0.y, p1.x, p1.y]) { + mapped.push(norm); + } + } + if mapped.len() > clip::MAX_CLIP_RECTS { + self.ignored_clips = self.ignored_clips.saturating_add(1); + } + mapped.truncate(clip::MAX_CLIP_RECTS); + let combined = match &self.clip { + Some(cur) => clip::combine(Some(cur.clone()), mapped, clip::RGN_AND, None), + None => Some(mapped), + }; + (RawClip { rects: combined, paths: Vec::new() }, true) + } else { + (RawClip { rects: self.clip.clone(), paths: Vec::new() }, false) + }; + + self.push_raw(Raw::Bitmap { rect, xf: unit_xf.as_coeffs(), img, region }, keep_region); + } + + fn transfer(&mut self, img: &mut Rgba, mode: u16, bitmap: bool) { + let clear = match mode & !64 { + 0 => false, + 1 if bitmap => true, + 36 => true, + _ => { + self.unplayed_raster_ops = self.unplayed_raster_ops.saturating_add(1); + false + } + }; + if clear { + let bg = self.bg; + for p in img.px.as_chunks_mut::<4>().0.iter_mut() { + if [p[0], p[1], p[2]] == bg { + p[3] = 0; + } + } + } + } + + fn quicktime(&mut self, r: &mut Be) -> Option<()> { + let n = usize::try_from(r.u32()?).ok()?; + let data = r.bytes(n)?; + match qt_image(data) { + Some((ctype, xf, src, image)) if &ctype == b"jpeg" => match self.jpeg(image) { + Some(img) => { + if let Some((img, in_bounds)) = crop(img, src) { + self.image_xf(img, xf * Affine::translate(in_bounds.origin().to_vec2()), None); + } + } + None => self.dropped_images = self.dropped_images.saturating_add(1), + }, + Some(_) | None => self.dropped_images = self.dropped_images.saturating_add(1), + } + Some(()) + } + + fn jpeg(&mut self, data: &[u8]) -> Option { + let img = dib::decode_compressed(data)?; + let (wide, high) = (u32::try_from(img.w).ok()?, u32::try_from(img.h).ok()?); + let pixels = (wide as u64).saturating_mul(high as u64); + let px_left = self.pixels_left.checked_sub(pixels)?; + self.pixels_left = px_left; + Some(img) + } +} + +fn qt_image(d: &[u8]) -> Option<([u8; 4], Affine, Rect, &[u8])> { + let mut b = Be::new(d, 2); + let mut m = [0.0; 9]; + for v in &mut m { + *v = f64::from(b.i32()?) / 65536.0; + } + let matte = usize::try_from(b.u32()?).ok()?; + b.skip(10)?; + let src = b.rect()?; + b.skip(4)?; + let mask = usize::try_from(b.u32()?).ok()?; + b.skip(matte)?; + b.skip(mask)?; + let start = b.pos; + let id_size = usize::try_from(b.u32()?).ok()?; + let ctype = b.array::<4>()?; + b.skip(36)?; + let size = usize::try_from(b.u32()?).ok()?; + let at = start.checked_add(id_size)?; + let data = d.get(at..at.checked_add(size)?).or_else(|| d.get(at..))?; + let xf = Affine::new([m[0], m[1], m[3], m[4], m[6], m[7]]); + Some((ctype, xf, src, data)) +} + +/// Read a QuickDraw picture. +pub fn parse(bytes: &[u8]) -> Result { + crate::dib::set_decode_budget(crate::dib::MAX_DECODE_PIXELS); + parse_nested(bytes) +} + +/// [`parse`] for a picture inside the metafile being parsed: it draws on the outer file's decode budget. +pub(crate) fn parse_nested(bytes: &[u8]) -> Result { + let h = find(bytes).ok_or(Error::NotPict)?; + let mut q = Pict::new(h.frame); + let mut r = Be::new(bytes, h.ops); + let mut stopped_early = true; + for _ in 0..MAX_OPS { + if h.v2 && r.pos % 2 == 1 && r.skip(1).is_none() { + break; + } + let Some(op) = (if h.v2 { r.u16() } else { r.u8().map(u16::from) }) else { + break; + }; + if op == 0x00FF { + stopped_early = false; + break; + } + if q.op(op, &mut r).is_none() { + break; + } + } + if stopped_early { + q.truncated = true; + } + q.flush(); + let pic = + crate::build(q.items, Some(Frame { rect: [0.0, 0.0, h.frame.width(), h.frame.height()], size: Some((h.frame.width(), h.frame.height())) })); + Ok(Picture { + skipped_records: q.skipped_records.saturating_add(pic.skipped_records), + truncated: q.truncated || pic.truncated, + dropped_images: q.dropped_images.saturating_add(pic.dropped_images), + ignored_clips: q.ignored_clips.saturating_add(pic.ignored_clips), + unplayed_raster_ops: q.unplayed_raster_ops.saturating_add(pic.unplayed_raster_ops), + ..pic + }) +} diff --git a/crates/metafile/src/size.rs b/crates/metafile/src/size.rs index 8766b99626..f97de7fdc1 100644 --- a/crates/metafile/src/size.rs +++ b/crates/metafile/src/size.rs @@ -1,7 +1,7 @@ //! The size of a metafile picture without playing its records. use crate::bytes::Bytes; -use crate::{Error, emf, f, parse, wmf}; +use crate::{Error, emf, f, parse, pict, wmf}; /// A placeable WMF header is 22 bytes, followed by the 9-word standard header. const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; @@ -29,8 +29,14 @@ pub(crate) fn header_size(b: Bytes) -> Option<(f32, f32)> { if emf::is_emf(b) { return emf_size(b); } - if wmf::is_wmf(b) && b.u32(0) == Some(PLACEABLE_KEY) { - return placeable_wmf_size(b); + if let Some(size) = pict::header_size(b.0) { + return Some(size); + } + if wmf::is_wmf(b) { + if b.u32(0) == Some(PLACEABLE_KEY) { + return placeable_wmf_size(b); + } + return None; } None } @@ -88,7 +94,7 @@ fn sets_the_mapping(b: Bytes, mut pos: usize) -> bool { if func == 0 || b.slice(pos, len).is_none() { return false; } - if matches!(func, 0x0103 | 0x020E) { + if matches!(func, 0x0103 | 0x020E) || (func == 0x0626 && pos.checked_add(6).and_then(|o| b.u16(o)) == Some(0x000F)) { return true; } let Some(next) = pos.checked_add(len) else { return false }; diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 3b47036fa9..610592f256 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -176,7 +176,8 @@ fn truncated_random_and_mutated_inputs_never_panic() { [0, 0, 20, 10], [0, 0, 2540, 1270], ); - for file in [&wfile, &efile] { + let wmfc_file = wmf(&wmfc_chunks(&efile, &[efile.len() / 2, efile.len() - efile.len() / 2]), None); + for file in [&wfile, &efile, &wmfc_file] { for n in 0..=file.len() { let prefix = &file[..n]; let _ = parse(prefix); @@ -190,7 +191,11 @@ fn truncated_random_and_mutated_inputs_never_panic() { let _ = parse(&buf); } for i in 0..1500usize { - let mut buf = if i.is_multiple_of(2) { efile.clone() } else { wfile.clone() }; + let mut buf = match i % 3 { + 0 => efile.clone(), + 1 => wfile.clone(), + _ => wmfc_file.clone(), + }; for _ in 0..8 { let at = rng.rnd() as usize % buf.len(); buf[at] = rng.rnd() as u8; @@ -198,7 +203,11 @@ fn truncated_random_and_mutated_inputs_never_panic() { let _ = parse(&buf); } for i in 0..500usize { - let mut buf = if i.is_multiple_of(2) { efile.clone() } else { wfile.clone() }; + let mut buf = match i % 3 { + 0 => efile.clone(), + 1 => wfile.clone(), + _ => wmfc_file.clone(), + }; let at = rng.rnd() as usize % buf.len(); buf[at..].iter_mut().for_each(|b| *b = 0xFF); let _ = parse(&buf); @@ -2139,3 +2148,202 @@ fn wmf_viewport_scaling_before_first_window_is_retained() { assert_eq!(p.skipped_records, 0); assert_eq!(rect_extent(&p.items[0]), (0.0, 0.0, 50.0, 100.0)); } + +struct WmfcChunk<'a> { + escape_fn: u16, + identifier: u32, + comment_type: u32, + version: u32, + flags: u32, + record_count: u32, + current_size: u32, + remaining: u32, + total_size: u32, + data: &'a [u8], +} + +impl<'a> WmfcChunk<'a> { + fn single(data: &'a [u8]) -> Self { + let n = data.len() as u32; + Self { + escape_fn: 0x000F, + identifier: 0x4346_4D57, + comment_type: 1, + version: 0x0001_0000, + flags: 0, + record_count: 1, + current_size: n, + remaining: 0, + total_size: n, + data, + } + } + + fn encode(&self) -> Vec { + let byte_count = (34 + self.data.len()) as u16; + let mut p = Vec::with_capacity(4 + 34 + self.data.len()); + p.extend(self.escape_fn.to_le_bytes()); + p.extend(byte_count.to_le_bytes()); + p.extend(self.identifier.to_le_bytes()); + p.extend(self.comment_type.to_le_bytes()); + p.extend(self.version.to_le_bytes()); + p.extend(0u16.to_le_bytes()); // checksum + p.extend(self.flags.to_le_bytes()); + p.extend(self.record_count.to_le_bytes()); + p.extend(self.current_size.to_le_bytes()); + p.extend(self.remaining.to_le_bytes()); + p.extend(self.total_size.to_le_bytes()); + p.extend(self.data); + wrec(0x0626, &p) + } +} + +fn wmfc_chunks(emf_bytes: &[u8], chunk_sizes: &[usize]) -> Vec> { + let total = emf_bytes.len() as u32; + let count = chunk_sizes.len() as u32; + let mut off = 0usize; + let mut out = Vec::with_capacity(chunk_sizes.len()); + for &sz in chunk_sizes { + let end = off + sz; + let rem = (emf_bytes.len() - end) as u32; + out.push( + WmfcChunk { record_count: count, current_size: sz as u32, remaining: rem, total_size: total, ..WmfcChunk::single(&emf_bytes[off..end]) } + .encode(), + ); + off = end; + } + assert_eq!(off, emf_bytes.len()); + out +} + +fn sample_ole_emf() -> Vec { + let mut stretch = cat(vec![ + e32(0), + e32(0), + e32(100), + e32(50), + e32(0), + e32(0), + e32(0), + e32(0), + e32(2), + e32(2), + e32(80), + e32(40), + e32(120), + e32(16), + e32(0), + e32(0x00CC_0020), + e32(100), + e32(50), + ]); + stretch.extend(info_header(2, 2, 24, 16)); + stretch.extend(dib24_bottom_up().get(40..).unwrap_or_default()); + // EMR_STRETCHDIBITS + stock HOLLOW_BRUSH (0x8000_0005) + Rectangle, with rclBounds = (0, 0, -1, -1). + emf( + &[erec(81, &stretch), erec(37, &h32(0x8000_0005)), erec(43, &cat(vec![e32(10), e32(10), e32(90), e32(40)]))], + [0, 0, -1, -1], + [0, 0, 2500, 1250], + ) +} + +#[test] +fn wmf_meta_escape_enhanced_metafile_single_and_multi_chunk() { + let inner = sample_ole_emf(); + let direct = parse(&inner).unwrap(); + assert_eq!(direct.items.len(), 2); + assert!(matches!(direct.items[0], Item::Bitmap { width: 2, height: 2, .. })); + assert!(matches!(direct.items[1], Item::Path { fill: None, stroke: Some(_), .. })); + + // Single-chunk WMFC inside a placeable WMF with no native drawing records. + let single = wmf(&wmfc_chunks(&inner, &[inner.len()]), Some([0, 0, 1000, 500])); + let p1 = parse(&single).unwrap(); + assert_eq!(p1.items, direct.items); + assert!((p1.width - direct.width).abs() < 1e-3 && (p1.height - direct.height).abs() < 1e-3); + assert_eq!(crate::size(&single).unwrap(), (p1.width, p1.height)); + + // Multi-chunk WMFC including an odd-sized chunk padded to a 16-bit WMF word boundary. + let c0 = 33usize; + let c1 = 75usize; + let c2 = inner.len() - c0 - c1; + let multi = wmf(&wmfc_chunks(&inner, &[c0, c1, c2]), None); + let p2 = parse(&multi).unwrap(); + assert_eq!(p2.items, direct.items); + assert_eq!(crate::size(&multi).unwrap(), (p2.width, p2.height)); +} + +#[test] +fn wmf_with_native_records_ignores_embedded_emf_escape() { + let inner = sample_ole_emf(); + let mut recs = wmfc_chunks(&inner, &[inner.len()]); + recs.push(wrec(0x041B, &cat(vec![h16(20), h16(20), h16(10), h16(10)]))); + let p = parse(&wmf(&recs, Some([0, 0, 100, 100]))).unwrap(); + assert_eq!(p.items.len(), 1); + assert!(matches!(p.items[0], Item::Path { .. })); + assert_eq!(p.skipped_records, 0); +} + +#[test] +fn wmf_malformed_or_oversized_wmfc_is_rejected_without_panic() { + let inner = sample_ole_emf(); + + // 1. Truncated stream (RemainingBytes > 0 with no following chunk). + let truncated = wmf( + &[WmfcChunk { record_count: 2, remaining: (inner.len() - 10) as u32, total_size: inner.len() as u32, ..WmfcChunk::single(&inner[..10]) } + .encode()], + None, + ); + let p = parse(&truncated).unwrap(); + assert!(p.items.is_empty()); + + // 2. Mismatched RemainingBytes on the second chunk. + let half = inner.len() / 2; + let bad_rem = wmf( + &[ + WmfcChunk { + record_count: 2, + remaining: (inner.len() - half) as u32, + total_size: inner.len() as u32, + ..WmfcChunk::single(&inner[..half]) + } + .encode(), + WmfcChunk { record_count: 2, remaining: 1, total_size: inner.len() as u32, ..WmfcChunk::single(&inner[half..]) }.encode(), + ], + None, + ); + assert!(parse(&bad_rem).unwrap().items.is_empty()); + + // 3. Mismatched EnhancedMetafileDataSize across chunks. + let bad_total = wmf( + &[ + WmfcChunk { + record_count: 2, + remaining: (inner.len() - half) as u32, + total_size: inner.len() as u32, + ..WmfcChunk::single(&inner[..half]) + } + .encode(), + WmfcChunk { record_count: 2, total_size: (inner.len() + 4) as u32, ..WmfcChunk::single(&inner[half..]) }.encode(), + ], + None, + ); + assert!(parse(&bad_total).unwrap().items.is_empty()); + + // 4. Invalid Version and non-zero Flags. + let bad_ver = wmf(&[WmfcChunk { version: 0x0002_0000, ..WmfcChunk::single(&inner) }.encode()], None); + assert!(parse(&bad_ver).unwrap().items.is_empty()); + let bad_flags = wmf(&[WmfcChunk { flags: 1, ..WmfcChunk::single(&inner) }.encode()], None); + assert!(parse(&bad_flags).unwrap().items.is_empty()); + + // 5. Oversized EnhancedMetafileDataSize (> MAX_EMBEDDED_EMF_BYTES) with a tiny payload. + let over = (crate::wmf::MAX_EMBEDDED_EMF_BYTES + 1) as u32; + let oversized = wmf(&[WmfcChunk { remaining: over - 8, total_size: over, ..WmfcChunk::single(&[0u8; 8]) }.encode()], None); + let p_over = parse(&oversized).unwrap(); + assert!(p_over.items.is_empty()); + assert!(p_over.truncated); + + // 6. Non-EMF bytes (e.g. a WMF) inside valid WMFC chunks are ignored safely. + let fake_wmf = wmf(&[wrec(0x041B, &cat(vec![h16(10), h16(10), h16(0), h16(0)]))], None); + let wrapped_wmf = wmf(&wmfc_chunks(&fake_wmf, &[fake_wmf.len()]), None); + assert!(parse(&wrapped_wmf).unwrap().items.is_empty()); +} diff --git a/crates/metafile/src/tests/limits.rs b/crates/metafile/src/tests/limits.rs index 365ea147c5..405d0d32d2 100644 --- a/crates/metafile/src/tests/limits.rs +++ b/crates/metafile/src/tests/limits.rs @@ -40,6 +40,22 @@ fn metafiles_nest_only_so_deep() { assert_eq!(nested(emfplus::MAX_NESTING + 1), 0, "the innermost picture is not read"); } +#[test] +fn wmf_wrapped_emf_shares_nesting_depth_cap() { + let square = emf(&[erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))], [0; 4], [0; 4]); + let wmf_wrap = |inner: Vec| wmf(&wmfc_chunks(&inner, &[inner.len()]), None); + // WMF (0) -> EMF (1) -> EMF+ WMF (2) -> EMF (3): at MAX_NESTED_DEPTH, still drawn. + let ok = wmf_wrap(wrap(wmf_wrap(square.clone()))); + let p_ok = parse(&ok).unwrap(); + assert_eq!(p_ok.items.len(), 1); + assert!(!p_ok.truncated); + // One more EMF+ level exceeds MAX_NESTED_DEPTH: stops cleanly without stack overflow. + let too_deep = wmf_wrap(wrap(wmf_wrap(wrap(square)))); + let p_deep = parse(&too_deep).unwrap(); + assert_eq!(p_deep.items.len(), 0); + assert_eq!(p_deep.dropped_images, 1); +} + #[test] fn emfplus_images_that_are_not_read_are_counted() { let square = || emf(&[erec(43, &cat(vec![e32(0), e32(0), e32(10), e32(10)]))], [0; 4], [0; 4]); diff --git a/crates/metafile/src/units.rs b/crates/metafile/src/units.rs new file mode 100644 index 0000000000..33dc87137b --- /dev/null +++ b/crates/metafile/src/units.rs @@ -0,0 +1,272 @@ +//! Frame and unit facts for consumers that apply their own fallback scale. +//! The WMF map-mode scan is adapted from VectorCraft’s metafile importer. + +use crate::{Kind, MAX_STACK, bytes::Bytes, sniff, wmf::PLACEABLE_KEY}; + +/// File-declared frame and source-unit information; does not assign a default physical scale. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UnitFacts { + /// A placeable WMF with positive frame extents. + WmfPlaceableFrame, + /// Without a placeable frame, a WMF whose drawing records predominantly use legacy map + /// modes 2–6 (LOMETRIC, HIMETRIC, LOENGLISH, HIENGLISH, TWIPS). This compatibility group + /// does not imply a particular physical unit. Ties use the last map mode seen. + WmfMetricMap, + /// Without a placeable frame, a WMF whose drawing records use logical units. + WmfLogical { + /// Positive units per inch from a placeable header, when one is present. + units_per_inch: Option, + }, + Emf { + /// The frame coordinates have positive extents, independently of device calibration. + has_frame: bool, + /// The device calibration, when both axes are positive. + device: Option, + }, +} + +/// The two axes of device calibration in an EMF header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EmfDevice { + /// Width and height, in pixels. + pub pixels: (u32, u32), + /// Device width and height, in the units supplied by the header. + pub physical_size: EmfPhysicalSize, +} + +/// The precision of the physical device size supplied by an EMF header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EmfPhysicalSize { + /// The header's extended micrometre fields were both positive. + Micrometres(u32, u32), + /// The extension was missing or incomplete; the millimetre fields were both positive. + Millimetres(u32, u32), +} + +/// Inspects a recognized WMF or EMF without decoding images, allocating geometry, or assigning +/// a physical size to a file that supplies none. A matching header is not proof that its records +/// parse successfully: use [`crate::parse`] for the actual picture. +pub fn unit_facts(bytes: &[u8]) -> Option { + let b = Bytes(bytes); + Some(match sniff(bytes)? { + Kind::Emf => UnitFacts::Emf { + has_frame: matches!((b.i32(24), b.i32(28), b.i32(32), b.i32(36)), (Some(l), Some(t), Some(r), Some(bt)) if r > l && bt > t), + device: emf_device(b), + }, + Kind::Wmf => { + let placeable = b.u32(0) == Some(PLACEABLE_KEY); + if placeable && matches!((b.i16(6), b.i16(8), b.i16(10), b.i16(12)), (Some(l), Some(t), Some(r), Some(bt)) if r > l && bt > t) { + UnitFacts::WmfPlaceableFrame + } else if wmf_metric(b, if placeable { 22 } else { 0 }) { + UnitFacts::WmfMetricMap + } else { + let units_per_inch = if placeable { b.u16(14).filter(|&inch| inch > 0) } else { None }; + UnitFacts::WmfLogical { units_per_inch } + } + } + }) +} + +// MS-EMF §2.3.4.2: optional description and pixel-format data follow +// the fixed fields. The total record size by itself cannot identify an extension. +fn emf_fixed_header_size(b: Bytes<'_>) -> Option { + let mut end = usize::try_from(b.u32(4)?).ok()?.min(b.0.len()); + if b.u32(60)? != 0 { + end = end.min(usize::try_from(b.u32(64)?).ok()?); + } + // Only inspect the extension-1 descriptor if it fits before any description. + if end >= 100 && b.u32(88)? != 0 { + end = end.min(usize::try_from(b.u32(92)?).ok()?); + } + Some(end) +} + +pub(crate) fn emf_device(b: Bytes<'_>) -> Option { + let positive = |v: i32| u32::try_from(v).ok().filter(|&v| v > 0); + let pixels = (positive(b.i32(72)?)?, positive(b.i32(76)?)?); + let physical_size = if emf_fixed_header_size(b)? >= 108 + && let (Some(w), Some(h)) = (positive(b.i32(100)?), positive(b.i32(104)?)) + { + EmfPhysicalSize::Micrometres(w, h) + } else { + EmfPhysicalSize::Millimetres(positive(b.i32(80)?)?, positive(b.i32(84)?)?) + }; + Some(EmfDevice { pixels, physical_size }) +} + +// Preserve the VectorCraft compatibility scan: count recognized drawing records under the map +// mode in which they appear, skipping suppressed shape and PATBLT classes. This is not replay. +fn wmf_metric(b: Bytes<'_>, start: usize) -> bool { + const SHAPES: [u16; 10] = [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0538, 0x061C, 0x0817, 0x081A, 0x0830]; + const DRAW: [u16; 5] = [0x0521, 0x0940, 0x0A32, 0x0B41, 0x0F43]; + const MIX_SKIPS: [u16; 2] = [7, 11]; // R2_XORPEN and R2_NOP + const PATCOPY: u32 = 0x00F0_0021; + const BLACKNESS: u32 = 0x0000_0042; + const WHITENESS: u32 = 0x00FF_0062; + let Some(words) = start.checked_add(2).and_then(|at| b.u16(at)) else { return false }; + let mut at = start.saturating_add(usize::from(words) * 2); + let (mut mode, mut mix) = (1, 13); // MM_TEXT, R2_COPYPEN + let metric = |mode: u16| (2..=6).contains(&mode); + let (mut in_metric, mut in_other) = (0usize, 0usize); + let mut saved = Vec::new(); + while let (Some(words), Some(function)) = (b.u32(at), b.u16(at.saturating_add(4))) { + let size = (words as usize).saturating_mul(2); + let Some(next) = at.checked_add(size) else { break }; + if function == 0 || size < 6 || next > b.0.len() { + break; + } + match function { + 0x0103 if size >= 8 => mode = b.u16(at + 6).unwrap_or(mode), // SETMAPMODE + 0x0104 if size >= 8 => mix = b.u16(at + 6).unwrap_or(mix), // SETROP2 + 0x001E => { + // SAVEDC + if saved.len() >= MAX_STACK { + break; + } + saved.push((mode, mix)); + } + 0x0127 if size >= 8 => { + // RESTOREDC + let n = b.i16(at + 6).map_or(0, i32::from); + let level = if n < 0 { saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) }; + if let Some(level) = level + && let Some((m, x)) = saved.get(level).copied() + { + mode = m; + mix = x; + saved.truncate(level); + } + } + f => { + let draws = match f { + _ if DRAW.contains(&f) => true, + _ if SHAPES.contains(&f) => !MIX_SKIPS.contains(&mix), + 0x061D => match b.u32(at + 6).filter(|_| size >= 10) { + // PATBLT + Some(PATCOPY) => !MIX_SKIPS.contains(&mix), + Some(rop) => rop == BLACKNESS || rop == WHITENESS, + None => false, + }, + _ => false, + }; + if draws && metric(mode) { + in_metric += 1; + } else if draws { + in_other += 1; + } + } + } + at = next; + } + if in_metric == in_other { metric(mode) } else { in_metric > in_other } +} + +#[cfg(test)] +mod tests { + use super::*; + + // Spec-generated headers and records; no external fixture bytes. + fn plain_wmf(records: &[(u16, &[u8])]) -> Vec { + let mut bytes = vec![0; 18]; + bytes[..6].copy_from_slice(&[1, 0, 9, 0, 0, 3]); + for (kind, parameters) in records { + bytes.extend_from_slice(&((parameters.len() / 2 + 3) as u32).to_le_bytes()); + bytes.extend_from_slice(&kind.to_le_bytes()); + bytes.extend_from_slice(parameters); + } + bytes + } + + #[test] + fn placeable_bounds_win_or_leave_the_declared_scale_for_logical_units() { + let mut bytes = vec![0; 22]; + bytes[..4].copy_from_slice(&PLACEABLE_KEY.to_le_bytes()); + bytes[10..12].copy_from_slice(&100i16.to_le_bytes()); + bytes[12..14].copy_from_slice(&80i16.to_le_bytes()); + bytes[14..16].copy_from_slice(&720u16.to_le_bytes()); + bytes.extend_from_slice(&plain_wmf(&[(0x0103, &[3, 0])])); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfPlaceableFrame)); + bytes[12..14].fill(0); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfMetricMap)); + bytes[46..48].copy_from_slice(&[1, 0]); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfLogical { units_per_inch: Some(720) })); + bytes[14..16].fill(0); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfLogical { units_per_inch: None })); + assert_eq!(unit_facts(&plain_wmf(&[])), Some(UnitFacts::WmfLogical { units_per_inch: None })); + } + + #[test] + fn wmf_dominance_counts_drawing_modes_and_respects_save_restore() { + let metric = [3, 0]; + let logical = [1, 0]; + let nop = [11, 0]; + let restore = (-1i16).to_le_bytes(); + let line = [20, 0, 10, 0]; + let unsupported_rop = 0x0055_0009u32.to_le_bytes(); + let bytes = plain_wmf(&[ + (0x0103, &metric), + (0x0213, &line), + (0x001E, &[]), + (0x0103, &logical), + (0x0104, &nop), + (0x0213, &line), + (0x0213, &line), + (0x061D, &unsupported_rop), + (0x0127, &restore), + (0x0213, &line), + (0x0103, &logical), + ]); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfMetricMap)); + let mut bytes = plain_wmf(&[(0x0103, &metric)]); + bytes.extend_from_slice(&[4, 0, 0, 0, 3, 1]); // Declares a mode change with a missing parameter. + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfMetricMap)); + } + + #[test] + fn emf_frame_and_device_calibration_are_independent_facts() { + let mut bytes = vec![0; 108]; + let set = |buf: &mut [u8], i: usize, value: i32| buf[i..i + 4].copy_from_slice(&value.to_le_bytes()); + for (i, v) in + [(0, 1), (4, 108), (32, 100), (36, 50), (40, 0x464d_4520), (72, 800), (76, 600), (80, 200), (84, 150), (100, 200_150), (104, 149_900)] + { + set(&mut bytes, i, v); + } + let facts = |has_frame, physical_size| Some(UnitFacts::Emf { has_frame, device: Some(EmfDevice { pixels: (800, 600), physical_size }) }); + assert_eq!(unit_facts(&bytes), facts(true, EmfPhysicalSize::Micrometres(200_150, 149_900))); + assert_eq!(unit_facts(&bytes[..104]), facts(true, EmfPhysicalSize::Millimetres(200, 150))); + set(&mut bytes, 100, -1); + assert_eq!(unit_facts(&bytes), facts(true, EmfPhysicalSize::Millimetres(200, 150))); + set(&mut bytes, 100, 200_150); + set(&mut bytes, 104, -1); + assert_eq!(unit_facts(&bytes), facts(true, EmfPhysicalSize::Millimetres(200, 150))); + set(&mut bytes, 104, 149_900); + set(&mut bytes, 4, 88); + set(&mut bytes, 36, 0); + assert_eq!(unit_facts(&bytes), facts(false, EmfPhysicalSize::Millimetres(200, 150))); + set(&mut bytes, 76, -1); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::Emf { has_frame: false, device: None })); + assert_eq!(unit_facts(b"not a metafile"), None); + } + #[test] + fn emf_variable_payloads_do_not_supply_micrometres() { + let mut bytes = vec![0; 148]; + let set = |buf: &mut [u8], i: usize, value: u32| buf[i..i + 4].copy_from_slice(&value.to_le_bytes()); + for (at, value) in [(0, 1), (4, 112), (40, 0x464d_4520), (60, 11), (64, 88), (72, 800), (76, 600), (80, 200), (84, 150)] { + set(&mut bytes, at, value); + } + for (dst, src) in bytes[88..110].as_chunks_mut::<2>().0.iter_mut().zip("app\0title\0\0".encode_utf16()) { + dst.copy_from_slice(&src.to_le_bytes()); + } + let mm = Some(EmfDevice { pixels: (800, 600), physical_size: EmfPhysicalSize::Millimetres(200, 150) }); + assert_eq!(emf_device(Bytes(&bytes)), mm); + + // The same numeric bytes are part of a pixel descriptor in extension 1, + // but are fixed calibration fields when extension 2 precedes that descriptor. + for (at, value) in [(4, 148), (60, 0), (64, 0), (88, 40), (92, 100), (100, 201_000), (104, 151_000)] { + set(&mut bytes, at, value); + } + assert_eq!(emf_device(Bytes(&bytes)), mm); + set(&mut bytes, 92, 108); + assert_eq!(emf_device(Bytes(&bytes)), Some(EmfDevice { pixels: (800, 600), physical_size: EmfPhysicalSize::Micrometres(201_000, 151_000) })); + } +} diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs index 62af9c74bd..4c9382da60 100644 --- a/crates/metafile/src/wmf.rs +++ b/crates/metafile/src/wmf.rs @@ -10,10 +10,136 @@ use crate::geom::{self, ArcKind, P}; use crate::text::{ETO_CLIPPED, ETO_OPAQUE, Font, MAX_CHARS, decode_bytes}; use crate::{Error, Frame, MAX_PATH_OPS}; -const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; +pub(crate) const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; const DEFAULT_INCH: f64 = 1440.0; /// A placeable WMF plays into a target sized in points; brushes are laid out in 96-dpi pixels. const PT_PER_PX: f64 = 72.0 / 96.0; +const META_ESCAPE: u16 = 0x0626; +const META_ESCAPE_ENHANCED_METAFILE: u16 = 0x000F; +const WMFC_IDENTIFIER: u32 = 0x4346_4D57; +const WMFC_COMMENT_TYPE: u32 = 0x0000_0001; +const WMFC_VERSION: u32 = 0x0001_0000; +const WMFC_HEADER_LEN: usize = 34; +/// Largest embedded EMF reassembled from `META_ESCAPE_ENHANCED_METAFILE` chunks (16 MiB). +pub(crate) const MAX_EMBEDDED_EMF_BYTES: usize = 16 * 1024 * 1024; + +pub(crate) struct ParsedWmf { + pub cv: Canvas, + pub frame: Option, + pub embedded_emf: Option>, + pub embedded_emf_capped: bool, +} + +enum CollectorState { + Empty, + Collecting { buf: Vec, total: usize, expected_records: u32, seen_records: u32 }, + Done(Vec), + Invalid, +} + +/// Reassembles an embedded EMF from `META_ESCAPE_ENHANCED_METAFILE` (`0x0626` / `0x000F`) chunks +/// ([MS-WMF] §2.3.6.14). +struct EmfCollector { + state: CollectorState, + capped: bool, +} + +impl EmfCollector { + fn new() -> Self { + Self { state: CollectorState::Empty, capped: false } + } + + fn push(&mut self, r: Bytes) { + if r.u16(6) != Some(META_ESCAPE_ENHANCED_METAFILE) { + return; + } + // Only "WMFC" with CommentType == 1 carries an embedded EMF; other MFCOMMENT records are ignored. + if r.u32(10) != Some(WMFC_IDENTIFIER) || r.u32(14) != Some(WMFC_COMMENT_TYPE) { + return; + } + if !matches!(self.state, CollectorState::Empty | CollectorState::Collecting { .. }) { + return; + } + let Some(byte_count) = r.u16(8).map(usize::from) else { + self.state = CollectorState::Invalid; + return; + }; + if byte_count < WMFC_HEADER_LEN || 10usize.checked_add(byte_count).is_none_or(|end| end > r.0.len()) { + self.state = CollectorState::Invalid; + return; + } + let (Some(version), Some(flags), Some(record_count)) = (r.u32(18), r.u32(24), r.u32(28)) else { + self.state = CollectorState::Invalid; + return; + }; + let (Some(current_size), Some(remaining), Some(total_size)) = + (r.u32(32).map(|v| v as usize), r.u32(36).map(|v| v as usize), r.u32(40).map(|v| v as usize)) + else { + self.state = CollectorState::Invalid; + return; + }; + if version != WMFC_VERSION + || flags != 0 + || record_count == 0 + || current_size == 0 + || total_size == 0 + || WMFC_HEADER_LEN.checked_add(current_size).is_none_or(|n| n > byte_count) + { + self.state = CollectorState::Invalid; + return; + } + if total_size > MAX_EMBEDDED_EMF_BYTES { + self.capped = true; + self.state = CollectorState::Invalid; + return; + } + let Some(chunk) = r.slice(44, current_size) else { + self.state = CollectorState::Invalid; + return; + }; + let state = std::mem::replace(&mut self.state, CollectorState::Invalid); + self.state = match state { + CollectorState::Empty => { + if current_size.checked_add(remaining) != Some(total_size) { + CollectorState::Invalid + } else { + let mut buf = Vec::new(); + buf.extend_from_slice(chunk); + if remaining == 0 { + if record_count == 1 { CollectorState::Done(buf) } else { CollectorState::Invalid } + } else { + CollectorState::Collecting { buf, total: total_size, expected_records: record_count, seen_records: 1 } + } + } + } + CollectorState::Collecting { mut buf, total, expected_records, mut seen_records } => { + if total_size != total + || record_count != expected_records + || seen_records >= expected_records + || buf.len().checked_add(current_size).and_then(|n| n.checked_add(remaining)) != Some(total) + { + CollectorState::Invalid + } else { + buf.extend_from_slice(chunk); + seen_records += 1; + if remaining == 0 { + if seen_records == expected_records && buf.len() == total { CollectorState::Done(buf) } else { CollectorState::Invalid } + } else { + CollectorState::Collecting { buf, total, expected_records, seen_records } + } + } + } + other => other, + }; + } + + fn finish(self) -> (Option>, bool) { + match self.state { + CollectorState::Done(buf) => (Some(buf), self.capped), + _ => (None, self.capped), + } + } +} pub(crate) fn is_wmf(b: Bytes) -> bool { if b.u32(0) == Some(PLACEABLE_KEY) { @@ -22,9 +148,9 @@ pub(crate) fn is_wmf(b: Bytes) -> bool { matches!(b.u16(0), Some(1 | 2)) && b.u16(2) == Some(9) && matches!(b.u16(4), Some(0x100 | 0x300)) } -/// Reads all records. Returns the drawing state and the picture frame, or an error when no record -/// could be read at all. -pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { +/// Reads all records. Returns the drawing state, picture frame, and any complete embedded EMF +/// reassembled from `META_ESCAPE_ENHANCED_METAFILE`, or an error when no record could be read. +pub(crate) fn parse(input: Bytes) -> Result { let placeable = input.u32(0) == Some(PLACEABLE_KEY); // Placeable bounds: logical corners (left, top, right, bottom) and their size in points. let (hdr, bounds) = if placeable { @@ -52,6 +178,7 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { } // Keep the player target independent of subsequent mapping changes. let mut player_target = bounds.map(|(_, size)| size); + let mut emf_collector = EmfCollector::new(); let mut parsed = 0usize; while !cv.full() { let (Some(words), Some(func)) = (input.u32(pos), pos.checked_add(4).and_then(|o| input.u16(o))) else { break }; @@ -60,7 +187,11 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { if func == 0 { break; } - record(&mut cv, func, Bytes(rec)); + if func == META_ESCAPE { + emf_collector.push(Bytes(rec)); + } else { + record(&mut cv, func, Bytes(rec)); + } if func == 0x020C && cv.window_set && player_target.is_none() && !cv.viewport_set { let we = cv.map.window_ext(); let target = (we.0.abs(), we.1.abs()); @@ -93,7 +224,8 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { None if cv.window_set => Some(Frame { rect: cv.map.window_rect(), size: None }), None => None, }; - Ok((cv, frame)) + let (embedded_emf, embedded_emf_capped) = emf_collector.finish(); + Ok(ParsedWmf { cv, frame, embedded_emf, embedded_emf_capped }) } fn record(cv: &mut Canvas, func: u16, r: Bytes) { @@ -202,9 +334,9 @@ fn record(cv: &mut Canvas, func: u16, r: Bytes) { } /// Records that change nothing the picture keeps: relative-absolute and stretch modes, character -/// spacing and justification, mapper flags, palettes, escapes and the layout. Every other record +/// spacing and justification, mapper flags, palettes and the layout. Every other record /// the reader does not play is counted as skipped. -const IGNORED: &[u16] = &[0x0105, 0x0107, 0x0108, 0x020A, 0x0231, 0x0234, 0x0035, 0x0037, 0x0139, 0x0436, 0x0626, 0x0149]; +const IGNORED: &[u16] = &[0x0105, 0x0107, 0x0108, 0x020A, 0x0231, 0x0234, 0x0035, 0x0037, 0x0139, 0x0436, 0x0149]; /// A 16-bit WMF handle as a canvas object index: stock objects are `0x8000 | index`, which the /// canvas reads with the 32-bit stock flag. diff --git a/crates/metafile/tests/it/main.rs b/crates/metafile/tests/it/main.rs new file mode 100644 index 0000000000..35eb0e79ef --- /dev/null +++ b/crates/metafile/tests/it/main.rs @@ -0,0 +1,4 @@ +//! Integration tests: one test binary for the crate, one module per area. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod pict; diff --git a/crates/metafile/tests/it/pict.rs b/crates/metafile/tests/it/pict.rs new file mode 100644 index 0000000000..dcfb2822c9 --- /dev/null +++ b/crates/metafile/tests/it/pict.rs @@ -0,0 +1,427 @@ +//! QuickDraw pictures read from hand-built opcodes: versions 1 and 2, with and without the file's +//! application data; shapes, lines, regions, patterns, text, bitmaps, pixel maps and QuickTime +//! JPEG images; and pictures that are cut short, damaged or never end. + +use kurbo::{Rect, Shape}; + +use craft_metafile::{Item, bez_path, parse_pict}; + +/// Big-endian words. +fn be(v: &[i16]) -> Vec { + v.iter().flat_map(|x| x.to_be_bytes()).collect() +} + +/// A QuickDraw rectangle: top, left, bottom, right. +fn rect(top: i16, left: i16, bottom: i16, right: i16) -> Vec { + be(&[top, left, bottom, right]) +} + +/// A version 2 PICT file: 512 bytes of application data, then a picture of `frame` (top, left, +/// bottom, right) holding `ops`, each padded to an even length, and the end opcode. +fn v2(frame: [i16; 4], ops: &[(u16, Vec)]) -> Vec { + let mut b = vec![0xA5; 512]; + b.extend([0, 0]); + b.extend(be(&frame)); + b.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + b.extend(be(&[-1, 0])); + b.extend([0; 20]); + for (op, data) in ops { + b.extend(op.to_be_bytes()); + b.extend(data); + if b.len() % 2 == 1 { + b.push(0); + } + } + b.extend([0x00, 0xFF]); + b +} + +/// An RGB foreground color. +fn fg(r: u16, g: u16, b: u16) -> (u16, Vec) { + (0x1A, [r, g, b].iter().flat_map(|c| c.to_be_bytes()).collect()) +} + +fn near(a: Rect, b: Rect, tol: f64) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() <= tol) +} + +fn near_box(a: [f32; 4], b: [f32; 4], tol: f32) -> bool { + a.iter().zip(b.iter()).all(|(x, y)| (x - y).abs() <= tol) +} + +fn path_bounds(item: &Item) -> Rect { + let Item::Path { segs, .. } = item else { panic!("expected a path") }; + bez_path(segs).bounding_box() +} + +fn fill_rgb(item: &Item) -> Option<[u8; 3]> { + match item { + Item::Path { fill: Some(c), .. } => Some([c[0], c[1], c[2]]), + Item::Pattern { tile, .. } => { + let px = tile.rgba.as_chunks::<4>().0; + let n = px.len().max(1) as f64; + let mut sum = [0.0; 3]; + for p in px { + sum[0] += f64::from(p[0]); + sum[1] += f64::from(p[1]); + sum[2] += f64::from(p[2]); + } + Some([(sum[0] / n).round() as u8, (sum[1] / n).round() as u8, (sum[2] / n).round() as u8]) + } + _ => None, + } +} + +fn stroke(item: &Item) -> Option<([u8; 3], f32)> { + match item { + Item::Path { stroke: Some((c, w)), .. } => Some(([c[0], c[1], c[2]], *w)), + _ => None, + } +} + +#[test] +fn a_version_2_picture_opens_as_shapes_in_its_frame() { + let bytes = v2( + [10, 20, 110, 220], + &[ + fg(0xFFFF, 0, 0), + // paintRect + (0x31, rect(20, 30, 60, 80)), + (0x07, be(&[4, 4])), + fg(0, 0, 0xFFFF), + // frameRect: stroked inside the rectangle. + (0x30, rect(20, 120, 80, 200)), + // A line, and one from its end: one path. + (0x20, be(&[90, 40, 90, 140])), + (0x21, be(&[100, 140])), + ], + ); + assert!(craft_metafile::is_pict(&bytes)); + let p = parse_pict(&bytes).unwrap(); + assert_eq!((p.width, p.height), (200.0, 100.0)); + assert_eq!(p.items.len(), 3); + assert_eq!(fill_rgb(&p.items[0]), Some([255, 0, 0])); + let b0 = path_bounds(&p.items[0]); + assert!(near(b0, Rect::new(10.0, 10.0, 60.0, 50.0), 1e-5), "{b0:?}"); + assert_eq!(stroke(&p.items[1]), Some(([0, 0, 255], 4.0))); + let b1 = path_bounds(&p.items[1]); + assert!(near(b1, Rect::new(102.0, 12.0, 178.0, 68.0), 1e-5), "{b1:?}"); + assert_eq!(stroke(&p.items[2]), Some(([0, 0, 255], 4.0))); + let b2 = path_bounds(&p.items[2]); + assert!(near(b2, Rect::new(22.0, 82.0, 122.0, 92.0), 1e-5), "{b2:?}"); +} + +#[test] +fn a_bare_picture_and_a_version_1_picture_open() { + // A version 2 picture without the file's application data. + let file = v2([0, 0, 50, 50], &[(0x31, rect(10, 10, 20, 20))]); + let bare = &file[512..]; + assert!(craft_metafile::is_pict(bare)); + assert_eq!(parse_pict(bare).unwrap().items.len(), 1); + + // Version 1: byte opcodes, known by name only. + let mut v1 = vec![0, 0]; + v1.extend(rect(0, 0, 40, 60)); + v1.extend([0x11, 0x01, 0x31]); + v1.extend(rect(5, 5, 15, 25)); + v1.extend([0xA0, 0x00, 0x05, 0x50]); + v1.extend(rect(20, 20, 30, 30)); + v1.push(0xFF); + assert!(craft_metafile::is_pict(&v1)); + let p = parse_pict(&v1).unwrap(); + assert_eq!((p.width, p.height), (60.0, 40.0)); + assert_eq!(p.items.len(), 2); + let b0 = path_bounds(&p.items[0]); + assert!(near(b0, Rect::new(5.0, 5.0, 25.0, 15.0), 1e-5)); + assert_eq!(stroke(&p.items[1]), Some(([0, 0, 0], 1.0))); + + let mut file = vec![0; 512]; + file.extend(&v1); + assert_eq!(parse_pict(&file).unwrap().items.len(), 2); +} + +#[test] +fn files_that_are_not_pictures_are_refused() { + assert_eq!(parse_pict(&[0; 600]).unwrap_err(), craft_metafile::Error::NotPict); + assert_eq!(parse_pict(b"").unwrap_err(), craft_metafile::Error::NotPict); + let mut b = vec![0, 0]; + b.extend(rect(10, 10, 10, 50)); + b.extend([0x11, 0x01, 0xFF]); + assert_eq!(parse_pict(&b).unwrap_err(), craft_metafile::Error::NotPict); +} + +#[test] +fn rounded_rectangles_ovals_arcs_and_same_shapes() { + let bytes = v2( + [0, 0, 100, 100], + &[ + (0x0B, be(&[20, 20])), + (0x41, rect(0, 0, 50, 50)), + (0x51, rect(50, 0, 100, 50)), + // A wedge from 12 to 3 o'clock. + (0x61, [rect(0, 50, 100, 150), be(&[0, 90])].concat()), + fg(0, 0xFFFF, 0), + // paintSameRect after paintRect: the same rectangle. + (0x31, rect(60, 60, 70, 80)), + (0x39, vec![]), + ], + ); + let p = parse_pict(&bytes).unwrap(); + assert_eq!(p.items.len(), 5); + assert!(near(path_bounds(&p.items[0]), Rect::new(0.0, 0.0, 50.0, 50.0), 1e-5)); + assert!(near(path_bounds(&p.items[1]), Rect::new(0.0, 50.0, 50.0, 100.0), 1e-3)); + assert!(near(path_bounds(&p.items[2]), Rect::new(100.0, 0.0, 150.0, 50.0), 1e-3)); + assert_eq!(path_bounds(&p.items[3]), path_bounds(&p.items[4])); + assert_eq!(fill_rgb(&p.items[4]), Some([0, 255, 0])); +} + +#[test] +fn polygons_and_regions_fill_and_clip() { + let region = [be(&[36]), rect(0, 0, 20, 20), be(&[0, 0, 20, 0x7FFF, 10, 10, 20, 0x7FFF, 20, 0, 10, 0x7FFF, 0x7FFF])].concat(); + let poly = [be(&[22]), rect(0, 0, 40, 40), be(&[0, 0, 40, 40, 0, 40])].concat(); + let bytes = v2([0, 0, 100, 100], &[(0x81, region.clone()), (0x71, poly), (0x01, region), (0x31, rect(0, 0, 100, 100))]); + let p = parse_pict(&bytes).unwrap(); + assert_eq!(p.items.len(), 3); + assert!(near(path_bounds(&p.items[0]), Rect::new(0.0, 0.0, 20.0, 20.0), 1e-5)); + assert!(near(path_bounds(&p.items[1]), Rect::new(0.0, 0.0, 40.0, 40.0), 1e-5)); + let Item::Path { region: Some(r), .. } = &p.items[2] else { panic!("expected clip region on item 2") }; + assert!(!r.is_empty()); +} + +#[test] +fn patterns_fill_with_their_average_color() { + let gray = vec![0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55]; + let bytes = v2( + [0, 0, 10, 10], + &[(0x0A, gray), (0x34, rect(0, 0, 10, 10)), (0x12, [be(&[2]), vec![0; 8], be(&[0, -1, 0])].concat()), (0x32, rect(0, 0, 5, 5))], + ); + let p = parse_pict(&bytes).unwrap(); + assert!(matches!(&p.items[0], Item::Pattern { .. })); + assert_eq!(fill_rgb(&p.items[0]), Some([128, 128, 128])); + assert_eq!(fill_rgb(&p.items[1]), Some([0, 255, 0])); +} + +#[test] +fn text_comes_in_as_point_type_in_the_named_font() { + let name = [be(&[9, 300]), vec![6], b"Geneva".to_vec()].concat(); + let bytes = v2( + [0, 0, 100, 200], + &[(0x2C, name), (0x03, be(&[300])), (0x0D, be(&[18])), (0x04, vec![1]), (0x28, [be(&[50, 10]), vec![4], b"Caf\x8E".to_vec()].concat())], + ); + let p = parse_pict(&bytes).unwrap(); + let Item::Text(t) = &p.items[0] else { panic!("expected text") }; + assert_eq!(t.text, "Café"); + assert_eq!(t.font.family, "Geneva"); + assert_eq!(t.font.weight, 700); + assert_eq!(t.font.height, -18.0); + assert_eq!((t.transform[4], t.transform[5]), (10.0, 50.0)); +} + +fn pixmap_fields(pack: i16, size: i16, cmps: i16) -> Vec { + be(&[0, pack, 0, 0, 72, 0, 72, 0, 0, size, cmps, 8, 0, 0, 0, 0, 0, 0]) +} + +#[test] +fn a_packed_indexed_pixel_map_becomes_an_image() { + let table = be(&[0, 0, 0, 1, 0, -1, 0, 0, 1, 0, 0, -1]); + let rows = [vec![2, 0xF9, 0], vec![9, 7, 1, 0, 1, 0, 1, 0, 1, 0]].concat(); + let data = + [be(&[0x8008u16 as i16]), rect(0, 0, 2, 8), pixmap_fields(0, 8, 1), table, rect(0, 0, 2, 8), rect(10, 20, 14, 36), be(&[0]), rows].concat(); + let p = parse_pict(&v2([0, 0, 50, 50], &[(0x98, data)])).unwrap(); + let Item::Bitmap { width, height, rect, rgba, .. } = &p.items[0] else { panic!("expected bitmap") }; + assert_eq!((*width, *height), (8, 2)); + assert_eq!(rgba[0..4], [255, 0, 0, 255]); + assert_eq!(rgba[32..36], [0, 0, 255, 255]); + assert_eq!(rgba[36..40], [255, 0, 0, 255]); + assert!(near_box(*rect, [20.0, 10.0, 16.0, 4.0], 1e-5)); +} + +#[test] +fn direct_pixel_maps_and_masked_bitmaps() { + let row = vec![7, 5, 255, 0, 0, 255, 0, 0]; + let direct = + [be(&[0, 0xFF, 0x8008u16 as i16]), rect(0, 0, 1, 2), pixmap_fields(4, 32, 3), rect(0, 0, 1, 2), rect(0, 0, 1, 2), be(&[0]), row].concat(); + let mask = [be(&[10]), rect(5, 0, 6, 1)].concat(); + let bitmap = [be(&[2]), rect(0, 0, 1, 2), rect(0, 0, 1, 2), rect(5, 0, 6, 2), be(&[1]), mask, vec![0x80, 0]].concat(); + let p = parse_pict(&v2([0, 0, 10, 10], &[(0x9A, direct), (0x91, bitmap)])).unwrap(); + assert_eq!(p.items.len(), 2); + let Item::Bitmap { rgba: rgba0, .. } = &p.items[0] else { panic!("expected bitmap 0") }; + assert_eq!(rgba0[0..4], [255, 0, 0, 255]); + assert_eq!(rgba0[4..8], [0, 255, 0, 255]); + let Item::Bitmap { rgba: rgba1, region: Some(r), .. } = &p.items[1] else { panic!("expected bitmap 1 with region") }; + assert_eq!(rgba1[0..4], [0, 0, 0, 255]); + assert_eq!(rgba1[7], 0, "the clear bit is left out"); + assert_eq!(r, &vec![[0.0, 5.0, 1.0, 6.0]]); +} + +#[test] +fn rows_far_longer_than_their_pixels_are_refused() { + let table = be(&[0, 0, 0, 1, 0, -1, 0, 0, 1, -1, 0, 0]); + let mut row = be(&[256]); + (0..127).for_each(|_| row.extend([0x81, 1])); + row.extend([0x82, 1]); + let map = [be(&[0xBFFFu16 as i16]), rect(0, 0, 1, 1), pixmap_fields(0, 8, 1), table.clone()].concat(); + let data = [map, rect(0, 0, 1, 1), rect(0, 0, 1, 1), be(&[0]), row.clone()].concat(); + let p = parse_pict(&v2([0, 0, 10, 10], &[(0x98, data), (0x31, rect(0, 0, 5, 5))])).unwrap(); + assert_eq!(p.dropped_images, 1); + assert_eq!(p.items.len(), 1); + assert!(!p.truncated); + + let pattern = [be(&[1]), vec![0xFF; 8], be(&[0xBFFFu16 as i16]), rect(0, 0, 1, 1), pixmap_fields(0, 8, 1), table, row].concat(); + let p = parse_pict(&v2([0, 0, 10, 10], &[(0x12, pattern), (0x32, rect(0, 0, 5, 5))])).unwrap(); + assert_eq!(fill_rgb(&p.items[0]), Some([0, 0, 0])); +} + +#[test] +fn bitmap_rows_of_eight_bytes_or_more_are_read_unpacked() { + let row = vec![0x80, 0, 0, 0, 0, 0, 0, 0]; + let bitmap = [be(&[8]), rect(0, 0, 1, 16), rect(0, 0, 1, 16), rect(0, 0, 1, 16), be(&[0]), row].concat(); + let p = parse_pict(&v2([0, 0, 10, 20], &[(0x90, bitmap), (0x31, rect(2, 2, 4, 4))])).unwrap(); + assert_eq!(p.items.len(), 2); + let Item::Bitmap { width, height, rgba, .. } = &p.items[0] else { panic!("expected bitmap") }; + assert_eq!((*width, *height), (16, 1)); + assert_eq!(rgba[0..4], [0, 0, 0, 255]); + assert_eq!(rgba[4..8], [255, 255, 255, 255]); +} + +#[test] +fn an_empty_clip_region_hides_what_follows() { + let empty = [be(&[10]), rect(0, 0, 0, 0)].concat(); + let p = parse_pict(&v2([0, 0, 50, 50], &[(0x01, empty), (0x31, rect(0, 0, 10, 10))])).unwrap(); + let Item::Path { region: Some(r), .. } = &p.items[0] else { panic!("expected item with clip") }; + assert_eq!(r, &vec![[0.0, 0.0, 0.0, 0.0]]); +} + +fn quicktime(ctype: &[u8; 4], matrix: [f64; 6], w: i16, h: i16, data: &[u8]) -> Vec { + let fixed = |v: f64| ((v * 65536.0) as i32).to_be_bytes(); + let [a, b, c, d, tx, ty] = matrix; + let mut q = be(&[0]); + for v in [a, b, 0.0, c, d, 0.0, tx, ty] { + q.extend(fixed(v)); + } + q.extend((1i32 << 30).to_be_bytes()); + q.extend([0; 4]); + q.extend([0; 8]); + q.extend(be(&[0])); + q.extend(rect(0, 0, h, w)); + q.extend([0; 4]); + q.extend([0; 4]); + let mut desc = vec![]; + desc.extend(86u32.to_be_bytes()); + desc.extend(ctype); + desc.extend([0; 24]); + desc.extend(be(&[w, h])); + desc.extend([0; 8]); + desc.extend((data.len() as u32).to_be_bytes()); + desc.resize(86, 0); + q.extend(desc); + q.extend(data); + [(q.len() as u32).to_be_bytes().to_vec(), q].concat() +} + +fn red_jpeg() -> Vec { + let img = image::RgbImage::from_pixel(4, 2, image::Rgb([255, 0, 0])); + let mut buf = std::io::Cursor::new(Vec::new()); + img.write_to(&mut buf, image::ImageFormat::Jpeg).unwrap(); + buf.into_inner() +} + +#[test] +fn quicktime_jpeg_images_are_placed_by_their_matrix() { + let jpeg = red_jpeg(); + let ops = [ + (0x8200, quicktime(b"jpeg", [2.0, 0.0, 0.0, 2.0, 10.0, 5.0], 4, 2, &jpeg)), + (0x8200, quicktime(b"rle ", [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], 4, 2, &[1, 2, 3])), + ]; + let p = parse_pict(&v2([0, 0, 50, 50], &ops)).unwrap(); + assert_eq!(p.items.len(), 1); + let Item::Bitmap { width, height, rgba, rect, .. } = &p.items[0] else { panic!("expected bitmap") }; + assert_eq!((*width, *height), (4, 2)); + assert!(rgba[0] > 240 && rgba[1] < 16 && rgba[2] < 16); + assert!(near_box(*rect, [10.0, 5.0, 8.0, 4.0], 1e-5)); + assert_eq!(p.dropped_images, 1); +} + +#[test] +fn a_flattened_image_adds_no_image_data() { + let p = parse_pict(&v2([0, 0, 50, 50], &[(0x8200, quicktime(b"jpeg", [0.0; 6], 4, 2, &red_jpeg()))])).unwrap(); + assert!(p.items.is_empty()); +} + +#[test] +fn pictures_cut_short_keep_what_came_before() { + let full = v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10)), (0x31, rect(20, 20, 30, 30))]); + let cut = &full[..full.len() - 6]; + let p = parse_pict(cut).unwrap(); + assert_eq!(p.items.len(), 1); + assert!(p.truncated); + + let p = parse_pict(&v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10)), (0xA1, be(&[100, 5000]))])).unwrap(); + assert_eq!(p.items.len(), 1); + assert!(p.truncated); + + let p = parse_pict(&v2([0, 0, 50, 50], &[(0xA0, be(&[100]))])).unwrap(); + assert!(p.items.is_empty()); +} + +#[test] +fn reserved_opcodes_are_skipped_by_their_lengths() { + let ops = [ + (0x0024, be(&[4, 1, 2])), + (0x0200, be(&[1, 2])), + (0x00D0, [8u32.to_be_bytes().to_vec(), vec![9; 8]].concat()), + (0x8201, [2u32.to_be_bytes().to_vec(), vec![9; 2]].concat()), + (0x31, rect(0, 0, 10, 10)), + ]; + let p = parse_pict(&v2([0, 0, 50, 50], &ops)).unwrap(); + assert_eq!(p.items.len(), 1); + assert_eq!(p.skipped_records, 4); +} + +#[test] +fn a_picture_that_never_ends_stops_at_the_opcode_limit() { + let mut b = v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10))]); + b.truncate(b.len() - 2); + b.resize(b.len() + 2 * ((1 << 22) + 1), 0); + b.extend([0x00, 0x31]); + b.extend(rect(20, 20, 30, 30)); + b.extend([0x00, 0xFF]); + let p = parse_pict(&b).unwrap(); + assert_eq!(p.items.len(), 1); + assert!(p.truncated); +} + +#[test] +fn regions_past_the_picture_budget_are_left_out() { + let mut words = vec![0]; + words.extend(0..16_000i16); + words.extend([0x7FFF, 1, 0x7FFF, 0x7FFF]); + let body = [rect(0, 0, 1, 16_000), be(&words)].concat(); + let region = [be(&[(body.len() + 2) as i16]), body].concat(); + let p = parse_pict(&v2([0, 0, 300, 300], &[(0x81, region.clone()), (0x81, region.clone()), (0x81, region)])).unwrap(); + assert_eq!(p.skipped_records, 1); + assert_eq!(p.ignored_clips, 0); + assert_eq!(p.items.len(), 2); +} + +#[test] +fn pict_size_works_from_header() { + let file = v2([10, 20, 110, 220], &[(0x31, rect(20, 30, 60, 80))]); + assert_eq!(craft_metafile::size(&file).unwrap(), (200.0, 100.0)); + assert_eq!(craft_metafile::size(&file[512..]).unwrap(), (200.0, 100.0)); +} + +#[test] +fn bare_v1_pict_with_10x10_frame_is_parsed_as_pict() { + let mut v1 = vec![0, 0]; + v1.extend(rect(0, 0, 10, 10)); + v1.extend([0x11, 0x01, 0x31]); + v1.extend(rect(0, 0, 10, 10)); + v1.push(0xFF); + v1.resize(256, 0); + assert!(craft_metafile::is_pict(&v1)); + assert_eq!(craft_metafile::size(&v1).unwrap(), (10.0, 10.0)); + let pic = craft_metafile::parse(&v1).unwrap(); + assert_eq!((pic.width, pic.height), (10.0, 10.0)); + assert_eq!(pic.items.len(), 1); +} diff --git a/crates/plotter/src/hpgl/write.rs b/crates/plotter/src/hpgl/write.rs index 1d1cac34ea..a1b60e9d0d 100644 --- a/crates/plotter/src/hpgl/write.rs +++ b/crates/plotter/src/hpgl/write.rs @@ -94,10 +94,42 @@ pub fn write_hpgl2(pens: &[Pen], paths_per_pen: &[Vec>]) -> Vec< out } +/// HP-GL: `IN;`, each pen's paths as `PU` and `PD`, `PU;SP0;`. +/// +/// The index of each path group plus one is its pen number; empty groups do not +/// renumber later pens. The caller owns coordinate and output-size limits. +/// The original classic serializer is from dotCooCoo (VectorCraft 987dd18a). +pub fn write_hpgl(by_pen: &[Vec>]) -> Vec { + let mut s = String::from("IN;"); + for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + s.push_str(&format!("PU;SP{};", i + 1)); + for path in paths { + let Some(((x, y), rest)) = path.split_first() else { continue }; + s.push_str(&format!("PU{x},{y};PD")); + for (k, (x, y)) in rest.iter().enumerate() { + if k > 0 { + s.push(','); + } + s.push_str(&format!("{x},{y}")); + } + s.push(';'); + } + } + s.push_str("PU;SP0;"); + s.into_bytes() +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn classic_hpgl_keeps_pen_ordinals_and_path_bytes() { + assert_eq!(write_hpgl(&[]), b"IN;PU;SP0;"); + let paths = vec![vec![vec![(0, 0), (9, -3), (5, 1)]], vec![], vec![vec![(4, 1), (0, 2)], vec![(5, -6), (7, 8)]]]; + assert_eq!(write_hpgl(&paths), b"IN;PU;SP1;PU0,0;PD9,-3,5,1;PU;SP3;PU4,1;PD0,2;PU5,-6;PD7,8;PU;SP0;"); + } + #[test] fn pe_numbers_are_raw_bytes_and_paths_lift_the_pen() { let first: &[(i64, i64)] = &[(0, 0), (10, -10)]; diff --git a/crates/png/Cargo.toml b/crates/png/Cargo.toml new file mode 100644 index 0000000000..f37e1ed8b8 --- /dev/null +++ b/crates/png/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "craft-png" +description = "Writer for plain 8-bit PNG images" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +png = "0.18" +thiserror = { workspace = true } diff --git a/crates/png/src/lib.rs b/crates/png/src/lib.rs new file mode 100644 index 0000000000..904a425a95 --- /dev/null +++ b/crates/png/src/lib.rs @@ -0,0 +1,190 @@ +//! Write plain 8-bit and 16-bit PNGs from packed samples. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::io::Write; + +/// Stored samples per pixel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Layout { + Gray, + Rgb, + Rgba, +} + +impl Layout { + fn color_and_channels(self) -> (png::ColorType, usize) { + match self { + Layout::Gray => (png::ColorType::Grayscale, 1), + Layout::Rgb => (png::ColorType::Rgb, 3), + Layout::Rgba => (png::ColorType::Rgba, 4), + } + } +} + +/// PNG encoding or sample validation failure. +#[derive(Debug, thiserror::Error)] +pub enum EncodeError { + #[error("invalid PNG dimensions {0}×{1}")] + Dimensions(u32, u32), + #[error("PNG needs {expected} sample bytes, got {actual}")] + SampleLength { expected: usize, actual: usize }, + #[error(transparent)] + Png(#[from] png::EncodingError), +} + +fn validate_dimensions(width: u32, height: u32, channels: usize, sample_bytes: usize) -> Result<(usize, usize), EncodeError> { + const MAX_DIMENSION: u32 = i32::MAX as u32; + let invalid_dimensions = || EncodeError::Dimensions(width, height); + if !(1..=MAX_DIMENSION).contains(&width) || !(1..=MAX_DIMENSION).contains(&height) { + return Err(invalid_dimensions()); + } + let bytes_per_pixel = channels.checked_mul(sample_bytes).ok_or_else(invalid_dimensions)?; + let row_bytes = (width as usize).checked_mul(bytes_per_pixel).ok_or_else(invalid_dimensions)?; + // Include each scanline's filter byte in the encoder's uncompressed size. + let with_filters = row_bytes.checked_add(1).and_then(|stride| stride.checked_mul(height as usize)).filter(|&size| size <= isize::MAX as usize); + let expected_bytes = with_filters.ok_or_else(invalid_dimensions)? - height as usize; + Ok((row_bytes, expected_bytes)) +} + +fn write_png(output: impl Write, width: u32, height: u32, color: png::ColorType, depth: png::BitDepth, bytes: &[u8]) -> Result<(), EncodeError> { + let mut encoder = png::Encoder::new(output, width, height); + encoder.set_color(color); + encoder.set_depth(depth); + encoder.set_compression(png::Compression::Fast); + encoder.set_filter(png::Filter::Adaptive); + let mut writer = encoder.write_header()?; + writer.write_image_data(bytes)?; + writer.finish()?; + Ok(()) +} + +/// Write an 8-bit PNG with fast compression and adaptive row filtering. +/// +/// Samples are packed without padding in top-to-bottom row order. The dimensions and +/// exact input length are checked before a header is written. Success includes IEND +/// and flushing the sink. +pub fn write_8bit(output: impl Write, width: u32, height: u32, layout: Layout, samples: &[u8]) -> Result<(), EncodeError> { + let (color, channels) = layout.color_and_channels(); + let (_, expected) = validate_dimensions(width, height, channels, 1)?; + if samples.len() != expected { + return Err(EncodeError::SampleLength { expected, actual: samples.len() }); + } + write_png(output, width, height, color, png::BitDepth::Eight, samples) +} + +/// Write a 16-bit PNG with fast compression and adaptive row filtering. +/// +/// Samples are native `u16` values packed without padding in top-to-bottom row order +/// and written in big-endian PNG byte order. The dimensions and exact input length are +/// checked before a header is written. Success includes IEND and flushing the sink. +pub fn write_16bit(output: impl Write, width: u32, height: u32, layout: Layout, samples: &[u16]) -> Result<(), EncodeError> { + let (color, channels) = layout.color_and_channels(); + let (_, expected_bytes) = validate_dimensions(width, height, channels, 2)?; + let expected_samples = expected_bytes / 2; + let actual_bytes = samples.len().saturating_mul(2); + if samples.len() != expected_samples { + return Err(EncodeError::SampleLength { expected: expected_bytes, actual: actual_bytes }); + } + let mut big_endian = Vec::with_capacity(expected_bytes); + for &sample in samples { + big_endian.extend_from_slice(&sample.to_be_bytes()); + } + write_png(output, width, height, color, png::BitDepth::Sixteen, &big_endian) +} + +#[cfg(test)] +mod tests { + use std::io::{self, Cursor}; + + use super::{EncodeError, Layout, Write, write_8bit, write_16bit}; + + #[test] + fn decodes_exact_samples_in_each_layout() -> Result<(), Box> { + let (width, height) = (513, 131); + for (layout, color, channels) in + [(Layout::Gray, png::ColorType::Grayscale, 1), (Layout::Rgb, png::ColorType::Rgb, 3), (Layout::Rgba, png::ColorType::Rgba, 4)] + { + let expected: Vec = (0..width * height * channels).map(|i| (i * 17 + i / (width * channels)) as u8).collect(); + let mut encoded = Vec::new(); + write_8bit(&mut encoded, width, height, layout, &expected)?; + + assert!(encoded.ends_with(b"\0\0\0\0IEND\xaeB\x60\x82")); + let mut reader = png::Decoder::new(Cursor::new(encoded)).read_info()?; + let mut decoded = vec![0; reader.output_buffer_size().ok_or("output size")?]; + let info = reader.next_frame(&mut decoded)?; + assert_eq!((info.width, info.height, info.color_type, info.bit_depth), (width, height, color, png::BitDepth::Eight)); + assert_eq!(decoded, expected); + } + Ok(()) + } + + #[test] + fn rejects_invalid_dimensions_and_sample_lengths_before_output() { + let mut encoded = Vec::new(); + for (width, height) in [(0, 1), (1, 0), (u32::MAX, 1), (i32::MAX as u32, i32::MAX as u32)] { + assert!(matches!(write_8bit(&mut encoded, width, height, Layout::Rgba, &[]), Err(EncodeError::Dimensions(..)))); + } + for actual in [7, 9] { + assert!(matches!( + write_8bit(&mut encoded, 2, 1, Layout::Rgba, &[0; 9][..actual]), + Err(EncodeError::SampleLength { expected: 8, actual: n }) if n == actual + )); + } + assert!(encoded.is_empty()); + } + + #[test] + fn returns_an_error_when_the_sink_cannot_write_or_flush() { + struct FlushError; + + impl Write for FlushError { + fn write(&mut self, bytes: &[u8]) -> io::Result { + Ok(bytes.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Err(io::ErrorKind::BrokenPipe.into()) + } + } + + let mut short = [0; 20]; + assert!(matches!(write_8bit(short.as_mut_slice(), 1, 1, Layout::Gray, &[19]), Err(EncodeError::Png(_)))); + assert!(matches!(write_8bit(FlushError, 1, 1, Layout::Gray, &[19]), Err(EncodeError::Png(_)))); + } + + #[test] + fn decodes_exact_16bit_samples_in_each_layout() -> Result<(), Box> { + let (width, height) = (37, 19); + for (layout, color, channels) in + [(Layout::Gray, png::ColorType::Grayscale, 1), (Layout::Rgb, png::ColorType::Rgb, 3), (Layout::Rgba, png::ColorType::Rgba, 4)] + { + let expected: Vec = (0..width * height * channels).map(|i| ((i * 257 + 13) & 0xFFFF) as u16).collect(); + let mut encoded = Vec::new(); + write_16bit(&mut encoded, width, height, layout, &expected)?; + + assert!(encoded.ends_with(b"\0\0\0\0IEND\xaeB\x60\x82")); + let mut reader = png::Decoder::new(Cursor::new(encoded)).read_info()?; + let mut decoded = vec![0u8; reader.output_buffer_size().ok_or("output size")?]; + let info = reader.next_frame(&mut decoded)?; + assert_eq!((info.width, info.height, info.color_type, info.bit_depth), (width, height, color, png::BitDepth::Sixteen)); + let decoded_u16: Vec = decoded.as_chunks::<2>().0.iter().copied().map(u16::from_be_bytes).collect(); + assert_eq!(decoded_u16, expected); + } + Ok(()) + } + + #[test] + fn rejects_invalid_16bit_dimensions_and_sample_lengths_before_output() { + let mut encoded = Vec::new(); + for (width, height) in [(0, 1), (1, 0), (u32::MAX, 1), (i32::MAX as u32, i32::MAX as u32)] { + assert!(matches!(write_16bit(&mut encoded, width, height, Layout::Rgba, &[]), Err(EncodeError::Dimensions(..)))); + } + for actual in [3, 5] { + assert!(matches!( + write_16bit(&mut encoded, 1, 1, Layout::Rgba, &[0u16; 5][..actual]), + Err(EncodeError::SampleLength { expected: 8, actual: n }) if n == actual * 2 + )); + } + assert!(encoded.is_empty()); + } +} diff --git a/crates/pptx/tests/it/read.rs b/crates/pptx/tests/it/read.rs index fd03d2d981..4696299d3b 100644 --- a/crates/pptx/tests/it/read.rs +++ b/crates/pptx/tests/it/read.rs @@ -1,5 +1,7 @@ //! The reader on small packages written by hand. +use super::common; + use craft_opc::{PackageOut, RelsOut}; use craft_pptx::{Defaults, Geom, LayoutType, Master, PhType, Plain, Presentation, ShapeKind, Size}; @@ -105,6 +107,40 @@ fn shape<'a>(p: &'a Presentation, name: &str) -> &'a craft_pptx::Shape { found.unwrap_or_else(|| panic!("no shape {name}")) } +#[test] +fn direct_nested_compatibility_choice_imports_selected_shape() { + let before = sp(20, "Before choice", "", XFRM, "Before"); + let outer_rejected = sp(21, "Outer rejected", "", XFRM, "Outer"); + let selected = sp(22, "Nested selected", "", XFRM, "Selected"); + let inner_rejected = sp(23, "Inner rejected", "", XFRM, "Inner"); + let after = sp(24, "After choice", "", XFRM, "After"); + let nested = format!( + r#"{before} + {outer_rejected} + + {selected} + {inner_rejected} + + {after}"# + ); + let bytes = common::rewrite( + &deck(), + |part, data| { + if part == "ppt/slides/slide1.xml" { + Some(std::str::from_utf8(data).unwrap().replace("", &nested).into_bytes()) + } else { + Some(data.to_vec()) + } + }, + &[], + ); + let p = craft_pptx::import(&bytes, &Plain).unwrap(); + let names: Vec<_> = p.slides[0].shapes.iter().map(|shape| shape.name.as_str()).collect(); + assert!(names.ends_with(&["Before choice", "Nested selected", "After choice"]), "{names:?}"); + assert_eq!(names.iter().filter(|&&name| name == "Nested selected").count(), 1); + assert!(!names.contains(&"Outer rejected") && !names.contains(&"Inner rejected")); +} + #[test] fn a_small_deck_reads_into_the_model() { let bytes = deck(); diff --git a/crates/ps/src/read/interp.rs b/crates/ps/src/read/interp.rs index 1f4e7e1408..085b342f23 100644 --- a/crates/ps/src/read/interp.rs +++ b/crates/ps/src/read/interp.rs @@ -153,6 +153,9 @@ const MAX_GSTACK: usize = 10_000; const MAX_NAME_DEPTH: usize = 48; const MAX_CALL_DEPTH: usize = 48; +/// A dictionary entry's previous state recorded for `restore`: (dict, key, previous entry). +type JournalEntry = (PDict, crate::read::obj::Key, Option<(Obj, Obj)>); + pub struct Interp { pub o: Vec, pub d: Vec, @@ -162,6 +165,10 @@ pub struct Interp { pub gstack: Vec, /// Graphics-state depths that `save` objects restore to. pub saves: Vec, + /// Journal lengths at each open `save`, so `restore` puts dictionary entries back. + pub journal_marks: Vec, + /// Dictionary entries changed while a `save` is open: (dict, key, previous entry). + pub journal: Vec, pub gstates: Vec, pub systemdict: PDict, pub globaldict: PDict, @@ -216,6 +223,8 @@ impl Interp { gs: GState::default(), gstack: Vec::new(), saves: Vec::new(), + journal_marks: Vec::new(), + journal: Vec::new(), gstates: Vec::new(), systemdict, globaldict, @@ -728,6 +737,26 @@ impl Interp { self.gs = g; } } + + /// Put `key -> value` in `dict`, journaling the prior entry while a `save` is open. + pub fn dict_put(&mut self, dict: &PDict, key: Obj, value: Obj) -> R { + let (k, old) = dict.put_ret(key, value); + if !self.saves.is_empty() { + self.alloc(2 * std::mem::size_of::())?; + self.journal.push((dict.clone(), k, old)); + } + Ok(()) + } + + /// Remove `key` from `dict`, journaling the prior entry while a `save` is open. + pub fn dict_remove(&mut self, dict: &PDict, key: &crate::read::obj::Key) -> R { + let old = dict.remove_ret(key); + if !self.saves.is_empty() && old.is_some() { + self.alloc(2 * std::mem::size_of::())?; + self.journal.push((dict.clone(), key.clone(), old)); + } + Ok(()) + } } /// A six-number array as a matrix. diff --git a/crates/ps/src/read/lex.rs b/crates/ps/src/read/lex.rs index c8f81add7c..6c08bf5fce 100644 --- a/crates/ps/src/read/lex.rs +++ b/crates/ps/src/read/lex.rs @@ -252,6 +252,13 @@ impl<'a> Lexer<'a> { out.push(b); } b'\\' => self.string_escape(&mut out)?, + // PLRM §3.8 treats an unescaped CR or CRLF as one LF inside a string. + b'\r' => { + if self.peek() == Some(b'\n') { + self.pos += 1; + } + out.push(b'\n'); + } _ => out.push(b), } } @@ -391,6 +398,17 @@ mod tests { assert_eq!(lex.rest(), b"TA"); } + #[test] + fn literal_string_line_endings_preserve_currentfile_data() { + for eol in [b"\n".as_slice(), b"\r", b"\r\n"] { + let source = [b"(first".as_slice(), eol, b"second\\", eol, b"third\\r\\015)", b"\r\nA\r\nB"].concat(); + let mut lex = Lexer::new(&source); + assert_eq!(lex.next(), Ok(Some(Token::Str(b"first\nsecondthird\r\r".to_vec()))), "line ending {eol:?}"); + assert_eq!(lex.rest(), b"\r\nA\r\nB"); + assert_eq!(lex.data(), b"A\r\nB"); + } + } + #[test] fn partial_lines_and_eof() { let mut lex = Lexer::new(b"1 2 add"); diff --git a/crates/ps/src/read/obj.rs b/crates/ps/src/read/obj.rs index 411450123a..71d4b36bea 100644 --- a/crates/ps/src/read/obj.rs +++ b/crates/ps/src/read/obj.rs @@ -158,6 +158,12 @@ impl PDict { self.0.borrow_mut().map.insert(k, (key, v)); } + pub fn put_ret(&self, key: Obj, v: Obj) -> (Key, Option<(Obj, Obj)>) { + let k = key.key(); + let old = self.0.borrow_mut().map.insert(k.clone(), (key, v)); + (k, old) + } + pub fn put_name(&self, n: &[u8], v: Obj) { self.put(Obj::Name(name(n), false), v); } @@ -166,6 +172,18 @@ impl PDict { self.0.borrow_mut().map.remove(k); } + pub fn remove_ret(&self, k: &Key) -> Option<(Obj, Obj)> { + self.0.borrow_mut().map.remove(k) + } + + pub fn restore_entry(&self, k: Key, old: Option<(Obj, Obj)>) { + let mut inner = self.0.borrow_mut(); + match old { + Some(entry) => inner.map.insert(k, entry), + None => inner.map.remove(&k), + }; + } + pub fn len(&self) -> usize { self.0.borrow().map.len() } diff --git a/crates/ps/src/read/ops/basic.rs b/crates/ps/src/read/ops/basic.rs index 7177bd7f1b..89c922c39b 100644 --- a/crates/ps/src/read/ops/basic.rs +++ b/crates/ps/src/read/ops/basic.rs @@ -68,7 +68,7 @@ pub fn copy(ip: &mut Interp) -> R { ip.charge(src.len() as u64)?; ip.alloc(src.len().saturating_mul(2 * OBJ_BYTES))?; for (k, v) in src.entries() { - dst.put(k, v); + ip.dict_put(&dst, k, v)?; } ip.push(Obj::Dict(dst)) } @@ -739,8 +739,8 @@ pub fn def(ip: &mut Interp) -> R { let k = ip.pop()?; key_cost(ip, &k)?; ip.alloc(2 * OBJ_BYTES)?; - ip.current_dict()?.put(k, v); - Ok(()) + let d = ip.current_dict()?; + ip.dict_put(&d, k, v) } pub fn load(ip: &mut Interp) -> R { @@ -759,8 +759,7 @@ pub fn store(ip: &mut Interp) -> R { key_cost(ip, &k)?; let key = k.key(); let d = ip.d.iter().rev().find(|d| d.known(&key)).cloned().map_or_else(|| ip.current_dict(), Ok)?; - d.put(k, v); - Ok(()) + ip.dict_put(&d, k, v) } pub fn get(ip: &mut Interp) -> R { @@ -802,8 +801,7 @@ pub fn put(ip: &mut Interp) -> R { Obj::Dict(d) => { key_cost(ip, &k)?; ip.alloc(2 * OBJ_BYTES)?; - d.put(k, v); - Ok(()) + ip.dict_put(&d, k, v) } Obj::Array(a, _) => { let i = usize::try_from(int_of(&k)?).map_err(|_| PsErr::Ps("rangecheck"))?; @@ -829,8 +827,7 @@ pub fn undef(ip: &mut Interp) -> R { let k = ip.pop()?; key_cost(ip, &k)?; let d = ip.pop_dict()?; - d.remove(&k.key()); - Ok(()) + ip.dict_remove(&d, &k.key()) } pub fn where_(ip: &mut Interp) -> R { diff --git a/crates/ps/src/read/ops/gfx.rs b/crates/ps/src/read/ops/gfx.rs index 489c9fe860..24fddd3e33 100644 --- a/crates/ps/src/read/ops/gfx.rs +++ b/crates/ps/src/read/ops/gfx.rs @@ -35,6 +35,7 @@ pub fn initgraphics(ip: &mut Interp) -> R { pub fn save(ip: &mut Interp) -> R { ip.gsave()?; ip.saves.push(ip.gstack.len()); + ip.journal_marks.push(ip.journal.len()); let n = ip.saves.len(); ip.push(Obj::Save(n)) } @@ -45,7 +46,12 @@ pub fn restore(ip: &mut Interp) -> R { return err("invalidrestore"); } let depth = ip.saves.get(n - 1).copied().unwrap_or(0); + let mark = ip.journal_marks.get(n - 1).copied().unwrap_or(0); ip.saves.truncate(n - 1); + ip.journal_marks.truncate(n - 1); + for (dict, key, old) in ip.journal.drain(mark..).rev() { + dict.restore_entry(key, old); + } // Back to the state saved with it (save did a gsave, leaving `depth` states stacked). while ip.gstack.len() >= depth.max(1) { let Some(g) = ip.gstack.pop() else { break }; diff --git a/crates/ps/src/read/tests.rs b/crates/ps/src/read/tests.rs index c694a71771..b1345e93aa 100644 --- a/crates/ps/src/read/tests.rs +++ b/crates/ps/src/read/tests.rs @@ -776,3 +776,47 @@ fn the_web_gets_smaller_default_limits() { assert!(l.memory <= 1 << 30 && l.steps <= 50_000_000); } } + +#[test] +fn restore_undoes_dictionary_changes() { + let (_, conv) = run("/Depth 2 dict def Depth /open 0 put \ + /enter { save Depth /open get 1 add dup 8 gt { rangecheck } if Depth exch /open exch put } def \ + 1 1 50 { pop enter 0 0 1 1 rectfill restore } for \ + Depth /open get 0 eq { 10 10 5 5 rectfill } if"); + assert!(conv.warnings.is_empty(), "{:?}", conv.warnings); + + let (c, conv) = run("/a 1 def /d 2 dict def d /k 1 put save /a 2 def /b 3 def d /k 2 put d /k undef \ + 1 dict dup /z 9 put d copy pop /a 4 store restore \ + a 1 eq /b where not and d /k get 1 eq and d /z known not and { 0 0 10 10 rectfill } if"); + assert!(conv.warnings.is_empty(), "{:?}", conv.warnings); + assert!(c.lines().any(|l| l == "f"), "{c}"); + + let (c, _) = run("save dup restore { restore } stopped { 0 0 10 10 rectfill } if"); + assert!(c.lines().any(|l| l == "f"), "{c}"); +} + +#[test] +fn prolog_keeps_builtin_cmyk_with_where() { + let (c, conv) = run("/setcmykcolor where { pop } { /setcmykcolor { pop pop pop pop 0 1 0 setrgbcolor } def } ifelse \ + 0 1 1 0 setcmykcolor 0 0 10 10 rectfill"); + assert!(conv.warnings.is_empty(), "{:?}", conv.warnings); + assert!(c.contains("0 1 1 0 k\n"), "{c}"); + + let (c, conv) = run("0.1 0.2 0.3 0.4 setcmykcolor currentcmykcolor \ + 0.4 eq exch 0.3 eq and exch 0.2 eq and exch 0.1 eq and { 0 0 10 10 rectfill } if"); + assert!(conv.warnings.is_empty(), "{:?}", conv.warnings); + assert!(c.lines().any(|l| l == "f"), "{c}"); +} + +#[test] +fn readline_partial_line_and_eof() { + let (c, conv) = run("/s 16 string def currentfile 0 (END) /SubFileDecode filter s readline\n\ + okEND { (ok) eq { 0 0 10 10 rectfill } if } { pop } ifelse"); + assert!(conv.warnings.is_empty(), "{:?}", conv.warnings); + assert!(c.lines().any(|l| l == "f"), "{c}"); + + let (c, conv) = run("/s 16 string def currentfile 0 (END) /SubFileDecode filter s readline\n\ + END not exch length 0 eq and { 0 0 10 10 rectfill } if"); + assert!(conv.warnings.is_empty(), "{:?}", conv.warnings); + assert!(c.lines().any(|l| l == "f"), "{c}"); +} diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index 987b306b4d..6740933900 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -514,15 +514,24 @@ fn read_count(r: &mut Reader<'_>, v: Version) -> Result { Ok(if v.is_psb() { r.u32()? as usize } else { r.u16()? as usize }) } +/// Reads `rows` RLE byte-count entries (`u16` for PSD, `u32` for PSB) from `data`, +/// returning the parsed counts and the remaining row-payload slice. +pub fn read_rle_row_counts(data: &[u8], rows: usize, version: Version) -> Result<(Vec, &[u8])> { + let mut r = Reader::new(data); + let count_size = if version.is_psb() { 4 } else { 2 }; + r.check_count(rows as u64, count_size as u64)?; + let mut counts = Vec::with_capacity(rows); + for _ in 0..rows { + counts.push(read_count(&mut r, version)?); + } + Ok((counts, r.peek_rest())) +} + fn decode_rle(data: &[u8], layout: &PlaneLayout, total: usize) -> Result> { let rows = layout.rows()?; let rb = layout.row_bytes(); - let mut r = Reader::new(data); - r.check_count(rows as u64, layout.count_size() as u64)?; - let mut counts = Vec::with_capacity(rows); - for _ in 0..rows { - counts.push(read_count(&mut r, layout.version)?); - } + let (counts, rest) = read_rle_row_counts(data, rows, layout.version)?; + let mut r = Reader::new(rest); // PackBits expands at most 64x (2 input bytes -> 128 output bytes). if (total as u64) > (r.remaining() as u64).saturating_mul(64) { return Err(PsdError::Decompress("RLE data too short for declared size".into())); @@ -742,6 +751,147 @@ pub fn zip_decompress(data: &[u8], expected: usize) -> Result> { Ok(out) } +/// Decompresses a zlib stream up to `limit` output bytes, verifying the zlib trailer +/// when the stream ends within `limit`. +/// +/// Unlike [`zip_decompress`], a stream that ends cleanly with fewer than `limit` bytes +/// returns the bytes produced so far so callers can apply their own recovery (such as +/// zero-padding a short layer channel). Corrupt streams, bad Adler-32 checksums, or +/// streams that produce more than `limit` bytes return an error. +pub fn zip_decompress_up_to(data: &[u8], limit: usize) -> Result> { + const OOM: PsdError = PsdError::OutOfMemory("not enough memory for the decoded channel data"); + let mut decoder = flate2::Decompress::new(true); + let mut out = Vec::new(); + out.try_reserve_exact(limit.min(data.len().saturating_mul(1032))).map_err(|_| OOM)?; + let mut buf = vec![0u8; limit.clamp(8192, 1 << 20)]; + loop { + let before = (decoder.total_in(), decoder.total_out()); + let input = data.get(before.0 as usize..).ok_or_else(|| PsdError::Decompress("zlib input overflow".into()))?; + let status = decoder.decompress(input, &mut buf, flate2::FlushDecompress::None).map_err(|e| PsdError::Decompress(e.to_string()))?; + let got = decoder.total_out(); + if got > limit as u64 { + return Err(PsdError::LimitExceeded("zlib output exceeds caller limit")); + } + let n = (got - before.1) as usize; + out.try_reserve(n).map_err(|_| OOM)?; + out.extend_from_slice(buf.get(..n).ok_or_else(|| PsdError::Decompress("zlib output overflow".into()))?); + if status == flate2::Status::StreamEnd { + return Ok(out); + } + if before == (decoder.total_in(), got) { + return Err(PsdError::Decompress("incomplete zlib stream".into())); + } + } +} + +/// Staged access to a sequence of encoded image planes (e.g. a single layer channel or +/// a multi-plane merged image). +/// +/// Unlike [`decode_planes`], this lets callers: +/// - borrow uncompressed (`Raw`) planes directly from the input slice without copying, +/// - read only a prefix of `total_planes` (for example skipping trailing spot channels), +/// - supply their own per-plane allocation, memory budget, and RLE/ZIP recovery policy. +#[derive(Debug, Clone)] +pub enum PlaneStream<'a> { + /// Uncompressed planes: each [`Self::next_raw_plane`] borrows `plane_bytes` from `rest`. + Raw { + /// Remaining unread bytes. + rest: &'a [u8], + }, + /// PackBits RLE planes: `counts` holds `total_planes * height` row byte counts, followed by `rest`. + Rle { + /// Per-row byte counts for all planes, plane after plane. + counts: Vec, + /// Remaining unread row payload bytes. + rest: &'a [u8], + }, + /// Inflated ZIP data holding consecutive planes. + Zip { + /// Inflated bytes (at most `zip_limit`). + data: Vec, + }, +} + +impl<'a> PlaneStream<'a> { + /// Prepares a plane stream from `data` (positioned immediately after the 2-byte compression field). + /// + /// For RLE, reads the `total_planes * height` row-count table. For ZIP/ZIP-with-prediction, + /// invokes `before_zip(zip_limit)` (allowing callers to charge a memory budget before + /// allocation) and inflates up to `zip_limit` bytes via [`zip_decompress_up_to`]. + pub fn open( + compression: Compression, + data: &'a [u8], + total_planes: usize, + height: usize, + version: Version, + zip_limit: usize, + before_zip: impl FnOnce(usize) -> Result<()>, + ) -> Result { + match compression { + Compression::Raw => Ok(Self::Raw { rest: data }), + Compression::Rle => { + let total_rows = total_planes.checked_mul(height).ok_or(PsdError::LimitExceeded("row count overflow"))?; + let (counts, rest) = read_rle_row_counts(data, total_rows, version)?; + Ok(Self::Rle { counts, rest }) + } + Compression::Zip | Compression::ZipPrediction => { + before_zip(zip_limit)?; + Ok(Self::Zip { data: zip_decompress_up_to(data, zip_limit)? }) + } + Compression::Unknown(c) => Err(PsdError::Unsupported(format!("compression method {c}"))), + } + } + + /// Borrows the next `plane_bytes` from a `Raw` stream, advancing past it. + pub fn next_raw_plane(&mut self, plane_bytes: usize) -> Result<&'a [u8]> { + let Self::Raw { rest } = self else { + return Err(PsdError::invalid("expected raw plane stream")); + }; + if rest.len() < plane_bytes { + return Err(PsdError::UnexpectedEof { offset: rest.len(), needed: plane_bytes - rest.len() }); + } + let (head, tail) = rest.split_at(plane_bytes); + *rest = tail; + Ok(head) + } + + /// Decodes `height` RLE rows of `plane_index` into `out`, advancing past their payload bytes. + /// + /// When `padded` is true, uses [`packbits::decode_padded_into`] (zero-padding short rows and + /// clipping oversized packets); otherwise uses strict PackBits decoding. + pub fn next_rle_plane_into(&mut self, plane_index: usize, row_bytes: usize, height: usize, padded: bool, out: &mut Vec) -> Result<()> { + let Self::Rle { counts, rest } = self else { + return Err(PsdError::invalid("expected RLE plane stream")); + }; + let base = plane_index.checked_mul(height).ok_or(PsdError::LimitExceeded("row count overflow"))?; + for row in 0..height { + let n = *counts.get(base + row).ok_or(PsdError::UnexpectedEof { offset: 0, needed: 1 })?; + if rest.len() < n { + return Err(PsdError::UnexpectedEof { offset: rest.len(), needed: n - rest.len() }); + } + let (src, tail) = rest.split_at(n); + *rest = tail; + if padded { + packbits::decode_padded_into(src, row_bytes, row_bytes, out)?; + } else { + packbits::decode_into(src, row_bytes, out)?; + } + } + Ok(()) + } + + /// Returns a mutable slice of `plane_bytes` for `plane_index` in a `Zip` stream. + pub fn zip_plane_mut(&mut self, plane_index: usize, plane_bytes: usize) -> Result<&mut [u8]> { + let Self::Zip { data } = self else { + return Err(PsdError::invalid("expected ZIP plane stream")); + }; + let start = plane_index.checked_mul(plane_bytes).ok_or(PsdError::LimitExceeded("plane offset overflow"))?; + let end = start.checked_add(plane_bytes).ok_or(PsdError::LimitExceeded("plane offset overflow"))?; + let len = data.len(); + data.get_mut(start..end).ok_or(PsdError::UnexpectedEof { offset: len, needed: end.saturating_sub(len) }) + } +} + /// Applies horizontal delta prediction in place (encoder side). /// /// * 1/8-bit: byte-wise delta per row. diff --git a/crates/psd/src/compression/tests.rs b/crates/psd/src/compression/tests.rs index 5f162dea71..dc378efcf5 100644 --- a/crates/psd/src/compression/tests.rs +++ b/crates/psd/src/compression/tests.rs @@ -870,3 +870,64 @@ fn packbits_slice_roundtrips_all_packet_lengths() { } } } + +#[test] +fn rle_row_counts_parse_psd_and_psb_and_reject_short_tables() { + let psd = [0, 3, 0, 5, 1, 2, 3]; + let (counts, rest) = read_rle_row_counts(&psd, 2, Version::Psd).unwrap(); + assert_eq!(counts, vec![3, 5]); + assert_eq!(rest, &[1, 2, 3]); + assert!(matches!(read_rle_row_counts(&psd[..3], 2, Version::Psd), Err(PsdError::UnexpectedEof { .. }))); + + let psb = [0, 0, 0, 3, 0, 1, 0, 0, 9]; + let (counts, rest) = read_rle_row_counts(&psb, 2, Version::Psb).unwrap(); + assert_eq!(counts, vec![3, 0x10000]); + assert_eq!(rest, &[9]); + assert!(matches!(read_rle_row_counts(&psb[..7], 2, Version::Psb), Err(PsdError::UnexpectedEof { .. }))); +} + +#[test] +fn zip_decompress_up_to_enforces_limit_and_verifies_trailer() { + let payload: Vec = (0..1024).map(|i| (i * 17 % 251) as u8).collect(); + let compressed = zip_compress(&payload); + + assert_eq!(zip_decompress_up_to(&compressed, payload.len()).unwrap(), payload); + assert_eq!(zip_decompress_up_to(&compressed, payload.len() * 2).unwrap(), payload); + assert!(matches!(zip_decompress_up_to(&compressed, payload.len() - 1), Err(PsdError::LimitExceeded(_)))); + + let mut bad_adler = compressed.clone(); + let last = bad_adler.len() - 1; + bad_adler[last] ^= 0xff; + assert!(matches!(zip_decompress_up_to(&bad_adler, payload.len()), Err(PsdError::Decompress(_)))); + assert!(matches!(zip_decompress_up_to(&compressed[..compressed.len() / 2], payload.len()), Err(PsdError::Decompress(_)))); +} + +#[test] +fn plane_stream_stages_raw_rle_and_zip_planes() { + let raw_bytes = [1u8, 2, 3, 4, 5, 6]; + let mut raw_stream = PlaneStream::open(Compression::Raw, &raw_bytes, 3, 2, Version::Psd, 0, |_| Ok(())).unwrap(); + assert_eq!(raw_stream.next_raw_plane(2).unwrap(), &[1, 2]); + assert_eq!(raw_stream.next_raw_plane(2).unwrap(), &[3, 4]); + + // Two RLE planes (2 rows x 2 bytes each); first row of plane 0 is short for padded recovery. + let mut rle_data = vec![0, 2, 0, 2, 0, 2, 0, 2]; + rle_data.extend_from_slice(&[0, 9]); // 1 byte literal, zero-padded to 2 when padded=true + rle_data.extend_from_slice(&[255, 8]); // 2 copies of 8 + rle_data.extend_from_slice(&[255, 7]); + rle_data.extend_from_slice(&[255, 6]); + let mut rle_stream = PlaneStream::open(Compression::Rle, &rle_data, 2, 2, Version::Psd, 0, |_| Ok(())).unwrap(); + let mut plane0 = Vec::new(); + rle_stream.next_rle_plane_into(0, 2, 2, true, &mut plane0).unwrap(); + assert_eq!(plane0, vec![9, 0, 8, 8]); + let mut plane1 = Vec::new(); + rle_stream.next_rle_plane_into(1, 2, 2, false, &mut plane1).unwrap(); + assert_eq!(plane1, vec![7, 7, 6, 6]); + + let zip_src = zip_compress(&[10, 20, 30, 40]); + let refused = PlaneStream::open(Compression::Zip, &zip_src, 2, 1, Version::Psd, 4, |_| Err(PsdError::LimitExceeded("budget"))); + assert!(matches!(refused, Err(PsdError::LimitExceeded("budget")))); + + let mut zip_stream = PlaneStream::open(Compression::Zip, &zip_src, 2, 1, Version::Psd, 4, |_| Ok(())).unwrap(); + assert_eq!(zip_stream.zip_plane_mut(0, 2).unwrap(), &[10, 20]); + assert_eq!(zip_stream.zip_plane_mut(1, 2).unwrap(), &[30, 40]); +} diff --git a/crates/psd/src/resources.rs b/crates/psd/src/resources.rs index 8eefaf25a3..eee74e1a62 100644 --- a/crates/psd/src/resources.rs +++ b/crates/psd/src/resources.rs @@ -99,7 +99,9 @@ impl<'a> ImageResourceView<'a> { r.skip(name_pad)?; let len = r.u32()?; let data = r.bytes_u64(u64::from(len))?; - if len % 2 == 1 { + // A writer that drops the pad byte after the section's last resource is common; that + // byte would be past the section, so don't fail the whole file over it. + if len % 2 == 1 && !r.is_empty() { r.skip(1)?; } Ok(ImageResourceView { signature, id, name, data }) @@ -517,6 +519,19 @@ mod tests { assert_eq!(roundtrip(&[]), vec![0, 0, 0, 0]); } + /// The last resource of the section has odd data and no pad byte (some writers drop it): + /// the resource still reads instead of the whole file failing. + #[test] + fn odd_last_resource_without_pad() { + let mut out = Vec::new(); + write_section(&mut out, &[ImageResource::new(1000, vec![1, 2, 3])]).unwrap(); + out.pop(); + let len = u32::from_be_bytes([out[0], out[1], out[2], out[3]]) - 1; + out[..4].copy_from_slice(&len.to_be_bytes()); + let back = read_section(&mut Reader::new(&out)).unwrap(); + assert_eq!(back, [ImageResource::new(1000, vec![1, 2, 3])]); + } + #[test] fn odd_data_is_padded() { let out = roundtrip(&[ImageResource::new(1000, vec![1, 2, 3])]); diff --git a/crates/raw/README.md b/crates/raw/README.md index d709e7047e..7bc57fdca5 100644 --- a/crates/raw/README.md +++ b/crates/raw/README.md @@ -248,6 +248,20 @@ sequence. It is empty for images without a CFA. Active area and crop are `x,y,wi crop coordinates relative to the active area. Orientation is the Exif integer code, and baseline exposure is the `f64` bit pattern as 16 lowercase hexadecimal digits. +Use `--linearization` before the paths to select schema version 2: + +```sh +cargo run --quiet --locked --release -p craft-raw --example decode_report -- --linearization fixture-a.dng fixture-b.dng > report.tsv +``` + +Schema 2 appends `linearization_state` and `linearization_table_sha256`. The state is `absent`, +`applied`, or `deferred`. A deferred table is carried by the decoder for application after DNG +`OpcodeList1`. The digest hashes all decoded table entries in index order as little-endian `u16` +values. It is empty when the table is absent. Both fields are empty for failed inputs. The sample +digest still describes `RawImage::data`, so two deferred inputs with identical stored samples can +have the same sample digest and different table digests. Use a `--` separator before the paths to +pass a path literally when its name matches an option. + Each row's status is `ok`, `read_error`, `input_limit`, `not_raw`, `unsupported`, `corrupt`, `decode_limit`, or `tiff_error`. `input_limit` means the encoded-byte cap was exceeded. `decode_limit` covers RAW and TIFF decoder limits. A failed input has empty fields after `status`, @@ -259,10 +273,14 @@ To compare two pinned decoder revisions, use separate clean checkouts and keep t enabled features, and ordered fixture list identical. If a revision predates the example, copy both `examples/decode_report/main.rs` and `examples/decode_report/report.rs` at the same relative paths under that checkout's `crates/raw/` directory. The example uses the crate's existing `sha2` dev -dependency. It builds on `main` from +dependency. The schema 2-capable example requires +[`a99c8f8e`](https://github.com/storytold/craft-libs/commit/a99c8f8e366363ac5ff2f1eee535751610c2c82c) +or later for `RawImage::linearization_table`. For comparisons involving an older decoder, use +both example files from [#2417](https://github.com/storytold/craft-libs/pull/2417) in each checkout +to produce schema 1. Those files require [`ecee6933`](https://github.com/storytold/craft-libs/commit/ecee693322c27acdbcafed4b57066356404e8378) -(#1171, 2026-11-13) onwards, the first revision whose `Cfa` has `origin_x` and `origin_y`. Older -revisions fail to build it. Build and save one report from each checkout, then compare them. +or later for `Cfa::origin_x` and `Cfa::origin_y`. Build and save one report from each checkout, then +compare them. ```sh git diff --no-index -- before.tsv after.tsv diff --git a/crates/raw/examples/decode_report/main.rs b/crates/raw/examples/decode_report/main.rs index 94b7225623..7ca4feb50a 100644 --- a/crates/raw/examples/decode_report/main.rs +++ b/crates/raw/examples/decode_report/main.rs @@ -1,5 +1,5 @@ //! Report the decoded samples and selected metadata of explicitly supplied RAW files. -//! `cargo run --locked -p craft-raw --example decode_report -- [ ...]` +//! `cargo run --locked -p craft-raw --example decode_report -- [--linearization] [--] [ ...]` #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] @@ -20,7 +20,7 @@ fn main() -> std::process::ExitCode { let mut err = stderr.lock(); match error { report::RunError::Usage => { - let _ = writeln!(err, "usage: decode_report [ ...]"); + let _ = writeln!(err, "usage: decode_report [--linearization] [--] [ ...]"); } report::RunError::Output(error) => { let _ = writeln!(err, "decode_report: report output failed ({:?})", error.kind()); diff --git a/crates/raw/examples/decode_report/report.rs b/crates/raw/examples/decode_report/report.rs index 2d0c14dc05..b5da78e4e2 100644 --- a/crates/raw/examples/decode_report/report.rs +++ b/crates/raw/examples/decode_report/report.rs @@ -8,8 +8,23 @@ use craft_tiff::TiffError; use sha2::{Digest, Sha256}; pub(super) const MAX_INPUT_BYTES: u64 = 512 * 1024 * 1024; -const SCHEMA: u8 = 1; const HEADER: &str = "schema\tinput\tstatus\tformat\tsample_type\tsample_count\tsensor_sha256\twidth\theight\tcpp\tbits\tcfa\tactive_area\tcrop\torientation\tbaseline_exposure_bits"; +const LINEARIZATION_HEADER: &str = "\tlinearization_state\tlinearization_table_sha256"; + +#[derive(Clone, Copy)] +enum Schema { + Original, + Linearization, +} + +impl Schema { + fn version(self) -> u8 { + match self { + Self::Original => 1, + Self::Linearization => 2, + } + } +} #[derive(Debug)] pub(super) enum RunError { @@ -17,12 +32,15 @@ pub(super) enum RunError { Output(io::Error), } -pub(super) fn run(paths: impl IntoIterator, out: &mut impl Write, max_input_bytes: u64, limits: &Limits) -> Result<(), RunError> { - let mut paths = paths.into_iter().peekable(); +pub(super) fn run(args: impl IntoIterator, out: &mut impl Write, max_input_bytes: u64, limits: &Limits) -> Result<(), RunError> { + let mut paths = args.into_iter().peekable(); + let (schema, extra_header) = + if paths.next_if(|arg| arg == "--linearization").is_some() { (Schema::Linearization, LINEARIZATION_HEADER) } else { (Schema::Original, "") }; + paths.next_if(|arg| arg == "--"); if paths.peek().is_none() { return Err(RunError::Usage); } - writeln!(out, "{HEADER}").map_err(RunError::Output)?; + writeln!(out, "{HEADER}{extra_header}").map_err(RunError::Output)?; for (index, path) in paths.enumerate() { let input = index + 1; let result = read_input(Path::new(&path), max_input_bytes) @@ -32,8 +50,8 @@ pub(super) fn run(paths: impl IntoIterator, out: &mut impl Writ }) .and_then(|bytes| craft_raw::decode_with(&bytes, limits).map_err(decode_status)); match result { - Ok(raw) => write_success(out, input, &raw), - Err(status) => write_failure(out, input, status), + Ok(raw) => write_success(out, schema, input, &raw), + Err(status) => write_failure(out, schema, input, status), } .map_err(RunError::Output)?; } @@ -79,12 +97,13 @@ fn decode_status(error: RawError) -> &'static str { } } -fn write_failure(out: &mut impl Write, input: usize, status: &str) -> io::Result<()> { - // Keep all 13 success-only fields present and empty. - writeln!(out, "{SCHEMA}\t{input}\t{status}\t\t\t\t\t\t\t\t\t\t\t\t\t") +fn write_failure(out: &mut impl Write, schema: Schema, input: usize, status: &str) -> io::Result<()> { + // Keep the success-only fields present and empty in both schemas. + let extra_fields = if let Schema::Linearization = schema { "\t\t" } else { "" }; + writeln!(out, "{}\t{input}\t{status}\t\t\t\t\t\t\t\t\t\t\t\t\t{extra_fields}", schema.version()) } -fn write_success(out: &mut impl Write, input: usize, raw: &RawImage) -> io::Result<()> { +fn write_success(out: &mut impl Write, schema: Schema, input: usize, raw: &RawImage) -> io::Result<()> { let mut hash = Sha256::new(); let (sample_type, count) = match &raw.data { RawData::U16(samples) => { @@ -103,7 +122,8 @@ fn write_success(out: &mut impl Write, input: usize, raw: &RawImage) -> io::Resu let digest = hash.finalize(); write!( out, - "{SCHEMA}\t{input}\tok\t{}\t{sample_type}\t{count}\t{digest:x}\t{}\t{}\t{}\t{}\t", + "{}\t{input}\tok\t{}\t{sample_type}\t{count}\t{digest:x}\t{}\t{}\t{}\t{}\t", + schema.version(), format_label(raw.format), raw.width, raw.height, @@ -122,7 +142,23 @@ fn write_success(out: &mut impl Write, input: usize, raw: &RawImage) -> io::Resu } write_rect(out, raw.active_area)?; write_rect(out, raw.crop)?; - writeln!(out, "\t{}\t{:016x}", raw.orientation.to_exif(), raw.color.baseline_exposure.to_bits()) + write!(out, "\t{}\t{:016x}", raw.orientation.to_exif(), raw.color.baseline_exposure.to_bits())?; + if let Schema::Linearization = schema { + write_linearization(out, raw)?; + } + writeln!(out) +} + +fn write_linearization(out: &mut impl Write, raw: &RawImage) -> io::Result<()> { + let Some(table) = &raw.linearization_table else { + return write!(out, "\tabsent\t"); + }; + let state = if raw.linearized { "applied" } else { "deferred" }; + let mut hash = Sha256::new(); + for entry in table { + hash.update(entry.to_le_bytes()); + } + write!(out, "\t{state}\t{:x}", hash.finalize()) } fn write_rect(out: &mut impl Write, rect: Rect) -> io::Result<()> { diff --git a/crates/raw/tests/it/decode_report.rs b/crates/raw/tests/it/decode_report.rs index 3d43a1db26..b98a08ccf3 100644 --- a/crates/raw/tests/it/decode_report.rs +++ b/crates/raw/tests/it/decode_report.rs @@ -1,4 +1,5 @@ -use super::dng::{base_ifd, dng, synthetic}; +use super::dng::{base_ifd, dng, synthetic, u16_bytes}; +use craft_raw::opcodes::{self, Area, Opcode}; use craft_raw::{BlackLevel, Cfa, DngCompression, DngWriteOptions, Limits, Orientation, RawData, RawImage, write_dng}; use craft_tiff::{ByteOrder, ImageData, Value, tags}; use std::ffi::OsString; @@ -122,6 +123,77 @@ fn report_rows(text: &str) -> Vec> { .collect() } +fn linearization_dng(table: Option>, deferred: bool, order: ByteOrder) -> Vec { + let mut raw = base_ifd(4, 2, 16, 1, true); + raw.set_image(ImageData::Strips { rows_per_strip: 2, strips: vec![u16_bytes(&[2; 8], order)] }); + raw.set(tags::WHITE_LEVEL, Value::Long(vec![30])); + if let Some(table) = table { + raw.set(tags::LINEARIZATION_TABLE, Value::Short(table)); + } + if deferred { + let area = Area { top: 0, left: 0, bottom: 2, right: 4, plane: 0, planes: 1, row_pitch: 1, col_pitch: 1 }; + let list = opcodes::write_list(&[Opcode::MapTable { area, table: vec![0, 1, 3, 3] }]); + raw.set(tags::OPCODE_LIST_1, Value::Undefined(list)); + } + dng(raw, order) +} + +#[test] +fn reports_linearization_state_and_digest_separately_from_samples() { + let fixtures = FixtureDir::new("linearization"); + let write = |name, table, deferred, order| write_bytes(fixtures.path(), name, &linearization_dng(table, deferred, order)); + let table = vec![0, 10, 20, 30]; + let paths = [ + OsString::from("--linearization"), + OsString::from("--"), + write("deferred.dng", Some(table.clone()), true, ByteOrder::Little), + write("changed-table.dng", Some(vec![0, 10, 20, 31]), true, ByteOrder::Little), + write("big-endian.dng", Some(table.clone()), true, ByteOrder::Big), + write("applied.dng", Some(table), false, ByteOrder::Little), + write("absent.dng", None, false, ByteOrder::Little), + fixtures.path().join("missing.dng").into_os_string(), + ]; + let original = String::from_utf8(run_report(&paths[2..4], report::MAX_INPUT_BYTES, &Limits::default())).unwrap(); + let original = report_rows(&original); + assert_eq!(original[0][2..], original[1][2..]); + let output = || run_report(&paths, report::MAX_INPUT_BYTES, &Limits::default()); + let text = String::from_utf8(output()).unwrap(); + let mut lines = text.lines(); + let header = format!("{}\tlinearization_state\tlinearization_table_sha256", HEADER.trim_end()); + assert_eq!(lines.next(), Some(header.as_str())); + assert_eq!(text.as_bytes(), output()); + let rows: Vec> = lines.map(|line| line.split('\t').collect()).collect(); + assert_eq!(rows.len(), 6); + for (index, row) in rows.iter().enumerate() { + assert_eq!(row.len(), 18); + assert_eq!(row[..2], ["2", &(index + 1).to_string()]); + } + + // Hashes from the four known u16 values packed as little-endian bytes. + let digest = "6e5d2a85c5e65eea7b6fde4ed812c7f22f3b41b99e76607a58a8141a254df12a"; + let changed = "138055ff13d0e163c85338c4221f468ee093cb792f7ecab41fd62abd3869a9c6"; + assert_eq!(rows[0][2..16], rows[1][2..16]); + assert_eq!(rows[0][2..], rows[2][2..]); + assert_eq!(rows[0][16..], ["deferred", digest]); + assert_eq!(rows[1][16..], ["deferred", changed]); + assert_eq!(rows[3][16..], ["applied", digest]); + assert_ne!(rows[3][6], rows[0][6]); + assert_eq!(rows[4][2], "ok"); + assert_eq!(rows[4][6], rows[0][6]); + assert_eq!(rows[4][16..], ["absent", ""]); + assert_eq!(rows[5][2], "read_error"); + assert!(rows[5][3..].iter().all(|field| field.is_empty())); +} + +#[test] +fn separator_allows_a_path_matching_the_linearization_option() { + let paths = [OsString::from("--"), OsString::from("--linearization")]; + let text = String::from_utf8(run_report(&paths, report::MAX_INPUT_BYTES, &Limits::default())).unwrap(); + let rows = report_rows(&text); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0][..2], ["1", "1"]); +} + #[test] fn reports_mixed_failures_and_keeps_the_last_success() { let fixtures = FixtureDir::new("mixed"); @@ -184,11 +256,13 @@ fn separates_encoded_file_and_shared_decoder_limits() { } #[test] -fn empty_arguments_report_usage_without_writing_a_header() { - let mut output = Vec::new(); - let result = report::run([], &mut output, report::MAX_INPUT_BYTES, &Limits::default()); - assert!(matches!(result, Err(report::RunError::Usage))); - assert!(output.is_empty()); +fn missing_paths_report_usage_without_writing_a_header() { + for args in [&[][..], &["--linearization"], &["--"], &["--linearization", "--"]] { + let mut output = Vec::new(); + let result = report::run(args.iter().map(OsString::from), &mut output, report::MAX_INPUT_BYTES, &Limits::default()); + assert!(matches!(result, Err(report::RunError::Usage))); + assert!(output.is_empty()); + } } struct BrokenOutput { diff --git a/crates/sqlite/src/lib.rs b/crates/sqlite/src/lib.rs index a86c4bcbb9..1771113384 100644 --- a/crates/sqlite/src/lib.rs +++ b/crates/sqlite/src/lib.rs @@ -8,22 +8,88 @@ use core::fmt; +pub mod wal; + const MAX_VARINT_BYTES: usize = 9; +/// The b-tree cell layouts that carry payload bytes. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum PayloadKind { + /// A table leaf cell; table interior cells have no payload. + TableLeaf, + /// An index leaf or interior cell, which share the same payload thresholds. + Index, +} + +/// Return the number of payload bytes stored in the b-tree page before overflow. +/// +/// `usable` is the page size minus its reserved bytes, not the space remaining after the +/// cell header. It may be odd. Sizes outside 480..=65,536 return `None`; validating the +/// database header and bounding payload reads remain the caller's responsibility. +/// +/// This implements the [SQLite b-tree cell payload formula](https://www.sqlite.org/fileformat.html#b_tree_pages). +/// The calculation allocates nothing and accepts the full `u64` payload length without +/// implying that the payload fits in the database or in memory. +pub fn local_payload_len(usable: u32, payload_len: u64, kind: PayloadKind) -> Option { + // SQLite requires at least 480 usable bytes; this also keeps every divisor and + // subtraction below valid even when the caller supplies an untrusted header. + if !(480..=65_536).contains(&usable) { + return None; + } + let usable = u64::from(usable); + let maximum = match kind { + PayloadKind::TableLeaf => usable - 35, + PayloadKind::Index => (usable - 12) * 64 / 255 - 23, + }; + let local = if payload_len <= maximum { + payload_len + } else { + let minimum = (usable - 12) * 32 / 255 - 23; + let candidate = minimum + (payload_len - minimum) % (usable - 4); + if candidate <= maximum { candidate } else { minimum } + }; + // Both branches bound the result by the supported page's maximum local payload. + Some(local as u32) +} + /// A failure to decode part of a SQLite record or page. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Error { /// Input ended before the integer was complete. TruncatedVarint, + /// The record's declared header length excludes its prefix or extends beyond the payload. + InvalidRecordHeaderLength(u64), /// The serial type is reserved and has no defined field width. ReservedSerialType(u64), + /// The decoded database page size is not a power of two in `512..=65_536`. + InvalidPageSize(u32), + /// The usable page size (`page_size - reserved`) is below 480 bytes. + UsablePageSizeTooSmall(u32), + /// A B-tree page ended before its header or cell-pointer array completed. + TruncatedPage, + /// The B-tree page type byte is not a table or index interior/leaf page. + UnsupportedBtreePageType(u8), + /// A cell pointer falls outside `[pointers_end, usable)`. + InvalidCellPointer { offset: usize, min: usize, usable: usize }, + /// The requested cell index is outside the page's cell count. + CellIndexOutOfBounds { index: usize, cells: usize }, + /// A signed big-endian integer slice is empty or wider than 8 bytes. + InvalidIntegerWidth(usize), } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::TruncatedVarint => f.write_str("truncated SQLite varint"), + Self::InvalidRecordHeaderLength(length) => write!(f, "invalid SQLite record header length {length}"), Self::ReservedSerialType(code) => write!(f, "reserved SQLite serial type {code}"), + Self::InvalidPageSize(size) => write!(f, "invalid SQLite page size {size}"), + Self::UsablePageSizeTooSmall(usable) => write!(f, "usable SQLite page size {usable} is too small"), + Self::TruncatedPage => f.write_str("truncated SQLite B-tree page"), + Self::UnsupportedBtreePageType(kind) => write!(f, "unsupported SQLite B-tree page type 0x{kind:02x}"), + Self::InvalidCellPointer { offset, min, usable } => write!(f, "invalid SQLite cell pointer {offset} outside {min}..{usable}"), + Self::CellIndexOutOfBounds { index, cells } => write!(f, "SQLite cell index {index} out of bounds for {cells} cells"), + Self::InvalidIntegerWidth(width) => write!(f, "invalid SQLite signed integer width {width}"), } } } @@ -59,6 +125,31 @@ pub fn read_varint(input: &[u8]) -> Result<(u64, usize), Error> { Err(Error::TruncatedVarint) } +/// Split a SQLite record payload into its serial-type bytes and body. +/// +/// The [record header length](https://www.sqlite.org/fileformat.html#record_format) includes +/// the leading length varint. The returned serial-type slice excludes that varint and ends +/// before the body. The caller decodes serial types from that slice and checks field lengths. +/// +/// # Errors +/// +/// Returns [`Error::TruncatedVarint`] for an incomplete length and +/// [`Error::InvalidRecordHeaderLength`] for a size outside the supplied payload's bounds. +/// +/// ``` +/// use craft_sqlite::split_record; +/// +/// assert_eq!(split_record(&[2, 1, 42]), Ok((&[1][..], &[42][..]))); +/// ``` +pub fn split_record(payload: &[u8]) -> Result<(&[u8], &[u8]), Error> { + let (length, length_bytes) = read_varint(payload)?; + let invalid_length = Error::InvalidRecordHeaderLength(length); + let header_end = usize::try_from(length).map_err(|_| invalid_length)?; + let (header, body) = payload.split_at_checked(header_end).ok_or(invalid_length)?; + let serial_types = header.get(length_bytes..).ok_or(invalid_length)?; + Ok((serial_types, body)) +} + /// Return the encoded body width in bytes for a SQLite record serial type. /// /// The width is independent of the host's pointer size. The caller checks it against the @@ -85,3 +176,137 @@ pub const fn serial_type_len(serial_type: u64) -> Result { _ => Ok((serial_type - 12) / 2), } } + +/// Decode a raw big-endian 16-bit SQLite header page size (`1` represents `65_536`). +/// +/// # Errors +/// +/// Returns [`Error::InvalidPageSize`] when the decoded size is not a power of two in `512..=65_536`. +/// +/// ``` +/// use craft_sqlite::page_size_from_raw; +/// +/// assert_eq!(page_size_from_raw(1), Ok(65_536)); +/// assert_eq!(page_size_from_raw(4096), Ok(4096)); +/// ``` +pub const fn page_size_from_raw(raw: u16) -> Result { + let size = if raw == 1 { 65_536 } else { raw as u32 }; + if size < 512 || !size.is_power_of_two() { Err(Error::InvalidPageSize(size)) } else { Ok(size) } +} + +/// Compute the usable byte count of a SQLite page after subtracting `reserved` trailing bytes. +/// +/// # Errors +/// +/// Returns [`Error::UsablePageSizeTooSmall`] when `page_size - reserved < 480`. +pub const fn usable_page_size(page_size: u32, reserved: u8) -> Result { + let Some(usable) = page_size.checked_sub(reserved as u32) else { + return Err(Error::UsablePageSizeTooSmall(0)); + }; + if usable < 480 { Err(Error::UsablePageSizeTooSmall(usable)) } else { Ok(usable) } +} + +/// Decode a 1..=8-byte big-endian signed two's-complement integer into `i64`. +/// +/// # Errors +/// +/// Returns [`Error::InvalidIntegerWidth`] if `bytes` is empty or longer than 8 bytes. +/// +/// ``` +/// use craft_sqlite::decode_signed_be_int; +/// +/// assert_eq!(decode_signed_be_int(&[0x80, 0x00, 0x01]), Ok(-8_388_607)); +/// ``` +pub fn decode_signed_be_int(bytes: &[u8]) -> Result { + let Some(&first) = bytes.first() else { + return Err(Error::InvalidIntegerWidth(0)); + }; + if bytes.len() > 8 { + return Err(Error::InvalidIntegerWidth(bytes.len())); + } + let mut value: i64 = if first & 0x80 != 0 { -1 } else { 0 }; + for &byte in bytes { + value = (value << 8) | i64::from(byte); + } + Ok(value) +} + +/// Parsed B-tree page header and cell-pointer array bounds within a usable page slice. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct BtreePageHeader { + /// B-tree page type (`0x02`, `0x05`, `0x0a`, or `0x0d`). + pub kind: u8, + /// Offset where the B-tree page header starts (`100` on page 1, `0` otherwise). + pub header_offset: usize, + /// Number of cells declared in the B-tree header. + pub cells: usize, + /// Start offset of the 2-byte big-endian cell-pointer array. + pub pointers_offset: usize, + /// Exclusive end offset of the cell-pointer array. + pub pointers_end: usize, +} + +/// Parse and bounds-check the B-tree page header and cell-pointer array on `usable_page`. +/// +/// # Errors +/// +/// Returns [`Error::TruncatedPage`] if the page ends before the header or pointer array, or +/// [`Error::UnsupportedBtreePageType`] if the page type byte is not `0x02`, `0x05`, `0x0a`, or `0x0d`. +pub fn parse_btree_page_header(usable_page: &[u8], is_page_one: bool) -> Result { + let header_offset = if is_page_one { 100 } else { 0 }; + let Some(&kind) = usable_page.get(header_offset) else { + return Err(Error::TruncatedPage); + }; + let header_size = match kind { + 0x05 | 0x02 => 12, + 0x0d | 0x0a => 8, + _ => return Err(Error::UnsupportedBtreePageType(kind)), + }; + let Some(cells_bytes) = header_offset + .checked_add(3) + .and_then(|start| start.checked_add(2).and_then(|end| usable_page.get(start..end))) + .and_then(|slice| <[u8; 2]>::try_from(slice).ok()) + else { + return Err(Error::TruncatedPage); + }; + let cells = usize::from(u16::from_be_bytes(cells_bytes)); + let Some(pointers_offset) = header_offset.checked_add(header_size) else { + return Err(Error::TruncatedPage); + }; + let Some(pointers_bytes) = cells.checked_mul(2) else { + return Err(Error::TruncatedPage); + }; + let Some(pointers_end) = pointers_offset.checked_add(pointers_bytes) else { + return Err(Error::TruncatedPage); + }; + if pointers_end > usable_page.len() { + return Err(Error::TruncatedPage); + } + Ok(BtreePageHeader { kind, header_offset, cells, pointers_offset, pointers_end }) +} + +/// Read and bounds-check the `index`-th cell offset from a parsed [`BtreePageHeader`]. +/// +/// # Errors +/// +/// Returns [`Error::CellIndexOutOfBounds`] when `index >= header.cells`, [`Error::TruncatedPage`] +/// if the pointer slot is out of bounds, or [`Error::InvalidCellPointer`] if the pointer lies +/// outside `[header.pointers_end, usable_page.len())`. +pub fn btree_cell_offset(usable_page: &[u8], header: &BtreePageHeader, index: usize) -> Result { + if index >= header.cells { + return Err(Error::CellIndexOutOfBounds { index, cells: header.cells }); + } + let Some(bytes) = index + .checked_mul(2) + .and_then(|off| header.pointers_offset.checked_add(off)) + .and_then(|ptr| ptr.checked_add(2).and_then(|end| usable_page.get(ptr..end))) + .and_then(|slice| <[u8; 2]>::try_from(slice).ok()) + else { + return Err(Error::TruncatedPage); + }; + let offset = usize::from(u16::from_be_bytes(bytes)); + if offset < header.pointers_end || offset >= usable_page.len() { + return Err(Error::InvalidCellPointer { offset, min: header.pointers_end, usable: usable_page.len() }); + } + Ok(offset) +} diff --git a/crates/sqlite/src/wal.rs b/crates/sqlite/src/wal.rs new file mode 100644 index 0000000000..1e236e0e29 --- /dev/null +++ b/crates/sqlite/src/wal.rs @@ -0,0 +1,123 @@ +//! Committed-prefix scanning for SQLite write-ahead logs. +//! Wire algorithm moved from LightCraft (Orthic Labs, 4a427894; Dylan M. Taylor, be760ee5). + +fn be_word(bytes: &[u8], at: usize) -> Result { + let word = bytes.get(at..at + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()).ok_or("truncated WAL")?; + Ok(u32::from_be_bytes(word)) +} + +fn wal_checksum(bytes: &[u8], big: bool, mut sum: (u32, u32)) -> (u32, u32) { + for pair in bytes.as_chunks::<8>().0 { + let first = [pair[0], pair[1], pair[2], pair[3]]; + let second = [pair[4], pair[5], pair[6], pair[7]]; + let (first, second) = + if big { (u32::from_be_bytes(first), u32::from_be_bytes(second)) } else { (u32::from_le_bytes(first), u32::from_le_bytes(second)) }; + sum.0 = sum.0.wrapping_add(first).wrapping_add(sum.1); + sum.1 = sum.1.wrapping_add(second).wrapping_add(sum.0); + } + sum +} + +// SQLite file format §4: validate the live checksum chain in constant space, then overlay +// only its last committed prefix. The forensic timeline materializes EVERY historical +// database snapshot; it must never be used to validate a large, actively used catalog. +/// Returns the byte length through the last checksum-valid commit, or zero if none. +/// An incomplete or uncommitted suffix is not applied; a malformed header errors. +/// The database header supplies the expected page size. Uses constant memory. +pub fn committed_prefix_len(main: &[u8], wal: &[u8]) -> Result { + if wal.is_empty() { + return Ok(0); + } + let header = wal.get(..32).ok_or("truncated WAL header")?; + let magic = be_word(header, 0)?; + if !matches!(magic, 0x377f0682 | 0x377f0683) || be_word(header, 4)? != 3_007_000 { + return Err("invalid WAL header"); + } + let raw_size = main.get(16..18).and_then(|s| <[u8; 2]>::try_from(s).ok()).map(u16::from_be_bytes).ok_or("truncated SQLite header")?; + let size = crate::page_size_from_raw(raw_size).map_err(|_| "WAL page size mismatch")?; + if be_word(header, 8)? != size { + return Err("WAL page size mismatch"); + } + let big = magic == 0x377f0683; + let mut sum = wal_checksum(&header[..24], big, (0, 0)); + if sum != (be_word(header, 24)?, be_word(header, 28)?) { + return Err("invalid WAL header checksum"); + } + let salt = (be_word(header, 16)?, be_word(header, 20)?); + let mut committed = 0; + let stride = size as usize + 24; + for (i, frame) in wal[32..].chunks_exact(stride).enumerate() { + if be_word(frame, 0)? == 0 || salt != (be_word(frame, 8)?, be_word(frame, 12)?) { + break; + } + sum = wal_checksum(&frame[..8], big, sum); + sum = wal_checksum(&frame[24..], big, sum); + if sum != (be_word(frame, 16)?, be_word(frame, 20)?) { + break; + } + if be_word(frame, 4)? != 0 { + committed = 32 + (i + 1) * stride; + } + } + Ok(committed) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn word(bytes: &mut [u8], at: usize, value: u32) { + bytes[at..at + 4].copy_from_slice(&value.to_be_bytes()); + } + + fn fixture(big: bool) -> ([u8; 18], [u8; 32 + 3 * 536]) { + let mut main = [0u8; 18]; + main[16..18].copy_from_slice(&512u16.to_be_bytes()); + let mut wal = [0; 32 + 3 * 536]; + word(&mut wal, 0, if big { 0x377f0683 } else { 0x377f0682 }); + word(&mut wal, 4, 3_007_000); + word(&mut wal, 8, 512); + word(&mut wal, 16, 17); + word(&mut wal, 20, 29); + let mut sum = wal_checksum(&wal[..24], big, (0, 0)); + word(&mut wal, 24, sum.0); + word(&mut wal, 28, sum.1); + for (i, frame) in wal[32..].as_chunks_mut::<536>().0.iter_mut().enumerate() { + word(frame, 0, i as u32 + 1); + word(frame, 4, [1, 3, 0][i]); + word(frame, 8, 17); + word(frame, 12, 29); + frame[24..].fill(i as u8 + 10); + sum = wal_checksum(&frame[..8], big, sum); + sum = wal_checksum(&frame[24..], big, sum); + word(frame, 16, sum.0); + word(frame, 20, sum.1); + } + (main, wal) + } + + #[test] + fn committed_prefix_stops_at_a_frame_checksum_mismatch() { + for big in [false, true] { + let (main, wal) = fixture(big); + let mut second_checksum_wrong = wal; + second_checksum_wrong[32 + 536 + 16] ^= 1; + assert_eq!(committed_prefix_len(&main, &second_checksum_wrong), Ok(32 + 536)); + + let mut first_checksum_wrong = wal; + first_checksum_wrong[32 + 16] ^= 1; + assert_eq!(committed_prefix_len(&main, &first_checksum_wrong), Ok(0)); + } + } + + #[test] + fn committed_prefix_stops_before_uncommitted_or_partial_frame() { + for big in [false, true] { + let (main, wal) = fixture(big); + let committed = 32 + 2 * 536; + assert_eq!(committed_prefix_len(&main, &wal), Ok(committed)); + assert_eq!(committed_prefix_len(&main, &wal[..committed + 23]), Ok(committed)); + assert_eq!(committed_prefix_len(&main, &wal[..32]), Ok(0)); + } + } +} diff --git a/crates/sqlite/tests/wire.rs b/crates/sqlite/tests/wire.rs index 9ef7bb278a..c332bf3225 100644 --- a/crates/sqlite/tests/wire.rs +++ b/crates/sqlite/tests/wire.rs @@ -1,4 +1,92 @@ -use craft_sqlite::{Error, read_varint, serial_type_len}; +use craft_sqlite::{ + BtreePageHeader, Error, PayloadKind, btree_cell_offset, decode_signed_be_int, local_payload_len, page_size_from_raw, parse_btree_page_header, + read_varint, serial_type_len, split_record, usable_page_size, +}; + +#[test] +fn record_split_excludes_the_length_encoding() { + assert_eq!(split_record(&[3, 1, 15, 42, b'A']), Ok((&[1, 15][..], &[42, b'A'][..]))); + assert_eq!(split_record(&[1]), Ok((&[][..], &[][..]))); + assert_eq!(split_record(&[3, 0, 9]), Ok((&[0, 9][..], &[][..]))); + + let mut payload = [0; 129]; + payload[..3].copy_from_slice(&[0x81, 0, 1]); + payload[128] = 42; + let (serial_types, body) = split_record(&payload).unwrap(); + assert_eq!(serial_types.len(), 126); + assert_eq!(serial_types[0], 1); + assert_eq!(body, [42]); +} + +#[test] +fn record_split_limits_a_serial_type_to_its_header() { + let (serial_types, body) = split_record(&[2, 0x81, 0]).unwrap(); + assert_eq!(body, [0]); + assert_eq!(read_varint(serial_types), Err(Error::TruncatedVarint)); + + let (serial_types, _) = split_record(&[3, 0x81, 0]).unwrap(); + assert_eq!(read_varint(serial_types), Ok((128, 2))); +} + +#[test] +fn record_split_rejects_incomplete_and_out_of_range_lengths() { + for payload in [&[][..], &[0x80][..]] { + assert_eq!(split_record(payload), Err(Error::TruncatedVarint)); + } + for (payload, length) in [(&[0][..], 0), (&[0x80, 1][..], 1), (&[2][..], 2), (&[0xff; 9][..], u64::MAX)] { + assert_eq!(split_record(payload), Err(Error::InvalidRecordHeaderLength(length))); + } +} + +#[test] +fn local_payload_preserves_inline_and_overflow_boundaries() { + // Original literal cases calculated from SQLite file format section 1.6, including + // the 512-byte page with 32 reserved bytes and an odd usable size with one reserved byte. + for (usable, minimum, table_max, index_max) in [ + (480, 35, 445, 94), + (511, 39, 476, 102), + (512, 39, 477, 102), + (1_024, 103, 989, 230), + (2_048, 232, 2_013, 487), + (4_096, 489, 4_061, 1_002), + (8_192, 1_003, 8_157, 2_030), + (16_384, 2_031, 16_349, 4_086), + (32_768, 4_087, 32_733, 8_198), + (65_536, 8_199, 65_501, 16_422), + ] { + for (kind, maximum) in [(PayloadKind::TableLeaf, table_max), (PayloadKind::Index, index_max)] { + for (payload, expected) in [(0, 0), (maximum, maximum), (maximum + 1, minimum)] { + assert_eq!(local_payload_len(usable, u64::from(payload), kind), Some(expected), "usable {usable}, payload {payload}, {kind:?}"); + } + // A complete overflow-page span returns to the upper local boundary; one + // further byte must fall back to the minimum rather than exceed the maximum. + let payload = u64::from(maximum) + u64::from(usable) - 4; + assert_eq!(local_payload_len(usable, payload, kind), Some(maximum), "usable {usable}, {kind:?}"); + assert_eq!(local_payload_len(usable, payload + 1, kind), Some(minimum), "usable {usable}, {kind:?}"); + } + } + assert_eq!(local_payload_len(512, 600, PayloadKind::TableLeaf), Some(92)); +} + +#[test] +fn local_payload_refuses_unsupported_usable_sizes() { + for usable in [0, 4, 35, 479, 65_537, u32::MAX] { + for kind in [PayloadKind::TableLeaf, PayloadKind::Index] { + assert_eq!(local_payload_len(usable, 0, kind), None); + assert_eq!(local_payload_len(usable, u64::MAX, kind), None); + } + } +} + +#[test] +fn local_payload_keeps_full_width_payload_lengths() { + // Literal remainders for the largest wire length catch host-size truncation and + // overflow in the minimum-plus-modulo calculation without allocating a payload. + for (usable, table_local, index_local) in [(480, 323, 35), (511, 93, 93), (512, 255, 39), (32_768, 4_095, 4_095), (65_536, 8_199, 8_199)] { + assert_eq!(local_payload_len(usable, u64::MAX, PayloadKind::TableLeaf), Some(table_local)); + assert_eq!(local_payload_len(usable, u64::MAX, PayloadKind::Index), Some(index_local)); + } +} #[test] fn varints_decode_at_each_width() { @@ -69,3 +157,77 @@ fn variable_serial_type_widths_are_portable() { assert_eq!(serial_type_len(serial_type), Ok(width), "code {serial_type}"); } } + +#[test] +fn page_size_and_usable_validation() { + assert_eq!(page_size_from_raw(512), Ok(512)); + assert_eq!(page_size_from_raw(4096), Ok(4096)); + assert_eq!(page_size_from_raw(1), Ok(65_536)); + assert_eq!(page_size_from_raw(0), Err(Error::InvalidPageSize(0))); + assert_eq!(page_size_from_raw(256), Err(Error::InvalidPageSize(256))); + assert_eq!(page_size_from_raw(1000), Err(Error::InvalidPageSize(1000))); + + assert_eq!(usable_page_size(512, 32), Ok(480)); + assert_eq!(usable_page_size(512, 33), Err(Error::UsablePageSizeTooSmall(479))); + assert_eq!(usable_page_size(100, 150), Err(Error::UsablePageSizeTooSmall(0))); + assert_eq!(usable_page_size(512, 0), Ok(512)); + + for err in [ + Error::InvalidPageSize(0), + Error::UsablePageSizeTooSmall(479), + Error::TruncatedPage, + Error::UnsupportedBtreePageType(0x01), + Error::InvalidCellPointer { offset: 109, min: 110, usable: 512 }, + Error::CellIndexOutOfBounds { index: 1, cells: 1 }, + Error::InvalidIntegerWidth(0), + ] { + assert!(!err.to_string().is_empty()); + } +} + +#[test] +fn signed_be_integers_decode_with_sign_extension() { + assert_eq!(decode_signed_be_int(&[0x7f]), Ok(127)); + assert_eq!(decode_signed_be_int(&[0x80]), Ok(-128)); + assert_eq!(decode_signed_be_int(&[0x80, 0x00, 0x01]), Ok(-8_388_607)); + assert_eq!(decode_signed_be_int(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xfe]), Ok(-2)); + assert_eq!(decode_signed_be_int(&[0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Ok(i64::MAX)); + assert_eq!(decode_signed_be_int(&[0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Ok(i64::MIN)); + assert_eq!(decode_signed_be_int(&[]), Err(Error::InvalidIntegerWidth(0))); + assert_eq!(decode_signed_be_int(&[0; 9]), Err(Error::InvalidIntegerWidth(9))); +} + +#[test] +fn btree_page_header_and_cell_pointer_bounds() { + let mut page = [0u8; 512]; + page[100] = 0x0d; + page[103..105].copy_from_slice(&1u16.to_be_bytes()); + page[108..110].copy_from_slice(&400u16.to_be_bytes()); + + let hdr = parse_btree_page_header(&page, true).unwrap(); + assert_eq!(hdr, BtreePageHeader { kind: 0x0d, header_offset: 100, cells: 1, pointers_offset: 108, pointers_end: 110 }); + assert_eq!(btree_cell_offset(&page, &hdr, 0), Ok(400)); + assert_eq!(btree_cell_offset(&page, &hdr, 1), Err(Error::CellIndexOutOfBounds { index: 1, cells: 1 })); + + // Pointer inside header/pointer array is rejected. + page[108..110].copy_from_slice(&109u16.to_be_bytes()); + assert_eq!(btree_cell_offset(&page, &hdr, 0), Err(Error::InvalidCellPointer { offset: 109, min: 110, usable: 512 })); + + // Unsupported page kind and truncated pages are rejected. + page[0] = 0x01; + assert_eq!(parse_btree_page_header(&page, false), Err(Error::UnsupportedBtreePageType(0x01))); + assert_eq!(parse_btree_page_header(&[], false), Err(Error::TruncatedPage)); + assert_eq!(parse_btree_page_header(&[0x0d, 0, 0, 0], false), Err(Error::TruncatedPage)); + + // Interior page with pointer array exceeding usable page is rejected. + page[0] = 0x05; + page[3..5].copy_from_slice(&300u16.to_be_bytes()); + assert_eq!(parse_btree_page_header(&page, false), Err(Error::TruncatedPage)); + + // Cell pointer >= usable is rejected. + page[0] = 0x0d; + page[3..5].copy_from_slice(&1u16.to_be_bytes()); + page[8..10].copy_from_slice(&512u16.to_be_bytes()); + let small_hdr = parse_btree_page_header(&page, false).unwrap(); + assert_eq!(btree_cell_offset(&page, &small_hdr, 0), Err(Error::InvalidCellPointer { offset: 512, min: 10, usable: 512 })); +} diff --git a/crates/stream-codecs/README.md b/crates/stream-codecs/README.md index b96c41c44e..a228f3188a 100644 --- a/crates/stream-codecs/README.md +++ b/crates/stream-codecs/README.md @@ -26,6 +26,7 @@ pub type Step = Result, Failure>; pay(work: &mut u64, steps) -> Result<(), CodecError> // an allowance shared across a run of images lzw::decode(data, early_change, max) -> Step; lzw::encode(data, early_change) -> Vec +lzw::decode_prefix(data, early_change, max) -> Result<(Vec, usize), Failure> ascii85::decode(data, max) -> Step; ascii85::encode(data) -> Vec asciihex::decode(data, max) -> Step; asciihex::encode(data) -> Vec runlength::decode(data, max) -> Step; runlength::encode(data) -> Vec diff --git a/crates/stream-codecs/src/lzw.rs b/crates/stream-codecs/src/lzw.rs index e16d78288c..fb230828e2 100644 --- a/crates/stream-codecs/src/lzw.rs +++ b/crates/stream-codecs/src/lzw.rs @@ -50,6 +50,23 @@ impl BitReader<'_> { } pub fn decode(data: &[u8], early: bool, max: usize) -> Step { + let out = Vec::with_capacity(data.len().saturating_mul(2).min(max)); + decode_stream(data, early, max, out).map(|(out, _)| out) +} + +/// Decode one LZW stream and return its bytes and the number of input bytes consumed. +/// +/// The count includes the byte containing the final bits of the end-of-data code (257). +/// Later bytes remain unread. If the input ends without EOD, complete codes still decode +/// and the count includes all bytes available. As in [`decode`], `early` selects the early +/// width change and `max` bounds the decoded output. +/// +/// Output grows as codes arrive because the input may include a program after the compressed data. +pub fn decode_prefix(data: &[u8], early: bool, max: usize) -> Result<(Vec, usize), Failure> { + decode_stream(data, early, max, Vec::new()) +} + +fn decode_stream(data: &[u8], early: bool, max: usize, mut out: Vec) -> Result<(Vec, usize), Failure> { // Table entry = (prefix code, last byte, first byte, length). let mut prefix = vec![0u16; TABLE]; let mut last = vec![0u8; TABLE]; @@ -64,7 +81,6 @@ pub fn decode(data: &[u8], early: bool, max: usize) -> Step { let mut w = 9; let mut prev: Option = None; let mut r = BitReader { data, pos: 0, acc: 0, bits: 0 }; - let mut out = Vec::with_capacity(data.len().saturating_mul(2).min(max)); while let Some(code) = r.read(w) { match code { @@ -111,7 +127,7 @@ pub fn decode(data: &[u8], early: bool, max: usize) -> Step { prev = Some(code); w = width(next, early); } - Ok(out) + Ok((out, r.pos)) } struct BitWriter { @@ -204,6 +220,46 @@ mod tests { assert_eq!(dec(&SPEC_OUT, false).unwrap(), SPEC_IN); } + #[test] + fn prefix_stops_at_the_byte_containing_end_of_data() { + let mut aligned = SPEC_OUT.to_vec(); + let following = b"\nshowpage"; + aligned.extend_from_slice(following); + let (decoded, consumed) = decode_prefix(&aligned, true, SPEC_IN.len()).ok().unwrap(); + assert_eq!(decoded, SPEC_IN); + assert_eq!(&aligned[consumed..], following); + + // Two 9-bit codes: literal 'A', then 257. The last six bits are padding. + let mut partial_byte = vec![0x20, 0xc0, 0x7f]; + partial_byte.resize(1 << 20, b'x'); + let (decoded, consumed) = decode_prefix(&partial_byte, true, usize::MAX).ok().unwrap(); + assert_eq!(decoded, b"A"); + assert_eq!(consumed, 3); + assert!(decoded.capacity() < partial_byte.len(), "the unread suffix must not reserve output"); + } + + #[test] + fn prefix_tolerates_eof_with_unused_bits() { + assert_eq!(decode_prefix(&[], true, 0).ok().unwrap(), (vec![], 0)); + // Literal 'A' and just the first seven bits of EOD. + assert_eq!(decode_prefix(&[0x20, 0xc0], true, 1).ok().unwrap(), (b"A".to_vec(), 2)); + } + + #[test] + fn prefix_preserves_corruption_and_output_limit() { + let mut w = BitWriter { out: vec![], acc: 0, bits: 0 }; + for c in [65, 66, 300] { + w.write(c, 9); + } + let bytes = w.finish(); + let at_limit = decode_prefix(&bytes, true, 2).err().unwrap(); + assert!(matches!(at_limit.error, CodecError::Corrupt { .. })); + assert_eq!(at_limit.partial, b"AB"); + let too_small = decode_prefix(&bytes, true, 1).err().unwrap(); + assert!(matches!(too_small.error, CodecError::LimitExceeded(1))); + assert!(too_small.partial.is_empty()); + } + #[test] fn missing_eod_and_clear() { // Drop the EOD (last 9 bits span the final 2 bytes; keep bits for 66 only). @@ -263,6 +319,14 @@ mod tests { assert_eq!(dec(&tiff, true).unwrap(), data); let plain = weezl::encode::Encoder::new(Msb, 8).encode(&data).unwrap(); assert_eq!(dec(&plain, false).unwrap(), data); + // Both independent bitstreams may be followed by uncompressed data. + for (mut bytes, early) in [(tiff, true), (plain, false)] { + let following = b"\nshowpage"; + bytes.extend_from_slice(following); + let (out, used) = decode_prefix(&bytes, early, data.len()).ok().unwrap(); + assert_eq!(out, data); + assert_eq!(&bytes[used..], following); + } let ours = encode(&data, true); assert_eq!(weezl::decode::Decoder::with_tiff_size_switch(Msb, 8).decode(&ours).unwrap(), data); let ours = encode(&data, false); diff --git a/crates/stream-codecs/src/runlength.rs b/crates/stream-codecs/src/runlength.rs index a13a1d4fbf..3883a58dac 100644 --- a/crates/stream-codecs/src/runlength.rs +++ b/crates/stream-codecs/src/runlength.rs @@ -7,7 +7,34 @@ use crate::{Failure, Step}; const NAME: &str = "RunLengthDecode"; pub fn decode(data: &[u8], max: usize) -> Step { - let mut out = Vec::with_capacity(data.len().saturating_mul(2).min(max)); + decode_packets(data, max, Mode::Whole).map(|(out, _)| out) +} + +/// Decode one run-length stream and return its bytes and the number of input bytes consumed. +/// +/// The count includes the end-of-data byte (128); any bytes after it remain unread. EOF between +/// packets is accepted without an end marker. Each packet must be complete before its output +/// limit is checked, so a truncated packet is corrupt even if its available bytes exceed `max`. +/// An earlier complete packet exceeding the limit still fails before any later packet is read. +/// On corruption, partial output contains only complete preceding packets. +/// +/// Output grows as packets arrive instead of reserving space for the input, which may include +/// an arbitrarily long program after the end marker. The existing [`decode`] retains its +/// allocation and partial-literal limit policy. +pub fn decode_prefix(data: &[u8], max: usize) -> Result<(Vec, usize), Failure> { + decode_packets(data, max, Mode::Prefix) +} + +enum Mode { + Whole, + Prefix, +} + +fn decode_packets(data: &[u8], max: usize, mode: Mode) -> Result<(Vec, usize), Failure> { + let mut out = match mode { + Mode::Whole => Vec::with_capacity(data.len().saturating_mul(2).min(max)), + Mode::Prefix => Vec::new(), + }; let mut i = 0; while let Some(&l) = data.get(i) { i += 1; @@ -16,6 +43,9 @@ pub fn decode(data: &[u8], max: usize) -> Step { 0..=127 => { let n = usize::from(l) + 1; let avail = n.min(data.len() - i); + if matches!(mode, Mode::Prefix) && avail < n { + return Err(Failure::corrupt(NAME, "truncated literal run", out)); + } if out.len() + avail > max { return Err(Failure::limit(max)); } @@ -38,7 +68,7 @@ pub fn decode(data: &[u8], max: usize) -> Step { } } } - Ok(out) + Ok((out, i)) } pub fn encode(data: &[u8]) -> Vec { @@ -118,6 +148,68 @@ mod tests { assert_eq!(decode(&[129, 0, 129, 0], 256).ok().unwrap().len(), 256); } + #[test] + fn prefix_stops_after_eod_without_reading_the_program_tail() { + let bytes = [2, b'a', b'b', b'c', 254, b'x', 128, 127]; + let (out, used) = decode_prefix(&bytes, 6).ok().unwrap(); + assert_eq!(out, b"abcxxx"); + assert_eq!(&bytes[used..], &[127]); // Truncated data after EOD is not decoded. + assert_eq!(used, 7); + assert_eq!(decode_prefix(&[128], 0).ok().unwrap(), (vec![], 1)); + } + + #[test] + fn prefix_accepts_empty_input_and_eof_between_packets() { + assert_eq!(decode_prefix(&[], 0).ok().unwrap(), (vec![], 0)); + let bytes = [0, b'a', 255, b'b']; + assert_eq!(decode_prefix(&bytes, 3).ok().unwrap(), (b"abb".to_vec(), bytes.len())); + } + + #[test] + fn prefix_checks_packet_completeness_before_its_output_limit() { + for bytes in [&[2, b'a', b'b'][..], &[129][..]] { + let failure = decode_prefix(bytes, 0).err().unwrap(); + assert!(matches!(failure.error, CodecError::Corrupt { .. })); + assert!(failure.partial.is_empty()); + } + let failure = decode_prefix(&[0, b'q', 2, b'a', b'b'], 1).err().unwrap(); + assert!(matches!(failure.error, CodecError::Corrupt { .. })); + assert_eq!(failure.partial, b"q"); + } + + #[test] + fn prefix_checks_each_complete_packet_before_later_corruption() { + for bytes in [&[0, b'a', 127][..], &[255, b'a', 127][..]] { + let failure = decode_prefix(bytes, 0).err().unwrap(); + assert!(matches!(failure.error, CodecError::LimitExceeded(0))); + assert!(failure.partial.is_empty()); + } + assert_eq!(decode_prefix(&[0, b'a', 128], 1).ok().unwrap(), (vec![b'a'], 3)); + assert_eq!(decode_prefix(&[255, b'a', 128], 2).ok().unwrap(), (vec![b'a'; 2], 3)); + } + + #[test] + fn prefix_does_not_reserve_for_the_undecoded_tail() { + let mut bytes = vec![128]; + bytes.resize(1 << 20, 127); + let (out, used) = decode_prefix(&bytes, usize::MAX).ok().unwrap(); + assert_eq!(used, 1); + assert_eq!(out.capacity(), 0); + let out = decode(&bytes, 256).ok().unwrap(); + assert!(out.capacity() >= 256, "whole decoding keeps its input-based reservation"); + } + + #[test] + fn whole_decode_keeps_its_partial_literal_and_limit_precedence() { + let bytes = [2, b'a', b'b']; + let failure = decode(&bytes, 1).err().unwrap(); + assert!(matches!(failure.error, CodecError::LimitExceeded(1))); + assert!(failure.partial.is_empty()); + let failure = decode(&bytes, 2).err().unwrap(); + assert!(matches!(failure.error, CodecError::Corrupt { .. })); + assert_eq!(failure.partial, b"ab"); + } + #[test] fn encoding() { assert_eq!(encode(b"abcxxx"), [2, b'a', b'b', b'c', 254, b'x', 128]); diff --git a/crates/svg/src/doc_style.rs b/crates/svg/src/doc_style.rs index fa830aa6c9..156dbce241 100644 --- a/crates/svg/src/doc_style.rs +++ b/crates/svg/src/doc_style.rs @@ -193,6 +193,87 @@ pub fn length(s: &str, axis: char, font: f64, vw: f64, vh: f64) -> Option { value.is_finite().then_some(value) } +/// Parse a strict SVG length in user units, rejecting unknown unit suffixes. +/// +/// `%` is relative to `reference`; `em`/`ex` assume a 16 px font. +pub fn length_strict(s: &str, reference: f64) -> Option { + let v = s.trim(); + let units: [(&str, f64); 9] = [ + ("%", reference / 100.0), + ("px", 1.0), + ("pt", 96.0 / 72.0), + ("pc", 16.0), + ("mm", 96.0 / 25.4), + ("cm", 96.0 / 2.54), + ("in", 96.0), + ("em", 16.0), + ("ex", 8.0), + ]; + let (num, k) = units.iter().find_map(|(u, k)| v.strip_suffix(u).map(|n| (n, *k))).unwrap_or((v, 1.0)); + let n: f64 = num.trim().parse().ok().filter(|n: &f64| n.is_finite())?; + Some(n * k).filter(|x| x.is_finite()) +} + +/// Parse an SVG opacity or offset value (number or percentage), clamped to `[0.0, 1.0]`. +pub fn parse_opacity(s: &str) -> Option { + let v = s.trim(); + let x = match v.strip_suffix('%') { + Some(p) => p.parse::().ok()? / 100.0, + None => v.parse::().ok()?, + }; + x.is_finite().then(|| x.clamp(0.0, 1.0)) +} + +/// Parse an SVG `font-size` (keyword, relative `em`/`ex`/`%` to `parent`, or strict length). +pub fn parse_font_size(s: &str, parent: f64, reference: f64) -> Option { + let v = s.trim(); + let keyword = match v { + "xx-small" => Some(9.0), + "x-small" => Some(10.0), + "small" => Some(13.0), + "medium" => Some(16.0), + "large" => Some(18.0), + "x-large" => Some(24.0), + "xx-large" => Some(32.0), + "larger" => Some(parent * 1.2), + "smaller" => Some(parent / 1.2), + _ => None, + }; + let rel = |suffix: &str, k: f64| v.strip_suffix(suffix).and_then(|n| n.trim().parse::().ok()).map(|n| n * k); + let size = keyword + .or_else(|| rel("em", parent)) + .or_else(|| rel("ex", parent * 0.5)) + .or_else(|| rel("%", parent / 100.0)) + .or_else(|| length_strict(v, reference))?; + size.is_finite().then(|| size.clamp(0.0, 2000.0)) +} + +/// Parse an SVG `stroke-dasharray` list (`none` or empty/negative/invalid returns `None`). +pub fn parse_dash_array(s: &str, reference: f64) -> Option> { + if s.trim() == "none" { + return None; + } + let mut out = Vec::new(); + for part in s.split(|c: char| c == ',' || c.is_whitespace()).filter(|p| !p.trim().is_empty()).take(1024) { + let x = length_strict(part, reference)?; + if x < 0.0 { + return None; + } + out.push(x); + } + (!out.is_empty()).then_some(out) +} + +/// What a percentage of geometry attribute `attr_name` is relative to in a `width` x `height` viewport. +pub fn symbol_percent_basis(attr_name: &str, width: f64, height: f64) -> Option { + match attr_name { + "x" | "x1" | "x2" | "cx" | "width" | "rx" => Some(width), + "y" | "y1" | "y2" | "cy" | "height" | "ry" => Some(height), + "r" => Some(((width * width + height * height) / 2.0).sqrt()), + _ => None, + } +} + /// Parse a length attribute on `n`, returning `0.0` if missing or invalid. pub fn attr_len(n: roxmltree::Node, name: &str, axis: char, st: &Style, vw: f64, vh: f64) -> f64 { n.attribute(name).and_then(|v| length(v, axis, st.font_size, vw, vh)).unwrap_or(0.0) @@ -315,9 +396,9 @@ pub fn resolve_paint(paint: &PaintRef, st: &Style, resolve_url: impl FnOnce(& } } -/// Parse an element's `viewBox` attribute into `([min_x, min_y], width, height)`. -pub fn viewbox(n: roxmltree::Node) -> Option<([f64; 2], f64, f64)> { - let (v, exceeded) = numbers_bounded(n.attribute("viewBox")?, 5); +/// Parse a `viewBox` attribute string into `([min_x, min_y], width, height)`. +pub fn parse_viewbox(s: &str) -> Option<([f64; 2], f64, f64)> { + let (v, exceeded) = numbers_bounded(s, 5); if exceeded || !v.iter().all(|x| x.is_finite()) { return None; } @@ -325,10 +406,10 @@ pub fn viewbox(n: roxmltree::Node) -> Option<([f64; 2], f64, f64)> { (*width > 0.0 && *height > 0.0).then_some(([*x, *y], *width, *height)) } -/// The `viewBox` -> viewport transform (`preserveAspectRatio`, default `xMidYMid meet`). -pub fn viewbox_transform(n: roxmltree::Node, w: f64, h: f64) -> Affine { - let Some(([x, y], vw, vh)) = viewbox(n) else { return Affine::IDENTITY }; - let par = n.attribute("preserveAspectRatio").unwrap_or("xMidYMid meet"); +/// Compute the `viewBox` -> viewport transform for `preserveAspectRatio` (default `xMidYMid meet`). +pub fn viewbox_transform_with(vb: ([f64; 2], f64, f64), w: f64, h: f64, preserve_aspect_ratio: &str) -> Affine { + let ([x, y], vw, vh) = vb; + let par = if preserve_aspect_ratio.trim().is_empty() { "xMidYMid meet" } else { preserve_aspect_ratio }; let mut parts = par.split_whitespace(); let mut align = parts.next().unwrap_or("xMidYMid"); if align == "defer" { @@ -359,6 +440,17 @@ pub fn viewbox_transform(n: roxmltree::Node, w: f64, h: f64) -> Affine { Affine::translate((tx, ty)) * Affine::scale(s) * Affine::translate((-x, -y)) } +/// Parse an element's `viewBox` attribute into `([min_x, min_y], width, height)`. +pub fn viewbox(n: roxmltree::Node) -> Option<([f64; 2], f64, f64)> { + parse_viewbox(n.attribute("viewBox")?) +} + +/// The `viewBox` -> viewport transform (`preserveAspectRatio`, default `xMidYMid meet`). +pub fn viewbox_transform(n: roxmltree::Node, w: f64, h: f64) -> Affine { + let Some(vb) = viewbox(n) else { return Affine::IDENTITY }; + viewbox_transform_with(vb, w, h, n.attribute("preserveAspectRatio").unwrap_or("xMidYMid meet")) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/svg/src/path_data.rs b/crates/svg/src/path_data.rs index 16d2f3de5b..2b7ed3afc5 100644 --- a/crates/svg/src/path_data.rs +++ b/crates/svg/src/path_data.rs @@ -194,6 +194,15 @@ impl<'a> Tokenizer<'a> { } } +fn reflected_control(at: Point, previous: Point) -> Point { + let reflect = |coordinate: f64, prior: f64| { + let doubled = coordinate * 2.0; + // If both inputs are finite and doubling overflows, round only the final value. + if doubled.is_infinite() && coordinate.is_finite() && prior.is_finite() { coordinate.mul_add(2.0, -prior) } else { doubled - prior } + }; + Point::new(reflect(at.x, previous.x), reflect(at.y, previous.y)) +} + /// Split `d` into subpaths, resolving relative commands and S/T control reflections while /// raising quadratic (`Q`/`T`) segments to cubics. pub fn parse_path(d: &str) -> Result> { @@ -355,7 +364,7 @@ pub fn parse_path_with_quads(d: &str) -> Result> { cur = p; } b'S' => { - let c1 = prev_cubic.map_or(cur, |c2| cur * 2.0 - c2); + let c1 = prev_cubic.map_or(cur, |c2| reflected_control(cur, c2)); let (c2, p) = (point(args[0], args[1]), point(args[2], args[3])); segs.push(QuadSegment::Cubic(c1, c2, p)); prev_cubic = Some(c2); @@ -370,7 +379,7 @@ pub fn parse_path_with_quads(d: &str) -> Result> { cur = p; } b'T' => { - let reflect = prev_quad.map_or(cur, |q| cur * 2.0 - q); + let reflect = prev_quad.map_or(cur, |q| reflected_control(cur, q)); let p = point(args[0], args[1]); segs.push(QuadSegment::Quad(reflect, p)); prev_quad = Some(reflect); @@ -467,8 +476,13 @@ pub fn elliptical_params(p0: Point, p1: Point, rx: f64, ry: f64, phi: f64, large let angle = |ux: f64, uy: f64, vx: f64, vy: f64| { let dot = ux * vx + uy * vy; let det = ux * vy - uy * vx; - let denom = (ux.hypot(uy) * vx.hypot(vy)).max(f64::MIN_POSITIVE); - (dot / denom).clamp(-1.0, 1.0).acos().copysign(det) + if dot == 0.0 && det == 0.0 { + // Preserve the fallback for a degenerate vector. + std::f64::consts::FRAC_PI_2.copysign(det) + } else { + // The determinant retains tiny angles even when their cosine rounds to one. + det.atan2(dot) + } }; let (ux, uy) = ((x1 - cxp) / rx, (y1 - cyp) / ry); let (vx, vy) = ((-x1 - cxp) / rx, (-y1 - cyp) / ry); @@ -510,6 +524,21 @@ mod tests { ); } + #[test] + fn smooth_cubic_matches_explicit_control_when_doubling_would_overflow() { + let smooth = "M1e308 0 C1e308 1 1e308 2 1e308 3 S1e308 5 1e308 6"; + let explicit = "M1e308 0 C1e308 1 1e308 2 1e308 3 C1e308 4 1e308 5 1e308 6"; + assert_eq!(parse_path(smooth).unwrap(), parse_path(explicit).unwrap()); + } + + #[test] + fn smooth_quadratic_matches_explicit_control_when_doubling_would_overflow() { + let smooth = "M0 -1e308 Q1 -1e308 2 -1e308 T4 -1e308"; + let explicit = "M0 -1e308 Q1 -1e308 2 -1e308 Q3 -1e308 4 -1e308"; + assert_eq!(parse_path_with_quads(smooth).unwrap(), parse_path_with_quads(explicit).unwrap()); + assert_eq!(parse_path(smooth).unwrap(), parse_path(explicit).unwrap()); + } + #[test] fn close_resets_smooth_control_history() { // After Z, S must not reflect the preceding C's control (20,20) → (0,0). @@ -531,6 +560,28 @@ mod tests { assert!((sweep - std::f64::consts::PI).abs() < 1e-10); } + #[test] + fn short_elliptical_arcs_keep_their_sweep_and_endpoints() { + let p0 = Point::ZERO; + let p1 = Point::new(1e-9, 0.0); + let rx = 1.0; + let ry = 2.0; + let short = 2.0 * (p1.x / (2.0 * rx)).asin(); + for large in [false, true] { + for sweep in [false, true] { + let (center, start, delta) = elliptical_params(p0, p1, rx, ry, 0.0, large, sweep).unwrap(); + let magnitude = if large { std::f64::consts::TAU - short } else { short }; + let expected = if sweep { magnitude } else { -magnitude }; + assert!((delta - expected).abs() < 1e-11, "large={large}, sweep={sweep}: {delta} vs {expected}"); + let at = |angle: f64| Point::new(center.x + rx * angle.cos(), center.y + ry * angle.sin()); + for (actual, expected) in [(at(start), p0), (at(start + delta), p1)] { + let error = actual - expected; + assert!(error.x.hypot(error.y) < 1e-11, "{actual:?} vs {expected:?}"); + } + } + } + } + #[test] fn rejects_invalid_tokens_instead_of_returning_a_partial_path() { for input in ["@", "M0 0 L1 1@ L2 2", "M0 0 L1 1@", "M0 0 Z@", "M0 0 L1 1é", "M0 0 L1 1 +", "M0 0 L1 1 .", "M0 0 L1 1 2e+", "M0 0 L1 1 1e999"] diff --git a/crates/svg/src/simple_css.rs b/crates/svg/src/simple_css.rs index 767b252577..94d0550c6b 100644 --- a/crates/svg/src/simple_css.rs +++ b/crates/svg/src/simple_css.rs @@ -101,6 +101,31 @@ pub fn declarations(s: &str) -> impl Iterator + '_ { .filter(|(k, _)| !k.is_empty()) } +/// Escape `s` as a CSS string delimited by `quote`. +/// +/// Escapes backslashes, the delimiter quote, control characters, and `<` / `>` (which could end +/// a `