diff --git a/.config/nextest.toml b/.config/nextest.toml new file mode 100644 index 000000000..1037b2310 --- /dev/null +++ b/.config/nextest.toml @@ -0,0 +1,44 @@ +# cargo-nextest (https://nexte.st) runs every test in its own process, in parallel across test +# binaries. The Windows leg of the Workspace gate uses it (.github/workflows/workspace.yml); every +# other leg, and local runs, keep `cargo test`. Nextest does not run doctests, so the Windows leg +# also runs `cargo test --doc`. +# +# cargo nextest run --workspace --profile ci +# cargo test --workspace --doc +# +# Refuse an older nextest: CI installs exactly this version (GHSA-vc25-qg58-w57c is fixed in it). +nextest-version = "0.9.150" + +# Some tests share a resource that an in-process mutex keeps to one test at a time. With one +# process per test those mutexes no longer serialize anything, so these groups do it instead, one +# test at a time, as under `cargo test`. +[test-groups] +# craft-ui: `gpu_test_lock()` / `gpu_lock()`. Each renderer creates its own wgpu instance and +# device, and creating or destroying one while another test uses its device can crash. +gpu = { max-threads = 1 } +# craft-video h264_decode: `FIXTURE_GENERATION` keeps a second producer from replacing a fixture +# file another test is reading. +video-fixtures = { max-threads = 1 } +# craft-print: `PRINT_TICKET_PROVIDER` serializes the Windows PrintTicket provider, and the tests +# share the one test print queue the gate installs. +print = { max-threads = 1 } + +[[profile.default.overrides]] +filter = 'package(craft-ui) & (binary(visual_regression) | test(/^combo::tests::|selected_tab_erases_a_baseline_centered_on_its_bottom_edge/))' +test-group = 'gpu' + +[[profile.default.overrides]] +filter = 'package(craft-video) & binary(h264_decode)' +test-group = 'video-fixtures' + +[[profile.default.overrides]] +filter = 'package(craft-print)' +test-group = 'print' + +# The gate (`--profile ci`). Run every test and list all failures at the end, as `cargo test` +# reports a whole binary. Slow tests are named every 60 seconds; none is stopped for being slow, +# so a hang is still ended by the gate's own timeout, as before. +[profile.ci] +fail-fast = false +slow-timeout = { period = "60s" } +failure-output = "immediate-final" diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 20e947480..4d717fed8 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -25,7 +25,8 @@ jobs: with: os: '["ubuntu-latest","windows-latest","macos-latest"]' timeout-minutes: 120 - tools: "" + # The Windows leg runs its tests with nextest (.config/nextest.toml). + tools: cargo-nextest@0.9.150 packages: mesa-vulkan-drivers libvulkan1 craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan @@ -58,8 +59,12 @@ jobs: cargo fmt --check cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - cargo test --workspace --locked - cargo test --workspace --all-features --locked + # The same tests as `cargo test`, run in parallel across test binaries instead of one + # binary at a time; nextest skips doctests, so `cargo test --doc` runs them. + cargo nextest run --workspace --locked --profile ci + cargo test --workspace --doc --locked + cargo nextest run --workspace --all-features --locked --profile ci + cargo test --workspace --doc --all-features --locked msrv: name: Rust 1.95 diff --git a/Cargo.lock b/Cargo.lock index 50b715040..8679e4eac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1498,6 +1498,14 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-color" +version = "0.1.0" +dependencies = [ + "proptest", + "serde", +] + [[package]] name = "craft-control" version = "0.1.0" @@ -1551,6 +1559,13 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-dds" +version = "0.1.0" +dependencies = [ + "rayon", +] + [[package]] name = "craft-deckcraft-format" version = "0.1.0" @@ -1925,6 +1940,16 @@ dependencies = [ "sha2 0.10.9", ] +[[package]] +name = "craft-frame" +version = "0.1.0" +dependencies = [ + "craft-color", + "craft-time", + "rayon", + "serde", +] + [[package]] name = "craft-gainmap" version = "0.1.0" @@ -2042,6 +2067,7 @@ name = "craft-image-codecs" version = "0.1.0" dependencies = [ "avif-serialize", + "craft-dds", "craft-heif", "craft-jpeg", "craft-media-testkit", @@ -2255,6 +2281,20 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-media-source" +version = "0.1.0" +dependencies = [ + "craft-audio", + "craft-color", + "craft-frame", + "craft-media", + "craft-time", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-media-testkit" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 0ed80bda2..c8ae36287 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,6 +52,8 @@ craft-captions = { path = "crates/captions" } craft-cfb = { path = "crates/cfb" } craft-codepage = { path = "crates/codepage" } craft-cms = { path = "crates/cms" } +craft-color = { path = "crates/color" } +craft-frame = { path = "crates/frame" } craft-crs = { path = "crates/crs" } craft-crw = { path = "crates/crw" } craft-csv = { path = "crates/csv" } @@ -117,6 +119,7 @@ craft-macho = { path = "crates/macho" } craft-math = { path = "crates/math" } # No default features: craft-audio turns on the craft-media modules each of its features needs. craft-media = { path = "crates/media", default-features = false } +craft-media-source = { path = "crates/media-source" } craft-materialx = { path = "crates/materialx" } craft-media-testkit = { path = "crates/media-testkit" } craft-midi = { path = "crates/midi" } @@ -143,6 +146,7 @@ craft-print = { path = "crates/print" } craft-proof = { path = "crates/proof" } craft-raster-codecs = { path = "crates/raster-codecs" } craft-image-codecs = { path = "crates/image-codecs" } +craft-dds = { path = "crates/dds" } craft-psd = { path = "crates/psd" } craft-pst = { path = "crates/pst" } craft-quit = { path = "crates/quit" } diff --git a/README.md b/README.md index 47b223d48..a3373f3a3 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit black and white levels and as-shot white balance. The complete derivation record (plan, sources log, scripts, verification) is in `crates/crw/clean-room/`. Colour stays in each app. - [`craft-csv`](crates/csv/README.md): delimited text (CSV, TSV) and SYLK: encoding detection (UTF-8, UTF-16, Windows-1252 or Windows-1256), delimiter sniffing, a record parser with a cap on fields per record, field quoting for writers, and a SYLK (`.slk`) reader with R1C1 formulas rewritten to A1. +- [`craft-dds`](crates/dds/README.md): DirectDraw Surface (DDS) textures, read and written: the + top mip level of uncompressed, BC1 to BC3 (DXT1/3/5) and BC4/BC5 (grayscale data and normal + maps) textures, legacy and DX10 headers, and our own block encoder with optional mip chains. No dependencies (rayon behind `parallel`), so an + app that only exports textures needn't take the whole `craft-image-codecs` codec set and its + licences; `craft-image-codecs` reads and writes DDS through it. - [`craft-dialogs`](crates/dialogs/README.md): native file and message dialogs that never block the event loop: queued requests shown at the end of the frame and answered on a later frame, free-standing Open and Folder panels and Save sheets on macOS, case-insensitive filters. What @@ -249,7 +254,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit encoder, from PhotoCraft; includes a frame probe for routing. Metadata interpretation stays in each app. - [`craft-raster-codecs`](crates/raster-codecs/README.md): small raster formats, one module each, - from PhotoCraft: DDS (BC1 to BC3, read and write), DICOM, FITS (read and write), IFF/ILBM (read + from PhotoCraft: DDS (BC1 to BC3 read and write, BC4 and BC5 read), DICOM, FITS (read and write), IFF/ILBM (read and write), PCX, PNM/PAM/PFM (read and write) and XPM, into one flat image type. Bounded and panic-free on hostile input. Colour, orientation and the document mapping stay in each app. - [`craft-kiwi`](crates/kiwi/README.md): clean-room decoder and encoder for the kiwi binary schema diff --git a/crates/cms/src/curve.rs b/crates/cms/src/curve.rs index 5da1be801..6615a3882 100644 --- a/crates/cms/src/curve.rs +++ b/crates/cms/src/curve.rs @@ -26,6 +26,47 @@ pub fn srgb_trc() -> Curve { } impl Curve { + /// Creates a gamma curve `y = x^g`. Returns `Identity` if `g == 1.0` (within 1e-6). + pub fn gamma(g: f64) -> Result { + if !crate::math::fits_s15f16(g) || crate::math::s15f16_round(g) <= 0.0 { + return Err(crate::CmsError::InvalidArgument("gamma must remain positive and representable in ICC fixed point".into())); + } + if (g - 1.0).abs() < 1e-6 { Ok(Curve::Identity) } else { Ok(Curve::Gamma(g)) } + } + + /// Creates an ICC parametric curve (types 0 to 4). + pub fn parametric(kind: u16, p: [f64; 7]) -> Result { + if kind > 4 { + return Err(crate::CmsError::InvalidArgument(format!("parametric curve kind {kind} must be <= 4"))); + } + let count = Self::param_count(kind); + if !p.iter().take(count).all(|&v| crate::math::fits_s15f16(v)) { + return Err(crate::CmsError::InvalidArgument("parametric curve parameters must be representable in ICC fixed point".into())); + } + Ok(Curve::Parametric { kind, p }) + } + + /// Creates a sampled lookup table curve over evenly spaced inputs in `[0, 1]`. + pub fn from_table(samples: Vec) -> Result { + if samples.len() < 2 { + return Err(crate::CmsError::InvalidArgument("sampled curve must contain at least 2 entries".into())); + } + if !samples.iter().all(|s| s.is_finite() && (0.0..=1.0).contains(s)) { + return Err(crate::CmsError::InvalidArgument("sampled curve values must be finite and within [0, 1]".into())); + } + Ok(Curve::Table(samples)) + } + + /// Validate public enum variants before a profile stores them in ICC tags. + pub(crate) fn validate_icc(&self) -> Result<(), crate::CmsError> { + match self { + Self::Identity => Ok(()), + Self::Gamma(g) => Self::gamma(*g).map(|_| ()), + Self::Parametric { kind, p } => Self::parametric(*kind, *p).map(|_| ()), + Self::Table(t) if t.len() >= 2 && u32::try_from(t.len()).is_ok() && t.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) => Ok(()), + Self::Table(_) => Err(crate::CmsError::InvalidArgument("sampled curve must contain representable finite normalized samples".into())), + } + } /// Number of parameters stored for a parametric function type. pub fn param_count(kind: u16) -> usize { match kind { diff --git a/crates/cms/src/lib.rs b/crates/cms/src/lib.rs index 2f4abdc50..b082f67a5 100644 --- a/crates/cms/src/lib.rs +++ b/crates/cms/src/lib.rs @@ -45,6 +45,7 @@ pub use curve::Curve; pub use gamut::GamutCheck; pub use gpu_matrix_shaper::GpuMatrixShaper; pub use lut3d::Lut3d; +pub use math::Mat3; pub use named::{NamedColor, NamedColors}; pub use normalize::normalize_for_embedding; pub use profile::{ColorSpace, Pcs, Profile, ProfileClass}; diff --git a/crates/cms/src/math.rs b/crates/cms/src/math.rs index dbc686555..860126653 100644 --- a/crates/cms/src/math.rs +++ b/crates/cms/src/math.rs @@ -216,6 +216,12 @@ pub fn d50_quantized() -> [f64; 3] { [s15f16_round(D50[0]), s15f16_round(D50[1]), s15f16_round(D50[2])] } +/// Whether ICC s15Fixed16 encoding can round this value without saturation. +pub(crate) fn fits_s15f16(v: f64) -> bool { + let scaled = (v * 65536.0).round(); + scaled.is_finite() && scaled >= f64::from(i32::MIN) && scaled <= f64::from(i32::MAX) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/cms/src/profile.rs b/crates/cms/src/profile.rs index 6bd83a744..86624c1c9 100644 --- a/crates/cms/src/profile.rs +++ b/crates/cms/src/profile.rs @@ -182,6 +182,128 @@ pub struct Profile { } impl Profile { + /// Builds a matrix/TRC display profile from an already PCS D50-adapted colorant matrix, + /// a white point, and per-channel tone reproduction curves. + /// + /// # Matrix Coordinate Space + /// In accordance with ICC.1:2010 §9.2.35–37, the colorant matrix tags (`rXYZ`, `gXYZ`, `bXYZ`) + /// stored in an ICC profile must be chromatically adapted to the D50 Profile Connection Space (PCS). + /// `pcs_matrix` must therefore be expressed relative to D50 (e.g. as read directly from ICC profile tags). + /// + /// If `white` is not D50, the profile's `chad` tag is populated with the Bradford chromatic adaptation + /// matrix mapping `white` to D50. + pub fn matrix_shaper(white: [f64; 3], pcs_matrix: Mat3, trc: [Curve; 3]) -> Result { + for curve in &trc { + curve.validate_icc()?; + } + if !white.iter().all(|&c| math::fits_s15f16(c) && math::s15f16_round(c) > 0.0) { + return Err(CmsError::InvalidArgument("white point must remain positive and representable in ICC fixed point".into())); + } + if !pcs_matrix.iter().flatten().all(|&v| v.is_finite()) { + return Err(CmsError::InvalidArgument("matrix elements must be finite".into())); + } + if math::invert(&pcs_matrix).is_none() { + return Err(CmsError::InvalidArgument("colorant matrix must be invertible".into())); + } + + let d50 = math::d50_quantized(); + let is_d50 = (white[0] - math::D50[0]).abs() < 1e-4 && (white[1] - math::D50[1]).abs() < 1e-4 && (white[2] - math::D50[2]).abs() < 1e-4; + + let chad = if is_d50 { None } else { Some(math::bradford(white, math::D50)) }; + + // Quantize and normalize to ensure (1, 1, 1) maps exactly to PCS D50 + let mut q = pcs_matrix.map(|row| row.map(math::s15f16_round)); + for (i, row) in q.iter_mut().enumerate() { + let err = d50[i] - row.iter().sum::(); + let k = (0..3).max_by(|a, b| row[*a].abs().total_cmp(&row[*b].abs())).unwrap_or(0); + row[k] = math::s15f16_round(row[k] + err); + } + if !q.iter().flatten().all(|&v| math::fits_s15f16(v)) || math::invert(&q).is_none() { + return Err(CmsError::InvalidArgument("colorant matrix is singular or unrepresentable after quantization/normalization".into())); + } + let chad_quantized = chad.map(|a| a.map(|row| row.map(math::s15f16_round))); + // Positive finite XYZ inputs can still overflow Bradford cone ratios or quantization. + // Refuse invalid stored adaptation rather than serializing nonfinite coefficients. + if chad_quantized.as_ref().is_some_and(|a| !a.iter().flatten().all(|&v| math::fits_s15f16(v)) || math::invert(a).is_none()) { + return Err(CmsError::InvalidArgument("chromatic adaptation must remain representable and invertible after quantization".into())); + } + + Ok(Profile { + version: (4, 0x30), + class: ProfileClass::Display, + color_space: ColorSpace::Rgb, + pcs: Pcs::Xyz, + rendering_intent: Intent::RelativeColorimetric, + description: "Parametric Matrix/TRC".into(), + copyright: "".into(), + white_point: if is_d50 { d50 } else { white }, + black_point: None, + chad: chad_quantized, + matrix: Some(q), + trc: Some(trc), + gray_trc: None, + a2b: [None, None, None], + b2a: [None, None, None], + bytes: None, + hash: Default::default(), + }) + } + + /// Builds a matrix/TRC display profile from unadapted source primaries relative to `white`. + /// + /// The unadapted `source_matrix` (whose columns sum to `white`) is chromatically adapted to PCS D50 + /// using the Bradford transform before storage in the profile's matrix tags. + pub fn from_source_matrix(white: [f64; 3], source_matrix: Mat3, trc: [Curve; 3]) -> Result { + if !white.iter().all(|&c| math::fits_s15f16(c) && math::s15f16_round(c) > 0.0) { + return Err(CmsError::InvalidArgument("white point must remain positive and representable in ICC fixed point".into())); + } + if !source_matrix.iter().flatten().all(|&v| v.is_finite()) { + return Err(CmsError::InvalidArgument("matrix elements must be finite".into())); + } + if math::invert(&source_matrix).is_none() { + return Err(CmsError::InvalidArgument("colorant matrix must be invertible".into())); + } + + let is_d50 = (white[0] - math::D50[0]).abs() < 1e-4 && (white[1] - math::D50[1]).abs() < 1e-4 && (white[2] - math::D50[2]).abs() < 1e-4; + let pcs_matrix = if is_d50 { + source_matrix + } else { + let adapt = math::bradford(white, math::D50); + math::mul(&adapt, &source_matrix) + }; + + Self::matrix_shaper(white, pcs_matrix, trc) + } + + /// Builds a monochrome profile from a white point and tone reproduction curve. + pub fn gray(white: [f64; 3], trc: Curve) -> Result { + trc.validate_icc()?; + if !white.iter().all(|&c| math::fits_s15f16(c) && math::s15f16_round(c) > 0.0) { + return Err(CmsError::InvalidArgument("white point must remain positive and representable in ICC fixed point".into())); + } + let is_d50 = (white[0] - math::D50[0]).abs() < 1e-4 && (white[1] - math::D50[1]).abs() < 1e-4 && (white[2] - math::D50[2]).abs() < 1e-4; + + Ok(Profile { + version: (4, 0x30), + class: ProfileClass::Display, + color_space: ColorSpace::Gray, + pcs: Pcs::Xyz, + rendering_intent: Intent::RelativeColorimetric, + description: "Parametric Gray".into(), + copyright: "".into(), + white_point: if is_d50 { math::d50_quantized() } else { white }, + black_point: None, + chad: None, + matrix: None, + trc: None, + gray_trc: Some(trc), + a2b: [None, None, None], + b2a: [None, None, None], + bytes: None, + hash: Default::default(), + }) + } + /// Parses ICC profile bytes. pub fn parse(bytes: &[u8]) -> Result { CURVE_SAMPLES_LEFT.with(|left| left.set(MAX_CURVE_SAMPLES)); diff --git a/crates/cms/tests/constructors.rs b/crates/cms/tests/constructors.rs new file mode 100644 index 000000000..aabb313ab --- /dev/null +++ b/crates/cms/tests/constructors.rs @@ -0,0 +1,183 @@ +use craft_cms::{Builtin, Curve, Intent, Mat3, Profile, Transform}; + +#[test] +fn test_curve_constructors() { + // Gamma + let g22 = Curve::gamma(2.2).expect("valid gamma"); + assert_eq!(g22, Curve::Gamma(2.2)); + + let g10 = Curve::gamma(1.0).expect("gamma 1.0 is identity"); + assert_eq!(g10, Curve::Identity); + + let g_near = Curve::gamma(1.0 + 1e-7).expect("near-identity gamma normalized"); + assert_eq!(g_near, Curve::Identity); + + assert!(Curve::gamma(0.0).is_err()); + assert!(Curve::gamma(-2.2).is_err()); + assert!(Curve::gamma(f64::NAN).is_err()); + assert!(Curve::gamma(f64::INFINITY).is_err()); + + // Parametric + let p0 = Curve::parametric(0, [2.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]).expect("valid parametric type 0"); + assert_eq!(p0, Curve::Parametric { kind: 0, p: [2.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }); + + assert!(Curve::parametric(5, [0.0; 7]).is_err()); + assert!(Curve::parametric(0, [f64::NAN, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]).is_err()); + + // Sampled table + let table = Curve::from_table(vec![0.0, 0.5, 1.0]).expect("valid sampled table"); + assert_eq!(table, Curve::Table(vec![0.0, 0.5, 1.0])); + + assert!(Curve::from_table(vec![0.5]).is_err()); + assert!(Curve::from_table(vec![0.0, f32::NAN]).is_err()); + assert!(Curve::from_table(vec![0.0, -0.1, 1.0]).is_err()); + assert!(Curve::from_table(vec![0.0, 2.0]).is_err()); + assert!(Curve::from_table(vec![0.0, 1.0001]).is_err()); +} + +#[test] +fn test_profile_constructors() { + let srgb = Builtin::Srgb.profile(); + let white_d65 = [0.95047, 1.0, 1.08883]; + + // 1. Matrix shaper with already PCS D50-adapted matrix (e.g. read from ICC tags) + let pcs_d50_matrix: Mat3 = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]]; + let trc = [craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc()]; + let custom_from_pcs = Profile::matrix_shaper(white_d65, pcs_d50_matrix, trc.clone()).expect("matrix shaper from PCS D50"); + assert_eq!(custom_from_pcs.color_space, craft_cms::ColorSpace::Rgb); + assert!(custom_from_pcs.same_colors(srgb), "custom profile from PCS D50 matrix should match reference sRGB"); + + // 2. Matrix shaper from unadapted D65 source primaries (undergoes single Bradford adaptation) + let source_d65_matrix: Mat3 = [[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]]; + let custom_from_source = Profile::from_source_matrix(white_d65, source_d65_matrix, trc).expect("matrix shaper from source"); + assert!(custom_from_source.same_colors(srgb), "custom profile adapted from source primaries should match reference sRGB"); + + // Evaluate transform + let xform = Transform::new(&custom_from_pcs, srgb, Intent::RelativeColorimetric, true).expect("transform from custom RGB to sRGB"); + let mut out = [0.0f32; 3]; + xform.eval(&[0.5, 0.5, 0.5], &mut out).expect("eval"); + assert!((out[0] - 0.5).abs() < 1e-2); + assert!((out[1] - 0.5).abs() < 1e-2); + assert!((out[2] - 0.5).abs() < 1e-2); + + // Invalid matrix shaper inputs + assert!(Profile::matrix_shaper([0.0, 1.0, 1.0], pcs_d50_matrix, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err()); + assert!(Profile::matrix_shaper([f64::NAN, 1.0, 1.0], pcs_d50_matrix, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err()); + let singular: Mat3 = [[0.0; 3]; 3]; + assert!(Profile::matrix_shaper(white_d65, singular, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err()); + + // Near-degenerate matrix that is invertible before quantization but becomes singular after + let d50 = [0.9642, 1.0, 0.8249]; + let near_degenerate: Mat3 = [[d50[0] - 0.000001, 0.000001, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, d50[2]]]; + assert!(Profile::matrix_shaper(d50, near_degenerate, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err()); + + // Gray profile + let gray = Profile::gray(white_d65, Curve::gamma(2.2).expect("curve")).expect("gray profile"); + assert_eq!(gray.color_space, craft_cms::ColorSpace::Gray); + + let gray_to_srgb = Transform::new(&gray, srgb, Intent::RelativeColorimetric, true).expect("transform from gray to sRGB"); + let mut srgb_out = [0.0f32; 3]; + gray_to_srgb.eval(&[0.5], &mut srgb_out).expect("eval"); + assert!((srgb_out[0] - srgb_out[1]).abs() < 1e-3); + assert!((srgb_out[1] - srgb_out[2]).abs() < 1e-3); +} + +#[test] +fn test_matrix_constructors_against_independent_moxcms_oracle() { + use moxcms::{ColorProfile, Layout, TransformOptions as MoxOpts}; + + let srgb = Builtin::Srgb.profile(); + let white_d65 = [0.95047, 1.0, 1.08883]; + + // 1. PCS D50-adapted matrix profile + let pcs_d50_matrix: Mat3 = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]]; + let trc = [craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc()]; + let custom_from_pcs = Profile::matrix_shaper(white_d65, pcs_d50_matrix, trc.clone()).expect("matrix shaper from PCS D50"); + + // 2. Unadapted source matrix profile + let source_d65_matrix: Mat3 = [[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]]; + let custom_from_source = Profile::from_source_matrix(white_d65, source_d65_matrix, trc).expect("matrix shaper from source"); + + // Convert both to standard ICC bytes and parse with independent oracle moxcms + let mox_from_pcs = ColorProfile::new_from_slice(&custom_from_pcs.to_bytes()).expect("moxcms parse custom PCS profile"); + let mox_from_source = ColorProfile::new_from_slice(&custom_from_source.to_bytes()).expect("moxcms parse custom source profile"); + let mox_dst_srgb = ColorProfile::new_from_slice(&srgb.to_bytes()).expect("moxcms parse builtin sRGB"); + + let test_pixels: Vec = (0..512u32).flat_map(|i| [(i * 17 % 256) as u8, (i * 53 % 256) as u8, (i * 97 % 256) as u8]).collect(); + + // Verify 1: moxcms transforming custom_from_pcs -> builtin sRGB produces identity (diff <= 1) + let mox_xform_pcs = mox_from_pcs.create_transform_8bit(Layout::Rgb, &mox_dst_srgb, Layout::Rgb, MoxOpts::default()).unwrap(); + let mut mox_out_pcs = vec![0u8; test_pixels.len()]; + mox_xform_pcs.transform(&test_pixels, &mut mox_out_pcs).unwrap(); + let max_diff_pcs = test_pixels.iter().zip(&mox_out_pcs).map(|(a, b)| (*a as i32 - *b as i32).abs()).max().unwrap(); + assert!(max_diff_pcs <= 1, "moxcms PCS-adapted profile -> sRGB max diff was {max_diff_pcs}"); + + // Verify 2: moxcms transforming custom_from_source -> builtin sRGB produces identity (diff <= 1) + let mox_xform_src = mox_from_source.create_transform_8bit(Layout::Rgb, &mox_dst_srgb, Layout::Rgb, MoxOpts::default()).unwrap(); + let mut mox_out_src = vec![0u8; test_pixels.len()]; + mox_xform_src.transform(&test_pixels, &mut mox_out_src).unwrap(); + let max_diff_src = test_pixels.iter().zip(&mox_out_src).map(|(a, b)| (*a as i32 - *b as i32).abs()).max().unwrap(); + assert!(max_diff_src <= 1, "moxcms source-adapted profile -> sRGB max diff was {max_diff_src}"); + + // Verify 3: craft_cms and moxcms agree when converting from custom_from_source to DisplayP3 + let p3 = Builtin::DisplayP3.profile(); + let mox_dst_p3 = ColorProfile::new_from_slice(&p3.to_bytes()).expect("moxcms parse Display P3"); + let mox_xform_p3 = mox_from_source.create_transform_8bit(Layout::Rgb, &mox_dst_p3, Layout::Rgb, MoxOpts::default()).unwrap(); + let mut mox_p3_out = vec![0u8; test_pixels.len()]; + mox_xform_p3.transform(&test_pixels, &mut mox_p3_out).unwrap(); + + let ours_xform_p3 = Transform::new(&custom_from_source, p3, Intent::RelativeColorimetric, false).unwrap(); + let mut ours_p3_out = vec![0u8; test_pixels.len()]; + ours_xform_p3.convert_u8(&test_pixels, 3, &mut ours_p3_out, 3, false).unwrap(); + + let max_p3_diff = ours_p3_out.iter().zip(&mox_p3_out).map(|(a, b)| (*a as i32 - *b as i32).abs()).max().unwrap(); + assert!(max_p3_diff <= 1, "craft_cms vs moxcms custom source profile -> P3 max diff was {max_p3_diff}"); +} + +#[test] +fn constructor_never_returns_a_nonfinite_adaptation() { + let matrix = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]]; + for white in [[f64::MAX; 3], [f64::MIN_POSITIVE; 3], [1.0, 1.0, (0.8951 + 0.2664) / 0.1614]] { + if let Ok(profile) = Profile::matrix_shaper(white, matrix, [Curve::Identity, Curve::Identity, Curve::Identity]) { + assert!(profile.chad.unwrap().iter().flatten().all(|v| v.is_finite()), "nonfinite adaptation for {white:?}"); + } + } +} + +#[test] +fn constructors_reject_values_that_saturate_icc_fixed_point() { + assert!(Profile::gray([f64::MAX; 3], Curve::Identity).is_err()); + assert!(Profile::gray([f64::MIN_POSITIVE; 3], Curve::Identity).is_err()); + assert!(Curve::gamma(32768.0).is_err()); + assert!(Curve::gamma(f64::MIN_POSITIVE).is_err()); + assert!(Curve::parametric(0, [32768.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]).is_err()); + let matrix = [[40000.0, -39999.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + assert!(Profile::matrix_shaper([0.9642, 1.0, 0.8249], matrix, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err()); +} + +#[test] +fn profile_constructors_validate_direct_curve_variants() { + let white = [0.9642, 1.0, 0.8249]; + let matrix = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]]; + for curve in [ + Curve::Gamma(f64::NAN), + Curve::Gamma(32768.0), + Curve::Parametric { kind: 5, p: [0.0; 7] }, + Curve::Table(vec![0.0, f32::NAN]), + Curve::Table(vec![]), + ] { + assert!(Profile::gray(white, curve.clone()).is_err()); + assert!(Profile::matrix_shaper(white, matrix, [curve.clone(), Curve::Identity, Curve::Identity]).is_err()); + assert!(Profile::from_source_matrix(white, matrix, [Curve::Identity, Curve::Identity, curve]).is_err()); + } +} + +#[test] +fn icc_fixed_point_boundaries_remain_accepted() { + let max = f64::from(i32::MAX) / 65536.0; + let min = f64::from(i32::MIN) / 65536.0; + assert!(Curve::gamma(max).is_ok()); + assert!(Curve::gamma(1.0 / 65536.0).is_ok()); + assert!(Curve::parametric(4, [1.0, 1.0, min, max, 0.0, 0.0, 0.0]).is_ok()); + assert!(Profile::gray([max; 3], Curve::Identity).is_ok()); +} diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml new file mode 100644 index 000000000..44578baed --- /dev/null +++ b/crates/color/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-color" +description = "Colour tags, Y'CbCr matrices, transfer functions and HDR static metadata for compositor and display frames" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +serde = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs new file mode 100644 index 000000000..dfbdf1787 --- /dev/null +++ b/crates/color/src/lib.rs @@ -0,0 +1,440 @@ +//! Colour tags and the conversions compositor and display frames need. +//! +//! This is the slim colour-metadata layer used by craft-frame and by media +//! `MediaInfo`: [`ColorInfo`] (matrix, transfer, primaries, range), [`HdrMetadata`], Y'CbCr +//! matrices, transfer functions, and a few helpers (sRGB tables, HSL, hex). It is not a +//! colour-managed pipeline: LUTs, camera log, grade and tone mapping stay out. +//! +//! Came from FilmCraft's `filmcraft-color` (the metadata and transfer part of that crate). +//! Distinct from `craft-video`'s decoder colour tags (`ColorTags` in #1231 / #1768). + +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] + +use serde::{Deserialize, Serialize}; +use std::sync::OnceLock; + +/// HDR reference white in cd/m² (ITU-R BT.2408). +pub const REFERENCE_WHITE_NITS: f64 = 203.0; + +/// YUV ↔ RGB matrix coefficients. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Matrix { + Bt601, + #[default] + Bt709, + Bt2020Ncl, +} + +impl Matrix { + /// (Kr, Kb) luma coefficients. + pub fn kr_kb(self) -> (f32, f32) { + match self { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020Ncl => (0.2627, 0.0593), + } + } + /// From an ISO/IEC 23091-2 `matrix_coefficients` code. + pub fn from_code(c: u8) -> Option { + match c { + 1 => Some(Matrix::Bt709), + 5 | 6 => Some(Matrix::Bt601), + // H.273 table 4: code 10 is constant luminance, not this matrix. + 9 => Some(Matrix::Bt2020Ncl), + _ => None, + } + } +} + +/// Transfer characteristics. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Transfer { + /// BT.709 display, approximated with the sRGB curve by this slim conversion layer. + /// This is not a pure-gamma BT.1886 decode. + #[default] + Bt709, + Srgb, + Linear, + /// SMPTE ST 2084. + Pq, + /// ARIB STD-B67. + Hlg, +} + +impl Transfer { + /// From an ISO/IEC 23091-2 `transfer_characteristics` code. + pub fn from_code(c: u8) -> Option { + match c { + 1 | 6 | 14 | 15 => Some(Transfer::Bt709), + 13 => Some(Transfer::Srgb), + 8 => Some(Transfer::Linear), + 16 => Some(Transfer::Pq), + 18 => Some(Transfer::Hlg), + _ => None, + } + } +} + +/// Chromaticity primaries. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Primaries { + #[default] + Bt709, + Bt601_625, + Bt601_525, + Bt2020, + P3D65, +} + +/// Quantisation range of integer Y'CbCr samples. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Range { + /// 16–235 (8-bit) "video" range. + #[default] + Limited, + Full, +} + +/// Colour metadata attached to a compositor or display frame. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct ColorInfo { + pub matrix: Matrix, + pub transfer: Transfer, + pub primaries: Primaries, + pub range: Range, +} + +impl ColorInfo { + pub const SRGB_FULL: ColorInfo = ColorInfo { matrix: Matrix::Bt709, transfer: Transfer::Srgb, primaries: Primaries::Bt709, range: Range::Full }; + pub const REC709: ColorInfo = ColorInfo { matrix: Matrix::Bt709, transfer: Transfer::Bt709, primaries: Primaries::Bt709, range: Range::Limited }; +} + +/// HDR static metadata of a stream: SMPTE ST 2086 mastering display luminance and the CTA-861.3 +/// content light levels (MaxCLL / MaxFALL), in cd/m². Read from `mdcv` / `clli` (MP4 / MOV) and +/// Matroska `MasteringMetadata` / `MaxCLL` / `MaxFALL`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct HdrMetadata { + pub mastering_max_nits: Option, + pub mastering_min_nits: Option, + pub max_cll: Option, + pub max_fall: Option, +} + +impl HdrMetadata { + /// The content's peak for tone mapping: MaxCLL when signalled (the brightest pixel actually + /// in the content), else the mastering display's peak; `None` when neither is (0 means + /// unknown in both). Never below HDR reference white. + pub fn peak_nits(&self) -> Option { + let known = |v: Option| v.filter(|n| *n > 0.0); + let p = match (known(self.max_cll), known(self.mastering_max_nits)) { + (Some(c), _) => c, + (None, m) => m?, + }; + Some(p.clamp(REFERENCE_WHITE_NITS as f32, 10_000.0)) + } +} + +/// Convert normalised Y'CbCr (Y in 0..1, Cb/Cr in -0.5..0.5) to non-linear R'G'B'. +#[inline] +pub fn ycbcr_to_rgb(y: f32, cb: f32, cr: f32, m: Matrix) -> [f32; 3] { + let (kr, kb) = m.kr_kb(); + let kg = 1.0 - kr - kb; + let r = y + 2.0 * (1.0 - kr) * cr; + let b = y + 2.0 * (1.0 - kb) * cb; + let g = (y - kr * r - kb * b) / kg; + [r, g, b] +} + +/// Convert non-linear R'G'B' to normalised Y'CbCr. +#[inline] +pub fn rgb_to_ycbcr(r: f32, g: f32, b: f32, m: Matrix) -> [f32; 3] { + let (kr, kb) = m.kr_kb(); + let kg = 1.0 - kr - kb; + let y = kr * r + kg * g + kb * b; + [y, (b - y) / (2.0 * (1.0 - kb)), (r - y) / (2.0 * (1.0 - kr))] +} + +/// Unsupported integer sample depth. Normalization supports 8 through 16 bits. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvalidBitDepth(pub u32); + +impl std::fmt::Display for InvalidBitDepth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "unsupported sample bit depth {}; expected 8..=16", self.0) + } +} +impl std::error::Error for InvalidBitDepth {} + +/// Normalise an integer luma code value to 0..1 given bit depth and range. +#[inline] +pub fn normalize_y(v: u32, bits: u32, range: Range) -> Result { + if !(8..=16).contains(&bits) { + return Err(InvalidBitDepth(bits)); + } + let scale = (1u32 << (bits - 8)) as f32; + Ok(match range { + Range::Limited => (v as f32 - 16.0 * scale) / (219.0 * scale), + Range::Full => v as f32 / ((1u32 << bits) - 1) as f32, + }) +} + +/// Normalise an integer chroma code value to −0.5..0.5 given bit depth and range. +#[inline] +pub fn normalize_c(v: u32, bits: u32, range: Range) -> Result { + if !(8..=16).contains(&bits) { + return Err(InvalidBitDepth(bits)); + } + let scale = (1u32 << (bits - 8)) as f32; + Ok(match range { + Range::Limited => (v as f32 - 128.0 * scale) / (224.0 * scale), + Range::Full => (v as f32 - (1u32 << (bits - 1)) as f32) / ((1u32 << bits) - 1) as f32, + }) +} + +/// sRGB electro-optical transfer (encoded → linear). +#[inline] +pub fn srgb_to_linear(v: f32) -> f32 { + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } +} + +/// sRGB inverse EOTF (linear → encoded). +#[inline] +pub fn linear_to_srgb(v: f32) -> f32 { + if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } +} + +/// Encoded → linear for a transfer function (display-referred; PQ normalised to 100 nits = 1.0). +pub fn to_linear(v: f32, t: Transfer) -> f32 { + match t { + Transfer::Srgb => srgb_to_linear(v), + // Rec.709 is treated as display gamma 2.4; the sRGB curve is visually identical for + // previews and keeps round-trips exact. + Transfer::Bt709 => srgb_to_linear(v), + Transfer::Linear => v, + Transfer::Pq => pq_eotf(v) * 100.0, + Transfer::Hlg => hlg_inverse_oetf(v), + } +} + +/// Linear → encoded for a transfer function (the inverse of [`to_linear`]). +pub fn from_linear(v: f32, t: Transfer) -> f32 { + match t { + Transfer::Srgb | Transfer::Bt709 => linear_to_srgb(v), + Transfer::Linear => v, + Transfer::Pq => pq_inverse_eotf(v / 100.0), + Transfer::Hlg => hlg_oetf(v), + } +} + +/// SMPTE ST 2084 EOTF, output normalised to 10 000 nits = 1.0. +pub fn pq_eotf(e: f32) -> f32 { + let (m1, m2) = (0.159_301_76_f32, 78.84375_f32); + let (c1, c2, c3) = (0.835_937_5_f32, 18.851_563_f32, 18.6875_f32); + let p = e.max(0.0).powf(1.0 / m2); + ((p - c1).max(0.0) / (c2 - c3 * p)).powf(1.0 / m1) +} + +/// Inverse of [`pq_eotf`]. +pub fn pq_inverse_eotf(y: f32) -> f32 { + let (m1, m2) = (0.159_301_76_f32, 78.84375_f32); + let (c1, c2, c3) = (0.835_937_5_f32, 18.851_563_f32, 18.6875_f32); + let p = y.max(0.0).powf(m1); + ((c1 + c2 * p) / (1.0 + c3 * p)).powf(m2) +} + +/// ARIB STD-B67 HLG OETF. +pub fn hlg_oetf(l: f32) -> f32 { + let (a, b, c) = (0.178_832_77_f32, 0.284_668_92_f32, 0.559_910_7_f32); + if l <= 1.0 / 12.0 { (3.0 * l.max(0.0)).sqrt() } else { a * (12.0 * l - b).ln() + c } +} + +/// Inverse of [`hlg_oetf`]. +pub fn hlg_inverse_oetf(e: f32) -> f32 { + let (a, b, c) = (0.178_832_77_f32, 0.284_668_92_f32, 0.559_910_7_f32); + if e <= 0.5 { e * e / 3.0 } else { (((e - c) / a).exp() + b) / 12.0 } +} + +/// 256-entry table: sRGB-encoded u8 → linear f32. +pub fn srgb_u8_to_linear_table() -> &'static [f32; 256] { + static T: OnceLock<[f32; 256]> = OnceLock::new(); + T.get_or_init(|| std::array::from_fn(|i| srgb_to_linear(i as f32 / 255.0))) +} + +/// 4096-entry table: linear (0..1, quantised to 12 bits) → sRGB-encoded u8. +pub fn linear_to_srgb_u8_table() -> &'static [u8; 4096] { + static T: OnceLock<[u8; 4096]> = OnceLock::new(); + T.get_or_init(|| std::array::from_fn(|i| (linear_to_srgb(i as f32 / 4095.0) * 255.0 + 0.5).clamp(0.0, 255.0) as u8)) +} + +/// Linear 0..1 to an sRGB-encoded u8, via [`linear_to_srgb_u8_table`]. +#[inline] +pub fn linear_to_srgb_u8(v: f32) -> u8 { + let i = (v.clamp(0.0, 1.0) * 4095.0 + 0.5) as usize; + linear_to_srgb_u8_table()[i] +} + +/// Rec.709 luma of a linear or encoded RGB triple. +#[inline] +pub fn luma709(r: f32, g: f32, b: f32) -> f32 { + 0.2126 * r + 0.7152 * g + 0.0722 * b +} + +/// RGB (0..1) → HSL (h in 0..1). +pub fn rgb_to_hsl(r: f32, g: f32, b: f32) -> [f32; 3] { + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let l = (max + min) / 2.0; + if (max - min).abs() < 1e-7 { + return [0.0, 0.0, l]; + } + let d = max - min; + let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) }; + let h = if max == r { + (g - b) / d + if g < b { 6.0 } else { 0.0 } + } else if max == g { + (b - r) / d + 2.0 + } else { + (r - g) / d + 4.0 + }; + [h / 6.0, s, l] +} + +/// Inverse of [`rgb_to_hsl`]. +pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] { + if s <= 0.0 { + return [l, l, l]; + } + let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s }; + let p = 2.0 * l - q; + let f = |mut t: f32| { + t = t.rem_euclid(1.0); + if t < 1.0 / 6.0 { + p + (q - p) * 6.0 * t + } else if t < 0.5 { + q + } else if t < 2.0 / 3.0 { + p + (q - p) * (2.0 / 3.0 - t) * 6.0 + } else { + p + } + }; + [f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0)] +} + +/// Parse `#rrggbb` / `#rrggbbaa` into 0..1 floats. +pub fn parse_hex(s: &str) -> Option<[f32; 4]> { + let s = s.trim(); + let s = s.strip_prefix('#').unwrap_or(s); + if !s.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let b = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| v as f32 / 255.0); + match s.len() { + 6 => Some([b(0)?, b(2)?, b(4)?, 1.0]), + 8 => Some([b(0)?, b(2)?, b(4)?, b(6)?]), + _ => None, + } +} + +/// The inverse of [`parse_hex`], lowercase, omitting alpha when it is 1. +pub fn to_hex(c: [f32; 4]) -> String { + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if c[3] >= 0.999 { + format!("#{:02x}{:02x}{:02x}", q(c[0]), q(c[1]), q(c[2])) + } else { + format!("#{:02x}{:02x}{:02x}{:02x}", q(c[0]), q(c[1]), q(c[2]), q(c[3])) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_hex_rejects_signs() { + assert_eq!(parse_hex("#+f+f+f"), None); + assert_eq!(parse_hex("#-f-f-f"), None); + assert_eq!(parse_hex("##0f0f0f"), None); + assert_eq!(parse_hex("#0f0f0"), None); + assert!(parse_hex("#0f0f0f").is_some()); + assert!(parse_hex("0f0f0f80").is_some()); + } + + #[test] + fn ycbcr_roundtrip() { + for m in [Matrix::Bt601, Matrix::Bt709, Matrix::Bt2020Ncl] { + let rgb = [0.8, 0.3, 0.1]; + let y = rgb_to_ycbcr(rgb[0], rgb[1], rgb[2], m); + let back = ycbcr_to_rgb(y[0], y[1], y[2], m); + for k in 0..3 { + assert!((rgb[k] - back[k]).abs() < 1e-5); + } + } + } + + #[test] + fn invalid_bit_depths_are_errors_not_shifts() { + for bits in [0, 1, 7, 17, 31, 32, u32::MAX] { + assert_eq!(normalize_y(0, bits, Range::Full), Err(InvalidBitDepth(bits))); + assert_eq!(normalize_c(0, bits, Range::Limited), Err(InvalidBitDepth(bits))); + } + } + + #[test] + fn limited_range_levels() { + assert_eq!(normalize_y(16, 8, Range::Limited).unwrap(), 0.0); + assert_eq!(normalize_y(235, 8, Range::Limited).unwrap(), 1.0); + assert_eq!(normalize_y(940, 10, Range::Limited).unwrap(), 1.0); + assert_eq!(normalize_c(128, 8, Range::Limited).unwrap(), 0.0); + } + + #[test] + fn transfer_roundtrips() { + for t in [Transfer::Srgb, Transfer::Pq, Transfer::Hlg, Transfer::Linear] { + for v in [0.0, 0.1, 0.5, 0.9] { + let l = to_linear(v, t); + assert!((from_linear(l, t) - v).abs() < 1e-3, "{t:?} {v}"); + } + } + assert_eq!(linear_to_srgb_u8(1.0), 255); + assert_eq!(linear_to_srgb_u8(0.0), 0); + assert_eq!(linear_to_srgb_u8(srgb_u8_to_linear_table()[128]), 128); + } + + #[test] + fn hsl_roundtrip() { + let c = [0.2, 0.6, 0.9]; + let h = rgb_to_hsl(c[0], c[1], c[2]); + let b = hsl_to_rgb(h[0], h[1], h[2]); + for k in 0..3 { + assert!((c[k] - b[k]).abs() < 1e-5); + } + } + + #[test] + fn hex() { + assert_eq!(parse_hex("#ff8000"), Some([1.0, 128.0 / 255.0, 0.0, 1.0])); + assert_eq!(to_hex([1.0, 0.0, 0.0, 1.0]), "#ff0000"); + } + + #[test] + fn hdr_peak_nits() { + assert_eq!(HdrMetadata::default().peak_nits(), None); + assert_eq!(HdrMetadata { max_cll: Some(4000.0), mastering_max_nits: Some(1000.0), ..HdrMetadata::default() }.peak_nits(), Some(4000.0)); + assert_eq!(HdrMetadata { max_cll: Some(1000.0), mastering_max_nits: Some(4000.0), ..HdrMetadata::default() }.peak_nits(), Some(1000.0)); + assert_eq!(HdrMetadata { max_cll: Some(0.0), mastering_max_nits: Some(400.0), ..HdrMetadata::default() }.peak_nits(), Some(400.0)); + // never below reference white + assert_eq!(HdrMetadata { max_cll: Some(100.0), ..HdrMetadata::default() }.peak_nits(), Some(REFERENCE_WHITE_NITS as f32)); + } + + #[test] + fn codes() { + assert_eq!(Matrix::from_code(9), Some(Matrix::Bt2020Ncl)); + assert_eq!(Matrix::from_code(10), None); + assert_eq!(Matrix::from_code(1), Some(Matrix::Bt709)); + assert_eq!(Matrix::from_code(6), Some(Matrix::Bt601)); + assert_eq!(Transfer::from_code(16), Some(Transfer::Pq)); + assert_eq!(Transfer::from_code(99), None); + } +} diff --git a/crates/dds/Cargo.toml b/crates/dds/Cargo.toml new file mode 100644 index 000000000..f93e8cbcc --- /dev/null +++ b/crates/dds/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-dds" +description = "DirectDraw Surface (DDS) textures: uncompressed and BC1-BC5 block compression, read and write, without dependencies" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +default = [] +# Encode and decode rows of blocks (and mip levels) on several threads. +parallel = ["dep:rayon"] + +[dependencies] +rayon = { workspace = true, optional = true } diff --git a/crates/dds/README.md b/crates/dds/README.md new file mode 100644 index 000000000..a3f81e50b --- /dev/null +++ b/crates/dds/README.md @@ -0,0 +1,52 @@ +# craft-dds + +DirectDraw Surface (DDS) textures, after Microsoft's public DDS and block-compression +documentation, with no dependencies. `craft-image-codecs` reads and writes DDS through this +crate and re-exports its `DdsCompression` and `DdsOptions`; an app that only needs DDS (a texture +exporter, say) can depend on it alone and leave out the other codecs and their licences. + +```toml +craft-dds = { git = "https://github.com/storytold/craft-libs", rev = "" } +``` + +| | Read | Write | +|---|---|---| +| Uncompressed | 8, 16, 24 or 32 bits per pixel described by channel masks, RGB or luminance, with or without alpha; padded rows (`DDSD_PITCH`) | BGRA, BGRX, luminance, luminance with alpha | +| Block-compressed | BC1, BC2, BC3 (DXT1, DXT3, DXT5); unsigned BC4 (ATI1, BC4U, DXGI 79 and 80) and BC5 (ATI2, BC5U, DXGI 82 and 83) | BC1, BC2, BC3, BC4, BC5 | +| Headers | legacy and DX10 | legacy; DX10 for BC4 and BC5 | +| Mip levels | the top level only | optional full chain, box-filtered | + +Cubemaps, texture arrays, volume textures, premultiplied-alpha textures (DXT2/DXT4, or DX10 alpha mode 2), signed (SNORM) BC4/BC5 and +the other DXGI formats (BC6H, BC7, float) are refused with `DdsError::Unsupported` rather than read +in part. + +Pixels are 8 bits per channel, interleaved and top row first, in one of four `Layout`s (`Gray`, +`GrayA`, `Rgb`, `Rgba`). BC1 to BC3 are written from RGBA, BC4 from gray and BC5 from RGB +(`DdsCompression::layout` names it). BC4 reads back as gray. BC5 stores red and green only, so it +reads back as RGB with blue 0: for a tangent-space normal map, X and Y, with Z left to the +renderer. ATI2 files are read as Microsoft's tools read them (red in the first block), not with +the two blocks swapped as FFmpeg does. + +```rust +use craft_dds::{DdsCompression, DdsOptions, Layout, Texture}; + +let pixels = [10, 20, 30, 255].repeat(6 * 5); +let file = craft_dds::encode(6, 5, Layout::Rgba, &pixels, DdsOptions { compression: DdsCompression::Bc1, mipmaps: true })?; +// The header first: the size and layout are known before anything is allocated. +let texture = Texture::parse(&file)?; +assert_eq!((texture.width(), texture.height(), texture.layout()), (6, 5, Layout::Rgba)); +let decoded = texture.decode()?; +``` + +`Texture::parse` requires a complete header and nonzero dimensions. `Texture::decode` bounds its output buffer to 1 GiB; use `decode_with_limit(max_bytes)` for an explicit per-buffer budget. Allocation is fallible. This is not a total process memory limit. The `craft-image-codecs` adapter forwards its own existing `Limits::max_alloc` instead of imposing the standalone default. + +The block encoder is our own: RGB565 endpoints fitted along each block's principal axis and +refined by least squares, indices picked against the palette the reader decodes; BC1 turns texels +under half opacity into its transparent black, and BC3, BC4 and BC5 pick whichever mode of their +value blocks fits. The block functions don't depend on the DDS header, so other containers of +the same blocks can share them. + +## Features + +- `parallel`: encodes and decodes rows of blocks (and mip levels) on several threads with rayon. + `craft-image-codecs` turns it on for native targets. diff --git a/crates/image-codecs/src/codecs/dds_bc.rs b/crates/dds/src/bc.rs similarity index 61% rename from crates/image-codecs/src/codecs/dds_bc.rs rename to crates/dds/src/bc.rs index df60e462c..863aa3077 100644 --- a/crates/image-codecs/src/codecs/dds_bc.rs +++ b/crates/dds/src/bc.rs @@ -1,6 +1,10 @@ -//! BC1, BC2 and BC3 (DXT1, DXT3, DXT5) blocks, after Microsoft's public block compression +//! BC1 to BC5 (DXT1, DXT3, DXT5, ATI1, ATI2) blocks, after Microsoft's public block compression //! documentation ("Block Compression (Direct3D 10)" and "Texture Block Compression in Direct3D -//! 11"): the palettes the DDS reader decodes with, and the block encoder the DDS writer uses. +//! 11"): the block decoders and the block encoder the DDS reader and writer use. Nothing here +//! knows about DDS headers, so other containers of the same blocks can use it. +//! +//! BC4 is one block of 16 single-channel values, the same block BC3 stores its alpha in; BC5 is +//! two of them, red then green. [`value_block`] and [`decode_values`] serve all three. //! //! The encoder fits a block's colours with two RGB565 endpoints along their principal axis, //! refines them by least squares, and scores every candidate against the exact palette the @@ -35,7 +39,7 @@ pub(crate) fn colour_palette(c0: u16, c1: u16, four: bool) -> [[u8; 4]; 4] { } } -/// A BC3 alpha block's eight values: six interpolated at sevenths when `a0 > a1`, else four +/// A value block's eight values: six interpolated at sevenths when `a0 > a1`, else four /// interpolated at fifths followed by 0 and 255. pub(crate) fn alpha_palette(a0: u8, a1: u8) -> [u8; 8] { let (a0, a1) = (u32::from(a0), u32::from(a1)); @@ -54,6 +58,32 @@ pub(crate) fn alpha_palette(a0: u8, a1: u8) -> [u8; 8] { palette.map(|v| v as u8) } +/// A colour block's 16 texels as RGBA. BC2 and BC3 colour blocks always have four colours +/// (`one_bit_alpha` false); only BC1's `c0 <= c1` order selects three colours and transparent +/// black. Missing bytes read as 0. +pub(crate) fn decode_colour(block: &[u8], one_bit_alpha: bool) -> Block { + let byte = |i: usize| block.get(i).copied().unwrap_or(0); + let (c0, c1) = (u16::from_le_bytes([byte(0), byte(1)]), u16::from_le_bytes([byte(2), byte(3)])); + let palette = colour_palette(c0, c1, c0 > c1 || !one_bit_alpha); + let indices = u32::from_le_bytes([byte(4), byte(5), byte(6), byte(7)]); + std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) +} + +/// BC2's alpha: four explicit bits per texel. +pub(crate) fn decode_bc2_alpha(block: &[u8]) -> [u8; 16] { + let bits = u64::from_le_bytes(std::array::from_fn(|i| block.get(i).copied().unwrap_or(0))); + std::array::from_fn(|t| ((bits >> (4 * t)) & 0xf) as u8 * 17) +} + +/// A value block (BC3's alpha, BC4, either half of BC5): two endpoints and a 3-bit index per +/// texel into eight values, or into six plus 0 and 255 when `a0 <= a1`. Missing bytes read as 0. +pub(crate) fn decode_values(block: &[u8]) -> [u8; 16] { + let byte = |i: usize| block.get(i).copied().unwrap_or(0); + let palette = alpha_palette(byte(0), byte(1)); + let bits = u64::from_le_bytes([byte(2), byte(3), byte(4), byte(5), byte(6), byte(7), 0, 0]); + std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize]) +} + /// A BC1 block. Texels under half opacity become BC1's transparent black, which needs the /// three-colour mode; an opaque block takes whichever mode fits its colours better. pub(crate) fn encode_bc1(block: &Block, inside: Mask) -> [u8; 8] { @@ -69,7 +99,8 @@ pub(crate) fn encode_bc2(block: &Block, inside: Mask) -> [u8; 16] { /// A BC3 block: an interpolated alpha block, then a four-colour block. pub(crate) fn encode_bc3(block: &Block, inside: Mask) -> [u8; 16] { - join(alpha_block(block, inside), colour_block(block, inside, 0, false)) + let alphas = std::array::from_fn(|t| block[t][3]); + join(value_block(&alphas, inside), colour_block(block, inside, 0, false)) } fn join(a: [u8; 8], b: [u8; 8]) -> [u8; 16] { @@ -92,21 +123,56 @@ fn to565(c: [f32; 3]) -> u16 { } fn distance(a: &[u8; 4], b: &[u8; 4]) -> u32 { - (0..3).map(|i| u32::from(a[i].abs_diff(b[i])).pow(2)).sum() + let d = |i: usize| u32::from(a[i].abs_diff(b[i])).pow(2); + d(0) + d(1) + d(2) +} + +/// The index of the first of `palette`'s entries nearest by `distance`, and that distance: the +/// entry `Iterator::min_by_key` picks, found without the iterator (a texel equal to an entry +/// stops the search, as no later entry can be nearer and an equal one doesn't win). +fn nearest(palette: &[T], distance: impl Fn(&T) -> u32) -> (usize, u32) { + let mut best = (0, u32::MAX); + for (i, p) in palette.iter().enumerate() { + let d = distance(p); + if d < best.1 { + best = (i, d); + if d == 0 { + break; + } + } + } + if palette.is_empty() { (0, 0) } else { best } } /// A colour block (endpoints, then 2-bit indices) for the `opaque` texels' colours, with the /// `transparent` ones on BC1's transparent index. `bc1` allows the three-colour mode; BC2 and /// BC3 always decode four colours. fn colour_block(block: &Block, opaque: Mask, transparent: Mask, bc1: bool) -> [u8; 8] { - let colours: Vec<[f32; 3]> = block.iter().enumerate().filter(|(t, _)| opaque >> t & 1 != 0).map(|(_, texel)| rgb_of(texel)).collect(); - if colours.is_empty() { + // The opaque texels' colours in texel order, on the stack (after storytold/photocraft#10669, + // which took the per-block allocations out of PhotoCraft's copy of this encoder). + let mut buffer = [[0f32; 3]; 16]; + let mut n = 0; + for (t, texel) in block.iter().enumerate() { + if opaque >> t & 1 != 0 + && let Some(slot) = buffer.get_mut(n) + { + *slot = rgb_of(texel); + n += 1; + } + } + let colours = buffer.get(..n).unwrap_or_default(); + let Some((first, rest)) = colours.split_first() else { // Nothing visible: every texel on the transparent index (or index 0 of black). let indices = if transparent != 0 { u32::MAX } else { 0 }; return pack(0, 0, indices); - } - let (lo, hi) = principal_endpoints(&colours); - let mut candidates = vec![(to565(lo), to565(hi))]; + }; + // One colour has no axis: `principal_endpoints` returns that colour (their mean) for both + // ends, so it is skipped. Everything after it runs as for any block. + let (lo, hi) = if rest.iter().all(|c| c == first) { (*first, *first) } else { principal_endpoints(colours) }; + let mut candidate = (to565(lo), to565(hi)); + // The endpoint pairs fitted so far: at most one per round. + let mut fitted = [candidate; 3]; + let mut count = 1; let modes: &[bool] = if transparent != 0 { &[false] } else if bc1 { @@ -118,22 +184,30 @@ fn colour_block(block: &Block, opaque: Mask, transparent: Mask, bc1: bool) -> [u // Each refinement starts from the best block so far: its indices give the least-squares // endpoints, which become one more candidate. for round in 0..3 { - for &(e0, e1) in &candidates { - for &four in modes { - let (bytes, error) = fit(block, opaque, transparent, e0, e1, four); - if best.is_none_or(|(e, _)| error < e) { - best = Some((error, bytes)); - } + let (e0, e1) = candidate; + for &four in modes { + let (bytes, error) = fit(block, opaque, transparent, e0, e1, four); + if best.is_none_or(|(e, _)| error < e) { + best = Some((error, bytes)); } } let Some((error, bytes)) = best else { break }; if error == 0 || round == 2 { break; } - candidates = least_squares(block, opaque, &bytes).into_iter().collect(); - if candidates.is_empty() { + let Some(next) = least_squares(block, opaque, &bytes) else { break }; + // A pair fitted before (in either order: `fit` orders the endpoints itself) fits the same + // again and can't beat the best block, which then gives the same pair again: the rounds + // left would change nothing. + let seen = fitted.get(..count).unwrap_or_default(); + if seen.iter().any(|&(a, b)| (a, b) == next || (b, a) == next) { break; } + if let Some(slot) = fitted.get_mut(count) { + *slot = next; + count += 1; + } + candidate = next; } best.map_or([0; 8], |(_, bytes)| bytes) } @@ -151,7 +225,7 @@ fn fit(block: &Block, opaque: Mask, transparent: Mask, e0: u16, e1: u16, four: b let index = if transparent >> t & 1 != 0 { 3 } else if opaque >> t & 1 != 0 { - let (i, d) = palette.iter().take(choices).enumerate().map(|(i, p)| (i, distance(texel, p))).min_by_key(|&(_, d)| d).unwrap_or((0, 0)); + let (i, d) = nearest(palette.get(..choices).unwrap_or_default(), |p| distance(texel, p)); error += d; i as u32 } else { @@ -191,7 +265,14 @@ fn principal_endpoints(colours: &[[f32; 3]]) -> ([f32; 3], [f32; 3]) { if !len.is_normal() { break; } - axis = next.map(|v| v / len); + let normalised = next.map(|v| v / len); + // A step that returns the same axis, bit for bit, returns it on every later step too: + // stopping there gives the very axis the remaining steps would. Kept only if timing + // shows the comparison pays for itself. + if normalised.map(f32::to_bits) == axis.map(f32::to_bits) { + break; + } + axis = normalised; } axis }; @@ -248,29 +329,39 @@ fn least_squares(block: &Block, opaque: Mask, bytes: &[u8; 8]) -> Option<(u16, u Some((to565(e0), to565(e1))) } -/// A BC3 alpha block: whichever of the two modes (eight values between the extremes, or six -/// between the extremes other than 0 and 255, plus exact 0 and 255) fits better. -fn alpha_block(block: &Block, inside: Mask) -> [u8; 8] { - let alphas = || block.iter().enumerate().filter(move |(t, _)| inside >> t & 1 != 0).map(|(_, texel)| texel[3]); - let range = - |values: &mut dyn Iterator| values.fold(None, |r: Option<(u8, u8)>, a| Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a))))); - let (lo, hi) = range(&mut alphas()).unwrap_or((0, 0)); +/// A block of 16 single-channel values (BC3's alpha, BC4, either half of BC5): whichever of the two modes +/// (eight values between the extremes, or six between the extremes other than 0 and 255, plus +/// exact 0 and 255) fits better. Only the values of `inside` count. +pub(crate) fn value_block(values: &[u8; 16], inside: Mask) -> [u8; 8] { + // Both ranges in one pass: of all values, and of those other than 0 and 255. + let mut all: Option<(u8, u8)> = None; + let mut mid = all; + let widen = |r: Option<(u8, u8)>, v: u8| Some(r.map_or((v, v), |(lo, hi)| (lo.min(v), hi.max(v)))); + for (t, &v) in values.iter().enumerate() { + if inside >> t & 1 != 0 { + all = widen(all, v); + if !matches!(v, 0 | 255) { + mid = widen(mid, v); + } + } + } + let (lo, hi) = all.unwrap_or((0, 0)); // Eight values need a0 > a1; equal ends fall to the six-value mode, which starts with a0 too. - let eight = alpha_fit(block, inside, hi, lo); - let (mid_lo, mid_hi) = range(&mut alphas().filter(|a| !matches!(a, 0 | 255))).unwrap_or((0, 0)); - let six = alpha_fit(block, inside, mid_lo, mid_hi); + let eight = value_fit(values, inside, hi, lo); + let (mid_lo, mid_hi) = mid.unwrap_or((0, 0)); + let six = value_fit(values, inside, mid_lo, mid_hi); if six.1 < eight.1 { six.0 } else { eight.0 } } -fn alpha_fit(block: &Block, inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u32) { +fn value_fit(values: &[u8; 16], inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u32) { let palette = alpha_palette(a0, a1); let mut bits = 0u64; let mut error = 0u32; - for (t, texel) in block.iter().enumerate() { + for (t, &v) in values.iter().enumerate() { if inside >> t & 1 == 0 { continue; } - let (i, d) = palette.iter().enumerate().map(|(i, &p)| (i, u32::from(p.abs_diff(texel[3])).pow(2))).min_by_key(|&(_, d)| d).unwrap_or((0, 0)); + let (i, d) = nearest(&palette, |&p| u32::from(p.abs_diff(v)).pow(2)); error += d; bits |= (i as u64) << (3 * t); } @@ -282,13 +373,6 @@ fn alpha_fit(block: &Block, inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u32) { mod tests { use super::*; - fn decode_colour(bytes: &[u8; 8], bc1: bool) -> Block { - let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); - let palette = colour_palette(c0, c1, c0 > c1 || !bc1); - let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); - std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) - } - #[test] fn solid_blocks_land_on_the_nearest_565_colour() { for colour in [[0, 0, 0, 255], [255, 255, 255, 255], [12, 200, 77, 255]] { @@ -333,7 +417,7 @@ mod tests { fn alpha_blocks_pick_the_mode_that_keeps_0_and_255() { // 0, 255 and a cluster in between: the six-value mode stores 0 and 255 exactly. let block: Block = std::array::from_fn(|t| [0, 0, 0, [0, 255, 100, 110][t % 4]]); - let bytes = alpha_block(&block, u16::MAX); + let bytes = value_block(&block.map(|t| t[3]), u16::MAX); assert!(bytes[0] <= bytes[1], "six-value mode"); let palette = alpha_palette(bytes[0], bytes[1]); let bits = u64::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], 0, 0]); @@ -358,6 +442,48 @@ mod tests { assert!(ours < bounding_box, "{ours} vs the bounding box's {bounding_box}"); } + #[test] + fn value_blocks_decode_the_frozen_vectors() { + // Eight-value mode (a0 = 200 > a1 = 50), every index 0. + assert_eq!(decode_values(&[0xc8, 0x32, 0, 0, 0, 0, 0, 0]), [200; 16]); + // Six-value mode (a0 = 10 <= a1 = 250), every index 1. + assert_eq!(decode_values(&[0x0a, 0xfa, 0x49, 0x92, 0x24, 0x49, 0x92, 0x24]), [250; 16]); + // Six-value mode's indices 6 and 7 are 0 and 255 whatever the endpoints. + let bits: u64 = (0..16).fold(0, |b, t| b | (6 + (t % 2)) << (3 * t)); + let b = bits.to_le_bytes(); + let got = decode_values(&[10, 250, b[0], b[1], b[2], b[3], b[4], b[5]]); + assert_eq!(got, std::array::from_fn(|t| if t % 2 == 0 { 0 } else { 255 })); + } + + #[test] + fn value_blocks_round_trip_ramps_and_solids() { + for values in [[200u8; 16], [0; 16], [255; 16], std::array::from_fn(|t| (t * 17) as u8), std::array::from_fn(|t| 100 + t as u8)] { + let back = decode_values(&value_block(&values, u16::MAX)); + let worst = values.iter().zip(back).map(|(a, b)| a.abs_diff(b)).max().unwrap_or(0); + // Within half a step of either mode: 255 / 7 apart in the eight-value mode, about + // 221 / 5 in the six-value one. + assert!(worst <= 23, "{values:?} -> {back:?}"); + } + assert_eq!(decode_values(&value_block(&[200; 16], u16::MAX)), [200; 16]); + } + + #[test] + fn nearest_picks_what_min_by_key_picks() { + // Ties (equal entries, entries equally far on both sides) and exact hits included. + let mut seed = 0x2545_f491u32; + for _ in 0..2000 { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let palette = [seed as u8 & 0xf0, (seed >> 8) as u8 & 0xf0, (seed >> 16) as u8 & 0xf0, (seed >> 24) as u8 & 0xf0]; + let v = (seed >> 4) as u8 & 0xf8; + let d = |p: &u8| u32::from(p.abs_diff(v)).pow(2); + let want = palette.iter().enumerate().map(|(i, p)| (i, d(p))).min_by_key(|&(_, d)| d).unwrap(); + assert_eq!(nearest(&palette, d), want, "{palette:?} {v}"); + } + assert_eq!(nearest::(&[], |_| 7), (0, 0)); + } + #[test] fn texels_outside_the_image_are_ignored() { // Only the top-left texel is inside: its colour alone decides the endpoints. diff --git a/crates/dds/src/lib.rs b/crates/dds/src/lib.rs new file mode 100644 index 000000000..f7b44fc7a --- /dev/null +++ b/crates/dds/src/lib.rs @@ -0,0 +1,983 @@ +//! DirectDraw Surface (DDS) textures, after Microsoft's public DDS documentation ("DDS", +//! "DDS_HEADER", "DDS_PIXELFORMAT", "DDS_HEADER_DXT10"). +//! +//! Reading: the top mip level of a 2D texture, either uncompressed (8 to 32 bits per pixel +//! described by channel masks, RGB or luminance) or block-compressed BC1/BC2/BC3 +//! (DXT1/DXT3/DXT5) or unsigned BC4/BC5 (ATI1/ATI2), with or without the DX10 header. BC4 opens +//! as gray and BC5 as RGB with blue 0: BC5 stores only red and green, and a normal map's Z is +//! left for the caller to reconstruct. Cubemaps, texture arrays and volume textures are refused +//! rather than flattened to one face or slice, and signed (SNORM) BC4/BC5 is refused too. +//! +//! Writing: a 2D texture, uncompressed (BGRA or BGRX, luminance with or without alpha), +//! BC1/BC2/BC3 or BC4/BC5, optionally with its full mip chain. The legacy header describes all +//! but BC4 and BC5, which are written with the DX10 header (`BC4_UNORM`, `BC5_UNORM`): their +//! legacy FourCCs are vendor names that programs read differently (ATI2's two blocks are swapped +//! by some). BC6H, BC7 and sRGB formats aren't written. +//! +//! Pixels are 8 bits per channel, interleaved, top row first, in one of the [`Layout`]s. The +//! crate has no dependencies; the `parallel` feature encodes and decodes rows of blocks (and mip +//! levels) on several threads with rayon. +//! +//! ``` +//! use craft_dds::{DdsCompression, DdsOptions, Layout}; +//! +//! let pixels = [10, 20, 30, 255].repeat(6 * 5); +//! let options = DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }; +//! let file = craft_dds::encode(6, 5, Layout::Rgba, &pixels, options)?; +//! let texture = craft_dds::Texture::parse(&file)?; +//! assert_eq!((texture.width(), texture.height(), texture.layout()), (6, 5, Layout::Rgba)); +//! assert_eq!(texture.decode()?.len(), 6 * 5 * 4); +//! # Ok::<(), craft_dds::DdsError>(()) +//! ``` +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod bc; + +use std::borrow::Cow; +use std::fmt; + +use bc::{Block, Mask}; + +/// The channels of a pixel, 8 bits each, in this order. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Layout { + Gray, + /// Gray, then straight (not premultiplied) alpha. + GrayA, + Rgb, + /// Red, green, blue, then straight alpha. + Rgba, +} + +impl Layout { + /// Samples per pixel. + pub fn channels(self) -> usize { + match self { + Layout::Gray => 1, + Layout::GrayA => 2, + Layout::Rgb => 3, + Layout::Rgba => 4, + } + } +} + +/// Why a texture could not be read or written. More kinds may be added, so a `match` on it needs +/// a wildcard arm. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum DdsError { + /// The file is damaged or not a DDS file. + Malformed(String), + /// A valid texture in a form this crate doesn't read (a cubemap, an array, a compression it + /// doesn't decode). + Unsupported(String), + /// The pixels can't be written with the options given. + Encode(String), + /// An output buffer of this many bytes could not be allocated. + Alloc(usize), + /// The decoded output exceeds the caller-selected per-buffer byte limit. + LimitExceeded { required: usize, limit: u64 }, +} + +impl fmt::Display for DdsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + DdsError::Malformed(reason) => write!(f, "malformed DDS: {reason}"), + DdsError::Unsupported(reason) => write!(f, "unsupported DDS: {reason}"), + DdsError::Encode(reason) => write!(f, "DDS encode failed: {reason}"), + DdsError::Alloc(len) => write!(f, "cannot allocate {len} bytes for the texture"), + DdsError::LimitExceeded { required, limit } => write!(f, "decoded texture requires {required} bytes, exceeding limit {limit}"), + } + } +} + +impl std::error::Error for DdsError {} + +/// How a DDS texture stores its pixels. More compressions may be added, so a `match` on it needs +/// a wildcard arm. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[non_exhaustive] +pub enum DdsCompression { + /// Uncompressed, 8 bits per channel: BGRA (BGRX without alpha), or luminance with or + /// without alpha for grayscale. Lossless. + #[default] + None, + /// BC1 (DXT1): 4 bits per pixel. Alpha is on or off: texels under half opacity become + /// transparent black. + Bc1, + /// BC2 (DXT3): 8 bits per pixel, with 4 bits of explicit alpha per texel. + Bc2, + /// BC3 (DXT5): 8 bits per pixel, with smooth interpolated alpha. + Bc3, + /// BC4 (ATI1): 4 bits per pixel, one channel: gray, for roughness, metallic, height or + /// ambient-occlusion maps. Written from gray pixels. + Bc4, + /// BC5 (ATI2): 8 bits per pixel, two channels: red and green, for tangent-space normal maps + /// (X and Y; Z is reconstructed by the renderer). Written from RGB pixels, blue dropped. + Bc5, +} + +impl DdsCompression { + pub const ALL: [DdsCompression; 6] = + [DdsCompression::None, DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3, DdsCompression::Bc4, DdsCompression::Bc5]; + + /// The name scripts and the CLI use: `none`, `bc1`, `bc2`, `bc3`, `bc4` or `bc5`. + pub fn name(self) -> &'static str { + match self { + DdsCompression::None => "none", + DdsCompression::Bc1 => "bc1", + DdsCompression::Bc2 => "bc2", + DdsCompression::Bc3 => "bc3", + DdsCompression::Bc4 => "bc4", + DdsCompression::Bc5 => "bc5", + } + } + + /// [`Self::name`] back to a compression, also taking the DXT and ATI names (`dxt1`, `dxt3`, + /// `dxt5`, `ati1`, `ati2`), in any case. Anything else is `None`. + pub fn from_name(name: &str) -> Option { + match name.to_ascii_lowercase().as_str() { + "none" => Some(DdsCompression::None), + "bc1" | "dxt1" => Some(DdsCompression::Bc1), + "bc2" | "dxt3" => Some(DdsCompression::Bc2), + "bc3" | "dxt5" => Some(DdsCompression::Bc3), + "bc4" | "ati1" => Some(DdsCompression::Bc4), + "bc5" | "ati2" => Some(DdsCompression::Bc5), + _ => None, + } + } + + /// The pixel layout the compression is written from: gray for BC4, RGB for BC5, RGBA for + /// the other block compressions. `None` for uncompressed textures, which take every layout. + pub fn layout(self) -> Option { + match self { + DdsCompression::None => None, + DdsCompression::Bc4 => Some(Layout::Gray), + DdsCompression::Bc5 => Some(Layout::Rgb), + DdsCompression::Bc1 | DdsCompression::Bc2 | DdsCompression::Bc3 => Some(Layout::Rgba), + } + } + + /// A block compression (lossy), not uncompressed pixels. + pub fn is_block(self) -> bool { + self != DdsCompression::None + } +} + +/// What a DDS file is written with. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct DdsOptions { + pub compression: DdsCompression, + /// Write the full mip chain down to 1×1, each level a box filter of the one above. + pub mipmaps: bool, +} + +/// `DDS ` plus the 124-byte DDS_HEADER. +const HEADER: usize = 128; +/// DDS_HEADER_DXT10, present when the FourCC is `DX10`. +const DX10_HEADER: usize = 20; + +const DDSD_DEPTH: u32 = 0x80_0000; +const DDPF_ALPHAPIXELS: u32 = 0x1; +const DDPF_FOURCC: u32 = 0x4; +const DDPF_RGB: u32 = 0x40; +const DDPF_LUMINANCE: u32 = 0x2_0000; +const DDSCAPS2_CUBEMAP: u32 = 0x200; +const DDSCAPS2_CUBEMAP_FACES: u32 = 0xfc00; +const DDSCAPS2_VOLUME: u32 = 0x20_0000; +const DIMENSION_TEXTURE2D: u32 = 3; +const MISC_TEXTURECUBE: u32 = 0x4; + +fn bad(reason: impl fmt::Display) -> DdsError { + DdsError::Malformed(reason.to_string()) +} +fn unsupported(reason: impl Into) -> DdsError { + DdsError::Unsupported(reason.into()) +} +fn le32(b: &[u8], at: usize) -> Result { + let bytes = b.get(at..at + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()).ok_or_else(|| bad("truncated header"))?; + Ok(u32::from_le_bytes(bytes)) +} + +/// Whether the header declares more than the one image a reader takes: further mip levels, +/// cubemap faces, volume slices or array textures, even without their presence flags. +pub fn has_additional_images(bytes: &[u8]) -> Result { + let depth = le32(bytes, 24)?; + let mips = le32(bytes, 28)?; + let faces = (le32(bytes, 112)? & DDSCAPS2_CUBEMAP_FACES).count_ones(); + let dx10 = le32(bytes, 80)? & DDPF_FOURCC != 0 && bytes.get(84..88) == Some(b"DX10"); + let (cube, array) = if dx10 { (le32(bytes, 136)? & MISC_TEXTURECUBE != 0, le32(bytes, 140)?) } else { (false, 0) }; + Ok(depth > 1 || mips > 1 || faces > 1 || cube || array > 1) +} + +/// A FourCC as text when it is printable, else as the number legacy writers store there. +fn fourcc_name(fourcc: u32) -> String { + let bytes = fourcc.to_le_bytes(); + if bytes.iter().all(|c| c.is_ascii_graphic() || *c == b' ') { bytes.iter().map(|&c| char::from(c)).collect() } else { fourcc.to_string() } +} + +/// One channel of an uncompressed pixel: where it sits and its largest value. +#[derive(Clone, Copy)] +struct Field { + shift: u32, + max: u32, +} + +impl Field { + /// `None` for an empty mask; an error for one with gaps or wider than the pixel. + fn new(mask: u32, bits: u32) -> Result, DdsError> { + if mask == 0 { + return Ok(None); + } + let shift = mask.trailing_zeros(); + let max = mask >> shift; + if max & max.wrapping_add(1) != 0 || (bits < 32 && mask >> bits != 0) { + return Err(bad(format!("channel mask {mask:#x} is not a contiguous field of a {bits}-bit pixel"))); + } + Ok(Some(Field { shift, max })) + } + + fn get(self, pixel: u32) -> u8 { + let v = u64::from((pixel >> self.shift) & self.max); + let max = u64::from(self.max); + ((v * 255 + max / 2) / max) as u8 + } +} + +#[derive(Clone, Copy)] +enum Encoding { + /// Uncompressed: bytes per pixel, then red (or luminance), green, blue and alpha. + Masks { + bytes: usize, + gray: bool, + fields: [Option; 4], + }, + Bc1, + Bc2, + Bc3, + /// One value block: gray. + Bc4, + /// Two value blocks: red, then green. + Bc5, +} + +impl Encoding { + fn masks(bits: u32, masks: [u32; 4], gray: bool) -> Result { + if !matches!(bits, 8 | 16 | 24 | 32) { + return Err(bad(format!("{bits} bits per pixel is not 8, 16, 24 or 32"))); + } + let mut fields = [None; 4]; + for (field, mask) in fields.iter_mut().zip(masks) { + *field = Field::new(mask, bits)?; + } + let colour = if gray { fields[0].is_some() } else { fields[..3].iter().any(Option::is_some) }; + if !colour { + return Err(bad("the pixel format has no colour channel masks")); + } + Ok(Encoding::Masks { bytes: bits as usize / 8, gray, fields }) + } + + fn layout(&self) -> Layout { + match self { + Encoding::Masks { gray: true, fields, .. } if fields[3].is_some() => Layout::GrayA, + Encoding::Masks { gray: true, .. } => Layout::Gray, + Encoding::Masks { fields, .. } if fields[3].is_none() => Layout::Rgb, + Encoding::Bc4 => Layout::Gray, + Encoding::Bc5 => Layout::Rgb, + _ => Layout::Rgba, + } + } + + /// Bytes per 4×4 block; 0 for uncompressed pixels. + fn block_size(&self) -> usize { + match self { + Encoding::Masks { .. } => 0, + Encoding::Bc1 | Encoding::Bc4 => 8, + Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc5 => 16, + } + } + + /// Stored row stride and byte size of the top mip level (block rows for BC). + fn level_layout(&self, width: u32, height: u32, pitch: Option) -> Result<(usize, usize), DdsError> { + let overflow = || bad("pixel data size overflow"); + let (w, h) = (usize::try_from(width).map_err(|_| overflow())?, usize::try_from(height).map_err(|_| overflow())?); + let (row_bytes, rows) = match self { + Encoding::Masks { bytes, .. } => { + let packed = w.checked_mul(*bytes).ok_or_else(overflow)?; + let row_bytes = match pitch { + Some(pitch) => usize::try_from(pitch).map_err(|_| overflow())?, + None => packed, + }; + if row_bytes < packed { + return Err(bad(format!("row pitch {row_bytes} is smaller than the {packed}-byte pixel row"))); + } + (row_bytes, h) + } + Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc4 | Encoding::Bc5 => { + (w.div_ceil(4).checked_mul(self.block_size()).ok_or_else(overflow)?, h.div_ceil(4)) + } + }; + let size = row_bytes.checked_mul(rows).ok_or_else(overflow)?; + Ok((row_bytes, size)) + } +} + +/// The legacy pixel format: a FourCC, or channel masks. +fn legacy_encoding(b: &[u8]) -> Result { + let (flags, fourcc, bits) = (le32(b, 80)?, le32(b, 84)?, le32(b, 88)?); + let alpha = if flags & DDPF_ALPHAPIXELS != 0 { le32(b, 104)? } else { 0 }; + if flags & DDPF_FOURCC != 0 { + return match &fourcc.to_le_bytes() { + b"DXT1" => Ok(Encoding::Bc1), + b"DXT3" => Ok(Encoding::Bc2), + b"DXT5" => Ok(Encoding::Bc3), + // Microsoft's mapping (DirectXTex reads ATI2 as BC5_UNORM, as Pillow does): red in + // the first block, green in the second. FFmpeg's reader swaps the two blocks of + // ATI2, after the old ATI 3Dc tools; this reader doesn't. + b"ATI1" | b"BC4U" => Ok(Encoding::Bc4), + b"ATI2" | b"BC5U" => Ok(Encoding::Bc5), + b"BC4S" | b"BC5S" => Err(unsupported(format!("signed (SNORM) `{}` textures are not supported", fourcc_name(fourcc)))), + b"DXT2" | b"DXT4" => Err(unsupported("premultiplied-alpha DXT2/DXT4 textures are not supported")), + _ => Err(unsupported(format!("compression `{}` is not supported (DXT1, DXT3, DXT5, ATI1/BC4U and ATI2/BC5U are)", fourcc_name(fourcc)))), + }; + } + if flags & DDPF_RGB != 0 { + return Encoding::masks(bits, [le32(b, 92)?, le32(b, 96)?, le32(b, 100)?, alpha], false); + } + if flags & DDPF_LUMINANCE != 0 { + return Encoding::masks(bits, [le32(b, 92)?, 0, 0, alpha], true); + } + Err(unsupported(format!("pixel format flags {flags:#x} are not RGB, luminance or a supported compression"))) +} + +/// The DX10 header's DXGI format, refusing anything but a single 2D texture. +fn dx10_encoding(b: &[u8]) -> Result { + let (dxgi, dimension, misc, array) = (le32(b, HEADER)?, le32(b, HEADER + 4)?, le32(b, HEADER + 8)?, le32(b, HEADER + 12)?); + if misc & MISC_TEXTURECUBE != 0 { + return Err(unsupported("cubemaps are not supported")); + } + if dimension != DIMENSION_TEXTURE2D { + return Err(unsupported(format!("only 2D textures are supported (resource dimension {dimension})"))); + } + if array > 1 { + return Err(unsupported(format!("texture arrays are not supported ({array} textures)"))); + } + // miscFlags2 bits 0-2 are the alpha mode; 2 is premultiplied. Only the formats with a real + // alpha channel are affected, and the legacy path refuses their DXT2/DXT4 equivalents too. + if le32(b, HEADER + 16)? & 0x7 == 2 && matches!(dxgi, 27..=29 | 73..=78 | 87 | 90 | 91) { + return Err(unsupported(format!("premultiplied-alpha DX10 textures are not supported (DXGI format {dxgi})"))); + } + const RGBA: [u32; 4] = [0xff, 0xff00, 0xff_0000, 0xff00_0000]; + const BGRA: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0xff00_0000]; + const BGRX: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0]; + match dxgi { + 27..=29 => Encoding::masks(32, RGBA, false), + 87 | 90 | 91 => Encoding::masks(32, BGRA, false), + 88 | 92 | 93 => Encoding::masks(32, BGRX, false), + 70..=72 => Ok(Encoding::Bc1), + 73..=75 => Ok(Encoding::Bc2), + 76..=78 => Ok(Encoding::Bc3), + // Typeless, then UNORM: a typeless texture's view is unsigned unless a program says + // otherwise, and Pillow writes BC5 as typeless. + 79 | 80 => Ok(Encoding::Bc4), + 82 | 83 => Ok(Encoding::Bc5), + 81 | 84 => Err(unsupported(format!("signed (SNORM) BC4 and BC5 textures are not supported (DXGI format {dxgi})"))), + _ => Err(unsupported(format!("DXGI format {dxgi} is not supported (BC1 to BC5 and 8-bit RGBA or BGRA are)"))), + } +} + +/// Default per-buffer decoded output budget (1 GiB). This is not a total process memory budget. +pub const DEFAULT_MAX_DECODE_BYTES: u64 = 1024 * 1024 * 1024; + +/// A DDS file whose header has been read: its size and pixel layout are known before +/// [`Texture::decode`] allocates anything, so a caller can check them against its limits. +pub struct Texture<'a> { + bytes: &'a [u8], + flags: u32, + width: u32, + height: u32, + encoding: Encoding, + /// Where the top level's pixel data starts. + start: usize, +} + +impl<'a> Texture<'a> { + /// Reads the header, refusing what [`Texture::decode`] can't read. + pub fn parse(b: &'a [u8]) -> Result, DdsError> { + if !b.starts_with(b"DDS ") { + return Err(bad("missing the `DDS ` signature")); + } + if le32(b, 4)? != 124 { + return Err(bad("header size is not 124")); + } + let (flags, height, width, depth, caps2) = (le32(b, 8)?, le32(b, 12)?, le32(b, 16)?, le32(b, 24)?, le32(b, 112)?); + if caps2 & DDSCAPS2_CUBEMAP != 0 { + return Err(unsupported("cubemaps are not supported")); + } + if caps2 & DDSCAPS2_VOLUME != 0 || (flags & DDSD_DEPTH != 0 && depth > 1) { + return Err(unsupported("volume textures are not supported")); + } + let dx10 = le32(b, 80)? & DDPF_FOURCC != 0 && &le32(b, 84)?.to_le_bytes() == b"DX10"; + let (encoding, start) = if dx10 { (dx10_encoding(b)?, HEADER + DX10_HEADER) } else { (legacy_encoding(b)?, HEADER) }; + if b.len() < start { + return Err(bad("truncated header")); + } + if width == 0 || height == 0 { + return Err(bad("texture dimensions must be nonzero")); + } + Ok(Texture { bytes: b, flags, width, height, encoding, start }) + } + + pub fn width(&self) -> u32 { + self.width + } + + pub fn height(&self) -> u32 { + self.height + } + + /// The layout [`Texture::decode`] returns. + pub fn layout(&self) -> Layout { + self.encoding.layout() + } + + /// The top mip level's pixels in [`Texture::layout`], bounded by [`DEFAULT_MAX_DECODE_BYTES`]. + pub fn decode(&self) -> Result, DdsError> { + self.decode_with_limit(DEFAULT_MAX_DECODE_BYTES) + } + + /// Decode with an explicit per-buffer output byte budget; allocation remains fallible. + pub fn decode_with_limit(&self, max_bytes: u64) -> Result, DdsError> { + let (b, flags, encoding) = (self.bytes, self.flags, self.encoding); + let (width, height) = (self.width, self.height); + // The same header field is a total level size for BC, but a row stride when DDSD_PITCH is set. + let pitch = if flags & DDSD_PITCH != 0 { Some(le32(b, 20)?) } else { None }; + let (row_pitch, size) = encoding.level_layout(width, height, pitch)?; + let (w, h) = (width as usize, height as usize); + let channels = encoding.layout().channels(); + let row_size = w.checked_mul(channels).ok_or_else(|| bad("pixel size overflow"))?; + let total = row_size.checked_mul(h).ok_or_else(|| bad("pixel size overflow"))?; + if total as u64 > max_bytes { + return Err(DdsError::LimitExceeded { required: total, limit: max_bytes }); + } + let data = b.get(self.start..).and_then(|d| d.get(..size)).ok_or_else(|| bad(format!("truncated pixel data: {size} bytes needed")))?; + let mut pixels = alloc_zeroed(total)?; + match encoding { + Encoding::Masks { bytes, gray, fields } => decode_masks(Masks { bytes, gray, fields }, data, row_pitch, &mut pixels, row_size), + Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc4 | Encoding::Bc5 => { + decode_blocks(encoding, data, (w, channels), &mut pixels) + } + } + Ok(pixels) + } +} + +/// An uncompressed pixel format: bytes per pixel, luminance or RGB, and the red (or +/// luminance), green, blue and alpha fields. +struct Masks { + bytes: usize, + gray: bool, + fields: [Option; 4], +} + +/// Uncompressed rows `row_pitch` apart into `pixels` (rows of `row_size` bytes), one row of +/// pixels per task. +fn decode_masks(m: Masks, data: &[u8], row_pitch: usize, pixels: &mut [u8], row_size: usize) { + let Masks { bytes, gray, fields } = m; + let channels = if gray { 1 + usize::from(fields[3].is_some()) } else { 3 + usize::from(fields[3].is_some()) }; + // The field each output channel comes from. + let picks = if gray { [0, 3, 0, 0] } else { [0, 1, 2, 3] }; + // An 8-bit field on a byte boundary scales to itself, so when every channel is one (or + // absent, and 0) the pixels are a byte shuffle: the byte each channel copies. + let mut at: [Option; 4] = [None; 4]; + let mut whole_bytes = true; + for (slot, &pick) in at.iter_mut().zip(&picks).take(channels) { + match fields.get(pick).copied().flatten() { + None => {} + Some(f) if f.max == 255 && f.shift % 8 == 0 => *slot = Some(f.shift as usize / 8), + Some(_) => whole_bytes = false, + } + } + // Four bytes to four channels, each present: RGBA, BGRA and the like. + let four = (whole_bytes && bytes == 4 && channels == 4 && at.iter().all(Option::is_some)).then(|| at.map(|i| i.unwrap_or(0) & 3)); + rows(pixels, row_size, |y, dst_row| { + // Stop at the output width, leaving any stored row padding unread. + let src_row = data.get(y * row_pitch..).unwrap_or_default(); + if let Some(order) = four { + let (src, dst) = (src_row.as_chunks::<4>().0, dst_row.as_chunks_mut::<4>().0); + if order == [0, 1, 2, 3] { + for (d, s) in dst.iter_mut().zip(src) { + *d = *s; + } + } else { + for (d, s) in dst.iter_mut().zip(src) { + *d = order.map(|i| s[i]); + } + } + } else if whole_bytes { + for (src, dst) in src_row.chunks_exact(bytes).zip(dst_row.chunks_exact_mut(channels)) { + for (v, i) in dst.iter_mut().zip(at) { + *v = i.and_then(|i| src.get(i)).copied().unwrap_or(0); + } + } + } else { + for (src, dst) in src_row.chunks_exact(bytes).zip(dst_row.chunks_exact_mut(channels)) { + let pixel = src.iter().rev().fold(0u32, |v, &byte| v << 8 | u32::from(byte)); + let channel = |i: usize| fields[i].map_or(0, |f| f.get(pixel)); + let values = if gray { [channel(0), channel(3), 0, 0] } else { [channel(0), channel(1), channel(2), channel(3)] }; + dst.copy_from_slice(&values[..channels]); + } + } + }); +} + +/// Block-compressed data into `pixels` of `width` × `channels` bytes a row, one row of blocks +/// per task. Blocks wholly inside the image copy whole rows of texels; only those on the right +/// edge check each texel. +fn decode_blocks(encoding: Encoding, data: &[u8], (width, channels): (usize, usize), pixels: &mut [u8]) { + let block_size = encoding.block_size().max(1); + let blocks_x = width.div_ceil(4); + let row_size = width * channels; + rows(pixels, row_size.saturating_mul(4), |by, band| { + let src = data.get(by * blocks_x * block_size..).unwrap_or_default(); + for (bx, block) in src.chunks_exact(block_size).take(blocks_x).enumerate() { + let second = block.get(8..).unwrap_or_default(); + let texels = match encoding { + Encoding::Bc1 => bc::decode_colour(block, true), + Encoding::Bc2 => with_alpha(bc::decode_colour(second, false), bc::decode_bc2_alpha(block)), + Encoding::Bc4 => values(&[bc::decode_values(block)]), + Encoding::Bc5 => values(&[bc::decode_values(block), bc::decode_values(second)]), + _ => with_alpha(bc::decode_colour(second, false), bc::decode_values(block)), + }; + let x0 = bx * 4; + // The band holds the block's rows that lie inside the image (fewer than four in the + // last band of a height that isn't a multiple of four). + for (line, row) in band.chunks_exact_mut(row_size).zip(texels.as_chunks::<4>().0) { + if x0 + 4 <= width && channels == 4 { + if let Some(dst) = line.get_mut(x0 * 4..x0 * 4 + 16) { + dst.copy_from_slice(row.as_flattened()); + } + } else { + let dst = line.get_mut(x0 * channels..).unwrap_or_default(); + for (d, texel) in dst.chunks_exact_mut(channels).zip(row) { + d.copy_from_slice(texel.get(..channels).unwrap_or_default()); + } + } + } + } + }); +} + +/// Texels whose first channels are `channels`' values, the rest 0: gray for BC4, red and green +/// (and blue 0) for BC5. +fn values(channels: &[[u8; 16]]) -> [[u8; 4]; 16] { + std::array::from_fn(|t| std::array::from_fn(|c| channels.get(c).map_or(0, |v| v[t]))) +} + +fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] { + for (texel, a) in texels.iter_mut().zip(alpha) { + texel[3] = a; + } + texels +} + +const DDSD_CAPS: u32 = 0x1; +const DDSD_HEIGHT: u32 = 0x2; +const DDSD_WIDTH: u32 = 0x4; +const DDSD_PITCH: u32 = 0x8; +const DDSD_PIXELFORMAT: u32 = 0x1000; +const DDSD_MIPMAPCOUNT: u32 = 0x2_0000; +const DDSD_LINEARSIZE: u32 = 0x8_0000; +const DDSCAPS_COMPLEX: u32 = 0x8; +const DDSCAPS_TEXTURE: u32 = 0x1000; +const DDSCAPS_MIPMAP: u32 = 0x40_0000; +const DXGI_BC4_UNORM: u32 = 80; +const DXGI_BC5_UNORM: u32 = 83; + +fn encode_err(reason: impl fmt::Display) -> DdsError { + DdsError::Encode(reason.to_string()) +} + +/// A zeroed buffer of `len` bytes, or [`DdsError::Alloc`] when it can't be reserved. +fn alloc_zeroed(len: usize) -> Result, DdsError> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| DdsError::Alloc(len))?; + v.resize(len, 0); + Ok(v) +} + +/// How a written texture stores its pixels. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Store { + /// 8-bit luminance. + Luminance, + /// 8-bit luminance, then 8-bit alpha. + LuminanceAlpha, + /// Blue, green, red and an unused byte (written as 255, so a reader that takes it for + /// alpha still sees an opaque texture). + Bgrx, + Bgra, + Bc1, + Bc2, + Bc3, + Bc4, + Bc5, +} + +impl Store { + /// The storage for pixels of `layout`. Block compressions take their + /// [`DdsCompression::layout`] only. + fn new(compression: DdsCompression, layout: Layout) -> Result { + Ok(match (compression, layout) { + (DdsCompression::None, Layout::Gray) => Store::Luminance, + (DdsCompression::None, Layout::GrayA) => Store::LuminanceAlpha, + (DdsCompression::None, Layout::Rgb) => Store::Bgrx, + (DdsCompression::None, Layout::Rgba) => Store::Bgra, + (DdsCompression::Bc1, Layout::Rgba) => Store::Bc1, + (DdsCompression::Bc2, Layout::Rgba) => Store::Bc2, + (DdsCompression::Bc3, Layout::Rgba) => Store::Bc3, + (DdsCompression::Bc4, Layout::Gray) => Store::Bc4, + (DdsCompression::Bc5, Layout::Rgb) => Store::Bc5, + (_, layout) => return Err(encode_err(format!("{layout:?} pixels can't be written as `{}`", compression.name()))), + }) + } + + /// Bytes per pixel, or per 4×4 block for a block compression. + fn unit(self) -> usize { + match self { + Store::Luminance => 1, + Store::LuminanceAlpha => 2, + Store::Bgrx | Store::Bgra => 4, + Store::Bc1 | Store::Bc4 => 8, + Store::Bc2 | Store::Bc3 | Store::Bc5 => 16, + } + } + + fn is_block(self) -> bool { + matches!(self, Store::Bc1 | Store::Bc2 | Store::Bc3 | Store::Bc4 | Store::Bc5) + } + + /// The DXGI format of the DX10 header, for the formats the legacy header can't name. + fn dxgi(self) -> Option { + match self { + Store::Bc4 => Some(DXGI_BC4_UNORM), + Store::Bc5 => Some(DXGI_BC5_UNORM), + _ => None, + } + } + + /// Bytes of one row of pixels (or of 4×4 blocks) of a level `width` wide. + fn row_bytes(self, width: usize) -> Option { + if self.is_block() { width.div_ceil(4).checked_mul(self.unit()) } else { width.checked_mul(self.unit()) } + } + + fn level_bytes(self, width: usize, height: usize) -> Option { + let rows = if self.is_block() { height.div_ceil(4) } else { height }; + self.row_bytes(width)?.checked_mul(rows) + } + + /// DDS_PIXELFORMAT: flags, FourCC, bits per pixel and the red, green, blue and alpha masks. + fn pixel_format(self) -> (u32, [u8; 4], u32, [u32; 4]) { + match self { + Store::Luminance => (DDPF_LUMINANCE, [0; 4], 8, [0xff, 0, 0, 0]), + Store::LuminanceAlpha => (DDPF_LUMINANCE | DDPF_ALPHAPIXELS, [0; 4], 16, [0xff, 0, 0, 0xff00]), + Store::Bgrx => (DDPF_RGB, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0]), + Store::Bgra => (DDPF_RGB | DDPF_ALPHAPIXELS, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]), + Store::Bc1 => (DDPF_FOURCC, *b"DXT1", 0, [0; 4]), + Store::Bc2 => (DDPF_FOURCC, *b"DXT3", 0, [0; 4]), + Store::Bc3 => (DDPF_FOURCC, *b"DXT5", 0, [0; 4]), + Store::Bc4 | Store::Bc5 => (DDPF_FOURCC, *b"DX10", 0, [0; 4]), + } + } +} + +/// Levels in a full mip chain: the larger side halves down to 1. +fn mip_levels(width: u32, height: u32) -> u32 { + 32 - width.max(height).max(1).leading_zeros() +} + +fn half((w, h): (usize, usize)) -> (usize, usize) { + ((w / 2).max(1), (h / 2).max(1)) +} + +/// A DDS file of `width` × `height` `pixels` in `layout`, interleaved and top row first. +/// Block compressions take the layout [`DdsCompression::layout`] names (RGBA for BC1 to BC3, +/// gray for BC4, RGB for BC5); uncompressed textures take every layout. +pub fn encode(width: u32, height: u32, layout: Layout, pixels: &[u8], options: DdsOptions) -> Result, DdsError> { + if width == 0 || height == 0 { + return Err(encode_err("texture dimensions must be nonzero")); + } + let store = Store::new(options.compression, layout)?; + let expected = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(layout.channels())); + if expected != Some(pixels.len()) { + return Err(encode_err(format!("{} bytes of pixels for a {width}x{height} {layout:?} texture", pixels.len()))); + } + let levels = if options.mipmaps { mip_levels(width, height) } else { 1 }; + let top = (width as usize, height as usize); + // Every level's size, checked before anything is allocated. + let mut sizes = Vec::new(); + let mut size = top; + for _ in 0..levels { + sizes.push(store.level_bytes(size.0, size.1).ok_or_else(|| encode_err("texture size overflow"))?); + size = half(size); + } + let head = if store.dxgi().is_some() { HEADER + DX10_HEADER } else { HEADER }; + let total = sizes.iter().try_fold(head, |total, &s| total.checked_add(s)).ok_or_else(|| encode_err("texture size overflow"))?; + let header = header(width, height, store, levels, sizes.first().copied().unwrap_or(0))?; + let mut out = alloc_zeroed(total)?; + let (Some(dst), Some(src)) = (out.get_mut(..head), header.get(..head)) else { + return Err(encode_err("output buffer too small")); + }; + dst.copy_from_slice(src); + + let channels = layout.channels(); + let mut level = Cow::Borrowed(pixels); + let (mut size, mut at) = (top, head); + for (i, &bytes) in sizes.iter().enumerate() { + let dst = out.get_mut(at..at + bytes).ok_or_else(|| encode_err("output buffer too small"))?; + write_level(store, &level, size, dst)?; + at += bytes; + if i + 1 < sizes.len() { + let next = half(size); + level = Cow::Owned(downsample(&level, size, next, channels)?); + size = next; + } + } + Ok(out) +} + +/// The `DDS ` signature, DDS_HEADER and, for a format only DXGI names, DDS_HEADER_DXT10 (the +/// caller keeps the first [`HEADER`] bytes otherwise). `top` is the top level's size in bytes. +fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Result<[u8; HEADER + DX10_HEADER], DdsError> { + let mut b = [0u8; HEADER + DX10_HEADER]; + let mut put = |at: usize, v: u32| { + if let Some(d) = b.get_mut(at..at + 4) { + d.copy_from_slice(&v.to_le_bytes()); + } + }; + // Uncompressed: the pitch of one row. Compressed: the whole top level (its "linear size"). + let (size_flag, pitch_or_size) = if store.is_block() { (DDSD_LINEARSIZE, Some(top)) } else { (DDSD_PITCH, store.row_bytes(width as usize)) }; + let pitch_or_size = pitch_or_size + .and_then(|v| u32::try_from(v).ok()) + .ok_or_else(|| encode_err(format!("a {width}x{height} level is too large for a DDS header")))?; + let mipmapped = levels > 1; + put(4, 124); + put(8, DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | size_flag | if mipmapped { DDSD_MIPMAPCOUNT } else { 0 }); + put(12, height); + put(16, width); + put(20, pitch_or_size); + put(28, levels); + let (flags, fourcc, bits, masks) = store.pixel_format(); + put(76, 32); + put(80, flags); + put(84, u32::from_le_bytes(fourcc)); + put(88, bits); + for (i, mask) in masks.into_iter().enumerate() { + put(92 + 4 * i, mask); + } + put(108, DDSCAPS_TEXTURE | if mipmapped { DDSCAPS_COMPLEX | DDSCAPS_MIPMAP } else { 0 }); + if let Some(dxgi) = store.dxgi() { + // One 2D texture, no misc flags, alpha mode unknown (the formats have no alpha). + put(HEADER, dxgi); + put(HEADER + 4, DIMENSION_TEXTURE2D); + put(HEADER + 12, 1); + } + b[..4].copy_from_slice(b"DDS "); + Ok(b) +} + +/// Runs `f` on each `len`-byte row of `out` with its index, in parallel with the `parallel` +/// feature. +fn rows(out: &mut [u8], len: usize, f: impl Fn(usize, &mut [u8]) + Send + Sync) { + #[cfg(feature = "parallel")] + { + use rayon::prelude::*; + out.par_chunks_mut(len.max(1)).enumerate().for_each(|(i, row)| f(i, row)); + } + #[cfg(not(feature = "parallel"))] + for (i, row) in out.chunks_mut(len.max(1)).enumerate() { + f(i, row); + } +} + +/// Writes one level of `width` × `height` pixels (in the image's layout) into `dst`. +fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst: &mut [u8]) -> Result<(), DdsError> { + let row_bytes = store.row_bytes(width).ok_or_else(|| encode_err("texture size overflow"))?; + match store { + Store::Luminance | Store::LuminanceAlpha => { + // The image's gray (and alpha) samples, in the same order. + let src = pixels.get(..dst.len()).ok_or_else(|| encode_err("the level is smaller than its size"))?; + dst.copy_from_slice(src); + } + Store::Bgrx | Store::Bgra => { + let channels = if store == Store::Bgra { 4 } else { 3 }; + rows(dst, row_bytes, |y, row| { + let src = pixels.get(y * width * channels..).unwrap_or_default(); + for (d, s) in row.as_chunks_mut::<4>().0.iter_mut().zip(src.chunks_exact(channels)) { + let byte = |i: usize| s.get(i).copied().unwrap_or(255); + *d = [byte(2), byte(1), byte(0), byte(3)]; + } + }); + } + Store::Bc1 | Store::Bc2 | Store::Bc3 => { + let (texels, _) = pixels.as_chunks::<4>(); + rows(dst, row_bytes, |by, row| { + for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() { + let (block, inside) = gather(texels, (width, height), bx, by); + let encoded: &[u8] = match store { + Store::Bc1 => &bc::encode_bc1(&block, inside), + Store::Bc2 => &bc::encode_bc2(&block, inside), + _ => &bc::encode_bc3(&block, inside), + }; + for (d, s) in d.iter_mut().zip(encoded) { + *d = *s; + } + } + }); + } + Store::Bc4 | Store::Bc5 => { + // BC4: the gray channel; BC5: red, then green, of RGB pixels. + let channels = if store == Store::Bc4 { 1 } else { 3 }; + rows(dst, row_bytes, |by, row| { + for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() { + for (c, d) in d.as_chunks_mut::<8>().0.iter_mut().enumerate() { + let (values, inside) = gather_channel(pixels, (width, height), channels, c, (bx, by)); + *d = bc::value_block(&values, inside); + } + } + }); + } + } + Ok(()) +} + +/// Channel `c` of block (`bx`, `by`) of pixels with `channels` channels, and which of its texels +/// lie inside the image. +fn gather_channel(pixels: &[u8], (width, height): (usize, usize), channels: usize, c: usize, (bx, by): (usize, usize)) -> ([u8; 16], Mask) { + let mut values = [0u8; 16]; + let mut inside: Mask = 0; + for (t, v) in values.iter_mut().enumerate() { + let (x, y) = (bx * 4 + t % 4, by * 4 + t / 4); + if x < width + && y < height + && let Some(&p) = pixels.get((y * width + x) * channels + c) + { + *v = p; + inside |= 1 << t; + } + } + (values, inside) +} + +/// Block (`bx`, `by`)'s texels, and which of them lie inside the image. +fn gather(texels: &[[u8; 4]], (width, height): (usize, usize), bx: usize, by: usize) -> (Block, Mask) { + let mut block = [[0u8; 4]; 16]; + // A block wholly inside the image: four rows of four texels. + let (x0, y0) = (bx * 4, by * 4); + if x0 + 4 <= width && y0 + 4 <= height { + let mut copied = 0; + for (ty, row) in block.as_chunks_mut::<4>().0.iter_mut().enumerate() { + if let Some(src) = texels.get((y0 + ty) * width + x0..).and_then(|s| s.first_chunk::<4>()) { + *row = *src; + copied += 1; + } + } + if copied == 4 { + return (block, Mask::MAX); + } + } + let mut inside: Mask = 0; + for (t, texel) in block.iter_mut().enumerate() { + let (x, y) = (bx * 4 + t % 4, by * 4 + t / 4); + if x < width + && y < height + && let Some(p) = texels.get(y * width + x) + { + *texel = *p; + inside |= 1 << t; + } + } + (block, inside) +} + +/// The next mip level: each pixel the average of the 2×2 pixels it covers, or of 2×3, 3×2 or +/// 3×3 along the last column and row of an odd-sized level, so no pixel is dropped. +fn downsample(src: &[u8], (w, h): (usize, usize), (nw, nh): (usize, usize), channels: usize) -> Result, DdsError> { + let len = nw.checked_mul(nh).and_then(|n| n.checked_mul(channels)).ok_or_else(|| encode_err("mip level size overflow"))?; + let mut dst = alloc_zeroed(len)?; + let span = |i: usize, n: usize, size: usize| 2 * i..=if i + 1 == n { size.saturating_sub(1) } else { 2 * i + 1 }; + let ch = channels.max(1); + let line = w * ch; + rows(&mut dst, nw * channels, |y, row| { + let ys = span(y, nh, h); + // Every pixel but those of the last column and row averages exactly 2×2: the same sum + // and rounding as below, from two source rows read in step. + let mut edge = 0; + if y + 1 < nh + && let (Some(r0), Some(r1)) = (src.get(2 * y * line..(2 * y + 1) * line), src.get((2 * y + 1) * line..(2 * y + 2) * line)) + { + let interior = nw.saturating_sub(1); + for ((px, a), b) in row.chunks_exact_mut(ch).zip(r0.chunks_exact(2 * ch)).zip(r1.chunks_exact(2 * ch)).take(interior) { + for (c, v) in px.iter_mut().enumerate() { + let sum = u32::from(a[c]) + u32::from(a[ch + c]) + u32::from(b[c]) + u32::from(b[ch + c]); + *v = ((sum + 2) / 4) as u8; + } + } + edge = interior; + } + for (x, px) in row.chunks_exact_mut(ch).enumerate().skip(edge) { + let xs = span(x, nw, w); + for (c, v) in px.iter_mut().enumerate() { + let (mut sum, mut n) = (0u32, 0u32); + for sy in ys.clone() { + for sx in xs.clone() { + if let Some(&s) = src.get((sy * w + sx) * channels + c) { + sum += u32::from(s); + n += 1; + } + } + } + *v = ((sum + n / 2) / n.max(1)) as u8; + } + } + }); + Ok(dst) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pixel_buffer_of_the_wrong_size_is_refused() { + let options = DdsOptions::default(); + assert!(matches!(encode(2, 2, Layout::Rgb, &[0; 11], options), Err(DdsError::Encode(_)))); + assert!(matches!(encode(2, 2, Layout::Rgb, &[0; 13], options), Err(DdsError::Encode(_)))); + assert!(encode(2, 2, Layout::Rgb, &[0; 12], options).is_ok()); + } + + #[test] + fn block_compressions_take_their_layout_only() { + let options = DdsOptions { compression: DdsCompression::Bc3, mipmaps: false }; + assert_eq!(encode(1, 1, Layout::Rgb, &[1, 2, 3], options), Err(DdsError::Encode("Rgb pixels can't be written as `bc3`".into()))); + for compression in DdsCompression::ALL { + for layout in [Layout::Gray, Layout::GrayA, Layout::Rgb, Layout::Rgba] { + let options = DdsOptions { compression, mipmaps: false }; + let written = encode(1, 1, layout, &[9; 4][..layout.channels()], options); + let takes = compression.layout().is_none_or(|l| l == layout); + assert_eq!(written.is_ok(), takes, "{compression:?} from {layout:?}"); + } + } + } + + #[test] + fn the_header_is_read_before_the_pixels() { + // A header that promises more pixel data than the file holds: its size and layout are + // known, and only decoding fails. + let file = encode(8, 8, Layout::Gray, &[7; 64], DdsOptions::default()).unwrap(); + let texture = Texture::parse(&file[..HEADER + 10]).unwrap(); + assert_eq!((texture.width(), texture.height(), texture.layout()), (8, 8, Layout::Gray)); + assert!(matches!(texture.decode(), Err(DdsError::Malformed(_)))); + assert_eq!(Texture::parse(&file).and_then(|t| t.decode()), Ok(vec![7; 64])); + } +} diff --git a/crates/dds/tests/boundary.rs b/crates/dds/tests/boundary.rs new file mode 100644 index 000000000..ecd3aac11 --- /dev/null +++ b/crates/dds/tests/boundary.rs @@ -0,0 +1,46 @@ +use craft_dds::{DdsCompression, DdsOptions, Layout, Texture, encode}; +#[test] +fn metadata_requires_a_complete_header() { + for (compression, layout, channels, header) in [(DdsCompression::None, Layout::Gray, 1, 128), (DdsCompression::Bc4, Layout::Gray, 1, 148)] { + let data = encode(4, 4, layout, &vec![7; 16 * channels], DdsOptions { compression, mipmaps: false }).unwrap(); + for n in 0..header { + assert!(Texture::parse(&data[..n]).is_err(), "accepted {n}/{header} header bytes"); + } + assert!(Texture::parse(&data[..header]).is_ok()); + } +} +#[test] +fn empty_dimensions_are_not_textures() { + for (w, h) in [(0, 0), (0, 4), (4, 0)] { + assert!(encode(w, h, Layout::Gray, &[], DdsOptions::default()).is_err(), "encoded {w}x{h}"); + } +} +#[test] +fn decoded_output_respects_explicit_budget() { + let data = encode(4, 4, Layout::Rgba, &[7; 64], DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }).unwrap(); + let texture = Texture::parse(&data).unwrap(); + assert!(matches!(texture.decode_with_limit(63), Err(craft_dds::DdsError::LimitExceeded { required: 64, limit: 63 }))); + assert_eq!(texture.decode_with_limit(64).unwrap().len(), 64); + assert_eq!(texture.decode().unwrap(), texture.decode_with_limit(u64::MAX).unwrap()); +} +#[test] +fn parse_rejects_empty_dimensions() { + let valid = encode(1, 1, Layout::Gray, &[7], DdsOptions::default()).unwrap(); + for (w, h) in [(0u32, 0u32), (0, 4), (4, 0)] { + let mut data = valid.clone(); + data[12..16].copy_from_slice(&h.to_le_bytes()); + data[16..20].copy_from_slice(&w.to_le_bytes()); + assert!(Texture::parse(&data).is_err()); + } +} +#[test] +fn default_budget_rejects_oversized_header_before_payload_or_allocation() { + let mut data = encode(1, 1, Layout::Gray, &[7], DdsOptions::default()).unwrap(); + data.truncate(128); + data[12..16].copy_from_slice(&65536u32.to_le_bytes()); + data[16..20].copy_from_slice(&32768u32.to_le_bytes()); + data[20..24].copy_from_slice(&32768u32.to_le_bytes()); + let texture = Texture::parse(&data).unwrap(); + assert!(matches!(texture.decode(), Err(craft_dds::DdsError::LimitExceeded { limit: craft_dds::DEFAULT_MAX_DECODE_BYTES, .. }))); + assert!(matches!(texture.decode_with_limit(u64::MAX), Err(craft_dds::DdsError::Malformed(_)))); +} diff --git a/crates/docx/src/read/chart.rs b/crates/docx/src/read/chart.rs index 5b02603d6..4b7696eee 100644 --- a/crates/docx/src/read/chart.rs +++ b/crates/docx/src/read/chart.rs @@ -37,7 +37,7 @@ use parse::{axis, category_text, labels, numbers}; use parse::{read_series, text_size, title_of}; #[cfg(test)] use plot::{Scale, narrow, nice_scale}; -use plot::{backdrop, cartesian}; +use plot::{backdrop, cartesian, label}; use polar::{pie, radar}; /// Most series read from one chart. @@ -141,6 +141,51 @@ fn placeholder(out: &mut Vec, space: &El, theme: &[Rgb], w: f32, h: text(out, line, &clip_text(&msg, area.w, size), size, TextAlign::Center, false); } +/// Items for an Office 2016 chart (`cx:chartSpace`: waterfall, funnel, treemap…), sized `w` x `h` +/// points: none of these types is drawn yet, so this is the same placeholder an unsupported +/// classic chart gets (frame, title, the type it is), at the size the chart takes in Word. +/// `space` is `None` when the part can't be read: the frame and "Chart" are still drawn. +pub(crate) fn chartex_items(space: Option<&El>, w: f32, h: f32) -> Vec { + let mut out = Vec::new(); + if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + return out; + } + out.push(GraphicItem::Shape { rect: [0.0, 0.0, w, h], kind: ShapeKind::Rectangle, fill: None, stroke: Some(AXIS), stroke_width: 0.75 }); + let mut area = Rect { x: PAD, y: PAD, w: (w - 2.0 * PAD).max(1.0), h: (h - 2.0 * PAD).max(1.0) }; + let chart = space.and_then(|s| s.child("cx:chart")); + let title = chart.and_then(|c| c.child("cx:title")).and_then(|t| { + // Rich text keeps its runs together ("Sales " + "funnel"); a text-data title is one value. + let s = t.find("cx:rich").or_else(|| t.find("cx:v")).map(|e| e.deep_text()).unwrap_or_default(); + let s = label(s.trim()); + (!s.is_empty()).then_some(s) + }); + if let Some(t) = title { + area = title_block(&mut out, &t, area); + } + let kind = chart.and_then(|c| c.find("cx:series")).and_then(|s| s.attr("layoutId")).unwrap_or(""); + let size = FONT; + let lh = size * LINE; + let msg = format!("{} (not supported yet)", chartex_name(kind)); + let line = Rect { x: area.x, y: area.y + ((area.h - lh) / 2.0).max(0.0), w: area.w, h: lh }; + text(&mut out, line, &clip_text(&msg, area.w, size), size, TextAlign::Center, false); + out +} + +/// What a placeholder calls an Office 2016 chart type (`cx:series` `layoutId`). +fn chartex_name(layout: &str) -> &'static str { + match layout { + "waterfall" => "Waterfall chart", + "funnel" => "Funnel chart", + "treemap" => "Treemap chart", + "sunburst" => "Sunburst chart", + "boxWhisker" => "Box and whisker chart", + "clusteredColumn" => "Histogram chart", + "paretoLine" => "Pareto chart", + "regionMap" => "Map chart", + _ => "Chart", + } +} + /// What a placeholder calls a chart type element WordCraft doesn't draw. fn unsupported_name(name: &str) -> &'static str { match name { diff --git a/crates/docx/src/read/chart/tests.rs b/crates/docx/src/read/chart/tests.rs index ae80c028e..d785d4400 100644 --- a/crates/docx/src/read/chart/tests.rs +++ b/crates/docx/src/read/chart/tests.rs @@ -899,3 +899,27 @@ fn source_linked_series_labels_do_not_inherit_the_chart_format() { let inherited = run(r#""#); assert!(inherited.contains(&"320%".to_string()), "{inherited:?}"); } + +#[test] +fn office_2016_chart_draws_a_placeholder_of_its_size() { + let cx = |series: &str, title: &str| { + let x = format!( + r#"{title}{series}"# + ); + crate::xml::parse(x.as_bytes()).unwrap() + }; + let title = r#"Quarterly steps"#; + let rich = r#"Sales funnel"#; + let waterfall = chartex_items(Some(&cx(r#""#, title)), 432.0, 252.0); + assert_eq!(texts(&waterfall), ["Quarterly steps", "Waterfall chart (not supported yet)"]); + let framed = waterfall.iter().any(|it| matches!(it, GraphicItem::Shape { rect, stroke: Some(_), .. } if *rect == [0.0, 0.0, 432.0, 252.0])); + assert!(framed, "the frame has the chart's size: {waterfall:?}"); + let funnel = chartex_items(Some(&cx(r#""#, rich)), 300.0, 200.0); + assert_eq!(texts(&funnel), ["Sales funnel", "Funnel chart (not supported yet)"]); + let other = chartex_items(Some(&cx(r#""#, "")), 300.0, 200.0); + assert_eq!(texts(&other), ["Chart (not supported yet)"]); + // An unreadable part still reserves and frames the chart's place. + let missing = chartex_items(None, 300.0, 200.0); + assert_eq!(texts(&missing), ["Chart (not supported yet)"]); + assert!(chartex_items(None, 0.0, 200.0).is_empty() && chartex_items(None, f32::NAN, 200.0).is_empty()); +} diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index bb4804e0d..8cf4c99dd 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -56,6 +56,7 @@ impl Reader<'_> { } "m:mathPr" => s.math = Some(math::read_math_pr(k)), "w:mirrorMargins" => s.mirror_margins = on_off(k), + "w:gutterAtTop" => s.gutter_at_top = on_off(k), "w:autoHyphenation" => s.auto_hyphenation = on_off(k), "w:doNotHyphenateCaps" => s.hyphenate_caps = !on_off(k), "w:hyphenationZone" => { diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index dc61b3a28..618ef8c10 100644 --- a/crates/docx/src/read/props.rs +++ b/crates/docx/src/read/props.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use craft_wordmodel::para::cap_alt; use craft_wordmodel::props::{ - Align, Border, BorderStyle, Borders, CellProps, CharProps, CombineBrackets, EastAsianLayout, HeightRule, Highlight, LineSpacing, NumRef, + Align, Border, BorderStyle, Borders, CellProps, CharProps, CombineBrackets, EastAsianLayout, HeightRule, Highlight, Kashida, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, Rgb, RowProps, TabAlign, TabLeader, TabStop, TableFloat, TableLook, TableProps, TextAlignment, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign, }; @@ -465,7 +465,14 @@ impl PropCtx { _ => {} } } - "w:jc" => p.align = k.attr("w:val").map(align), + "w:jc" => { + if let Some(v) = k.attr("w:val") { + p.align = Some(align(v)); + if let Some(kashida) = Kashida::from_jc(v) { + p.kashida = Some(kashida); + } + } + } "w:outlineLvl" => p.outline_level = k.attr("w:val").and_then(u32_of).map(|v| v.min(9) as u8), "w:rPr" => mark = self.rpr(k), _ => {} @@ -555,6 +562,17 @@ pub fn margins(e: &El) -> [f32; 4] { margin_sides(e).map(|side| side.unwrap_or(0.0)) } +/// Word's own cell margins (the Normal Table style): 0.08" left and right, none above or below. +pub const WORD_CELL_MARGINS: [f32; 4] = [0.0, 5.4, 0.0, 5.4]; + +/// A table's `w:tblCellMar` over the margins it would have without one (its +/// style's, else Word's). A side the element leaves out keeps the underlying margin, as in Word: +/// a form table that sets only `w:left` keeps its style's right margin, not none. +pub fn margins_over(e: &El, base: [f32; 4]) -> [f32; 4] { + let sides = margin_sides(e); + std::array::from_fn(|i| sides.get(i).copied().flatten().or_else(|| base.get(i).copied()).unwrap_or(0.0)) +} + fn margin_sides(e: &El) -> [Option; 4] { let get = |names: &[&str]| names.iter().find_map(|n| e.child(n)).and_then(|c| tw(c, "w:w")).map(|v| v.clamp(0.0, 1584.0)); [get(&["w:top"]), get(&["w:left", "w:start"]), get(&["w:bottom"]), get(&["w:right", "w:end"])] diff --git a/crates/docx/src/read/shape_style.rs b/crates/docx/src/read/shape_style.rs index 9f28ef2ff..983218f9e 100644 --- a/crates/docx/src/read/shape_style.rs +++ b/crates/docx/src/read/shape_style.rs @@ -47,6 +47,7 @@ pub(crate) fn preset_kind(prst: &str) -> ShapeKind { "downArrow" => ShapeKind::ArrowDown, "star4" | "star5" | "star6" | "star7" | "star8" | "star10" | "star12" | "star16" | "star24" | "star32" => ShapeKind::Star, "heart" => ShapeKind::Heart, + "frame" => ShapeKind::Frame, _ => ShapeKind::Rectangle, } } diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 770375365..86ceb1651 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -22,6 +22,7 @@ use craft_wordmodel::wordart::TextWarp; mod blocks; mod drawing; mod fields; +mod locked_canvas; mod runs; mod vml; diff --git a/crates/docx/src/read/story/blocks.rs b/crates/docx/src/read/story/blocks.rs index 878429454..91c54714f 100644 --- a/crates/docx/src/read/story/blocks.rs +++ b/crates/docx/src/read/story/blocks.rs @@ -333,12 +333,37 @@ impl Reader<'_> { } } + /// Omitted table-margin sides inherit from that property set's style. + fn table_margin_base(&self, style: Option<&str>) -> [f32; 4] { + style.and_then(|id| self.doc.styles.table_style(id)).and_then(|st| st.parts.cell_margins).unwrap_or(if self.no_default_table_style { + [0.0; 4] + } else { + crate::read::props::WORD_CELL_MARGINS + }) + } + fn read_table(&mut self, sc: &mut StoryCtx, t: &El, rels: &Rels, depth: usize) -> Option { let mut table = Table::default(); if let Some(p) = t.child("w:tblPr") { table.props = self.pc.tblpr(p); + // Sides `w:tblCellMar` leaves out keep the style's margins; without a style, Word's + // 0.08" left and right, or none in a file with no default table style. + if let Some(m) = p.child("w:tblCellMar") { + let base = self.table_margin_base(table.props.style.as_deref()); + table.props.cell_margins = Some(crate::read::props::margins_over(m, base)); + } if let Some(ch) = p.child("w:tblPrChange") { - let mut old = ch.child("w:tblPr").map(|o| self.pc.tblpr(o)).unwrap_or_default(); + let mut old = ch + .child("w:tblPr") + .map(|o| { + let mut props = self.pc.tblpr(o); + if let Some(m) = o.child("w:tblCellMar") { + let base = self.table_margin_base(props.style.as_deref()); + props.cell_margins = Some(crate::read::props::margins_over(m, base)); + } + props + }) + .unwrap_or_default(); // Rejecting the change brings back these properties: with the same margins. self.no_default_margins(&mut old); table.props.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, ch), old); diff --git a/crates/docx/src/read/story/drawing.rs b/crates/docx/src/read/story/drawing.rs index 811225f4a..d1e5bf2ce 100644 --- a/crates/docx/src/read/story/drawing.rs +++ b/crates/docx/src/read/story/drawing.rs @@ -12,23 +12,7 @@ impl Reader<'_> { /// text and drawing ids are carried into the object. Returns `None` when the frame or payload /// cannot be read. Ink written by WordCraft keeps its tool's caps rather than an outline cap. pub(super) fn read_drawing(&mut self, sc: &mut StoryCtx, d: &El, rels: &Rels) -> Option { - let (c, anchored) = match d.child("wp:inline") { - Some(c) => (c, false), - None => (d.child("wp:anchor")?, true), - }; - let ext = c.child("wp:extent"); - let dim = |n: &str| ext.and_then(|e| e.attr(n)).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT); - let (w, h) = (dim("cx"), dim("cy")); - let (alt, meta) = nv_alt(c.child("wp:docPr")); - let mut float = if anchored { anchor_float(c, self.file_orders) } else { Float::default() }; - float.alt = meta; - float.hidden = c.child("wp:docPr").is_some_and(|p| on_off_attr(p, "hidden")); - if let Some(e) = c.child("wp:effectExtent") { - for (slot, n) in float.effect.iter_mut().zip(["l", "t", "r", "b"]) { - // Negative for a rotated object narrower than its frame; settled below. - *slot = e.attr(n).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(-1584.0, 1584.0); - } - } + let Frame { c, anchored, w, h, alt, mut float } = drawing_frame(d, self.file_orders)?; let gd = c.child("a:graphic").and_then(|g| g.child("a:graphicData"))?; // Checked by URI before the blip search: a diagram's data can hold a blip further down. let uri = gd.attr("uri").unwrap_or(""); @@ -82,6 +66,10 @@ impl Reader<'_> { self.read_canvas(sc, c, rels, w, h, float) } else if let Some(g) = gd.child("wpg:wgp") { self.read_group(sc, g, rels, w, h, float)? + } else if let Some(lc) = gd.child("lc:lockedCanvas") { + // Word 2007's shapes, pictures and text in a drawing: read as the group they are. + let g = super::locked_canvas::as_group(lc, &self.doc.settings.theme_colors); + self.read_group(sc, &g, rels, w, h, float)? } else if direct_shape.is_none() && gd.find("a:blip").is_some() { self.read_pic(gd, rels, w, h, alt.clone(), float)? } else { @@ -188,14 +176,39 @@ impl Reader<'_> { let fallback = ac.child("mc:Fallback")?; let kept = El { name: "mc:AlternateContent".into(), attrs: Vec::new(), kids: vec![Node::El(choice.clone()), Node::El(fallback.clone())] }; let source = self.keep_embedded(&kept, rels, &[])?; - let Some(InlineObject::Image { media, w, h, alt, float, .. }) = self.read_drawing(sc, fallback.child("w:drawing")?, rels) else { - return None; + let picture = fallback.child("w:drawing").and_then(|d| self.read_drawing(sc, d, rels)); + let Some(InlineObject::Image { media, w, h, alt, float, .. }) = picture else { + return self.chartex_placeholder(choice, fallback, rels, source); }; let items = vec![GraphicItem::Image { rect: [0.0, 0.0, w, h], media }]; let graphic = Arc::new(Graphic { kind: GraphicKind::Chart, items, w, h, source: Some(source), ..Default::default() }); Some(InlineObject::Graphic { w, h, alt, float, graphic }) } + /// An Office 2016 chart whose fallback holds no picture (only text, say "Chart not + /// available"): a placeholder of the chart's own size (the `wp:extent` of its `mc:Choice`), + /// so the page breaks where they do with the chart drawn. The fallback is written back as it + /// was. `None` when the fallback has a picture or another drawing (read as before), or + /// holds runs or paragraphs, which a writer can't put inside the run that holds the object. + fn chartex_placeholder(&mut self, choice: &El, fallback: &El, rels: &Rels, source: Arc) -> Option { + const RUN_CONTENT: [&str; 6] = ["w:t", "w:tab", "w:br", "w:cr", "w:noBreakHyphen", "w:softHyphen"]; + if fallback.find("a:graphic").is_some() || !fallback.els().all(|e| RUN_CONTENT.contains(&e.name.as_str())) { + return None; + } + let Frame { c, w, h, alt, mut float, .. } = drawing_frame(choice.child("w:drawing")?, self.file_orders)?; + let part = c + .child("a:graphic") + .and_then(|g| g.child("a:graphicData")) + .and_then(|gd| gd.child("cx:chart")) + .and_then(|cx| cx.attr("r:id")) + .and_then(|id| crate::read::part_of(rels, id, "chartEx")); + let space = part.and_then(|p| self.graphic_part(&p)); + let items = crate::read::chart::chartex_items(space.as_deref(), w, h); + float.effect = float.effect.map(|e| e.max(0.0)); + let graphic = Arc::new(Graphic { kind: GraphicKind::Chart, items, w, h, source: Some(source), ..Default::default() }); + Some(InlineObject::Graphic { w, h, alt, float, graphic }) + } + /// A group or canvas member that is native ink (`content`, a `w14:contentPart`, inside /// `alternate` when it has a picture fallback): what to write back (the whole alternate when /// it can be kept, else the ink alone) and its fallback picture (a `Document::media` key). @@ -526,12 +539,17 @@ impl Reader<'_> { outline_fill: paint.outline_fill, ..ShapeExtra::default() }; - // A rounded rectangle's own corner (`adj`, ECMA-376 §20.1.10.56); other presets drawn as - // rounded rectangles keep the default. - if prst == "roundRect" { + // A rounded rectangle's own corner (`adj`, ECMA-376 §20.1.10.56), a frame's own border + // width (`adj1`); other presets drawn as rounded rectangles keep the default. + let adj = match prst { + "roundRect" => Some("adj"), + "frame" => Some("adj1"), + _ => None, + }; + if let Some(adj) = adj { extra.corner = sppr .and_then(|s| s.child("a:prstGeom")) - .and_then(|g| preset_adj(g, "adj")) + .and_then(|g| preset_adj(g, adj)) .and_then(|v| u32::try_from(v.clamp(0, i64::from(craft_wordmodel::connector::MAX_CORNER))).ok()); } // Arrowheads: any end type but `none` (ECMA-376 §20.1.10.33) is drawn as a triangle of its @@ -598,6 +616,38 @@ impl Reader<'_> { } } +/// The frame of a `w:drawing`: its `wp:inline` or `wp:anchor` element, the size in points, +/// the alternative text, and the placement with its effect extent (rotation not yet settled). +struct Frame<'a> { + c: &'a El, + anchored: bool, + w: f32, + h: f32, + alt: String, + float: Float, +} + +fn drawing_frame(d: &El, file_orders: craft_wordmodel::para::FileOrders) -> Option> { + let (c, anchored) = match d.child("wp:inline") { + Some(c) => (c, false), + None => (d.child("wp:anchor")?, true), + }; + let ext = c.child("wp:extent"); + let dim = |n: &str| ext.and_then(|e| e.attr(n)).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(0.0, crate::units::MAX_LEN_PT); + let (w, h) = (dim("cx"), dim("cy")); + let (alt, meta) = nv_alt(c.child("wp:docPr")); + let mut float = if anchored { anchor_float(c, file_orders) } else { Float::default() }; + float.alt = meta; + float.hidden = c.child("wp:docPr").is_some_and(|p| on_off_attr(p, "hidden")); + if let Some(e) = c.child("wp:effectExtent") { + for (slot, n) in float.effect.iter_mut().zip(["l", "t", "r", "b"]) { + // Negative for a rotated object narrower than its frame; settled below. + *slot = e.attr(n).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.0).clamp(-1584.0, 1584.0); + } + } + Some(Frame { c, anchored, w, h, alt, float }) +} + /// The `mc:Choice` holding an Office 2016 chart (`cx:chart`) in an `mc:AlternateContent`. fn chartex_choice(ac: &El) -> Option<&El> { ac.children("mc:Choice").find(|c| c.child("w:drawing").and_then(|d| d.find("a:graphicData")).and_then(|g| g.attr("uri")) == Some(CHARTEX_URI)) diff --git a/crates/docx/src/read/story/locked_canvas.rs b/crates/docx/src/read/story/locked_canvas.rs new file mode 100644 index 000000000..59a52cea2 --- /dev/null +++ b/crates/docx/src/read/story/locked_canvas.rs @@ -0,0 +1,265 @@ +//! A DrawingML locked canvas (`lc:lockedCanvas`, ECMA-376 Part 1 §20.3.2.1): the shapes, +//! pictures and text Word 2007 writes in a drawing in compatibility mode (wordcraft#5060). It is a group +//! shape in the DrawingML namespace (`a:sp`, `a:pic`, `a:grpSp`, `a:cxnSp`, text in `a:txSp`), so +//! it is read as the `wpg:wgp` group the reader already knows: each member renamed into its +//! WordprocessingML drawing form, and its DrawingML text into `w:txbxContent` paragraphs. + +use super::{El, Node, Rgb}; + +/// Groups nested deeper than this are left out, as `group_members` does. +const MAX_NEST: usize = 8; +/// DrawingML's text size when neither the run nor the list style gives one (18 pt, in +/// hundredths of a point). +const DEFAULT_SZ: i64 = 1800; + +/// The locked canvas `lc` as a `wpg:wgp` group. `theme` resolves its text colours. +pub(super) fn as_group(lc: &El, theme: &[Rgb]) -> El { + el("wpg:wgp", Vec::new(), members(lc, theme, 0)) +} + +/// The members of DrawingML group `g`, in their WordprocessingML drawing form. +fn members(g: &El, theme: &[Rgb], depth: usize) -> Vec { + g.els() + .filter_map(|e| match e.name.as_str() { + "a:grpSpPr" => Some(renamed(e, "wpg:grpSpPr")), + "a:grpSp" if depth < MAX_NEST => Some(el("wpg:grpSp", Vec::new(), members(e, theme, depth + 1))), + "a:sp" => Some(shape(e, theme)), + "a:cxnSp" => Some(connector(e)), + "a:pic" => Some(picture(e)), + "a:txSp" => Some(text_shape(e, theme)), + _ => None, + }) + .map(Node::El) + .collect() +} + +/// `a:sp` as `wps:wsp`: its name, properties and style, and its text as a text box's. +fn shape(sp: &El, theme: &[Rgb]) -> El { + let nv = sp.child("a:nvSpPr"); + let mut kids: Vec = [ + nv.and_then(|n| n.child("a:cNvPr")).map(|e| renamed(e, "wps:cNvPr")), + nv.and_then(|n| n.child("a:cNvSpPr")).map(|e| renamed(e, "wps:cNvSpPr")), + sp.child("a:spPr").map(|e| renamed(e, "wps:spPr")), + sp.child("a:style").map(|e| renamed(e, "wps:style")), + ] + .into_iter() + .flatten() + .map(Node::El) + .collect(); + // The text sits in the shape's own rectangle (`a:useSpRect`); a text rectangle of its own + // (`a:txSp/a:xfrm`) is not kept apart. + if let Some(body) = sp.child("a:txSp").and_then(|t| t.child("a:txBody")) { + kids.extend(text_box(body, theme)); + } + el("wps:wsp", Vec::new(), kids) +} + +/// A group's text shape (`a:txSp` as a member, text with no shape of its own) as a `wps:wsp` text +/// box without fill or outline at its own rectangle (`a:xfrm`). +fn text_shape(tx: &El, theme: &[Rgb]) -> El { + let none = || Node::El(el("a:noFill", Vec::new(), Vec::new())); + let geometry = el("a:prstGeom", attrs(&[("prst", "rect")]), vec![Node::El(el("a:avLst", Vec::new(), Vec::new()))]); + let mut sp_pr: Vec = tx.child("a:xfrm").map(|x| Node::El(x.clone())).into_iter().collect(); + sp_pr.extend([Node::El(geometry), none(), Node::El(el("a:ln", Vec::new(), vec![none()]))]); + let mut kids = vec![Node::El(el("wps:cNvSpPr", attrs(&[("txBox", "1")]), Vec::new())), Node::El(el("wps:spPr", Vec::new(), sp_pr))]; + if let Some(body) = tx.child("a:txBody") { + kids.extend(text_box(body, theme)); + } + el("wps:wsp", Vec::new(), kids) +} + +/// DrawingML text body `body` as a text box's content and body properties. +fn text_box(body: &El, theme: &[Rgb]) -> Vec { + let content = el("w:txbxContent", Vec::new(), paragraphs(body, theme)); + let mut kids = vec![Node::El(el("wps:txbx", Vec::new(), vec![Node::El(content)]))]; + if let Some(bp) = body.child("a:bodyPr") { + kids.push(Node::El(renamed(bp, "wps:bodyPr"))); + } + kids +} + +/// `a:cxnSp` as a `wps:wsp` line. Its glued ends name shapes by the canvas's own ids, which +/// aren't the document's, so they are left out. +fn connector(cx: &El) -> El { + let kids = [ + cx.child("a:nvCxnSpPr").and_then(|n| n.child("a:cNvPr")).map(|e| renamed(e, "wps:cNvPr")), + cx.child("a:spPr").map(|e| renamed(e, "wps:spPr")), + cx.child("a:style").map(|e| renamed(e, "wps:style")), + ]; + el("wps:wsp", Vec::new(), kids.into_iter().flatten().map(Node::El).collect()) +} + +/// `a:pic` as `pic:pic`. +fn picture(pic: &El) -> El { + let nv = pic.child("a:nvPicPr").and_then(|n| n.child("a:cNvPr")).map(|e| el("pic:nvPicPr", Vec::new(), vec![Node::El(renamed(e, "pic:cNvPr"))])); + let kids = [nv, pic.child("a:blipFill").map(|e| renamed(e, "pic:blipFill")), pic.child("a:spPr").map(|e| renamed(e, "pic:spPr"))]; + el("pic:pic", Vec::new(), kids.into_iter().flatten().map(Node::El).collect()) +} + +/// The paragraphs of DrawingML text body `body` as `w:p`s. DrawingML text has no space before +/// or after a paragraph and single lines, so each says so rather than taking the document's +/// defaults. +fn paragraphs(body: &El, theme: &[Rgb]) -> Vec { + body.children("a:p") + .map(|p| { + // A paragraph's properties default to the list style's for its level (`lvl`, 0–8), + // then to the list style's defaults (`a:defPPr`), property by property; a run's to its + // paragraph's own (`a:pPr/a:defRPr`), then to those two's. + let ppr_el = p.child("a:pPr"); + let level = ppr_el.and_then(|pp| pp.attr("lvl")).and_then(|v| v.trim().parse::().ok()).filter(|l| *l <= 8).unwrap_or(0); + let list_style = body.child("a:lstStyle"); + let paragraph_styles: Vec<&El> = + [ppr_el, list_style.and_then(|l| l.child(&format!("a:lvl{}pPr", level + 1))), list_style.and_then(|l| l.child("a:defPPr"))] + .into_iter() + .flatten() + .collect(); + let defaults: Vec<&El> = paragraph_styles.iter().filter_map(|pp| pp.child("a:defRPr")).collect(); + let defaults = defaults.as_slice(); + let mut ppr = + vec![Node::El(el("w:spacing", attrs(&[("w:before", "0"), ("w:after", "0"), ("w:line", "240"), ("w:lineRule", "auto")]), Vec::new()))]; + let jc = match paragraph_styles.iter().find_map(|pp| pp.attr("algn")) { + Some("ctr") => Some("center"), + Some("r") => Some("right"), + Some("just") => Some("both"), + Some("dist") => Some("distribute"), + Some("l") => Some("left"), + _ => None, + }; + if let Some(jc) = jc { + ppr.push(Node::El(el("w:jc", attrs(&[("w:val", jc)]), Vec::new()))); + } + // The paragraph mark's own size and font (`a:endParaRPr`), which an empty one's + // height follows. + ppr.push(Node::El(run_props(p.child("a:endParaRPr"), defaults, theme))); + let mut kids = vec![Node::El(el("w:pPr", Vec::new(), ppr))]; + for r in p.els() { + let text = match r.name.as_str() { + "a:r" | "a:fld" => Node::El(el( + "w:t", + attrs(&[("xml:space", "preserve")]), + vec![Node::Text(r.child("a:t").map(|t| t.text()).unwrap_or_default())], + )), + "a:br" => Node::El(el("w:br", Vec::new(), Vec::new())), + _ => continue, + }; + let rpr = run_props(r.child("a:rPr"), defaults, theme); + kids.push(Node::El(el("w:r", Vec::new(), vec![Node::El(rpr), text]))); + } + Node::El(el("w:p", Vec::new(), kids)) + }) + .collect() +} + +/// A DrawingML run's properties (`a:rPr`, each falling back on the first of `defaults`, the +/// `a:defRPr`s in order, that gives it) as `w:rPr`: font, size, bold, italic, underline, +/// strikethrough, caps, baseline and colour. +fn run_props(rpr: Option<&El>, defaults: &[&El], theme: &[Rgb]) -> El { + let get = |n: &str| rpr.and_then(|r| r.attr(n)).or_else(|| defaults.iter().find_map(|d| d.attr(n))); + let child = |n: &str| rpr.and_then(|r| r.child(n)).or_else(|| defaults.iter().find_map(|d| d.child(n))); + // On, off (kept, so the document's style doesn't turn it back on), or not given. + let toggle = |n: &str| match get(n) { + Some("1" | "true") => Some(true), + Some("0" | "false") => Some(false), + _ => None, + }; + let mut kids = Vec::new(); + let mut push = |name: &str, a: &[(&str, &str)]| kids.push(Node::El(el(name, attrs(a), Vec::new()))); + // Theme fonts (`+mn-lt`) are left to the document's. + let face = |n: &str| child(n).and_then(|f| f.attr("typeface")).filter(|t| !t.is_empty() && !t.starts_with('+')); + let mut fonts = Vec::new(); + if let Some(f) = face("a:latin") { + fonts.extend([("w:ascii", f), ("w:hAnsi", f)]); + } + if let Some(f) = face("a:ea") { + fonts.push(("w:eastAsia", f)); + } + if let Some(f) = face("a:cs") { + fonts.push(("w:cs", f)); + } + if !fonts.is_empty() { + push("w:rFonts", &fonts); + } + for (drawingml, word) in [("b", "w:b"), ("i", "w:i")] { + match toggle(drawingml) { + Some(true) => push(word, &[]), + Some(false) => push(word, &[("w:val", "0")]), + None => {} + } + } + match get("cap") { + Some("all") => push("w:caps", &[]), + Some("small") => push("w:smallCaps", &[]), + _ => {} + } + match get("strike") { + Some("sngStrike") => push("w:strike", &[]), + Some("dblStrike") => push("w:dstrike", &[]), + _ => {} + } + match get("u") { + None | Some("none") => {} + Some("dbl") => push("w:u", &[("w:val", "double")]), + Some(_) => push("w:u", &[("w:val", "single")]), + } + match get("baseline").and_then(|v| v.trim().parse::().ok()) { + Some(b) if b > 0 => push("w:vertAlign", &[("w:val", "superscript")]), + Some(b) if b < 0 => push("w:vertAlign", &[("w:val", "subscript")]), + _ => {} + } + if let Some(rgb) = child("a:solidFill").and_then(|f| crate::read::drawing_color::color(f, theme)) { + push("w:color", &[("w:val", &rgb.hex())]); + } + // Hundredths of a point into half-points, within Word's 1–1638 pt. + let sz = get("sz").and_then(|v| v.trim().parse::().ok()).unwrap_or(DEFAULT_SZ).clamp(100, 163_800) / 50; + let sz = sz.to_string(); + push("w:sz", &[("w:val", &sz)]); + push("w:szCs", &[("w:val", &sz)]); + // WordArt's outline, shadow, glow and reflection, as Word 2010 writes them in `w:rPr`. + kids.extend(text_effects(child("a:ln"), child("a:effectLst"), theme).into_iter().map(Node::El)); + el("w:rPr", Vec::new(), kids) +} + +/// A DrawingML run's text outline (`a:ln`) and effects (`a:effectLst`: outer shadow, glow, +/// reflection) as the `w14:` run properties ([MS-DOCX] §2.6.1) the run reader takes for WordArt. +/// Colours are resolved here, theme and modifiers included, into a `w14:srgbClr` with its +/// transparency. Lengths (EMUs), angles and percentages carry over as they are. +fn text_effects(ln: Option<&El>, fx: Option<&El>, theme: &[Rgb]) -> Vec { + let color = |e: &El| -> Option { + let (rgb, transparency) = crate::read::drawing_color::color_alpha(e, theme, None)?; + let alpha = ((transparency.clamp(0.0, 100.0) * 1000.0).round() as i64).to_string(); + let kids = if transparency > 0.0 { vec![Node::El(el("w14:alpha", attrs(&[("w14:val", &alpha)]), Vec::new()))] } else { Vec::new() }; + Some(Node::El(el("w14:srgbClr", attrs(&[("w14:val", &rgb.hex())]), kids))) + }; + // The attributes `names` of `e`, under the `w14:` prefix. + let copied = |e: &El, names: &[&str]| -> Vec<(String, String)> { + names.iter().filter_map(|n| e.attr(n).map(|v| (format!("w14:{n}"), v.to_string()))).collect() + }; + let mut out = Vec::new(); + if let Some(ln) = ln + && let Some(c) = ln.child("a:solidFill").and_then(color) + { + out.push(el("w14:textOutline", copied(ln, &["w"]), vec![Node::El(el("w14:solidFill", Vec::new(), vec![c]))])); + } + for e in fx.into_iter().flat_map(|f| f.els()) { + match e.name.as_str() { + "a:outerShdw" => out.push(el("w14:shadow", copied(e, &["blurRad", "dist", "dir"]), color(e).into_iter().collect())), + "a:glow" => out.push(el("w14:glow", copied(e, &["rad"]), color(e).into_iter().collect())), + "a:reflection" => out.push(el("w14:reflection", copied(e, &["blurRad", "stA", "endPos", "dist"]), Vec::new())), + _ => {} + } + } + out +} + +fn el(name: &str, attrs: Vec<(String, String)>, kids: Vec) -> El { + El { name: name.to_string(), attrs, kids } +} + +fn attrs(a: &[(&str, &str)]) -> Vec<(String, String)> { + a.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() +} + +/// `e` under another name, with its attributes and children. +fn renamed(e: &El, name: &str) -> El { + El { name: name.to_string(), ..e.clone() } +} diff --git a/crates/docx/src/write.rs b/crates/docx/src/write.rs index 0391ba615..9f4024159 100644 --- a/crates/docx/src/write.rs +++ b/crates/docx/src/write.rs @@ -178,6 +178,11 @@ pub fn write_as(doc: &Document, flavor: Flavor) -> Result, DocxError> { } impl Writer<'_> { + /// The document's styles, for writers that need the resolved style chain. + pub(crate) fn styles(&self) -> &craft_wordmodel::styles::StyleSheet { + &self.doc.styles + } + fn assign_media(&mut self) { let mut used: std::collections::HashSet = std::collections::HashSet::new(); for (key, bytes) in &self.doc.media { diff --git a/crates/docx/src/write/embed.rs b/crates/docx/src/write/embed.rs index 7673a6f26..ca2401443 100644 --- a/crates/docx/src/write/embed.rs +++ b/crates/docx/src/write/embed.rs @@ -341,7 +341,16 @@ impl super::Writer<'_> { /// the object's current size and position into its own markup (a chart or diagram's frame is /// written by the caller). `None` when it can't be written back (its parts are gone). pub(super) fn embedded_xml(&mut self, src: &Embedded, rels: &mut PartRels, resize: Option<(f32, f32, &Float, &str)>) -> Option { - self.embedded_tree(src, rels, resize).map(|root| root.to_xml()) + let mut root = self.embedded_tree(src, rels, resize)?; + // read_object prefers a direct VML preview. Its signed z-index is not modeled, so a + // coexisting retained DrawingML frame cannot safely be assigned the model's order. + let vml_preview = root.els().any(|e| e.name.starts_with("v:") && e.local() != "shapetype"); + if let Some((_, _, float, _)) = resize + && !vml_preview + { + self.retained_anchor_order(&mut root, float, &mut None, 0); + } + Some(root.to_xml()) } /// The same bounded preservation operation, retaining the parsed tree for a caller that @@ -480,6 +489,27 @@ impl super::Writer<'_> { /// Write an OLE object's size (and position, when floating), rotation and flips into its VML /// shape and DrawingML picture, with the effect extent covering the rotated bounds as for /// other drawings, its alt text into both, and give its drawing a fresh `wp:docPr` id. + /// Retained DrawingML frames of one OLE object share one allocated order. + /// This does not normalize VML z-index: its signed order is not represented by the reader. + /// Stop at each outer anchor or inline frame: nested drawings have their own placement. + fn retained_anchor_order(&mut self, e: &mut El, float: &Float, order: &mut Option, depth: usize) { + if depth > MAX_DEPTH { + return; + } + if e.name == "wp:inline" { + return; + } + if e.name == "wp:anchor" { + let z = *order.get_or_insert_with(|| self.drawing_order(float)); + set_attr(e, "relativeHeight", &z.to_string()); + return; + } + for child in &mut e.kids { + if let xml::Node::El(child) = child { + self.retained_anchor_order(child, float, order, depth + 1); + } + } + } fn resize_object(&mut self, e: &mut El, w: f32, h: f32, float: &Float, alt: &str, depth: usize) { if depth > MAX_DEPTH { return; diff --git a/crates/docx/src/write/props.rs b/crates/docx/src/write/props.rs index 0b92ce191..fb76da8d8 100644 --- a/crates/docx/src/write/props.rs +++ b/crates/docx/src/write/props.rs @@ -1,8 +1,8 @@ //! Property writers, in ECMA-376 schema element order. use craft_wordmodel::props::{ - Align, Border, BorderStyle, Borders, CellProps, CharProps, EastAsianLayout, HeightRule, Highlight, LineSpacing, ParaProps, RowProps, TabAlign, - TabLeader, TableFloat, TableLook, TableProps, TextColor, VAlign, VMerge, VertAlign, + Align, Border, BorderStyle, Borders, CellProps, CharProps, EastAsianLayout, HeightRule, Highlight, Kashida, LineSpacing, ParaProps, RowProps, + TabAlign, TabLeader, TableFloat, TableLook, TableProps, TextColor, VAlign, VMerge, VertAlign, }; use crate::units::{n, twips}; @@ -201,6 +201,11 @@ pub fn align_val(a: Align) -> &'static str { } } +/// `w:jc` for a paragraph, including the kashida length of a justified one. +pub fn jc_val(a: Align, kashida: Option) -> &'static str { + if a == Align::Justify { kashida.unwrap_or(Kashida::None).jc() } else { align_val(a) } +} + /// A tab stop's or positional tab's `w:leader` value. pub fn tab_leader(l: TabLeader) -> &'static str { match l { @@ -287,7 +292,7 @@ pub fn ppr_inner(w: &mut W, p: &ParaProps, framed: bool, num_change: Option<&Cha toggle(w, "w:contextualSpacing", p.contextual_spacing); toggle(w, "w:mirrorIndents", p.mirror_indents); if let Some(a) = p.align { - w.val("w:jc", align_val(a)); + w.val("w:jc", jc_val(a, p.kashida)); } if let Some(direction) = p.text_direction { w.val("w:textDirection", direction.ooxml()); diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index 18f9f8239..199676e16 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -50,6 +50,10 @@ pub(super) fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, temp if s.mirror_margins { w.empty("w:mirrorMargins", &[]); } + // CT_Settings order: after `w:mirrorMargins`, before `w:attachedTemplate`. + if s.gutter_at_top { + w.empty("w:gutterAtTop", &[]); + } if let Some(id) = template_rel { w.empty("w:attachedTemplate", &[("r:id", id)]); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 981b9c098..a72046e83 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -18,6 +18,7 @@ const OWNED: &[&str] = &[ "w:removeDateAndTime", "w:displayBackgroundShape", "w:mirrorMargins", + "w:gutterAtTop", "w:attachedTemplate", "w:linkStyles", "w:trackRevisions", @@ -386,4 +387,22 @@ mod tests { assert!(out.contains(""), "{out}"); assert!(out.contains(""), "{out}"); } + + #[test] + fn gutter_at_top_comes_from_the_generated_part() { + let orig = + r#""#; + assert!(has_unowned(orig.as_bytes())); + // Turned off in the model: the original element goes, the foreign one stays. + let out = String::from_utf8(merge(orig.as_bytes(), GEN.as_bytes()).unwrap()).unwrap(); + assert!(!out.contains("gutterAtTop") && out.contains("").count(), 1, "{out}"); + let at = |tag: &str| out.find(tag).unwrap_or_else(|| panic!("{tag} missing: {out}")); + assert!(at("") < at("") && at("") < at(""#)); + } } diff --git a/crates/docx/src/write/story/drawing.rs b/crates/docx/src/write/story/drawing.rs index b302f047b..1cc57ffac 100644 --- a/crates/docx/src/write/story/drawing.rs +++ b/crates/docx/src/write/story/drawing.rs @@ -126,16 +126,22 @@ impl Writer<'_> { ShapeKind::ArrowDown => "downArrow", ShapeKind::Star => "star5", ShapeKind::Heart => "heart", + ShapeKind::Frame => "frame", }; match geom { Some(f) => cust_geom(w, f, *sw, *sh), None => { w.open("a:prstGeom", &[("prst", prst)]); - match extra.corner.filter(|_| *kind == ShapeKind::RoundedRectangle) { - Some(c) => { + let adj = match kind { + ShapeKind::RoundedRectangle => Some("adj"), + ShapeKind::Frame => Some("adj1"), + _ => None, + }; + match adj.zip(extra.corner) { + Some((name, c)) => { w.open("a:avLst", &[]); let fmla = format!("val {}", c.min(craft_wordmodel::connector::MAX_CORNER)); - w.empty("a:gd", &[("name", "adj"), ("fmla", &fmla)]); + w.empty("a:gd", &[("name", name), ("fmla", &fmla)]); w.close("a:avLst"); } None => w.empty("a:avLst", &[]), @@ -257,6 +263,17 @@ impl Writer<'_> { w.close("w:drawing"); } + /// One order for an anchored object, shared by generated and retained drawings. + pub(in crate::write) fn drawing_order(&mut self, float: &Float) -> u32 { + let z = if float.z > 0 { + self.zmap.get(&float.z).copied().unwrap_or(float.z.saturating_sub(1)) + } else { + self.z = self.z.saturating_add(1); + self.z + }; + self.anchor_z = z; + z + } pub(super) fn drawing_open(&mut self, w: &mut W, info: DrawingInfo<'_>) { let DrawingInfo { float, size: (iw, ih), docpr, name, alt, link } = info; let (cx, cy) = (emu(iw.max(0.0)), emu(ih.max(0.0))); @@ -267,13 +284,7 @@ impl Writer<'_> { let (dt, db) = (emu(float.dist_top.clamp(0.0, 1584.0)), emu(float.dist_bottom.clamp(0.0, 1584.0))); // A stacking order read from a file is kept (one less: see `Float::z`); objects made // here go above those. - let z = if float.z > 0 { - self.zmap.get(&float.z).copied().unwrap_or(float.z.saturating_sub(1)) - } else { - self.z = self.z.saturating_add(1); - self.z - }; - self.anchor_z = z; + let z = self.drawing_order(float); let behind = if float.wrap == Wrap::BehindText { "1" } else { "0" }; w.open( "wp:anchor", diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index e0242d8eb..aa973184e 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -76,6 +76,12 @@ impl Writer<'_> { a.push(("w:original", c.original.clone())); a }); + // `w:jc` encodes alignment and kashida length together. A justified paragraph + // whose kashida is unset (`None`) still inherits a length from its style; writing + // `both` would read back as `Some(Kashida::None)` and cancel that length. + if pp.align == Some(craft_wordmodel::props::Align::Justify) && pp.kashida.is_none() { + pp.kashida = Some(self.styles().resolve_para(&pp).kashida); + } ppr_inner(w, &pp, framed, num_change.as_ref()); if has_mark { self.write_mark_rpr(w, &p.mark, &mark_revs); diff --git a/crates/docx/src/write/styles.rs b/crates/docx/src/write/styles.rs index 3bcf9ab97..0fddf33b4 100644 --- a/crates/docx/src/write/styles.rs +++ b/crates/docx/src/write/styles.rs @@ -184,7 +184,13 @@ fn style_property_xml(wr: &mut Writer<'_>, w: &mut W, st: &Style) { let para_change = st.para_change.as_deref().filter(|ch| ch.old.formatting() != st.para.formatting()); if (!st.para.is_empty() || para_change.is_some()) && st.kind != StyleKind::Character { w.open("w:pPr", &[]); - props::ppr_inner(w, &st.para, false, None); + let mut ppr = st.para.clone(); + if ppr.align == Some(craft_wordmodel::props::Align::Justify) && ppr.kashida.is_none() { + let mut probe = ppr.clone(); + probe.style = Some(st.id.clone()); + ppr.kashida = Some(wr.styles().resolve_para(&probe).kashida); + } + props::ppr_inner(w, &ppr, false, None); if let Some(ch) = para_change { let a = wr.change_attrs(ch.rev); open_change(w, "w:pPrChange", &a); diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index bb86755d9..fa50d217a 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -52,8 +52,10 @@ pub const NAMESPACES: &[(&str, &str)] = &[ pub const DECORATIVE_EXT: &str = "{C183D7F6-B498-43B3-948B-1728B52AA6E4}"; pub const DECORATIVE_NS: &str = "http://schemas.microsoft.com/office/drawing/2017/decorative"; -/// Namespaces that only appear in non-body parts. +/// Namespaces that only appear in non-body parts, or that the reader reads but never writes. const OTHER_NAMESPACES: &[(&str, &str)] = &[ + // A locked canvas, read into a drawing group (wordcraft#5060). + ("lc", "http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas"), ("b", "http://schemas.openxmlformats.org/officeDocument/2006/bibliography"), ("rel", "http://schemas.openxmlformats.org/package/2006/relationships"), ("ct", "http://schemas.openxmlformats.org/package/2006/content-types"), diff --git a/crates/docx/tests/it/cell_margin_inheritance.rs b/crates/docx/tests/it/cell_margin_inheritance.rs index 83aafc7d0..dc5cba644 100644 --- a/crates/docx/tests/it/cell_margin_inheritance.rs +++ b/crates/docx/tests/it/cell_margin_inheritance.rs @@ -98,3 +98,18 @@ fn no_default_table_style_means_no_cell_margins() { let reopened = craft_docx::read(&bytes).unwrap(); assert_eq!(reopened.body[0].as_table().unwrap().props.cell_margins, Some([0.0; 4])); } + +#[test] +fn tracked_partial_table_margins_keep_the_old_styles_other_sides() { + let body = r#""#; + let styles = r#""#; + let doc = craft_docx::read(&package(body, Some(styles))).unwrap(); + let table = doc.body[0].as_table().unwrap(); + assert_eq!(table.props.cell_margins, Some([3.0, 5.0, 0.0, 9.0])); + let old = &table.props.fmt_change.as_ref().unwrap().old; + assert_eq!( + old.cell_margins, + Some([1.0, 0.0, 2.0, 8.0]), + "explicit zero overrides left, omitted sides come from the old style, not the current one" + ); +} diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 08dc4befd..51fc20226 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1862,6 +1862,67 @@ fn a_link_on_an_office_2016_charts_drawing_is_kept() { } } +/// A package with one invented waterfall chart (432 x 252 pt) whose `mc:Fallback` is `fallback`. +fn chartex_text_fallback_docx(fallback: &str) -> Vec { + let chart = r#"Steps"#; + let frame = r#""#; + let body = format!( + r#"Before{frame}{fallback}"# + ); + let doc = format!(r#"{body}"#); + let doc_rels = r#""#; + let types = format!( + r#""# + ); + zip(&[ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", ROOT_RELS.as_bytes()), + ("word/document.xml", doc.as_bytes()), + ("word/_rels/document.xml.rels", doc_rels.as_bytes()), + ("word/charts/chartEx1.xml", chart.as_bytes()), + ]) +} + +/// #6820: an Office 2016 chart whose fallback is only text keeps its 432 x 252 pt place (as a +/// placeholder) instead of becoming the fallback words, and is written back unchanged. +#[test] +fn office_2016_chart_with_a_text_fallback_keeps_its_size_through_saves() { + let mut d = craft_docx::read(&chartex_text_fallback_docx("Chart not available.")).unwrap(); + for _ in 0..2 { + let g = graphics(&d); + let [InlineObject::Graphic { w, h, graphic, .. }] = g.as_slice() else { panic!("the chart is an object: {g:?}") }; + assert_eq!((*w, *h), (432.0, 252.0)); + assert_eq!((graphic.w, graphic.h), (432.0, 252.0)); + assert!( + graphic + .items + .iter() + .any(|i| matches!(i, craft_wordmodel::graphic::GraphicItem::Text { text, .. } if text.starts_with("Waterfall chart"))), + "{:?}", + graphic.items + ); + assert!(!paras(&d).iter().any(|p| p.text.contains("not available")), "the fallback words are not body text"); + let files = unzip(&craft_docx::write(&d).unwrap()); + let body = text(&files, "word/document.xml"); + assert_eq!(attr_values(&body, "wp:extent", "cx"), ["5486400"], "the chart's frame; the text fallback has none: {body}"); + assert!(body.contains("Chart not available."), "the fallback is written back as it was: {body}"); + let [cx_id] = attr_values(&body, "cx:chart", "r:id").try_into().unwrap_or_else(|_| panic!("chart lost: {body}")); + let (kind, target) = rel(&text(&files, "word/_rels/document.xml.rels"), &cx_id); + assert!(kind.ends_with("/chartEx"), "{kind}"); + assert!(text(&files, &part_at("word", &target)).contains(r#"layoutId="waterfall""#)); + let entries: Vec<_> = files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice())).collect(); + d = craft_docx::read(&zip(&entries)).unwrap(); + } +} + +/// Guard, not fix proof (it passes before the change too): a fallback that holds a run can't be +/// written back inside the object's own run, so it is not turned into a chart placeholder. +#[test] +fn office_2016_chart_with_a_run_fallback_is_not_made_a_placeholder() { + let d = craft_docx::read(&chartex_text_fallback_docx("Chart not available.")).unwrap(); + assert!(graphics(&d).is_empty(), "{:?}", graphics(&d)); +} + #[test] fn resized_office_2016_chart_resizes_its_fallback_too() { let mut d = craft_docx::read(&chartex_docx("cx1", "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex")).unwrap(); @@ -2824,6 +2885,39 @@ fn rounded_rectangle_corners_are_read_and_saved() { assert_eq!(corners(&craft_docx::read(&bytes).unwrap()), expected); } +/// A `frame` preset (a letterhead's page border) is a frame, not a filled rectangle: its border +/// width is its `adj1`, read, capped and written back as the same preset. +#[test] +fn frame_presets_keep_their_hole_and_border_width() { + let geom = + |av: &str| format!(r#"{av}"#); + let gd = |fmla: &str| format!(r#""#); + let body = [geom(&gd("val 2604")), geom(""), geom(&gd("val 90000")), geom(r#""#)] + .iter() + .map(|sppr| anchored_wsp("Frame", 2540000, 1270000, sppr, "", "")) + .collect::(); + let frames = |d: &Document| -> Vec<(ShapeKind, Option)> { + paras(d)[0] + .objects + .iter() + .filter_map(|o| match o { + InlineObject::Shape { kind, extra, .. } => Some((*kind, extra.corner)), + _ => None, + }) + .collect() + }; + let f = ShapeKind::Frame; + let expected = vec![(f, Some(2604)), (f, None), (f, Some(50_000)), (f, None)]; + let d = read_body(&format!("{body}")); + assert_eq!(frames(&d), expected); + let bytes = craft_docx::write(&d).unwrap(); + let mut xml = String::new(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap(); + std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap(); + assert!(xml.contains(r#""#), "{xml}"); + assert_eq!(frames(&craft_docx::read(&bytes).unwrap()), expected); +} + /// #611: legacy VML lines and rectangles (documents without DrawingML). #[test] fn vml_lines_and_rectangles() { @@ -4967,3 +5061,115 @@ fn extreme_raw_orders_share_one_map_across_parts_without_replaying_chunks() { let malformed = doc.replace("", ""); assert!(craft_docx::read(&zip(&[("_rels/.rels", ROOT_RELS.as_bytes()), ("word/document.xml", malformed.as_bytes())])).is_err()); } + +#[test] +fn retained_drawingml_ole_uses_the_shared_stacking_map() { + let source = r##""##; + let picture = "\u{89}PNG stand-in"; + let ole = "\u{d0}\u{cf} opaque OLE storage"; + let types = r#""#; + for raw in [u32::MAX - 2, u32::MAX] { + let object = source + .replace("", ""); + let shape = anchored_wsp("Other", 127000, 127000, r#""#, "", "") + .replace(r#"relativeHeight="1""#, r#"relativeHeight="4294967294""#); + let body = format!("{object}{shape}"); + let mut d = craft_docx::read(&docx( + &body, + &[("rId8", "image", "media/image1.png"), ("rId9", "oleObject", "embeddings/oleObject1.bin")], + &[("[Content_Types].xml", types), ("word/media/image1.png", picture), ("word/embeddings/oleObject1.bin", ole)], + )) + .unwrap(); + assert!(matches!(paras(&d)[0].objects[0], InlineObject::Image { ole: Some(_), .. })); + let mut made = paras(&d)[0].objects[0].clone(); + made.float_mut().unwrap().z = 0; + let mut p = Paragraph::new(); + p.insert_object(0, made, &Default::default()).unwrap(); + d.body.push(craft_wordmodel::para_block(p)); + for _ in 0..3 { + let out = craft_docx::write(&d).unwrap(); + let files = unzip(&out); + let xml = text(&files, "word/document.xml"); + assert_eq!(attr_values(&xml, "wp:anchor", "odd"), ["retain & this", "retain & this"]); + assert_eq!(attr_values(&xml, "o:OLEObject", "ProgID"), ["Package", "Package"]); + let z: Vec = attr_values(&xml, "wp:anchor", "relativeHeight").iter().map(|v| v.parse().unwrap()).collect(); + assert_eq!(z.len(), 3); + assert!(z[2] > z[0] && z[2] > z[1], "{z:?}"); + assert_eq!(z[0] < z[1], raw < u32::MAX - 1, "{z:?}"); + d = craft_docx::read(&out).unwrap(); + assert!(matches!(paras(&d)[0].objects[0], InlineObject::Image { ole: Some(_), .. })); + } + } + // An inline OLE frame may retain an opaque nested drawing. Its child's rank is not the + // outer object's rank, and the inline frame must not allocate an anchored rank at all. + let nested = source.replace("", r#""#); + let mut d = craft_docx::read(&docx( + &nested, + &[("rId8", "image", "media/image1.png"), ("rId9", "oleObject", "embeddings/oleObject1.bin")], + &[("[Content_Types].xml", types), ("word/media/image1.png", picture), ("word/embeddings/oleObject1.bin", ole)], + )) + .unwrap(); + for _ in 0..3 { + let out = craft_docx::write(&d).unwrap(); + let files = unzip(&out); + let xml = text(&files, "word/document.xml"); + assert_eq!(attr_values(&xml, "wp:anchor", "relativeHeight"), ["17"], "{xml}"); + assert_eq!(attr_values(&xml, "wp:anchor", "odd"), ["nested"]); + assert!(attr_values(&xml, "wp:inline", "relativeHeight").is_empty()); + d = craft_docx::read(&out).unwrap(); + assert!(matches!(paras(&d)[0].objects[0], InlineObject::Image { ole: Some(_), .. })); + } + // A direct VML preview wins in read_object, even when DrawingML is retained beside it. + // Its signed z-index is not a modeled stacking rank. Preserve both representations rather + // than assigning a fresh DrawingML rank from the VML-derived model's unset z. + for signed in [-17, 17] { + let vml = format!( + r#""# + ); + let mixed = + source.replace("", &vml).replace("", ""); + let mut d = craft_docx::read(&docx( + &mixed, + &[("rId8", "image", "media/image1.png"), ("rId9", "oleObject", "embeddings/oleObject1.bin")], + &[("[Content_Types].xml", types), ("word/media/image1.png", picture), ("word/embeddings/oleObject1.bin", ole)], + )) + .unwrap(); + assert_eq!(paras(&d)[0].objects[0].frame().unwrap().2.z, 0); + for _ in 0..3 { + let out = craft_docx::write(&d).unwrap(); + let files = unzip(&out); + let xml = text(&files, "word/document.xml"); + assert_eq!(attr_values(&xml, "wp:anchor", "relativeHeight"), ["21"]); + assert_eq!(attr_values(&xml, "v:shape", "odd"), ["vml"]); + let styles = attr_values(&xml, "v:shape", "style"); + assert_eq!(styles.len(), 1); + assert!(styles[0].split(';').any(|p| p == format!("z-index:{signed}"))); + d = craft_docx::read(&out).unwrap(); + assert_eq!(paras(&d)[0].objects[0].frame().unwrap().2.z, 0); + } + } +} + +#[test] +fn extreme_chart_with_text_fallback_uses_the_package_order_map() { + // Both callers need the package map. MAX alone would still saturate to MAX without it; + // placing MAX-1 on each representation in turn catches a missing map at either caller. + for (chart_raw, shape_raw) in [(u32::MAX, u32::MAX - 1), (u32::MAX - 1, u32::MAX)] { + let mut files = unzip(&chartex_text_fallback_docx("Chart not available.")); + let shape = anchored_wsp("Other", 127000, 127000, r#""#, "", "") + .replace(r#"relativeHeight="1""#, &format!(r#"relativeHeight="{shape_raw}""#)); + let xml = text(&files, "word/document.xml") + .replace("", "") + .replace("", &format!("{shape}")); + files.insert("word/document.xml".to_string(), xml.into_bytes()); + let entries: Vec<_> = files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice())).collect(); + let d = craft_docx::read(&zip(&entries)).unwrap(); + let g = graphics(&d); + let [InlineObject::Graphic { float, .. }] = g.as_slice() else { panic!("chart placeholder missing") }; + assert_eq!(float.z, chart_raw); + let other = paras(&d).iter().flat_map(|p| &p.objects).find(|o| matches!(o, InlineObject::Shape { .. })).unwrap(); + assert_eq!(other.frame().unwrap().2.z, shape_raw); + } +} diff --git a/crates/docx/tests/it/kashida.rs b/crates/docx/tests/it/kashida.rs new file mode 100644 index 000000000..02eaf2a49 --- /dev/null +++ b/crates/docx/tests/it/kashida.rs @@ -0,0 +1,136 @@ +//! Justified paragraphs keep their kashida length (`ST_Jc` `lowKashida`, `mediumKashida`, +//! `highKashida`, and ordinary `both` / `justify`) through read and write. + +use std::io::{Read, Write}; + +use std::sync::Arc; + +use craft_wordmodel::props::{Align, Kashida, ParaProps}; +use craft_wordmodel::styles::{Style, StyleKind, StyleSheet}; +use craft_wordmodel::{Document, Paragraph, para_block}; + +fn zip(entries: &[(&str, &[u8])]) -> Vec { + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in entries { + zw.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(bytes).unwrap(); + } + zw.finish().unwrap().into_inner() +} + +fn docx(body: &str) -> Vec { + let root = r#""#; + let doc = format!( + r#"{body}"# + ); + zip(&[("_rels/.rels", root.as_bytes()), ("word/document.xml", doc.as_bytes())]) +} + +fn paras(d: &Document) -> Vec<&Paragraph> { + d.body.iter().filter_map(|b| b.as_para()).collect() +} + +fn document_xml(bytes: &[u8]) -> String { + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut s = String::new(); + z.by_name("word/document.xml").unwrap().read_to_string(&mut s).unwrap(); + s +} + +fn jc_para(body: &str, val: &str) -> String { + format!(r#"{body}"#) +} + +#[test] +fn kashida_jc_values_are_read() { + let body = [ + jc_para("both", "both"), + jc_para("justify", "justify"), + jc_para("low", "lowKashida"), + jc_para("medium", "mediumKashida"), + jc_para("high", "highKashida"), + jc_para("left", "left"), + ] + .join(""); + let d = craft_docx::read(&docx(&body)).unwrap(); + let ps = paras(&d); + let got: Vec<_> = ps.iter().map(|p| (p.props.align, p.props.kashida)).collect(); + assert_eq!( + got, + vec![ + (Some(Align::Justify), Some(Kashida::None)), + (Some(Align::Justify), Some(Kashida::None)), + (Some(Align::Justify), Some(Kashida::Short)), + (Some(Align::Justify), Some(Kashida::Medium)), + (Some(Align::Justify), Some(Kashida::Long)), + (Some(Align::Left), None), + ] + ); +} + +#[test] +fn kashida_length_round_trips() { + let cases = [ + (Some(Kashida::None), "w:val=\"both\""), + (Some(Kashida::Short), "w:val=\"lowKashida\""), + (Some(Kashida::Medium), "w:val=\"mediumKashida\""), + (Some(Kashida::Long), "w:val=\"highKashida\""), + ]; + for (kashida, token) in cases { + let mut p = Paragraph::with_text("مثال", Default::default()); + p.props = ParaProps { align: Some(Align::Justify), kashida, ..Default::default() }; + let mut d = Document::new(); + d.body = vec![para_block(p.clone())]; + let bytes = craft_docx::write(&d).unwrap(); + let xml = document_xml(&bytes); + assert!(xml.contains(token), "expected {token} in {xml}"); + let r = craft_docx::read(&bytes).unwrap(); + let q = paras(&r)[0]; + assert_eq!(q.props.align, Some(Align::Justify)); + assert_eq!(q.props.kashida, kashida, "round-trip of {token}"); + } +} + +fn body_style(kashida: Kashida) -> StyleSheet { + let mut sheet = StyleSheet::empty(); + sheet.styles.push(Style { + id: "Body".into(), + name: "Body".into(), + kind: StyleKind::Paragraph, + para: ParaProps { align: Some(Align::Justify), kashida: Some(kashida), ..ParaProps::default() }, + ..Style::default() + }); + sheet +} + +#[test] +fn style_kashida_length_survives_a_write_when_the_paragraph_has_no_direct_jc() { + let mut p = Paragraph::with_text("مثال", Default::default()); + p.props = ParaProps { style: Some("Body".into()), ..ParaProps::default() }; + let mut d = Document::new(); + d.styles = Arc::new(body_style(Kashida::Short)); + d.body = vec![para_block(p)]; + assert_eq!(d.styles.resolve_para(&d.body[0].as_para().unwrap().props).kashida, Kashida::Short); + let bytes = craft_docx::write(&d).unwrap(); + let r = craft_docx::read(&bytes).unwrap(); + let q = paras(&r)[0]; + assert_eq!(q.props.kashida, None, "no direct w:jc on the paragraph"); + assert_eq!(r.styles.resolve_para(&q.props).kashida, Kashida::Short); +} + +#[test] +fn writing_justify_without_a_local_kashida_keeps_the_style_length() { + let mut p = Paragraph::with_text("مثال", Default::default()); + p.props = ParaProps { style: Some("Body".into()), align: Some(Align::Justify), kashida: None, ..ParaProps::default() }; + let mut d = Document::new(); + d.styles = Arc::new(body_style(Kashida::Medium)); + d.body = vec![para_block(p)]; + let bytes = craft_docx::write(&d).unwrap(); + let xml = document_xml(&bytes); + assert!(xml.contains("w:val=\"mediumKashida\""), "expected mediumKashida in {xml}"); + let r = craft_docx::read(&bytes).unwrap(); + let q = paras(&r)[0]; + assert_eq!(q.props.align, Some(Align::Justify)); + assert_eq!(q.props.kashida, Some(Kashida::Medium)); + assert_eq!(r.styles.resolve_para(&q.props).kashida, Kashida::Medium); +} diff --git a/crates/docx/tests/it/locked_canvas.rs b/crates/docx/tests/it/locked_canvas.rs new file mode 100644 index 000000000..fb01406a4 --- /dev/null +++ b/crates/docx/tests/it/locked_canvas.rs @@ -0,0 +1,163 @@ +//! A DrawingML locked canvas (`lc:lockedCanvas`, ECMA-376 Part 1 §20.3.2.1), as Word 2007 writes +//! shapes, pictures and WordArt in a drawing in compatibility mode (wordcraft#5060). Fixtures are +//! hand-written from ECMA-376 Part 1 §20.1 (DrawingML main) and §20.3 (locked canvas). + +use std::io::Write; + +use craft_wordmodel::para::ShapeKind; +use craft_wordmodel::props::{Rgb, TextColor}; +use craft_wordmodel::{Document, InlineObject, StoryRef}; + +const NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#; + +fn docx(body: &str) -> Vec { + let doc = format!(r#"{body}"#); + let types = + r#""#; + let root = r#""#; + let rels = r#""#; + let entries: [(&str, &[u8]); 5] = [ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", root.as_bytes()), + ("word/document.xml", doc.as_bytes()), + ("word/_rels/document.xml.rels", rels.as_bytes()), + ("word/media/image1.png", "\u{89}PNG stand-in".as_bytes()), + ]; + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in entries { + zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(bytes).unwrap(); + } + zw.finish().unwrap().into_inner() +} + +/// A floating drawing, 200 × 100 pt, holding `canvas` (the locked canvas's members) in a canvas +/// whose members' space starts at 10 pt, 10 pt. +fn drawing(canvas: &str) -> String { + format!( + r#"00{canvas}"# + ) +} + +const OVAL: &str = r#""#; + +/// WordArt in a nested group: bold, all-caps red text with a green outline and a reflection, +/// 32 pt, centred, bent by a chevron warp; a second paragraph takes the list style's size, and an +/// empty third one its mark's. +const WORD_ART: &str = r#"Youngkeepers"#; + +const PICTURE: &str = r#""#; + +/// A line glued to the oval by the canvas's own id, which isn't a document shape's. +const LINE: &str = r#""#; + +fn group(d: &Document) -> (f32, f32, Vec) { + let p = d.body.iter().find_map(|b| b.as_para()).unwrap(); + match p.objects.first() { + Some(InlineObject::Group { w, h, children, canvas: None, .. }) => (*w, *h, children.clone()), + o => panic!("{o:?}"), + } +} + +/// wordcraft#5060: the locked canvas is a group of its shapes, text, picture and line, each where the +/// canvas (and the group inside it) puts it, and nothing is lost on save. +#[test] +fn a_locked_canvas_reads_as_a_group_of_its_members() { + let d = craft_docx::read(&docx(&drawing(&[OVAL, WORD_ART, PICTURE, LINE].concat()))).unwrap(); + for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] { + let (w, h, children) = group(d); + assert_eq!((w, h), (200.0, 100.0)); + let at: Vec<(f32, f32)> = children.iter().map(|c| (c.x, c.y)).collect(); + assert_eq!(at, [(0.0, 0.0), (110.0, 60.0), (0.0, 50.0), (0.0, 80.0)]); + let [oval, art, picture, line] = &children[..] else { panic!("{children:?}") }; + let InlineObject::Shape { kind: ShapeKind::Ellipse, w: 100.0, h: 50.0, fill: Some(fill), stroke: Some(stroke), .. } = &oval.obj else { + panic!("{:?}", oval.obj) + }; + assert_eq!((fill.main_color(), *stroke), (Rgb(0xFF, 0xFF, 0x66), Rgb(0, 0, 0))); + let InlineObject::Shape { kind: ShapeKind::TextBox, w: 20.0, h: 10.0, story: Some(id), extra, .. } = &art.obj else { + panic!("{:?}", art.obj) + }; + assert_eq!(extra.warp.as_ref().map(|w| w.preset.as_str()), Some("textChevron")); + assert_eq!(d.plain_text(StoryRef::Part(*id)).trim_end(), "Young\nkeepers"); + let blocks = &d.parts.get(id).unwrap().blocks; + let first = blocks[0].as_para().unwrap(); + assert_eq!(first.props.align, Some(craft_wordmodel::props::Align::Center)); + assert_eq!((first.props.space_before, first.props.space_after), (Some(0.0), Some(0.0)), "DrawingML text has no paragraph spacing"); + let run = &first.runs[0].props; + assert_eq!((run.size, run.bold, run.caps, run.color), (Some(32.0), Some(true), Some(true), Some(TextColor::Rgb(Rgb(0xFF, 0, 0))))); + assert_eq!(run.font.as_deref(), Some("Corsiva Stand-in")); + let fx = run.text_effects.as_deref().unwrap(); + let outline = fx.outline.unwrap(); + assert_eq!((outline.color, outline.width), (Some(Rgb(0, 0xFF, 0)), 0.75)); + assert!(fx.reflection.is_some(), "{fx:?}"); + assert_eq!(blocks[1].as_para().unwrap().runs[0].props.size, Some(14.0), "the list style's size"); + assert_eq!(blocks[2].as_para().unwrap().mark.size, Some(10.0), "an empty paragraph's mark"); + let InlineObject::Image { w: 50.0, h: 50.0, alt, .. } = &picture.obj else { panic!("{:?}", picture.obj) }; + assert_eq!(alt, "A logo"); + let InlineObject::Shape { kind: ShapeKind::Line, stroke: Some(blue), extra, .. } = &line.obj else { panic!("{:?}", line.obj) }; + assert_eq!((*blue, extra.start), (Rgb(0, 0, 0xFF), None), "no glue to a canvas id"); + } +} + +/// A text shape as a member of the canvas (`a:txSp`, text with no shape of its own) is a text box +/// at its own rectangle. Runs take their paragraph's own defaults (`a:pPr/a:defRPr`) before the +/// list style's for the paragraph's level. +#[test] +fn a_locked_canvas_text_shape_and_paragraph_defaults() { + let text = r#"OwnLevelFirst"#; + let d = craft_docx::read(&docx(&drawing(text))).unwrap(); + for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] { + let (_, _, children) = group(d); + let [shape] = &children[..] else { panic!("{children:?}") }; + assert_eq!((shape.x, shape.y), (40.0, 20.0)); + let InlineObject::Shape { kind: ShapeKind::TextBox, w: 100.0, h: 40.0, fill: None, stroke: None, story: Some(id), .. } = &shape.obj else { + panic!("{:?}", shape.obj) + }; + assert_eq!(d.plain_text(StoryRef::Part(*id)).trim_end(), "Own\nLevel\nFirst"); + let blocks = &d.parts.get(id).unwrap().blocks; + let run = |i: usize| blocks[i].as_para().unwrap().runs[0].props.clone(); + assert_eq!((run(0).size, run(0).italic), (Some(32.0), Some(true)), "the paragraph's own size, the level's italic"); + assert_eq!((run(1).size, run(1).italic), (Some(20.0), None), "level 2's"); + assert_eq!((run(2).size, run(2).italic), (Some(14.0), Some(true)), "level 1's"); + } +} + +/// A paragraph's alignment and its runs' properties fall back on its level's style, then on the +/// list style's defaults (`a:defPPr`); a run's bold set off stays off. +#[test] +fn a_locked_canvas_paragraph_takes_its_level_and_the_list_defaults() { + use craft_wordmodel::props::Align; + let text = r#"PlainCentredOwn"#; + let d = craft_docx::read(&docx(&drawing(text))).unwrap(); + for d in [&d, &craft_docx::read(&craft_docx::write(&d).unwrap()).unwrap()] { + let (_, _, children) = group(d); + let [shape] = &children[..] else { panic!("{children:?}") }; + let InlineObject::Shape { story: Some(id), .. } = &shape.obj else { panic!("{:?}", shape.obj) }; + let blocks = &d.parts.get(id).unwrap().blocks; + let para = |i: usize| blocks[i].as_para().unwrap(); + let aligns: Vec> = (0..3).map(|i| para(i).props.align).collect(); + assert_eq!(aligns, [Some(Align::Right), Some(Align::Center), Some(Align::Left)], "the list defaults', the level's, its own"); + let runs: Vec<(Option, Option)> = (0..3).map(|i| (para(i).runs[0].props.size, para(i).runs[0].props.bold)).collect(); + assert_eq!(runs, [(Some(16.0), Some(false)), (Some(16.0), Some(true)), (Some(16.0), Some(true))]); + } +} + +/// Before wordcraft#5060 only the canvas's first picture showed: the shapes and their text were dropped. +#[test] +fn a_locked_canvas_is_not_read_as_its_picture_alone() { + let d = craft_docx::read(&docx(&drawing(&[OVAL, PICTURE].concat()))).unwrap(); + let (_, _, children) = group(&d); + assert_eq!(children.len(), 2); +} + +/// Hostile canvases never panic: no members, groups nested past the limit, text with no runs, +/// huge and broken sizes. +#[test] +fn hostile_locked_canvases_never_panic() { + let deep = format!("{}{}{}", r#""#.repeat(40), OVAL, "".repeat(40)); + let odd = r#"f"#; + for canvas in ["", deep.as_str(), odd] { + let d = craft_docx::read(&docx(&drawing(canvas))).unwrap(); + let _ = craft_docx::write(&d).unwrap(); + } +} diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index d1def3f8c..6d521effb 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -20,13 +20,16 @@ mod emphasis_marks; mod fixtures; mod glossary; mod heading_levels; +mod kashida; mod legacy_forms; mod ligatures; mod line_numbering; +mod locked_canvas; mod malformed; mod missing_pictures; mod nested_block_controls; mod note_comments; +mod partial_table_margins; mod passthrough; mod picture_links; mod positional_tabs; diff --git a/crates/docx/tests/it/partial_table_margins.rs b/crates/docx/tests/it/partial_table_margins.rs new file mode 100644 index 000000000..7cf3c5f49 --- /dev/null +++ b/crates/docx/tests/it/partial_table_margins.rs @@ -0,0 +1,36 @@ +//! a table's partial cell margins keep the other sides. + +use std::io::Write; + +#[test] +fn a_left_only_table_margin_keeps_the_other_sides() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let root = r#""#; + let rels = r#""#; + let styles = format!( + r#""# + ); + let table = |style: &str| { + format!( + r#"{style}Cell"# + ) + }; + let document = format!(r#"{}{}"#, table(r#""#), table("")); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, data) in [ + ("_rels/.rels", root), + ("word/_rels/document.xml.rels", rels), + ("word/document.xml", document.as_str()), + ("word/styles.xml", styles.as_str()), + ] { + zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(data.as_bytes()).unwrap(); + } + let doc = craft_docx::read(&zip.finish().unwrap().into_inner()).unwrap(); + let margins: Vec<_> = doc.body.iter().filter_map(|b| b.as_table()).map(|t| t.props.cell_margins).collect(); + assert_eq!( + margins, + vec![Some([1.0, 5.35, 2.0, 8.0]), Some([0.0, 5.35, 0.0, 0.0])], + "the left side is the table's, the rest the style's (none without one: the file has no default table style)" + ); +} diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 9cf4f27e4..29a7ffac9 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -6,8 +6,8 @@ use std::sync::Arc; use craft_wordmodel::numbering::ListKind; use craft_wordmodel::para::{Anchor, Float, FloatAlign, NoteKind, ShapeKind, Wrap}; use craft_wordmodel::props::{ - Align, Border, BorderStyle, Borders, CharProps, HeightRule, Highlight, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, Rgb, RowProps, - TabAlign, TabLeader, TabStop, TableLook, TextAlignment, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign, + Align, Border, BorderStyle, Borders, CharProps, HeightRule, Highlight, Kashida, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, Rgb, + RowProps, TabAlign, TabLeader, TabStop, TableLook, TextAlignment, TextColor, TextDirection, Underline, VAlign, VMerge, VertAlign, }; use craft_wordmodel::section::{Columns, DocGrid, DocGridType, LineNumberRestart, LineNumbering, NumFormat, PageVAlign, SectionProps, SectionStart}; use craft_wordmodel::styles::{Style, StyleKind}; @@ -159,6 +159,7 @@ fn every_para_prop_round_trips() { let pp = ParaProps { style: Some("Heading1".into()), align: Some(Align::Justify), + kashida: Some(Kashida::Medium), indent_left: Some(36.0), indent_right: Some(18.0), indent_first: Some(-18.0), @@ -2923,3 +2924,100 @@ fn drop_cap_options_round_trip() { (Some(4), Some(true), None, None) ); } + +/// `word/settings.xml` of a saved package. +fn settings_part(bytes: &[u8]) -> String { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut xml = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("word/settings.xml").unwrap(), &mut xml).unwrap(); + xml +} + +/// Page Setup's "Gutter position: Top" (`w:gutterAtTop`) is a document setting: off by default +/// (no element), written when on after `w:mirrorMargins` and before `w:attachedTemplate`, and +/// read back; the section's own gutter width is untouched. +#[test] +fn gutter_at_top_round_trips_and_is_off_by_default() { + let plain = craft_docx::write(&Document::new()).unwrap(); + assert!(!settings_part(&plain).contains("gutterAtTop")); + assert!(!craft_docx::read(&plain).unwrap().settings.gutter_at_top); + + let mut d = Document::new(); + d.settings.gutter_at_top = true; + d.settings.mirror_margins = true; + d.settings.attached_template = Some("file:///C:/Templates/Report.dotx".into()); + d.last_section.gutter = 50.0; + let bytes = craft_docx::write(&d).unwrap(); + let xml = settings_part(&bytes); + assert_eq!(xml.matches("").count(), 1, "{xml}"); + let at = |tag: &str| xml.find(tag).unwrap_or_else(|| panic!("{tag} missing: {xml}")); + assert!(at(""#; + assert!(xml.contains(zoom), "{xml}"); + for (element, expected) in [ + ("", false), + ("", true), + (r#""#, true), + (r#""#, true), + (r#""#, true), + (r#""#, false), + (r#""#, false), + (r#""#, false), + (r#""#, false), + (r#""#, false), + ] { + let file = replace_part(&plain, "word/settings.xml", xml.replace(zoom, &format!("{zoom}{element}")).as_bytes()); + assert_eq!(craft_docx::read(&file).unwrap().settings.gutter_at_top, expected, "{element:?}"); + } +} + +/// A settings part from another writer (proofing state, rsids, document variables…) is merged on +/// save, not regenerated: `w:gutterAtTop` stays once where it was, goes when the setting is turned +/// off, and is added at its schema position (after `w:mirrorMargins`, before `w:proofState`) when +/// the file had none. +#[test] +fn gutter_at_top_is_merged_into_a_foreign_settings_part() { + let plain = craft_docx::write(&Document::new()).unwrap(); + let xml = settings_part(&plain); + let zoom = r#""#; + let foreign = |element: &str| { + let extra = + format!(r#"{zoom}{element}"#); + replace_part(&plain, "word/settings.xml", xml.replace(zoom, &extra).as_bytes()) + }; + + let with = craft_docx::read(&foreign("")).unwrap(); + assert!(with.settings.gutter_at_top && with.settings.mirror_margins); + let saved = settings_part(&craft_docx::write(&with).unwrap()); + assert_eq!(saved.matches("").count(), 1, "{saved}"); + assert!(saved.contains("").count(), 1, "{saved}"); + let at = |tag: &str| saved.find(tag).unwrap_or_else(|| panic!("{tag} missing: {saved}")); + assert!(at(" + + + + + +"#; + + fn theme_round_trip(t: &Theme) -> (String, Theme) { + let xml = String::from_utf8(crate::theme::theme_xml(&mut Part::new(), t)).unwrap(); + let back = crate::theme::read_theme(&mut Part::new(), &parse(xml.as_bytes()).unwrap()); + (xml, back) + } + + #[test] + fn a_theme_keeps_system_colours_custom_colours_family_id_and_font_panose() { + let t = crate::theme::read_theme(&mut Part::new(), &parse(THEME_FILE.as_bytes()).unwrap()); + assert_eq!(t.sys_colors.len(), 2); + let (xml, back) = theme_round_trip(&t); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains("Brand red") && xml.contains("C00000") && xml.contains("Brand teal") && xml.contains("008080"), "{xml}"); + assert!( + xml.contains("thm15:themeFamily") + && xml.contains("{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}") + && xml.contains("{4A3C46E8-61CC-4603-A589-7422A47A8E4A}"), + "{xml}" + ); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + assert_eq!( + (&back.sys_colors, &back.colors.colors, &back.fonts, &back.raw_extra), + (&t.sys_colors, &t.colors.colors, &t.fonts, &t.raw_extra), + "read, write, read changes nothing" + ); + // Order: the colour list comes before the extension list, both after the theme elements. + let at = |n: &str| xml.find(n).unwrap_or_else(|| panic!("{n} in {xml}")); + assert!(at("") < at("") && at("") < at(""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + let (plain, back) = theme_round_trip(&Theme::default()); + assert!(!plain.contains("sysClr") && !plain.contains("custClrLst") && !plain.contains("themeFamily") && !plain.contains("panose"), "{plain}"); + assert!(back.sys_colors.is_empty() && back.fonts.minor.latin_attrs.is_empty()); + } + + #[test] + fn font_panose_is_dropped_when_the_typeface_changes() { + let mut t = crate::theme::read_theme(&mut Part::new(), &parse(THEME_FILE.as_bytes()).unwrap()); + t.fonts.minor.latin = "Arial".into(); + let (xml, _) = theme_round_trip(&t); + assert!(xml.contains(r#""#), "{xml}"); + assert!(!xml.contains("020F0502020204030204"), "{xml}"); + assert!(xml.contains(r#""#, r#""#) + .replace(r#""#, r#""#); + let t = crate::theme::read_theme(&mut Part::new(), &parse(file.as_bytes()).unwrap()); + let (xml, _) = theme_round_trip(&t); + assert!(xml.contains(r#""#), "{xml}"); + assert!(xml.contains(r#""#), "{xml}"); + } + + #[test] + fn custom_colours_and_family_id_without_object_defaults_follow_an_empty_one() { + let file = THEME_FILE.replace("", ""); + let t = crate::theme::read_theme(&mut Part::new(), &parse(file.as_bytes()).unwrap()); + let (xml, back) = theme_round_trip(&t); + let at = |n: &str| xml.find(n).unwrap_or_else(|| panic!("{n} in {xml}")); + assert!(at("") < at(""), "{xml}"); + assert!(at("") < at(""#; + let ls = crate::read::list_style(&mut Part::new(), &parse(src.as_bytes()).unwrap()); + let d = ls.default_level.as_ref().expect("defPPr read"); + assert_eq!( + (d.para.margin_left, d.para.align, d.run.lang.as_deref(), d.run.size), + (Some(36.0), Some(crate::text::Align::Center), Some("de-DE"), Some(18.0)) + ); + assert_eq!(ls.level(0).and_then(|l| l.run.size), Some(44.0)); + for tag in ["p:defaultTextStyle", "p:titleStyle", "p:bodyStyle", "p:otherStyle", "p:notesStyle", "a:lstStyle"] { + let mut w = craft_xml::Writer::new(); + crate::write::list_style(&mut w, &mut Part::new(), tag, &ls); + let xml = format!(r#"{}"#, w.finish()); + assert!(xml.find("{}"#, w.finish()); + let back = crate::read::text_body(&mut Part::new(), parse(xml.as_bytes()).unwrap().child(craft_xml::Local("txBody")).unwrap()); + assert_eq!(back.list_style, ls); + let empty = ListStyle { default_level: Some(Box::default()), ..Default::default() }; + assert!(!empty.is_empty()); + let mut w = craft_xml::Writer::new(); + crate::write::list_style(&mut w, &mut Part::new(), "p:defaultTextStyle", &empty); + assert_eq!(w.finish(), ""); + // Without `a:defPPr` none is written. + let mut w = craft_xml::Writer::new(); + crate::write::list_style(&mut w, &mut Part::new(), "p:defaultTextStyle", &ListStyle { default_level: None, ..ls }); + assert!(!w.finish().contains("defPPr")); + } } diff --git a/crates/drawingml/src/read.rs b/crates/drawingml/src/read.rs index 9e9f8ff3e..f26bf2073 100644 --- a/crates/drawingml/src/read.rs +++ b/crates/drawingml/src/read.rs @@ -623,6 +623,11 @@ pub fn list_style(src: &mut dyn Source, ls: &El) -> ListStyle { let mut out = ListStyle::default(); for e in ls.elements() { let n = e.local(); + if n == "defPPr" { + let (_, para, run) = ppr(src, e); + out.default_level = Some(Box::new(LevelStyle { para, run: run.unwrap_or_default() })); + continue; + } let Some(l) = n.strip_prefix("lvl").and_then(|r| r.strip_suffix("pPr")).and_then(|d| d.parse::().ok()) else { continue }; if !(1..=9).contains(&l) { continue; diff --git a/crates/drawingml/src/text.rs b/crates/drawingml/src/text.rs index f60f23236..dc34cf10f 100644 --- a/crates/drawingml/src/text.rs +++ b/crates/drawingml/src/text.rs @@ -706,6 +706,12 @@ pub struct LevelStyle { pub struct ListStyle { /// Levels 1–9 (index 0–8); `None` = not specified. pub levels: Vec>, + /// The default paragraph style (`a:defPPr`) that sits under levels 1–9; `None` = the list + /// style has no `a:defPPr`. Boxed: it sits inline in every `ListStyle`, hence in every text + /// body and shape, and the recursive group readers (pptx) would otherwise overflow the stack + /// of a debug build on Windows (1 MiB main thread) at the nesting depth the tests cut at. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_level: Option>, } impl ListStyle { @@ -722,7 +728,7 @@ impl ListStyle { } } pub fn is_empty(&self) -> bool { - self.levels.iter().all(Option::is_none) + self.default_level.is_none() && self.levels.iter().all(Option::is_none) } } @@ -759,6 +765,14 @@ mod tests { use super::*; use crate::color::Rgba; + /// `ListStyle` sits inline in every `TextBody`/`Shape`, which the pptx group reader holds on the + /// stack once per nesting level. Keep it at `Vec` (24) + `Option` (8) bytes (the `defPPr` + /// level is boxed) so a debug build does not overflow the 1 MiB Windows main-thread stack. + #[test] + fn list_style_stays_small() { + assert!(std::mem::size_of::() <= 32, "{}", std::mem::size_of::()); + } + #[test] fn alternate_language_inherits_and_native_input_is_bounded() { let mut child = RunProps::default(); diff --git a/crates/drawingml/src/theme.rs b/crates/drawingml/src/theme.rs index 69d7c2af6..bfe435be9 100644 --- a/crates/drawingml/src/theme.rs +++ b/crates/drawingml/src/theme.rs @@ -11,11 +11,37 @@ pub struct FontSet { pub latin: String, pub ea: String, pub cs: String, + /// The `panose`, `pitchFamily` and `charset` the file gives the Latin, East Asian and complex + /// script typefaces; `None` = the attribute is absent. + #[serde(skip_serializing_if = "TypefaceAttrs::is_empty")] + pub latin_attrs: TypefaceAttrs, + #[serde(skip_serializing_if = "TypefaceAttrs::is_empty")] + pub ea_attrs: TypefaceAttrs, + #[serde(skip_serializing_if = "TypefaceAttrs::is_empty")] + pub cs_attrs: TypefaceAttrs, /// Per-script typefaces (`a:font script="Arab" typeface="…"`), in document order. #[serde(skip_serializing_if = "Vec::is_empty")] pub scripts: Vec, } +/// The font-matching attributes of a theme typeface (`a:latin`, `a:ea`, `a:cs`). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct TypefaceAttrs { + /// The typeface name these attributes belong to; the writer drops them once the typeface changed. + pub typeface: String, + /// Ten hex byte pairs, as written. + pub panose: Option, + pub pitch_family: Option, + pub charset: Option, +} + +impl TypefaceAttrs { + pub fn is_empty(&self) -> bool { + self.panose.is_none() && self.pitch_family.is_none() && self.charset.is_none() + } +} + /// A theme font for one script (ISO 15924 tag, e.g. `Arab`). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -53,6 +79,17 @@ pub struct FormatScheme { pub bg_fills: Vec, } +/// A colour slot written as a system colour (``). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SysColor { + pub slot: SchemeSlot, + /// The `val` (`windowText`, `window`…). + pub name: String, + /// The `lastClr`. + pub last: Rgba, +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Theme { @@ -60,7 +97,14 @@ pub struct Theme { pub colors: ColorScheme, pub fonts: FontScheme, pub format: FormatScheme, - /// Raw theme XML extras kept for round-trip (object defaults, extra colour lists). + /// The colour slots the file wrote as `a:sysClr` (`dk1` `windowText`, `lt1` `window`), in + /// document order. The writer keeps a slot as `a:sysClr` while its colour still equals + /// `last`; a slot whose colour was changed is written as `a:srgbClr`. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub sys_colors: Vec, + /// Raw theme XML extras kept for round-trip, in document order: object defaults, extra + /// colour lists, custom colours (`a:custClrLst`) and the extension list (`a:extLst`, which + /// holds the theme family id). #[serde(skip_serializing_if = "Option::is_none")] pub raw_extra: Option, } @@ -76,6 +120,7 @@ impl Default for Theme { colors: ColorScheme::new("Default", colors.map(hex)), fonts: FontScheme::default(), format: default_format(), + sys_colors: Vec::new(), raw_extra: None, } } diff --git a/crates/drawingml/src/theme/read.rs b/crates/drawingml/src/theme/read.rs index 29e49dc93..0f4e4b2f0 100644 --- a/crates/drawingml/src/theme/read.rs +++ b/crates/drawingml/src/theme/read.rs @@ -2,7 +2,7 @@ use crate::color::{ColorScheme, Rgba, SchemeSlot}; use crate::style::{ColorBase, Effects}; -use crate::theme::{FontScheme, FontSet, FormatScheme, ScriptFont, Theme, default_format}; +use crate::theme::{FontScheme, FontSet, FormatScheme, ScriptFont, SysColor, Theme, TypefaceAttrs, default_format}; use craft_xml::{El, Local}; @@ -21,7 +21,12 @@ fn font_set(e: Option<&El>) -> FontSet { .collect() }) .unwrap_or_default(); - FontSet { latin: tf("latin"), ea: tf("ea"), cs: tf("cs"), scripts } + let attrs = |n: &str| { + let c = e.and_then(|e| e.child(Local(n))); + let at = |a: &str| c.and_then(|c| c.attr_local(a)).map(String::from); + TypefaceAttrs { typeface: at("typeface").unwrap_or_default(), panose: at("panose"), pitch_family: at("pitchFamily"), charset: at("charset") } + }; + FontSet { latin: tf("latin"), ea: tf("ea"), cs: tf("cs"), latin_attrs: attrs("latin"), ea_attrs: attrs("ea"), cs_attrs: attrs("cs"), scripts } } pub fn read_theme(src: &mut dyn Source, root: &El) -> Theme { @@ -33,7 +38,10 @@ pub fn read_theme(src: &mut dyn Source, root: &El) -> Theme { if let Some(c) = cs.child(Local(slot.xml_name())).and_then(dml::color) { let rgb = match c.base { ColorBase::Rgb { rgb } => rgb, - ColorBase::System { last, .. } => last, + ColorBase::System { name, last } => { + t.sys_colors.push(SysColor { slot, name, last }); + last + } ColorBase::Preset { name } => crate::color::preset(&name).unwrap_or(Rgba::BLACK), ColorBase::Scheme { .. } => continue, }; @@ -90,7 +98,7 @@ pub fn read_theme(src: &mut dyn Source, root: &El) -> Theme { } let extra: String = root .elements() - .filter(|e| e.is(Local("objectDefaults")) || e.is(Local("extraClrSchemeLst"))) + .filter(|e| ["objectDefaults", "extraClrSchemeLst", "custClrLst", "extLst"].iter().any(|n| e.is(Local(n)))) .filter(|e| !crate::xmlx::has_rel_refs(e)) .map(|e| src.keep(e)) .collect(); diff --git a/crates/drawingml/src/theme/write.rs b/crates/drawingml/src/theme/write.rs index 5e95e57eb..bc46d59e3 100644 --- a/crates/drawingml/src/theme/write.rs +++ b/crates/drawingml/src/theme/write.rs @@ -2,7 +2,7 @@ use crate::color::{ColorScheme, Rgba, SchemeSlot}; use crate::style::{ColorRef, Effects, Fill}; -use crate::theme::{FontSet, Theme, default_format}; +use crate::theme::{FontSet, Theme, TypefaceAttrs, default_format}; use craft_xml::Writer; @@ -12,9 +12,20 @@ use crate::write as dml; fn font_set(w: &mut Writer, tag: &str, f: &FontSet) { w.open(tag, &[]); - w.tag("a:latin").attr("typeface", if f.latin.is_empty() { "Arial" } else { &f.latin }).empty(); - w.tag("a:ea").attr("typeface", &f.ea).empty(); - w.tag("a:cs").attr("typeface", &f.cs).empty(); + let face = |w: &mut Writer, tag: &str, name: &str, a: &TypefaceAttrs| { + // Panose and the like describe one font: a changed typeface does not keep them. + let none = TypefaceAttrs::default(); + let a = if a.typeface == name { a } else { &none }; + w.tag(tag) + .attr("typeface", name) + .attr_opt("panose", a.panose.as_deref()) + .attr_opt("pitchFamily", a.pitch_family.as_deref()) + .attr_opt("charset", a.charset.as_deref()) + .empty(); + }; + face(w, "a:latin", if f.latin.is_empty() { "Arial" } else { &f.latin }, &f.latin_attrs); + face(w, "a:ea", &f.ea, &f.ea_attrs); + face(w, "a:cs", &f.cs, &f.cs_attrs); for sf in &f.scripts { w.tag("a:font").attr("script", &sf.script).attr("typeface", &sf.typeface).empty(); } @@ -74,7 +85,11 @@ pub fn theme_xml(out: &mut dyn Sink, t: &Theme) -> Vec { for slot in SchemeSlot::THEME { let tag = format!("a:{}", slot.xml_name()); w.open(&tag, &[]); - w.tag("a:srgbClr").attr("val", t.colors.get(slot).hex()).empty(); + let rgb = t.colors.get(slot); + match t.sys_colors.iter().find(|s| s.slot == slot && s.last == rgb && crate::color::is_system_name(&s.name)) { + Some(s) => w.tag("a:sysClr").attr("val", &s.name).attr("lastClr", rgb.hex()).empty(), + None => w.tag("a:srgbClr").attr("val", rgb.hex()).empty(), + } w.close(); } extra_colors(&mut w, &t.colors); diff --git a/crates/drawingml/src/write.rs b/crates/drawingml/src/write.rs index 25bfb89db..da3f10d79 100644 --- a/crates/drawingml/src/write.rs +++ b/crates/drawingml/src/write.rs @@ -777,6 +777,10 @@ pub fn list_style(w: &mut Writer, out: &mut dyn Sink, tag: &str, ls: &ListStyle) return; } w.open(tag, &[]); + if let Some(l) = &ls.default_level { + let def = (l.run != RunProps::default()).then_some(&l.run); + ppr(w, out, "a:defPPr", None, &l.para, def); + } for (i, l) in ls.levels.iter().enumerate().take(9) { if let Some(l) = l { let t = format!("a:lvl{}pPr", i + 1); diff --git a/crates/drawingml/src/xmlx.rs b/crates/drawingml/src/xmlx.rs index d31616b39..27fa58dc7 100644 --- a/crates/drawingml/src/xmlx.rs +++ b/crates/drawingml/src/xmlx.rs @@ -156,7 +156,20 @@ fn used_prefixes(el: &El) -> HashSet<&str> { used } -/// Serialize `el`, declaring every prefix it uses that the source root declared. +/// Does `el` or a descendant have an unprefixed name that no `xmlns` inside `el` binds? Such a +/// name is in the default namespace of the part it was read from. Attributes never are. +fn uses_outer_default(el: &El) -> bool { + fn rec(e: &El, depth: usize) -> bool { + if depth > MAX_DEPTH || e.attrs.iter().any(|(k, _)| k == "xmlns") { + return false; + } + !e.name.contains(':') || e.elements().any(|c| rec(c, depth + 1)) + } + rec(el, 0) +} + +/// Serialize `el`, declaring every prefix it uses that the source root declared, and the +/// root's default namespace when an unprefixed name in `el` depends on it. pub fn keep_xml(el: &El, ns: &[(String, String)]) -> String { keep_with(el, &[ns], None) } @@ -166,11 +179,15 @@ pub fn keep_xml(el: &El, ns: &[(String, String)]) -> String { /// [`MAX_COPIED_NS_BYTES`]). pub fn keep_with(el: &El, decls: &[&[(String, String)]], budget: Option<&Cell>) -> String { let used = used_prefixes(el); + let default = uses_outer_default(el); let mut have: HashSet<&str> = el.attrs.iter().map(|(a, _)| a.as_str()).collect(); let mut extra = Vec::new(); for (k, v) in decls.iter().flat_map(|d| d.iter()) { - let p = k.strip_prefix("xmlns:").unwrap_or(""); - if !p.is_empty() && used.contains(p) && v.len() <= MAX_NS_VALUE && !have.contains(k.as_str()) { + let wanted = match k.strip_prefix("xmlns:") { + Some(p) => !p.is_empty() && used.contains(p), + None => k == "xmlns" && default, + }; + if wanted && v.len() <= MAX_NS_VALUE && !have.contains(k.as_str()) { let cost = k.len() + v.len(); if let Some(b) = budget { if b.get() < cost { @@ -324,6 +341,33 @@ mod tests { assert!(!has_rel_refs(root.child(Local("z")).unwrap())); } + /// A part written with a default namespace (``): an unprefixed + /// fragment, or one with an unprefixed descendant, carries that namespace; a prefixed one + /// and one that declares its own default are written as before. + #[test] + fn a_kept_fragment_carries_the_default_namespace_its_names_depend_on() { + let root = parse( + br#""#, + ) + .unwrap(); + let ns = ns_decls(&root); + let kid = |n: &str| root.child(Local(n)).unwrap(); + assert_eq!(keep_xml(kid("custClrLst"), &ns), r#""#); + assert_eq!(keep_xml(kid("y"), &ns), r#""#, "prefixed: as before"); + assert_eq!(keep_xml(kid("z"), &ns), r#""#, "an unprefixed descendant"); + assert_eq!(keep_xml(kid("own"), &ns), r#""#, "its own default wins"); + assert_eq!(keep_xml(kid("u"), &ns), r#""#, "an undeclared default stays"); + // A part with no default namespace: unprefixed names stay in no namespace. + let plain = parse(br#""#).unwrap(); + assert_eq!(keep_xml(plain.child(Local("x")).unwrap(), &ns_decls(&plain)), ""); + // The default declaration spends the budget like the others. + let budget = Cell::new(3); + assert_eq!( + keep_with(kid("custClrLst"), &[&ns], Some(&budget)), + r#""# + ); + } + #[test] fn inner_declarations_are_found_and_clashing_ones_dropped() { let root = parse(br#""#).unwrap(); diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index c77fdbf4c..88e1e2a4a 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -720,6 +720,35 @@ mod native { } } + /// A FIELD's format string between the two places acadrust 0.6.6 keeps it. Its DXF reader + /// puts a pre-2007 field's format (group 4) only in `Field::format`, and its DWG writer + /// writes that one only for versions before 2007; from 2007 it writes `value.format`. A field + /// read from an older drawing and written as DWG 2007 or later would lose its format + /// (`dd/MM/yyyy`, `%lu2`). The child values hold no format of their own in the old DXF. + /// + /// `legacy`: the group 4 formats of a DXF that was read as a newer version than it declares + /// ([`legacy_field_formats`]), which the reader then skipped. They go back into an empty + /// `Field::format` first, as the reader puts them there under the DXF's own version, so a + /// DWG before 2007 keeps them too. + fn field_formats(doc: &mut acadrust::CadDocument, legacy: &[(acadrust::Handle, String)]) { + for (handle, format) in legacy { + if let Some(acadrust::objects::ObjectType::Field(f)) = doc.objects.get_mut(handle) + && f.format.is_empty() + { + f.format.clone_from(format); + } + } + if doc.version < acadrust::DxfVersion::AC1021 { + return; + } + for o in doc.objects.values_mut() { + let acadrust::objects::ObjectType::Field(f) = o else { continue }; + if f.value.format.is_empty() && !f.format.is_empty() { + f.value.format = f.format.clone(); + } + } + } + /// The DWG dimension flags byte. Its bit 1 is DXF group 70's bit 32 (ODA DWG specification, /// common dimension data), which acadrust keeps no copy of from DXF: it is set here as /// CADCraft's DXF writer always sets it (#1094). Bit 0, the opposite of group 70's bit 128, @@ -928,8 +957,9 @@ mod native { /// read from a file of version `kept` ("AC1032"), and acadrust reads several of those /// differently by version: read as R2000, an AC1032 file's mental ray render settings came out /// a class version too high, for which the ODA rejects the whole DWG, and a field lost its - /// cached value. So the DXF is read as `kept` declares. A `kept` version that is unknown, or - /// not newer than the DXF's own, changes nothing. + /// cached value. So the DXF is read as `kept` declares; the formats of the DXF's own pre-2007 + /// fields, which the reader skips then, are restored ([`legacy_field_formats`]). A `kept` + /// version that is unknown, or not newer than the DXF's own, changes nothing. pub fn dxf_to_dwg_kept_as(dxf: &[u8], version: &str, kept: &str) -> Result, String> { dxf_to_dwg_kept_noted(dxf, version, kept).map(|(dwg, _)| dwg) } @@ -995,6 +1025,35 @@ mod native { Some(out) } + /// The format (group 4) of each FIELD record in an ASCII DXF, by handle. acadrust 0.6.6 reads + /// it only from a DXF that declares a version before 2007 (AC1021), where it follows the + /// field code or the object handles, before group 91 (`read_field_object_dxf`). When + /// [`declare_version`] made an older DXF read as 2007 or later, a field the DXF wrote itself + /// would lose its format; a field carried over from a 2007+ file has none and keeps its own + /// `value.format`. + fn legacy_field_formats(dxf: &[u8]) -> Vec<(acadrust::Handle, String)> { + let Some(pairs) = super::proxy_transport::text_pairs(dxf) else { return Vec::new() }; + let mut formats = Vec::new(); + let (mut in_field, mut handle, mut format, mut past) = (false, None, None, false); + for pair in pairs { + let Some((code, value)) = pair else { break }; + match code { + 0 => { + if let (Some(h), Some(f)) = (handle.take(), format.take()) { + formats.push((h, f)); + } + in_field = value == "FIELD" || value == "ACDBFIELD"; + (handle, format, past) = (None, None, false); + } + 5 if in_field && handle.is_none() => handle = u64::from_str_radix(value.trim(), 16).ok().map(acadrust::Handle::new), + 4 if in_field && !past && format.is_none() => format = Some(value), + 91 if in_field => past = true, + _ => {} + } + } + formats + } + /// The byte offset and the trimmed value of header variable `name` in an ASCII DXF: the value /// of the group that follows the `9` group naming it. The file is read as (group code, /// value) line pairs, in one pass with no buffering, up to the first `0`/`ENDSEC`, the end @@ -1223,19 +1282,23 @@ mod native { )); } // Decoding a code page to UTF-8 can grow the text, so the limit applies again. - let data = match kept.and_then(|k| declare_version(dxf, k)) { - Some(d) if d.len() > Limits::DEFAULT.max_dxf_bytes => { + let (data, legacy) = match kept.and_then(|k| declare_version(dxf, k).map(|d| (k, d))) { + Some((_, d)) if d.len() > Limits::DEFAULT.max_dxf_bytes => { return Err(format!( "DXF: the input is {} as UTF-8, larger than the {} accepted for DWG conversion", mb(d.len() as u64), mb(Limits::DEFAULT.max_dxf_bytes as u64) )); } - Some(d) => d, - None => dxf.to_vec(), + // Read as 2007 or later, the DXF's own fields lose their formats: restored after. + Some((k, d)) => (d, k >= acadrust::DxfVersion::AC1021), + None => (dxf.to_vec(), false), }; - let (classes, source) = guarded(AssertUnwindSafe(|| (dxf_class_names(&data), super::proxy_transport::source_classes(&data)))) - .map_err(|_| "the DXF proxy class conversion failed".to_string())?; + let (classes, source, legacy) = guarded(AssertUnwindSafe(|| { + let legacy = if legacy { legacy_field_formats(&data) } else { Vec::new() }; + (dxf_class_names(&data), super::proxy_transport::source_classes(&data), legacy) + })) + .map_err(|_| "the DXF proxy class conversion failed".to_string())?; let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(acadrust::DxfReader::read)) .map_err(|_| "the DXF→DWG conversion failed".to_string())? .map_err(|e| format!("DXF: {e}"))?; @@ -1263,6 +1326,7 @@ mod native { }; other_layout_owners(&mut doc); table_style_rows(&mut doc, true); + field_formats(&mut doc, &legacy); dimension_flags(&mut doc); let mut unwritten = drop_unwritable(&mut doc); for (kind, n) in proxies { @@ -2134,4 +2198,127 @@ mod tests { assert_eq!(frames, [vec![0xDE, 0xAD, 0xBE, 0xEF]], "{version}"); } } + + /// A FIELD read from a pre-2007 DXF keeps its format (group 4) only in `Field::format`, which + /// acadrust's DWG writer writes just for versions before 2007: saved as DWG 2007 or later the + /// format (`dd/MM/yyyy`) was lost. A 2007+ field with its own format is written as it is. + #[cfg(not(no_dwg_bridge))] + #[test] + fn field_formats_survive_saving_an_older_drawing_as_dwg_2007_or_later() { + let formats = |dwg: Vec| -> Vec { + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + back.objects + .values() + .filter_map(|o| match o { + acadrust::objects::ObjectType::Field(f) => Some(f.value.format.clone()), + _ => None, + }) + .collect() + }; + for source in ["AC1015", "AC1018"] { + let dxf = format!( + " 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\n{source}\n 0\nENDSEC\n 0\nSECTION\n 2\nCLASSES\n 0\nCLASS\n 1\nFIELD\n 2\nAcDbField\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n 0\nENDSEC\n 0\nSECTION\n 2\nOBJECTS\n 0\nFIELD\n 5\nA1F\n330\n1F\n 1\nAcVar\n 2\n\\AcVar Date\n 4\ndd/MM/yyyy\n 90\n0\n 97\n0\n 91\n0\n 92\n0\n 94\n0\n 95\n0\n 96\n0\n300\n\n 0\nENDSEC\n 0\nEOF\n" + ); + assert_eq!(formats(dxf_to_dwg_as(dxf.as_bytes(), "AC1032").unwrap()), ["dd/MM/yyyy"], "{source}"); + } + let mut doc = acadrust::CadDocument::new(); + doc.classes.add_or_update(acadrust::classes::DxfClass::new("FIELD", "AcDbField")); + let handle = doc.allocate_handle(); + let field = acadrust::objects::Field { + handle, + owner: doc.header.named_objects_dict_handle, + evaluator_id: "AcVar".into(), + code: "\\AcVar Date".into(), + value: acadrust::entities::CellValue { format: "%lu2".into(), ..Default::default() }, + ..Default::default() + }; + doc.objects.insert(handle, acadrust::objects::ObjectType::Field(field)); + let mut dxf = Vec::new(); + acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); + assert_eq!(formats(dxf_to_dwg_as(&dxf, "AC1032").unwrap()), ["%lu2"]); + } + + /// A FIELD record as an AC1015/AC1018 DXF writes it, its format `dd/MM/yyyy` in group 4. + #[cfg(not(no_dwg_bridge))] + fn legacy_field(handle: acadrust::Handle, owner: acadrust::Handle) -> String { + format!( + " 0\r\nFIELD\r\n 5\r\n{handle:X}\r\n330\r\n{owner:X}\r\n 1\r\nAcVar\r\n 2\r\n\\AcVar Date\r\n 4\r\ndd/MM/yyyy\r\n 90\r\n0\r\n 97\r\n0\r\n 91\r\n0\r\n 92\r\n0\r\n 94\r\n0\r\n 95\r\n0\r\n 96\r\n0\r\n300\r\n\r\n" + ) + } + + /// The FIELD formats of a DWG by handle: `value.format` from 2007, `Field::format` before. + #[cfg(not(no_dwg_bridge))] + fn dwg_field_formats(dwg: Vec) -> Vec<(u64, String)> { + let back = acadrust::DwgReader::from_stream(std::io::Cursor::new(dwg)).read().unwrap(); + let mut formats: Vec<(u64, String)> = back + .objects + .values() + .filter_map(|o| match o { + acadrust::objects::ObjectType::Field(f) => Some((f.handle.into(), f.pre2007_format().to_string())), + _ => None, + }) + .collect(); + formats.sort(); + formats + } + + /// CADCraft's R2000 DXF of a drawing with fields declares AC1015 (or the drawing's AC1018) + /// and is read as the `kept` version, for which acadrust skips group 4: an older drawing's own + /// field lost its format (`dd/MM/yyyy`) in the DWG (#1580 review). + #[cfg(not(no_dwg_bridge))] + #[test] + fn field_formats_survive_a_kept_version_newer_than_the_drawing() { + for source in ["AC1015", "AC1018"] { + for kept in ["AC1024", "AC1032"] { + let owner = acadrust::Handle::new(0x1F); + let legacy = legacy_field(acadrust::Handle::new(0xA1F), owner); + let dxf = format!( + " 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n{source}\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 1\r\nFIELD\r\n 2\r\nAcDbField\r\n 3\r\nObjectDBX Classes\r\n 90\r\n0\r\n 91\r\n0\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nOBJECTS\r\n{legacy} 0\r\nENDSEC\r\n 0\r\nEOF\r\n" + ); + for version in ["AC1032", "AC1018"] { + let got = dwg_field_formats(dxf_to_dwg_kept_as(dxf.as_bytes(), version, kept).unwrap()); + assert_eq!(got, [(0xA1F, "dd/MM/yyyy".to_string())], "{source} kept {kept} as {version}"); + } + } + } + } + + /// The same DXF with a field carried over from a 2007+ file next to the drawing's own: the + /// carried-over one keeps its own `value.format` (`%lu2`), the drawing's own its group 4 + /// format (`dd/MM/yyyy`). + #[cfg(not(no_dwg_bridge))] + #[test] + fn field_formats_survive_a_kept_version_with_carried_over_and_own_fields() { + for source in ["AC1015", "AC1018"] { + for kept in ["AC1024", "AC1032"] { + // The carried-over field as acadrust writes 2007+ DXF, the drawing's own field in + // the old layout, under the older version. + let mut doc = acadrust::CadDocument::new(); + doc.classes.add_or_update(acadrust::classes::DxfClass::new("FIELD", "AcDbField")); + let (carried, own) = (doc.allocate_handle(), doc.allocate_handle()); + let field = acadrust::objects::Field { + handle: carried, + owner: doc.header.named_objects_dict_handle, + evaluator_id: "AcVar".into(), + code: "\\AcVar Date".into(), + value: acadrust::entities::CellValue { format: "%lu2".into(), ..Default::default() }, + ..Default::default() + }; + doc.objects.insert(carried, acadrust::objects::ObjectType::Field(field)); + let mut dxf = Vec::new(); + acadrust::DxfWriter::new(&doc).write_to_writer(&mut dxf).unwrap(); + let dxf = String::from_utf8(dxf).unwrap(); + let dxf = dxf.replacen("$ACADVER\r\n 1\r\nAC1032\r\n", &format!("$ACADVER\r\n 1\r\n{source}\r\n"), 1); + let at = dxf.find(" 0\r\nFIELD\r\n").unwrap(); + let dxf = format!("{}{}{}", &dxf[..at], legacy_field(own, doc.header.named_objects_dict_handle), &dxf[at..]); + assert!(dxf.contains(&format!("$ACADVER\r\n 1\r\n{source}\r\n"))); + for version in ["AC1032", "AC1018"] { + let got = dwg_field_formats(dxf_to_dwg_kept_as(dxf.as_bytes(), version, kept).unwrap()); + let mut want = vec![(carried.into(), "%lu2".to_string()), (own.into(), "dd/MM/yyyy".to_string())]; + want.sort(); + assert_eq!(got, want, "mixed {source} kept {kept} as {version}"); + } + } + } + } } diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index 791bb60ce..246d063e0 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -342,6 +342,20 @@ fn rich_inlines(doc: &Document, o: &InlineObject, f: &Fmt, opts: FlowOpts) -> Op }) } +/// The freeform a `w` × `h` frame shape with border `corner` (see +/// [`craft_wordmodel::connector::frame_width`]) draws: its outline clockwise and its hole the +/// other way, so the hole stays empty under either fill rule. +fn frame_freeform(corner: Option, w: f32, h: f32) -> craft_wordmodel::freeform::Freeform { + use craft_wordmodel::freeform::{FreePath, Freeform}; + let (w, h) = (craft_wordmodel::geom::finite(w).max(0.0), craft_wordmodel::geom::finite(h).max(0.0)); + let t = craft_wordmodel::connector::frame_width(corner, w, h); + let mut paths = vec![FreePath { pts: vec![[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]], closed: true }]; + if w - 2.0 * t > 0.0 && h - 2.0 * t > 0.0 { + paths.push(FreePath { pts: vec![[t, t], [t, h - t], [w - t, h - t], [w - t, t]], closed: true }); + } + Freeform { w, h, paths, ..Default::default() } +} + /// Comment `c` (a reply to `parent`) of `doc` as a flow comment: its text holds no comments or /// notes of its own. /// The flow inline for picture, shape or group `o` of `doc` (a member of groups `depth` deep), @@ -358,8 +372,12 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize { // A connector stays one in formats that glue them (ODT, with boxes); elsewhere it is a // straight line. + // A frame (a border with a hole), which the other formats have no shape for, is the + // freeform it draws: its outline and, wound the other way, its hole. + let frame = (*kind == ShapeKind::Frame).then(|| std::sync::Arc::new(frame_freeform(extra.corner, *w, *h))); let kind = match kind { ShapeKind::StraightConnector | ShapeKind::ElbowConnector | ShapeKind::CurvedConnector if !opts.boxes => ShapeKind::Line, + ShapeKind::Frame => ShapeKind::Freeform, k => *k, }; let inner = FlowOpts { notes: false, comments: false, boxes: false, ..opts }; @@ -383,7 +401,7 @@ fn drawing_inline(doc: &Document, o: &InlineObject, opts: FlowOpts, depth: usize Box::new(crate::Chain { name: format!("Frame{id}"), next }) }), }; - let path = freeform.clone().filter(|_| kind == ShapeKind::Freeform); + let path = frame.or_else(|| freeform.clone()).filter(|_| kind == ShapeKind::Freeform); Some(Inline::Shape { kind, w: w * sx, h: h * sy, float: kept_float(float), blocks, look, path }) } InlineObject::Image { media, w, h, alt, float, ole, crop, .. } => { diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index ce29a4448..0375c448c 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -841,7 +841,8 @@ impl<'a> Builder<'a> { tb.props.style = None; } if t.widths.len() == cols && t.widths.iter().all(|w| w.is_finite() && *w > 1.0) { - tb.grid = t.widths.iter().map(|w| w.clamp(6.0, 1584.0)).collect(); + // Narrow columns stay as they are: raising them would widen the table past its source. + tb.grid = t.widths.iter().map(|w| w.min(1584.0)).collect(); } tb.rows.clear(); if let Some(x) = &t.extra { diff --git a/crates/frame/Cargo.toml b/crates/frame/Cargo.toml new file mode 100644 index 000000000..f74bf9365 --- /dev/null +++ b/crates/frame/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-frame" +description = "Compositor and display VideoFrame (RGBA and planar Y'CbCr) with ColorInfo, distinct from craft-video decoder pictures" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-color = { workspace = true } +craft-time = { workspace = true } +rayon = { workspace = true } +serde = { workspace = true } diff --git a/crates/frame/src/lib.rs b/crates/frame/src/lib.rs new file mode 100644 index 000000000..4b843067d --- /dev/null +++ b/crates/frame/src/lib.rs @@ -0,0 +1,599 @@ +//! Compositor and display video frames. +//! +//! [`VideoFrame`] is a picture the compositor, monitors and export share: planar Y'CbCr (8 or +//! 16-bit) from a decoder, sRGB-encoded RGBA8 from stills, or linear premultiplied RGBA f32 in the +//! compositor. Pixel data is `Arc`-shared so caches can hold frames for free. Colour is explicit +//! ([`craft_color::ColorInfo`]); time is a [`craft_time::Tick`]. +//! +//! This is **not** the decoder-output picture type in `craft-video` (`craft_video::frame::VideoFrame` +//! in #1231 / #1768), which is a planar codec frame (per-plane bit depth, field order, colour +//! tags as H.273 codes). This type is the one `MediaSource::video_frame` returns. +//! +//! Came from FilmCraft's `filmcraft-frame` (the picture type and display conversions; the frame +//! pool and audio buffer stay out — audio is [`craft_audio::AudioBuffer`]). + +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] + +use std::sync::Arc; + +use craft_color::{ + ColorInfo, Matrix, Range, Transfer, linear_to_srgb_u8, normalize_c, normalize_y, srgb_u8_to_linear_table, to_linear, ycbcr_to_rgb, +}; +use craft_time::Tick; +use rayon::prelude::*; +use serde::{Deserialize, Serialize}; + +/// Default per-buffer allocation ceiling (1 GiB), permitting an 8K RGBA-f32 frame. +/// Callers with a smaller budget should use the `*_with_limit` conversions. +pub const DEFAULT_MAX_FRAME_BYTES: usize = 1 << 30; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FrameError { + InvalidLayout, + InvalidBitDepth, + InvalidSample, + TooLarge, + Allocation, +} +impl std::fmt::Display for FrameError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::InvalidLayout => "frame storage does not match its dimensions", + Self::InvalidBitDepth => "unsupported frame sample bit depth", + Self::InvalidSample => "frame sample exceeds its declared bit depth", + Self::TooLarge => "frame exceeds the allocation limit", + Self::Allocation => "unable to allocate frame buffer", + }) + } +} +impl std::error::Error for FrameError {} +impl From for FrameError { + fn from(_: craft_color::InvalidBitDepth) -> Self { + Self::InvalidBitDepth + } +} +pub type Result = std::result::Result; + +fn elements(width: u32, height: u32, channels: usize) -> Result { + usize::try_from(width) + .ok() + .and_then(|w| usize::try_from(height).ok().and_then(|h| w.checked_mul(h))) + .and_then(|n| n.checked_mul(channels)) + .ok_or(FrameError::TooLarge) +} + +fn buffer(len: usize, max_bytes: usize) -> Result> { + if len.checked_mul(std::mem::size_of::()).is_none_or(|bytes| bytes > max_bytes || bytes > isize::MAX as usize) { + return Err(FrameError::TooLarge); + } + let mut out = Vec::new(); + out.try_reserve_exact(len).map_err(|_| FrameError::Allocation)?; + out.resize(len, T::default()); + Ok(out) +} + +/// Chroma subsampling of planar Y'CbCr. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Chroma { + C420, + C422, + C444, +} + +impl Chroma { + /// (horizontal shift, vertical shift) + pub fn shifts(self) -> (u32, u32) { + match self { + Chroma::C420 => (1, 1), + Chroma::C422 => (1, 0), + Chroma::C444 => (0, 0), + } + } + /// A short 4:2:0 / 4:2:2 / 4:4:4 label. + pub fn label(self) -> &'static str { + match self { + Chroma::C420 => "4:2:0", + Chroma::C422 => "4:2:2", + Chroma::C444 => "4:4:4", + } + } +} + +/// Pixel storage of a [`VideoFrame`]. +#[derive(Clone, Debug)] +pub enum PixelData { + /// Straight-alpha, sRGB/709-encoded RGBA, 8 bits per channel. + Rgba8(Arc>), + /// Premultiplied, linear-light RGBA f32 (compositor working format). + RgbaF32(Arc>), + /// 8-bit planar Y'CbCr (optionally with an alpha plane). + Yuv8 { planes: [Arc>; 3], chroma: Chroma, alpha: Option>> }, + /// 9–16-bit planar Y'CbCr stored in u16 (`bits` significant bits). + Yuv16 { planes: [Arc>; 3], chroma: Chroma, bits: u32, alpha: Option>> }, +} + +/// A compositor or display picture. Pixel buffers are `Arc`-shared. +#[derive(Clone, Debug)] +pub struct VideoFrame { + pub width: u32, + pub height: u32, + pub data: PixelData, + pub color: ColorInfo, + /// Pixel aspect ratio (num, den). + pub par: (u32, u32), + /// Presentation time in media time (informational). + pub pts: Tick, +} + +/// A rectangle of pixels: `x`, `y` is its top-left corner. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Region { + pub x: usize, + pub y: usize, + pub w: usize, + pub h: usize, +} + +impl Region { + pub fn is_empty(&self) -> bool { + self.w == 0 || self.h == 0 + } + /// This rectangle cut to a `w`×`h` picture (empty when it lies outside). + pub fn clip(self, w: usize, h: usize) -> Region { + let x = self.x.min(w); + let y = self.y.min(h); + Region { x, y, w: self.w.min(w - x), h: self.h.min(h - y) } + } + /// Whether this rectangle is the whole `w`×`h` picture. + pub fn is_full(&self, w: usize, h: usize) -> bool { + (self.x, self.y, self.w, self.h) == (0, 0, w, h) + } +} + +impl VideoFrame { + /// An sRGB-full, 1:1, zero-pts RGBA8 frame. `data` is `width × height × 4` bytes. + pub fn rgba8(width: u32, height: u32, data: Vec) -> Result { + let frame = Self { width, height, data: PixelData::Rgba8(Arc::new(data)), color: ColorInfo::SRGB_FULL, par: (1, 1), pts: Tick::ZERO }; + frame.validate()?; + Ok(frame) + } + + /// A linear premultiplied RGBA f32 frame, sRGB-full tags, 1:1, zero pts. + pub fn rgba_f32(width: u32, height: u32, data: Vec) -> Result { + let frame = Self { width, height, data: PixelData::RgbaF32(Arc::new(data)), color: ColorInfo::SRGB_FULL, par: (1, 1), pts: Tick::ZERO }; + frame.validate()?; + Ok(frame) + } + + /// A transparent linear RGBA f32 frame of the given size. + pub fn transparent_f32(width: u32, height: u32) -> Result { + Self::rgba_f32(width, height, buffer(elements(width, height, 4)?, DEFAULT_MAX_FRAME_BYTES)?) + } + + /// Validate all public fields before indexing pixel storage. Rechecked by conversions because + /// callers can mutate these fields after construction. Padding beyond each required plane is allowed. + pub fn validate(&self) -> Result<()> { + let pixels = elements(self.width, self.height, 1)?; + let rgba = pixels.checked_mul(4).ok_or(FrameError::TooLarge)?; + let planar = |lengths: [usize; 3], chroma: Chroma, alpha: Option| { + let (sx, sy) = chroma.shifts(); + let cw = (self.width as usize).div_ceil(1 << sx); + let ch = (self.height as usize).div_ceil(1 << sy); + let cp = cw.checked_mul(ch).ok_or(FrameError::TooLarge)?; + if lengths[0] < pixels || lengths[1] < cp || lengths[2] < cp || alpha.is_some_and(|n| n < pixels) { + return Err(FrameError::InvalidLayout); + } + Ok(()) + }; + match &self.data { + PixelData::Rgba8(d) if d.len() == rgba => Ok(()), + PixelData::RgbaF32(d) if d.len() == rgba => Ok(()), + PixelData::Yuv8 { planes, chroma, alpha } => planar(planes.each_ref().map(|p| p.len()), *chroma, alpha.as_ref().map(|p| p.len())), + PixelData::Yuv16 { planes, chroma, bits, alpha } => { + if !(9..=16).contains(bits) { + return Err(FrameError::InvalidBitDepth); + } + planar(planes.each_ref().map(|p| p.len()), *chroma, alpha.as_ref().map(|p| p.len()))?; + let max = (1u32 << bits) - 1; + // Alpha is full-range at the declared depth. Out-of-range values would produce + // opacity above one and corrupt premultiplied colors; unused padding is ignored. + if alpha.as_ref().is_some_and(|a| a.iter().take(pixels).any(|&v| u32::from(v) > max)) { + return Err(FrameError::InvalidSample); + } + Ok(()) + } + _ => Err(FrameError::InvalidLayout), + } + } + + /// Sets the presentation timestamp and returns the frame. + pub fn with_pts(mut self, pts: Tick) -> Self { + self.pts = pts; + self + } + + /// A short format label for UI and logs. + pub fn format_label(&self) -> String { + match &self.data { + PixelData::Rgba8(_) => "RGBA 8-bit".into(), + PixelData::RgbaF32(_) => "RGBA 32-bit float".into(), + PixelData::Yuv8 { chroma, .. } => format!("YUV {} 8-bit", chroma.label()), + PixelData::Yuv16 { chroma, bits, .. } => format!("YUV {} {bits}-bit", chroma.label()), + } + } + + /// Approximate memory footprint in bytes (for caches). + pub fn byte_size(&self) -> usize { + match &self.data { + PixelData::Rgba8(d) => d.len(), + PixelData::RgbaF32(d) => d.len().saturating_mul(4), + PixelData::Yuv8 { planes, alpha, .. } => { + planes.iter().fold(0usize, |n, p| n.saturating_add(p.len())).saturating_add(alpha.as_ref().map_or(0, |a| a.len())) + } + PixelData::Yuv16 { planes, alpha, .. } => { + planes.iter().fold(0usize, |n, p| n.saturating_add(p.len())).saturating_add(alpha.as_ref().map_or(0, |a| a.len())).saturating_mul(2) + } + } + } + + /// Premultiplied linear-light RGBA f32, one pixel per source pixel, row-major, 4 samples each. + pub fn to_linear_f32(&self) -> Result> { + self.to_linear_f32_with_limit(DEFAULT_MAX_FRAME_BYTES) + } + + pub fn to_linear_f32_with_limit(&self, max_bytes: usize) -> Result> { + self.validate()?; + let (w, h) = (self.width as usize, self.height as usize); + let mut out = buffer::(elements(self.width, self.height, 4)?, max_bytes)?; + if w == 0 || h == 0 { + return Ok(out); + } + match &self.data { + PixelData::RgbaF32(d) => { + let n = out.len().min(d.len()); + out[..n].copy_from_slice(&d[..n]); + } + PixelData::Rgba8(d) => { + let lut = srgb_u8_to_linear_table(); + for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(d.as_chunks::<4>().0) { + let a = s[3] as f32 / 255.0; + o[0] = lut[s[0] as usize] * a; + o[1] = lut[s[1] as usize] * a; + o[2] = lut[s[2] as usize] * a; + o[3] = a; + } + } + PixelData::Yuv8 { planes, chroma, alpha } => { + let (sx, sy) = chroma.shifts(); + let cw = w.div_ceil(1 << sx); + let info = self.color; + let lin: Vec = (0..4096).map(|i| to_linear(i as f32 / 4095.0, info.transfer)).collect(); + let q = |v: f32| lin[(v.clamp(0.0, 1.0) * 4095.0 + 0.5) as usize]; + let ytab: Vec = (0..256).map(|v| normalize_y(v, 8, info.range)).collect::>()?; + let ctab: Vec = (0..256).map(|v| normalize_c(v, 8, info.range)).collect::>()?; + let rgb_of = |y: usize, x: usize| { + let yy = ytab[planes[0][y * w + x] as usize]; + let u = ctab[planes[1][(y >> sy) * cw + (x >> sx)] as usize]; + let v = ctab[planes[2][(y >> sy) * cw + (x >> sx)] as usize]; + let rgb = ycbcr_to_rgb(yy, u, v, info.matrix); + let a = alpha.as_ref().map_or(1.0, |al| al[y * w + x] as f32 / 255.0); + [q(rgb[0]) * a, q(rgb[1]) * a, q(rgb[2]) * a, a] + }; + for y in 0..h { + for x in 0..w { + let o = (y * w + x) * 4; + out[o..o + 4].copy_from_slice(&rgb_of(y, x)); + } + } + } + PixelData::Yuv16 { planes, chroma, bits, alpha } => { + let (sx, sy) = chroma.shifts(); + let cw = w.div_ceil(1 << sx); + let info = self.color; + let bits = *bits; + let amax = ((1u32 << bits) - 1) as f32; + let lin: Vec = (0..4096).map(|i| to_linear(i as f32 / 4095.0, info.transfer)).collect(); + let q = |v: f32| lin[(v.clamp(0.0, 1.0) * 4095.0 + 0.5) as usize]; + for y in 0..h { + for x in 0..w { + let yy = normalize_y(planes[0][y * w + x] as u32, bits, info.range)?; + let u = normalize_c(planes[1][(y >> sy) * cw + (x >> sx)] as u32, bits, info.range)?; + let v = normalize_c(planes[2][(y >> sy) * cw + (x >> sx)] as u32, bits, info.range)?; + let rgb = ycbcr_to_rgb(yy, u, v, info.matrix); + let a = alpha.as_ref().map_or(1.0, |al| al[y * w + x] as f32 / amax); + let o = (y * w + x) * 4; + out[o] = q(rgb[0]) * a; + out[o + 1] = q(rgb[1]) * a; + out[o + 2] = q(rgb[2]) * a; + out[o + 3] = a; + } + } + } + } + Ok(out) + } + + /// Convert to straight-alpha sRGB RGBA8 for display (fast path for 8-bit Rec.709/sRGB Y'CbCr + /// without alpha, and a copy for RGBA8). + pub fn to_rgba8(&self) -> Result> { + self.to_rgba8_with_limit(DEFAULT_MAX_FRAME_BYTES) + } + + pub fn to_rgba8_with_limit(&self, max_bytes: usize) -> Result> { + self.validate()?; + let (w, h) = (self.width as usize, self.height as usize); + // Empty pictures have no rows; Rayon rejects a zero-sized row chunk. + if w == 0 || h == 0 { + return Ok(Vec::new()); + } + match &self.data { + PixelData::Rgba8(d) => { + let mut out = buffer::(d.len(), max_bytes)?; + out.copy_from_slice(d); + Ok(out) + } + PixelData::Yuv8 { planes, chroma, alpha: None } if matches!(self.color.transfer, Transfer::Bt709 | Transfer::Srgb) => { + let (sx, sy) = chroma.shifts(); + let cw = w.div_ceil(1 << sx); + let (kr, kb) = self.color.matrix.kr_kb(); + let kg = 1.0 - kr - kb; + let (ys, yo, cs) = match self.color.range { + Range::Limited => (255.0 / 219.0, 16.0, 255.0 / 224.0), + Range::Full => (1.0, 0.0, 1.0), + }; + let (crr, cbb) = (2.0 * (1.0 - kr) * cs, 2.0 * (1.0 - kb) * cs); + let (cgr, cgb) = (crr * kr / kg, cbb * kb / kg); + let mut out = buffer::(elements(self.width, self.height, 4)?, max_bytes)?; + out.par_chunks_mut(w * 4).enumerate().for_each(|(y, row)| { + let cy = y >> sy; + let yrow = &planes[0][y * w..y * w + w]; + let urow = &planes[1][cy * cw..cy * cw + cw]; + let vrow = &planes[2][cy * cw..cy * cw + cw]; + for x in 0..w { + let yy = (yrow[x] as f32 - yo) * ys; + let u = urow[x >> sx] as f32 - 128.0; + let v = vrow[x >> sx] as f32 - 128.0; + let o = &mut row[x * 4..x * 4 + 4]; + o[0] = (yy + crr * v).round().clamp(0.0, 255.0) as u8; + o[1] = (yy - cgr * v - cgb * u).round().clamp(0.0, 255.0) as u8; + o[2] = (yy + cbb * u).round().clamp(0.0, 255.0) as u8; + o[3] = 255; + } + }); + Ok(out) + } + _ => { + let lin = self.to_linear_f32_with_limit(max_bytes)?; + let mut out = buffer::(elements(self.width, self.height, 4)?, max_bytes)?; + out.par_chunks_mut(w * 4).zip(lin.par_chunks(w * 4)).for_each(|(o, s)| linear_premul_to_srgb8(s, o)); + Ok(out) + } + } + } + + /// Luma plane (8-bit, for scopes and thumbnails). Y'CbCr 8-bit returns the Y plane; others go + /// through [`Self::to_rgba8`] and Rec.709 luma of the encoded RGB. + pub fn luma8(&self) -> Result> { + self.validate()?; + let pixels = elements(self.width, self.height, 1)?; + let mut out = buffer::(pixels, DEFAULT_MAX_FRAME_BYTES)?; + match &self.data { + PixelData::Yuv8 { planes, .. } => out.copy_from_slice(&planes[0][..pixels]), + _ => { + let rgba = self.to_rgba8()?; + for (o, p) in out.iter_mut().zip(rgba.as_chunks::<4>().0) { + *o = (0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32) as u8; + } + } + } + Ok(out) + } +} + +/// Convert a row of premultiplied linear f32 RGBA into straight sRGB RGBA8. +pub fn linear_premul_to_srgb8(src: &[f32], dst: &mut [u8]) { + for (s, o) in src.as_chunks::<4>().0.iter().zip(dst.as_chunks_mut::<4>().0) { + let a = s[3].clamp(0.0, 1.0); + if a <= 0.0 { + o.copy_from_slice(&[0, 0, 0, 0]); + continue; + } + let inv = 1.0 / a; + o[0] = linear_to_srgb_u8(s[0] * inv); + o[1] = linear_to_srgb_u8(s[1] * inv); + o[2] = linear_to_srgb_u8(s[2] * inv); + o[3] = (a * 255.0 + 0.5) as u8; + } +} + +/// Matrix used when a decoder does not signal one: BT.601 for SD, BT.709 otherwise (common practice). +pub fn default_matrix(width: u32, height: u32) -> Matrix { + if width <= 1024 && height <= 576 { Matrix::Bt601 } else { Matrix::Bt709 } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn malformed_storage_and_bit_depth_are_errors() { + let make = |data| VideoFrame { width: 2, height: 2, data, color: ColorInfo::REC709, par: (1, 1), pts: Tick::ZERO }; + let short = make(PixelData::Yuv8 { planes: std::array::from_fn(|_| Arc::new(vec![0])), chroma: Chroma::C420, alpha: None }); + assert_eq!(short.to_rgba8(), Err(FrameError::InvalidLayout)); + assert_eq!(short.to_linear_f32(), Err(FrameError::InvalidLayout)); + assert_eq!(short.luma8(), Err(FrameError::InvalidLayout)); + for bits in [0, 8, 17, 32, u32::MAX] { + let frame = make(PixelData::Yuv16 { planes: std::array::from_fn(|_| Arc::new(vec![0; 4])), chroma: Chroma::C444, bits, alpha: None }); + assert_eq!(frame.to_linear_f32(), Err(FrameError::InvalidBitDepth)); + } + assert!(VideoFrame::rgba8(2, 2, vec![0; 15]).is_err()); + assert!(VideoFrame::rgba_f32(2, 2, vec![0.0; 15]).is_err()); + let mut valid = VideoFrame::rgba8(1, 1, vec![0; 4]).unwrap(); + valid.width = 2; // public mutations must be checked again, not just by constructors. + assert_eq!(valid.to_linear_f32(), Err(FrameError::InvalidLayout)); + } + + #[test] + fn odd_subsampled_frames_validate_chroma_and_alpha_independently() { + let make = |bits| VideoFrame { + width: 3, + height: 3, + data: PixelData::Yuv16 { + planes: [Arc::new(vec![128; 9]), Arc::new(vec![128; 4]), Arc::new(vec![128; 4])], + chroma: Chroma::C420, + bits, + alpha: Some(Arc::new(vec![255; 9])), + }, + color: ColorInfo::REC709, + par: (1, 1), + pts: Tick::ZERO, + }; + for bits in [9, 16] { + let mut valid = make(bits); + assert_eq!(valid.to_linear_f32().unwrap().len(), 36); + assert_eq!(valid.to_rgba8().unwrap().len(), 36); + if let PixelData::Yuv16 { planes, .. } = &mut valid.data { + planes[1] = Arc::new(vec![128; 3]); + } + assert_eq!(valid.to_linear_f32(), Err(FrameError::InvalidLayout)); + let mut valid = make(bits); + if let PixelData::Yuv16 { alpha, .. } = &mut valid.data { + *alpha = Some(Arc::new(vec![255; 8])); + } + assert_eq!(valid.to_rgba8(), Err(FrameError::InvalidLayout)); + } + let mut fast = VideoFrame { + width: 3, + height: 3, + data: PixelData::Yuv8 { + planes: [Arc::new(vec![128; 9]), Arc::new(vec![128; 4]), Arc::new(vec![128; 4])], + chroma: Chroma::C420, + alpha: None, + }, + color: ColorInfo::REC709, + par: (1, 1), + pts: Tick::ZERO, + }; + assert_eq!(fast.to_rgba8().unwrap().len(), 36); + fast.height = 4; + assert_eq!(fast.to_rgba8(), Err(FrameError::InvalidLayout)); + } + + #[test] + fn yuv16_alpha_respects_declared_bit_depth() { + let make = |alpha, bits| VideoFrame { + width: 1, + height: 1, + data: PixelData::Yuv16 { + planes: [Arc::new(vec![128]), Arc::new(vec![128]), Arc::new(vec![128])], + chroma: Chroma::C444, + bits, + alpha: Some(Arc::new(vec![alpha])), + }, + color: ColorInfo::REC709, + par: (1, 1), + pts: Tick::ZERO, + }; + for bits in [9, 10, 12, 16] { + let max = ((1u32 << bits) - 1) as u16; + let valid = make(max, bits); + assert_eq!(valid.to_linear_f32().unwrap()[3], 1.0); + assert_eq!(valid.to_rgba8().unwrap()[3], 255); + if bits < 16 { + let invalid = make(max + 1, bits); + assert!(invalid.to_linear_f32().is_err()); + assert!(invalid.to_rgba8().is_err()); + assert!(make(u16::MAX, bits).validate().is_err()); + } + } + } + #[test] + fn frame_allocations_are_checked_before_reserving() { + assert!(matches!(VideoFrame::transparent_f32(u32::MAX, u32::MAX), Err(FrameError::TooLarge))); + let frame = VideoFrame::rgba8(1, 1, vec![0; 4]).unwrap(); + assert_eq!(frame.to_rgba8_with_limit(3), Err(FrameError::TooLarge)); + assert_eq!(frame.to_linear_f32_with_limit(15), Err(FrameError::TooLarge)); + assert_eq!(frame.to_linear_f32_with_limit(16).unwrap(), vec![0.0; 4]); + } + + #[test] + fn empty_frames_convert_without_zero_sized_chunks() { + for (w, h) in [(0, 0), (0, 1), (1, 0)] { + let frame = VideoFrame::transparent_f32(w, h).unwrap(); + assert!(frame.to_rgba8().unwrap().is_empty()); + assert!(frame.to_linear_f32().unwrap().is_empty()); + assert!(frame.luma8().unwrap().is_empty()); + } + } + + #[test] + fn rgba8_roundtrips_through_to_rgba8() { + let px = vec![10u8, 20, 30, 255, 0, 0, 0, 0]; + let f = VideoFrame::rgba8(2, 1, px.clone()).unwrap().with_pts(Tick(42)); + assert_eq!(f.pts, Tick(42)); + assert_eq!(f.to_rgba8().unwrap(), px); + assert_eq!(f.format_label(), "RGBA 8-bit"); + assert_eq!(f.byte_size(), 8); + assert_eq!(f.color, ColorInfo::SRGB_FULL); + } + + #[test] + fn rgba8_to_linear_premultiplies() { + // 50% red, 50% alpha, sRGB encoded. Linear of 128/255, times 0.5 alpha. + let f = VideoFrame::rgba8(1, 1, vec![128, 0, 0, 128]).unwrap(); + let lin = f.to_linear_f32().unwrap(); + let a = 128.0 / 255.0; + let r = srgb_u8_to_linear_table()[128] * a; + assert!((lin[0] - r).abs() < 1e-6); + assert_eq!(lin[1], 0.0); + assert!((lin[3] - a).abs() < 1e-6); + let back = f.to_rgba8().unwrap(); + assert_eq!(back[0], 128); + assert_eq!(back[3], 128); + } + + #[test] + fn limited_709_gray_yuv8_is_near_neutral() { + // Limited-range mid gray: Y=126 (~0.5), Cb=Cr=128. + let y = Arc::new(vec![126u8; 4]); + let c = Arc::new(vec![128u8; 4]); + let f = VideoFrame { + width: 2, + height: 2, + data: PixelData::Yuv8 { planes: [y, c.clone(), c], chroma: Chroma::C444, alpha: None }, + color: ColorInfo::REC709, + par: (1, 1), + pts: Tick::ZERO, + }; + let rgba = f.to_rgba8().unwrap(); + for p in rgba.as_chunks::<4>().0 { + assert!((p[0] as i16 - p[1] as i16).abs() <= 1, "{p:?}"); + assert!((p[1] as i16 - p[2] as i16).abs() <= 1, "{p:?}"); + assert!(p[0] > 90 && p[0] < 160, "{p:?}"); + assert_eq!(p[3], 255); + } + assert_eq!(f.luma8().unwrap(), vec![126, 126, 126, 126]); + assert_eq!(f.format_label(), "YUV 4:4:4 8-bit"); + } + + #[test] + fn default_matrix_is_601_for_sd_and_709_otherwise() { + assert_eq!(default_matrix(720, 576), Matrix::Bt601); + assert_eq!(default_matrix(1920, 1080), Matrix::Bt709); + } + + #[test] + fn region_clip() { + let r = Region { x: 8, y: 8, w: 16, h: 16 }.clip(10, 10); + assert_eq!(r, Region { x: 8, y: 8, w: 2, h: 2 }); + assert!(Region { x: 20, y: 0, w: 4, h: 4 }.clip(10, 10).is_empty()); + assert!(Region { x: 0, y: 0, w: 10, h: 10 }.is_full(10, 10)); + } + + #[test] + fn transparent_float_encodes_as_zero_rgba8() { + let f = VideoFrame::transparent_f32(2, 1).unwrap(); + assert_eq!(f.to_rgba8().unwrap(), vec![0; 8]); + assert_eq!(f.byte_size(), 32); // 2 pixels × 4 f32 channels × 4 bytes + } +} diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 32d24f92c..9b11af4e8 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -24,6 +24,7 @@ heif = ["dep:craft-heif"] avif-decode = ["dep:craft-video", "craft-video/av1-decode"] [dependencies] +craft-dds = { workspace = true } crc32fast = "1.5" thiserror = { workspace = true } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "gif", "bmp", "tga", "ico", "qoi", "hdr"] } @@ -48,6 +49,8 @@ avif-serialize = { version = "0.8", optional = true } hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["std", "simd"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# DDS encodes rows of blocks on several threads, as the other parallel codecs here do on native targets. +craft-dds = { workspace = true, features = ["parallel"] } rayon = { workspace = true } craft-video = { workspace = true, optional = true } exr = { version = "1.73", default-features = false, features = ["rayon"] } diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index eb7c37362..f96672817 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -46,7 +46,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "< | BMP | yes | yes | U8 | RGB, RGBA | yes | no | no | no | yes (header pixels per metre) | no | no | `image` | | TGA | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | no | `image` (read) / built in (RLE write, one scanline per packet) | | ICO | yes | yes | U8 | RGBA (at most 256×256) | yes | no | no | no | no | no | no | `image` | -| DDS | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | yes (BC1–BC3, when `EncodeOptions::dds` asks for one) | built in | +| DDS | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | yes (BC1–BC5, when `EncodeOptions::dds` asks for one) | [`craft-dds`](../dds/README.md) | | Netpbm (PBM/PGM/PPM/PAM/PFM) | yes | yes | U8, U16, F32 (float: PFM gray/RGB only) | all six (PAM `CMYK`/`CMYK_ALPHA`) | yes (PAM) | no | no | no | no | no | no | built in | | QOI | yes | yes | U8 | RGB, RGBA | yes | no | no | no | no | no | no | `image` | | OpenEXR | yes | yes | F16, F32 | Y, YA, RGB, RGBA | yes | no | no | no | no | no | no | `exr` | @@ -95,20 +95,29 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them Reading remains in the separate #2868 PR. The `ASYMMETRIC_EXCEPTIONS` entry stays until import is merged. -* **DDS.** The top mip level of a 2D texture: uncompressed pixels described by channel masks - (8, 16, 24 or 32 bits, RGB or luminance, with or without alpha) or BC1/BC2/BC3 (DXT1/DXT3/DXT5), - with the legacy header or the DX10 one. Uncompressed row padding follows the header's - `DDSD_PITCH` stride; without that flag, rows are tightly packed. Everything opens as U8; the - other mip levels are ignored. Cubemaps, texture arrays, volume textures, premultiplied DXT2/DXT4 and other formats - (BC4–BC7, float) are refused with `CodecError::Unsupported`. Writing (`EncodeOptions::dds`) makes - a 2D texture with the legacy header: uncompressed by default (BGRA, BGRX, or luminance with or - without alpha, so it reads back exactly), or BC1/BC2/BC3. The block encoder is our own, from +* **DDS** (through [`craft-dds`](../dds/README.md), whose `DdsCompression` and `DdsOptions` are + re-exported). The top mip level of a 2D texture: uncompressed pixels described by channel masks + (8, 16, 24 or 32 bits, RGB or luminance, with or without alpha), BC1/BC2/BC3 (DXT1/DXT3/DXT5) or + unsigned BC4/BC5 (ATI1/ATI2, BC4U/BC5U, DXGI 79, 80, 82 and 83), with the legacy header or the + DX10 one. BC4 opens as Gray and BC5 as RGB with blue 0 (BC5 stores only red and green; a normal + map's Z is not reconstructed). ATI2 is read as Microsoft reads it, red in the first block. + Uncompressed row padding follows the header's `DDSD_PITCH` stride; without that flag, rows are + tightly packed. Everything opens as U8; the other mip levels are ignored. Cubemaps, texture + arrays, volume textures, premultiplied-alpha textures (DXT2/DXT4, or DX10 alpha mode 2), signed (SNORM) BC4/BC5 and other formats + (BC6H, BC7, float) are refused with `CodecError::Unsupported`. Writing (`EncodeOptions::dds`) + makes a 2D texture: uncompressed by default (BGRA, BGRX, or luminance with or without alpha, so + it reads back exactly), BC1/BC2/BC3 (from RGBA) with the legacy header, or BC4 (from gray, for + roughness, height and other single-channel maps) and BC5 (from RGB, blue dropped, for normal + maps) with the DX10 header (`BC4_UNORM`, `BC5_UNORM`). The plan converts other layouts to what + the compression stores, so `fidelity_warnings` reports colour to gray for BC4 and dropped alpha + for both; BC5's dropped blue comes under `LossyCompression`. The block encoder is our own, from Microsoft's public block-compression documentation: RGB565 endpoints fitted along each block's principal axis and refined by least squares, indices picked against the palette the reader - decodes; BC1 turns texels under half opacity into its transparent black, and BC3 picks - whichever alpha mode fits. `mipmaps` adds the full chain down to 1×1, each level a box filter - of the one above (the last column and row of an odd-sized level average three pixels, so none - is dropped). Cubemaps, arrays, BC4–BC7 and sRGB (DX10-only) formats aren't written. + decodes; BC1 turns texels under half opacity into its transparent black, and BC3, BC4 and BC5 + pick whichever mode of their value blocks fits. `mipmaps` adds the full chain down to 1×1, each + level a box filter of the one above (the last column and row of an odd-sized level average + three pixels, so none is dropped). Cubemaps, arrays, BC6H, BC7 and sRGB (DX10-only) formats + aren't written. * **FITS.** The image in the primary HDU, or the first `IMAGE` extension, is read; `NAXIS3 = 3` opens as RGB and any other plane count opens the first plane with `DecodeWarning::MorePages`. diff --git a/crates/image-codecs/src/codecs.rs b/crates/image-codecs/src/codecs.rs index e2faaac4c..3fdf65ae3 100644 --- a/crates/image-codecs/src/codecs.rs +++ b/crates/image-codecs/src/codecs.rs @@ -3,7 +3,6 @@ pub(crate) mod avif; pub(crate) mod avif_decode; pub(crate) mod bmp; pub(crate) mod dds; -pub(crate) mod dds_bc; pub(crate) mod deep_exr; pub(crate) mod dicom; pub(crate) mod dpx; diff --git a/crates/image-codecs/src/codecs/dds.rs b/crates/image-codecs/src/codecs/dds.rs index 9ed4e3f35..4c8475ea8 100644 --- a/crates/image-codecs/src/codecs/dds.rs +++ b/crates/image-codecs/src/codecs/dds.rs @@ -1,557 +1,60 @@ -//! DirectDraw Surface (DDS) textures, after Microsoft's public DDS documentation ("DDS", -//! "DDS_HEADER", "DDS_PIXELFORMAT", "DDS_HEADER_DXT10"). -//! -//! Reading: the top mip level of a 2D texture, either uncompressed (8 to 32 bits per pixel -//! described by channel masks, RGB or luminance) or block-compressed BC1/BC2/BC3 -//! (DXT1/DXT3/DXT5), with or without the DX10 header. Cubemaps, texture arrays and volume -//! textures are refused rather than flattened to one face or slice. -//! -//! Writing: a 2D texture, uncompressed (BGRA or BGRX, luminance with or without alpha) or -//! BC1/BC2/BC3, optionally with its full mip chain. The legacy header describes all of these, -//! so no DX10 header is written; formats only DXGI can name (BC4–BC7, sRGB) aren't written. +//! DirectDraw Surface (DDS) textures through [`craft_dds`]: its errors and pixel layouts mapped +//! onto this crate's, and the decoder's size checked against [`Limits`] before it allocates. -use std::borrow::Cow; - -use super::dds_bc::{self, Block, Mask}; use crate::SampleType; use crate::error::CodecError; use crate::fidelity::Plan; use crate::format::Format; use crate::image::{ChannelLayout, Image}; -use crate::options::{DdsCompression, EncodeOptions, Limits}; +use crate::options::{EncodeOptions, Limits}; +use craft_dds::{DdsError, Layout, Texture}; -/// `DDS ` plus the 124-byte DDS_HEADER. -const HEADER: usize = 128; -/// DDS_HEADER_DXT10, present when the FourCC is `DX10`. -const DX10_HEADER: usize = 20; - -const DDSD_DEPTH: u32 = 0x80_0000; -const DDPF_ALPHAPIXELS: u32 = 0x1; -const DDPF_FOURCC: u32 = 0x4; -const DDPF_RGB: u32 = 0x40; -const DDPF_LUMINANCE: u32 = 0x2_0000; -const DDSCAPS2_CUBEMAP: u32 = 0x200; -const DDSCAPS2_CUBEMAP_FACES: u32 = 0xfc00; -const DDSCAPS2_VOLUME: u32 = 0x20_0000; -const DIMENSION_TEXTURE2D: u32 = 3; -const MISC_TEXTURECUBE: u32 = 0x4; - -fn bad(reason: impl std::fmt::Display) -> CodecError { - CodecError::malformed(Format::Dds, reason) +fn error(e: DdsError) -> CodecError { + match e { + DdsError::Malformed(reason) => CodecError::malformed(Format::Dds, reason), + DdsError::Unsupported(reason) => CodecError::unsupported(Format::Dds, reason), + DdsError::Encode(reason) => CodecError::encode(Format::Dds, reason), + DdsError::Alloc(len) => CodecError::LimitExceeded(format!("cannot allocate {len} elements for the image")), + DdsError::LimitExceeded { required, limit } => { + CodecError::LimitExceeded(format!("decoded texture requires {required} bytes, exceeding limit {limit}")) + } + other => CodecError::malformed(Format::Dds, other), + } } -fn unsupported(reason: impl Into) -> CodecError { - CodecError::unsupported(Format::Dds, reason) -} -fn le32(b: &[u8], at: usize) -> Result { - let bytes = b.get(at..at + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()).ok_or_else(|| bad("truncated header"))?; - Ok(u32::from_le_bytes(bytes)) + +pub(crate) fn channel_layout(layout: Layout) -> ChannelLayout { + match layout { + Layout::Gray => ChannelLayout::Gray, + Layout::GrayA => ChannelLayout::GrayA, + Layout::Rgb => ChannelLayout::Rgb, + Layout::Rgba => ChannelLayout::Rgba, + } } /// Header-declared extra subresources cannot survive a single-image rewrite, even without presence flags. pub(crate) fn has_additional_images(bytes: &[u8]) -> Result { - let depth = le32(bytes, 24)?; - let mips = le32(bytes, 28)?; - let faces = (le32(bytes, 112)? & DDSCAPS2_CUBEMAP_FACES).count_ones(); - let dx10 = le32(bytes, 80)? & DDPF_FOURCC != 0 && bytes.get(84..88) == Some(b"DX10"); - let (cube, array) = if dx10 { (le32(bytes, 136)? & MISC_TEXTURECUBE != 0, le32(bytes, 140)?) } else { (false, 0) }; - Ok(depth > 1 || mips > 1 || faces > 1 || cube || array > 1) -} - -/// A FourCC as text when it is printable, else as the number legacy writers store there. -fn fourcc_name(fourcc: u32) -> String { - let bytes = fourcc.to_le_bytes(); - if bytes.iter().all(|c| c.is_ascii_graphic() || *c == b' ') { bytes.iter().map(|&c| char::from(c)).collect() } else { fourcc.to_string() } -} - -/// One channel of an uncompressed pixel: where it sits and its largest value. -#[derive(Clone, Copy)] -struct Field { - shift: u32, - max: u32, -} - -impl Field { - /// `None` for an empty mask; an error for one with gaps or wider than the pixel. - fn new(mask: u32, bits: u32) -> Result, CodecError> { - if mask == 0 { - return Ok(None); - } - let shift = mask.trailing_zeros(); - let max = mask >> shift; - if max & max.wrapping_add(1) != 0 || (bits < 32 && mask >> bits != 0) { - return Err(bad(format!("channel mask {mask:#x} is not a contiguous field of a {bits}-bit pixel"))); - } - Ok(Some(Field { shift, max })) - } - - fn get(self, pixel: u32) -> u8 { - let v = u64::from((pixel >> self.shift) & self.max); - let max = u64::from(self.max); - ((v * 255 + max / 2) / max) as u8 - } -} - -enum Encoding { - /// Uncompressed: bytes per pixel, then red (or luminance), green, blue and alpha. - Masks { - bytes: usize, - gray: bool, - fields: [Option; 4], - }, - Bc1, - Bc2, - Bc3, -} - -impl Encoding { - fn masks(bits: u32, masks: [u32; 4], gray: bool) -> Result { - if !matches!(bits, 8 | 16 | 24 | 32) { - return Err(bad(format!("{bits} bits per pixel is not 8, 16, 24 or 32"))); - } - let mut fields = [None; 4]; - for (field, mask) in fields.iter_mut().zip(masks) { - *field = Field::new(mask, bits)?; - } - let colour = if gray { fields[0].is_some() } else { fields[..3].iter().any(Option::is_some) }; - if !colour { - return Err(bad("the pixel format has no colour channel masks")); - } - Ok(Encoding::Masks { bytes: bits as usize / 8, gray, fields }) - } - - fn layout(&self) -> ChannelLayout { - match self { - Encoding::Masks { gray: true, fields, .. } if fields[3].is_some() => ChannelLayout::GrayA, - Encoding::Masks { gray: true, .. } => ChannelLayout::Gray, - Encoding::Masks { fields, .. } if fields[3].is_none() => ChannelLayout::Rgb, - _ => ChannelLayout::Rgba, - } - } - - /// Stored row stride and byte size of the top mip level (block rows for BC). - fn level_layout(&self, width: u32, height: u32, pitch: Option) -> Result<(usize, usize), CodecError> { - let overflow = || bad("pixel data size overflow"); - let (w, h) = (usize::try_from(width).map_err(|_| overflow())?, usize::try_from(height).map_err(|_| overflow())?); - let (row_bytes, rows) = match self { - Encoding::Masks { bytes, .. } => { - let packed = w.checked_mul(*bytes).ok_or_else(overflow)?; - let row_bytes = match pitch { - Some(pitch) => usize::try_from(pitch).map_err(|_| overflow())?, - None => packed, - }; - if row_bytes < packed { - return Err(bad(format!("row pitch {row_bytes} is smaller than the {packed}-byte pixel row"))); - } - (row_bytes, h) - } - Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 => { - let block = if matches!(self, Encoding::Bc1) { 8 } else { 16 }; - (w.div_ceil(4).checked_mul(block).ok_or_else(overflow)?, h.div_ceil(4)) - } - }; - let size = row_bytes.checked_mul(rows).ok_or_else(overflow)?; - Ok((row_bytes, size)) - } -} - -/// The legacy pixel format: a FourCC, or channel masks. -fn legacy_encoding(b: &[u8]) -> Result { - let (flags, fourcc, bits) = (le32(b, 80)?, le32(b, 84)?, le32(b, 88)?); - let alpha = if flags & DDPF_ALPHAPIXELS != 0 { le32(b, 104)? } else { 0 }; - if flags & DDPF_FOURCC != 0 { - return match &fourcc.to_le_bytes() { - b"DXT1" => Ok(Encoding::Bc1), - b"DXT3" => Ok(Encoding::Bc2), - b"DXT5" => Ok(Encoding::Bc3), - b"DXT2" | b"DXT4" => Err(unsupported("premultiplied-alpha DXT2/DXT4 textures are not supported")), - _ => Err(unsupported(format!("compression `{}` is not supported (DXT1, DXT3 and DXT5 are)", fourcc_name(fourcc)))), - }; - } - if flags & DDPF_RGB != 0 { - return Encoding::masks(bits, [le32(b, 92)?, le32(b, 96)?, le32(b, 100)?, alpha], false); - } - if flags & DDPF_LUMINANCE != 0 { - return Encoding::masks(bits, [le32(b, 92)?, 0, 0, alpha], true); - } - Err(unsupported(format!("pixel format flags {flags:#x} are not RGB, luminance or a supported compression"))) -} - -/// The DX10 header's DXGI format, refusing anything but a single 2D texture. -fn dx10_encoding(b: &[u8]) -> Result { - let (dxgi, dimension, misc, array) = (le32(b, HEADER)?, le32(b, HEADER + 4)?, le32(b, HEADER + 8)?, le32(b, HEADER + 12)?); - if misc & MISC_TEXTURECUBE != 0 { - return Err(unsupported("cubemaps are not supported")); - } - if dimension != DIMENSION_TEXTURE2D { - return Err(unsupported(format!("only 2D textures are supported (resource dimension {dimension})"))); - } - if array > 1 { - return Err(unsupported(format!("texture arrays are not supported ({array} textures)"))); - } - const RGBA: [u32; 4] = [0xff, 0xff00, 0xff_0000, 0xff00_0000]; - const BGRA: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0xff00_0000]; - const BGRX: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0]; - match dxgi { - 27..=29 => Encoding::masks(32, RGBA, false), - 87 | 90 | 91 => Encoding::masks(32, BGRA, false), - 88 | 92 | 93 => Encoding::masks(32, BGRX, false), - 70..=72 => Ok(Encoding::Bc1), - 73..=75 => Ok(Encoding::Bc2), - 76..=78 => Ok(Encoding::Bc3), - _ => Err(unsupported(format!("DXGI format {dxgi} is not supported (BC1, BC2, BC3 and 8-bit RGBA or BGRA are)"))), - } + craft_dds::has_additional_images(bytes).map_err(error) } pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { - if !b.starts_with(b"DDS ") { - return Err(bad("missing the `DDS ` signature")); - } - if le32(b, 4)? != 124 { - return Err(bad("header size is not 124")); - } - let (flags, height, width, depth, caps2) = (le32(b, 8)?, le32(b, 12)?, le32(b, 16)?, le32(b, 24)?, le32(b, 112)?); - if caps2 & DDSCAPS2_CUBEMAP != 0 { - return Err(unsupported("cubemaps are not supported")); - } - if caps2 & DDSCAPS2_VOLUME != 0 || (flags & DDSD_DEPTH != 0 && depth > 1) { - return Err(unsupported("volume textures are not supported")); - } - let dx10 = le32(b, 80)? & DDPF_FOURCC != 0 && &le32(b, 84)?.to_le_bytes() == b"DX10"; - let (encoding, start) = if dx10 { (dx10_encoding(b)?, HEADER + DX10_HEADER) } else { (legacy_encoding(b)?, HEADER) }; - let layout = encoding.layout(); - limits.check(width, height, layout, SampleType::U8)?; - // The same header field is a total level size for BC, but a row stride when DDSD_PITCH is set. - let pitch = if flags & DDSD_PITCH != 0 { Some(le32(b, 20)?) } else { None }; - let (row_pitch, size) = encoding.level_layout(width, height, pitch)?; - let data = b.get(start..).and_then(|d| d.get(..size)).ok_or_else(|| bad(format!("truncated pixel data: {size} bytes needed")))?; - let (w, h) = (width as usize, height as usize); - let channels = layout.channels(); - let row_size = w.checked_mul(channels).ok_or_else(|| bad("pixel size overflow"))?; - let total = row_size.checked_mul(h).ok_or_else(|| bad("pixel size overflow"))?; - let mut pixels = vec![0u8; total]; - match encoding { - Encoding::Masks { bytes, gray, fields } => { - for (src_row, dst_row) in data.chunks_exact(row_pitch).zip(pixels.chunks_exact_mut(row_size)) { - // Stop at the output width, leaving any stored row padding unread. - for (src, dst) in src_row.chunks_exact(bytes).zip(dst_row.chunks_exact_mut(channels)) { - let pixel = src.iter().rev().fold(0u32, |v, &byte| v << 8 | u32::from(byte)); - let channel = |i: usize| fields[i].map_or(0, |f| f.get(pixel)); - let values = if gray { [channel(0), channel(3), 0, 0] } else { [channel(0), channel(1), channel(2), channel(3)] }; - dst.copy_from_slice(&values[..channels]); - } - } - } - Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 => { - let block_size = if matches!(encoding, Encoding::Bc1) { 8 } else { 16 }; - let blocks_x = w.div_ceil(4); - for (i, block) in data.chunks_exact(block_size).enumerate() { - let texels = match encoding { - Encoding::Bc1 => bc1(block, true), - Encoding::Bc2 => with_alpha(bc1(block.get(8..).unwrap_or_default(), false), bc2_alpha(block)), - _ => with_alpha(bc1(block.get(8..).unwrap_or_default(), false), bc3_alpha(block)), - }; - let (bx, by) = ((i % blocks_x) * 4, (i / blocks_x) * 4); - for (t, texel) in texels.iter().enumerate() { - let (x, y) = (bx + t % 4, by + t / 4); - if x < w && y < h { - let at = (y * w + x) * 4; - if let Some(dst) = pixels.get_mut(at..at + 4) { - dst.copy_from_slice(texel); - } - } - } - } - } - } - Image::from_u8(width, height, layout, pixels) -} - -/// A BC1 colour block. BC2 and BC3 colour blocks always have four colours; only BC1's -/// `c0 <= c1` order selects three colours and transparent black. -fn bc1(block: &[u8], one_bit_alpha: bool) -> [[u8; 4]; 16] { - let byte = |i: usize| block.get(i).copied().unwrap_or(0); - let (c0, c1) = (u16::from_le_bytes([byte(0), byte(1)]), u16::from_le_bytes([byte(2), byte(3)])); - let palette = dds_bc::colour_palette(c0, c1, c0 > c1 || !one_bit_alpha); - let indices = u32::from_le_bytes([byte(4), byte(5), byte(6), byte(7)]); - std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) -} - -/// BC2: four explicit bits of alpha per texel. -fn bc2_alpha(block: &[u8]) -> [u8; 16] { - let bits = u64::from_le_bytes(std::array::from_fn(|i| block.get(i).copied().unwrap_or(0))); - std::array::from_fn(|t| ((bits >> (4 * t)) & 0xf) as u8 * 17) -} - -/// BC3: two alpha endpoints and a 3-bit index per texel into eight values, or into six plus -/// 0 and 255 when `a0 <= a1`. -fn bc3_alpha(block: &[u8]) -> [u8; 16] { - let byte = |i: usize| block.get(i).copied().unwrap_or(0); - let palette = dds_bc::alpha_palette(byte(0), byte(1)); - let bits = u64::from_le_bytes([byte(2), byte(3), byte(4), byte(5), byte(6), byte(7), 0, 0]); - std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize]) -} - -fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] { - for (texel, a) in texels.iter_mut().zip(alpha) { - texel[3] = a; - } - texels -} - -const DDSD_CAPS: u32 = 0x1; -const DDSD_HEIGHT: u32 = 0x2; -const DDSD_WIDTH: u32 = 0x4; -const DDSD_PITCH: u32 = 0x8; -const DDSD_PIXELFORMAT: u32 = 0x1000; -const DDSD_MIPMAPCOUNT: u32 = 0x2_0000; -const DDSD_LINEARSIZE: u32 = 0x8_0000; -const DDSCAPS_COMPLEX: u32 = 0x8; -const DDSCAPS_TEXTURE: u32 = 0x1000; -const DDSCAPS_MIPMAP: u32 = 0x40_0000; - -fn encode_err(reason: impl std::fmt::Display) -> CodecError { - CodecError::encode(Format::Dds, reason) -} - -/// How a written texture stores its pixels. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Store { - /// 8-bit luminance. - Luminance, - /// 8-bit luminance, then 8-bit alpha. - LuminanceAlpha, - /// Blue, green, red and an unused byte (written as 255, so a reader that takes it for - /// alpha still sees an opaque texture). - Bgrx, - Bgra, - Bc1, - Bc2, - Bc3, -} - -impl Store { - /// The storage for an image of `layout`, as [`crate::fidelity::plan`] chose it. - fn new(compression: DdsCompression, layout: ChannelLayout) -> Result { - Ok(match (compression, layout) { - (DdsCompression::None, ChannelLayout::Gray) => Store::Luminance, - (DdsCompression::None, ChannelLayout::GrayA) => Store::LuminanceAlpha, - (DdsCompression::None, ChannelLayout::Rgb) => Store::Bgrx, - (DdsCompression::None, ChannelLayout::Rgba) => Store::Bgra, - (DdsCompression::Bc1, ChannelLayout::Rgba) => Store::Bc1, - (DdsCompression::Bc2, ChannelLayout::Rgba) => Store::Bc2, - (DdsCompression::Bc3, ChannelLayout::Rgba) => Store::Bc3, - (_, layout) => return Err(encode_err(format!("{layout:?} pixels can't be written as `{}`", compression.name()))), - }) - } - - /// Bytes per pixel, or per 4×4 block for a block compression. - fn unit(self) -> usize { - match self { - Store::Luminance => 1, - Store::LuminanceAlpha => 2, - Store::Bgrx | Store::Bgra => 4, - Store::Bc1 => 8, - Store::Bc2 | Store::Bc3 => 16, - } - } - - fn is_block(self) -> bool { - matches!(self, Store::Bc1 | Store::Bc2 | Store::Bc3) - } - - /// Bytes of one row of pixels (or of 4×4 blocks) of a level `width` wide. - fn row_bytes(self, width: usize) -> Option { - if self.is_block() { width.div_ceil(4).checked_mul(self.unit()) } else { width.checked_mul(self.unit()) } - } - - fn level_bytes(self, width: usize, height: usize) -> Option { - let rows = if self.is_block() { height.div_ceil(4) } else { height }; - self.row_bytes(width)?.checked_mul(rows) - } - - /// DDS_PIXELFORMAT: flags, FourCC, bits per pixel and the red, green, blue and alpha masks. - fn pixel_format(self) -> (u32, [u8; 4], u32, [u32; 4]) { - match self { - Store::Luminance => (DDPF_LUMINANCE, [0; 4], 8, [0xff, 0, 0, 0]), - Store::LuminanceAlpha => (DDPF_LUMINANCE | DDPF_ALPHAPIXELS, [0; 4], 16, [0xff, 0, 0, 0xff00]), - Store::Bgrx => (DDPF_RGB, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0]), - Store::Bgra => (DDPF_RGB | DDPF_ALPHAPIXELS, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]), - Store::Bc1 => (DDPF_FOURCC, *b"DXT1", 0, [0; 4]), - Store::Bc2 => (DDPF_FOURCC, *b"DXT3", 0, [0; 4]), - Store::Bc3 => (DDPF_FOURCC, *b"DXT5", 0, [0; 4]), - } - } -} - -/// Levels in a full mip chain: the larger side halves down to 1. -fn mip_levels(width: u32, height: u32) -> u32 { - 32 - width.max(height).max(1).leading_zeros() -} - -fn half((w, h): (usize, usize)) -> (usize, usize) { - ((w / 2).max(1), (h / 2).max(1)) + let texture = Texture::parse(b).map_err(error)?; + let layout = channel_layout(texture.layout()); + limits.check(texture.width(), texture.height(), layout, SampleType::U8)?; + let pixels = texture.decode_with_limit(limits.max_alloc).map_err(error)?; + Image::from_u8(texture.width(), texture.height(), layout, pixels) } pub(crate) fn encode(image: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { let img = image.converted(plan.layout, SampleType::U8); - let pixels = img.as_u8().ok_or_else(|| encode_err("the image was not converted to 8 bits per channel"))?; - let store = Store::new(opts.dds.compression, img.layout())?; - let (width, height) = img.dimensions(); - let levels = if opts.dds.mipmaps { mip_levels(width, height) } else { 1 }; - let top = (width as usize, height as usize); - // Every level's size, checked before anything is allocated. - let mut sizes = Vec::new(); - let mut size = top; - for _ in 0..levels { - sizes.push(store.level_bytes(size.0, size.1).ok_or_else(|| encode_err("texture size overflow"))?); - size = half(size); - } - let total = sizes.iter().try_fold(HEADER, |total, &s| total.checked_add(s)).ok_or_else(|| encode_err("texture size overflow"))?; - let header = header(width, height, store, levels, sizes.first().copied().unwrap_or(0))?; - let mut out = crate::options::alloc_zeroed::(total)?; - out.get_mut(..HEADER).ok_or_else(|| encode_err("output buffer too small"))?.copy_from_slice(&header); - - let channels = img.layout().channels(); - let mut level = Cow::Borrowed(pixels); - let (mut size, mut at) = (top, HEADER); - for (i, &bytes) in sizes.iter().enumerate() { - let dst = out.get_mut(at..at + bytes).ok_or_else(|| encode_err("output buffer too small"))?; - write_level(store, &level, size, dst)?; - at += bytes; - if i + 1 < sizes.len() { - let next = half(size); - level = Cow::Owned(downsample(&level, size, next, channels)?); - size = next; - } - } - Ok(out) -} - -/// The `DDS ` signature and DDS_HEADER. `top` is the top level's size in bytes. -fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Result<[u8; HEADER], CodecError> { - let mut b = [0u8; HEADER]; - let mut put = |at: usize, v: u32| { - if let Some(d) = b.get_mut(at..at + 4) { - d.copy_from_slice(&v.to_le_bytes()); - } + let pixels = img.as_u8().ok_or_else(|| CodecError::encode(Format::Dds, "the image was not converted to 8 bits per channel"))?; + let layout = match img.layout() { + ChannelLayout::Gray => Layout::Gray, + ChannelLayout::GrayA => Layout::GrayA, + ChannelLayout::Rgb => Layout::Rgb, + ChannelLayout::Rgba => Layout::Rgba, + // `fidelity::plan` only picks the four layouts above for DDS. + other => return Err(CodecError::encode(Format::Dds, format!("{other:?} pixels can't be written as `{}`", opts.dds.compression.name()))), }; - // Uncompressed: the pitch of one row. Compressed: the whole top level (its "linear size"). - let (size_flag, pitch_or_size) = if store.is_block() { (DDSD_LINEARSIZE, Some(top)) } else { (DDSD_PITCH, store.row_bytes(width as usize)) }; - let pitch_or_size = pitch_or_size - .and_then(|v| u32::try_from(v).ok()) - .ok_or_else(|| encode_err(format!("a {width}x{height} level is too large for a DDS header")))?; - let mipmapped = levels > 1; - put(4, 124); - put(8, DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | size_flag | if mipmapped { DDSD_MIPMAPCOUNT } else { 0 }); - put(12, height); - put(16, width); - put(20, pitch_or_size); - put(28, levels); - let (flags, fourcc, bits, masks) = store.pixel_format(); - put(76, 32); - put(80, flags); - put(84, u32::from_le_bytes(fourcc)); - put(88, bits); - for (i, mask) in masks.into_iter().enumerate() { - put(92 + 4 * i, mask); - } - put(108, DDSCAPS_TEXTURE | if mipmapped { DDSCAPS_COMPLEX | DDSCAPS_MIPMAP } else { 0 }); - b[..4].copy_from_slice(b"DDS "); - Ok(b) -} - -/// Runs `f` on each `len`-byte row of `out` with its index, in parallel on native targets. -fn rows(out: &mut [u8], len: usize, f: impl Fn(usize, &mut [u8]) + Send + Sync) { - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - out.par_chunks_mut(len.max(1)).enumerate().for_each(|(i, row)| f(i, row)); - } - #[cfg(target_arch = "wasm32")] - for (i, row) in out.chunks_mut(len.max(1)).enumerate() { - f(i, row); - } -} - -/// Writes one level of `width` × `height` pixels (in the image's layout) into `dst`. -fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst: &mut [u8]) -> Result<(), CodecError> { - let row_bytes = store.row_bytes(width).ok_or_else(|| encode_err("texture size overflow"))?; - match store { - Store::Luminance | Store::LuminanceAlpha => { - // The image's gray (and alpha) samples, in the same order. - let src = pixels.get(..dst.len()).ok_or_else(|| encode_err("the level is smaller than its size"))?; - dst.copy_from_slice(src); - } - Store::Bgrx | Store::Bgra => { - let channels = if store == Store::Bgra { 4 } else { 3 }; - rows(dst, row_bytes, |y, row| { - let src = pixels.get(y * width * channels..).unwrap_or_default(); - for (d, s) in row.as_chunks_mut::<4>().0.iter_mut().zip(src.chunks_exact(channels)) { - let byte = |i: usize| s.get(i).copied().unwrap_or(255); - *d = [byte(2), byte(1), byte(0), byte(3)]; - } - }); - } - Store::Bc1 | Store::Bc2 | Store::Bc3 => { - let (texels, _) = pixels.as_chunks::<4>(); - rows(dst, row_bytes, |by, row| { - for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() { - let (block, inside) = gather(texels, (width, height), bx, by); - let encoded: &[u8] = match store { - Store::Bc1 => &dds_bc::encode_bc1(&block, inside), - Store::Bc2 => &dds_bc::encode_bc2(&block, inside), - _ => &dds_bc::encode_bc3(&block, inside), - }; - for (d, s) in d.iter_mut().zip(encoded) { - *d = *s; - } - } - }); - } - } - Ok(()) -} - -/// Block (`bx`, `by`)'s texels, and which of them lie inside the image. -fn gather(texels: &[[u8; 4]], (width, height): (usize, usize), bx: usize, by: usize) -> (Block, Mask) { - let mut block = [[0u8; 4]; 16]; - let mut inside: Mask = 0; - for (t, texel) in block.iter_mut().enumerate() { - let (x, y) = (bx * 4 + t % 4, by * 4 + t / 4); - if x < width - && y < height - && let Some(p) = texels.get(y * width + x) - { - *texel = *p; - inside |= 1 << t; - } - } - (block, inside) -} - -/// The next mip level: each pixel the average of the 2×2 pixels it covers, or of 2×3, 3×2 or -/// 3×3 along the last column and row of an odd-sized level, so no pixel is dropped. -fn downsample(src: &[u8], (w, h): (usize, usize), (nw, nh): (usize, usize), channels: usize) -> Result, CodecError> { - let len = nw.checked_mul(nh).and_then(|n| n.checked_mul(channels)).ok_or_else(|| encode_err("mip level size overflow"))?; - let mut dst = crate::options::alloc_zeroed::(len)?; - let span = |i: usize, n: usize, size: usize| 2 * i..=if i + 1 == n { size.saturating_sub(1) } else { 2 * i + 1 }; - rows(&mut dst, nw * channels, |y, row| { - let ys = span(y, nh, h); - for (x, px) in row.chunks_exact_mut(channels.max(1)).enumerate() { - let xs = span(x, nw, w); - for (c, v) in px.iter_mut().enumerate() { - let (mut sum, mut n) = (0u32, 0u32); - for sy in ys.clone() { - for sx in xs.clone() { - if let Some(&s) = src.get((sy * w + sx) * channels + c) { - sum += u32::from(s); - n += 1; - } - } - } - *v = ((sum + n / 2) / n.max(1)) as u8; - } - } - }); - Ok(dst) + let (width, height) = img.dimensions(); + craft_dds::encode(width, height, layout, pixels, opts.dds).map_err(error) } diff --git a/crates/image-codecs/src/codecs/tiff.rs b/crates/image-codecs/src/codecs/tiff.rs index bf59157eb..0f53bb3da 100644 --- a/crates/image-codecs/src/codecs/tiff.rs +++ b/crates/image-codecs/src/codecs/tiff.rs @@ -207,8 +207,10 @@ fn camera_raw_mode(b: &[u8], legacy: bool) -> bool { } TAG_SUB_IFDS if count == 1 => queue.extend(value(e)), TAG_SUB_IFDS => { - // More than one offset: they are stored at the entry's offset. - let at = u32_at(e.saturating_add(8)).unwrap_or(0) as usize; + // More than one offset: they are stored at the entry's offset. A cut-off + // offset field means no array, not one at the start of the file. + let Some(at) = u32_at(e.saturating_add(8)) else { continue }; + let at = at as usize; for k in 0..count.min(8) as usize { queue.extend(u32_at(at.saturating_add(4 * k))); } diff --git a/crates/image-codecs/src/fidelity.rs b/crates/image-codecs/src/fidelity.rs index 12c285d7b..52d6eaa23 100644 --- a/crates/image-codecs/src/fidelity.rs +++ b/crates/image-codecs/src/fidelity.rs @@ -4,7 +4,7 @@ use std::fmt; -use crate::codecs::dpx; +use crate::codecs::{dds, dpx}; use crate::format::{Format, caps}; use crate::image::{ChannelLayout, Image, SampleType}; use crate::options::{DdsCompression, EncodeOptions}; @@ -45,7 +45,8 @@ pub enum FidelityWarning { ColorToGray, /// The image will be quantized to a 256-colour palette. PaletteQuantized, - /// The format's encoder is lossy. + /// The format's encoder is lossy. DDS BC5 also keeps only red and green: blue is dropped and + /// reads back as 0 (for a normal map, the renderer rebuilds Z from X and Y). LossyCompression, IccDropped, ExifDropped, @@ -175,8 +176,12 @@ pub(crate) fn plan(image: &Image, format: Format, opts: &EncodeOptions) -> Plan }, // CIELab has no float form: float Lab is written with 16 bits. Format::Tiff if layout.is_lab() && sample.is_float() => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: SampleType::U16 }, - // A block-compressed DDS stores RGBA whatever the source; uncompressed keeps gray and RGB. - Format::Dds if opts.dds.compression.is_block() => Plan { layout: ChannelLayout::Rgba, sample: SampleType::U8 }, + // A block-compressed DDS stores what its compression holds whatever the source: gray for + // BC4, red and green for BC5 (written from RGB, blue dropped), RGBA for BC1 to BC3. + // Uncompressed keeps gray and RGB. + Format::Dds if opts.dds.compression.is_block() => { + Plan { layout: opts.dds.compression.layout().map_or(ChannelLayout::Rgba, dds::channel_layout), sample: SampleType::U8 } + } _ => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: pick_sample(sample, c.depths) }, } } diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index 983dab3dd..1535c229e 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -19,7 +19,7 @@ pub enum Format { Pcx, /// X PixMap icons (XPM2 plain text and XPM3 C-string arrays). Xpm, - /// DirectDraw Surface: a 2D texture, uncompressed or BC1–BC3. Reading takes the top mip + /// DirectDraw Surface: a 2D texture, uncompressed or BC1–BC5. Reading takes the top mip /// level; writing can add the full mip chain ([`crate::DdsOptions`]). Dds, Qoi, diff --git a/crates/image-codecs/src/options.rs b/crates/image-codecs/src/options.rs index 71f6030b3..d0ef8ee9a 100644 --- a/crates/image-codecs/src/options.rs +++ b/crates/image-codecs/src/options.rs @@ -235,60 +235,8 @@ impl DpxBits { } } -/// How a DDS texture stores its pixels. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum DdsCompression { - /// Uncompressed, 8 bits per channel: BGRA (BGRX without alpha), or luminance with or - /// without alpha for grayscale. Lossless. - #[default] - None, - /// BC1 (DXT1): 4 bits per pixel. Alpha is on or off: texels under half opacity become - /// transparent black. - Bc1, - /// BC2 (DXT3): 8 bits per pixel, with 4 bits of explicit alpha per texel. - Bc2, - /// BC3 (DXT5): 8 bits per pixel, with smooth interpolated alpha. - Bc3, -} - -impl DdsCompression { - pub const ALL: [DdsCompression; 4] = [DdsCompression::None, DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3]; - - /// The name scripts and the CLI use: `none`, `bc1`, `bc2` or `bc3`. - pub fn name(self) -> &'static str { - match self { - DdsCompression::None => "none", - DdsCompression::Bc1 => "bc1", - DdsCompression::Bc2 => "bc2", - DdsCompression::Bc3 => "bc3", - } - } - - /// [`Self::name`] back to a compression, also taking the DXT names (`dxt1`, `dxt3`, - /// `dxt5`), in any case. Anything else is `None`. - pub fn from_name(name: &str) -> Option { - match name.to_ascii_lowercase().as_str() { - "none" => Some(DdsCompression::None), - "bc1" | "dxt1" => Some(DdsCompression::Bc1), - "bc2" | "dxt3" => Some(DdsCompression::Bc2), - "bc3" | "dxt5" => Some(DdsCompression::Bc3), - _ => None, - } - } - - /// A block compression (lossy), not uncompressed pixels. - pub fn is_block(self) -> bool { - self != DdsCompression::None - } -} - -/// What a DDS file is written with. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct DdsOptions { - pub compression: DdsCompression, - /// Write the full mip chain down to 1×1, each level a box filter of the one above. - pub mipmaps: bool, -} +/// How a DDS texture stores its pixels and whether it carries a mip chain, from [`craft_dds`]. +pub use craft_dds::{DdsCompression, DdsOptions}; /// The longer side, in pixels, at which a TIFF image pyramid stops: the last level written is /// the first one no longer than this ([`EncodeOptions::tiff_pyramid`]). diff --git a/crates/image-codecs/src/webp_probe.rs b/crates/image-codecs/src/webp_probe.rs index 07d6e0269..4a31def00 100644 --- a/crates/image-codecs/src/webp_probe.rs +++ b/crates/image-codecs/src/webp_probe.rs @@ -25,9 +25,10 @@ pub fn header(bytes: &[u8]) -> Result<(u32, u32, u16), CodecError> { if !has_image { return Err(err("no image data")); } - let (w, h) = crate::probe_size(bytes)?; + // Read stored dimensions directly. Undoing probe_size with the compatibility EXIF + // orientation is incorrect when its lenient parser disagrees with the strict one. + let (w, h, _) = crate::codecs::webp::probe(bytes, &crate::Limits::default())?; let orientation = exif.map_or(1, craft_metadata::compat_orientation::orientation); - let (w, h) = if (5..=8).contains(&orientation) { (h, w) } else { (w, h) }; Ok((w, h, orientation)) } @@ -47,6 +48,20 @@ mod tests { assert_eq!(header(&bytes).unwrap(), (2, 3, 6)); } + #[test] + fn malformed_exif_does_not_swap_stored_dimensions() { + let mut image = crate::Image::from_u8(2, 3, crate::ChannelLayout::Rgb, vec![42; 18]).unwrap(); + image.meta.exif = Some(b"II\x2a\x00\x08\x00\x00\x00\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00".to_vec()); + let mut bytes = crate::encode(&image, Format::WebP, &crate::EncodeOptions::default()).unwrap(); + let exif = bytes.windows(4).position(|v| v == b"EXIF").unwrap() + 8; + bytes[exif + 18] = 6; + // Compatibility metadata preserves orientation despite a malformed count; + // the strict orientation used by probe_size rejects it. Stored size is neither. + bytes[exif + 14..exif + 18].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(crate::probe_size(&bytes).unwrap(), (2, 3)); + assert_eq!(header(&bytes).unwrap(), (2, 3, 6)); + } + #[test] fn rejects_missing_and_truncated_image_chunks() { let mut bytes = b"RIFF\x00\x00\x00\x00WEBP".to_vec(); diff --git a/crates/image-codecs/tests/it/dds.rs b/crates/image-codecs/tests/it/dds.rs index 4f766a54c..d174255b2 100644 --- a/crates/image-codecs/tests/it/dds.rs +++ b/crates/image-codecs/tests/it/dds.rs @@ -318,10 +318,112 @@ fn refuses_cubemaps_arrays_and_volumes() { unsupported(&dx10(4, 4, 71, 3, 0, 6), "array"); unsupported(&dx10(4, 4, 71, 4, 0, 1), "2D"); unsupported(&dx10(4, 4, 98, 3, 0, 1), "98"); // BC7_UNORM - unsupported(&compressed(4, 4, b"ATI2"), "ATI2"); + unsupported(&compressed(4, 4, b"ATI3"), "ATI3"); unsupported(&compressed(4, 4, b"DXT2"), "premultiplied"); } +/// A BC4 block of 200 everywhere (eight-value mode, a0 = 200 > a1 = 50, every index 0). +const BC4_200: [u8; 8] = [0xc8, 0x32, 0, 0, 0, 0, 0, 0]; +/// A value block of 250 everywhere (six-value mode, a0 = 10 <= a1 = 250, every index 1). +const VALUES_250: [u8; 8] = [0x0a, 0xfa, 0x49, 0x92, 0x24, 0x49, 0x92, 0x24]; + +/// A DX10 file of one 1x1 level of `dxgi` with DDS_ALPHA_MODE `alpha_mode` (miscFlags2) and zeroed pixel data. +fn dx10_alpha_mode(dxgi: u32, alpha_mode: u32) -> Vec { + let mut b = dx10(1, 1, dxgi, 3, 0, 1); + let n = b.len(); + b[n - 4..].copy_from_slice(&alpha_mode.to_le_bytes()); + b.extend([0u8; 16]); + b +} + +#[test] +fn refuses_premultiplied_alpha_dx10_textures() { + // RGBA, BGRA (typeless, UNORM, sRGB) and BC2/BC3: alpha mode 2 is premultiplied, like DXT2/DXT4. + for dxgi in [27, 28, 29, 87, 90, 91, 73, 74, 75, 76, 77, 78] { + match decode_as(Format::Dds, &dx10_alpha_mode(dxgi, 2)) { + Err(CodecError::Unsupported { reason, .. }) => assert!(reason.contains("premultiplied"), "{dxgi}: {reason}"), + other => panic!("DXGI {dxgi}: {:?}", other.map(|_| ())), + } + } + // Straight, unknown, opaque and custom alpha modes, and formats without alpha, still decode. + for dxgi in [28, 87, 74, 77] { + for mode in [0, 1, 3, 4] { + assert!(decode_as(Format::Dds, &dx10_alpha_mode(dxgi, mode)).is_ok(), "{dxgi} mode {mode}"); + } + } + for dxgi in [88, 71, 80, 83] { + assert!(decode_as(Format::Dds, &dx10_alpha_mode(dxgi, 2)).is_ok(), "{dxgi}"); + } +} + +#[test] +fn decodes_bc4_as_gray_from_every_name() { + // 5×3: two blocks across, one down; the second block's texels outside the image are dropped. + let blocks = [BC4_200, BC4_200].concat(); + let mut files = vec![]; + for fourcc in [b"ATI1", b"BC4U"] { + let mut b = compressed(5, 3, fourcc); + b.extend(&blocks); + files.push((String::from_utf8_lossy(fourcc).into_owned(), b)); + } + for dxgi in [79, 80] { + let mut b = dx10(5, 3, dxgi, 3, 0, 1); // BC4_TYPELESS, BC4_UNORM + b.extend(&blocks); + files.push((format!("DXGI {dxgi}"), b)); + } + for (name, b) in files { + let im = decode(&b).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!((im.dimensions(), im.layout()), ((5, 3), ChannelLayout::Gray), "{name}"); + assert_eq!(im.data(), &[200; 15], "{name}"); + } +} + +#[test] +fn decodes_bc5_as_red_and_green_with_blue_zero() { + let block = [BC4_200, VALUES_250].concat(); + let mut files = vec![]; + // ATI2 is BC5 as Microsoft reads it: red in the first block, not swapped as FFmpeg does. + for fourcc in [b"ATI2", b"BC5U"] { + let mut b = compressed(3, 2, fourcc); + b.extend(&block); + files.push((String::from_utf8_lossy(fourcc).into_owned(), b)); + } + // BC5_TYPELESS (what Pillow writes) and BC5_UNORM. + for dxgi in [82, 83] { + let mut b = dx10(3, 2, dxgi, 3, 0, 1); + b.extend(&block); + files.push((format!("DXGI {dxgi}"), b)); + } + for (name, b) in files { + let im = decode(&b).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!((im.dimensions(), im.layout()), ((3, 2), ChannelLayout::Rgb), "{name}"); + assert!(im.data().chunks(3).all(|p| p == [200, 250, 0]), "{name}: {:?}", &im.data()[..3]); + } +} + +#[test] +fn refuses_signed_bc4_and_bc5() { + for mut b in [compressed(4, 4, b"BC4S"), compressed(4, 4, b"BC5S"), dx10(4, 4, 81, 3, 0, 1), dx10(4, 4, 84, 3, 0, 1)] { + b.extend([0; 16]); + match decode_as(Format::Dds, &b) { + Err(CodecError::Unsupported { reason, .. }) => assert!(reason.contains("SNORM"), "{reason}"), + other => panic!("{other:?}"), + } + } +} + +#[test] +fn truncated_bc4_and_bc5_data_is_refused() { + let mut b = dx10(5, 5, 83, 3, 0, 1); // four 16-byte blocks + b.extend([0x5a; 64]); + assert!(decode(&b).is_ok()); + assert!(matches!(decode_as(Format::Dds, &b[..b.len() - 1]), Err(CodecError::Malformed { .. }))); + let mut b = compressed(5, 5, b"ATI1"); // four 8-byte blocks + b.extend([0x5a; 32]); + assert!(decode(&b).is_ok()); + assert!(matches!(decode_as(Format::Dds, &b[..b.len() - 1]), Err(CodecError::Malformed { .. }))); +} + /// Face declarations matter even when the general cube flag is absent; padding does not. #[test] fn source_probe_distinguishes_extra_faces_from_single_images_and_padding() { diff --git a/crates/image-codecs/tests/it/dds_oracle.rs b/crates/image-codecs/tests/it/dds_oracle.rs new file mode 100644 index 000000000..05d000a73 --- /dev/null +++ b/crates/image-codecs/tests/it/dds_oracle.rs @@ -0,0 +1,520 @@ +//! Byte-for-byte oracle for the DDS reader and writer: SHA-256 digests of what the writer makes +//! for uncompressed, BC1, BC2 and BC3 textures, with and without mip chains, from deterministic +//! synthetic images, and of what the reader decodes from those files and from hand-built files +//! in the other stored layouts. The digests were taken from the code before the block encoder and +//! decoder were sped up; any change to them is a change of output. +//! +//! On a mismatch the test prints every digest it computed in the form of [`PINNED`], so a new +//! table can be pasted in once a change of output is intended. + +use craft_image_codecs::{ChannelLayout, DdsCompression, DdsOptions, EncodeOptions, Format, Image, decode, encode}; +use sha2::{Digest, Sha256}; + +/// `(case, SHA-256)`, taken from the code before the speed-ups. +const PINNED: &[(&str, &str)] = &[ + ("Rgba-517x389-none-mips0-encode", "e2aee5dcc86cc36e9735cb75e61852324210960092bfb2f2aec6cee9ba54ad16"), + ("Rgba-517x389-none-mips0-decode", "e0d9e319f260fa29481495313cfa8c3d224a27ad311e7aabd32f7cda8dfb81d2"), + ("Rgba-517x389-none-mips1-encode", "7611e8174d32962c9643e8f3208b8f30eba2cb85cfe16538c4321e419f3a98ce"), + ("Rgba-517x389-none-mips1-decode", "e0d9e319f260fa29481495313cfa8c3d224a27ad311e7aabd32f7cda8dfb81d2"), + ("Rgba-517x389-bc1-mips0-encode", "b6883d729a1eebbdc96176c9264754378d4f7f6bc19d355a12419c0ccfd3ac2a"), + ("Rgba-517x389-bc1-mips0-decode", "e23704d5f72ba4f2c63d815d5bff3d4c79433fa38122e1e21f1003fa1b12476a"), + ("Rgba-517x389-bc1-mips1-encode", "554ed42ba6b7c206f779324670629538d8ce12d85ef495ad36954aae2b952917"), + ("Rgba-517x389-bc1-mips1-decode", "e23704d5f72ba4f2c63d815d5bff3d4c79433fa38122e1e21f1003fa1b12476a"), + ("Rgba-517x389-bc2-mips0-encode", "473f389b464d2f74b05d44ab2d8c31d4d4cd64648d389e4fe27c27491003821b"), + ("Rgba-517x389-bc2-mips0-decode", "9d81c15d7f5f0dbc897063726fac6e2f3863818346e1c878326c22ed332ae328"), + ("Rgba-517x389-bc2-mips1-encode", "1eb8c1a73cb4e6965c60a5ca4322fb66f071cad7439d97d77dbea1a46231724a"), + ("Rgba-517x389-bc2-mips1-decode", "9d81c15d7f5f0dbc897063726fac6e2f3863818346e1c878326c22ed332ae328"), + ("Rgba-517x389-bc3-mips0-encode", "0b133915d5ac0376f8b4425cb2dd4a1ace609cf7c1d635be0ff46a37529363e2"), + ("Rgba-517x389-bc3-mips0-decode", "9c5aeecab34af4c04dd603cf5c379060e6615c07df05ae4e93058bca13a61bc9"), + ("Rgba-517x389-bc3-mips1-encode", "130e5657e870ee5c03bcfcc2c5e2befbc8a67fc0df1b7e7b71dbb67cc3f0b5e7"), + ("Rgba-517x389-bc3-mips1-decode", "9c5aeecab34af4c04dd603cf5c379060e6615c07df05ae4e93058bca13a61bc9"), + ("Rgb-517x389-none-mips0-encode", "6df9ec01a5ae0a8e0fe3b563a7ff670477446682cadd21c24ca5e0cff2b41ed8"), + ("Rgb-517x389-none-mips0-decode", "7f181edc81e2e38d56c2ed5c81edf480d52caa746e0bef90f0070e171ead89d1"), + ("Rgb-517x389-none-mips1-encode", "5a48af2cfa7d48455fe49105fc5d0173c6f4fd8187483af923f0af2fbf0af9ef"), + ("Rgb-517x389-none-mips1-decode", "7f181edc81e2e38d56c2ed5c81edf480d52caa746e0bef90f0070e171ead89d1"), + ("Rgb-517x389-bc1-mips0-encode", "1e8bf3d0ba485d0892ce771698868bf7029d2c4e63057f327ae3ab39bc57cd4a"), + ("Rgb-517x389-bc1-mips0-decode", "96feb4a7a3b7416ebc0d5e42271a9d6304131e6cbed25f745d3eef6a40279f8d"), + ("Rgb-517x389-bc1-mips1-encode", "76f866a8bbb0b3cad335c604cba97d173d01dcbfff4c8930a1d8af7c60924494"), + ("Rgb-517x389-bc1-mips1-decode", "96feb4a7a3b7416ebc0d5e42271a9d6304131e6cbed25f745d3eef6a40279f8d"), + ("Rgb-517x389-bc2-mips0-encode", "a8eaab96cf9c6f7926526069ed71f5df8c7f7d43f3ef40a85f1403639c09ac97"), + ("Rgb-517x389-bc2-mips0-decode", "8e00407a44922477b8d7c05b371f05c18ac3471095990b44aba438bf39db57b2"), + ("Rgb-517x389-bc2-mips1-encode", "d6fee09087b9a4c9a055051e7aa212a9a0a3b2660e1dfa49697c6fc9754a9aae"), + ("Rgb-517x389-bc2-mips1-decode", "8e00407a44922477b8d7c05b371f05c18ac3471095990b44aba438bf39db57b2"), + ("Rgb-517x389-bc3-mips0-encode", "2e177ad42c89f6662ebf2b834b691e10bfaea32a565b740e1bd48c7e4b39cb68"), + ("Rgb-517x389-bc3-mips0-decode", "8e00407a44922477b8d7c05b371f05c18ac3471095990b44aba438bf39db57b2"), + ("Rgb-517x389-bc3-mips1-encode", "0b53960adcf0844b47ed5927862901c95fb632af4e85cd94b5ceae59eccd78cd"), + ("Rgb-517x389-bc3-mips1-decode", "8e00407a44922477b8d7c05b371f05c18ac3471095990b44aba438bf39db57b2"), + ("GrayA-517x389-none-mips0-encode", "3f8e56201cb76990b3e25b62631666ac113a5340877acd57cdcb1c229127d3f4"), + ("GrayA-517x389-none-mips0-decode", "43503ba84a7d7579b1ebbe6ba522146f5e63f0116f8dd0eba095364cfba37c5d"), + ("GrayA-517x389-none-mips1-encode", "6282214743c82e3f74f2347c859ecfd79447cfbc87a2016a238e714f2d150b87"), + ("GrayA-517x389-none-mips1-decode", "43503ba84a7d7579b1ebbe6ba522146f5e63f0116f8dd0eba095364cfba37c5d"), + ("GrayA-517x389-bc1-mips0-encode", "32d7065b40986561349f0d76db148b1b62afedb1ce8be6a4e0b209c60c9d861f"), + ("GrayA-517x389-bc1-mips0-decode", "1cc1cbd355033b5674cc1000b879d4dc8cbb4b53b8dd38d90d8b439550e2be7c"), + ("GrayA-517x389-bc1-mips1-encode", "4b5e5c9db8ec9847b55e0c51b2e1c1cb41bb277517ef5a7bf59ace7581a7696a"), + ("GrayA-517x389-bc1-mips1-decode", "1cc1cbd355033b5674cc1000b879d4dc8cbb4b53b8dd38d90d8b439550e2be7c"), + ("GrayA-517x389-bc2-mips0-encode", "91fd37653f090668328d8feff0407c5998ef2ab96d220bd49e311faf7d768e00"), + ("GrayA-517x389-bc2-mips0-decode", "ac73339602e5062f78cf76694bde0a4ca538b355170eb424f0bd1cf7d2c12096"), + ("GrayA-517x389-bc2-mips1-encode", "05d77863968b0086ddf4a1c21ccbc8e1f2d9638ed4dffd114107a1d793ea3311"), + ("GrayA-517x389-bc2-mips1-decode", "ac73339602e5062f78cf76694bde0a4ca538b355170eb424f0bd1cf7d2c12096"), + ("GrayA-517x389-bc3-mips0-encode", "bb4057b77e0fa2959d6e79b77ff67090c9dd4d08f3c105b57ebbaea214ffc8c7"), + ("GrayA-517x389-bc3-mips0-decode", "fdcbd158c32404d09cf1ee38005b2870882e620bcd67c77332d492d07099d665"), + ("GrayA-517x389-bc3-mips1-encode", "65b2021ea2a385b349d2a6f3a44305e3655f35f3bee39fba5d177bb8c7a5d66a"), + ("GrayA-517x389-bc3-mips1-decode", "fdcbd158c32404d09cf1ee38005b2870882e620bcd67c77332d492d07099d665"), + ("Gray-517x389-none-mips0-encode", "fc6cf28e9220780d752ac3be0c9b9bf75412dbea4a54ab603577f78000f235d3"), + ("Gray-517x389-none-mips0-decode", "13df79103435da32999dff6deac57b02a872aef3fe7dafe580625a554258db30"), + ("Gray-517x389-none-mips1-encode", "e6f1bb2eb28353a1ead1b72e6e0c78f9490f9e933ee2fe464044ba2804d0a595"), + ("Gray-517x389-none-mips1-decode", "13df79103435da32999dff6deac57b02a872aef3fe7dafe580625a554258db30"), + ("Gray-517x389-bc1-mips0-encode", "ba3b1a2567ff1571dfb855b7c5ff8e2da276eb80f5f97db0fae661449bb51822"), + ("Gray-517x389-bc1-mips0-decode", "7df1ebd46f395e515af2763a0bf7189072a64f20ff811973098ea109df1ed832"), + ("Gray-517x389-bc1-mips1-encode", "e34896e52b393aa3035e641b43881df1a25ae4aa6261c9bdca34889ec42ea6ac"), + ("Gray-517x389-bc1-mips1-decode", "7df1ebd46f395e515af2763a0bf7189072a64f20ff811973098ea109df1ed832"), + ("Gray-517x389-bc2-mips0-encode", "2ebe06ad3ca05dc993a60c58dbae1d36c56516147176b4799648f534e9318b3a"), + ("Gray-517x389-bc2-mips0-decode", "2adde466f9a4c2c4905d50490bbed4cd5c4de0e3b951d63028702f7ab51d7927"), + ("Gray-517x389-bc2-mips1-encode", "8730c500b41e9b628cab1c789b2e2a2e4a4ad0350b6c3faaca5e3acd8b423ca7"), + ("Gray-517x389-bc2-mips1-decode", "2adde466f9a4c2c4905d50490bbed4cd5c4de0e3b951d63028702f7ab51d7927"), + ("Gray-517x389-bc3-mips0-encode", "e8b62246e29504bbbc92f1c5344846577232e2c12f5c6ab6fae68199bbcf5c3a"), + ("Gray-517x389-bc3-mips0-decode", "2adde466f9a4c2c4905d50490bbed4cd5c4de0e3b951d63028702f7ab51d7927"), + ("Gray-517x389-bc3-mips1-encode", "2b1122c5091c8a62c897fa4a133b2a21d19ec14a3ec2c5e0d4855570824e6211"), + ("Gray-517x389-bc3-mips1-decode", "2adde466f9a4c2c4905d50490bbed4cd5c4de0e3b951d63028702f7ab51d7927"), + ("Rgba-1x1-none-mips0-encode", "c059322936202ed846ae95243325c1756b3ca2734a310b9b58e957e7f6ecb65c"), + ("Rgba-1x1-none-mips0-decode", "ac6d8249b868a4df487ad3d4bc2bffa4ec32afed5bb89bcb916dc390872c00a4"), + ("Rgba-1x1-none-mips1-encode", "c059322936202ed846ae95243325c1756b3ca2734a310b9b58e957e7f6ecb65c"), + ("Rgba-1x1-none-mips1-decode", "ac6d8249b868a4df487ad3d4bc2bffa4ec32afed5bb89bcb916dc390872c00a4"), + ("Rgba-1x1-bc1-mips0-encode", "b128a04da98b6d855fd98c6908f9ba47d0acf2e79c1b39d0cf3e5787ee52b23c"), + ("Rgba-1x1-bc1-mips0-decode", "2c1567f9329e7d7046ebcba26c8b66a872a36d2140c47be6d8ee3fd1bdc7aa26"), + ("Rgba-1x1-bc1-mips1-encode", "b128a04da98b6d855fd98c6908f9ba47d0acf2e79c1b39d0cf3e5787ee52b23c"), + ("Rgba-1x1-bc1-mips1-decode", "2c1567f9329e7d7046ebcba26c8b66a872a36d2140c47be6d8ee3fd1bdc7aa26"), + ("Rgba-1x1-bc2-mips0-encode", "d53707f0da90291d459df619c204c09d0e5537b96055b7c5a7eebb164965a30c"), + ("Rgba-1x1-bc2-mips0-decode", "e41eb1f8866a8a844c5627ec9e119ea9b5b2c2afb62c2cc40d0b3463e191181f"), + ("Rgba-1x1-bc2-mips1-encode", "d53707f0da90291d459df619c204c09d0e5537b96055b7c5a7eebb164965a30c"), + ("Rgba-1x1-bc2-mips1-decode", "e41eb1f8866a8a844c5627ec9e119ea9b5b2c2afb62c2cc40d0b3463e191181f"), + ("Rgba-1x1-bc3-mips0-encode", "b7a5261aeaa590ee27d74e1ec40688cebfd95a8b32bad510dcf4889659bced99"), + ("Rgba-1x1-bc3-mips0-decode", "ac6d8249b868a4df487ad3d4bc2bffa4ec32afed5bb89bcb916dc390872c00a4"), + ("Rgba-1x1-bc3-mips1-encode", "b7a5261aeaa590ee27d74e1ec40688cebfd95a8b32bad510dcf4889659bced99"), + ("Rgba-1x1-bc3-mips1-decode", "ac6d8249b868a4df487ad3d4bc2bffa4ec32afed5bb89bcb916dc390872c00a4"), + ("Gray-1x1-none-mips0-encode", "9acce63d02641780f46268c15cb62bdf84b68edc091801d02f62d8840b90e76f"), + ("Gray-1x1-none-mips0-decode", "5ef973abd913579530066461f86da91115474c93b5a6cf1b73327feeb3650b83"), + ("Gray-1x1-none-mips1-encode", "9acce63d02641780f46268c15cb62bdf84b68edc091801d02f62d8840b90e76f"), + ("Gray-1x1-none-mips1-decode", "5ef973abd913579530066461f86da91115474c93b5a6cf1b73327feeb3650b83"), + ("Gray-1x1-bc1-mips0-encode", "ffec653603d347468446a15fe4101fda9cb34efb48dc69a8d0f403ce2e2fd9d7"), + ("Gray-1x1-bc1-mips0-decode", "bf04357a38e992a2513e373d00f664b687669a14e1405a2d1b95fb0de6e9a89b"), + ("Gray-1x1-bc1-mips1-encode", "ffec653603d347468446a15fe4101fda9cb34efb48dc69a8d0f403ce2e2fd9d7"), + ("Gray-1x1-bc1-mips1-decode", "bf04357a38e992a2513e373d00f664b687669a14e1405a2d1b95fb0de6e9a89b"), + ("Gray-1x1-bc2-mips0-encode", "3c36aac2c17a7aad99b2c1fa0f4e5b256a9b4421c38406f61961b09c64290178"), + ("Gray-1x1-bc2-mips0-decode", "bf04357a38e992a2513e373d00f664b687669a14e1405a2d1b95fb0de6e9a89b"), + ("Gray-1x1-bc2-mips1-encode", "3c36aac2c17a7aad99b2c1fa0f4e5b256a9b4421c38406f61961b09c64290178"), + ("Gray-1x1-bc2-mips1-decode", "bf04357a38e992a2513e373d00f664b687669a14e1405a2d1b95fb0de6e9a89b"), + ("Gray-1x1-bc3-mips0-encode", "73704fca801476ab72bf69b80a395de711e9a3fa4f476ce5481ae3858f844922"), + ("Gray-1x1-bc3-mips0-decode", "bf04357a38e992a2513e373d00f664b687669a14e1405a2d1b95fb0de6e9a89b"), + ("Gray-1x1-bc3-mips1-encode", "73704fca801476ab72bf69b80a395de711e9a3fa4f476ce5481ae3858f844922"), + ("Gray-1x1-bc3-mips1-decode", "bf04357a38e992a2513e373d00f664b687669a14e1405a2d1b95fb0de6e9a89b"), + ("Rgba-2x3-none-mips0-encode", "1f641b8e1cc01924b0d1a06d2d81ad22c759b44a4f640a83ba6339446e13fc6c"), + ("Rgba-2x3-none-mips0-decode", "af815e7ba5ce6369171335ae94e553524db701f94d152b903f220ee64b9373a6"), + ("Rgba-2x3-none-mips1-encode", "9be390b308b0961125828ca53894a87101983eafaf54e3c7e3da7b1f992fb518"), + ("Rgba-2x3-none-mips1-decode", "af815e7ba5ce6369171335ae94e553524db701f94d152b903f220ee64b9373a6"), + ("Rgba-2x3-bc1-mips0-encode", "743a3d25313924d68732ab399ed92c8e3f693ef26a415a12532918b80db085c4"), + ("Rgba-2x3-bc1-mips0-decode", "570f9feaf2d322a568b2a87ca652aa0606ff96cde281e24d247d071a9dc4e827"), + ("Rgba-2x3-bc1-mips1-encode", "711b0088c7c8083760921c3620d9d1adc02d47b5c3b0eb9e674d974fd1d6d641"), + ("Rgba-2x3-bc1-mips1-decode", "570f9feaf2d322a568b2a87ca652aa0606ff96cde281e24d247d071a9dc4e827"), + ("Rgba-2x3-bc2-mips0-encode", "b4facaf715dd8208fe02961fb99584b58c219117a99f2b1d15d10a556a9e5251"), + ("Rgba-2x3-bc2-mips0-decode", "66112c3066ef59936784fa938c26eb0e86772da586442237de5336c48558afbe"), + ("Rgba-2x3-bc2-mips1-encode", "cad117a2ddd6fe91876efd1dd0b80da0b393f3af21209efc3c1b0f165606a129"), + ("Rgba-2x3-bc2-mips1-decode", "66112c3066ef59936784fa938c26eb0e86772da586442237de5336c48558afbe"), + ("Rgba-2x3-bc3-mips0-encode", "b68ced41c6b33037f08b74c492da5688e9d80555c5843f9f323a74d7c86e114e"), + ("Rgba-2x3-bc3-mips0-decode", "051b60ea47094987d71180aeaa00b3f1b5427429e54812ea28b40f8e945044c8"), + ("Rgba-2x3-bc3-mips1-encode", "88e0fd6d04c896880d03731d6df1528f22290c1738b303eb2b09fe84d7882a64"), + ("Rgba-2x3-bc3-mips1-decode", "051b60ea47094987d71180aeaa00b3f1b5427429e54812ea28b40f8e945044c8"), + ("Gray-2x3-none-mips0-encode", "7e9d26894ca9a800b93f5dae0e5b58b18a6cbcaea56eacc657aba40a1933c476"), + ("Gray-2x3-none-mips0-decode", "d21c9cddccb970575eba36093410245f0a0fb15049fc96311874191f868de0d5"), + ("Gray-2x3-none-mips1-encode", "d2ee41ea49462e1d7be568cfcbf867c6395646710ba321c2dac9db319294bb5e"), + ("Gray-2x3-none-mips1-decode", "d21c9cddccb970575eba36093410245f0a0fb15049fc96311874191f868de0d5"), + ("Gray-2x3-bc1-mips0-encode", "000d5d9121042f7b88411d8e08a548a2c804b8b4b73b40bf317cff61899a5445"), + ("Gray-2x3-bc1-mips0-decode", "1a8f46dd535383398fbeebe5fdfca9bb256fa3b3a7b8552af34b67b09865e89d"), + ("Gray-2x3-bc1-mips1-encode", "07346ec09eb8d9b489e7dd50bd73851342205594ac985544bfe58b6bda73b21b"), + ("Gray-2x3-bc1-mips1-decode", "1a8f46dd535383398fbeebe5fdfca9bb256fa3b3a7b8552af34b67b09865e89d"), + ("Gray-2x3-bc2-mips0-encode", "5db43dcd4adec962a7a12c6f8da8bf05d3dc2e3d608ca3fa341e36b43c218c3d"), + ("Gray-2x3-bc2-mips0-decode", "afabd75898a95baac868e9e14905c2d89e90767750217e4c9ac84b1caeef41bc"), + ("Gray-2x3-bc2-mips1-encode", "3effae05c47854dfb5f20ed12e2c1588236464f17fbf5dd13e61958e5097a796"), + ("Gray-2x3-bc2-mips1-decode", "afabd75898a95baac868e9e14905c2d89e90767750217e4c9ac84b1caeef41bc"), + ("Gray-2x3-bc3-mips0-encode", "11c48dce5b7545cf3eafd1f01fc6b977b13cb7c7e8f2ef7ea1406a8f04b86cf9"), + ("Gray-2x3-bc3-mips0-decode", "afabd75898a95baac868e9e14905c2d89e90767750217e4c9ac84b1caeef41bc"), + ("Gray-2x3-bc3-mips1-encode", "6b7540afc583554e70f4131b4a0d8648eed65100293ab9b7060afcbd33751e64"), + ("Gray-2x3-bc3-mips1-decode", "afabd75898a95baac868e9e14905c2d89e90767750217e4c9ac84b1caeef41bc"), + ("Rgba-3x2-none-mips0-encode", "e821c1620e4e53588908268da45702924911ed756f3257cb0a21727748b736a6"), + ("Rgba-3x2-none-mips0-decode", "d4583449852070512fa3cb16c5132834ccee2f9dd3a6c0d6c8fa5bbbc2935e8d"), + ("Rgba-3x2-none-mips1-encode", "f79a699612ef8d8347a5e83af2fd9ee915eda35388bc86b4243b265f988fc3d8"), + ("Rgba-3x2-none-mips1-decode", "d4583449852070512fa3cb16c5132834ccee2f9dd3a6c0d6c8fa5bbbc2935e8d"), + ("Rgba-3x2-bc1-mips0-encode", "1c106b532f6afc132538b2bb2c1eb9e6bb075a448d19b6af2c67b4c31415e3b2"), + ("Rgba-3x2-bc1-mips0-decode", "f0e63ce55598b6c58c601a5cf3415522113181a08bc28f4d8cd499d160352cdd"), + ("Rgba-3x2-bc1-mips1-encode", "23d86eba138f7c4492f9955dd0a29eb1a675d69f1e612b54e783837d9414cb14"), + ("Rgba-3x2-bc1-mips1-decode", "f0e63ce55598b6c58c601a5cf3415522113181a08bc28f4d8cd499d160352cdd"), + ("Rgba-3x2-bc2-mips0-encode", "74a68d7b1cc0173f1e8a6e0f6101ffa010757df0434fcf5636db808ca20b341e"), + ("Rgba-3x2-bc2-mips0-decode", "bc63bba15c1bbe19cdef66535870c7dfeeae26a4686557e1530ae64a2b2253a5"), + ("Rgba-3x2-bc2-mips1-encode", "d28d7a4a7ee17d0f58f27ebef8d682a7fed42778a60e09186af523198a2f3562"), + ("Rgba-3x2-bc2-mips1-decode", "bc63bba15c1bbe19cdef66535870c7dfeeae26a4686557e1530ae64a2b2253a5"), + ("Rgba-3x2-bc3-mips0-encode", "fa0a02ba9822a007f1654d618b5225332f3934e5f07c51f8ca474e26658e2c45"), + ("Rgba-3x2-bc3-mips0-decode", "ee0221751e1d96bf76552df65a7e54d7711f834cf0431fd17a3a6542473b4ceb"), + ("Rgba-3x2-bc3-mips1-encode", "3a3c51f596a82ae666c6157da4266c3330e8e2e0744947e0ce663deb66e67ad6"), + ("Rgba-3x2-bc3-mips1-decode", "ee0221751e1d96bf76552df65a7e54d7711f834cf0431fd17a3a6542473b4ceb"), + ("Gray-3x2-none-mips0-encode", "6e1e49ee238e40108f1e934946b0d2498eb97f6824a82d4d71011759a58b83a4"), + ("Gray-3x2-none-mips0-decode", "e333fde639747f66aa4d74dbeae648566d6735ecc47de220e07b9da351e1bf37"), + ("Gray-3x2-none-mips1-encode", "906e16afa18db0290bec758a1a124de7a99255871344d462f797db54dbd30b4b"), + ("Gray-3x2-none-mips1-decode", "e333fde639747f66aa4d74dbeae648566d6735ecc47de220e07b9da351e1bf37"), + ("Gray-3x2-bc1-mips0-encode", "df204b170cd24f0375772d65b4f0548a824a4602c453cf891c9cc4aafc4b32ad"), + ("Gray-3x2-bc1-mips0-decode", "869a8202b3721a8d2bf232e75e9a91a271cf2ebad85c8df6a5260cb9c9b6b1ab"), + ("Gray-3x2-bc1-mips1-encode", "d06f38b5c40156888fe2ea04343f46d4753a80f83f63d80b3fd7ce82c5d7fe94"), + ("Gray-3x2-bc1-mips1-decode", "869a8202b3721a8d2bf232e75e9a91a271cf2ebad85c8df6a5260cb9c9b6b1ab"), + ("Gray-3x2-bc2-mips0-encode", "1832e5006137ae1583d34ba1bfab9c7b85f55791996f7cdf21ed799f3939c4f4"), + ("Gray-3x2-bc2-mips0-decode", "869a8202b3721a8d2bf232e75e9a91a271cf2ebad85c8df6a5260cb9c9b6b1ab"), + ("Gray-3x2-bc2-mips1-encode", "41d49c9cce6cbbdf1676033a9233ed774f339d92e8159d1d1b0cbc8503cfe72b"), + ("Gray-3x2-bc2-mips1-decode", "869a8202b3721a8d2bf232e75e9a91a271cf2ebad85c8df6a5260cb9c9b6b1ab"), + ("Gray-3x2-bc3-mips0-encode", "377e3d02919641d634bbe02cadb513237fcd90f540b8769c5e2a214d5ccf05e4"), + ("Gray-3x2-bc3-mips0-decode", "869a8202b3721a8d2bf232e75e9a91a271cf2ebad85c8df6a5260cb9c9b6b1ab"), + ("Gray-3x2-bc3-mips1-encode", "70b03c1901946a24abf34c60dd7bd9cc124df43a251a82622c15d56b0e2b2588"), + ("Gray-3x2-bc3-mips1-decode", "869a8202b3721a8d2bf232e75e9a91a271cf2ebad85c8df6a5260cb9c9b6b1ab"), + ("Rgba-5x5-none-mips0-encode", "be7677f4c86d5f3c0ba75ec04d36bcfd708bca44c9f6720c4b7494c290014491"), + ("Rgba-5x5-none-mips0-decode", "00dc5f1020a7de3a3bc5ee21e7a767d09dab9c9831e840290277af90d1e1e3be"), + ("Rgba-5x5-none-mips1-encode", "284c04f628c256ba546815e46df2b837ee997d90834b8a0f095f20e17ba36102"), + ("Rgba-5x5-none-mips1-decode", "00dc5f1020a7de3a3bc5ee21e7a767d09dab9c9831e840290277af90d1e1e3be"), + ("Rgba-5x5-bc1-mips0-encode", "a5350786ccbd004a88ca541c0d4d7cdf313f71fec9485a45acd380f318846435"), + ("Rgba-5x5-bc1-mips0-decode", "26559d0fc43534fad7318b66672ef9de924b6408b2528c00cb6be76a56a94654"), + ("Rgba-5x5-bc1-mips1-encode", "67e06000b2ee88a6e8e749b20ee6ec0016d294f2fba57e9773aea3a7addd1883"), + ("Rgba-5x5-bc1-mips1-decode", "26559d0fc43534fad7318b66672ef9de924b6408b2528c00cb6be76a56a94654"), + ("Rgba-5x5-bc2-mips0-encode", "6cf909177531b9ed88be4ffd031055a7b1cbcfab0c6082ca33913720d631f834"), + ("Rgba-5x5-bc2-mips0-decode", "060ad06944e973f57c866137f9bd8c903a4edd30af275f9ee92fadff54a0a4bb"), + ("Rgba-5x5-bc2-mips1-encode", "0590d1aa5b074abb89262432a3b6b5c3ff12edca0d454069dadfe20be690e727"), + ("Rgba-5x5-bc2-mips1-decode", "060ad06944e973f57c866137f9bd8c903a4edd30af275f9ee92fadff54a0a4bb"), + ("Rgba-5x5-bc3-mips0-encode", "8d24e90ef90f819353e1bbbb1ab1163463dbdf8d9aaeb89b3acbc8cf2d3dd625"), + ("Rgba-5x5-bc3-mips0-decode", "d3238486581875abcd37dfbe03e8fbea7aa4fcadb1fef866899deafb67ac38f9"), + ("Rgba-5x5-bc3-mips1-encode", "2c331cbc46a45536bc1ae50cff9a692bae969748aebfa13e93c0269055ad5031"), + ("Rgba-5x5-bc3-mips1-decode", "d3238486581875abcd37dfbe03e8fbea7aa4fcadb1fef866899deafb67ac38f9"), + ("Gray-5x5-none-mips0-encode", "8527392cacb17a19b3e1c0f7cbe05ea4abd7fba93a7952d30967047a2e317f3b"), + ("Gray-5x5-none-mips0-decode", "70193f4748cd97b7676693076afe2f1c20afa0dc37b4eb89ff3752114a0e0321"), + ("Gray-5x5-none-mips1-encode", "6c5bd6095bbed4d39c15a6b50dcb5da8d5da48aabf696d2fbfcaf9bd1954c69d"), + ("Gray-5x5-none-mips1-decode", "70193f4748cd97b7676693076afe2f1c20afa0dc37b4eb89ff3752114a0e0321"), + ("Gray-5x5-bc1-mips0-encode", "fc7740ff5a801fdcc82e645d25240b44899a64117e70d739c8cba1c17c5a0841"), + ("Gray-5x5-bc1-mips0-decode", "65a82c1c1048d612c3b5e947603206571f088d1348e6acc42b9e2c014121e227"), + ("Gray-5x5-bc1-mips1-encode", "3953cd92035a27902d5feaf61ba11b4696c8593fb139fbdb6fda0167ac6d7a58"), + ("Gray-5x5-bc1-mips1-decode", "65a82c1c1048d612c3b5e947603206571f088d1348e6acc42b9e2c014121e227"), + ("Gray-5x5-bc2-mips0-encode", "4b2c26f66303f83c35c4f0ca8e306afbde35cfac5e9986cb6dc2ab33696a21c1"), + ("Gray-5x5-bc2-mips0-decode", "65a82c1c1048d612c3b5e947603206571f088d1348e6acc42b9e2c014121e227"), + ("Gray-5x5-bc2-mips1-encode", "047e4d8df50b60f8936e8da938b7c62217da128aaf88a25a9384aa69a3701ce9"), + ("Gray-5x5-bc2-mips1-decode", "65a82c1c1048d612c3b5e947603206571f088d1348e6acc42b9e2c014121e227"), + ("Gray-5x5-bc3-mips0-encode", "9c31c80f1e254a0e590927faf77fe88007d01c93d7a99280b7d632c4d680a8c4"), + ("Gray-5x5-bc3-mips0-decode", "65a82c1c1048d612c3b5e947603206571f088d1348e6acc42b9e2c014121e227"), + ("Gray-5x5-bc3-mips1-encode", "e046981ea9208a3da3cabbb6dd3f3f439db09d8713e6594e099bd7a3ebcd50dc"), + ("Gray-5x5-bc3-mips1-decode", "65a82c1c1048d612c3b5e947603206571f088d1348e6acc42b9e2c014121e227"), + ("Rgba-1x9-none-mips0-encode", "94676df714a0e07fd91981b3f9795da76df174319d551573bf62a7324ceae4fb"), + ("Rgba-1x9-none-mips0-decode", "dbcf64981f64ab690faa081bf7a90405bc9710ca5789f2bbf63d643469d1dd78"), + ("Rgba-1x9-none-mips1-encode", "2614a6ecc2aa845cab81819cd8bcd8b84624d693df6979cba3df91e100f27361"), + ("Rgba-1x9-none-mips1-decode", "dbcf64981f64ab690faa081bf7a90405bc9710ca5789f2bbf63d643469d1dd78"), + ("Rgba-1x9-bc1-mips0-encode", "b7f1466fcebfb73bd6e3b6288d3a8adde258fd9801c694fd44d0f92fbde26c61"), + ("Rgba-1x9-bc1-mips0-decode", "7d3471a56c9ca5332bccb8943e9d5a01105e0ddfd432b403e77841137f927787"), + ("Rgba-1x9-bc1-mips1-encode", "4c7c22ba8e2653f31cd9114857d8ba63db6ac180507e40e8c567b61b9c6781d9"), + ("Rgba-1x9-bc1-mips1-decode", "7d3471a56c9ca5332bccb8943e9d5a01105e0ddfd432b403e77841137f927787"), + ("Rgba-1x9-bc2-mips0-encode", "9dc6e68ae27d0709f8859d6efa0dfc4028d9fbba2cc0aef106973c998417f5d1"), + ("Rgba-1x9-bc2-mips0-decode", "c9dd7bf6d44932b599eeb73b54c6f778880db038768110b005f1886f6993e1db"), + ("Rgba-1x9-bc2-mips1-encode", "5ca6d64da612af3b9018cefa50e98cb9097c2eb3dbda8f862571057ba02d4312"), + ("Rgba-1x9-bc2-mips1-decode", "c9dd7bf6d44932b599eeb73b54c6f778880db038768110b005f1886f6993e1db"), + ("Rgba-1x9-bc3-mips0-encode", "f1d5194773bea0b427702900c928d6829f35cbfd32ec0e76b3ee882670597a81"), + ("Rgba-1x9-bc3-mips0-decode", "feda0633d1e41776c56257893bbe2be5317f57bb771152e1a4336558c16c013c"), + ("Rgba-1x9-bc3-mips1-encode", "4faa40254411822689f7d6b356c447e58f89a00ea05de3f7c43253164d83823c"), + ("Rgba-1x9-bc3-mips1-decode", "feda0633d1e41776c56257893bbe2be5317f57bb771152e1a4336558c16c013c"), + ("Gray-1x9-none-mips0-encode", "deb41e75756b10819d44b9840171a088a5d0169f56962a055939131986b7ebd1"), + ("Gray-1x9-none-mips0-decode", "2713191d6e180f74fa7825564575abcf7cc40c34f09c2cb8ccd4d2b02a675bb0"), + ("Gray-1x9-none-mips1-encode", "2d0f36be14a693e7c0380d70841d56cc857e4b81d1a4acbd94eeb18fca0c9216"), + ("Gray-1x9-none-mips1-decode", "2713191d6e180f74fa7825564575abcf7cc40c34f09c2cb8ccd4d2b02a675bb0"), + ("Gray-1x9-bc1-mips0-encode", "0723a0ecd94984d4a24890abc427611135b5add4c8ced0cd570867abe49217df"), + ("Gray-1x9-bc1-mips0-decode", "dcac5ac2d759bc4166ec0d061863f6bf9a34a03a382ac1d88ebdec3e750ecf3e"), + ("Gray-1x9-bc1-mips1-encode", "b1c38854773fde2bf2fc6e0c13ea5d8f6c92a19c1cb7af5c2986851522f2c5c2"), + ("Gray-1x9-bc1-mips1-decode", "dcac5ac2d759bc4166ec0d061863f6bf9a34a03a382ac1d88ebdec3e750ecf3e"), + ("Gray-1x9-bc2-mips0-encode", "b55d775f6f6029fa6d58ea4bea1abeaed349478665874ae2d5a53be14389c595"), + ("Gray-1x9-bc2-mips0-decode", "dcac5ac2d759bc4166ec0d061863f6bf9a34a03a382ac1d88ebdec3e750ecf3e"), + ("Gray-1x9-bc2-mips1-encode", "2e90ad054e173a392042126fd8674516fd8dc928c098238f92b7d434181a5895"), + ("Gray-1x9-bc2-mips1-decode", "dcac5ac2d759bc4166ec0d061863f6bf9a34a03a382ac1d88ebdec3e750ecf3e"), + ("Gray-1x9-bc3-mips0-encode", "3316e2f5db9bccd337b9dfede5d8c7a4555a645939682f4fc323e746722ef850"), + ("Gray-1x9-bc3-mips0-decode", "dcac5ac2d759bc4166ec0d061863f6bf9a34a03a382ac1d88ebdec3e750ecf3e"), + ("Gray-1x9-bc3-mips1-encode", "0ce9b894539c7e6d22531884a6e352aef26fc899ccf97d8a86878f6f5a68d969"), + ("Gray-1x9-bc3-mips1-decode", "dcac5ac2d759bc4166ec0d061863f6bf9a34a03a382ac1d88ebdec3e750ecf3e"), + ("Rgba-9x1-none-mips0-encode", "29bc4ef0ce9120982b331bf34a460a75f7c086b630ea6710ddd907b01125cc30"), + ("Rgba-9x1-none-mips0-decode", "666aa0014607ab13b7141c423c1fb137bda8a5c92973b3252c0556247383d80b"), + ("Rgba-9x1-none-mips1-encode", "455e7e2173deb612b28ac2ea2cacaf66c740150b3702e2d027bf51dc1123217f"), + ("Rgba-9x1-none-mips1-decode", "666aa0014607ab13b7141c423c1fb137bda8a5c92973b3252c0556247383d80b"), + ("Rgba-9x1-bc1-mips0-encode", "8e21b90879f2768fe0341375245b42a1645bc776ef88f81d700cd7e4f538ece3"), + ("Rgba-9x1-bc1-mips0-decode", "f6b1a1af12998d9db067870ff988d9b527df09ebfbe6a06710474247155655a8"), + ("Rgba-9x1-bc1-mips1-encode", "034c32c5a3025a72161e02ea5422ead0253490df2abf37030a048c93a301b386"), + ("Rgba-9x1-bc1-mips1-decode", "f6b1a1af12998d9db067870ff988d9b527df09ebfbe6a06710474247155655a8"), + ("Rgba-9x1-bc2-mips0-encode", "7d9fbf241277124a62bd0bc466e687d915435cbc083cf0f228694546b612f75e"), + ("Rgba-9x1-bc2-mips0-decode", "5360be17f525cac699135d57837231fbeb993a906c0f7efbffea6c18da4bb9b4"), + ("Rgba-9x1-bc2-mips1-encode", "c7fb6cb488b40b0d08f9958d8d19e3e3f8ac19ce96cd67f99b4bf6d65fb7b0fa"), + ("Rgba-9x1-bc2-mips1-decode", "5360be17f525cac699135d57837231fbeb993a906c0f7efbffea6c18da4bb9b4"), + ("Rgba-9x1-bc3-mips0-encode", "1e9ad28a5057cd576ad5f47625ccbdd836e683fd321428ac30760a15753a3b0e"), + ("Rgba-9x1-bc3-mips0-decode", "a367950e128431e9c0728de32358905486a9f53efef56827cf8f7fa71c9382af"), + ("Rgba-9x1-bc3-mips1-encode", "0f36472c2a24a64e07893879b60a1fc15e492038a669a4fdf0f586942ff7d197"), + ("Rgba-9x1-bc3-mips1-decode", "a367950e128431e9c0728de32358905486a9f53efef56827cf8f7fa71c9382af"), + ("Gray-9x1-none-mips0-encode", "4d65e2aad9e331cfc4edf2c0aaa58673c7ba90f1ad37cfa9c6a31095976ebc0a"), + ("Gray-9x1-none-mips0-decode", "105c3ae0c54915506d98a823112f37182f15e2cbed571b5161c4dfa1007575b5"), + ("Gray-9x1-none-mips1-encode", "0943b2616b8800af4415b53893ea301f1020e062b20f37095f1be9653a31e9bd"), + ("Gray-9x1-none-mips1-decode", "105c3ae0c54915506d98a823112f37182f15e2cbed571b5161c4dfa1007575b5"), + ("Gray-9x1-bc1-mips0-encode", "2c41ef37fc366203a20e1970feecdc8b619659215412a916221ccaa2b273430e"), + ("Gray-9x1-bc1-mips0-decode", "afd18b30efff0e3eb4b59cf01dcbbb06691c3af6028596f8de9efdf370ea915a"), + ("Gray-9x1-bc1-mips1-encode", "d2de0189a1e7a6a70f9a5d4ea7c7a53e064b7d1511f9b183a8dc31268ddb6ac6"), + ("Gray-9x1-bc1-mips1-decode", "afd18b30efff0e3eb4b59cf01dcbbb06691c3af6028596f8de9efdf370ea915a"), + ("Gray-9x1-bc2-mips0-encode", "766180145e22838dc950a136791fb350d51821e39c58270be394357228462fc1"), + ("Gray-9x1-bc2-mips0-decode", "afd18b30efff0e3eb4b59cf01dcbbb06691c3af6028596f8de9efdf370ea915a"), + ("Gray-9x1-bc2-mips1-encode", "476abc493a613766ad73fdc6a89ab765a68677ef6623370472dfea2e3d531847"), + ("Gray-9x1-bc2-mips1-decode", "afd18b30efff0e3eb4b59cf01dcbbb06691c3af6028596f8de9efdf370ea915a"), + ("Gray-9x1-bc3-mips0-encode", "b2f6f7f90bd0530857b272a6b39ac60e20ff2c65f5c0f71de543276d48fc5a30"), + ("Gray-9x1-bc3-mips0-decode", "afd18b30efff0e3eb4b59cf01dcbbb06691c3af6028596f8de9efdf370ea915a"), + ("Gray-9x1-bc3-mips1-encode", "4376a76e8467759cd485d2241c6e1553b6d49e6eb2f83a466d71ca68754776cd"), + ("Gray-9x1-bc3-mips1-decode", "afd18b30efff0e3eb4b59cf01dcbbb06691c3af6028596f8de9efdf370ea915a"), + ("Rgba-6x13-none-mips0-encode", "f603fdcab8e987e1f4b023ec68a14d8c03808952fe429338669977f33131c5a8"), + ("Rgba-6x13-none-mips0-decode", "35c18e04c37154e00ba7a544476335c4e234d8390803eb8f370351551652e49c"), + ("Rgba-6x13-none-mips1-encode", "5254f124be9189174a400affb9192419d6350f6f3361d24cf417ea42c8d33411"), + ("Rgba-6x13-none-mips1-decode", "35c18e04c37154e00ba7a544476335c4e234d8390803eb8f370351551652e49c"), + ("Rgba-6x13-bc1-mips0-encode", "f1b5e39e9a7308be64aa3531cfd487116a4e7f3ea309b694292c9738721ac872"), + ("Rgba-6x13-bc1-mips0-decode", "0a63216b434cd9b24807ea58c6d63888d68e84fa4834a34a8068f7fbf054449d"), + ("Rgba-6x13-bc1-mips1-encode", "13e5b50aa32a32d3dc71d75426c773bb36b191bd97c16c6f2ee0d76f4ee4f54b"), + ("Rgba-6x13-bc1-mips1-decode", "0a63216b434cd9b24807ea58c6d63888d68e84fa4834a34a8068f7fbf054449d"), + ("Rgba-6x13-bc2-mips0-encode", "0e0f5815d03c6ec3b8d58715beacdbe67a3dde10bf3f3b635425dc93073dbb4d"), + ("Rgba-6x13-bc2-mips0-decode", "14d744c8aff8c596f409a6a5c7599bca6479e8e084aa63d99660a44bfe55be6e"), + ("Rgba-6x13-bc2-mips1-encode", "4d007cb53697f394feb540a4745818c1f8a9df4a47819eac38b2102039e9421c"), + ("Rgba-6x13-bc2-mips1-decode", "14d744c8aff8c596f409a6a5c7599bca6479e8e084aa63d99660a44bfe55be6e"), + ("Rgba-6x13-bc3-mips0-encode", "db7fc9607849f169b3e1a7a8e100a7515bdce53ff4f1db7a5fbb6cfc1d1b8162"), + ("Rgba-6x13-bc3-mips0-decode", "33ba59f2acc8ab6877b8474a4b2cf063a0ae54b4a27afc64fde51313ba4ca6bc"), + ("Rgba-6x13-bc3-mips1-encode", "c985feb0187e7ac21aa829e25c5e5fe08970c58e10aaf71b96416a7969c55e68"), + ("Rgba-6x13-bc3-mips1-decode", "33ba59f2acc8ab6877b8474a4b2cf063a0ae54b4a27afc64fde51313ba4ca6bc"), + ("Gray-6x13-none-mips0-encode", "f63bb759c82a74584022a92fa9dfb64f36f3709446e279157942bafef6edc9b9"), + ("Gray-6x13-none-mips0-decode", "71201dd954c691aff18dab0a886cb7f10c15dbb33fca26dcc9f1047d28382190"), + ("Gray-6x13-none-mips1-encode", "435bedffe3efccd86a63533671dd55c7cdc982ea176383adb7e56c4745d38d28"), + ("Gray-6x13-none-mips1-decode", "71201dd954c691aff18dab0a886cb7f10c15dbb33fca26dcc9f1047d28382190"), + ("Gray-6x13-bc1-mips0-encode", "f8cb01936384bbff861cbebfd7149753b31f185b52de437e03074102b1056abf"), + ("Gray-6x13-bc1-mips0-decode", "48669b49d5aec2ab69c120c938838ba206d4e2d589399d2bccf0df5580b48194"), + ("Gray-6x13-bc1-mips1-encode", "f09c7c8bc3def200c72ed32545de294bbcb5436dbc46e249e5d5d2b8ac987a64"), + ("Gray-6x13-bc1-mips1-decode", "48669b49d5aec2ab69c120c938838ba206d4e2d589399d2bccf0df5580b48194"), + ("Gray-6x13-bc2-mips0-encode", "a2b00acf35735c638e07c7468dd8d5ab3405a8d69c653cf95a369538168b8e85"), + ("Gray-6x13-bc2-mips0-decode", "48669b49d5aec2ab69c120c938838ba206d4e2d589399d2bccf0df5580b48194"), + ("Gray-6x13-bc2-mips1-encode", "40769615b4e3117ade50c33e69a51a3f2f1601018c49ea216971955bed74b2ea"), + ("Gray-6x13-bc2-mips1-decode", "48669b49d5aec2ab69c120c938838ba206d4e2d589399d2bccf0df5580b48194"), + ("Gray-6x13-bc3-mips0-encode", "a429bc2f9725fb23f84ac6bff8bd6a1faaf0ab2808912515069b90c002bbf460"), + ("Gray-6x13-bc3-mips0-decode", "48669b49d5aec2ab69c120c938838ba206d4e2d589399d2bccf0df5580b48194"), + ("Gray-6x13-bc3-mips1-encode", "df1d533175cc807a8474701fe4cbdecd694fadd03082d506be50d8716e3e138f"), + ("Gray-6x13-bc3-mips1-decode", "48669b49d5aec2ab69c120c938838ba206d4e2d589399d2bccf0df5580b48194"), + ("dx10-rgba8-decode", "154284a9d25eef84bb2ee0b8b1c2d3cd95149dbae9a61cbe0ddb0f4e59cd1482"), + ("dx10-bgra8-decode", "ec571c9b54af06a0e63fed4b8b00a878d634f62297e72a22372c38fec561b08f"), + ("dx10-bgrx8-decode", "1e9e7678fcd37dcb5c61047cadac102a2053c9d738fab17c55d9d4af573aea99"), + ("legacy-rgba8-decode", "387f6d2b46545aa0188614c6c407a4c7498f065f3124964b92992a304c4e997d"), + ("legacy-bgra8-padded-decode", "5d4a59bd952afd03eb206aa2e3eaeb652d1d6abd1bf2ada8d8bc67e153fd0b3b"), + ("legacy-rgb24-decode", "0d33d20540b8d8714fb2f50193505188a60a743edbca6729806210a990bcebb7"), + ("legacy-rgb565-decode", "e0529a28e87837cea810bee99263a4d3c1ec99bfa6547bff583fc5848b7319e9"), + ("legacy-argb4444-decode", "0cf215d8c21faeff39c8b4e37acb8a72c69a873b7d132746c66c2f4a6277d58a"), + ("legacy-l8-padded-decode", "0c72254df5d58d8a1b4c62d1da03548c10a058dab179d7486a1e1c394a4b1cee"), + ("legacy-l8a8-decode", "066ff8e0a187094a1feb4bdc57e1cb8a99bc6ed3d69647c87c9d54a093b6815a"), + ("legacy-dxt1-noise-decode", "78d4ec7cec69249f8b065667eb66a23b23e82a6b7ab167043539976ae874c433"), + ("legacy-dxt3-noise-decode", "2dae7a8abe345ca37af54ad56e65dcb8a6fc1837f233cc81b5693b0b547babc8"), + ("legacy-dxt5-noise-decode", "5a6edeb62a5d6043a474de25da0611a550cf81716a8960dbf57feaebddf7d950"), + ("dx10-bc1-noise-decode", "5c6ea27a01ccb2a1ab3badea75551a9d3209a0176335871186362cc7e1923ead"), + ("dx10-bc3-noise-decode", "9c5376a1d714471d575344920380755e40f5be6cd4cb54add5b982d833276823"), +]; + +/// The compressions the digests cover, listed here rather than taken from `DdsCompression::ALL` +/// so a compression added later doesn't change the set. +const COMPRESSIONS: [DdsCompression; 4] = [DdsCompression::None, DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3]; + +/// A 64-bit LCG (Knuth's MMIX constants) with a fixed seed: the same noise on every run. +struct Lcg(u64); + +impl Lcg { + fn next(&mut self) -> u8 { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 33) as u8 + } +} + +/// An RGBA test picture in four vertical bands: smooth ramps with mid alpha, noise in every +/// channel, flat 8×8 tiles of a few colours (whole blocks of one colour, opaque), and a band +/// where alpha jumps between 0, 255 and in-between values over gentle colour. +fn picture(w: u32, h: u32, seed: u64) -> Vec { + let mut rng = Lcg(seed); + let tiles: [[u8; 4]; 5] = [[12, 200, 77, 255], [255, 255, 255, 255], [0, 0, 0, 255], [255, 0, 255, 255], [90, 91, 92, 255]]; + let band = w.div_ceil(4).max(1); + let mut data = Vec::with_capacity(w as usize * h as usize * 4); + for y in 0..h { + for x in 0..w { + let noise = [rng.next(), rng.next(), rng.next(), rng.next()]; + let px = match x / band { + 0 => [(x * 2) as u8, (y * 3) as u8, (x + y) as u8, (64 + y % 128) as u8], + 1 => noise, + 2 => tiles[((x / 8 + y / 8) % 5) as usize], + _ => { + let alpha = match (x / 3 + y / 5) % 4 { + 0 => 0, + 1 => 255, + 2 => 128, + _ => noise[3], + }; + [(y % 256) as u8, 128, (255 - y % 256) as u8, alpha] + } + }; + data.extend(px); + } + } + data +} + +/// The picture in `layout`, its channels picked from the RGBA picture without any conversion +/// formula: gray is red, and gray's alpha is alpha. +fn image(w: u32, h: u32, layout: ChannelLayout, seed: u64) -> Image { + let rgba = picture(w, h, seed); + let data = rgba + .as_chunks::<4>() + .0 + .iter() + .flat_map(|p| match layout { + ChannelLayout::Gray => vec![p[0]], + ChannelLayout::GrayA => vec![p[0], p[3]], + ChannelLayout::Rgb => vec![p[0], p[1], p[2]], + _ => p.to_vec(), + }) + .collect(); + Image::from_u8(w, h, layout, data).unwrap() +} + +fn sha256_hex(bytes: &[u8]) -> String { + Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect() +} + +/// A decoded image's digest: its size and layout, then its samples. +fn image_digest(img: &Image) -> String { + let mut h = Sha256::new(); + h.update(img.width().to_le_bytes()); + h.update(img.height().to_le_bytes()); + h.update(format!("{:?}", img.layout()).as_bytes()); + h.update(img.data()); + h.finalize().iter().map(|b| format!("{b:02x}")).collect() +} + +const DDPF_ALPHAPIXELS: u32 = 0x1; +const DDPF_FOURCC: u32 = 0x4; +const DDPF_RGB: u32 = 0x40; +const DDPF_LUMINANCE: u32 = 0x2_0000; +const DDSD_PITCH: u32 = 0x8; + +/// A DDS_HEADER for a single-level 2D texture, with `pitch` set (and flagged) when given. +fn header(width: u32, height: u32, pf_flags: u32, fourcc: &[u8; 4], bits: u32, masks: [u32; 4], pitch: Option) -> Vec { + let mut b = vec![0u8; 128]; + b[0..4].copy_from_slice(b"DDS "); + let mut put = |at: usize, v: u32| b[at..at + 4].copy_from_slice(&v.to_le_bytes()); + put(4, 124); + put(8, 0x1007 | if pitch.is_some() { DDSD_PITCH } else { 0 }); + put(12, height); + put(16, width); + put(20, pitch.unwrap_or(0)); + put(76, 32); + put(80, pf_flags); + put(88, bits); + for (i, m) in masks.into_iter().enumerate() { + put(92 + 4 * i, m); + } + put(108, 0x1000); + b[84..88].copy_from_slice(fourcc); + b +} + +/// A DX10 texture header for DXGI format `dxgi`. +fn dx10(width: u32, height: u32, dxgi: u32) -> Vec { + let mut b = header(width, height, DDPF_FOURCC, b"DX10", 0, [0; 4], None); + for v in [dxgi, 3, 0, 1, 0] { + b.extend(v.to_le_bytes()); + } + b +} + +/// `len` bytes of noise. +fn noise(len: usize, seed: u64) -> Vec { + let mut rng = Lcg(seed); + (0..len).map(|_| rng.next()).collect() +} + +/// Hand-built files in the layouts the writer never makes: RGBA and BGRA through the DX10 +/// header, padded rows, 24- and 16-bit masks, and block data of pure noise (which reaches BC1's +/// three-colour mode and BC3's six-value mode as often as their other modes). +fn foreign_files() -> Vec<(String, Vec)> { + let (w, h) = (37u32, 23u32); + let px = (w * h) as usize; + let blocks = (w.div_ceil(4) * h.div_ceil(4)) as usize; + let mut files = Vec::new(); + let mut add = |name: &str, mut head: Vec, body: Vec| { + head.extend(body); + files.push((name.to_string(), head)); + }; + add("dx10-rgba8", dx10(w, h, 28), noise(px * 4, 1)); + add("dx10-bgra8", dx10(w, h, 87), noise(px * 4, 2)); + add("dx10-bgrx8", dx10(w, h, 88), noise(px * 4, 3)); + add("legacy-rgba8", header(w, h, DDPF_RGB | DDPF_ALPHAPIXELS, &[0; 4], 32, [0xff, 0xff00, 0xff_0000, 0xff00_0000], None), noise(px * 4, 4)); + add( + "legacy-bgra8-padded", + header(w, h, DDPF_RGB | DDPF_ALPHAPIXELS, &[0; 4], 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000], Some(w * 4 + 12)), + noise((w * 4 + 12) as usize * h as usize, 5), + ); + add("legacy-rgb24", header(w, h, DDPF_RGB, &[0; 4], 24, [0xff_0000, 0xff00, 0xff, 0], None), noise(px * 3, 6)); + add("legacy-rgb565", header(w, h, DDPF_RGB, &[0; 4], 16, [0xf800, 0x07e0, 0x001f, 0], None), noise(px * 2, 7)); + add("legacy-argb4444", header(w, h, DDPF_RGB | DDPF_ALPHAPIXELS, &[0; 4], 16, [0x0f00, 0x00f0, 0x000f, 0xf000], None), noise(px * 2, 8)); + add("legacy-l8-padded", header(w, h, DDPF_LUMINANCE, &[0; 4], 8, [0xff, 0, 0, 0], Some(w + 3)), noise((w + 3) as usize * h as usize, 9)); + add("legacy-l8a8", header(w, h, DDPF_LUMINANCE | DDPF_ALPHAPIXELS, &[0; 4], 16, [0xff, 0, 0, 0xff00], None), noise(px * 2, 10)); + add("legacy-dxt1-noise", header(w, h, DDPF_FOURCC, b"DXT1", 0, [0; 4], None), noise(blocks * 8, 11)); + add("legacy-dxt3-noise", header(w, h, DDPF_FOURCC, b"DXT3", 0, [0; 4], None), noise(blocks * 16, 12)); + add("legacy-dxt5-noise", header(w, h, DDPF_FOURCC, b"DXT5", 0, [0; 4], None), noise(blocks * 16, 13)); + add("dx10-bc1-noise", dx10(w, h, 71), noise(blocks * 8, 14)); + add("dx10-bc3-noise", dx10(w, h, 77), noise(blocks * 16, 15)); + files +} + +/// Every case and its digest, in a fixed order. +fn digests() -> Vec<(String, String)> { + let mut out = Vec::new(); + // Odd sizes, the sub-block sizes and the one-pixel strips whose mip chains reach the + // downsampler's edge spans in only one direction. + let sizes = [(517u32, 389u32), (1, 1), (2, 3), (3, 2), (5, 5), (1, 9), (9, 1), (6, 13)]; + let layouts = [ChannelLayout::Rgba, ChannelLayout::Rgb, ChannelLayout::GrayA, ChannelLayout::Gray]; + for (i, &(w, h)) in sizes.iter().enumerate() { + for layout in layouts { + // The large picture in every layout; the small ones in RGBA and gray. + if i > 0 && !matches!(layout, ChannelLayout::Rgba | ChannelLayout::Gray) { + continue; + } + let img = image(w, h, layout, 0x5eed + i as u64); + for compression in COMPRESSIONS { + for mipmaps in [false, true] { + let name = format!("{layout:?}-{w}x{h}-{}-mips{}", compression.name(), u8::from(mipmaps)); + let opts = EncodeOptions { dds: DdsOptions { compression, mipmaps }, ..Default::default() }; + let file = encode(&img, Format::Dds, &opts).unwrap_or_else(|e| panic!("{name}: {e}")); + out.push((format!("{name}-encode"), sha256_hex(&file))); + let back = decode(&file).unwrap_or_else(|e| panic!("{name}: {e}")); + out.push((format!("{name}-decode"), image_digest(&back))); + } + } + } + } + for (name, file) in foreign_files() { + let back = decode(&file).unwrap_or_else(|e| panic!("{name}: {e}")); + out.push((format!("{name}-decode"), image_digest(&back))); + } + out +} + +#[test] +fn dds_output_matches_the_pinned_digests() { + let got = digests(); + let pinned = |name: &str| PINNED.iter().find(|(n, _)| *n == name).map(|(_, d)| *d); + let mismatched: Vec<&str> = got.iter().filter(|(name, digest)| pinned(name) != Some(digest.as_str())).map(|(n, _)| n.as_str()).collect(); + let stale: Vec<&str> = PINNED.iter().filter(|(n, _)| !got.iter().any(|(g, _)| g == n)).map(|(n, _)| *n).collect(); + if !mismatched.is_empty() || !stale.is_empty() { + eprintln!("const PINNED: &[(&str, &str)] = &["); + for (name, digest) in &got { + eprintln!(" (\"{name}\", \"{digest}\"),"); + } + eprintln!("];"); + panic!("{} digests differ or are new: {mismatched:?}; {} pinned cases are gone: {stale:?}", mismatched.len(), stale.len()); + } +} diff --git a/crates/image-codecs/tests/it/dds_write.rs b/crates/image-codecs/tests/it/dds_write.rs index f9d9add8e..af6a2c7d2 100644 --- a/crates/image-codecs/tests/it/dds_write.rs +++ b/crates/image-codecs/tests/it/dds_write.rs @@ -16,6 +16,8 @@ const DDPF_ALPHAPIXELS: u32 = 0x1; const DDPF_FOURCC: u32 = 0x4; const DDPF_RGB: u32 = 0x40; const DDPF_LUMINANCE: u32 = 0x2_0000; +const DXGI_BC4_UNORM: u32 = 80; +const DXGI_BC5_UNORM: u32 = 83; const BLOCKS: [DdsCompression; 3] = [DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3]; @@ -80,11 +82,21 @@ fn psnr(a: &Image, b: &Image) -> f64 { if mse == 0.0 { f64::INFINITY } else { 10.0 * (255.0f64.powi(2) / mse).log10() } } +/// Whether a written texture has the DX10 header after the legacy one. +fn has_dx10(file: &[u8]) -> bool { + le32(file, 80) & DDPF_FOURCC != 0 && &file[84..88] == b"DX10" +} + +/// Bytes of the headers before the first level. +fn head(file: &[u8]) -> usize { + if has_dx10(file) { 148 } else { 128 } +} + /// Bytes of one level as a reader computes them from the header's pixel format. fn level_bytes(file: &[u8], w: usize, h: usize) -> usize { if le32(file, 80) & DDPF_FOURCC != 0 { - let block = if &file[84..88] == b"DXT1" { 8 } else { 16 }; - w.div_ceil(4) * h.div_ceil(4) * block + let eight = &file[84..88] == b"DXT1" || (has_dx10(file) && le32(file, 128) == DXGI_BC4_UNORM); + w.div_ceil(4) * h.div_ceil(4) * if eight { 8 } else { 16 } } else { w * h * le32(file, 88) as usize / 8 } @@ -94,9 +106,9 @@ fn level_bytes(file: &[u8], w: usize, h: usize) -> usize { fn level(file: &[u8], i: u32) -> Image { let (w, h) = (le32(file, 16) as usize, le32(file, 12) as usize); let size = |i: u32| ((w >> i).max(1), (h >> i).max(1)); - let start = 128 + (0..i).map(|j| level_bytes(file, size(j).0, size(j).1)).sum::(); + let start = head(file) + (0..i).map(|j| level_bytes(file, size(j).0, size(j).1)).sum::(); let (lw, lh) = size(i); - let mut b = file[..128].to_vec(); + let mut b = file[..head(file)].to_vec(); b[12..16].copy_from_slice(&(lh as u32).to_le_bytes()); b[16..20].copy_from_slice(&(lw as u32).to_le_bytes()); b[28..32].copy_from_slice(&1u32.to_le_bytes()); @@ -338,15 +350,122 @@ fn fidelity_warnings_follow_the_compression() { } assert!(warns(DdsCompression::Bc1).contains(&FidelityWarning::AlphaBinarized)); assert!(!warns(DdsCompression::Bc3).contains(&FidelityWarning::AlphaBinarized)); + // BC4 is gray and BC5 has no alpha: translucent colour loses what they don't hold. + let bc4 = warns(DdsCompression::Bc4); + for w in [FidelityWarning::LossyCompression, FidelityWarning::ColorToGray, FidelityWarning::AlphaDiscarded] { + assert!(bc4.contains(&w), "BC4: {w:?} missing from {bc4:?}"); + } + let bc5 = warns(DdsCompression::Bc5); + assert!(bc5.contains(&FidelityWarning::LossyCompression) && bc5.contains(&FidelityWarning::AlphaDiscarded), "{bc5:?}"); + assert!(!bc5.contains(&FidelityWarning::ColorToGray) && !bc5.contains(&FidelityWarning::AlphaBinarized), "{bc5:?}"); + // A gray map written as BC4 loses only to the compression. + let gray = ramp(8, 8, ChannelLayout::Gray); + assert_eq!(fidelity_warnings_with(&gray, Format::Dds, &opts(DdsCompression::Bc4, false)), [FidelityWarning::LossyCompression]); +} + +/// The largest difference in channel `c` between two images of `channels` channels. +fn max_diff(a: &Image, b: &Image, channels: usize, c: usize) -> u8 { + a.data().chunks(channels).zip(b.data().chunks(channels)).map(|(x, y)| x[c].abs_diff(y[c])).max().unwrap_or(0) +} + +/// `gradient`'s red as gray, or its red, green and blue. +fn gradient_as(w: u32, h: u32, layout: ChannelLayout) -> Image { + let rgba = gradient(w, h); + let data = rgba.data().chunks(4).flat_map(|p| if layout == ChannelLayout::Gray { vec![p[0]] } else { p[..3].to_vec() }).collect(); + Image::from_u8(w, h, layout, data).unwrap() +} + +#[test] +fn bc4_and_bc5_are_written_with_the_dx10_header() { + for (compression, dxgi, block, layout) in + [(DdsCompression::Bc4, DXGI_BC4_UNORM, 8, ChannelLayout::Gray), (DdsCompression::Bc5, DXGI_BC5_UNORM, 16, ChannelLayout::Rgb)] + { + for (w, h) in [(1, 1), (2, 2), (5, 3), (33, 17)] { + let img = ramp(w, h, layout); + let b = encode(&img, Format::Dds, &opts(compression, false)).unwrap(); + let linear = w.div_ceil(4) * h.div_ceil(4) * block; + assert_eq!(&b[84..88], b"DX10"); + assert_eq!((le32(&b, 80), le32(&b, 88)), (DDPF_FOURCC, 0)); + assert_eq!(le32(&b, 8), REQUIRED | DDSD_LINEARSIZE, "linear size, not pitch"); + assert_eq!(le32(&b, 20), linear, "{compression:?} {w}x{h}: the top level's size"); + // DXGI format, a 2D texture, no misc flags, one texture, alpha mode unknown. + assert_eq!([le32(&b, 128), le32(&b, 132), le32(&b, 136), le32(&b, 140), le32(&b, 144)], [dxgi, 3, 0, 1, 0]); + assert_eq!(b.len(), 148 + linear as usize); + assert!(!craft_image_codecs::has_unretained_source_data(&b).unwrap()); + let back = decode(&b).unwrap(); + assert_eq!((back.dimensions(), back.layout()), ((w, h), layout), "{compression:?} {w}x{h}"); + } + } +} + +#[test] +fn bc4_and_bc5_error_on_gradients_is_bounded() { + // Each block of the gradient spans 12 levels in a channel: eight values (or six and the + // extremes) are under two levels apart. + let gray = gradient_as(64, 64, ChannelLayout::Gray); + let back = decode(&encode(&gray, Format::Dds, &opts(DdsCompression::Bc4, false)).unwrap()).unwrap(); + assert_eq!(back.layout(), ChannelLayout::Gray); + let err = max_diff(&gray, &back, 1, 0); + assert!(err <= 2, "BC4 off by {err}"); + + let rgb = gradient_as(64, 64, ChannelLayout::Rgb); + let back = decode(&encode(&rgb, Format::Dds, &opts(DdsCompression::Bc5, false)).unwrap()).unwrap(); + assert_eq!(back.layout(), ChannelLayout::Rgb); + let (red, green) = (max_diff(&rgb, &back, 3, 0), max_diff(&rgb, &back, 3, 1)); + assert!(red <= 2 && green <= 2, "BC5 red off by {red}, green by {green}"); + assert!(back.data().chunks(3).all(|p| p[2] == 0), "BC5 has no blue"); +} + +#[test] +fn bc4_and_bc5_take_any_source_layout() { + // RGBA to BC4 goes through gray; to BC5 through RGB, dropping alpha and then blue. + let img = gradient(9, 7); + for (compression, layout) in [(DdsCompression::Bc4, ChannelLayout::Gray), (DdsCompression::Bc5, ChannelLayout::Rgb)] { + let back = decode(&encode(&img, Format::Dds, &opts(compression, true)).unwrap()).unwrap(); + let want = img.convert(layout, img.sample_type()); + let ch = layout.channels(); + assert_eq!((back.dimensions(), back.layout()), ((9, 7), layout)); + for c in 0..ch.min(2) { + let err = max_diff(&want, &back, ch, c); + assert!(err <= 8, "{compression:?} channel {c} off by {err}"); + } + } +} + +#[test] +fn bc4_and_bc5_mip_chains_follow_the_box_filter() { + for (compression, layout, block) in [(DdsCompression::Bc4, ChannelLayout::Gray, 8), (DdsCompression::Bc5, ChannelLayout::Rgb, 16)] { + let img = gradient_as(12, 6, layout); + let b = encode(&img, Format::Dds, &opts(compression, true)).unwrap(); + // 12×6, 6×3, 3×1, 1×1: 3×2, 2×1, 1 and 1 blocks after both headers. + assert_eq!(le32(&b, 28), 4); + assert_eq!(le32(&b, 8), REQUIRED | DDSD_LINEARSIZE | DDSD_MIPMAPCOUNT); + assert_eq!(b.len(), 148 + (6 + 2 + 1 + 1) * block); + let mut want = img.clone(); + for i in 0..4 { + let got = level(&b, i); + assert_eq!((got.dimensions(), got.layout()), (want.dimensions(), layout), "{compression:?} level {i}"); + for c in 0..layout.channels().min(2) { + // Smaller levels are steeper (8, then 16 levels a pixel), so a block's values + // sit up to a few levels off its palette. + let err = max_diff(&want, &got, layout.channels(), c); + assert!(err <= 4, "{compression:?} level {i} channel {c} off by {err}"); + } + want = box_filter(&want); + } + } } #[test] fn compression_names_round_trip() { + assert_eq!(DdsCompression::ALL.len(), 6); for c in DdsCompression::ALL { assert_eq!(DdsCompression::from_name(c.name()), Some(c)); } assert_eq!(DdsCompression::from_name("DXT5"), Some(DdsCompression::Bc3)); assert_eq!(DdsCompression::from_name("dxt1"), Some(DdsCompression::Bc1)); + assert_eq!(DdsCompression::from_name("ATI1"), Some(DdsCompression::Bc4)); + assert_eq!(DdsCompression::from_name("ati2"), Some(DdsCompression::Bc5)); for bad in ["", "bc7", "dxt2", "uncompressed "] { assert_eq!(DdsCompression::from_name(bad), None, "{bad:?}"); } @@ -360,6 +479,18 @@ fn compression_names_round_trip() { #[test] #[ignore] fn dds_encode_timings_on_30_mp() { + let img = texture_30_mp(); + for compression in DdsCompression::ALL { + for mipmaps in [false, true] { + let t = std::time::Instant::now(); + let b = encode(&img, Format::Dds, &opts(compression, mipmaps)).unwrap(); + eprintln!("{compression:?} mipmaps={mipmaps}: {:.0} ms, {} MB", t.elapsed().as_secs_f64() * 1e3, b.len() >> 20); + } + } +} + +/// A synthetic ~30 MP RGBA texture (6336×4752): gentle ramps with a little noise. +fn texture_30_mp() -> Image { let (w, h) = (6336u32, 4752u32); let mut s = 0x1234_5678u32; let mut data = Vec::with_capacity(w as usize * h as usize * 4); @@ -371,12 +502,28 @@ fn dds_encode_timings_on_30_mp() { data.extend([(x / 25 + y / 19) as u8, (x / 31) as u8 ^ (s as u8 & 3), (y / 23) as u8, (255 - x / 25) as u8]); } } - let img = Image::from_u8(w, h, ChannelLayout::Rgba, data).unwrap(); + Image::from_u8(w, h, ChannelLayout::Rgba, data).unwrap() +} + +/// Decode timings of the same texture written with each compression: the best of five runs, so +/// one slow run doesn't decide. Ignored by default; run in release: +/// +/// ```sh +/// cargo test --release -p craft-image-codecs --test it -- dds_write:: --ignored --nocapture +/// ``` +#[test] +#[ignore] +fn dds_decode_timings_on_30_mp() { + let img = texture_30_mp(); for compression in DdsCompression::ALL { - for mipmaps in [false, true] { + let b = encode(&img, Format::Dds, &opts(compression, false)).unwrap(); + let mut best = f64::INFINITY; + for _ in 0..5 { let t = std::time::Instant::now(); - let b = encode(&img, Format::Dds, &opts(compression, mipmaps)).unwrap(); - eprintln!("{compression:?} mipmaps={mipmaps}: {:.0} ms, {} MB", t.elapsed().as_secs_f64() * 1e3, b.len() >> 20); + let back = decode(&b).unwrap(); + best = best.min(t.elapsed().as_secs_f64()); + assert_eq!(back.dimensions(), img.dimensions()); } + eprintln!("{compression:?} decode: {:.0} ms, {} MB", best * 1e3, b.len() >> 20); } } diff --git a/crates/image-codecs/tests/it/main.rs b/crates/image-codecs/tests/it/main.rs index 69be177db..e3c0feaaf 100644 --- a/crates/image-codecs/tests/it/main.rs +++ b/crates/image-codecs/tests/it/main.rs @@ -4,6 +4,7 @@ mod bmp_resolution; mod camera_raw; mod common; mod dds; +mod dds_oracle; mod dds_write; mod decode_warnings; mod deep_exr; diff --git a/crates/image-codecs/tests/legacy_tiff_raw.rs b/crates/image-codecs/tests/legacy_tiff_raw.rs index 770801734..27cf6b881 100644 --- a/crates/image-codecs/tests/legacy_tiff_raw.rs +++ b/crates/image-codecs/tests/legacy_tiff_raw.rs @@ -63,3 +63,23 @@ fn oversized_or_cut_directories_are_skipped() { cut.truncate(20); assert!(!legacy_tiff_raw_hint(&cut)); } + +#[test] +fn a_subifds_array_without_its_offset_is_skipped() { + // IFD0 at 64 holds one SubIFDs entry (LONG, count 3) whose offset field is cut off. A DNG + // directory sits at 32, and the bytes at 8 point to it. Reading the missing offset as 0 + // would treat the TIFF header as the pointer array and follow 8 -> 32. + let mut b = vec![0u8; 64]; + b[..8].copy_from_slice(b"II\x2a\0\x40\0\0\0"); + b[8..12].copy_from_slice(&32u32.to_le_bytes()); + b[32..34].copy_from_slice(&1u16.to_le_bytes()); + b[34..46].copy_from_slice(&[0x12, 0xc6, 1, 0, 4, 0, 0, 0, 1, 4, 0, 0]); + b.extend_from_slice(&1u16.to_le_bytes()); + b.extend_from_slice(&[0x4a, 0x01, 4, 0, 3, 0, 0, 0]); + assert_eq!(b.len(), 74); + assert!(!legacy_tiff_raw_hint(&b)); + // With the offset present (the array at 8), the same SubIFD is followed. + let mut whole = b.clone(); + whole.extend_from_slice(&8u32.to_le_bytes()); + assert!(legacy_tiff_raw_hint(&whole)); +} diff --git a/crates/media-source/Cargo.toml b/crates/media-source/Cargo.toml new file mode 100644 index 000000000..3edda0b2e --- /dev/null +++ b/crates/media-source/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "craft-media-source" +description = "Compositor MediaSource trait and a pluggable open_bytes / open_reader registry" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-audio = { workspace = true } +craft-color = { workspace = true } +craft-frame = { workspace = true } +craft-media = { workspace = true } +craft-time = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/media-source/src/lib.rs b/crates/media-source/src/lib.rs new file mode 100644 index 000000000..c27aea688 --- /dev/null +++ b/crates/media-source/src/lib.rs @@ -0,0 +1,563 @@ +//! Compositor media sources and a pluggable opener registry. +//! +//! This crate is the EffectCraft / FilmCraft opener hub: a [`MediaSource`] yields compositor +//! [`VideoFrame`]s and [`AudioBuffer`]s, and [`open_bytes`] / [`open_reader`] try caller-supplied +//! openers in order. It lives in its own crate rather than `craft-media` so it can depend on +//! `craft-audio` without a cycle (`craft-audio` already depends on `craft-media`). +//! +//! Built-in still-image, WAV, and generator openers stay in the apps. [`open_bytes`] only runs the +//! `extra` openers; [`open_reader`] tries `reader_openers` and otherwise reads the file whole +//! (up to `max_whole`) and falls back to [`open_bytes`]. Container sources register themselves +//! from later PRs. +//! +//! [`SharedSource`] is `Arc`. It is not `craft_audio::SharedSource`, which is a +//! `ByteSource` marker used by the audio decoder. + +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] + +use std::io; +use std::path::Path; +use std::sync::Arc; + +use craft_audio::AudioBuffer; +use craft_color::{ColorInfo, HdrMetadata}; +use craft_frame::VideoFrame; +use craft_media::ByteSource; +use craft_time::{FrameRate, Tick}; +use serde::{Deserialize, Serialize}; + +/// Errors from opening or reading a media source. +#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] +pub enum MediaError { + #[error("unsupported media: {0}")] + Unsupported(String), + #[error("I/O error: {0}")] + Io(String), + #[error("decode error: {0}")] + Decode(String), + #[error("no {0} stream")] + NoStream(&'static str), + #[error("media offline: {0}")] + Offline(String), + /// The request was cancelled. + #[error("cancelled")] + Cancelled, +} + +impl From for MediaError { + fn from(e: io::Error) -> Self { + MediaError::Io(e.to_string()) + } +} + +pub type Result = std::result::Result; + +/// Kind of media a source reports. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum MediaKind { + /// Video, possibly with audio. + Movie, + AudioOnly, + Still, + ImageSequence, + Synthetic, +} + +/// Video stream metadata a source reports. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct VideoStreamInfo { + pub width: u32, + pub height: u32, + pub frame_rate: FrameRate, + pub par: (u32, u32), + pub codec: String, + pub pixel_format: String, + pub color: ColorInfo, + pub has_alpha: bool, + /// Bitrate in bits/s when known. + pub bitrate: Option, + /// HDR static metadata when the file carries it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hdr: Option, +} + +/// Most audio streams a source reports (the count comes from the file: never trusted). +pub const MAX_AUDIO_STREAMS: usize = 64; + +/// Audio stream metadata a source reports. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct AudioStreamInfo { + pub sample_rate: u32, + pub channels: u32, + pub codec: String, + pub bits_per_sample: Option, +} + +/// Identity and streams of an open source. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct MediaInfo { + pub name: String, + pub kind: MediaKind, + /// Media duration. Stills typically report a default duration chosen by the app. + pub duration: Tick, + pub video: Option, + /// Every audio stream the container carries, in file order. Stream 0 is the one + /// [`MediaSource::audio`] reads; the others are read with [`MediaSource::audio_stream`]. + /// Project files written before multi-stream support hold a single `audio` object (or + /// `null`): both still load. + #[serde(default, alias = "audio", deserialize_with = "deserialize_audio_streams")] + pub audio_streams: Vec, + pub container: String, + /// Timecode of the first frame (in frames at `video.frame_rate`), if the file carries one. + pub start_timecode: Option, + pub file_size: Option, +} + +/// Reads `audio_streams` from a list, or from the single optional stream older project files wrote. +fn deserialize_audio_streams<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { + struct StreamsVisitor; + struct RejectExtra; + impl<'de> serde::de::DeserializeSeed<'de> for RejectExtra { + type Value = (); + fn deserialize>(self, _d: D) -> std::result::Result<(), D::Error> { + Err(serde::de::Error::custom("audio stream count exceeds MAX_AUDIO_STREAMS")) + } + } + impl<'de> serde::de::Visitor<'de> for StreamsVisitor { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("at most 64 audio streams, a legacy audio object, or null") + } + fn visit_unit(self) -> std::result::Result { + Ok(Vec::new()) + } + fn visit_none(self) -> std::result::Result { + Ok(Vec::new()) + } + fn visit_map>(self, map: A) -> std::result::Result { + AudioStreamInfo::deserialize(serde::de::value::MapAccessDeserializer::new(map)).map(|stream| vec![stream]) + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut streams = Vec::new(); + // Do not reserve from an untrusted size hint or buffer an untagged sequence. + while streams.len() < MAX_AUDIO_STREAMS { + let Some(stream) = seq.next_element()? else { return Ok(streams) }; + streams.push(stream); + } + // Detect an excess entry without deserializing or allocating its contents. + seq.next_element_seed(RejectExtra)?; + Ok(streams) + } + } + d.deserialize_any(StreamsVisitor) +} + +impl MediaInfo { + pub fn frame_rate(&self) -> FrameRate { + self.video.as_ref().map(|v| v.frame_rate).unwrap_or_default() + } + pub fn has_video(&self) -> bool { + self.video.is_some() + } + pub fn has_audio(&self) -> bool { + !self.audio_streams.is_empty() + } + /// The primary audio stream (stream 0), the one [`MediaSource::audio`] reads. + pub fn audio(&self) -> Option<&AudioStreamInfo> { + self.audio_streams.first() + } +} + +/// A request for a video frame. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FrameRequest { + /// Media time. + pub time: Tick, + /// Desired scale relative to full resolution (1.0 = full). Sources may return a larger frame. + pub scale: f32, +} + +impl FrameRequest { + pub fn full(time: Tick) -> Self { + Self { time, scale: 1.0 } + } +} + +/// A decoded or generated media source that can yield compositor frames and audio. +pub trait MediaSource: Send + Sync { + fn info(&self) -> &MediaInfo; + /// The frame displayed at media time `req.time`. + fn video_frame(&self, req: FrameRequest) -> Result>; + /// `frames` audio frames starting at sample index `start` (at `sample_rate`, media time). + fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result; + /// Like [`audio`](Self::audio) for audio stream `stream` (an index into + /// [`MediaInfo::audio_streams`]). Sources with a single audio stream need not override this: + /// stream 0 is `audio`, any other index is [`MediaError::NoStream`]. + fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result { + if stream == 0 { self.audio(start, frames, sample_rate) } else { Err(MediaError::NoStream("audio")) } + } +} + +/// Shared compositor source. Distinct from [`craft_audio::SharedSource`], a `ByteSource` marker. +pub type SharedSource = Arc; + +/// Random-access bytes used by [`open_reader`]. +pub type SharedBytes = Arc; + +/// File extensions recognised at import (the media browser filters on these). +pub const STILL_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "tga", "dpx", "exr", "hdr", "dng"]; +pub const AUDIO_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "mp3", "mp2", "m4a", "aac", "flac", "ogg", "opus"]; +pub const VIDEO_EXTENSIONS: &[&str] = &[ + "mp4", "m4v", "mov", "mkv", "webm", "avi", "mxf", "mts", "m2ts", "m2t", "ts", "mpg", "mpeg", "vob", "mod", "tod", "m2v", "m1v", "mpv", "3gp", + "y4m", "apv", +]; + +/// True when `path` has a still, audio, or video extension we recognise, ignoring case. +pub fn is_importable(path: &Path) -> bool { + let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + STILL_EXTENSIONS.contains(&ext.as_str()) || AUDIO_EXTENSIONS.contains(&ext.as_str()) || VIDEO_EXTENSIONS.contains(&ext.as_str()) +} + +/// A pluggable in-memory opener. Returns `None` when the format is not this opener's. +pub type Opener = fn(name: &str, bytes: Arc<[u8]>) -> Option>; + +/// Opens a container from a reader: `head` is the first bytes of the file (for sniffing). +/// Returns `None` when the format is not this opener's. +pub type ReaderOpener = fn(name: &str, head: &[u8], reader: &SharedBytes) -> Option>; + +/// Bytes sniffed by [`open_reader`]. +pub const HEAD_LEN: usize = 64 * 1024; + +/// Default ceiling for a whole-file fallback or an offline output buffer (256 MiB). +/// Streaming openers are tried first. Use open_reader_within for an explicit different file budget. +pub const DEFAULT_MAX_MEDIA_BYTES: usize = 256 << 20; + +fn allocate(len: usize, max_bytes: usize) -> io::Result> { + if len.checked_mul(std::mem::size_of::()).is_none_or(|bytes| bytes > max_bytes || bytes > isize::MAX as usize) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "media buffer exceeds allocation limit")); + } + let mut out = Vec::new(); + out.try_reserve_exact(len).map_err(|e| io::Error::other(format!("cannot allocate media buffer: {e}")))?; + out.resize(len, T::default()); + Ok(out) +} + +fn io_named(name: &str, e: io::Error) -> MediaError { + MediaError::Io(format!("{name}: {e}")) +} + +/// Read `len` bytes at `offset` (fewer at the end of the source). +pub fn read_range(r: &dyn ByteSource, offset: u64, len: usize) -> io::Result> { + read_range_within(r, offset, len, DEFAULT_MAX_MEDIA_BYTES) +} + +fn read_range_within(r: &dyn ByteSource, offset: u64, len: usize, max_bytes: usize) -> io::Result> { + let n = usize::try_from(r.len().saturating_sub(offset).min(len as u64)) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "media length is not representable"))?; + let mut v = allocate(n, max_bytes)?; + r.read_at(offset, &mut v)?; + Ok(v) +} + +/// Open media from bytes by trying `extra` openers in order. There is no built-in fallback: +/// stills, WAV, and generators stay in the apps and register here. +pub fn open_bytes(name: &str, bytes: Arc<[u8]>, extra: &[Opener]) -> Result { + for o in extra { + if let Some(r) = o(name, bytes.clone()) { + return r; + } + } + Err(MediaError::Unsupported(format!("{name}: unrecognised format"))) +} + +/// Open media from a reader: `reader_openers` first; otherwise read the whole file (if it fits in +/// `max_whole`) and use [`open_bytes`] with `extra`. +pub fn open_reader(name: &str, reader: SharedBytes, reader_openers: &[ReaderOpener], extra: &[Opener]) -> Result { + open_reader_within(name, reader, reader_openers, extra, DEFAULT_MAX_MEDIA_BYTES as u64) +} + +/// Like [`open_reader`], but a file no reader opener takes is read whole only up to `max_whole` +/// bytes; a larger one is refused instead. For looking at files rather than importing them: +/// reading a multi-gigabyte file into memory to show its duration, or to find out it isn't +/// supported, thrashes the disk. +pub fn open_reader_within( + name: &str, + reader: SharedBytes, + reader_openers: &[ReaderOpener], + extra: &[Opener], + max_whole: u64, +) -> Result { + let head = read_range(&*reader, 0, HEAD_LEN).map_err(|e| io_named(name, e))?; + for o in reader_openers { + if let Some(r) = o(name, &head, &reader) { + return r; + } + } + if extra.is_empty() { + return Err(MediaError::Unsupported(format!("{name}: unrecognised format"))); + } + if reader.len() > max_whole { + return Err(MediaError::Unsupported(format!("{name}: no streaming reader for this format, and it is too large to read whole here"))); + } + let len = usize::try_from(reader.len()).map_err(|_| MediaError::Unsupported(format!("{name}: media length is not representable")))?; + let budget = usize::try_from(max_whole).unwrap_or(usize::MAX); + let all = read_range_within(&*reader, 0, len, budget).map_err(|e| io_named(name, e))?; + open_bytes(name, all.into(), extra) +} + +/// Open a regular file through the shared pooled FileReader. Non-files (including FIFOs) +/// are refused without a blocking open, using the same contract as other media readers. +#[cfg(not(target_arch = "wasm32"))] +pub fn open_path(path: &Path, reader_openers: &[ReaderOpener], extra: &[Opener]) -> Result { + let file = craft_media::FileReader::open(path).map_err(|e| MediaError::Io(format!("{}: {e}", path.display())))?; + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + open_reader(&name, Arc::new(file), reader_openers, extra) +} + +fn audio_channels(info: &MediaInfo) -> u16 { + info.audio().map_or(2, |a| u16::try_from(a.channels).unwrap_or(u16::MAX).max(1)) +} + +/// A source that renders a solid slate (used for offline media). +pub struct OfflineSource { + pub info: MediaInfo, +} + +impl MediaSource for OfflineSource { + fn info(&self) -> &MediaInfo { + &self.info + } + fn video_frame(&self, req: FrameRequest) -> Result> { + let v = self.info.video.as_ref().ok_or(MediaError::NoStream("video"))?; + if !req.scale.is_finite() || req.scale <= 0.0 || v.width == 0 || v.height == 0 { + return Err(MediaError::Decode("invalid offline frame dimensions or scale".into())); + } + let s = req.scale.clamp(0.02, 1.0); + let (w, h) = (((v.width as f32 * s) as u32).max(2), ((v.height as f32 * s) as u32).max(2)); + let samples = usize::try_from(w) + .ok() + .and_then(|w| usize::try_from(h).ok().and_then(|h| w.checked_mul(h))) + .and_then(|pixels| pixels.checked_mul(4)) + .ok_or_else(|| MediaError::Decode("offline frame dimensions overflow".into()))?; + let mut px = allocate::(samples, DEFAULT_MAX_MEDIA_BYTES)?; + for p in px.as_chunks_mut::<4>().0 { + p.copy_from_slice(&[140, 16, 16, 255]); + } + Ok(Arc::new(VideoFrame::rgba8(w, h, px).map_err(|e| MediaError::Decode(e.to_string()))?.with_pts(req.time))) + } + fn audio(&self, _start: i64, frames: usize, sample_rate: u32) -> Result { + let channels = usize::from(audio_channels(&self.info)); + let bytes = frames + .checked_mul(channels) + .and_then(|n| n.checked_mul(std::mem::size_of::())) + .ok_or_else(|| MediaError::Decode("offline audio dimensions overflow".into()))?; + if bytes > DEFAULT_MAX_MEDIA_BYTES { + return Err(MediaError::Decode("offline audio exceeds allocation limit".into())); + } + let mut planes = Vec::new(); + planes.try_reserve_exact(channels).map_err(|e| MediaError::Io(e.to_string()))?; + for _ in 0..channels { + planes.push(allocate::(frames, DEFAULT_MAX_MEDIA_BYTES)?); + } + Ok(AudioBuffer { sample_rate, channels: planes }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn silent(name: &str, kind: MediaKind) -> OfflineSource { + OfflineSource { + info: MediaInfo { + name: name.into(), + kind, + duration: Tick::from_seconds_f64(1.0), + video: Some(VideoStreamInfo { + width: 16, + height: 8, + frame_rate: FrameRate::FPS_24, + par: (1, 1), + codec: "slate".into(), + pixel_format: "rgba8".into(), + color: ColorInfo::default(), + has_alpha: false, + bitrate: None, + hdr: None, + }), + audio_streams: vec![AudioStreamInfo { sample_rate: 48000, channels: 2, codec: "pcm".into(), bits_per_sample: Some(32) }], + container: "none".into(), + start_timecode: None, + file_size: None, + }, + } + } + + fn accept_ok(name: &str, _bytes: Arc<[u8]>) -> Option> { + if name.ends_with(".ok") { Some(Ok(Arc::new(silent(name, MediaKind::Synthetic)))) } else { None } + } + + fn reject_all(_name: &str, _bytes: Arc<[u8]>) -> Option> { + None + } + + fn boom(name: &str, _bytes: Arc<[u8]>) -> Option> { + Some(Err(MediaError::Decode(format!("{name}: boom")))) + } + + fn reader_ok(name: &str, head: &[u8], _reader: &SharedBytes) -> Option> { + if head.starts_with(b"OK") { Some(Ok(Arc::new(silent(name, MediaKind::Movie)))) } else { None } + } + + struct HugeSource; + impl ByteSource for HugeSource { + fn len(&self) -> u64 { + u64::MAX + } + fn read_at(&self, _offset: u64, buf: &mut [u8]) -> io::Result<()> { + assert!(buf.len() <= HEAD_LEN, "must reject whole-file allocation before reading"); + buf.fill(0); + Ok(()) + } + } + + #[test] + fn whole_file_fallback_and_explicit_ranges_are_bounded() { + let reader: SharedBytes = Arc::new(HugeSource); + assert!(open_reader("large.ok", reader.clone(), &[], &[accept_ok]).is_err()); + assert!(open_reader_within("large.ok", reader.clone(), &[], &[accept_ok], u64::MAX).is_err()); + assert!(read_range(&HugeSource, 0, usize::MAX).is_err()); + assert!(read_range_within(&HugeSource, 0, 10, 9).is_err()); + assert_eq!(read_range_within(&HugeSource, 0, 10, 10).unwrap(), vec![0; 10]); + } + + struct SniffOnlySource(std::sync::atomic::AtomicUsize); + impl ByteSource for SniffOnlySource { + fn len(&self) -> u64 { + u64::MAX + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + assert_eq!(offset, 0); + assert_eq!(buf.len(), HEAD_LEN); + assert_eq!(self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst), 0, "must only sniff once"); + buf.fill(0); + buf[..2].copy_from_slice(b"OK"); + Ok(()) + } + } + + #[test] + fn no_fallback_stops_after_sniff_and_streaming_opener_precedes_size_cap() { + let reader = Arc::new(SniffOnlySource(std::sync::atomic::AtomicUsize::new(0))); + let error = open_reader("unknown", reader.clone(), &[], &[]).err().unwrap(); + assert!(matches!(error, MediaError::Unsupported(_))); + assert_eq!(reader.0.load(std::sync::atomic::Ordering::SeqCst), 1); + let reader = Arc::new(SniffOnlySource(std::sync::atomic::AtomicUsize::new(0))); + let source = open_reader_within("large.mov", reader.clone(), &[reader_ok], &[accept_ok], 0).unwrap(); + assert_eq!(source.info().kind, MediaKind::Movie); + assert_eq!(reader.0.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[test] + fn hostile_offline_metadata_and_requests_are_errors() { + let mut source = silent("bad", MediaKind::Synthetic); + source.info.video.as_mut().unwrap().width = u32::MAX; + source.info.video.as_mut().unwrap().height = u32::MAX; + assert!(source.video_frame(FrameRequest::full(Tick::ZERO)).is_err()); + assert!(source.audio(0, usize::MAX, 48000).is_err()); + let source = silent("bad-scale", MediaKind::Synthetic); + for scale in [f32::NAN, f32::INFINITY, 0.0, -1.0] { + assert!(source.video_frame(FrameRequest { time: Tick::ZERO, scale }).is_err()); + } + } + + #[cfg(unix)] + #[test] + fn open_path_refuses_a_fifo_without_waiting_for_a_writer() { + let root = std::env::temp_dir().join(format!("craft-media-source-fifo-{}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + let path = root.join("fifo"); + if std::process::Command::new("mkfifo").arg(&path).status().is_ok_and(|s| s.success()) { + assert!(open_path(&path, &[], &[]).is_err()); + std::fs::remove_file(&path).unwrap(); + } + std::fs::remove_dir(&root).unwrap(); + } + + #[test] + fn importable_extensions_match_regardless_of_case() { + for name in ["clip.mov", "clip.MOV", "clip.Mov", "shot.MP4", "IMG_0001.JPG", "sound.WAV", "take.M2TS"] { + assert!(is_importable(Path::new(name)), "{name}"); + } + assert!(!is_importable(Path::new("notes.txt"))); + } + + #[test] + fn open_bytes_tries_extra_in_order_and_otherwise_is_unsupported() { + let bytes: Arc<[u8]> = Arc::from(&b"xxxx"[..]); + let err = open_bytes("a.bin", bytes.clone(), &[]).err().expect("expected error"); + assert!(matches!(err, MediaError::Unsupported(_))); + let err = open_bytes("a.bin", bytes.clone(), &[reject_all, accept_ok]).err().expect("expected error"); + assert!(matches!(err, MediaError::Unsupported(_))); + let src = open_bytes("clip.ok", bytes.clone(), &[reject_all, accept_ok]).unwrap(); + assert_eq!(src.info().name, "clip.ok"); + let err = open_bytes("clip.ok", bytes, &[boom, accept_ok]).err().expect("expected error"); + assert!(matches!(err, MediaError::Decode(_))); + } + + #[test] + fn open_reader_uses_reader_openers_then_falls_back_within_max_whole() { + let small: SharedBytes = Arc::new(b"HELLO".to_vec()); + let err = open_reader("a.bin", small.clone(), &[], &[]).err().expect("expected error"); + assert!(matches!(err, MediaError::Unsupported(_))); + + let ok: SharedBytes = Arc::new(b"OK-file".to_vec()); + let src = open_reader("clip.mov", ok, &[reader_ok], &[]).unwrap(); + assert_eq!(src.info().kind, MediaKind::Movie); + + let tagged: SharedBytes = Arc::new(b"xxxx".to_vec()); + let src = open_reader("clip.ok", tagged.clone(), &[], &[accept_ok]).unwrap(); + assert_eq!(src.info().name, "clip.ok"); + + let big = vec![0u8; HEAD_LEN + 8]; + let r: SharedBytes = Arc::new(big); + let e = open_reader_within("a.avi", r, &[], &[accept_ok], HEAD_LEN as u64).err().expect("expected error"); + assert!(matches!(e, MediaError::Unsupported(s) if s.contains("too large"))); + } + + #[test] + fn audio_streams_serde_accepts_legacy_single_object() { + let stream = r#"{"sample_rate":48000,"channels":2,"codec":"pcm","bits_per_sample":null}"#; + let prefix = r#"{"name":"a","kind":"Movie","duration":0,"video":null,"audio_streams":["#; + let suffix = r#"],"container":"wav","start_timecode":null,"file_size":null}"#; + let full = std::iter::repeat_n(stream, MAX_AUDIO_STREAMS).collect::>().join(","); + let info: MediaInfo = serde_json::from_str(&format!("{prefix}{full}{suffix}")).unwrap(); + assert_eq!(info.audio_streams.len(), MAX_AUDIO_STREAMS); + for extra in [stream, r#"{"malformed":"not an audio stream"}"#] { + let error = serde_json::from_str::(&format!("{prefix}{full},{extra}{suffix}")).unwrap_err(); + assert!(error.to_string().contains("MAX_AUDIO_STREAMS"), "{error}"); + } + let many = r#"{"name":"a","kind":"Movie","duration":0,"video":null,"audio_streams":[{"sample_rate":48000,"channels":2,"codec":"pcm","bits_per_sample":null}],"container":"wav","start_timecode":null,"file_size":null}"#; + let info: MediaInfo = serde_json::from_str(many).unwrap(); + assert_eq!(info.audio_streams.len(), 1); + let one = r#"{"name":"a","kind":"AudioOnly","duration":0,"video":null,"audio":{"sample_rate":44100,"channels":1,"codec":"pcm","bits_per_sample":16},"container":"wav","start_timecode":null,"file_size":null}"#; + let info: MediaInfo = serde_json::from_str(one).unwrap(); + assert_eq!(info.audio().map(|a| a.sample_rate), Some(44100)); + let none = r#"{"name":"a","kind":"Still","duration":0,"video":null,"audio":null,"container":"png","start_timecode":null,"file_size":null}"#; + let info: MediaInfo = serde_json::from_str(none).unwrap(); + assert!(info.audio_streams.is_empty()); + } + + #[test] + fn offline_source_returns_slate_and_silence() { + let src = silent("off", MediaKind::Synthetic); + let frame = src.video_frame(FrameRequest::full(Tick::ZERO)).unwrap(); + assert_eq!((frame.width, frame.height), (16, 8)); + assert_eq!(frame.pts, Tick::ZERO); + let audio = src.audio(0, 8, 48000).unwrap(); + assert_eq!(audio.sample_rate, 48000); + assert_eq!(audio.num_channels(), 2); + assert_eq!(audio.frames(), 8); + assert!(src.audio_stream(1, 0, 8, 48000).is_err()); + } +} diff --git a/crates/media/src/file.rs b/crates/media/src/file.rs new file mode 100644 index 000000000..f343737b3 --- /dev/null +++ b/crates/media/src/file.rs @@ -0,0 +1,361 @@ +//! Pooled file [`ByteSource`]s: many clips can be open at once without holding a descriptor each. +//! +//! Past [`MAX_OPEN_FILES`] retained pool entries, the least recently read file is closed and +//! reopened by path on demand, so a project with hundreds of sources does not hit the process +//! file-descriptor limit (often 256 on macOS, 1024 on Linux). The cap does not bound in-flight +//! `Arc` handles: a file another thread is mid-read stays open until that read ends. + +#![cfg(not(target_arch = "wasm32"))] + +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use crate::source::ByteSource; + +fn eof() -> io::Error { + io::Error::new(io::ErrorKind::UnexpectedEof, "read past end of byte source") +} + +/// Open `path` for reading without blocking on a FIFO that was swapped in after the metadata check +/// (`O_NONBLOCK`; it changes nothing for a regular file, and the callers check the handle's type). +/// `O_NONBLOCK` has no std constant (no libc dependency here): it is 0o4000 on most Linux targets, +/// 0x80 on Linux MIPS, 0x4000 on Linux SPARC and 4 on the BSD family, and the open stays a plain +/// one on any other target. +fn open_nonblocking(path: &Path) -> io::Result { + let mut o = std::fs::OpenOptions::new(); + o.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + #[cfg(all( + any(target_os = "linux", target_os = "android"), + any(target_arch = "mips", target_arch = "mips32r6", target_arch = "mips64", target_arch = "mips64r6") + ))] + o.custom_flags(0x80); + #[cfg(all(any(target_os = "linux", target_os = "android"), any(target_arch = "sparc", target_arch = "sparc64")))] + o.custom_flags(0x4000); + #[cfg(all( + any(target_os = "linux", target_os = "android"), + not(any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "sparc", + target_arch = "sparc64" + )) + ))] + o.custom_flags(0o4000); + #[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + target_os = "dragonfly" + ))] + o.custom_flags(0x4); + } + o.open(path) +} + +fn not_a_file(path: &Path) -> io::Error { + io::Error::new(io::ErrorKind::NotFound, format!("{} is not a file", path.display())) +} + +/// Retained pool entries [`FileReader`]s keep open at most, together. Past this many, the least +/// recently read file is closed and its reader reopens it on demand. The cap does not bound +/// in-flight `Arc` handles: a file another thread is mid-read stays open until that read ends, +/// even if the pool has already evicted its entry. +pub const MAX_OPEN_FILES: usize = 128; + +/// The open files of a set of [`FileReader`]s, least recently used first. +#[derive(Debug)] +pub(crate) struct FilePool { + cap: usize, + state: std::sync::Mutex, +} + +#[derive(Debug, Default)] +struct PoolState { + next_id: u64, + open: std::collections::VecDeque<(u64, Arc)>, +} + +impl FilePool { + pub(crate) fn new(cap: usize) -> Self { + Self { cap: cap.max(1), state: Default::default() } + } + + fn state(&self) -> std::sync::MutexGuard<'_, PoolState> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn next_id(&self) -> u64 { + let mut s = self.state(); + s.next_id = s.next_id.wrapping_add(1); + s.next_id + } + + /// The open file of reader `id`, now the most recently used. + fn get(&self, id: u64) -> Option> { + let mut s = self.state(); + let at = s.open.iter().position(|(i, _)| *i == id)?; + let entry = s.open.remove(at)?; + let file = entry.1.clone(); + s.open.push_back(entry); + Some(file) + } + + /// Keep `file` open for reader `id`, closing the least recently used files past the cap. A + /// file another thread is reading from stays open until that read ends. + fn insert(&self, id: u64, file: std::fs::File) -> Arc { + let mut s = self.state(); + if let Some((_, open)) = s.open.iter().find(|(i, _)| *i == id) { + return open.clone(); // another thread reopened it first + } + let file = Arc::new(file); + s.open.push_back((id, file.clone())); + while s.open.len() > self.cap { + s.open.pop_front(); + } + file + } + + fn remove(&self, id: u64) { + self.state().open.retain(|(i, _)| *i != id); + } + + #[cfg(test)] + fn open_count(&self) -> usize { + self.state().open.len() + } +} + +static FILE_POOL: std::sync::LazyLock> = std::sync::LazyLock::new(|| Arc::new(FilePool::new(MAX_OPEN_FILES))); + +/// A file on disk, read in place: only the requested ranges are read, so opening a clip costs its +/// index rather than its size. The file is kept open in a shared pool of at most +/// [`MAX_OPEN_FILES`] and reopened by path when the pool closed it. +#[derive(Debug)] +pub struct FileReader { + path: PathBuf, + len: u64, + id: u64, + pool: Arc, +} + +impl FileReader { + /// Open `path` in the process-wide pool. + pub fn open(path: &Path) -> io::Result { + Self::open_in(path, &FILE_POOL) + } + + pub(crate) fn open_in(path: &Path, pool: &Arc) -> io::Result { + // Resolve once against this process's cwd, so a later cwd change cannot + // make a reopen after eviction open a different file of the same length. + let path = std::path::absolute(path)?; + // checked before opening: opening a named pipe with no writer blocks the caller for good + if !std::fs::metadata(&path)?.is_file() { + return Err(not_a_file(&path)); + } + let file = open_nonblocking(&path)?; + let m = file.metadata()?; + if !m.is_file() { + return Err(not_a_file(&path)); + } + let id = pool.next_id(); + pool.insert(id, file); + Ok(Self { path, len: m.len(), id, pool: pool.clone() }) + } + + /// The open file, reopened when the pool closed it. A file now shorter than when it was opened + /// (replaced or truncated) is refused rather than read as the old one; a longer one (still + /// being written) is read up to the opened length. + fn file(&self) -> io::Result> { + if let Some(file) = self.pool.get(self.id) { + let m = file.metadata()?; + if m.is_file() && m.len() >= self.len { + return Ok(file); + } + self.pool.remove(self.id); + return Err(io::Error::other(format!("{} changed since it was opened", self.path.display()))); + } + let file = open_nonblocking(&self.path)?; + let m = file.metadata()?; + if !m.is_file() || m.len() < self.len { + return Err(io::Error::other(format!("{} changed since it was opened", self.path.display()))); + } + Ok(self.pool.insert(self.id, file)) + } +} + +impl Drop for FileReader { + fn drop(&mut self) { + self.pool.remove(self.id); + } +} + +impl ByteSource for FileReader { + fn len(&self) -> u64 { + self.len + } + + /// Positional reads: threads decoding different parts of the file do not share a cursor. + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + if offset.checked_add(buf.len() as u64).is_none_or(|e| e > self.len) { + return Err(eof()); + } + let file = self.file()?; + file.read_at(offset, buf) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_reader_reads_ranges_in_place() { + let v: Vec = (0..=255).collect(); + let dir = craft_media_testkit::private_dir("file-reader"); + let path = dir.join("bytes.bin"); + std::fs::write(&path, &v).unwrap(); + let r = FileReader::open(&path).unwrap(); + assert_eq!(ByteSource::len(&r), 256); + let mut b = [0u8; 3]; + r.read_at(4, &mut b).unwrap(); + assert_eq!(&b, &v[4..7]); + // reads are positional: an earlier offset after a later one + r.read_at(0, &mut b).unwrap(); + assert_eq!(&b, &v[0..3]); + assert_eq!(r.read_at(254, &mut [0u8; 3]).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); + assert!(FileReader::open(&dir).is_err(), "a directory is not a media file"); + assert_eq!(FileReader::open(&dir.join("missing")).unwrap_err().kind(), io::ErrorKind::NotFound); + drop(r); + std::fs::remove_dir_all(&dir).ok(); + } + + /// More readers than the pool keeps open stay readable; past the cap the least recently read + /// file is closed and reopened on demand, and a file truncated meanwhile is refused. + #[test] + fn more_file_readers_than_the_pool_holds_stay_readable() { + let dir = craft_media_testkit::private_dir("file-pool"); + let pool = Arc::new(FilePool::new(2)); + let paths: Vec<_> = (0..5).map(|i| dir.join(format!("{i}.bin"))).collect(); + for (i, p) in paths.iter().enumerate() { + std::fs::write(p, format!("file{i}-0123456789")).unwrap(); + } + let readers: Vec<_> = paths.iter().map(|p| FileReader::open_in(p, &pool).unwrap()).collect(); + assert_eq!(pool.open_count(), 2); + for _ in 0..2 { + for (i, r) in readers.iter().enumerate() { + let mut b = [0u8; 5]; + r.read_at(0, &mut b).unwrap(); + assert_eq!(b, *format!("file{i}").as_bytes()); + assert!(pool.open_count() <= 2); + } + } + // reader 0 was closed by the later reads; its file is now shorter than when opened + std::fs::write(&paths[0], b"short").unwrap(); + let mut b = [0u8; 5]; + assert!(readers[0].read_at(0, &mut b).is_err()); + drop(readers); + assert_eq!(pool.open_count(), 0, "dropped readers close their files"); + std::fs::remove_dir_all(&dir).ok(); + } + + /// A named pipe with no writer would block `open` for good: refuse it first. + #[cfg(unix)] + #[test] + fn a_fifo_is_refused_without_blocking() { + let dir = craft_media_testkit::private_dir("file-fifo"); + let fifo = dir.join("pipe"); + if !std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()) { + return; // no mkfifo here + } + assert!(FileReader::open(&fifo).is_err()); + std::fs::remove_dir_all(&dir).ok(); + } + + /// The open itself must not block on a FIFO swapped in after the path check (a FIFO with no writer). + #[cfg(target_os = "linux")] + #[test] + fn opening_a_fifo_with_no_writer_does_not_block() { + let dir = craft_media_testkit::private_dir("file-fifo-open"); + let fifo = dir.join("pipe"); + if std::process::Command::new("mkfifo").arg(&fifo).status().is_ok_and(|s| s.success()) { + let f = super::open_nonblocking(&fifo).unwrap(); + assert!(!f.metadata().unwrap().is_file()); + } + std::fs::remove_dir_all(&dir).ok(); + } + + /// After eviction, a reader opened with a relative path must still read the original file + /// even if the process working directory has changed (same-length substitute in the new cwd). + /// The harness runs in a subprocess so it cannot change this process's cwd. + #[test] + fn reopening_a_relative_path_stays_on_the_original_file() { + const FLAG: &str = "CRAFT_MEDIA_FILE_READER_CWD_TEST"; + const ROOT: &str = "CRAFT_MEDIA_FILE_READER_CWD_ROOT"; + if std::env::var_os(FLAG).is_some() { + let root = PathBuf::from(std::env::var_os(ROOT).expect("test root")); + let a = root.join("a"); + let b = root.join("b"); + std::env::set_current_dir(&a).unwrap(); + let pool = Arc::new(FilePool::new(1)); + let reader = FileReader::open_in(Path::new("clip.bin"), &pool).unwrap(); + let _evict = FileReader::open_in(Path::new("other.bin"), &pool).unwrap(); + std::env::set_current_dir(&b).unwrap(); + let mut buf = [0u8; 4]; + reader.read_at(0, &mut buf).unwrap(); + assert_eq!(&buf, b"AAAA", "reopen must not follow the new cwd to b/clip.bin"); + return; + } + + let dir = craft_media_testkit::private_dir("file-cwd"); + std::fs::create_dir_all(dir.join("a")).unwrap(); + std::fs::create_dir_all(dir.join("b")).unwrap(); + std::fs::write(dir.join("a").join("clip.bin"), b"AAAA").unwrap(); + std::fs::write(dir.join("a").join("other.bin"), b"XXXX").unwrap(); + std::fs::write(dir.join("b").join("clip.bin"), b"BBBB").unwrap(); + let exe = std::env::current_exe().unwrap(); + let out = std::process::Command::new(&exe) + .env(FLAG, "1") + .env(ROOT, &dir) + .env("RUST_TEST_THREADS", "1") + .args(["--exact", "file::tests::reopening_a_relative_path_stays_on_the_original_file"]) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + out.status.success() + && stdout.contains("test file::tests::reopening_a_relative_path_stays_on_the_original_file") + && stdout.contains("ok"), + "subprocess failed\nstatus: {:?}\nstdout:\n{stdout}\nstderr:\n{stderr}", + out.status + ); + std::fs::remove_dir_all(&dir).ok(); + } + + /// A file truncated while its handle is still in the pool is refused, same as after eviction. + #[test] + fn a_truncated_file_is_refused_while_still_pooled() { + let dir = craft_media_testkit::private_dir("file-trunc-hit"); + let path = dir.join("clip.bin"); + std::fs::write(&path, b"0123456789").unwrap(); + let pool = Arc::new(FilePool::new(2)); + let reader = FileReader::open_in(&path, &pool).unwrap(); + assert_eq!(pool.open_count(), 1); + let mut b = [0u8; 5]; + reader.read_at(0, &mut b).unwrap(); + assert_eq!(&b, b"01234"); + std::fs::write(&path, b"short").unwrap(); + assert!(reader.read_at(0, &mut b).is_err(), "truncation must be refused on a cache hit too"); + drop(reader); + assert_eq!(pool.open_count(), 0); + std::fs::remove_dir_all(&dir).ok(); + } +} diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index a9c812318..32bd583d8 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -14,6 +14,8 @@ //! program streams). //! - [`Container`] and [`CodecId`] (no feature): the identifiers the codec crates report a file's //! container and codec with. +//! - `FileReader` (native): a pooled file `ByteSource` so many clips can be open without holding a +//! descriptor each. //! //! `bitstream` and `isobmff` are on by default; `matroska`, `ogg`, `avi`, `mxf` and `mpegts` are opt-in. A crate that needs //! only bit I/O uses `default-features = false, features = ["bitstream"]`. @@ -22,6 +24,8 @@ pub mod avi; #[cfg(feature = "bitstream")] pub mod bitstream; +#[cfg(not(target_arch = "wasm32"))] +mod file; mod id; #[cfg(feature = "isobmff")] pub mod isobmff; @@ -34,6 +38,8 @@ pub mod mxf; #[cfg(feature = "ogg")] pub mod ogg; pub mod source; +#[cfg(not(target_arch = "wasm32"))] +pub use file::{FileReader, MAX_OPEN_FILES}; pub use id::{CodecId, CodecParams, Container, PcmFormat, xiph_lace}; pub use source::{ByteSource, ReadSeekSource}; diff --git a/crates/odf/src/text/shapes.rs b/crates/odf/src/text/shapes.rs index 7c08151aa..eb184f5c9 100644 --- a/crates/odf/src/text/shapes.rs +++ b/crates/odf/src/text/shapes.rs @@ -124,7 +124,8 @@ pub(super) fn element_of(kind: ShapeKind) -> (&'static str, Option<&'static str> ShapeKind::ArrowDown => custom("down-arrow"), ShapeKind::Star => custom("star5"), ShapeKind::Heart => custom("heart"), - ShapeKind::Freeform => ("draw:path", None), + // A frame reaches the writer as the freeform it draws (see `model::from_doc`). + ShapeKind::Freeform | ShapeKind::Frame => ("draw:path", None), ShapeKind::Rectangle | ShapeKind::TextBox => ("draw:rect", None), } } diff --git a/crates/odf/src/text/tests.rs b/crates/odf/src/text/tests.rs index 8d7af18dc..da00b350c 100644 --- a/crates/odf/src/text/tests.rs +++ b/crates/odf/src/text/tests.rs @@ -442,6 +442,41 @@ fn table_column_widths_survive_a_round_trip() { assert_eq!(grid(&back), widths); } +#[test] +fn narrow_table_columns_keep_their_width() { + // Columns of a few points stay as the file gives them, so the table stays as wide as its source. + let content = format!( + r##"AB"## + ); + let doc = import(&package(&content, None)).unwrap(); + let grid_of = |doc: &craft_wordmodel::Document| { + doc.body.iter().find_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t.grid.clone()) } else { None }) + }; + assert_eq!(grid_of(&doc), Some(vec![3.0, 100.0])); + // Saved and opened again, the narrow column is still the file's width. + let back = import(&export(&doc).unwrap()).unwrap(); + let grid = grid_of(&back).unwrap(); + assert_eq!(grid.len(), 2, "{grid:?}"); + assert!((grid[0] - 3.0).abs() < 0.01 && (grid[1] - 100.0).abs() < 0.01, "{grid:?}"); +} + +#[test] +fn table_columns_of_a_point_or_less_give_equal_columns() { + // A column of a point or less, nothing or NaN (a damaged or hostile file) is no width to + // lay out: the whole grid falls back to equal columns, and nothing reaches layout below a + // point, negative or not a number. + for bad in ["1pt", "0.5pt", "0pt", "-3pt", "NaNpt"] { + let content = format!( + r##"AB"## + ); + let doc = import(&package(&content, None)).unwrap(); + let grid = doc.body.iter().find_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t.grid.clone()) } else { None }).unwrap(); + assert_eq!(grid.len(), 2, "{bad}: {grid:?}"); + assert!(grid.iter().all(|w| w.is_finite() && *w > 1.0), "{bad}: {grid:?}"); + assert_eq!(grid[0], grid[1], "{bad}: equal columns, {grid:?}"); + } +} + #[test] fn table_without_column_widths_keeps_the_equal_split() { let content = format!( diff --git a/crates/odf/src/text/tests_more/shapes.rs b/crates/odf/src/text/tests_more/shapes.rs index f6bbe9ae8..8d1a9d5fd 100644 --- a/crates/odf/src/text/tests_more/shapes.rs +++ b/crates/odf/src/text/tests_more/shapes.rs @@ -188,3 +188,44 @@ fn a_shape_with_only_an_empty_paragraph_has_no_text() { let stories: Vec = d.body.iter().filter_map(|b| b.as_para()).flat_map(|p| p.objects.iter()).map(|o| o.text_box().is_some()).collect(); assert_eq!(stories, [false, false, true, false, false, false]); } + +/// A frame shape (a letterhead's page border, from DOCX `frame`), which ODT has no shape for, +/// is written as the outline it draws: its outer edge and its hole, so LibreOffice doesn't fill +/// the whole box; read back, it is that freeform, hole and all. +#[test] +fn a_frame_shape_is_written_as_a_border_with_a_hole() { + let mut p = Paragraph::new(); + p.text.push(OBJ); + p.objects.push(InlineObject::Shape { + kind: ShapeKind::Frame, + w: 200.0, + h: 100.0, + fill: Some(craft_wordmodel::fill::Fill::solid(Rgb(1, 2, 3))), + stroke: None, + stroke_width: 0.0, + float: Default::default(), + story: None, + freeform: None, + effects: Default::default(), + // A border a tenth of the shorter side: 10 pt. + extra: craft_wordmodel::connector::ShapeExtra { corner: Some(10_000), ..Default::default() }, + }); + p.runs = vec![craft_wordmodel::para::Run { len: p.text.len(), props: Default::default() }]; + let mut d = Document::new(); + d.body = vec![para_block(p)]; + let odt = export(&d).unwrap(); + let content = content_of(&odt); + assert!(content.contains("= 9.5 * sx && *x <= 190.5 * sx && *y >= 9.5 * sy && *y <= 90.5 * sy), "{hole:?}"); +} diff --git a/crates/pptx/tests/read.rs b/crates/pptx/tests/read.rs index 5fe263f02..fd03d2d98 100644 --- a/crates/pptx/tests/read.rs +++ b/crates/pptx/tests/read.rs @@ -217,23 +217,52 @@ fn other_files_are_refused() { assert!(craft_pptx::import_theme(&doc).is_err()); } -/// Groups nested past 32 levels are cut there; the rest of the slide is read. -#[test] -fn deep_group_nesting_is_cut() { +/// A slide whose group tree is 40 levels deep, with a shape after it. +fn deep_group_deck() -> Vec { let open = r#""#; let tree = format!("{}{}{}", open.repeat(40), sp(4, "Deep", "", XFRM, "x"), "".repeat(40)); let pres = format!(r#""#); let slide = format!(r#"{tree}{}"#, sp(5, "Top", "", XFRM, "y")); - let bytes = package( + package( &[ ("ppt/presentation.xml", CT_PRES, pres), ("ppt/slides/slide1.xml", "application/vnd.openxmlformats-officedocument.presentationml.slide+xml", slide), ], &[("", &[("officeDocument", "ppt/presentation.xml")]), ("ppt/presentation.xml", &[("slide", "slides/slide1.xml")])], - ); + ) +} + +/// Groups nested past 32 levels are cut there; the rest of the slide is read. +#[test] +fn deep_group_nesting_is_cut() { + let bytes = deep_group_deck(); let p = craft_pptx::import(&bytes, &Plain).unwrap(); let mut depth = 0; craft_pptx::walk(&p.slides[0].shapes, &mut |_, d| depth = depth.max(d)); assert_eq!(depth, 32, "33 levels of groups, the last one empty"); assert!(p.slides[0].shapes.iter().any(|s| s.name == "Top")); } + +/// The group reader recurses once per nesting level and keeps a `Shape` per level on the stack, so +/// anything that makes `Shape` (or `TextBody`/`ListStyle` inside it) bigger shows up here first. +/// A debug build is the worst case, so import the deepest accepted tree on a stack that is small +/// but ample for the current size: measured in a Linux debug build, this import needs about +/// 1.3 MiB, and about 2 MiB when `ListStyle` holds its `defPPr` level inline. Fails with a stack +/// overflow (the process aborts) when a type on the recursive path grows by value. Linux only: +/// frame sizes differ per platform, and the Windows CI runs `deep_group_nesting_is_cut` on the +/// default stack, where that growth first showed up. +#[test] +#[cfg(target_os = "linux")] +fn deep_group_import_fits_a_small_stack() { + const STACK: usize = 1664 * 1024; + std::thread::Builder::new() + .stack_size(STACK) + .spawn(|| { + let bytes = deep_group_deck(); + let p = craft_pptx::import(&bytes, &Plain).unwrap(); + assert!(p.slides[0].shapes.iter().any(|s| s.name == "Top")); + }) + .unwrap() + .join() + .unwrap(); +} diff --git a/crates/pptx/tests/write.rs b/crates/pptx/tests/write.rs index bec5fb239..46f7513e7 100644 --- a/crates/pptx/tests/write.rs +++ b/crates/pptx/tests/write.rs @@ -1,5 +1,7 @@ //! The writer, read back with the reader. +mod common; + use std::sync::Arc; use craft_pptx::table::{Cell, Table}; @@ -193,6 +195,127 @@ fn reads_the_theme_of_a_pptx_and_of_a_thmx() { } } +const NS_A: &str = "http://schemas.openxmlformats.org/drawingml/2006/main"; +const NS_P: &str = "http://schemas.openxmlformats.org/presentationml/2006/main"; +const NS_THM15: &str = "http://schemas.microsoft.com/office/thememl/2012/main"; + +/// The namespace of every element named `local` in `xml`, resolved through the declarations in +/// scope (`""` for none). +fn namespaces_of(xml: &str, local: &str) -> Vec { + fn rec(e: &craft_xml::El, scope: &mut Vec<(String, String)>, local: &str, out: &mut Vec) { + let n = scope.len(); + scope.extend(e.ns_decls().map(|(p, u)| (p.to_string(), u.to_string()))); + if e.local() == local { + out.push(scope.iter().rev().find(|(p, _)| p == e.prefix()).map(|(_, u)| u.clone()).unwrap_or_default()); + } + for c in e.elements() { + rec(c, scope, local, out); + } + scope.truncate(n); + } + let root = craft_xml::Options::default().strict().parse(xml.as_bytes()).unwrap_or_else(|e| panic!("not well-formed: {e}\n{xml}")); + let mut out = vec![]; + rec(&root, &mut vec![], local, &mut out); + out +} + +/// A theme with a custom colour list and a theme family id, with the `a:` prefix. +const PREFIXED_THEME: &str = r#""#; + +/// The deck with its theme part replaced by `theme`. +fn with_theme(theme: &str) -> Vec { + let pptx = craft_pptx::export(&deck(), &Plain).unwrap(); + common::rewrite(&pptx, |name, data| Some(if name == "ppt/theme/theme1.xml" { theme.as_bytes().to_vec() } else { data.to_vec() }), &[]) +} + +/// A theme written with a default namespace instead of the `a:` prefix: the parts kept as +/// written (custom colours, theme family id) stay in the DrawingML namespace on save. +#[test] +fn a_default_namespace_theme_keeps_its_kept_parts_in_the_drawingml_namespace() { + let theme = PREFIXED_THEME.replace("").expect("themeElements")..].to_string(); + let twice = craft_pptx::export(&craft_pptx::import(&once, &Plain).unwrap(), &Plain).unwrap(); + assert_eq!(kept(&part(&twice, "ppt/theme/theme1.xml")), kept(&xml)); +} + +/// The same theme with the `a:` prefix: the kept parts are written as before (each declaring +/// the `a:` it uses), with no default namespace added. +#[test] +fn a_prefixed_theme_keeps_its_kept_parts_unchanged() { + let p = craft_pptx::import(&with_theme(PREFIXED_THEME), &Plain).unwrap(); + let xml = part(&craft_pptx::export(&p, &Plain).unwrap(), "ppt/theme/theme1.xml"); + assert!(!xml.contains(r#" xmlns=""#), "{xml}"); + let a = format!(r#"xmlns:a="{NS_A}""#); + let kept = format!( + r#""# + ); + assert!(xml.contains(&kept), "{xml}"); +} + +/// The deck with part `name` (root `root`) given a default PresentationML namespace and an +/// unprefixed extension list, saved again: the part as written. +fn default_namespace_extensions(name: &str, root: &str) -> String { + let pptx = craft_pptx::export(&deck(), &Plain).unwrap(); + let ext = r#""#; + let (open, close) = (format!("<{root} "), format!("")); + let doc = common::rewrite( + &pptx, + |n, data| { + if n != name { + return Some(data.to_vec()); + } + let xml = String::from_utf8(data.to_vec()).unwrap(); + assert!(xml.contains(&open) && xml.contains(&close) && !xml.contains("extLst"), "{xml}"); + Some(xml.replacen(&open, &format!(r#"<{root} xmlns="{NS_P}" "#), 1).replace(&close, &format!("{ext}{close}")).into_bytes()) + }, + &[], + ); + let p = craft_pptx::import(&doc, &Plain).unwrap(); + part(&craft_pptx::export(&p, &Plain).unwrap(), name) +} + +/// The namespaces of the `ext` elements in `xml` other than DrawingML's `a:ext` (an extent). +fn extension_namespaces(xml: &str) -> Vec { + namespaces_of(xml, "ext").into_iter().filter(|n| n != NS_A).collect() +} + +/// A slide written with a default PresentationML namespace: its kept extension list stays in +/// that namespace under the writer's `p:extLst`. +#[test] +fn a_default_namespace_slide_keeps_its_extensions_in_the_presentationml_namespace() { + let xml = default_namespace_extensions("ppt/slides/slide1.xml", "p:sld"); + assert!(xml.contains("{11111111-2222-3333-4444-555555555555}"), "{xml}"); + assert_eq!(extension_namespaces(&xml), [NS_P], "{xml}"); + assert_eq!(namespaces_of(&xml, "data"), ["urn:test"], "{xml}"); +} + +/// The same for a layout and a master, whose kept extension list is written back through +/// `ext_children`. +#[test] +fn a_default_namespace_layout_and_master_keep_their_extensions_in_the_presentationml_namespace() { + for (name, root) in [("ppt/slideLayouts/slideLayout1.xml", "p:sldLayout"), ("ppt/slideMasters/slideMaster1.xml", "p:sldMaster")] { + let xml = default_namespace_extensions(name, root); + assert!(xml.contains("{11111111-2222-3333-4444-555555555555}"), "{name}: {xml}"); + assert_eq!(extension_namespaces(&xml), [NS_P], "{name}: {xml}"); + assert_eq!(namespaces_of(&xml, "data"), ["urn:test"], "{name}: {xml}"); + } +} + #[test] fn templates_and_shows_differ_in_the_main_content_type() { let p = deck(); diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index 76891a421..8383b30c0 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -769,8 +769,42 @@ pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> { if rb == 0 { return Ok(()); } + let mut scratch = if layout.depth == 32 && buf.len() >= rb { vec![0; rb] } else { Vec::new() }; + unpredict_rows(buf, layout, &mut scratch) +} + +/// Reverses prediction without allocating, using caller-accounted scratch memory. +/// +/// `buf` must contain exactly `planes * height` complete rows. For 32-bit samples, +/// `scratch` must hold at least one row (`width * 4` bytes); other depths need none. +/// Layout, input length and scratch capacity are checked before any bytes are changed. +/// Scratch contents are overwritten. Unlike [`unpredict`], partial or surplus rows +/// are rejected, making this suitable for callers with explicit decode budgets. +pub fn unpredict_with_scratch(buf: &mut [u8], layout: &PlaneLayout, scratch: &mut [u8]) -> Result<()> { + let rb = match layout.depth { + 1 => layout.width.div_ceil(8), + 8 => layout.width, + 16 => layout.width.checked_mul(2).ok_or(PsdError::LimitExceeded("row size overflow"))?, + 32 => layout.width.checked_mul(4).ok_or(PsdError::LimitExceeded("row size overflow"))?, + d => return Err(PsdError::Unsupported(format!("prediction for depth {d}"))), + }; + let expected = + rb.checked_mul(layout.height).and_then(|n| n.checked_mul(layout.planes)).ok_or(PsdError::LimitExceeded("decoded size overflow"))?; + if buf.len() != expected { + return Err(PsdError::Invalid("prediction buffer length does not match layout".into())); + } + if rb == 0 || buf.is_empty() { + return Ok(()); + } + if layout.depth == 32 && scratch.len() < rb { + return Err(PsdError::Invalid("prediction scratch is shorter than one row".into())); + } + unpredict_rows(buf, layout, scratch) +} + +fn unpredict_rows(buf: &mut [u8], layout: &PlaneLayout, scratch: &mut [u8]) -> Result<()> { + let rb = layout.row_bytes(); let w = layout.width; - let mut scratch = Vec::new(); for row in buf.chunks_exact_mut(rb) { match layout.depth { 1 | 8 => { @@ -787,8 +821,8 @@ pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> { } } 32 => { - scratch.clear(); - scratch.extend_from_slice(row); + scratch[..rb].copy_from_slice(row); + let scratch = &scratch[..rb]; // The byte-wise running sum runs across the four planes, so // plane k starts at the wrapping total of planes 0..k. let (p0, rest) = scratch.split_at(w); diff --git a/crates/psd/src/compression/tests.rs b/crates/psd/src/compression/tests.rs index 7cf876321..df4093aa3 100644 --- a/crates/psd/src/compression/tests.rs +++ b/crates/psd/src/compression/tests.rs @@ -793,3 +793,39 @@ fn padded_packbits_preserves_recovery_without_weakening_strict_decode() { super::packbits::decode_padded_into(&[0, 7, 255], 1, 1, &mut out).unwrap(); assert_eq!(out, [42, 7]); } + +#[test] +fn caller_scratch_prediction_matches_existing_decoder_across_planes() { + for depth in [1u16, 8, 16, 32] { + let layout = PlaneLayout { planes: 3, width: 13, height: 7, depth, version: Version::Psb }; + let mut actual: Vec = (0..layout.decoded_len().unwrap()).map(|i| (i.wrapping_mul(31) % 251) as u8).collect(); + let mut expected = actual.clone(); + unpredict(&mut expected, &layout).unwrap(); + let needed = if depth == 32 { layout.row_bytes() } else { 0 }; + let mut scratch = vec![0xa5; needed + 11]; + unpredict_with_scratch(&mut actual, &layout, &mut scratch).unwrap(); + assert_eq!(actual, expected, "depth {depth}"); + assert_eq!(&scratch[needed..], &[0xa5; 11]); + } +} + +#[test] +fn caller_scratch_prediction_rejects_invalid_inputs_before_mutation() { + let layout = PlaneLayout { planes: 1, width: 3, height: 2, depth: 32, version: Version::Psd }; + let original = vec![0x73; 24]; + for (len, scratch_len) in [(23, 12), (25, 12), (24, 11)] { + let mut bytes = vec![0x73; len]; + let mut scratch = vec![0xa5; scratch_len]; + assert!(unpredict_with_scratch(&mut bytes, &layout, &mut scratch).is_err()); + assert_eq!(bytes, vec![0x73; len]); + assert_eq!(scratch, vec![0xa5; scratch_len]); + } + for invalid in [PlaneLayout { width: usize::MAX, ..layout }, PlaneLayout { planes: usize::MAX, ..layout }, PlaneLayout { depth: 12, ..layout }] { + let mut bytes = original.clone(); + assert!(unpredict_with_scratch(&mut bytes, &invalid, &mut []).is_err()); + assert_eq!(bytes, original); + } + for empty in [PlaneLayout { width: 0, ..layout }, PlaneLayout { height: 0, ..layout }] { + unpredict_with_scratch(&mut [], &empty, &mut []).unwrap(); + } +} diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index f3afae64a..1a6f2000e 100644 --- a/crates/psd/src/descriptor.rs +++ b/crates/psd/src/descriptor.rs @@ -12,6 +12,26 @@ mod lookup; /// Maximum nesting depth accepted when parsing (fuzz safety). pub const MAX_DEPTH: usize = 64; +/// Per-container limits for parsing descriptor trees. +/// +/// Limits apply to every nested descriptor and `VlLs` list, before allocation. +/// They are not a total memory budget; byte strings and other value types retain +/// their existing input-length checks. Defaults preserve the unrestricted counts +/// accepted by the original API. Nesting remains bounded by [`MAX_DEPTH`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ParseLimits { + /// Maximum key/value pairs in each descriptor. + pub max_descriptor_items: u32, + /// Maximum values in each `VlLs` list. + pub max_list_items: u32, +} + +impl Default for ParseLimits { + fn default() -> Self { + Self { max_descriptor_items: u32::MAX, max_list_items: u32::MAX } + } +} + /// A Photoshop Unicode string: UTF-16 code units, preserved exactly /// (including any trailing NUL and unpaired surrogates). #[derive(Debug, Clone, PartialEq, Eq, Default, Hash)] @@ -300,6 +320,23 @@ impl Descriptor { Ok(d) } + /// Parses a descriptor at the start of `data`, returning it and the number of bytes consumed + /// (trailing data is allowed). Mid-stream reads of layer effects, fill and adjustment + /// descriptors use this; [`from_bytes`] still requires the slice to be fully consumed. + pub fn parse_prefix(data: &[u8]) -> Result<(Self, usize)> { + let mut r = Reader::new(data); + let d = Self::read(&mut r)?; + Ok((d, r.pos())) + } + + /// Parses a descriptor prefix with explicit per-container limits. + /// Returns the descriptor and bytes consumed, allowing trailing data. + pub fn parse_prefix_with_limits(data: &[u8], limits: ParseLimits) -> Result<(Self, usize)> { + let mut r = Reader::new(data); + let d = Self::read_with_limits(&mut r, limits)?; + Ok((d, r.pos())) + } + /// Serializes the descriptor. pub fn to_bytes(&self) -> Vec { let mut v = Vec::new(); @@ -308,7 +345,11 @@ impl Descriptor { } pub(crate) fn read(r: &mut Reader<'_>) -> Result { - read_descriptor(r, 0) + Self::read_with_limits(r, ParseLimits::default()) + } + + pub(crate) fn read_with_limits(r: &mut Reader<'_>, limits: ParseLimits) -> Result { + read_descriptor(r, 0, limits) } pub(crate) fn write(&self, out: &mut Vec) { @@ -382,33 +423,36 @@ pub(crate) fn vec_for_count(n: u32) -> Vec { Vec::with_capacity((n as usize).min(MAX_PREALLOC)) } -fn read_descriptor(r: &mut Reader<'_>, depth: usize) -> Result { +fn read_descriptor(r: &mut Reader<'_>, depth: usize, limits: ParseLimits) -> Result { if depth > MAX_DEPTH { return Err(PsdError::LimitExceeded("descriptor nesting too deep")); } let name = UnicodeString::read(r)?; let class_id = Id::read(r)?; let n = r.u32()?; + if n > limits.max_descriptor_items { + return Err(PsdError::LimitExceeded("too many descriptor items")); + } // Each item needs at least 5 (1-byte string key) + 4 (type) + 1 (bool). r.check_count(u64::from(n), 10)?; let mut items = vec_for_count(n); for _ in 0..n { let key = Id::read(r)?; - let v = read_value(r, depth + 1)?; + let v = read_value(r, depth + 1, limits)?; items.push((key, v)); } Ok(Descriptor { name, class_id, items }) } -fn read_value(r: &mut Reader<'_>, depth: usize) -> Result { +fn read_value(r: &mut Reader<'_>, depth: usize, limits: ParseLimits) -> Result { if depth > MAX_DEPTH { return Err(PsdError::LimitExceeded("descriptor nesting too deep")); } let ty = r.array::<4>()?; - read_typed_value(r, &ty, depth) + read_typed_value(r, &ty, depth, limits) } -fn read_typed_value(r: &mut Reader<'_>, ty: &[u8; 4], depth: usize) -> Result { +fn read_typed_value(r: &mut Reader<'_>, ty: &[u8; 4], depth: usize, limits: ParseLimits) -> Result { Ok(match ty { b"obj " => { let n = r.u32()?; @@ -419,14 +463,17 @@ fn read_typed_value(r: &mut Reader<'_>, ty: &[u8; 4], depth: usize) -> Result Value::Descriptor(read_descriptor(r, depth + 1)?), - b"GlbO" => Value::GlobalObject(read_descriptor(r, depth + 1)?), + b"Objc" => Value::Descriptor(read_descriptor(r, depth + 1, limits)?), + b"GlbO" => Value::GlobalObject(read_descriptor(r, depth + 1, limits)?), b"VlLs" => { let n = r.u32()?; + if n > limits.max_list_items { + return Err(PsdError::LimitExceeded("too many descriptor list items")); + } r.check_count(u64::from(n), 4)?; let mut items = vec_for_count(n); for _ in 0..n { - items.push(read_value(r, depth + 1)?); + items.push(read_value(r, depth + 1, limits)?); } Value::List(items) } @@ -463,7 +510,7 @@ fn read_typed_value(r: &mut Reader<'_>, ty: &[u8; 4], depth: usize) -> Result { let prefix = r.u32()?; - Value::ObjectArray(ObjectArray { prefix, body: read_descriptor(r, depth + 1)? }) + Value::ObjectArray(ObjectArray { prefix, body: read_descriptor(r, depth + 1, limits)? }) } other => { return Err(PsdError::Unsupported(format!("descriptor OSType {:?}", String::from_utf8_lossy(other)))); @@ -616,7 +663,7 @@ mod tests { data.extend_from_slice(b"bool\x01"); } let mut r = Reader::new(&data); - match read_typed_value(&mut r, b"VlLs", 0).unwrap() { + match read_typed_value(&mut r, b"VlLs", 0, ParseLimits::default()).unwrap() { Value::List(v) => assert_eq!(v.len(), n as usize), other => panic!("expected list, got {other:?}"), } @@ -705,6 +752,18 @@ mod tests { assert_eq!(VersionedDescriptor::from_bytes(&b).unwrap(), v); } + #[test] + fn parse_prefix() { + let d = sample(); + let mut b = d.to_bytes(); + let n = b.len(); + b.extend_from_slice(&[1, 2, 3]); + let (p, used) = Descriptor::parse_prefix(&b).unwrap(); + assert_eq!(p, d); + assert_eq!(used, n); + assert!(Descriptor::from_bytes(&b).is_err(), "from_bytes still refuses trailing bytes"); + } + #[test] fn versioned_parse_prefix() { let v = VersionedDescriptor::new(sample()); diff --git a/crates/psd/src/float.rs b/crates/psd/src/float.rs index 6e26cd75b..658538bc2 100644 --- a/crates/psd/src/float.rs +++ b/crates/psd/src/float.rs @@ -436,8 +436,22 @@ impl SmartObject { /// exceed [`MAX_BAKE_PIXELS`], or the mesh needs more rasterising work than eight times the /// output allows (a hostile mesh whose triangles each cover the whole output). pub fn render_placed(&self, content: &FloatImage, k: f64, size: Option<(u32, u32)>) -> Option<(FloatImage, [f64; 2])> { - let (cw, ch) = (f64::from(content.width), f64::from(content.height)); - if content.width == 0 || content.height == 0 { + self.render_placed_pixels(content.width, content.height, &content.data, k, size) + } + + /// Bakes borrowed straight RGBA pixels without copying the source image. + /// Uses the same placement, output and work limits as [`Self::render_placed`]. + /// Missing pixels in a short slice read as transparent; extra pixels are ignored. + pub fn render_placed_pixels( + &self, + width: u32, + height: u32, + data: &[[f32; 4]], + k: f64, + size: Option<(u32, u32)>, + ) -> Option<(FloatImage, [f64; 2])> { + let (cw, ch) = (f64::from(width), f64::from(height)); + if width == 0 || height == 0 { return None; } // The quad is solved once for the bounds, the size and the whole grid. @@ -464,7 +478,7 @@ impl SmartObject { let mut out: Vec<[f32; 4]> = Vec::new(); out.try_reserve_exact(count).ok()?; out.resize(count, [0.0; 4]); - let sampler = Sampler { content, cw, ch }; + let sampler = Sampler { width, height, data, cw, ch }; let idx = |i: usize, j: usize| j * (n + 1) + i; // A sane mesh's triangles each span about one grid cell (ow/n by oh/n), rounded out to // whole pixels. A thin output (16384×1) stacks every grid row onto the same pixel row, so @@ -498,7 +512,9 @@ impl SmartObject { /// Bilinear, premultiplied sampling of the content at content-pixel coordinates. struct Sampler<'a> { - content: &'a FloatImage, + width: u32, + height: u32, + data: &'a [[f32; 4]], cw: f64, ch: f64, } @@ -506,14 +522,14 @@ struct Sampler<'a> { impl Sampler<'_> { fn at(&self, x: usize, y: usize) -> [f32; 4] { // `data` is a public field: a short one reads as transparent. - let p = self.content.data.get(y * self.content.width as usize + x).copied().unwrap_or([0.0; 4]); + let p = y.checked_mul(self.width as usize).and_then(|row| row.checked_add(x)).and_then(|i| self.data.get(i)).copied().unwrap_or([0.0; 4]); [p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]] } fn sample(&self, x: f64, y: f64) -> [f32; 4] { let (fx, fy) = ((x - 0.5).clamp(0.0, self.cw - 1.0), (y - 0.5).clamp(0.0, self.ch - 1.0)); let (x0, y0) = (fx.floor() as usize, fy.floor() as usize); - let (x1, y1) = ((x0 + 1).min(self.content.width as usize - 1), (y0 + 1).min(self.content.height as usize - 1)); + let (x1, y1) = ((x0 + 1).min(self.width as usize - 1), (y0 + 1).min(self.height as usize - 1)); let (a, b) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32); let (p00, p10, p01, p11) = (self.at(x0, y0), self.at(x1, y0), self.at(x0, y1), self.at(x1, y1)); std::array::from_fn(|c| (p00[c] * (1.0 - a) + p10[c] * a) * (1.0 - b) + (p01[c] * (1.0 - a) + p11[c] * a) * b) diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index a2195bf5d..d4d98c695 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -259,11 +259,16 @@ pub struct SmartObject { impl SmartObject { /// Reads the data of a `SoLd` / `SoLE` block. pub fn from_placed_layer_data(data: &[u8]) -> Result { + Self::from_placed_layer_data_with_limits(data, crate::descriptor::ParseLimits::default()) + } + + /// Reads a `SoLd` / `SoLE` block with explicit descriptor container limits. + pub fn from_placed_layer_data_with_limits(data: &[u8], limits: crate::descriptor::ParseLimits) -> Result { let mut r = Reader::new(data); let _kind = r.array::<4>()?; let _version = r.u32()?; let _descriptor_version = r.u32()?; - let d = Descriptor::read(&mut r)?; + let d = Descriptor::read_with_limits(&mut r, limits)?; let uuid = d.get_text("Idnt").unwrap_or_default(); let t = eight(&d, "Trnf").unwrap_or([0.0; 8]); // The non-affine transform when present (perspective), else the transform. diff --git a/crates/psd/src/text/envelope.rs b/crates/psd/src/text/envelope.rs index 73345fa83..16fac8737 100644 --- a/crates/psd/src/text/envelope.rs +++ b/crates/psd/src/text/envelope.rs @@ -29,6 +29,33 @@ pub fn transform_is_safe(t: &[f64; 6]) -> bool { t.iter().all(|v| v.is_finite() && v.abs() <= f64::from(i32::MAX)) } +/// Recovers the text and raw transform of a `TySh` prefix, even if its descriptor is damaged. +/// +/// This is PhotoCraft's preservation fallback, not a rendering-ready type layer. It keeps +/// line endings, the trailing paragraph terminator and non-finite transform values verbatim. +/// Callers must validate geometry before rendering. A complete 52-byte prefix is required; +/// a missing, unsupported or malformed text descriptor produces empty text. Warp and bounds +/// are not interpreted. Above [`MAX_BYTES`], the descriptor is not parsed and text is empty, +/// retaining the fixed transform so consumers can preserve the original block without decoding +/// an oversized descriptor. Inputs within that cap retain the shared parser's allocation limits. +pub fn parse_tysh_text_prefix(data: &[u8]) -> Option<(String, [f64; 6])> { + let f = |at: usize| data.get(at..at + 8).map(|b| f64::from_be_bytes(b.try_into().unwrap_or([0; 8]))); + let mut m = [0.0; 6]; + for (i, v) in m.iter_mut().enumerate() { + *v = f(2 + i * 8)?; + } + // text version (2) at 50, descriptor version (4) at 52, descriptor at 56. + let rest = data.get(52..)?; + if data.len() > MAX_BYTES { + return Some((String::new(), m)); + } + let text = VersionedDescriptor::parse_prefix(rest).ok().and_then(|(d, _)| match d.descriptor.get("Txt ") { + Some(D::Text(t)) => Some(t.to_string_lossy()), + _ => None, + }); + Some((text.unwrap_or_default(), m)) +} + /// Parses a `TySh` block. pub fn parse_tysh(data: &[u8]) -> Option { if data.len() > MAX_BYTES { @@ -246,6 +273,54 @@ mod tests { bounds: [-1.0, 2.0, 30.0, 40.0], } } + #[test] + fn recovery_prefix_preserves_text_and_ignores_damaged_tail() { + let mut t = sample(); + t.text = t.text.with("Txt ", D::Text(UnicodeString::new_nul("Hello\r\nWorld\r"))); + let mut bytes = write_tysh(&t).unwrap(); + let (_, n) = VersionedDescriptor::parse_prefix(&bytes[52..]).unwrap(); + bytes.truncate(52 + n); + bytes.extend_from_slice(b"broken warp"); + assert_eq!(parse_tysh_text_prefix(&bytes), Some(("Hello\r\nWorld\r".into(), t.transform))); + } + + #[test] + fn recovery_prefix_needs_only_complete_fixed_header() { + let bytes = write_tysh(&sample()).unwrap(); + for cut in 0..52 { + assert!(parse_tysh_text_prefix(&bytes[..cut]).is_none(), "{cut}"); + } + for cut in 52..56 { + assert_eq!(parse_tysh_text_prefix(&bytes[..cut]), Some((String::new(), sample().transform))); + } + let mut unsupported = bytes.clone(); + unsupported[52..56].copy_from_slice(&99u32.to_be_bytes()); + assert_eq!(parse_tysh_text_prefix(&unsupported), Some((String::new(), sample().transform))); + assert_eq!(parse_tysh_text_prefix(&bytes), Some((String::new(), sample().transform))); + } + + #[test] + fn recovery_prefix_bounds_descriptor_work_without_losing_preservation_geometry() { + let mut t = sample(); + t.text = t.text.with("Txt ", D::Text(UnicodeString::new_nul("kept"))); + let mut bytes = write_tysh(&t).unwrap(); + bytes.resize(MAX_BYTES, 0); + assert_eq!(parse_tysh_text_prefix(&bytes), Some(("kept".into(), t.transform))); + bytes.push(0); + assert_eq!(parse_tysh_text_prefix(&bytes), Some((String::new(), t.transform))); + assert!(parse_tysh(&bytes).is_none()); + } + + #[test] + fn recovery_prefix_retains_geometry_but_is_not_render_validation() { + let mut bytes = write_tysh(&sample()).unwrap(); + bytes[2..10].copy_from_slice(&f64::NAN.to_be_bytes()); + let (_, transform) = parse_tysh_text_prefix(&bytes).unwrap(); + assert!(transform[0].is_nan()); + assert!(!transform_is_safe(&transform)); + assert!(parse_tysh(&bytes).is_none()); + } + #[test] fn roundtrip_preserves_descriptors_transform_and_bounds() { let t = sample(); diff --git a/crates/psd/tests/resource_limits.rs b/crates/psd/tests/resource_limits.rs new file mode 100644 index 000000000..624aaf287 --- /dev/null +++ b/crates/psd/tests/resource_limits.rs @@ -0,0 +1,76 @@ +use craft_psd::descriptor::{Descriptor, ObjectArray, ParseLimits, Value}; +use craft_psd::float::FloatImage; +use craft_psd::smart::SmartObject; + +#[test] +fn descriptor_limits_apply_at_boundary_and_through_every_nested_container() { + let limits = ParseLimits { max_descriptor_items: 1, max_list_items: 1 }; + let one = Descriptor::new("test").with("one", Value::Boolean(true)); + let two = one.clone().with("two", Value::Boolean(false)); + assert!(Descriptor::parse_prefix_with_limits(&one.to_bytes(), limits).is_ok()); + assert!(Descriptor::parse_prefix_with_limits(&two.to_bytes(), limits).is_err()); + assert!(Descriptor::parse_prefix(&two.to_bytes()).is_ok()); + for nested in [ + Value::Descriptor(two.clone()), + Value::GlobalObject(two.clone()), + Value::ObjectArray(ObjectArray { prefix: 0, body: two.clone() }), + Value::List(vec![Value::Descriptor(two.clone())]), + ] { + let bytes = Descriptor::new("test").with("nest", nested).to_bytes(); + assert!(Descriptor::parse_prefix_with_limits(&bytes, limits).is_err()); + assert!(Descriptor::parse_prefix(&bytes).is_ok()); + } + for n in [0, 1, 2] { + let d = Descriptor::new("test").with("list", Value::List(vec![Value::Boolean(true); n])); + assert_eq!(Descriptor::parse_prefix_with_limits(&d.to_bytes(), limits).is_ok(), n <= 1); + } + let nested_list = Descriptor::new("test").with("list", Value::List(vec![Value::List(vec![Value::Boolean(true); 2])])); + assert!(Descriptor::parse_prefix_with_limits(&nested_list.to_bytes(), limits).is_err()); + let mut bytes = one.to_bytes(); + let used = bytes.len(); + bytes.extend_from_slice(b"tail"); + assert_eq!(Descriptor::parse_prefix_with_limits(&bytes, limits).unwrap().1, used); + let zero = ParseLimits { max_descriptor_items: 0, max_list_items: 0 }; + assert!(Descriptor::parse_prefix_with_limits(&Descriptor::new("test").to_bytes(), zero).is_ok()); + assert!(Descriptor::parse_prefix_with_limits(&one.to_bytes(), zero).is_err()); +} + +#[test] +fn count_limits_reject_before_reading_declared_elements() { + let limits = ParseLimits { max_descriptor_items: 1, max_list_items: 1 }; + let mut bytes = Descriptor::new("test").to_bytes(); + let end = bytes.len(); + bytes[end - 4..].copy_from_slice(&2u32.to_be_bytes()); + assert!(matches!(Descriptor::parse_prefix_with_limits(&bytes, limits), Err(craft_psd::PsdError::LimitExceeded(_)))); + let mut bytes = Descriptor::new("test").with("list", Value::List(vec![])).to_bytes(); + let end = bytes.len(); + bytes[end - 4..].copy_from_slice(&2u32.to_be_bytes()); + assert!(matches!(Descriptor::parse_prefix_with_limits(&bytes, limits), Err(craft_psd::PsdError::LimitExceeded(_)))); +} + +#[test] +fn placed_layer_data_honors_descriptor_limits() { + let d = Descriptor::new("test").with("one", Value::Boolean(true)).with("two", Value::Boolean(false)); + let mut bytes = b"soLD".to_vec(); + bytes.extend_from_slice(&4u32.to_be_bytes()); + bytes.extend_from_slice(&16u32.to_be_bytes()); + bytes.extend_from_slice(&d.to_bytes()); + assert!(SmartObject::from_placed_layer_data(&bytes).is_ok()); + assert!(SmartObject::from_placed_layer_data_with_limits(&bytes, ParseLimits { max_descriptor_items: 1, max_list_items: 1 }).is_err()); +} + +#[test] +fn borrowed_pixels_match_owned_render_and_preserve_short_slice_behavior() { + let smart = SmartObject { uuid: String::new(), quad: [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]], size: None, warp: None }; + for data in [vec![], vec![[1.0, 0.5, 0.25, 0.5]], vec![[1.0, 0.5, 0.25, 0.5]; 4]] { + let image = FloatImage { width: 2, height: 2, data }; + let owned = smart.render_placed(&image, 1.0, Some((2, 2))); + let borrowed = smart.render_placed_pixels(2, 2, &image.data, 1.0, Some((2, 2))); + assert!(owned.is_some()); + assert_eq!(owned, borrowed); + } + assert!(smart.render_placed_pixels(0, 2, &[], 1.0, None).is_none()); + assert!(smart.render_placed_pixels(u32::MAX, u32::MAX, &[], 1.0, Some((u32::MAX, u32::MAX))).is_none()); + // A short source remains safely transparent even with enormous declared dimensions. + assert!(smart.render_placed_pixels(u32::MAX, u32::MAX, &[], 1.0, Some((1, 1))).is_some()); +} diff --git a/crates/raster-codecs/README.md b/crates/raster-codecs/README.md index 907e73763..eec7ac0d5 100644 --- a/crates/raster-codecs/README.md +++ b/crates/raster-codecs/README.md @@ -11,7 +11,7 @@ craft-raster-codecs = { git = "https://github.com/storytold/craft-libs", rev = " | Module | Format | Read | Write | |---|---|---|---| -| `dds` | DirectDraw Surface: uncompressed masks, luminance, BC1/BC2/BC3 (DXT1/3/5), legacy and DX10 headers; top mip level | yes | uncompressed and BC1-BC3, optional mip chain | +| `dds` | DirectDraw Surface: uncompressed masks, luminance, BC1/BC2/BC3 (DXT1/3/5), unsigned BC4/BC5 (ATI1/2, as gray and as RGB with blue 0), legacy and DX10 headers; top mip level | yes | uncompressed and BC1-BC3, optional mip chain | | `dicom` | DICOM Part 10, uncompressed transfer syntaxes: MONOCHROME1/2, RGB, YBR_FULL, 8 and 16 bits | yes | no | | `fits` | FITS primary HDU or first `IMAGE` extension, every `BITPIX`, `BSCALE`/`BZERO`, header cards as text | yes | gray or RGB; 8-bit, 16-bit, float | | `iff` | IFF ILBM (1 to 8 planes with a palette, 24 planes, mask plane or transparent colour) and PBM, stored or ByteRun1; HAM and EHB are refused | yes | 24-plane ILBM with an optional mask plane | diff --git a/crates/raster-codecs/src/lib.rs b/crates/raster-codecs/src/lib.rs index 7e705da99..a9aa7c4c6 100644 --- a/crates/raster-codecs/src/lib.rs +++ b/crates/raster-codecs/src/lib.rs @@ -3,7 +3,7 @@ //! //! | Module | Format | Read | Write | //! |---|---|---|---| -//! | [`dds`] | DirectDraw Surface: uncompressed masks, BC1-BC3 (DXT1/3/5), the DX10 header | yes | yes | +//! | [`dds`] | DirectDraw Surface: uncompressed masks, BC1-BC5 (DXT1/3/5, ATI1/2), the DX10 header | yes | yes (uncompressed, BC1-BC3) | //! | [`dicom`] | DICOM Part 10, uncompressed native pixel data | yes | no | //! | [`fits`] | FITS primary and image-extension HDUs | yes | yes | //! | [`iff`] | IFF ILBM (palette or 24-bit planes, masks) and PBM | yes | yes (24-plane ILBM) | diff --git a/crates/raster-codecs/tests/dds.rs b/crates/raster-codecs/tests/dds.rs index afb9066aa..d5c482aa7 100644 --- a/crates/raster-codecs/tests/dds.rs +++ b/crates/raster-codecs/tests/dds.rs @@ -320,7 +320,8 @@ fn refuses_cubemaps_arrays_and_volumes() { unsupported(&dx10(4, 4, 71, 3, 0, 6), "array"); unsupported(&dx10(4, 4, 71, 4, 0, 1), "2D"); unsupported(&dx10(4, 4, 98, 3, 0, 1), "98"); // BC7_UNORM - unsupported(&compressed(4, 4, b"ATI2"), "ATI2"); + unsupported(&compressed(4, 4, b"ATI3"), "ATI3"); + unsupported(&compressed(4, 4, b"BC5S"), "SNORM"); unsupported(&compressed(4, 4, b"DXT2"), "premultiplied"); } diff --git a/crates/rtf/src/doc/parse.rs b/crates/rtf/src/doc/parse.rs index 60a65740a..01978da1e 100644 --- a/crates/rtf/src/doc/parse.rs +++ b/crates/rtf/src/doc/parse.rs @@ -1,3 +1,6 @@ +use std::cmp::Reverse; +use std::collections::BinaryHeap; + use super::reader::Reader; use super::state::{CommentData, Dest, HeaderFooter, HfPages, MARK_CLOSE, MARK_OPEN, MAX_PICT, NoteData, PageGeom}; use super::{Arc, Block, Blocks, Cell, Document, FBlock, Flow, HashMap, InlineObject, Para, Paragraph, model}; @@ -262,43 +265,137 @@ fn finalize(mut r: Reader) -> Parsed { Parsed { flow: Flow { blocks, meta: r.meta }, page: r.page, last_section, default_font, headers_footers, notes: r.notes, comments: r.comments } } +/// Most grid columns a table gets (the document model's own cap). +const MAX_GRID_COLS: usize = 63; +/// Grid columns of this width or less, in twips (1 pt), always merge: the document model refuses +/// them, and would then give the table equal columns. +const NO_GRID_GAP: i64 = 20; + /// The column grid of a table from its rows' cell right edges: every distinct edge starts a grid /// column, and each cell spans the grid columns between its left and right edges, as Word lays /// out RTF rows whose cells don't line up. Returns the widths in points, or none (equal columns) -/// when the edges don't make a grid. +/// when no grid fits, which only a row of more cells than grid columns can cause. +/// +/// One odd row never costs the whole table its grid (a form exported from a spreadsheet, with +/// many narrow columns, otherwise had its wide title squeezed into one of four equal columns): +/// - Over [`MAX_GRID_COLS`] edges, or edges [`NO_GRID_GAP`] or less apart, merge +/// ([`coarse_edges`]); each cell edge moves to the nearest grid edge. Narrow columns over a +/// point stay: import keeps them as narrow as the file gives them. +/// - A cell that ends at or before the previous one (a zero-width cell, or a cell with no +/// `\cellx` of its own) still gets a grid column of its own; cells pushed past the table's +/// right edge move back. pub(super) fn column_grid(rows: &mut [Vec], rights: &[Vec]) -> Vec { + if rights.len() != rows.len() { + return Vec::new(); + } let mut edges: Vec = rights.iter().flatten().copied().filter(|&x| x > 0).collect(); edges.sort_unstable(); edges.dedup(); - let ok = rights.len() == rows.len() - && rows - .iter() - .zip(rights) - .all(|(r, x)| r.len() == x.len() && x.windows(2).all(|w| w.first() < w.get(1)) && x.first().is_some_and(|&v| v > 0)) - && !edges.is_empty() - && edges.len() <= 63; - if !ok { + if edges.is_empty() { return Vec::new(); } - for (row, x) in rows.iter_mut().zip(rights) { + let grid = coarse_edges(&edges); + // Each cell's right edge as a grid edge number (1 = the first grid column's right edge). + let mut ends: Vec> = Vec::with_capacity(rows.len()); + for (row, x) in rows.iter().zip(rights) { + if row.len() > grid.len() { + return Vec::new(); + } + let mut at: Vec = Vec::with_capacity(row.len()); + let mut prev = 0; + for i in 0..row.len() { + let end = x.get(i).map_or(0, |&r| nearest_edge(&grid, r)).max(prev + 1); + at.push(end); + prev = end; + } + // Cells pushed past the right edge move back, each keeping a column of its own. + let mut limit = grid.len(); + for end in at.iter_mut().rev() { + *end = (*end).min(limit); + limit = end.saturating_sub(1); + } + ends.push(at); + } + for (row, at) in rows.iter_mut().zip(&ends) { let mut left = 0; - for (c, &right) in row.iter_mut().zip(x) { - let span = edges.iter().filter(|&&e| e > left && e <= right).count().max(1); - c.colspan = span as u32; - left = right; + for (c, &end) in row.iter_mut().zip(at) { + c.colspan = u32::try_from(end.saturating_sub(left)).unwrap_or(1).max(1); + left = end; } } - let mut prev = 0; - edges - .iter() + let mut prev = 0i64; + grid.iter() .map(|&e| { - let w = (e - prev) as f32 / 20.0; - prev = e; + let w = (i64::from(e) - prev) as f32 / 20.0; + prev = i64::from(e); w }) .collect() } +/// The grid edges kept from the sorted, distinct, positive `edges`. The narrowest column merges +/// into the next, one at a time, so an edge moves only when it has to: while there are over +/// [`MAX_GRID_COLS`] columns, or columns of [`NO_GRID_GAP`] or less. The table's right edge is +/// always kept. +fn coarse_edges(edges: &[i32]) -> Vec { + let n = edges.len(); + // Each edge's neighbours among the edges still kept. + let mut left: Vec> = (0..n).map(|i| i.checked_sub(1)).collect(); + let mut right: Vec> = (1..=n).map(|i| (i < n).then_some(i)).collect(); + let mut kept = vec![true; n]; + let at = |i: Option| i.and_then(|i| edges.get(i)).map_or(0, |&e| i64::from(e)); + let width = |i: usize, left: &[Option]| at(Some(i)) - at(left.get(i).copied().flatten()); + let mut narrowest: BinaryHeap> = (0..n).map(|i| Reverse((width(i, &left), i))).collect(); + let mut count = n; + while count > 1 { + let Some(Reverse((w, i))) = narrowest.pop() else { + break; + }; + // A column that has since grown, or gone, has a fresher entry or none. + if !kept.get(i).copied().unwrap_or(false) || w != width(i, &left) { + continue; + } + if count <= MAX_GRID_COLS && w > NO_GRID_GAP { + break; + } + // The column's right edge goes, unless it is the table's: then its left edge does. + let last = right.get(i).copied().flatten().is_none(); + let Some(gone) = (if last { left.get(i).copied().flatten() } else { Some(i) }) else { + break; + }; + let before = left.get(gone).copied().flatten(); + let after = right.get(gone).copied().flatten(); + if let Some(slot) = before.and_then(|b| right.get_mut(b)) { + *slot = after; + } + if let Some(a) = after { + if let Some(slot) = left.get_mut(a) { + *slot = before; + } + narrowest.push(Reverse((width(a, &left), a))); + } + if let Some(slot) = kept.get_mut(gone) { + *slot = false; + } + count -= 1; + } + edges.iter().zip(&kept).filter(|&(_, &k)| k).map(|(&e, _)| e).collect() +} + +/// The number of the grid edge nearest `x` (1-based; 0 is the table's left edge). +fn nearest_edge(grid: &[i32], x: i32) -> usize { + if x <= 0 { + return 0; + } + let p = grid.partition_point(|&e| e < x); + let below = if p == 0 { 0 } else { grid.get(p - 1).copied().unwrap_or(0) }; + match grid.get(p) { + Some(&above) if i64::from(above) - i64::from(x) <= i64::from(x) - i64::from(below) => p + 1, + Some(_) => p, + None => grid.len(), + } +} + /// Parse RTF bytes into a document. pub fn import(bytes: &[u8]) -> Result { model::begin_import(); diff --git a/crates/rtf/src/doc/tests.rs b/crates/rtf/src/doc/tests.rs index 2a4103eb1..fddd198da 100644 --- a/crates/rtf/src/doc/tests.rs +++ b/crates/rtf/src/doc/tests.rs @@ -389,6 +389,26 @@ fn page_size_and_margins() { assert_eq!(d.last_section, craft_wordmodel::SectionProps::default()); } +#[test] +fn narrow_grid_columns_keep_their_width() { + // Rows' edges a few points apart, as in a form exported from a spreadsheet. The table stays as + // wide as its source, through an export and back too. + let rtf = br"{\rtf1\ansi +\trowd\cellx400\cellx800 \pard\intbl a\cell b\cell\row +\trowd\cellx80\cellx480\cellx800 \pard\intbl c\cell d\cell e\cell\row +\pard after\par}"; + let table = |doc: &Document| match doc.body.iter().find_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t.clone()) } else { None }) + { + Some(t) => t, + None => panic!("no table"), + }; + let doc = import(rtf).unwrap(); + let t = table(&doc); + assert_eq!(t.grid, [4.0, 16.0, 4.0, 16.0]); + assert_eq!(t.rows[0].cells.iter().map(|c| c.props.width).collect::>(), [Some(20.0), Some(20.0)]); + assert_eq!(table(&import(export(&doc).as_bytes()).unwrap()).grid, t.grid); +} + #[test] fn table_grid_from_cell_edges_and_borders() { // Rows whose cells don't line up share one grid: edges 2000, 3000, 9000. @@ -460,6 +480,141 @@ fn table_grid_from_cell_edges_and_borders() { assert_eq!(t.grid, [240.9, 241.0]); } +/// The table of `rtf`'s flow and every row's column spans; checks the spans fit the grid. +fn grid_of(rtf: &[u8]) -> (Vec, Vec>) { + let f = parse(rtf).unwrap(); + let FBlock::Table(t) = &f.blocks[0] else { panic!("no table") }; + let spans: Vec> = t.rows.iter().map(|r| r.iter().map(|c| c.colspan).collect()).collect(); + assert!(!t.widths.is_empty(), "the table kept no grid"); + assert_eq!(t.cols(), t.widths.len(), "spans {spans:?} don't fit {} grid columns", t.widths.len()); + assert!(t.widths.iter().all(|&w| w > 1.0), "a grid column under a point: {:?}", t.widths); + (t.widths.clone(), spans) +} + +/// Width in points of the first `n` grid columns. +fn first_cols(widths: &[f32], n: u32) -> f32 { + widths.iter().take(n as usize).sum() +} + +#[test] +fn table_grid_survives_more_than_63_edges() { + // A form exported from a spreadsheet: a wide title over rows whose middle edge moves by + // 100 twips, 80 distinct edges in all. The grid used to be dropped, giving equal columns. + let mut rtf = String::from(r"{\rtf1\ansi\trowd\cellx6000\cellx8000\pard\intbl Title\cell Codes\cell\row"); + for k in 1..80 { + rtf.push_str(&format!(r"\trowd\cellx{}\cellx8000\pard\intbl a\cell b\cell\row", k * 100)); + } + rtf.push_str(r"\pard\par}"); + let (widths, spans) = grid_of(rtf.as_bytes()); + assert!(widths.len() <= 63, "{} grid columns", widths.len()); + assert!((widths.iter().sum::() - 400.0).abs() < 0.01, "the table keeps its 400 pt"); + // The title keeps its 300 pt, within a grid column's merge. + let title = first_cols(&widths, spans[0][0]); + assert!((title - 300.0).abs() <= 5.0, "title {title} pt"); + // The staircase still climbs: the 60th row's first cell is about 300 pt wide too. + assert!((first_cols(&widths, spans[60][0]) - 300.0).abs() <= 5.0); + + // The same through import: the document table has the grid, not equal columns. + let d = import(rtf.as_bytes()).unwrap(); + let t = d.body.iter().find_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t) } else { None }).unwrap(); + assert_eq!(t.grid.len(), widths.len()); + let w = t.rows[0].cells[0].props.width.unwrap(); + assert!((w - 300.0).abs() <= 5.0, "title cell {w} pt"); +} + +#[test] +fn table_grid_survives_a_zero_width_cell_and_a_missing_cellx() { + // A zero-width cell (two edges at 3000) in one row: the other rows keep their grid. + let (widths, spans) = grid_of( + br"{\rtf1\ansi +\trowd\cellx6000\cellx9000 \pard\intbl Title\cell b\cell\row +\trowd\cellx2000\cellx2000\cellx9000 \pard\intbl a\cell\cell c\cell\row +\pard\par}", + ); + assert_eq!(first_cols(&widths, spans[0][0]), 300.0); + assert_eq!(spans[1].len(), 3, "the zero-width cell is kept: {spans:?}"); + assert_eq!(first_cols(&widths, spans[1][0]), 100.0, "the cell before it keeps its width"); + + // A row with a third cell but only two `\cellx`. + let (widths, spans) = grid_of( + br"{\rtf1\ansi +\trowd\cellx6000\cellx9000 \pard\intbl Title\cell b\cell\row +\trowd\cellx2000\cellx6000 \pard\intbl a\cell b\cell extra\cell\row +\pard\par}", + ); + assert_eq!(first_cols(&widths, spans[0][0]), 300.0); + assert_eq!(spans[1].len(), 3); + assert_eq!(first_cols(&widths, spans[1][0]), 100.0); +} + +#[test] +fn table_grid_merges_edges_a_few_twips_apart() { + // Two rows that mean the same 3000-twip edge, 5 twips apart: one grid column, not one of + // a quarter point (which the document model refuses, so the table got equal columns). + let (widths, spans) = grid_of( + br"{\rtf1\ansi +\trowd\cellx3000\cellx9000 \pard\intbl a\cell b\cell\row +\trowd\cellx3005\cellx9000 \pard\intbl c\cell d\cell\row +\pard\par}", + ); + assert_eq!(widths.len(), 2, "{widths:?}"); + assert_eq!(spans, [[1, 1], [1, 1]]); + assert_eq!(widths.iter().sum::(), 450.0); +} + +/// `edges` as one table row, a cell for each. +fn rtf_row(edges: &[usize]) -> String { + let cells: String = edges.iter().map(|e| format!(r"\cellx{e}")).collect(); + format!(r"\trowd{cells}\pard\intbl {}\row", r"x\cell ".repeat(edges.len())) +} + +#[test] +fn table_grid_keeps_a_column_for_each_cell_of_the_widest_row() { + // 64 evenly spaced edges: merging by a common gap halves them to 32 columns, too few for a + // row of 33 or more cells, and the table lost its grid. + let edges: Vec = (1..=64).map(|k| k * 100).collect(); + for cells in [33, 40, 50, 62] { + let wide: Vec = edges.iter().copied().take(cells).chain([6400]).collect(); + let rest: Vec = edges.iter().copied().skip(cells - 1).collect(); + let rtf = format!(r"{{\rtf1\ansi {}{}\pard\par}}", rtf_row(&wide), rtf_row(&rest)); + let (widths, spans) = grid_of(rtf.as_bytes()); + assert!((cells + 1..=63).contains(&widths.len()), "{cells} cells, {} grid columns", widths.len()); + assert_eq!(spans[0].len(), cells + 1, "every cell is kept"); + assert_eq!(widths.iter().sum::(), 320.0, "the table keeps its 320 pt"); + } +} + +#[test] +fn table_grid_keeps_narrow_columns_at_their_width() { + // Columns under 6 pt that no row needs keep their 3 pt: import no longer widens them, so the + // table keeps its 60 pt. + let mut rtf = String::from(r"{\rtf1\ansi "); + for k in 1..=20 { + rtf.push_str(&rtf_row(&[k * 60, 1200])); + } + rtf.push_str(r"\pard\par}"); + let (widths, _) = grid_of(rtf.as_bytes()); + assert_eq!(widths, [3.0; 20], "{widths:?}"); + let d = import(rtf.as_bytes()).unwrap(); + let t = d.body.iter().find_map(|b| if let craft_wordmodel::Block::Table(t) = &**b { Some(t) } else { None }).unwrap(); + assert_eq!(t.grid.iter().sum::(), 60.0, "{:?}", t.grid); + + // A row that needs them keeps them, narrow as they are. + let (widths, spans) = grid_of(format!(r"{{\rtf1\ansi {}\pard\par}}", rtf_row(&[60, 120, 180])).as_bytes()); + assert_eq!(widths, [3.0, 3.0, 3.0]); + assert_eq!(spans, [[1, 1, 1]]); +} + +#[test] +fn table_grid_never_keeps_a_column_the_document_model_refuses() { + // Three cells within a point of each other: too narrow to keep even for a row that needs + // them. The row can't fit, so the table has no grid, and nothing panics. + let f = parse(format!(r"{{\rtf1\ansi {}\pard\par}}", rtf_row(&[5, 10, 15])).as_bytes()).unwrap(); + let FBlock::Table(t) = &f.blocks[0] else { panic!("no table") }; + assert!(t.widths.is_empty(), "{:?}", t.widths); + assert_eq!(t.rows[0].len(), 3); +} + #[test] fn code_pages_from_ansicpg_and_font_charsets() { // The document's code page: Russian RTF as accounting systems write it. diff --git a/crates/stream-codecs/src/runlength.rs b/crates/stream-codecs/src/runlength.rs index a6df9e19d..a13a1d4fb 100644 --- a/crates/stream-codecs/src/runlength.rs +++ b/crates/stream-codecs/src/runlength.rs @@ -43,6 +43,21 @@ pub fn decode(data: &[u8], max: usize) -> Step { pub fn encode(data: &[u8]) -> Vec { let mut out = Vec::with_capacity(data.len() + data.len() / 128 + 2); + encode_packets(data, &mut out, 2); + out.push(128); + out +} + +/// Append a TIFF PackBits row without an end-of-data marker. +/// +/// Runs of three or more bytes use repeat packets; pairs remain in literal packets. +/// Existing output is retained, permitting rows to be appended directly to a strip. +/// PostScript callers can append their own EOD byte after the final row. +pub fn encode_packbits_into(data: &[u8], out: &mut Vec) { + encode_packets(data, out, 3); +} + +fn encode_packets(data: &[u8], out: &mut Vec, repeat_min: usize) { let n = data.len(); let mut i = 0; while i < n { @@ -50,7 +65,7 @@ pub fn encode(data: &[u8]) -> Vec { while i + run < n && run < 128 && data[i + run] == data[i] { run += 1; } - if run >= 2 { + if run >= repeat_min { out.push((257 - run) as u8); out.push(data[i]); i += run; @@ -59,15 +74,14 @@ pub fn encode(data: &[u8]) -> Vec { // Literal: extend until a repeat begins or 128 bytes. let start = i; let mut j = i + 1; - while j < n && j - start < 128 && !(j + 1 < n && data[j] == data[j + 1]) { + while j < n && j - start < 128 && !data.get(j..).and_then(|rest| rest.get(..repeat_min)).is_some_and(|run| run.iter().all(|b| *b == data[j])) + { j += 1; } out.push((j - start - 1) as u8); out.extend_from_slice(&data[start..j]); i = j; } - out.push(128); - out } #[cfg(test)] @@ -114,4 +128,21 @@ mod tests { assert_eq!((e[0], e[129]), (127, 71)); assert_eq!(dec(&e).unwrap(), lit); } + #[test] + fn packbits_appends_rows_without_eod_and_keeps_pairs_literal() { + let mut out = vec![42]; + encode_packbits_into(b"aabbccc", &mut out); + assert_eq!(out, [42, 3, b'a', b'a', b'b', b'b', 254, b'c']); + let before = out.clone(); + encode_packbits_into(b"", &mut out); + assert_eq!(out, before); + assert_eq!(encode(b"aa"), [255, b'a', 128]); + for n in [1, 2, 3, 127, 128, 129, 255, 256, 300] { + for row in [vec![7; n], (0..n).map(|i| (i % 251) as u8).collect()] { + let mut encoded = Vec::new(); + encode_packbits_into(&row, &mut encoded); + assert_eq!(decode(&encoded, n).map_err(|failure| failure.error).unwrap(), row); + } + } + } } diff --git a/crates/svg/src/guard.rs b/crates/svg/src/guard.rs index 9601b2a13..0be356820 100644 --- a/crates/svg/src/guard.rs +++ b/crates/svg/src/guard.rs @@ -20,6 +20,30 @@ const MAX_NESTING: u32 = 16; /// The longest entity name a reference is looked for with ([`references`]). const MAX_NAME: usize = 256; +/// The longest prefix of `s` of at most `max` bytes that ends on a character boundary. +/// Unlike `s.get(..s.len().min(max)).unwrap_or(s)`, a mid-character cut does not +/// fall back to the rest of the string. +fn bounded_prefix(s: &str, max: usize) -> &str { + let mut end = s.len().min(max); + while end > 0 && !s.is_char_boundary(end) { + end -= 1; + } + &s[..end] +} + +/// A char-bounded prefix of `rest` longer than [`MAX_NAME`], used when the bounded +/// window found no whitespace and `rest` itself is overlong. +fn overlong_name_key<'a>(rest: &'a str, window: &'a str) -> &'a str { + if window.len() > MAX_NAME { + return window; + } + let mut end = (MAX_NAME + 1).min(rest.len()); + while end < rest.len() && !rest.is_char_boundary(end) { + end += 1; + } + rest.get(..end).filter(|key| key.len() > MAX_NAME).unwrap_or(window) +} + /// The internal general entities declared in `svg`: name → every value declared for it. Text that /// only looks like a declaration in another entity's value is kept too: the largest value counts, /// so it can only make the estimate larger. Comments and CDATA are skipped, so markers there are @@ -52,8 +76,9 @@ fn declared(svg: &str) -> HashMap<&str, Vec<&str>> { continue; } // Bound the name scan: a comment full of ` HashMap<&str, Vec<&str>> { } } else if rest.len() > MAX_NAME { // A name longer than MAX_NAME cannot be referenced, but it must still be - // recorded so `entities_expand_past` can refuse the document. - map.entry(window).or_default().push(""); + // recorded so `entities_expand_past` can refuse the document. If the + // MAX_NAME+1 cut split a character, extend to the next boundary so the + // recorded key is still longer than MAX_NAME. + map.entry(overlong_name_key(rest, window)).or_default().push(""); } i = at + 1; continue; @@ -441,6 +468,28 @@ mod tests { assert!(!entities_expand_past(&svg, MAX_ENTITY_EXPANSION)); } + #[test] + fn a_multibyte_cut_does_not_scan_the_rest_of_the_suffix() { + // The MAX_NAME+1 window ends in the middle of `é`. Falling back to the whole + // suffix would walk every following `x` looking for whitespace. Inside an + // entity value the marker is still counted (same conservative rule as other + // declarations in values), and because the name is overlong the document is + // refused — but the scan stays linear. + let mid = format!("{}é{}", "x".repeat(MAX_NAME), "x".repeat(200_000)); + let in_value = format!("]>"); + assert!(entities_expand_past(&in_value, MAX_ENTITY_EXPANSION)); + // The recorded overlong key must stay a short prefix, not the whole suffix + // the old unwrap_or(rest) fallback would have stored. + assert!(declared(&in_value).keys().all(|name| name.len() <= MAX_NAME + 4)); + // A short multibyte name is still read as a normal declaration. + let short = "]>"; + assert!(!entities_expand_past(short, MAX_ENTITY_EXPANSION)); + // An overlong name that straddles the window is still refused. + let long = format!("{}é", "n".repeat(MAX_NAME)); + let long_name = format!("]>"); + assert!(entities_expand_past(&long_name, MAX_ENTITY_EXPANSION)); + } + fn svg(body: &str) -> String { format!(r#"{body}"#) } diff --git a/crates/texture/README.md b/crates/texture/README.md index a41b42666..8c82e5d0b 100644 --- a/crates/texture/README.md +++ b/crates/texture/README.md @@ -25,7 +25,16 @@ network I/O and has no `unsafe` code. (). Repeat keeps its period at any finite coordinate. A NaN or infinite coordinate gives `[0, 0, 0, 1]`. Bilinear sums are taken in `f64` and clamped to the `f32` range, so finite - texels give a finite sample. + texels give a finite sample. `sample_axes`, `sample_nearest_axes` and `get_axes` take + `tiling: [bool; 2]`, the wrap mode of `u` and of `v` on their own, as glTF's `wrapS` and + `wrapT`; with equal entries they give the same results as the forms with one `tile`. +- **Stored sampling.** `sample_stored` is the texture read of MaterialCraft's function graphs. It + rounds the bilinear weights to multiples of 1/256 and blends the texels by linear interpolation + in `f32`. When the image's integer-sampling flag is on (`with_integer_sampling(true)`, read with + `integer_sampling()`), it then clamps each channel to `0..=1` and rounds it to a multiple of + 1/65535. A channel whose interpolation is not finite is taken from the `f64` weighted sum + instead, so finite texels give a finite sample. New images start with the flag off, clones keep + it, and two images are equal only when their flags are equal. - **Other operations.** `get` reads one texel, `map`, `to_gray`, `to_color` and `to_kind` convert, `resize` box-averages whole-factor shrinks and samples bilinearly otherwise, and `to_rgba8_display` encodes 8-bit sRGB RGBA. `linear_to_srgb`, `srgb_to_linear` and `luminance` @@ -58,7 +67,8 @@ Without `parallel` the crate builds for `wasm32-unknown-unknown`. | Part | Source | |---|---| | `Image`, `Kind`, sampling, resizing, conversions, sRGB helpers, resource keys and the six tests `sample_survives_huge_coordinates`, `resource_keys_round_trip`, `sample_wraps_and_clamps`, `resize_box_and_bilinear`, `hostile_sizes_are_clamped`, `conversions` | MaterialCraft `crates/image/src/lib.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) | -| `Limits`, the `try_` constructors, `from_data`, private fields with getters, the `parallel` feature | written here | +| `get_axes`, `sample_axes`, `sample_nearest_axes`, `sample_stored` and the integer-sampling flag | MaterialCraft `crates/image/src/lib.rs` at [6c3b35c](https://github.com/storytold/materialcraft/commit/6c3b35c39632feafcda3d7a90ff18242f3ad910f), on this crate's coordinate reduction and `f64` bilinear sum | +| `Limits`, the `try_` constructors, `from_data`, private fields with getters, the `parallel` feature, `with_integer_sampling` and `integer_sampling` | written here | ## Migration @@ -73,5 +83,7 @@ For MaterialCraft: | --- | --- | | `image.w`, `image.h`, `image.kind`, `image.data` | `width()`, `height()`, `kind()`, `data()` and `shared_data()` | | `Image { w, h, kind, data }` built by hand | `Image::from_data(w, h, kind, data, &Limits::default())` | +| `image.integer_sampling = on` and `Image { integer_sampling, .. }` | `image.with_integer_sampling(on)`; read it with `integer_sampling()` | +| `sample_axes` blends with `a + (b − a)t` in `f32` | it sums the weighted texels in `f64`, as `sample` does; the results differ by rounding | | `rayon` always on | the `parallel` feature | | `linear_to_srgb(NaN)` returned −0.055 | it returns NaN | diff --git a/crates/texture/src/lib.rs b/crates/texture/src/lib.rs index e33b68d88..baaabee66 100644 --- a/crates/texture/src/lib.rs +++ b/crates/texture/src/lib.rs @@ -12,6 +12,10 @@ //! [`Image::sample_nearest`] and [`Image::sample`] (bilinear) use the texel coordinates, wrapping //! and weights of the Vulkan specification, sections 20.4.1, 20.6.1 and 20.6.3 //! (). +//! [`Image::get_axes`], [`Image::sample_axes`] and [`Image::sample_nearest_axes`] take the wrap +//! mode of each axis on its own. [`Image::sample_stored`] is MaterialCraft's function-graph texture +//! read: bilinear with weights rounded to eight fractional bits, and with its result rounded to 16 +//! bits when the image's integer-sampling flag is on ([`Image::with_integer_sampling`]). //! //! Sizes are bounded. [`Limits`] caps the side, the pixel count and the bytes, and the `try_` //! constructors return an [`ImageError`] before allocating anything over them. A plane is also @@ -133,15 +137,18 @@ pub struct Image { w: u32, h: u32, kind: Kind, + /// Whether [`Image::sample_stored`] rounds its result to 16 bits, as for a normalized integer + /// texture. Off for every new image. + integer_sampling: bool, /// Row-major, `kind.channels()` floats per pixel. data: Arc>, } -/// Images are equal when their size, kind and floats are equal. Floats compare as `f32` does, so -/// an image holding NaN is unequal to every image, its clones included. +/// Images are equal when their size, kind, integer-sampling flag and floats are equal. Floats +/// compare as `f32` does, so an image holding NaN is unequal to every image, its clones included. impl PartialEq for Image { fn eq(&self, o: &Image) -> bool { - self.w == o.w && self.h == o.h && self.kind == o.kind && self.data == o.data + self.w == o.w && self.h == o.h && self.kind == o.kind && self.integer_sampling == o.integer_sampling && self.data == o.data } } @@ -190,6 +197,13 @@ fn reduce(t: f32, tile: bool) -> Option { Some(if tile { t.rem_euclid(1.0).min(BELOW_ONE) } else { t.clamp(-1.0, 2.0) }) } +/// A bilinear sum taken in `f64` as an `f32`: a finite sum clamped to the `f32` range, and an +/// infinite or NaN sum as it is. +#[inline] +fn f32_of_sum(v: f64) -> f32 { + if v.is_finite() { v.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32 } else { v as f32 } +} + /// Fill `data` row by row with `f(x, y)`, keeping the first `c` channels of each result. fn fill [f32; 4] + Sync>(data: &mut [f32], w: u32, c: usize, f: &F) { let row_len = (w as usize).max(1) * c; @@ -212,7 +226,7 @@ impl Image { let (w, h, len) = bounded_size(w, h, kind, MAX_ALLOC_BYTES); let mut data = vec![0.0f32; len]; fill(&mut data, w, kind.channels(), &f); - Image { w, h, kind, data: Arc::new(data) } + Image { w, h, kind, integer_sampling: false, data: Arc::new(data) } } /// An image checked against `limits`, with its memory reserved before any pixel is generated. @@ -222,7 +236,7 @@ impl Image { data.try_reserve_exact(len).map_err(|_| ImageError::OutOfMemory(w, h))?; data.resize(len, 0.0); fill(&mut data, w, kind.channels(), &f); - Ok(Image { w, h, kind, data: Arc::new(data) }) + Ok(Image { w, h, kind, integer_sampling: false, data: Arc::new(data) }) } /// A constant image, each side clamped to `1..=MAX_SIDE`. @@ -275,7 +289,21 @@ impl Image { if data.len() != expected { return Err(ImageError::BadDataLength { expected, found: data.len() }); } - Ok(Image { w, h, kind, data }) + Ok(Image { w, h, kind, integer_sampling: false, data }) + } + + /// This image with the integer-sampling flag set to `on`. The flag only changes + /// [`Image::sample_stored`], which then rounds its result to 16 bits. Clones keep the flag. + /// [`Image::map`], [`Image::resize`] to a new size and the other operations that make a new + /// buffer return an image with the flag off. The pixels are not changed or copied. + pub fn with_integer_sampling(mut self, on: bool) -> Image { + self.integer_sampling = on; + self + } + + /// Whether [`Image::sample_stored`] rounds its result to 16 bits. + pub fn integer_sampling(&self) -> bool { + self.integer_sampling } pub fn width(&self) -> u32 { @@ -311,7 +339,14 @@ impl Image { /// The pixel at integer coordinates (wrapped or clamped), as RGBA (gray → `[v, v, v, 1]`). #[inline] pub fn get(&self, x: i64, y: i64, tile: bool) -> [f32; 4] { - let (x, y) = (wrap(x, self.w, tile), wrap(y, self.h, tile)); + self.get_axes(x, y, [tile; 2]) + } + + /// [`Image::get`] with the wrap mode of each axis given on its own: `tiling[0]` repeats `x` + /// and `tiling[1]` repeats `y`; an axis whose entry is `false` is clamped to its edge texels. + #[inline] + pub fn get_axes(&self, x: i64, y: i64, tiling: [bool; 2]) -> [f32; 4] { + let (x, y) = (wrap(x, self.w, tiling[0]), wrap(y, self.h, tiling[1])); let i = y * self.w as usize + x; match self.kind { Kind::Gray => { @@ -342,7 +377,15 @@ impl Image { /// leaves a sample at a texel center unchanged. NaN or infinite coordinates give `[0, 0, 0, 1]`. #[inline] pub fn sample(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + self.sample_axes(u, v, [tile; 2]) + } + + /// [`Image::sample`] with the wrap mode of each axis given on its own: `tiling[0]` for `u` and + /// `tiling[1]` for `v`, as glTF samplers set `wrapS` and `wrapT` separately. With both entries + /// equal the result is the same as [`Image::sample`] with that `tile`. + #[inline] + pub fn sample_axes(&self, u: f32, v: f32, tiling: [bool; 2]) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tiling[0]), reduce(v, tiling[1])) else { return [0.0, 0.0, 0.0, 1.0]; }; let fx = u * self.w as f32 - 0.5; @@ -359,12 +402,12 @@ impl Image { if weight == 0.0 { continue; } - let p = self.get(x, y, tile); + let p = self.get_axes(x, y, tiling); for (o, p) in o.iter_mut().zip(p) { *o += f64::from(weight) * f64::from(p); } } - o.map(|v| if v.is_finite() { v.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32 } else { v as f32 }) + o.map(f32_of_sum) } #[inline] @@ -376,18 +419,73 @@ impl Image { } } + /// Bilinear sample at normalized `(u, v)` with filter weights of eight fractional bits, the + /// texture read of MaterialCraft's function graphs. The texel coordinate and wrapping are those + /// of [`Image::sample`]. Each fractional part `α` and `β` is rounded to the nearest multiple of + /// 1/256 (a half rounds away from zero), and the four texels are blended by linear + /// interpolation in `f32`: `a + (b − a)α` along each of the two rows, then the same between + /// the rows with `β`. When the image's integer-sampling flag is on + /// ([`Image::with_integer_sampling`]), each channel is then clamped to `0..=1` and rounded to + /// the nearest multiple of 1/65535, as a filtered 16-bit texel. A NaN channel stays NaN. + /// + /// A channel whose interpolation is infinite or NaN is computed again as the weighted sum of + /// [`Image::sample`], skipping texels of weight 0 and clamping a finite sum to the `f32` + /// range, so finite texels give a finite sample. NaN or infinite coordinates give + /// `[0, 0, 0, 1]`. + #[inline] + pub fn sample_stored(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let pixel = self.sample_fixed_weights(u, v, tile); + if self.integer_sampling { pixel.map(|value| (value.clamp(0.0, 1.0) * 65535.0).round() / 65535.0) } else { pixel } + } + + /// The bilinear interpolation of [`Image::sample_stored`] before its 16-bit rounding. + #[inline] + fn sample_fixed_weights(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + return [0.0, 0.0, 0.0, 1.0]; + }; + let fx = u * self.w as f32 - 0.5; + let fy = v * self.h as f32 - 0.5; + let (x0, y0) = (fx.floor(), fy.floor()); + let tx = ((fx - x0) * 256.0).round() / 256.0; + let ty = ((fy - y0) * 256.0).round() / 256.0; + let (x0, y0) = (x0 as i64, y0 as i64); + let (a, b, c, d) = (self.get(x0, y0, tile), self.get(x0 + 1, y0, tile), self.get(x0, y0 + 1, tile), self.get(x0 + 1, y0 + 1, tile)); + let mut o = [0.0f32; 4]; + for (k, o) in o.iter_mut().enumerate() { + let top = a[k] + (b[k] - a[k]) * tx; + let bot = c[k] + (d[k] - c[k]) * tx; + *o = top + (bot - top) * ty; + if !o.is_finite() { + let taps = [((1.0 - tx) * (1.0 - ty), a[k]), (tx * (1.0 - ty), b[k]), ((1.0 - tx) * ty, c[k]), (tx * ty, d[k])]; + let sum = taps.iter().filter(|(weight, _)| *weight != 0.0).map(|(weight, p)| f64::from(*weight) * f64::from(*p)).sum(); + *o = f32_of_sum(sum); + } + } + o + } + /// Nearest sample at normalized `(u, v)`: the texel `floor(u × w)`, wrapped or clamped. NaN or /// infinite coordinates give `[0, 0, 0, 1]`. #[inline] pub fn sample_nearest(&self, u: f32, v: f32, tile: bool) -> [f32; 4] { - let (Some(u), Some(v)) = (reduce(u, tile), reduce(v, tile)) else { + self.sample_nearest_axes(u, v, [tile; 2]) + } + + /// [`Image::sample_nearest`] with the wrap mode of each axis given on its own: `tiling[0]` for + /// `u` and `tiling[1]` for `v`. With both entries equal the result is the same as + /// [`Image::sample_nearest`] with that `tile`. + #[inline] + pub fn sample_nearest_axes(&self, u: f32, v: f32, tiling: [bool; 2]) -> [f32; 4] { + let (Some(u), Some(v)) = (reduce(u, tiling[0]), reduce(v, tiling[1])) else { return [0.0, 0.0, 0.0, 1.0]; }; let (x, y) = ((u * self.w as f32).floor() as i64, (v * self.h as f32).floor() as i64); // A repeated coordinate is below 1, so its texel is below the size even where `u × w` // rounds up to it. - let (x, y) = if tile { (x.min(i64::from(self.w) - 1), y.min(i64::from(self.h) - 1)) } else { (x, y) }; - self.get(x, y, tile) + let x = if tiling[0] { x.min(i64::from(self.w) - 1) } else { x }; + let y = if tiling[1] { y.min(i64::from(self.h) - 1) } else { y }; + self.get_axes(x, y, tiling) } /// Map every pixel (as RGBA) to a new image of `kind`, same size. When a result of that size @@ -895,4 +993,247 @@ mod tests { assert_eq!(half.data(), &[0.5, 0.5, 0.0, 1.0, 2.5, 0.5, 0.0, 1.0]); assert_eq!(img.to_gray().width(), 4); } + + /// The four wrap combinations of the two axes. + const TILINGS: [[bool; 2]; 4] = [[false, false], [true, true], [true, false], [false, true]]; + + /// Gray texels of 8-bit values, `k / 255`. + fn gray8() -> Image { + Image::gray(5, 3, |x, y| ((x * 37 + y * 91 + 13) % 256) as f32 / 255.0) + } + + /// Color texels from −2.5 to 3.42, with negative values and values above 1. + fn color() -> Image { + Image::generate(4, 3, Kind::Color, |x, y| { + let s = |k: u32| ((x * 7 + y * 13 + k * 5) % 17) as f32 * 0.37 - 2.5; + [s(0), s(1), s(2), s(3)] + }) + } + + /// 65 even steps from `lo` to `hi`, then the texel centers and edges of sides 3, 4 and 5. + fn coordinates(lo: f32, hi: f32) -> Vec { + let mut v: Vec = (0..=64).map(|i| lo + (hi - lo) * i as f32 / 64.0).collect(); + for side in [3u32, 4, 5] { + v.extend((0..=2 * side).map(|i| i as f32 / (2 * side) as f32)); + } + v + } + + /// FNV-1a over the bits of every channel. + fn hash(h: &mut u64, p: [f32; 4]) { + for b in p.iter().flat_map(|v| v.to_bits().to_le_bytes()) { + *h ^= u64::from(b); + *h = h.wrapping_mul(0x100_0000_01b3); + } + } + + const FNV_START: u64 = 0xcbf2_9ce4_8422_2325; + + /// Hash of `f(u, v)` over every pair of `coordinates`. + fn hash_grid(us: &[f32], f: impl Fn(f32, f32) -> [f32; 4]) -> u64 { + let mut h = FNV_START; + for &u in us { + for &v in us { + hash(&mut h, f(u, v)); + } + } + h + } + + /// Hashes of `sample_stored`, `sample_nearest_axes` and `get_axes` computed with MaterialCraft's + /// `crates/image` at storytold/materialcraft `6c3b35c396`, over the fixtures and grids above. + #[test] + fn stored_and_axis_reads_match_materialcraft() { + // (range, image, integer sampling, tile, sample_stored hash) + let stored = [ + ("unit", "gray8", false, false, 0x702b_0f81_2833_5e06u64), + ("unit", "gray8", false, true, 0x4ac5_b29c_45b2_d0ca), + ("unit", "gray8", true, false, 0x8400_a867_00fc_389a), + ("unit", "gray8", true, true, 0x47ea_befd_7fd6_cc5e), + ("unit", "color", false, false, 0x25f6_2544_f084_4182), + ("unit", "color", false, true, 0x607f_3c9f_896b_5975), + ("unit", "color", true, false, 0x0261_02eb_451b_36d6), + ("unit", "color", true, true, 0x51f8_9417_f5e9_2341), + ("wide", "gray8", false, false, 0xb0e7_096c_c64b_0f72), + ("wide", "gray8", false, true, 0x7a8a_4059_68ac_2a07), + ("wide", "gray8", true, false, 0x418c_9c08_2718_2171), + ("wide", "gray8", true, true, 0xe0b7_0088_256f_ccb2), + ("wide", "color", false, false, 0x51b4_8bb3_2885_f844), + ("wide", "color", false, true, 0xab4b_72d5_25ff_aaed), + ("wide", "color", true, false, 0x6570_eaa2_25f3_4d29), + ("wide", "color", true, true, 0x15a3_5aa7_7f50_4f92), + ]; + // (range, image, sample_nearest_axes hash for each entry of TILINGS) + let nearest = [ + ("unit", "gray8", [0xe427_9012_572d_b173u64, 0x76b9_e33c_849f_069d, 0x42ab_5ecd_8f1a_5dd2, 0x190c_23b8_f3e9_a2e5]), + ("unit", "color", [0x6a0e_0370_810d_1ad9, 0x0ab0_d62b_8308_4f9d, 0xa839_3cdf_db7d_844a, 0x1fc4_027e_bb8d_7c45]), + ("wide", "gray8", [0xd1cf_daaf_d7db_239c, 0x1d22_a6db_ad03_0960, 0x754e_fabf_5203_d6a0, 0xfe73_7385_df89_4dd4]), + ("wide", "color", [0xb894_834b_96fe_684d, 0x7eb4_0a21_3a51_c6bc, 0x2443_5503_2fea_4068, 0x4705_30d0_9afc_dc75]), + ]; + // (image, get_axes hash over x and y in -12..12 for each entry of TILINGS) + let get = [ + ("gray8", [0x6c95_1e05_c9c6_8f21u64, 0xac4a_e19a_4da7_b625, 0xcee5_f582_facb_f043, 0x7f1d_ff0e_357b_5eb5]), + ("color", [0x21af_a81f_327a_d3af, 0x9cf4_2557_9880_5345, 0x9b58_bde1_8021_2779, 0x6bb0_a98f_13d5_6635]), + ]; + let image = |name: &str| if name == "gray8" { gray8() } else { color() }; + let grid = |range: &str| if range == "unit" { coordinates(0.0, 0.99) } else { coordinates(-2.5, 3.5) }; + for (range, name, integer, tile, expected) in stored { + let img = image(name).with_integer_sampling(integer); + let h = hash_grid(&grid(range), |u, v| img.sample_stored(u, v, tile)); + assert_eq!(h, expected, "sample_stored {range} {name} integer {integer} tile {tile}"); + } + for (range, name, expected) in nearest { + let img = image(name); + for (tiling, expected) in TILINGS.into_iter().zip(expected) { + let h = hash_grid(&grid(range), |u, v| img.sample_nearest_axes(u, v, tiling)); + assert_eq!(h, expected, "sample_nearest_axes {range} {name} {tiling:?}"); + } + } + for (name, expected) in get { + let img = image(name); + for (tiling, expected) in TILINGS.into_iter().zip(expected) { + let mut h = FNV_START; + for x in -12..12 { + for y in -12..12 { + hash(&mut h, img.get_axes(x, y, tiling)); + } + } + assert_eq!(h, expected, "get_axes {name} {tiling:?}"); + } + } + } + + /// Values of MaterialCraft's `sample_axes` at storytold/materialcraft `6c3b35c396`. It blends + /// by linear interpolation in `f32`, and this crate sums the weighted texels in `f64`, so the + /// results differ by rounding only. + #[test] + fn axis_bilinear_matches_materialcraft_up_to_rounding() { + let img = color(); + let cases = [ + (0.3, 0.7, [true, false], [1.473_799_7, -0.072_800_055, 0.645_000_2, 0.733_799_8]), + (0.3, 0.7, [false, true], [1.473_799_7, -0.072_800_055, 0.645_000_2, 0.733_799_8]), + (1.2, -0.4, [true, false], [-1.722_999_5, 0.127_000_57, 0.089_999_32, 1.939_999_3]), + (1.2, -0.4, [false, true], [-1.057_000_3, -1.094, 0.756_000_1, 2.606_000_2]), + (-0.15, 1.1, [true, false], [2.051, -1.76, 0.090_000_15, 1.311_000_1]), + (-0.15, 1.1, [false, true], [-1.834_000_6, 0.015_999_317, 0.608_000_5, 2.458_000_7]), + (0.95, 0.05, [true, false], [-1.464, 0.386_000_04, 2.236_000_3, -0.317_000_15]), + (0.95, 0.05, [false, true], [0.145_500_18, -0.206_000_21, 1.644_000_2, -0.594_499_8]), + ]; + for (u, v, tiling, expected) in cases { + let p = img.sample_axes(u, v, tiling); + for (p, e) in p.iter().zip(expected) { + assert!((p - e).abs() <= 2.0e-6, "u {u} v {v} {tiling:?}: {p} against {e}"); + } + } + } + + #[test] + fn equal_axes_give_the_shared_results() { + let us = coordinates(-2.5, 3.5); + for img in [gray8(), color()] { + for tile in [false, true] { + for &u in &us { + for &v in &us { + assert_eq!(img.sample_axes(u, v, [tile; 2]).map(f32::to_bits), img.sample(u, v, tile).map(f32::to_bits)); + assert_eq!(img.sample_nearest_axes(u, v, [tile; 2]).map(f32::to_bits), img.sample_nearest(u, v, tile).map(f32::to_bits)); + } + } + for x in -12..12 { + assert_eq!(img.get_axes(x, -x, [tile; 2]), img.get(x, -x, tile)); + } + } + } + } + + #[test] + fn axes_wrap_independently() { + // Texel (x, y) holds x + 10y. + let img = Image::gray(4, 2, |x, y| (x + 10 * y) as f32); + assert_eq!(img.get_axes(-1, -1, [true, false])[0], 3.0); + assert_eq!(img.get_axes(-1, -1, [false, true])[0], 10.0); + assert_eq!(img.get_axes(5, 3, [true, false])[0], 11.0); + assert_eq!(img.sample_nearest_axes(1.1, 1.5, [true, false])[0], 10.0); + assert_eq!(img.sample_nearest_axes(1.1, 1.5, [false, true])[0], 13.0); + // v = 0.25 is the center of row 0; u = 1 is halfway between texels 3 and 0 when repeating. + assert!((img.sample_axes(1.0, 0.25, [true, false])[0] - 1.5).abs() < 1e-6); + assert_eq!(img.sample_axes(1.0, 0.25, [false, true])[0], 3.0); + assert_eq!(img.sample_axes(f32::NAN, 0.5, [false, true]), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(img.sample_nearest_axes(0.5, f32::INFINITY, [true, false]), [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn stored_sampling_rounds_weights_to_eight_bits() { + let img = Image::gray(2, 1, |x, _| x as f32); + // u × 2 − 0.5 = 0.3: the weight 0.3 rounds to 77/256. + assert_eq!(img.sample_stored(0.4, 0.5, false)[0], 77.0 / 256.0); + assert!((img.sample(0.4, 0.5, false)[0] - 0.3).abs() < 1e-6); + // A fraction of 255.5/256 or more rounds up to the next texel. + assert_eq!(img.sample_stored((1.5 - 0.25 / 256.0) / 2.0, 0.5, false)[0], 1.0); + assert_eq!(img.sample_stored(f32::NAN, 0.5, true), [0.0, 0.0, 0.0, 1.0]); + assert_eq!(img.sample_stored(0.5, f32::NEG_INFINITY, false), [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn integer_sampling_rounds_stored_samples_to_sixteen_bits() { + let img = Image::gray(2, 1, |x, _| x as f32); + assert!(!img.integer_sampling()); + let int = img.clone().with_integer_sampling(true); + assert!(int.integer_sampling()); + // 77/256 × 65535 = 19711.64, which rounds to 19712. + assert_eq!(int.sample_stored(0.4, 0.5, false)[0], 19_712.0 / 65_535.0); + assert_eq!(int.sample(0.4, 0.5, false), img.sample(0.4, 0.5, false)); + assert_eq!(int.sample_nearest(0.4, 0.5, false), img.sample_nearest(0.4, 0.5, false)); + let l = Limits::default(); + let Ok(wide) = Image::from_data(3, 1, Kind::Gray, vec![-0.5, 2.0, f32::NAN], &l) else { panic!("valid 3 x 1 image") }; + let wide = wide.with_integer_sampling(true); + assert_eq!(wide.sample_stored(0.5 / 3.0, 0.5, false)[0], 0.0); + assert_eq!(wide.sample_stored(1.5 / 3.0, 0.5, false)[0], 1.0); + assert!(wide.sample_stored(2.5 / 3.0, 0.5, false)[0].is_nan()); + assert_eq!(wide.sample_stored(0.5 / 3.0, 0.5, false)[3], 1.0); + } + + #[test] + fn integer_sampling_follows_clones_and_not_new_buffers() { + let img = Image::gray(4, 2, |x, y| (x + y) as f32 / 8.0).with_integer_sampling(true); + let plain = img.clone().with_integer_sampling(false); + assert_eq!(img.clone(), img); + assert_ne!(img, plain); + assert_eq!(img.data(), plain.data()); + assert!(img.clone().integer_sampling()); + assert!(img.to_gray().integer_sampling()); + assert!(img.resize(4, 2, false).integer_sampling()); + assert!(!img.resize(2, 1, false).integer_sampling()); + assert!(!img.map(Kind::Gray, |p| p).integer_sampling()); + assert!(!img.to_color().integer_sampling()); + assert!(img.try_to_kind(Kind::Gray, &Limits::default()).is_ok_and(|i| i.integer_sampling())); + assert!(Arc::ptr_eq(img.shared_data(), plain.shared_data())); + } + + #[test] + fn stored_sampling_keeps_finite_texels_finite() { + let l = Limits::default(); + let Ok(inf) = Image::from_data(2, 1, Kind::Gray, vec![1.0, f32::INFINITY], &l) else { panic!("valid 2 x 1 image") }; + // The center of texel 0 gives texel 0, though its neighbor is infinite. + assert_eq!(inf.sample_stored(0.25, 0.5, false)[0], 1.0); + assert_eq!(inf.sample_stored(0.5, 0.5, false)[0], f32::INFINITY); + let Ok(hdr) = Image::from_data(2, 1, Kind::Gray, vec![f32::MAX, -f32::MAX], &l) else { panic!("valid 2 x 1 image") }; + assert_eq!(hdr.sample_stored(0.5, 0.5, false)[0], 0.0); + assert_eq!(hdr.clone().with_integer_sampling(true).sample_stored(0.5, 0.5, false)[0], 0.0); + let max = Image::filled(2, 2, Kind::Gray, [f32::MAX; 4]); + for tile in [false, true] { + assert_eq!(max.sample_stored(0.3, 0.6, tile)[0], f32::MAX, "tile = {tile}"); + } + } + + #[test] + fn stored_sampling_keeps_the_repeat_period_at_large_coordinates() { + let img = stripe(); + let at_zero = img.sample_stored(0.0, 0.5, true)[0]; + assert_eq!(at_zero, 0.5); + for u in [1.0e9_f32, -1.0e9, 4.0e9, 3.0e12, f32::MAX] { + assert_eq!(img.sample_stored(u, 0.5, true)[0], at_zero, "u = {u}"); + let edge = if u > 0.0 { 1.0 } else { 0.0 }; + assert_eq!(img.sample_stored(u, 0.5, false)[0], edge, "u = {u}"); + } + } } diff --git a/crates/timeline/src/lib.rs b/crates/timeline/src/lib.rs index b638fd3ec..8c409120e 100644 --- a/crates/timeline/src/lib.rs +++ b/crates/timeline/src/lib.rs @@ -34,6 +34,7 @@ pub mod model; #[cfg(feature = "otio")] pub mod otio; pub mod path; +pub mod preflight; pub mod rate; pub mod report; pub mod time; diff --git a/crates/timeline/src/preflight.rs b/crates/timeline/src/preflight.rs new file mode 100644 index 000000000..235577198 --- /dev/null +++ b/crates/timeline/src/preflight.rs @@ -0,0 +1,82 @@ +//! Allocation-free lexical nesting preflight for timeline XML and JSON. +//! +//! Extracted from EffectCraft's interchange reader; original attribution is retained in Git history. +//! These functions preserve its lightweight byte-scanner behavior. They do not validate +//! syntax, expand entities, decode encodings, or replace a bounded format parser. In +//! particular XML self-closing elements do not increase the count, and declarations are +//! skipped lexically rather than parsed as DTDs. Apply document/encoding/entity policy +//! separately; callers choose the maximum acceptable nesting for their parser. + +/// The deepest element nesting of an XML document (a quick scan that skips comments, CDATA, +/// processing instructions, declarations and quoted attribute values). +pub fn xml_depth(b: &[u8]) -> usize { + let (mut i, mut depth, mut max) = (0usize, 0usize, 0usize); + let skip_to = + |from: usize, end: &[u8]| b.get(from..).and_then(|r| r.windows(end.len()).position(|w| w == end)).map_or(b.len(), |p| from + p + end.len()); + while let Some(&c) = b.get(i) { + if c != b'<' { + i += 1; + continue; + } + let rest = b.get(i..).unwrap_or_default(); + if rest.starts_with(b""); + } else if rest.starts_with(b"") { + i = skip_to(i + 9, b""); + } else if rest.starts_with(b""); + } else if rest.starts_with(b""); + } else if rest.starts_with(b""); + } else { + // A start tag: find its end outside quotes; `/>` closes it at once. + let mut j = i + 1; + let mut quote = None; + while let Some(&c) = b.get(j) { + match quote { + Some(q) if c == q => quote = None, + Some(_) => {} + None if c == b'"' || c == b'\'' => quote = Some(c), + None if c == b'>' => break, + None => {} + } + j += 1; + } + if b.get(j.wrapping_sub(1)) != Some(&b'/') { + depth += 1; + max = max.max(depth); + } + i = j + 1; + } + } + max +} + +/// The deepest array / object nesting of a JSON document (strings skipped). +pub fn json_depth(b: &[u8]) -> usize { + let (mut depth, mut max, mut in_str, mut esc) = (0usize, 0usize, false, false); + for &c in b { + if in_str { + if esc { + esc = false; + } else if c == b'\\' { + esc = true; + } else if c == b'"' { + in_str = false; + } + continue; + } + match c { + b'"' => in_str = true, + b'[' | b'{' => { + depth += 1; + max = max.max(depth); + } + b']' | b'}' => depth = depth.saturating_sub(1), + _ => {} + } + } + max +} diff --git a/crates/timeline/tests/preflight.rs b/crates/timeline/tests/preflight.rs new file mode 100644 index 000000000..bbe485d67 --- /dev/null +++ b/crates/timeline/tests/preflight.rs @@ -0,0 +1,31 @@ +use craft_timeline::preflight::{json_depth, xml_depth}; + +#[test] +fn xml_skips_markup_inside_quotes_comments_and_cdata() { + let input = br#"<fake>"#; + assert_eq!(xml_depth(input), 2); + assert_eq!(xml_depth(b""), 0); +} + +#[test] +fn lexical_scans_do_not_claim_to_validate_malformed_documents() { + assert_eq!(xml_depth(b""), 1); + assert_eq!(xml_depth(b"