From ce819906a58fc8ce0482ed159f11c4d1e7fa2d3b Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Tue, 13 Oct 2026 12:28:12 -0700 Subject: [PATCH 01/57] craft-cms: public constructors for matrix/TRC and gray profiles (closes #61) - Add Curve::gamma, Curve::parametric, and Curve::from_table constructors with finite and range validation. - Add Profile::matrix_shaper accepting PCS D50-adapted matrices and populating chad for non-D50 white points. - Add Profile::from_source_matrix adapting unadapted source primaries to PCS D50 via Bradford transform. - Add Profile::gray constructor for monochrome display profiles. - Validate curve samples remain within [0.0, 1.0] and verify colorant matrix invertibility post-quantization. - Re-export math::Mat3 from the crate root. - Add independent ICC oracle validation tests against moxcms verifying both matrix conventions produce exact color transforms (diff <= 1). --- crates/cms/src/curve.rs | 31 +++++++ crates/cms/src/lib.rs | 3 +- crates/cms/src/profile.rs | 113 ++++++++++++++++++++++++++ crates/cms/tests/constructors.rs | 135 +++++++++++++++++++++++++++++++ crates/cms/tests/fogra39.rs | 9 ++- 5 files changed, 288 insertions(+), 3 deletions(-) create mode 100644 crates/cms/tests/constructors.rs diff --git a/crates/cms/src/curve.rs b/crates/cms/src/curve.rs index f50f2d663..9e2795cd8 100644 --- a/crates/cms/src/curve.rs +++ b/crates/cms/src/curve.rs @@ -26,6 +26,37 @@ 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 !g.is_finite() || g <= 0.0 { + return Err(crate::CmsError::InvalidArgument("gamma must be positive and finite".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| v.is_finite()) { + return Err(crate::CmsError::InvalidArgument("parametric curve parameters must be finite".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)) + } + /// 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 613d0db6b..31dc6b1ab 100644 --- a/crates/cms/src/lib.rs +++ b/crates/cms/src/lib.rs @@ -13,7 +13,7 @@ //! * [`Lut3d`] samples a display transform into a 3D texture for the GPU canvas. //! //! Implemented from the public ICC.1:2010 (v4.3) and ICC.1:2001-04 (v2) specifications, -//! CIE 15, and Adobe's published black point compensation paper. +//! CIE 15, and the ISO 18619 black point compensation standard. #![forbid(unsafe_code)] pub mod builtin; @@ -34,6 +34,7 @@ pub use clut::Clut; pub use curve::Curve; pub use gamut::GamutCheck; pub use lut3d::Lut3d; +pub use math::Mat3; pub use profile::{ColorSpace, Pcs, Profile, ProfileClass}; pub use transform::{SampleKind, Transform, TransformOptions, black_point, cached}; diff --git a/crates/cms/src/profile.rs b/crates/cms/src/profile.rs index ef8cbcee6..9c428179d 100644 --- a/crates/cms/src/profile.rs +++ b/crates/cms/src/profile.rs @@ -182,6 +182,119 @@ 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 { + if !white.iter().all(|&c| c.is_finite() && c > 0.0) { + return Err(CmsError::InvalidArgument("white point must be positive and finite".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 math::invert(&q).is_none() { + return Err(CmsError::InvalidArgument("colorant matrix became singular after quantization/normalization".into())); + } + let chad_quantized = chad.map(|a| a.map(|row| row.map(math::s15f16_round))); + + 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| c.is_finite() && c > 0.0) { + return Err(CmsError::InvalidArgument("white point must be positive and finite".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 { + if !white.iter().all(|&c| c.is_finite() && c > 0.0) { + return Err(CmsError::InvalidArgument("white point must be positive and finite".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 { let mut p = parse_profile(bytes)?; diff --git a/crates/cms/tests/constructors.rs b/crates/cms/tests/constructors.rs new file mode 100644 index 000000000..eecd8883e --- /dev/null +++ b/crates/cms/tests/constructors.rs @@ -0,0 +1,135 @@ +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}"); +} diff --git a/crates/cms/tests/fogra39.rs b/crates/cms/tests/fogra39.rs index f7fcdd0ca..f958ffc51 100644 --- a/crates/cms/tests/fogra39.rs +++ b/crates/cms/tests/fogra39.rs @@ -545,8 +545,13 @@ fn stand_in_separations_respect_the_ink_limit() { let t = Transform::new(Builtin::Srgb.profile(), cmyk, intent, true).unwrap(); let mut out = vec![0.0f32; N * N * N * 4]; t.convert_f32(&grid, 3, &mut out, 4, false).unwrap(); - let (i, max) = - out.chunks_exact(4).map(|c| c.iter().sum::()).enumerate().fold((0, 0.0f32), |m, (i, s)| if s > m.1 { (i, s) } else { m }); + let (i, max) = out + .as_chunks::<4>() + .0 + .iter() + .map(|c| c.iter().sum::()) + .enumerate() + .fold((0, 0.0f32), |m, (i, s)| if s > m.1 { (i, s) } else { m }); eprintln!("{name}, {intent:?}: max total ink {:.2} % at sRGB {:?}", max * 100.0, &grid[i * 3..i * 3 + 3]); assert!(max <= LIMIT, "{name}, {intent:?}: total ink {max} at sRGB {:?}", &grid[i * 3..i * 3 + 3]); From 4a250888020df77cb7bdac49252c6d79ae15c1cc Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Sat, 14 Nov 2026 11:18:42 -0500 Subject: [PATCH 02/57] craft-xlsx: read the tables of a binary workbook Package::tables reads a sheet's tableN.bin parts, through its BrtListParts, into the Table the XML reader builds, as Excel writes the table in .xlsx: BrtBeginList and its columns, the calculated and totals formulas decoded as cell formulas are, an XML map's column properties, the table style, and the AutoFilter and sort state built as the autoFilter and sortState elements. A filter column whose criteria are in an extension (date groups) or on a Boolean value is left out with a warning, as is a sort by stroke or PinYin order. PtgList now decodes to the structured reference .xlsx holds (Sales[Val], Sales[[#Headers],[Key]], escaped column names, Excel's spacing flags), from the workbook's tables, indexed when the workbook part is read. A reference to a table that can't be read, a deleted table or another workbook keeps the cell's saved result. Closes #1251. --- crates/xlsx/README.md | 21 +- crates/xlsx/src/package.rs | 59 ++- crates/xlsx/src/xlsb.rs | 24 +- crates/xlsx/src/xlsb/expr.rs | 3 + crates/xlsx/src/xlsb/formula.rs | 98 +++- crates/xlsx/src/xlsb/table.rs | 770 ++++++++++++++++++++++++++++++++ crates/xlsx/tests/xlsb.rs | 266 ++++++++++- 7 files changed, 1228 insertions(+), 13 deletions(-) create mode 100644 crates/xlsx/src/xlsb/table.rs diff --git a/crates/xlsx/README.md b/crates/xlsx/README.md index e03128e81..c99218085 100644 --- a/crates/xlsx/README.md +++ b/crates/xlsx/README.md @@ -91,9 +91,24 @@ the formula, numbers as Excel spells them), with `FormulaKind::Shared` or `FormulaKind::Array` and their ranges, and `BrtCellMeta` as the cell metadata index. Every cell of a shared formula gets its own text, decoded at the cell, since the file keeps the tokens once. A formula whose decoding needs something the reader does not read -keeps only its saved result, with a warning saying why: user defined names, table references, -other workbooks, Python code stored outside the cell, data tables. The XLSB function table -(`xlsb/ftab.rs`) and the expression printer are this crate's own, apart from `craft-xls`'s. +keeps only its saved result, with a warning saying why: user defined names, other workbooks, +Python code stored outside the cell, data tables. + +A binary workbook's tables (`tableN.bin`, listed by the sheet's `BrtListPart`s) read through +`Package::tables` into the same `Table`, as Excel writes the table in `.xlsx`: the calculated and +totals formulas decoded as cell formulas are, an XML map's column properties, and the AutoFilter and +sort state built as the `autoFilter` and `sortState` elements, with numbers in a filter spelled as +Excel writes them there (17 significant digits; Excel writes a few values shorter, such as `0.1`, +which read back the same). A filter column the reader can't spell is left out with a warning (Excel +keeps date-group filters in an extension the reader skips; a custom filter on a Boolean value has no +`.xlsx` spelling Excel has shown), as is a sort by stroke or PinYin order. The revision ids Excel +writes (`xr:uid`) are in alternate-content blocks, which are skipped. A structured reference in a +formula (`PtgList`) is spelled as `.xlsx` has it (`Sales[Val]`, `Sales[[#Headers],[Key]]`, +`Sales[[#This Row],[A]:[B]]`, with Excel's spacing flags), from the table's id, which is +workbook-wide: the workbook's table parts are indexed when its workbook part is read. A reference to +a table that can't be read, to a deleted table or into another workbook keeps the cell's saved +result. The XLSB function table (`xlsb/ftab.rs`) and the expression printer are this crate's own, +apart from `craft-xls`'s. ## Hostile input diff --git a/crates/xlsx/src/package.rs b/crates/xlsx/src/package.rs index 8f2c5efc6..820132836 100644 --- a/crates/xlsx/src/package.rs +++ b/crates/xlsx/src/package.rs @@ -12,7 +12,7 @@ use crate::pivot::{CacheRecord, PivotCacheDefinition, PivotTableDefinition, read use crate::sheet::{Row, RowReader, SheetPart}; use crate::strings::StringItem; use crate::styles::Styles; -use crate::workbook::{SheetEntry, Workbook}; +use crate::workbook::{SheetEntry, SheetKind, Workbook}; use crate::{Error, Limits, Warnings, xlsb}; /// Most bytes of `[Content_Types].xml` read from a binary workbook. @@ -149,7 +149,10 @@ impl<'a> Package<'a> { if self.binary.is_some() { let bytes = self.required(&self.workbook_part.clone())?; let rels = self.workbook_rels()?; - let (wb, links) = xlsb::workbook(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings)?; + let (wb, mut links) = xlsb::workbook(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings)?; + if let Some(links) = links.as_mut() { + self.index_tables(&wb, links)?; + } self.binary_links = Some(links); return Ok(wb); } @@ -296,10 +299,31 @@ impl<'a> Package<'a> { Ok(Some((part, Drawing::read(&root), rels))) } - /// The tables of a worksheet read by [`Package::sheet`], in the order of its `tableParts`, - /// each with its part name. A table part that does not read is skipped with a warning. + /// The tables of a worksheet read by [`Package::sheet`], in the order of its `tableParts` + /// (its `BrtListPart`s in a binary workbook), each with its part name. A table part that does + /// not read is skipped with a warning. pub fn tables(&mut self, sheet: &SheetPart) -> Result, Error> { let mut out = Vec::new(); + if self.binary.is_some() { + let rels = self.opc.rels(&sheet.part)?; + for id in &sheet.features.table_parts { + let Some(rel) = rels.by_id(id).filter(|r| !r.external && r.kind() == "table") else { + self.warn(format!("XLSB: {}: a table part relationship is missing", sheet.part)); + continue; + }; + let part = rel.target.clone(); + let read = self.binary_part(&part, xlsb::TABLE).and_then(|bytes| { + let links = self.binary_links.as_ref().and_then(Option::as_ref); + xlsb::table(&bytes, links, &self.limits, &self.budget, &mut self.warnings) + }); + match read { + Ok(t) => out.push((part, t)), + Err(Error::TooLarge(m)) => return Err(Error::TooLarge(m)), + Err(e) => self.warn(format!("skipped {part}: {e}")), + } + } + return Ok(out); + } for id in &sheet.features.table_parts { let Some(rel) = sheet.rels.by_id(id).filter(|r| !r.external) else { continue }; let part = rel.target.clone(); @@ -392,6 +416,33 @@ impl<'a> Package<'a> { Ok(root.map(|r| craft_drawingml::theme::read_theme(&mut craft_drawingml::part::NoSource, &r))) } + /// A part of a binary workbook, checked against its content type. + fn binary_part(&mut self, part: &str, content_type: &str) -> Result, Error> { + if let Some(types) = &self.binary { + xlsb::check_type(types, part, content_type)?; + } + self.required(part) + } + + /// Indexes the table parts of a binary workbook's worksheets, for the structured references + /// in its formulas. A table part that does not read is left out with a warning: formulas + /// using it keep their saved results. + fn index_tables(&mut self, wb: &Workbook, links: &mut xlsb::Links) -> Result<(), Error> { + for entry in wb.sheets.iter().filter(|e| e.kind == SheetKind::Worksheet) { + let Some(part) = &entry.part else { continue }; + let rels = self.opc.rels(part)?; + for rel in rels.list.iter().filter(|r| r.kind() == "table" && !r.external) { + let read = self.binary_part(&rel.target, xlsb::TABLE).and_then(|bytes| xlsb::index_table(links, &bytes, &self.limits, &self.budget)); + match read { + Ok(()) => {} + Err(Error::TooLarge(m)) => return Err(Error::TooLarge(m)), + Err(e) => self.warn(format!("XLSB: {} could not be read ({e}); formulas using its table keep their saved results", rel.target)), + } + } + } + Ok(()) + } + fn required(&mut self, part: &str) -> Result, Error> { self.opc.read(part)?.ok_or_else(|| Error::Invalid(format!("missing part {part}"))) } diff --git a/crates/xlsx/src/xlsb.rs b/crates/xlsx/src/xlsb.rs index 65aab0eb8..13e687d2c 100644 --- a/crates/xlsx/src/xlsb.rs +++ b/crates/xlsx/src/xlsb.rs @@ -1,11 +1,13 @@ //! Binary workbooks ([MS-XLSB]): the workbook part, shared strings and worksheet cells, from //! their records. Cell formulas are decoded from their tokens ([`formula`]) into the text an //! `.xlsx` file holds; one that can't be keeps only its saved result, with a warning saying why. -//! Styles are not read. A record that does not parse fails the read. +//! Table parts are read in `table`. Styles are not read. A record that does not parse fails +//! the read. mod expr; mod formula; mod ftab; +mod table; use std::collections::HashMap; use std::sync::Arc; @@ -19,6 +21,7 @@ use crate::workbook::{SheetEntry, SheetKind, Workbook}; use crate::{Error, Limits, Warnings}; pub(crate) use formula::Links; use formula::{Book, Mode, Name, Xti}; +pub(crate) use table::{TABLE, index_table, table}; pub(crate) const MAIN: &str = "application/vnd.ms-excel.main"; const BINARY_MAIN: &str = "application/vnd.ms-excel.sheet.binary.macroEnabled.main"; @@ -28,6 +31,8 @@ pub(crate) const STRINGS: &str = "application/vnd.ms-excel.sharedStrings"; const MAX_SHEETS: usize = 1024; /// Most merged ranges in one worksheet. const MAX_MERGES: usize = 100_000; +/// Table parts one worksheet lists at most. +const MAX_TABLE_PARTS: usize = 65_536; /// Defined names (Excel's hidden ones for newer functions included) read at most; past it, the /// workbook's formulas keep their saved results. const MAX_NAMES: usize = 65_536; @@ -172,11 +177,13 @@ struct Records<'a, 'l> { limits: &'l Limits, budget: &'l Budget, blocks: Vec, + /// Future-record and alternate-content blocks skipped so far. + skipped: usize, } impl<'a, 'l> Records<'a, 'l> { fn new(bytes: &'a [u8], limits: &'l Limits, budget: &'l Budget) -> Self { - Self { bytes: Bytes::new(bytes), limits, budget, blocks: vec![] } + Self { bytes: Bytes::new(bytes), limits, budget, blocks: vec![], skipped: 0 } } fn next(&mut self, warnings: &mut Warnings) -> Result, Error> { @@ -219,6 +226,7 @@ impl<'a, 'l> Records<'a, 'l> { return Err(invalid("extension blocks nested too deeply")); } self.blocks.push(id + 1); + self.skipped += 1; warnings.warn("unsupported XLSB future-record and alternate-content blocks were skipped"); } // BrtFRTEnd, BrtACEnd. @@ -886,6 +894,18 @@ pub(crate) fn worksheet( }); col = Some(c); } + // BrtListPart: one of the sheet's tables, by relationship id. + 661 => { + if data { + return Err(invalid("table part inside worksheet data")); + } + let rel = b.text(255)?; + b.finish()?; + if sheet.features.table_parts.len() >= MAX_TABLE_PARTS { + return Err(Error::TooLarge(format!("XLSB exceeds {MAX_TABLE_PARTS} tables on a sheet"))); + } + sheet.features.table_parts.push(rel); + } 176 => { if data { return Err(invalid("merge inside worksheet data")); diff --git a/crates/xlsx/src/xlsb/expr.rs b/crates/xlsx/src/xlsb/expr.rs index 197644a33..96dc8f03a 100644 --- a/crates/xlsx/src/xlsb/expr.rs +++ b/crates/xlsx/src/xlsb/expr.rs @@ -123,6 +123,8 @@ pub(crate) enum Expr { /// Spaces and line breaks typed before and after an expression (`PtgAttrSpace`), which /// `.xlsx` formula text keeps. Spaced(String, Box, String), + /// A structured reference to a table, as written (`Sales[[#Headers],[Key]]`). + Structured(String), Unary(UnOp, Box), Binary(BinOp, Box, Box), Call(String, Vec), @@ -310,6 +312,7 @@ fn write_expr(s: &mut String, e: &Expr) { } None => s.push_str(n), }, + Expr::Structured(t) => s.push_str(t), Expr::Unary(UnOp::Neg, x) => { s.push('-'); write_expr(s, x); diff --git a/crates/xlsx/src/xlsb/formula.rs b/crates/xlsx/src/xlsb/formula.rs index 3a6960b39..7cc820ff8 100644 --- a/crates/xlsx/src/xlsb/formula.rs +++ b/crates/xlsx/src/xlsb/formula.rs @@ -5,10 +5,12 @@ //! ([`super::ftab`]) and its own copies of craft-xls's depth guards and limits. Anything outside the //! token set it knows is reported as unsupported, and the caller keeps the cell's cached value. //! So is a formula that needs something the reader doesn't read: a user's defined name (XLSB -//! names are not read yet) or Python code stored outside the cell. +//! names are not read yet), a table whose part could not be read, or Python code stored outside +//! the cell. Structured references (`PtgList`) are spelled from the tables in [`Links`]. //! //! Names keep their file spelling (`_xlfn.CONCAT`, `_xlpm.x`), as `.xlsx` formula text has them. +use std::collections::HashMap; use std::sync::Arc; use craft_sheet::{CellError, CellRef, MAX_COLS, MAX_ROWS}; @@ -154,6 +156,15 @@ pub(crate) struct Links { pub(super) names: Vec, pub(super) books: Vec, pub(super) xti: Vec, + /// Every table by its `idList`, which `PtgList` names: `None` for an id two tables share. + pub(super) tables: HashMap>, +} + +/// A table as structured references need it: its display name and its columns' names. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct ListInfo { + pub name: String, + pub columns: Vec, } /// Whether a name stands for a LET parameter (`_xlpm.x`), which only the formula itself defines. @@ -530,7 +541,13 @@ pub(super) fn decode(rgce: &[u8], rgcb: &[u8], links: &Links, mode: Mode) -> Res } 0x01 => return Err(Unsupported("the shared or array formula form")), 0x02 => return Err(Unsupported("what-if data tables")), - 0x18 => return Err(Unsupported("structured table references")), + 0x18 => { + if t.u8()? != 0x19 { + return Err(Unsupported("unknown formula token")); + } + let text = list(&mut t, links)?; + push(&mut stack, kids, Expr::Structured(text))?; + } 0x2C => { let Mode::Shared(_) = mode else { return Err(Unsupported("relative references in a cell formula")) }; let (r, c) = (t.u32()?, t.u16()?); @@ -570,6 +587,83 @@ fn bare_function(name: String) -> String { } } +/// `PtgList` ([MS-XLSB] 2.5.98.52), after its two token bytes: a structured reference, spelled +/// as `.xlsx` has it (`Sales[Val]`, `Sales[[#Headers],[Key]]`, `Sales[[#This Row],[A]:[B]]`). +/// The two spacing flags put a space inside the outer brackets and after each comma, as Excel +/// shows the reference. +fn list(t: &mut Bytes<'_>, links: &Links) -> Result { + let ixti = t.u16()?; + let bits = t.u16()?; + let index = t.u32()?; + let (first, last) = (usize::from(t.u16()?), usize::from(t.u16()?)); + if bits & 0x3000 != 0 { + return Err(Unsupported("structured references to deleted tables or to tables in other workbooks")); + } + // The table's sheet link: a table is always in this workbook, on one of its sheets. + links.sheet_sel(ixti)?; + let table = links.tables.get(&index).and_then(Option::as_ref).ok_or(Unsupported("structured references to tables the reader could not read"))?; + let rows: &[&str] = match (bits >> 2) & 0x1F { + 0x00 => &[], + 0x01 => &["#All"], + 0x02 => &["#Headers"], + 0x04 => &["#Data"], + 0x06 => &["#Headers", "#Data"], + 0x08 => &["#Totals"], + 0x0C => &["#Data", "#Totals"], + 0x10 => &["#This Row"], + _ => return Err(Unsupported("unknown structured reference rows")), + }; + let column = |i: usize| table.columns.get(i).map(|c| escape_column(c)).ok_or(Unsupported("structured reference to a missing table column")); + let columns = match bits & 3 { + 0 => None, + 1 => Some((column(first)?, None)), + 2 if first <= last => Some((column(first)?, Some(column(last)?))), + _ => return Err(Unsupported("invalid structured reference columns")), + }; + let mut s = table.name.clone(); + match (rows, &columns) { + ([], None) => s.push_str("[]"), + ([], Some((c, None))) => { + s.push('['); + s.push_str(c); + s.push(']'); + } + ([row], None) => { + s.push('['); + s.push_str(row); + s.push(']'); + } + _ => { + let mut items: Vec = rows.iter().map(|r| format!("[{r}]")).collect(); + match &columns { + Some((a, Some(b))) => items.push(format!("[{a}]:[{b}]")), + Some((a, None)) => items.push(format!("[{a}]")), + None => {} + } + let pad = if bits & 0x80 != 0 { " " } else { "" }; + let comma = if bits & 0x100 != 0 { ", " } else { "," }; + s.push('['); + s.push_str(pad); + s.push_str(&items.join(comma)); + s.push_str(pad); + s.push(']'); + } + } + Ok(s) +} + +/// A column name in a structured reference: `'` escapes `[`, `]`, `#` and `'` (`It''s '['#1']`). +fn escape_column(name: &str) -> String { + let mut s = String::with_capacity(name.len()); + for c in name.chars() { + if matches!(c, '[' | ']' | '#' | '\'') { + s.push('\''); + } + s.push(c); + } + s +} + /// Text written out in the formula: a string, or strings joined with `&` (how Python code /// longer than a string constant is written). fn literal_text(e: &Expr) -> bool { diff --git a/crates/xlsx/src/xlsb/table.rs b/crates/xlsx/src/xlsb/table.rs new file mode 100644 index 000000000..71e8f3d92 --- /dev/null +++ b/crates/xlsx/src/xlsb/table.rs @@ -0,0 +1,770 @@ +//! Table parts ([MS-XLSB] 2.1.7.51, `tableN.bin`) into the [`Table`] a `.xlsx` table part reads +//! as. The table's AutoFilter and sort state are held as `.xlsx` elements, so they are built here +//! as Excel writes them. A filter column the reader can't spell is left out with a warning, as +//! is a sort state; the table keeps the rest. + +use craft_sheet::{CellRef, MAX_COLS, MAX_ROWS, Range}; +use craft_xml::El; + +use super::formula::{self, ListInfo, Mode}; +use super::{Budget, Bytes, Links, Records, expr, invalid}; +use crate::features::{Table, TableColumn, TableStyleInfo}; +use crate::{Error, Limits, Warnings}; + +/// The content type of a table part. +pub(crate) const TABLE: &str = "application/vnd.ms-excel.table"; + +/// `RfX` / `UncheckedRfX` ([MS-XLSB] 2.5.118, 2.5.154): first and last row, first and last column. +fn rfx(b: &mut Bytes<'_>) -> Result { + let (r0, r1, c0, c1) = (b.u32()?, b.u32()?, b.u32()?, b.u32()?); + if r0 > r1 || c0 > c1 || r1 >= MAX_ROWS || c1 >= MAX_COLS { + return Err(invalid("invalid table range")); + } + Ok(Range::new(CellRef::new(r0, c0), CellRef::new(r1, c1))) +} + +/// A `DXFId`, `None` for 0xFFFFFFFF (no differential format). +fn dxf(id: u32) -> Option { + (id != u32::MAX).then_some(id) +} + +/// An `XLNullableWideString` of at most `max` characters, with the empty string as none: Excel +/// writes an empty comment where `.xlsx` has no attribute. +fn text(b: &mut Bytes<'_>, max: u32) -> Result, Error> { + Ok(b.string(max, true)?.filter(|s| !s.is_empty())) +} + +/// What a table part holds of formulas, for the reader's index of tables: its id, display name +/// and column names. +fn list_info(bytes: &[u8], limits: &Limits, budget: &Budget) -> Result<(u32, ListInfo), Error> { + let t = table(bytes, None, limits, budget, &mut Warnings::default())?; + let id = t.id.ok_or_else(|| invalid("table without an id"))?; + let name = t.display_name.or(t.name).ok_or_else(|| invalid("table without a name"))?; + // A column without a name can't be spelled in a structured reference. + let columns = t + .columns + .into_iter() + .map(|c| c.name.filter(|n| !n.is_empty())) + .collect::>() + .ok_or_else(|| invalid("table column without a name"))?; + Ok((id, ListInfo { name, columns })) +} + +/// Adds a table part to `links`, so formulas can name it. Two tables with one id name neither. +pub(crate) fn index_table(links: &mut Links, bytes: &[u8], limits: &Limits, budget: &Budget) -> Result<(), Error> { + let (id, info) = list_info(bytes, limits, budget)?; + links.tables.entry(id).and_modify(|t| *t = None).or_insert(Some(info)); + Ok(()) +} + +/// A table part. `links` decodes its calculated-column and totals-row formulas; without them +/// (or when one can't be decoded) a formula is left out, with a warning. +pub(crate) fn table(bytes: &[u8], links: Option<&Links>, limits: &Limits, budget: &Budget, warnings: &mut Warnings) -> Result { + let mut records = Records::new(bytes, limits, budget); + let mut table = match records.next(warnings)? { + Some((343, payload)) => begin_list(payload)?, + _ => return Err(invalid("missing table begin record")), + }; + let mut cols_open = false; + let mut cols_seen = false; + let mut column: Option = None; + while let Some((id, payload)) = records.next(warnings)? { + let mut b = Bytes::new(payload); + match id { + 161 if !cols_seen && table.auto_filter.is_none() => { + let range = rfx(&mut b)?; + b.finish()?; + table.auto_filter = Some(auto_filter(range, &mut records, warnings)?); + } + 530 if !cols_seen && table.sort_state.is_none() => table.sort_state = sort_state(payload, &mut records, warnings)?, + 345 if !cols_seen => { + b.u32()?; + b.finish()?; + cols_open = true; + cols_seen = true; + } + 346 if cols_open && column.is_none() => { + b.finish()?; + cols_open = false; + } + 347 if cols_open && column.is_none() => { + if table.columns.len() >= MAX_COLS as usize { + return Err(invalid("too many table columns")); + } + column = Some(begin_list_col(payload)?); + } + 351 | 352 if column.is_some() => { + let f = list_formula(payload, links, limits, budget, warnings)?; + if let Some(c) = column.as_mut() { + *(if id == 351 { &mut c.calculated_formula } else { &mut c.totals_row_formula }) = f; + } + } + 348 => { + b.finish()?; + table.columns.push(column.take().ok_or_else(|| invalid("table column end without a column"))?); + } + 349 => { + let c = column.as_mut().ok_or_else(|| invalid("XML column properties outside a table column"))?; + c.other.push(xml_column(payload)?); + } + 513 if !cols_open && cols_seen => { + let flags = b.u16()?; + let name = b.string(255, true)?; + b.finish()?; + let bit = |n: u16| Some(flags & (1 << n) != 0); + table.style = Some(TableStyleInfo { + name, + show_first_column: bit(0), + show_last_column: bit(1), + show_row_stripes: bit(2), + show_column_stripes: bit(3), + ..TableStyleInfo::default() + }); + } + 344 => { + if cols_open || !cols_seen || column.is_some() { + return Err(invalid("incomplete table")); + } + records.end(payload, warnings)?; + return Ok(table); + } + // The end of an XML map's column; anything else out of place is damage. + 350 => b.finish()?, + _ => return Err(invalid(format!("unexpected record {id} in a table"))), + } + } + Err(invalid("missing table end record")) +} + +/// `BrtBeginList` ([MS-XLSB] 2.4.100). `.xlsx` leaves out what is the default: one header row, +/// no totals row, a totals row that has been shown, a worksheet table. +fn begin_list(payload: &[u8]) -> Result { + let mut b = Bytes::new(payload); + let range = rfx(&mut b)?; + let table_type = match b.u32()? { + 0 => None, + 2 => Some("xml".to_string()), + 3 => Some("queryTable".to_string()), + _ => return Err(invalid("invalid table type")), + }; + let id = b.u32()?; + if id == 0 || id == u32::MAX { + return Err(invalid("invalid table id")); + } + let header = b.u32()?; + let totals = b.u32()?; + let flags = b.u32()?; + // fSingleCell: a single-cell table belongs in its own part type, not here. + if flags & 2 != 0 { + return Err(invalid("single-cell table in a table part")); + } + let dxfs: Vec> = (0..6).map(|_| b.u32().map(dxf)).collect::>()?; + let connection = b.u32()?; + let name = b.string(255, true)?; + let display_name = b.string(255, true)?; + let comment = text(&mut b, 255)?; + let header_row_cell_style = b.string(255, true)?; + let data_cell_style = b.string(255, true)?; + let totals_row_cell_style = b.string(255, true)?; + b.finish()?; + let set = |bit: u32| (flags & bit != 0).then_some(true); + Ok(Table { + id: Some(id), + name, + display_name, + comment, + table_type, + header_row_count: (header != 1).then_some(header), + insert_row: set(4), + insert_row_shift: set(8), + totals_row_count: (totals != 0).then_some(totals), + totals_row_shown: (flags & 1 == 0).then_some(false), + published: set(16), + header_row_dxf_id: dxfs[0], + data_dxf_id: dxfs[1], + totals_row_dxf_id: dxfs[2], + table_border_dxf_id: dxfs[3], + header_row_border_dxf_id: dxfs[4], + totals_row_border_dxf_id: dxfs[5], + header_row_cell_style, + data_cell_style, + totals_row_cell_style, + connection_id: (connection != 0).then_some(connection), + range, + ..Table::default() + }) +} + +/// `BrtBeginListCol` ([MS-XLSB] 2.4.101): `stName` is `.xlsx`'s `uniqueName`, `stCaption` its +/// `name`, and the insert row's format and style are the data's. +fn begin_list_col(payload: &[u8]) -> Result { + let mut b = Bytes::new(payload); + let id = b.u32()?; + let function = match b.u32()? { + 0 => None, + 1 => Some("average"), + 2 => Some("count"), + 3 => Some("countNums"), + 4 => Some("max"), + 5 => Some("min"), + 6 => Some("sum"), + 7 => Some("stdDev"), + 8 => Some("var"), + 9 => Some("custom"), + _ => return Err(invalid("invalid totals row function")), + }; + let header_row_dxf_id = dxf(b.u32()?); + let data_dxf_id = dxf(b.u32()?); + let totals_row_dxf_id = dxf(b.u32()?); + let query = b.u32()?; + let unique_name = b.string(255, true)?; + let name = b.string(255, true)?; + let totals_row_label = b.string(8189, true)?; + let header_row_cell_style = b.string(255, true)?; + let data_cell_style = b.string(255, true)?; + let totals_row_cell_style = b.string(255, true)?; + b.finish()?; + Ok(TableColumn { + id: Some(id), + unique_name, + name, + totals_row_function: function.map(str::to_string), + totals_row_label, + query_table_field_id: (query != 0).then_some(query), + header_row_dxf_id, + data_dxf_id, + totals_row_dxf_id, + header_row_cell_style, + data_cell_style, + totals_row_cell_style, + ..TableColumn::default() + }) +} + +/// `XmlDataType` ([MS-XLSB] 2.5.170) from 1, as `.xlsx` names the XML Schema types. +const XML_TYPES: [&str; 45] = [ + "string", + "normalizedString", + "token", + "byte", + "unsignedByte", + "base64Binary", + "hexBinary", + "integer", + "positiveInteger", + "negativeInteger", + "nonPositiveInteger", + "nonNegativeInteger", + "int", + "unsignedInt", + "long", + "unsignedLong", + "short", + "unsignedShort", + "decimal", + "float", + "double", + "boolean", + "time", + "dateTime", + "duration", + "date", + "gMonth", + "gYear", + "gYearMonth", + "gDay", + "gMonthDay", + "Name", + "QName", + "NCName", + "anyURI", + "language", + "ID", + "IDREF", + "IDREFS", + "ENTITY", + "ENTITIES", + "NOTATION", + "NMTOKEN", + "NMTOKENS", + "anyType", +]; + +/// `BrtBeginListXmlCPr` ([MS-XLSB] 2.4.104): a column's place in an XML map, as `xmlColumnPr`. +/// `fCanBeSingle` (one node for every row) is `.xlsx`'s `denormalized`. +fn xml_column(payload: &[u8]) -> Result { + let mut b = Bytes::new(payload); + let map = b.u32()?; + let flags = b.u32()?; + let kind = b.u32()?; + let xpath = b.text(31_999)?; + b.finish()?; + let kind = kind.checked_sub(1).and_then(|k| XML_TYPES.get(k as usize)).ok_or_else(|| invalid("invalid XML data type"))?; + let mut el = El::new("xmlColumnPr").with_attr("mapId", map).with_attr("xpath", xpath); + if flags & 2 != 0 { + el.set_attr("denormalized", 1); + } + el.set_attr("xmlDataType", kind); + Ok(el) +} + +/// `BrtListCCFmla` / `BrtListTrFmla` ([MS-XLSB] 2.4.706, 2.4.708): a flag byte (`fArray`, bit 1) +/// and a `ListParsedFormula`. Its references hold coordinates, as a cell formula's do. +fn list_formula( + payload: &[u8], + links: Option<&Links>, + limits: &Limits, + budget: &Budget, + warnings: &mut Warnings, +) -> Result, Error> { + let mut b = Bytes::new(payload); + let array = b.u8()? & 2 != 0; + let cce = b.u32()?; + if !(1..=16384).contains(&cce) { + return Err(invalid("invalid formula token length")); + } + let rgce = b.take(cce as usize)?; + let cb = b.u32()?; + let rgcb = b.take(cb as usize)?; + b.finish()?; + let Some(links) = links else { return Ok(None) }; + let text = match formula::decode(rgce, rgcb, links, Mode::Cell) { + Ok(e) => expr::print(&e), + Err(formula::Unsupported(why)) => { + warnings.warn(format!("XLSB: some table column formulas were left out ({why})")); + return Ok(None); + } + }; + if !budget.try_formula_text(text.len(), limits) { + warnings.warn("XLSB: some table column formulas were left out (more formula text than the limits allow)"); + return Ok(None); + } + Ok(Some((text, array))) +} + +/// A number in a filter, as Excel writes it in `.xlsx`, which differs from a formula's: 17 +/// significant digits (`1234.5678901234501`, `1.0000000000000001E-5`), written out from 0.01 up to +/// 10^16 unless that takes more than 17 decimals, and otherwise with an exponent of no fixed +/// width (`1E-4`, `1E+20`). Excel writes a few values with fewer digits (`0.1`, not +/// `0.10000000000000001`); both read back as the same number. +fn filter_number(n: f64) -> String { + if n == 0.0 || !n.is_finite() { + return "0".into(); + } + let sci = format!("{:.16e}", n.abs()); + let Some((mantissa, exp)) = sci.split_once('e') else { return sci }; + let e: i32 = exp.parse().unwrap_or(0); + let digits = mantissa.replace('.', ""); + let digits = digits.trim_end_matches('0'); + let digits = if digits.is_empty() { "0" } else { digits }; + let decimals = i32::try_from(digits.len()).unwrap_or(i32::MAX).saturating_sub(1).saturating_sub(e); + let mut s = String::from(if n < 0.0 { "-" } else { "" }); + if !(-2..=15).contains(&e) || decimals > 17 { + s.push_str(&digits[..1]); + if digits.len() > 1 { + s.push('.'); + s.push_str(&digits[1..]); + } + s.push_str(&format!("E{}{}", if e < 0 { '-' } else { '+' }, e.unsigned_abs())); + } else if e >= 0 { + let whole = e as usize + 1; + if digits.len() <= whole { + s.push_str(digits); + s.push_str(&"0".repeat(whole - digits.len())); + } else { + s.push_str(&digits[..whole]); + s.push('.'); + s.push_str(&digits[whole..]); + } + } else { + s.push_str("0."); + s.push_str(&"0".repeat((-e - 1) as usize)); + s.push_str(digits); + } + s +} + +/// Warns that a table's filter column was left out, and why. +fn left_out(warnings: &mut Warnings, why: &str) { + warnings.warn(format!("XLSB: some table filters were left out ({why})")); +} + +/// The records after `BrtBeginAFilter` ([MS-XLSB] 2.4.8) up to `BrtEndAFilter`, as `autoFilter`. +fn auto_filter(range: Range, records: &mut Records<'_, '_>, warnings: &mut Warnings) -> Result { + let mut el = El::new("autoFilter").with_attr("ref", range.a1()); + while let Some((id, payload)) = records.next(warnings)? { + match id { + 163 => { + if let Some(c) = filter_column(payload, records, warnings)? { + el.push(c); + } + } + 162 => { + Bytes::new(payload).finish()?; + return Ok(el); + } + _ => return Err(invalid(format!("unexpected record {id} in a table filter"))), + } + } + Err(invalid("missing table filter end record")) +} + +/// A `BrtBeginFilterColumn` ([MS-XLSB] 2.4.84) and its criteria, up to `BrtEndFilterColumn`, as +/// `filterColumn`. `None` when its criteria can't be spelled as `.xlsx` has them, or are kept +/// in an extension the reader skips (Excel's date-group filters). +fn filter_column(payload: &[u8], records: &mut Records<'_, '_>, warnings: &mut Warnings) -> Result, Error> { + let mut b = Bytes::new(payload); + let col = b.u32()?; + let flags = b.u16()?; + b.finish()?; + let mut el = El::new("filterColumn").with_attr("colId", col); + if flags & 1 != 0 { + el.set_attr("hiddenButton", 1); + } + if flags & 2 != 0 { + el.set_attr("showButton", 0); + } + let skipped = records.skipped; + let mut keep = true; + while let Some((id, payload)) = records.next(warnings)? { + let mut b = Bytes::new(payload); + match id { + 165 => { + let blank = b.u32()?; + b.u32()?; + b.finish()?; + let mut filters = El::new("filters"); + if blank == 1 { + filters.set_attr("blank", 1); + } + loop { + let (id, payload) = records.next(warnings)?.ok_or_else(|| invalid("missing filter list end record"))?; + let mut b = Bytes::new(payload); + match id { + 167 => { + let val = b.text(255)?; + b.finish()?; + filters.push(El::new("filter").with_attr("val", val)); + } + 175 => filters.push(date_group_item(payload)?), + 166 => { + b.finish()?; + break; + } + _ => return Err(invalid(format!("unexpected record {id} in a filter list"))), + } + } + el.push(filters); + } + 172 => { + let and = b.u32()?; + b.finish()?; + // Excel writes 1 where `.xlsx` has `and="1"` ([MS-XLSB]'s table has them the other way round). + let mut custom = El::new("customFilters"); + if and == 1 { + custom.set_attr("and", 1); + } + loop { + let (id, payload) = records.next(warnings)?.ok_or_else(|| invalid("missing custom filter end record"))?; + match id { + 174 => match custom_filter(payload)? { + Some(f) => custom.push(f), + None => { + left_out(warnings, "custom filters on a Boolean value"); + keep = false; + } + }, + 173 => { + Bytes::new(payload).finish()?; + break; + } + _ => return Err(invalid(format!("unexpected record {id} in custom filters"))), + } + } + el.push(custom); + } + 170 => { + let flags = b.u8()?; + let val = b.f64()?; + let filter_val = b.f64()?; + b.finish()?; + let mut top = El::new("top10"); + if flags & 1 == 0 { + top.set_attr("top", 0); + } + if flags & 2 != 0 { + top.set_attr("percent", 1); + } + top.set_attr("val", filter_number(val)); + if flags & 4 != 0 { + top.set_attr("filterVal", filter_number(filter_val)); + } + el.push(top); + } + 171 => el.push(dynamic_filter(payload)?), + 168 => { + let dxf_id = b.u32()?; + let cell = b.u32()?; + b.finish()?; + let mut color = El::new("colorFilter").with_attr("dxfId", dxf_id); + if cell == 0 { + color.set_attr("cellColor", 0); + } + el.push(color); + } + 169 => { + let set = b.u32()?; + let icon = b.u32()?; + b.finish()?; + // KPINIL: no filter. + if set != u32::MAX { + let name = ICON_SETS.get(set as usize).ok_or_else(|| invalid("invalid filter icon set"))?; + el.push(El::new("iconFilter").with_attr("iconSet", name).with_attr("iconId", icon)); + } + } + 164 => { + b.finish()?; + if records.skipped != skipped { + left_out(warnings, "filters kept in extensions the reader skips, such as date groups"); + return Ok(None); + } + return Ok(keep.then_some(el)); + } + _ => return Err(invalid(format!("unexpected record {id} in a filter column"))), + } + } + Err(invalid("missing filter column end record")) +} + +/// `KPISets` ([MS-XLSB] 2.5.86), as `.xlsx` names them. +const ICON_SETS: [&str; 17] = [ + "3Arrows", + "3ArrowsGray", + "3Flags", + "3TrafficLights1", + "3TrafficLights2", + "3Signs", + "3Symbols", + "3Symbols2", + "4Arrows", + "4ArrowsGray", + "4RedToBlack", + "4Rating", + "4TrafficLights", + "5Arrows", + "5ArrowsGray", + "5Rating", + "5Quarters", +]; + +/// `BrtCustomFilter` ([MS-XLSB] 2.4.348) as `customFilter`; `None` for a Boolean value, whose +/// `.xlsx` spelling no Excel file has shown. A blank or non-blank test is `val=" "`, as Excel +/// writes it. +fn custom_filter(payload: &[u8]) -> Result, Error> { + let mut b = Bytes::new(payload); + let vts = b.u8()?; + let operator = match b.u8()? { + 1 => Some("lessThan"), + 2 => None, + 3 => Some("lessThanOrEqual"), + 4 => Some("greaterThan"), + 5 => Some("notEqual"), + 6 => Some("greaterThanOrEqual"), + _ => return Err(invalid("invalid custom filter operator")), + }; + let union = b.take(8)?; + let val = match vts { + 4 => { + let n = f64::from_le_bytes(union.try_into().map_err(|_| invalid("truncated number"))?); + if !n.is_finite() { + return Err(invalid("nonfinite numeric value")); + } + filter_number(n) + } + 6 => b.text(255)?, + 8 => return Ok(None), + 0x0C | 0x0E => " ".to_string(), + _ => return Err(invalid("invalid custom filter type")), + }; + b.finish()?; + let mut el = El::new("customFilter"); + if let Some(op) = operator { + el.set_attr("operator", op); + } + el.set_attr("val", val); + Ok(Some(el)) +} + +/// `BrtDynamicFilter` ([MS-XLSB] 2.4.362) as `dynamicFilter`: the computed values only once the +/// filter has been applied, and the maximum only for date periods. +fn dynamic_filter(payload: &[u8]) -> Result { + let mut b = Bytes::new(payload); + let cft = b.u32()?; + let applied = b.u8()? & 1 != 0; + let val = b.f64()?; + let max = b.f64()?; + b.finish()?; + const PERIODS: [&str; 16] = [ + "tomorrow", + "today", + "yesterday", + "nextWeek", + "thisWeek", + "lastWeek", + "nextMonth", + "thisMonth", + "lastMonth", + "nextQuarter", + "thisQuarter", + "lastQuarter", + "nextYear", + "thisYear", + "lastYear", + "yearToDate", + ]; + let kind = match cft { + 0 => "null".to_string(), + 1 => "aboveAverage".to_string(), + 2 => "belowAverage".to_string(), + 8..=0x17 => PERIODS[(cft - 8) as usize].to_string(), + 0x18..=0x1B => format!("Q{}", cft - 0x17), + 0x1C..=0x27 => format!("M{}", cft - 0x1B), + _ => return Err(invalid("invalid dynamic filter type")), + }; + let mut el = El::new("dynamicFilter").with_attr("type", kind); + if applied && (1..=0x17).contains(&cft) { + el.set_attr("val", filter_number(val)); + if cft >= 8 { + el.set_attr("maxVal", filter_number(max)); + } + } + Ok(el) +} + +/// `BrtAFilterDateGroupItem` ([MS-XLSB] 2.4.5) as `dateGroupItem`, with the parts of the date +/// its grouping compares. +fn date_group_item(payload: &[u8]) -> Result { + let mut b = Bytes::new(payload); + let year = b.u16()?; + let month = b.u16()?; + let day = b.u32()?; + let (hour, minute, second) = (b.u16()?, b.u16()?, b.u16()?); + b.take(6)?; + let grouping = b.u32()?; + b.finish()?; + const GROUPS: [&str; 6] = ["year", "month", "day", "hour", "minute", "second"]; + let name = GROUPS.get(grouping as usize).ok_or_else(|| invalid("invalid date group"))?; + let mut el = El::new("dateGroupItem").with_attr("year", year); + let parts = [("month", u32::from(month)), ("day", day), ("hour", u32::from(hour)), ("minute", u32::from(minute)), ("second", u32::from(second))]; + for (name, value) in parts.iter().take(grouping as usize) { + el.set_attr(name, value); + } + el.set_attr("dateTimeGrouping", name); + Ok(el) +} + +/// `BrtBeginSortState` ([MS-XLSB] 2.4.227) and its `BrtBeginSortCond`s, up to `BrtEndSortState`, +/// as `sortState`. `None`, with a warning, for a sort by another method than character order, +/// which `.xlsx` names (stroke or PinYin) and the record does not. +fn sort_state(payload: &[u8], records: &mut Records<'_, '_>, warnings: &mut Warnings) -> Result, Error> { + let mut b = Bytes::new(payload); + let flags = b.u16()?; + let range = rfx(&mut b)?; + b.finish()?; + let mut el = El::new("sortState"); + if flags & 1 != 0 { + el.set_attr("columnSort", 1); + } + if flags & 2 != 0 { + el.set_attr("caseSensitive", 1); + } + el.set_attr("ref", range.a1()); + let keep = flags & 4 == 0; + if !keep { + warnings.warn("XLSB: some table sort states were left out (sorts by stroke or PinYin order)"); + } + while let Some((id, payload)) = records.next(warnings)? { + let mut b = Bytes::new(payload); + match id { + 532 => { + let flags = b.u16()?; + let range = rfx(&mut b)?; + let (first, second) = (b.u32()?, b.u32()?); + let list = b.string(32_767, true)?; + b.finish()?; + let mut cond = El::new("sortCondition"); + if flags & 1 != 0 { + cond.set_attr("descending", 1); + } + let on = (flags >> 1) & 0xF; + match on { + 0 => {} + 1 => cond.set_attr("sortBy", "cellColor"), + 2 => cond.set_attr("sortBy", "fontColor"), + 3 => cond.set_attr("sortBy", "icon"), + _ => return Err(invalid("invalid sort condition")), + } + cond.set_attr("ref", range.a1()); + match on { + 0 => { + if let Some(list) = list { + cond.set_attr("customList", list); + } + } + 1 | 2 => cond.set_attr("dxfId", first), + _ => { + let name = ICON_SETS.get(first as usize).ok_or_else(|| invalid("invalid sort icon set"))?; + cond.set_attr("iconSet", name); + cond.set_attr("iconId", second); + } + } + el.push(cond); + } + 533 => b.finish()?, + 531 => { + b.finish()?; + return Ok(keep.then_some(el)); + } + _ => return Err(invalid(format!("unexpected record {id} in a sort state"))), + } + } + Err(invalid("missing sort state end record")) +} + +#[cfg(test)] +mod tests { + use super::filter_number; + + #[test] + fn filter_numbers_are_spelled_as_excel_writes_them() { + // Excel's `.xlsx` text for each value. + let cases = [ + (20.0, "20"), + (23.25, "23.25"), + (46340.0, "46340"), + (-1.5, "-1.5"), + (1e15, "1000000000000000"), + (999_999_999_999_999.0, "999999999999999"), + (1.234_567_890_123_45e17, "1.2345678901234499E+17"), + (1e16, "1E+16"), + (-1e16, "-1E+16"), + (1e20, "1E+20"), + (2.5e300, "2.5000000000000001E+300"), + (1_234.567_890_123_45, "1234.5678901234501"), + (12_345_678_901_234.5, "12345678901234.5"), + (99_999_999_999_999.9, "99999999999999.906"), + (1.1, "1.1000000000000001"), + (0.57, "0.56999999999999995"), + (0.01, "0.01"), + (0.035, "3.5000000000000003E-2"), + (0.001, "1E-3"), + (1e-4, "1E-4"), + (1e-5, "1.0000000000000001E-5"), + (1.5e-10, "1.5E-10"), + (1e-19, "9.9999999999999998E-20"), + ]; + for (n, want) in cases { + assert_eq!(filter_number(n), want, "{n}"); + } + } +} diff --git a/crates/xlsx/tests/xlsb.rs b/crates/xlsx/tests/xlsb.rs index 950dc8847..3a0228275 100644 --- a/crates/xlsx/tests/xlsb.rs +++ b/crates/xlsx/tests/xlsb.rs @@ -5,7 +5,7 @@ mod common; use common::{read, read_with}; use craft_xlsx::testing::zip; -use craft_xlsx::{CellError, CellRef, Error, FormulaKind, Limits, Range, SheetKind, Value, Visibility, is_xlsb}; +use craft_xlsx::{CellError, CellRef, Error, FormulaKind, Limits, Package, Range, SheetKind, Table, Value, Visibility, is_xlsb}; const ROOT: &str = r#""#; const RELS: &str = r#""#; @@ -584,7 +584,7 @@ fn cell_formulas_are_read_in_their_xlsx_spelling() { assert_eq!(sheet.cell_metadata.iter().collect::>(), [(&CellRef::new(0, 14), &1)]); // Every formula cell keeps its saved result as its value. assert!((1..=15).all(|c| sheet.value(CellRef::new(0, c)) == Value::Number(0.0))); - for why in ["defined names", "other workbooks", "missing from the file", "structured table references"] { + for why in ["defined names", "other workbooks", "missing from the file", "tables the reader could not read"] { assert!(warned(&wb, why), "{why}: {:?}", wb.warnings); } } @@ -1035,3 +1035,265 @@ fn references_to_macro_sheets_and_spans_over_chart_sheets_are_named() { assert_eq!(got, [Some("Macro1!$A$1"), Some("Data:Hidden!$A$1"), None]); assert!(warned(&wb, "references to sheets with no cells"), "{:?}", wb.warnings); } + +// Tables ([MS-XLSB] 2.1.7.51): table parts assembled from the specification's records, and the +// `` Excel writes for the same table in `.xlsx`. + +fn rfx(r0: u32, r1: u32, c0: u32, c1: u32) -> Vec { + [r0, r1, c0, c1].iter().flat_map(|n| n.to_le_bytes()).collect() +} +/// `BrtBeginList`: a worksheet table with no formats or cell styles, its name as its display name. +fn begin_list(range: &[u8], id: u32, header: u32, totals: u32, flags: u32, name: &str) -> Vec { + begin_list_of(0, range, id, header, totals, flags, name) +} +/// `BrtBeginList` of a table type (`lt`): 0 a worksheet table, 2 an XML table. +fn begin_list_of(lt: u32, range: &[u8], id: u32, header: u32, totals: u32, flags: u32, name: &str) -> Vec { + let mut data = range.to_vec(); + for n in [lt, id, header, totals, flags] { + data.extend(n.to_le_bytes()); + } + data.extend(u32::MAX.to_le_bytes().repeat(6)); + data.extend(0u32.to_le_bytes()); + data.extend([wide(name), wide(name), wide("")].concat()); + data.extend(u32::MAX.to_le_bytes().repeat(3)); + record(343, &data) +} +/// `BrtBeginListCol` with its totals function (`ilta`), data format and totals label. +fn list_col(id: u32, ilta: u32, data_dxf: u32, name: &str, total: Option<&str>) -> Vec { + let mut data: Vec = [id, ilta, u32::MAX, data_dxf, u32::MAX, 0, u32::MAX].iter().flat_map(|n| n.to_le_bytes()).collect(); + data.extend(wide(name)); + data.extend(total.map_or_else(|| u32::MAX.to_le_bytes().to_vec(), wide)); + data.extend(u32::MAX.to_le_bytes().repeat(3)); + record(347, &data) +} +/// `BrtListCCFmla` (351) or `BrtListTrFmla` (352). +fn list_formula(id: u16, rgce: &[u8]) -> Vec { + record(id, &[&[0u8][..], &(rgce.len() as u32).to_le_bytes(), rgce, &0u32.to_le_bytes()].concat()) +} +/// `PtgList`: the flags hold the columns (bits 0-1), the rows (2-6) and the two spacing bits. +fn ptg_list(ixti: u16, flags: u16, list: u32, first: u16, last: u16) -> Vec { + [&[0x18u8, 0x19][..], &ixti.to_le_bytes(), &flags.to_le_bytes(), &list.to_le_bytes(), &first.to_le_bytes(), &last.to_le_bytes()].concat() +} +fn filter_column(col: u32, flags: u16, criteria: &[Vec]) -> Vec { + [record(163, &[&col.to_le_bytes()[..], &flags.to_le_bytes()].concat()), criteria.concat(), record(164, &[])].concat() +} +fn custom_filter(vts: u8, op: u8, union: [u8; 8], text: Option<&str>) -> Vec { + record(174, &[&[vts, op][..], &union, &text.map(wide).unwrap_or_default()].concat()) +} +fn table_style(flags: u16, name: &str) -> Vec { + record(513, &[&flags.to_le_bytes()[..], &wide(name)].concat()) +} +/// The rows of a `PtgList` (bits 2-6). +const fn rows(t: u16) -> u16 { + t << 2 +} + +/// The filters of Sales: a value list with blanks, two custom criteria (OR), a bottom-percent +/// filter applied with its button hidden, and "today" applied. +fn sales_filters() -> Vec> { + vec![ + filter_column(0, 0, &[record(165, &[1, 0, 0, 0, 0, 0, 0, 0]), record(167, &wide("k3")), record(167, &wide("k4")), record(166, &[])]), + filter_column( + 1, + 0, + &[ + record(172, &0u32.to_le_bytes()), + custom_filter(4, 1, 20f64.to_le_bytes(), None), + custom_filter(6, 2, [0; 8], Some("k*")), + record(173, &[]), + ], + ), + filter_column(2, 1, &[record(170, &[&[0b110u8][..], &10f64.to_le_bytes(), &23.25f64.to_le_bytes()].concat())]), + filter_column(3, 0, &[record(171, &[&9u32.to_le_bytes()[..], &[1], &46340f64.to_le_bytes(), &46341f64.to_le_bytes()].concat())]), + ] +} + +/// Sales (B2:E8, id 1) with a totals row, a calculated column, a column name needing escapes, +/// `filters` and a sort. +fn sales(filters: &[Vec]) -> Vec { + [ + begin_list(&rfx(1, 7, 1, 4), 1, 1, 1, 1, "Sales"), + record(161, &rfx(1, 6, 1, 4)), + filters.concat(), + record(162, &[]), + record(530, &[&0u16.to_le_bytes()[..], &rfx(2, 6, 1, 4)].concat()), + record(532, &[&1u16.to_le_bytes()[..], &rfx(1, 7, 1, 1), &[0; 8], &u32::MAX.to_le_bytes()].concat()), + record(533, &[]), + record(531, &[]), + record(345, &4u32.to_le_bytes()), + list_col(1, 0, u32::MAX, "Key", Some("Total")), + record(348, &[]), + list_col(2, 6, u32::MAX, "Val", None), + record(348, &[]), + list_col(3, 0, 2, "It's [#1]", None), + record(348, &[]), + list_col(4, 9, u32::MAX, "Calc", None), + list_formula(351, &[ptg_list(0, 1 | rows(0x10), 1, 1, 1), vec![0x1E, 2, 0, 0x05]].concat()), + list_formula(352, &[ptg_list(0, 1, 1, 3, 3), vec![0x42, 1, 7, 0]].concat()), + record(348, &[]), + record(346, &[]), + table_style(0b101, "TableStyleMedium9"), + record(344, &[]), + ] + .concat() +} + +/// NoHead (H10:I11, id 2): no header row, a totals row never shown, no stripes. +fn no_head() -> Vec { + [ + begin_list(&rfx(9, 10, 7, 8), 2, 0, 0, 0, "NoHead"), + record(345, &2u32.to_le_bytes()), + list_col(1, 0, u32::MAX, "Column1", None), + record(348, &[]), + list_col(2, 0, u32::MAX, "Column2", None), + record(348, &[]), + record(346, &[]), + table_style(0, "TableStyleMedium2"), + record(344, &[]), + ] + .concat() +} + +/// XmlT (K1:L2, id 3): an XML table, its columns mapped to an XML map's elements. +fn xml_table_part() -> Vec { + let col = |id: u32, name: &str, kind: u32, xpath: &str| { + let mut data: Vec = [id, 0, u32::MAX, u32::MAX, u32::MAX, 0].iter().flat_map(|n| n.to_le_bytes()).collect(); + data.extend([wide(name), wide(name)].concat()); + data.extend(u32::MAX.to_le_bytes().repeat(4)); + let map = [&1u32.to_le_bytes()[..], &(if id == 2 { 2u32 } else { 0 }).to_le_bytes(), &kind.to_le_bytes(), &wide(xpath)].concat(); + [record(347, &data), record(349, &map), record(350, &[]), record(348, &[])].concat() + }; + [ + begin_list_of(2, &rfx(0, 1, 10, 11), 3, 1, 0, 0, "XmlT"), + record(345, &2u32.to_le_bytes()), + col(1, "a", 0x0D, "/rows/r/a"), + col(2, "b", 0x01, "/rows/@b"), + record(346, &[]), + table_style(0b100, "TableStyleMedium2"), + record(344, &[]), + ] + .concat() +} + +const XML_TABLE_XML: &str = r#"
"#; +const SALES_XML: &str = r#"Sales[[#This Row],[Val]]*2MAX(Sales[Calc])
"#; +const NO_HEAD_XML: &str = r#"
"#; + +fn xml_table(xml: &str) -> Table { + let root = craft_xml::Options::canonical(&craft_xlsx::ns::CANONICAL).parse(xml.as_bytes()).unwrap(); + Table::read(&root).unwrap() +} + +/// `book_with_links(&xti())` whose sheet one lists `tables` (`BrtListPart`, relationship ids +/// t1, t2, ...) after `data`. +fn book_with_tables(data: &[u8], tables: &[Vec]) -> Vec { + let mut list = vec![record(660, &(tables.len() as u32).to_le_bytes())]; + let mut rels = String::from(r#""#); + let mut types = TYPES.trim_end_matches("").to_string(); + for i in 1..=tables.len() { + list.push(record(661, &wide(&format!("t{i}")))); + rels.push_str(&format!(r#""#)); + types.push_str(&format!(r#""#)); + } + list.push(record(662, &[])); + rels.push_str(""); + types.push_str(""); + let names: Vec = (1..=tables.len()).map(|i| format!("tables/t{i}.bin")).collect(); + let (book, one, two, strings) = (book_with_links(&xti()), worksheet(data, &list.concat()), worksheet(&[], &[]), sst()); + let mut entries: Vec<(&str, &[u8])> = vec![ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", ROOT.as_bytes()), + ("records/book.bin", &book), + ("records/_rels/book.bin.rels", RELS.as_bytes()), + ("data/one.bin", &one), + ("data/_rels/one.bin.rels", rels.as_bytes()), + ("data/two.bin", &two), + ("text/strings.bin", &strings), + ]; + entries.extend(names.iter().map(String::as_str).zip(tables.iter().map(Vec::as_slice))); + zip(&entries) +} + +/// Sheet one's tables through `Package`, and its warnings. +fn tables_of(bytes: &[u8]) -> (Vec, Vec) { + let mut p = Package::open(bytes, &Limits::default()).unwrap(); + let wb = p.workbook().unwrap(); + let part = p.sheet(&wb.sheets[0], |_| Ok(())).unwrap(); + let tables = p.tables(&part).unwrap().into_iter().map(|(_, t)| t).collect(); + (tables, p.warnings().to_vec()) +} + +#[test] +fn tables_are_read_as_their_xlsx_spelling() { + // Spacing flags: 0x80 inside the outer brackets, 0x100 after commas. + let cells: Vec> = vec![ + ptg_list(0, 1, 1, 1, 1), + ptg_list(0, 1 | rows(2), 1, 0, 0), + ptg_list(0, 2 | rows(4), 1, 1, 3), + ptg_list(0, rows(1), 1, 0, 0), + ptg_list(0, 0, 1, 0, 0), + ptg_list(0, 2 | rows(0x10), 1, 1, 3), + ptg_list(0, 1, 1, 2, 2), + ptg_list(0, 1 | rows(4) | 0x180, 1, 1, 1), + ptg_list(0, rows(0x10), 2, 0, 0), + ptg_list(0, 1 | rows(0xC) | 0x100, 1, 0, 0), + ptg_list(0, rows(6), 1, 0, 0), + // Kept as their saved results: a table that isn't there, a deleted table, a column past + // the table's last. + ptg_list(0, 0, 9, 0, 0), + ptg_list(0, 0x1000, 1, 0, 0), + ptg_list(0, 1, 1, 4, 4), + ]; + let mut data = row(0); + for (i, rgce) in cells.iter().enumerate() { + data.extend(formula_cell(i as u32 + 1, rgce, &[])); + } + let bytes = book_with_tables(&data, &[sales(&sales_filters()), no_head(), xml_table_part()]); + let (tables, _) = tables_of(&bytes); + assert_eq!(tables, [xml_table(SALES_XML), xml_table(NO_HEAD_XML), xml_table(XML_TABLE_XML)]); + let wb = read(&bytes).unwrap(); + let got: Vec<_> = (1..=14).map(|c| wb.sheets[0].formula(CellRef::new(0, c))).collect(); + let want = [ + Some("Sales[Val]"), + Some("Sales[[#Headers],[Key]]"), + Some("Sales[[#Data],[Val]:[Calc]]"), + Some("Sales[#All]"), + Some("Sales[]"), + Some("Sales[[#This Row],[Val]:[Calc]]"), + Some("Sales[It''s '['#1']]"), + Some("Sales[ [#Data], [Val] ]"), + Some("NoHead[#This Row]"), + Some("Sales[[#Data], [#Totals], [Key]]"), + Some("Sales[[#Headers],[#Data]]"), + None, + None, + None, + ]; + assert_eq!(got, want); + for why in ["tables the reader could not read", "deleted tables", "missing table column"] { + assert!(warned(&wb, why), "{why}: {:?}", wb.warnings); + } +} + +#[test] +fn table_filters_and_parts_the_reader_cannot_spell_are_left_out() { + // A filter column whose criteria are in a future-record block (where Excel keeps date + // groups), and one on a Boolean value: both left out, the table kept. + let frt = [record(35, &[3, 0, 2, 0]), record(5094, &[0; 32]), record(36, &[])].concat(); + let mut filters = sales_filters(); + filters.push(filter_column(4, 0, &[frt])); + filters.push(filter_column(5, 0, &[record(172, &0u32.to_le_bytes()), custom_filter(8, 2, [1, 0, 0, 0, 0, 0, 0, 0], None), record(173, &[])])); + // A truncated table part: skipped, and formulas using it keep their saved results. + let mut broken = no_head(); + broken.truncate(20); + let data = [row(0), formula_cell(1, &ptg_list(0, 0, 2, 0, 0), &[]), formula_cell(2, &ptg_list(0, 1, 1, 1, 1), &[])].concat(); + let bytes = book_with_tables(&data, &[sales(&filters), broken]); + let (tables, warnings) = tables_of(&bytes); + assert_eq!(tables, [xml_table(SALES_XML)]); + for why in ["filters kept in extensions", "custom filters on a Boolean value", "skipped tables/t2.bin"] { + assert!(warnings.iter().any(|w| w.contains(why)), "{why}: {warnings:?}"); + } + let wb = read(&bytes).unwrap(); + assert_eq!([1, 2].map(|c| wb.sheets[0].formula(CellRef::new(0, c))), [None, Some("Sales[Val]")]); + assert!(warned(&wb, "tables the reader could not read"), "{:?}", wb.warnings); +} From 3bd1794251a5cfdc72c99e2fa9d63c28ab827ba7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 13:24:04 +0100 Subject: [PATCH 03/57] DWG: keep field formats when saving an older drawing as DWG 2007 or later acadrust reads a pre-2007 DXF FIELD's format only into Field::format, but its DWG writer writes that for versions before 2007 only and value.format from 2007 on. Copy it over before writing. Co-Authored-By: Claude Sonnet 5.5 --- crates/dwg/src/lib.rs | 57 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 05c1a673c..216ed49a0 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -703,6 +703,23 @@ 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. + fn field_formats(doc: &mut acadrust::CadDocument) { + 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, @@ -1238,6 +1255,7 @@ mod native { }; other_layout_owners(&mut doc); table_style_rows(&mut doc, true); + field_formats(&mut doc); dimension_flags(&mut doc); let mut unwritten = drop_unwritable(&mut doc); for (kind, n) in proxies { @@ -2103,4 +2121,43 @@ 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"]); + } } From 0dba1ed64ebe764ffea4a97d801d65a9e708431e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 15:03:42 +0100 Subject: [PATCH 04/57] DWG: keep a field's format when the DXF is read as a newer kept version dxf_to_dwg_kept_as declares the kept version before reading, and acadrust 0.6.6 reads a FIELD's group 4 format only below AC1021, so an older drawing's own field lost its format. Collect the group 4 formats by handle before reading and put them back into an empty Field::format; field_formats then copies them into value.format for 2007+. Carried-over fields keep their own value.format. Co-Authored-By: Claude Opus 5.5 --- crates/dwg/src/lib.rs | 150 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 140 insertions(+), 10 deletions(-) diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 216ed49a0..2d173b325 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -708,7 +708,19 @@ mod native { /// 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. - fn field_formats(doc: &mut acadrust::CadDocument) { + /// + /// `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; } @@ -920,8 +932,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) } @@ -987,6 +1000,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 @@ -1215,19 +1257,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(|r| r.read())) .map_err(|_| "the DXF→DWG conversion failed".to_string())? .map_err(|e| format!("DXF: {e}"))?; @@ -1255,7 +1301,7 @@ mod native { }; other_layout_owners(&mut doc); table_style_rows(&mut doc, true); - field_formats(&mut doc); + field_formats(&mut doc, &legacy); dimension_flags(&mut doc); let mut unwritten = drop_unwritable(&mut doc); for (kind, n) in proxies { @@ -2160,4 +2206,88 @@ mod tests { 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}"); + } + } + } + } } From 6fde933469b8e86fc9d6d0f034fc7b680bb819d0 Mon Sep 17 00:00:00 2001 From: Diego Guerini Date: Sun, 15 Nov 2026 18:01:57 +0100 Subject: [PATCH 05/57] craft-docx: read a DrawingML locked canvas as a group of its members Word 2007 writes shapes, pictures and WordArt in a drawing as an lc:lockedCanvas (ECMA-376 Part 1 20.3.2.1) in compatibility mode. Only its first picture was read; its shapes and their text were dropped. The canvas is now rewritten as the wpg group the reader already handles, its DrawingML text as text-box paragraphs with their run formatting. Moved from storytold/wordcraft#5067 (wordcraft#5060), whose DOCX reader now lives here. --- crates/docx/src/read/story.rs | 1 + crates/docx/src/read/story/drawing.rs | 4 + crates/docx/src/read/story/locked_canvas.rs | 254 ++++++++++++++++++++ crates/docx/src/xml.rs | 4 +- crates/docx/tests/it/locked_canvas.rs | 143 +++++++++++ crates/docx/tests/it/main.rs | 1 + 6 files changed, 406 insertions(+), 1 deletion(-) create mode 100644 crates/docx/src/read/story/locked_canvas.rs create mode 100644 crates/docx/tests/it/locked_canvas.rs 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/drawing.rs b/crates/docx/src/read/story/drawing.rs index cb1152da8..0b7f7e78a 100644 --- a/crates/docx/src/read/story/drawing.rs +++ b/crates/docx/src/read/story/drawing.rs @@ -82,6 +82,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 { 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..01e8f2872 --- /dev/null +++ b/crates/docx/src/read/story/locked_canvas.rs @@ -0,0 +1,254 @@ +//! 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 run's properties default to its paragraph's own (`a:pPr/a:defRPr`), then to the + // list style's for the paragraph's level (`lvl`, 0–8), property by property. + 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 level_style = body.child("a:lstStyle").and_then(|l| l.child(&format!("a:lvl{}pPr", level + 1))); + let defaults: Vec<&El> = + [ppr_el.and_then(|pp| pp.child("a:defRPr")), level_style.and_then(|l| l.child("a:defRPr"))].into_iter().flatten().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 ppr_el.and_then(|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))); + let on = |n: &str| get(n).is_some_and(|v| v == "1" || v == "true"); + 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); + } + if on("b") { + push("w:b", &[]); + } + if on("i") { + push("w:i", &[]); + } + 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/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/locked_canvas.rs b/crates/docx/tests/it/locked_canvas.rs new file mode 100644 index 000000000..8fa7a0a20 --- /dev/null +++ b/crates/docx/tests/it/locked_canvas.rs @@ -0,0 +1,143 @@ +//! 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"); + } +} + +/// 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 b0bab5833..7d706e3d8 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -23,6 +23,7 @@ mod heading_levels; mod legacy_forms; mod ligatures; mod line_numbering; +mod locked_canvas; mod malformed; mod missing_pictures; mod nested_block_controls; From 88c52213b45509b3f1c7aec43029592b2af2acd7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 18:38:29 +0100 Subject: [PATCH 06/57] craft-drawingml: keep theme sysClr, custClrLst, theme family id, font panose and a:defPPr on save Co-Authored-By: Claude Sonnet 5.5 --- crates/drawingml/src/part.rs | 80 +++++++++++++++++++++++++++++ crates/drawingml/src/read.rs | 5 ++ crates/drawingml/src/text.rs | 6 ++- crates/drawingml/src/theme.rs | 45 +++++++++++++++- crates/drawingml/src/theme/read.rs | 16 ++++-- crates/drawingml/src/theme/write.rs | 22 ++++++-- crates/drawingml/src/write.rs | 4 ++ 7 files changed, 167 insertions(+), 11 deletions(-) diff --git a/crates/drawingml/src/part.rs b/crates/drawingml/src/part.rs index 27215f85d..c3e530dd8 100644 --- a/crates/drawingml/src/part.rs +++ b/crates/drawingml/src/part.rs @@ -239,4 +239,84 @@ mod tests { assert_eq!(back.extra.len(), MAX_EXTRA_COLORS); assert_eq!(back.extra[0].tints.as_deref(), Some(&long[..MAX_TINT_ROWS])); } + + const THEME_FILE: &str = r#" + + + + + +"#; + + 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 list_styles_keep_def_ppr_in_every_place_they_are_written() { + use crate::text::{ListStyle, TextBody}; + let src = r#""#; + 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(Default::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..012c20552 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(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..8fe0244e1 100644 --- a/crates/drawingml/src/text.rs +++ b/crates/drawingml/src/text.rs @@ -706,6 +706,10 @@ 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`. + #[serde(skip_serializing_if = "Option::is_none")] + pub default_level: Option, } impl ListStyle { @@ -722,7 +726,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) } } diff --git a/crates/drawingml/src/theme.rs b/crates/drawingml/src/theme.rs index 69d7c2af6..9b663b86e 100644 --- a/crates/drawingml/src/theme.rs +++ b/crates/drawingml/src/theme.rs @@ -11,11 +11,35 @@ 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 { + /// 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 +77,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 +95,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 +118,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..24b882b3a 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 { 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..98a87f3a2 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,17 @@ 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| { + 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 +82,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); From a2d2eefa3cf5d53410575784824ace6abbf0a0b7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 18:40:20 +0100 Subject: [PATCH 07/57] craft-drawingml: drop theme font panose when the typeface changes; more theme tests Co-Authored-By: Claude Sonnet 5.5 --- crates/drawingml/src/part.rs | 32 +++++++++++++++++++++++++++++ crates/drawingml/src/theme.rs | 2 ++ crates/drawingml/src/theme/read.rs | 2 +- crates/drawingml/src/theme/write.rs | 3 +++ 4 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/drawingml/src/part.rs b/crates/drawingml/src/part.rs index c3e530dd8..37d99481d 100644 --- a/crates/drawingml/src/part.rs +++ b/crates/drawingml/src/part.rs @@ -286,6 +286,38 @@ mod tests { 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(", pub pitch_family: Option, diff --git a/crates/drawingml/src/theme/read.rs b/crates/drawingml/src/theme/read.rs index 24b882b3a..0f4e4b2f0 100644 --- a/crates/drawingml/src/theme/read.rs +++ b/crates/drawingml/src/theme/read.rs @@ -24,7 +24,7 @@ fn font_set(e: Option<&El>) -> FontSet { 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 { panose: at("panose"), pitch_family: at("pitchFamily"), charset: at("charset") } + 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 } } diff --git a/crates/drawingml/src/theme/write.rs b/crates/drawingml/src/theme/write.rs index 98a87f3a2..bc46d59e3 100644 --- a/crates/drawingml/src/theme/write.rs +++ b/crates/drawingml/src/theme/write.rs @@ -13,6 +13,9 @@ use crate::write as dml; fn font_set(w: &mut Writer, tag: &str, f: &FontSet) { w.open(tag, &[]); 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()) From d88b7542c4709fb0b3d98604e1a50bbc7cdf9948 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 18:43:13 +0100 Subject: [PATCH 08/57] craft-drawingml: format theme tests Co-Authored-By: Claude Sonnet 5.5 --- crates/drawingml/src/part.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/drawingml/src/part.rs b/crates/drawingml/src/part.rs index 37d99481d..a251d4f3c 100644 --- a/crates/drawingml/src/part.rs +++ b/crates/drawingml/src/part.rs @@ -263,12 +263,21 @@ mod tests { 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("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"); + 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("") < 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!( + (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(); From 92fb3fa8ac2981c4c31961cfce7f7fdfbb03540d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:27:00 -0800 Subject: [PATCH 09/57] craft-texture: add per-axis wrapping and MaterialCraft's stored sampling MaterialCraft's `crates/image` gained per-axis wrap modes and the texture read of its function graphs. This adds them to craft-texture so the app can switch to the crate. - `get_axes`, `sample_axes` and `sample_nearest_axes` take `tiling: [bool; 2]`, the wrap mode of `u` and of `v` on their own. With equal entries they give the same results as `get`, `sample` and `sample_nearest`, which now call them. - `sample_stored` rounds the bilinear weights to multiples of 1/256 and blends by linear interpolation in `f32`. With the image's integer-sampling flag on, it 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, so finite texels give a finite sample. - `with_integer_sampling` and `integer_sampling` set and read the flag. New images start with it off, clones keep it, and `PartialEq` compares it. --- crates/texture/README.md | 16 +- crates/texture/src/lib.rs | 367 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 368 insertions(+), 15 deletions(-) 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 2aaef3e8b..04bc292f5 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 @@ -130,15 +134,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 } } @@ -187,6 +194,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; @@ -209,7 +223,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. @@ -219,7 +233,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`. @@ -272,7 +286,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 { @@ -308,7 +336,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 => { @@ -339,7 +374,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; @@ -356,12 +399,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] @@ -373,18 +416,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 @@ -892,4 +990,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}"); + } + } } From 2632c41eb4d4a0d07eda816b7a17eb436a791954 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 20:47:25 +0100 Subject: [PATCH 10/57] craft-drawingml: box ListStyle::default_level to keep ListStyle small Co-Authored-By: Claude Sonnet 5.5 --- crates/drawingml/src/part.rs | 2 +- crates/drawingml/src/read.rs | 2 +- crates/drawingml/src/text.rs | 14 ++++++++++++-- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/drawingml/src/part.rs b/crates/drawingml/src/part.rs index a251d4f3c..af2f6b736 100644 --- a/crates/drawingml/src/part.rs +++ b/crates/drawingml/src/part.rs @@ -354,7 +354,7 @@ mod tests { let xml = format!(r#"{}"#, 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(Default::default()), ..Default::default() }; + 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); diff --git a/crates/drawingml/src/read.rs b/crates/drawingml/src/read.rs index 012c20552..f26bf2073 100644 --- a/crates/drawingml/src/read.rs +++ b/crates/drawingml/src/read.rs @@ -625,7 +625,7 @@ pub fn list_style(src: &mut dyn Source, ls: &El) -> ListStyle { let n = e.local(); if n == "defPPr" { let (_, para, run) = ppr(src, e); - out.default_level = Some(LevelStyle { para, run: run.unwrap_or_default() }); + 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 }; diff --git a/crates/drawingml/src/text.rs b/crates/drawingml/src/text.rs index 8fe0244e1..135d070f9 100644 --- a/crates/drawingml/src/text.rs +++ b/crates/drawingml/src/text.rs @@ -707,9 +707,11 @@ 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`. + /// 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, + pub default_level: Option>, } impl ListStyle { @@ -763,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 small (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::() <= 64, "{}", std::mem::size_of::()); + } + #[test] fn alternate_language_inherits_and_native_input_is_bounded() { let mut child = RunProps::default(); From d5b4dbef8827b7a5ef9c00f113ee2457359a9a14 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 20:51:33 +0100 Subject: [PATCH 11/57] craft-drawingml: tighten ListStyle size guard, add deep group stack test Co-Authored-By: Claude Sonnet 5.5 --- crates/drawingml/src/text.rs | 6 +++--- crates/pptx/tests/read.rs | 39 +++++++++++++++++++++++++++++++----- 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/crates/drawingml/src/text.rs b/crates/drawingml/src/text.rs index 135d070f9..dc34cf10f 100644 --- a/crates/drawingml/src/text.rs +++ b/crates/drawingml/src/text.rs @@ -766,11 +766,11 @@ mod tests { 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 small (the `defPPr` level is boxed) so a debug build - /// does not overflow the 1 MiB Windows main-thread stack. + /// 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::() <= 64, "{}", std::mem::size_of::()); + assert!(std::mem::size_of::() <= 32, "{}", std::mem::size_of::()); } #[test] 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(); +} From e7627d396c3ee4c10dd9ba0da6e6d4860c1959e8 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 22:03:46 +0100 Subject: [PATCH 12/57] craft-drawingml: keep the default namespace on kept fragments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A part written with a default namespace (``, a slide with `xmlns="…/presentationml/2006/main"`) has unprefixed names. `keep_with` copied only prefixed declarations, so a kept fragment (theme custClrLst, extLst, objectDefaults, effect 3-D, slide/layout/master extLst) lost its namespace when written under a root that binds no default. A kept fragment now gets the part root's `xmlns` when one of its unprefixed names is not bound inside it; prefixed fragments are written as before. Co-Authored-By: Claude Opus 5.5 --- crates/drawingml/src/xmlx.rs | 50 +++++++++++++++++-- crates/pptx/tests/write.rs | 96 ++++++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 3 deletions(-) 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/pptx/tests/write.rs b/crates/pptx/tests/write.rs index bec5fb239..b6315375a 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,100 @@ 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}"); +} + +/// 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 pptx = craft_pptx::export(&deck(), &Plain).unwrap(); + let ext = r#""#; + let doc = common::rewrite( + &pptx, + |name, data| { + if name != "ppt/slides/slide1.xml" { + return Some(data.to_vec()); + } + let xml = String::from_utf8(data.to_vec()).unwrap(); + assert!(xml.contains("") && !xml.contains("extLst"), "{xml}"); + Some(xml.replacen("", &format!("{ext}")).into_bytes()) + }, + &[], + ); + let p = craft_pptx::import(&doc, &Plain).unwrap(); + let xml = part(&craft_pptx::export(&p, &Plain).unwrap(), "ppt/slides/slide1.xml"); + assert!(xml.contains("{11111111-2222-3333-4444-555555555555}"), "{xml}"); + assert_eq!(namespaces_of(&xml, "ext"), [NS_P], "{xml}"); + assert_eq!(namespaces_of(&xml, "data"), ["urn:test"], "{xml}"); +} + #[test] fn templates_and_shows_differ_in_the_main_content_type() { let p = deck(); From 3b02f3ee6c9b3d7ce3bddbfd87c4a1436278fa4f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 22:11:54 +0100 Subject: [PATCH 13/57] craft-pptx: test kept 3-D and layout/master extensions in default-namespace parts Extends the default-namespace theme test with an effect style holding scene3d and sp3d, and adds a layout and master case whose unprefixed extLst/ext is written back through ext_children. To be precise about the previous commit: theme effect styles and shape spPr 3-D kept from a part with a default namespace now keep that namespace. Text bodyPr and group spPr 3-D without a prefix are still dropped on save, as before (valid_raw3d requires the a: prefix); that is out of scope here. Co-Authored-By: Claude Opus 5.5 --- crates/pptx/tests/write.rs | 49 +++++++++++++++++++++++++++++--------- 1 file changed, 38 insertions(+), 11 deletions(-) diff --git a/crates/pptx/tests/write.rs b/crates/pptx/tests/write.rs index b6315375a..46f7513e7 100644 --- a/crates/pptx/tests/write.rs +++ b/crates/pptx/tests/write.rs @@ -220,7 +220,7 @@ fn namespaces_of(xml: &str, local: &str) -> Vec { } /// A theme with a custom colour list and a theme family id, with the `a:` prefix. -const PREFIXED_THEME: &str = r#""#; +const PREFIXED_THEME: &str = r#""#; /// The deck with its theme part replaced by `theme`. fn with_theme(theme: &str) -> Vec { @@ -244,6 +244,9 @@ fn a_default_namespace_theme_keeps_its_kept_parts_in_the_drawingml_namespace() { assert!(!ns.is_empty() && ns.iter().all(|n| n == NS_A), "{local}: {ns:?}\n{xml}"); } assert_eq!(namespaces_of(&xml, "themeFamily"), [NS_THM15], "{xml}"); + // The effect style's 3-D is kept as written too. + assert_eq!(namespaces_of(&xml, "scene3d"), [NS_A], "{xml}"); + assert_eq!(namespaces_of(&xml, "sp3d"), [NS_A], "{xml}"); // The second save writes the same kept parts. let kept = |x: &str| x[x.find("").expect("themeElements")..].to_string(); let twice = craft_pptx::export(&craft_pptx::import(&once, &Plain).unwrap(), &Plain).unwrap(); @@ -264,31 +267,55 @@ fn a_prefixed_theme_keeps_its_kept_parts_unchanged() { assert!(xml.contains(&kept), "{xml}"); } -/// 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() { +/// 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, - |name, data| { - if name != "ppt/slides/slide1.xml" { + |n, data| { + if n != name { return Some(data.to_vec()); } let xml = String::from_utf8(data.to_vec()).unwrap(); - assert!(xml.contains("") && !xml.contains("extLst"), "{xml}"); - Some(xml.replacen("", &format!("{ext}")).into_bytes()) + 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(); - let xml = part(&craft_pptx::export(&p, &Plain).unwrap(), "ppt/slides/slide1.xml"); + 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!(namespaces_of(&xml, "ext"), [NS_P], "{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(); From e70cceae3377e0fadf12ea3c35030da73a5091f2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 23:23:49 +0100 Subject: [PATCH 14/57] DDS: pin the writer's and reader's output as SHA-256 digests Digests of uncompressed, BC1, BC2 and BC3 textures, with and without mip chains, from deterministic odd-sized pictures (ramps, noise, flat tiles, alpha at 0, 255 and in between) in RGBA, RGB, gray with alpha and gray, and of decoding those files and hand-built ones in the other stored layouts. The table is filled from the unchanged code; on a mismatch the test prints every digest it computed. --- crates/image-codecs/tests/it/dds_oracle.rs | 520 +++++++++++++++++++++ crates/image-codecs/tests/it/main.rs | 1 + 2 files changed, 521 insertions(+) create mode 100644 crates/image-codecs/tests/it/dds_oracle.rs 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/main.rs b/crates/image-codecs/tests/it/main.rs index 4eda74a26..78762de5f 100644 --- a/crates/image-codecs/tests/it/main.rs +++ b/crates/image-codecs/tests/it/main.rs @@ -3,6 +3,7 @@ mod camera_raw; mod common; mod dds; +mod dds_oracle; mod dds_write; mod decode_warnings; mod deep_exr; From a98aa0b46218e24c5272b89b72e1226077b93b5a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 23:28:54 +0100 Subject: [PATCH 15/57] Move the DDS reader and writer into a craft-dds crate without dependencies craft-dds holds the header parsing, the uncompressed and BC1-BC3 readers and writers and the block encoder, with its own pixel layout and error types and rayon behind a `parallel` feature. It parses the header first (Texture::parse) so a caller can check the size against its limits before anything is allocated. craft-image-codecs reads and writes DDS through it, re-exports its DdsCompression and DdsOptions and maps its errors onto CodecError with the same messages, so its API and output stay the same. Apps that only need DDS can depend on craft-dds without the other codecs and their licences. --- Cargo.lock | 8 + Cargo.toml | 1 + README.md | 5 + crates/dds/Cargo.toml | 19 + crates/dds/README.md | 43 + .../src/codecs/dds_bc.rs => dds/src/bc.rs} | 0 crates/dds/src/lib.rs | 755 ++++++++++++++++++ crates/image-codecs/Cargo.toml | 3 + crates/image-codecs/README.md | 5 +- crates/image-codecs/src/codecs.rs | 1 - crates/image-codecs/src/codecs/dds.rs | 572 +------------ crates/image-codecs/src/options.rs | 56 +- 12 files changed, 875 insertions(+), 593 deletions(-) create mode 100644 crates/dds/Cargo.toml create mode 100644 crates/dds/README.md rename crates/{image-codecs/src/codecs/dds_bc.rs => dds/src/bc.rs} (100%) create mode 100644 crates/dds/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 7ed516463..406340734 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1480,6 +1480,13 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-dds" +version = "0.1.0" +dependencies = [ + "rayon", +] + [[package]] name = "craft-deckcraft-format" version = "0.1.0" @@ -1925,6 +1932,7 @@ name = "craft-image-codecs" version = "0.1.0" dependencies = [ "avif-serialize", + "craft-dds", "craft-heif", "craft-jpeg", "craft-media-testkit", diff --git a/Cargo.toml b/Cargo.toml index 48a2edf1d..4d31e635d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -132,6 +132,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 0b4b9a415..af98f90e7 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,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 and BC1 to BC3 (DXT1/3/5) 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 diff --git a/crates/dds/Cargo.toml b/crates/dds/Cargo.toml new file mode 100644 index 000000000..e3cee5696 --- /dev/null +++ b/crates/dds/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-dds" +description = "DirectDraw Surface (DDS) textures: uncompressed and BC1-BC3 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 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..465975ff2 --- /dev/null +++ b/crates/dds/README.md @@ -0,0 +1,43 @@ +# 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) | BC1, BC2, BC3 | +| Headers | legacy and DX10 | legacy | +| Mip levels | the top level only | optional full chain, box-filtered | + +Cubemaps, texture arrays, volume textures, premultiplied DXT2/DXT4 and the other DXGI formats +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`). Block compressions are written from RGBA. + +```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()?; +``` + +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 picks whichever alpha mode fits. + +## Features + +- `parallel`: encodes 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 100% rename from crates/image-codecs/src/codecs/dds_bc.rs rename to crates/dds/src/bc.rs diff --git a/crates/dds/src/lib.rs b/crates/dds/src/lib.rs new file mode 100644 index 000000000..a98a08631 --- /dev/null +++ b/crates/dds/src/lib.rs @@ -0,0 +1,755 @@ +//! 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. +//! +//! 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 rows of blocks 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), +} + +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"), + } + } +} + +impl std::error::Error for DdsError {} + +/// 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, +} + +/// `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, +} + +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, + _ => Layout::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), 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 => { + 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)"))), + } +} + +/// 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) }; + 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`]. + pub fn decode(&self) -> 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 data = b.get(self.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 = 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"))?; + 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); + } + } + } + } + } + } + Ok(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 = 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 = 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 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, +} + +impl Store { + /// The storage for pixels of `layout`. Block compressions take RGBA 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, + (_, 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)) +} + +/// A DDS file of `width` × `height` `pixels` in `layout`, interleaved and top row first. +/// Block compressions take [`Layout::Rgba`] pixels; uncompressed textures take every layout. +pub fn encode(width: u32, height: u32, layout: Layout, pixels: &[u8], options: DdsOptions) -> Result, DdsError> { + 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 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 = alloc_zeroed(total)?; + out.get_mut(..HEADER).ok_or_else(|| encode_err("output buffer too small"))?.copy_from_slice(&header); + + let channels = 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], DdsError> { + 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()); + } + }; + // 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 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; + } + } + }); + } + } + 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, 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 }; + 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) +} + +#[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_rgba_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()))); + } + + #[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/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 208ff3ce7..ef8d7b76e 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -20,6 +20,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"] } @@ -43,6 +44,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 a0e1afaa4..27ddddb69 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 | no | 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–BC3, 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` | @@ -92,7 +92,8 @@ 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 +* **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) 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 diff --git a/crates/image-codecs/src/codecs.rs b/crates/image-codecs/src/codecs.rs index 00b94b7ec..f647809af 100644 --- a/crates/image-codecs/src/codecs.rs +++ b/crates/image-codecs/src/codecs.rs @@ -2,7 +2,6 @@ pub(crate) mod avif; #[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))] pub(crate) mod avif_decode; 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..9d682b03f 100644 --- a/crates/image-codecs/src/codecs/dds.rs +++ b/crates/image-codecs/src/codecs/dds.rs @@ -1,557 +1,57 @@ -//! 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")), + 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)) + +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().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/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`]). From e22ccf3511d57115feaf5aa156d1118864f87537 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 23:32:31 +0100 Subject: [PATCH 16/57] DDS: encode and decode faster with the same bytes Encoding: - colour blocks keep their colours and endpoint candidates on the stack instead of in per-block vectors (the idea of storytold/photocraft#10669) - a refinement round whose endpoint pair was already fitted ends the search, which could not change the block any more - a block of one colour skips the principal-axis search, whose result for it is that colour at both ends - the alpha block gathers its 16 values once, finds both ranges in one pass and picks indices in a plain loop with the same tie-break - the nearest palette colour is found the same way - interior blocks are gathered as four rows of four texels, and interior mip pixels average their 2x2 source pixels directly Decoding: - block-compressed data is decoded one row of blocks per task, copying whole texel rows and checking bounds only on the right edge - uncompressed rows are decoded one per task; when every channel is a whole byte (RGBA, BGRA, BGRX, luminance), pixels are a byte shuffle The f32 arithmetic and its order are unchanged; the digest oracle pins the output. --- crates/dds/Cargo.toml | 2 +- crates/dds/README.md | 2 +- crates/dds/src/bc.rs | 131 ++++++++++++++++++++++++++-------- crates/dds/src/lib.rs | 158 +++++++++++++++++++++++++++++++++--------- 4 files changed, 229 insertions(+), 64 deletions(-) diff --git a/crates/dds/Cargo.toml b/crates/dds/Cargo.toml index e3cee5696..ca40bd69a 100644 --- a/crates/dds/Cargo.toml +++ b/crates/dds/Cargo.toml @@ -12,7 +12,7 @@ workspace = true [features] default = [] -# Encode rows of blocks and mip levels on several threads. +# Encode and decode rows of blocks (and mip levels) on several threads. parallel = ["dep:rayon"] [dependencies] diff --git a/crates/dds/README.md b/crates/dds/README.md index 465975ff2..3871452df 100644 --- a/crates/dds/README.md +++ b/crates/dds/README.md @@ -39,5 +39,5 @@ under half opacity into its transparent black, and BC3 picks whichever alpha mod ## Features -- `parallel`: encodes rows of blocks and mip levels on several threads with rayon. +- `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/dds/src/bc.rs b/crates/dds/src/bc.rs index df60e462c..1641a9e56 100644 --- a/crates/dds/src/bc.rs +++ b/crates/dds/src/bc.rs @@ -69,7 +69,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 +93,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 +154,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 +195,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 { @@ -248,29 +292,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)); +/// An interpolated block of 16 single-channel values (BC3's alpha): 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); } @@ -333,7 +387,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 +412,23 @@ mod tests { assert!(ours < bounding_box, "{ours} vs the bounding box's {bounding_box}"); } + #[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 index a98a08631..079b3e3b5 100644 --- a/crates/dds/src/lib.rs +++ b/crates/dds/src/lib.rs @@ -11,8 +11,8 @@ //! so no DX10 header is written; formats only DXGI can name (BC4–BC7, sRGB) 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 rows of blocks on several threads -//! with rayon. +//! 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}; @@ -385,41 +385,104 @@ impl<'a> Texture<'a> { 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::Masks { bytes, gray, fields } => decode_masks(Masks { bytes, gray, fields }, data, row_pitch, &mut pixels, row_size), + Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 => 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]); } } - 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); - } - } + } 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 = if matches!(encoding, Encoding::Bc1) { 8 } else { 16 }; + 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 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 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()); } } } } - Ok(pixels) - } + }); } /// A BC1 colour block. BC2 and BC3 colour blocks always have four colours; only BC1's @@ -683,6 +746,20 @@ fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst /// 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); @@ -703,9 +780,26 @@ fn downsample(src: &[u8], (w, h): (usize, usize), (nw, nh): (usize, usize), chan 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); - for (x, px) in row.chunks_exact_mut(channels.max(1)).enumerate() { + // 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); From 203f225562114a0e227ba021b481857901e6f08f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 23:32:37 +0100 Subject: [PATCH 17/57] DDS: stop the principal-axis iteration once the axis is a fixed point A power-iteration step that gives back the same axis bit for bit gives it back on every later step, so stopping there keeps the output. Kept only if the timings show a gain. --- crates/dds/src/bc.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/dds/src/bc.rs b/crates/dds/src/bc.rs index 1641a9e56..12bf15179 100644 --- a/crates/dds/src/bc.rs +++ b/crates/dds/src/bc.rs @@ -235,7 +235,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 }; From f31c93cf59a7cc68947fd49f15a7b43d39aa8c53 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 23:38:08 +0100 Subject: [PATCH 18/57] DDS: read and write BC4 and BC5 (grayscale data and normal maps) BC4 is one block of 16 single-channel values and BC5 two of them, the block BC3 already stores its alpha in, so the alpha block encoder and decoder now serve all three (BC3's output stays the same). Reading: ATI1 and BC4U, and DXGI 79 (typeless) and 80, open as gray; ATI2 and BC5U, and DXGI 82 (typeless, as Pillow writes it) and 83, open as RGB with blue 0. ATI2 follows Microsoft's mapping, red in the first block. Signed BC4S/BC5S and DXGI 81/84 are refused, naming SNORM. Writing: DdsCompression::Bc4 (bc4, ati1) from gray and Bc5 (bc5, ati2) from RGB, with the DX10 header (BC4_UNORM, BC5_UNORM, one 2D texture), mip chains included. The encode plan converts other layouts to gray and RGB, so the fidelity warnings report colour to gray and dropped alpha; BC5's dropped blue is documented under LossyCompression. DdsCompression is now #[non_exhaustive] and ALL has six entries. --- README.md | 6 +- crates/dds/Cargo.toml | 2 +- crates/dds/README.md | 19 +- crates/dds/src/bc.rs | 70 +++++-- crates/dds/src/lib.rs | 216 ++++++++++++++++------ crates/image-codecs/README.md | 32 ++-- crates/image-codecs/src/codecs/dds.rs | 2 +- crates/image-codecs/src/fidelity.rs | 13 +- crates/image-codecs/src/format.rs | 2 +- crates/image-codecs/tests/it/dds.rs | 75 +++++++- crates/image-codecs/tests/it/dds_write.rs | 127 ++++++++++++- crates/raster-codecs/README.md | 2 +- crates/raster-codecs/src/lib.rs | 2 +- crates/raster-codecs/tests/dds.rs | 3 +- 14 files changed, 469 insertions(+), 102 deletions(-) diff --git a/README.md b/README.md index af98f90e7..7b0c88ded 100644 --- a/README.md +++ b/README.md @@ -89,8 +89,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit 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 and BC1 to BC3 (DXT1/3/5) textures, legacy and DX10 headers, and - our own block encoder with optional mip chains. No dependencies (rayon behind `parallel`), so an + 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 @@ -245,7 +245,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/dds/Cargo.toml b/crates/dds/Cargo.toml index ca40bd69a..f93e8cbcc 100644 --- a/crates/dds/Cargo.toml +++ b/crates/dds/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-dds" -description = "DirectDraw Surface (DDS) textures: uncompressed and BC1-BC3 block compression, read and write, without dependencies" +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 diff --git a/crates/dds/README.md b/crates/dds/README.md index 3871452df..720ec9ba7 100644 --- a/crates/dds/README.md +++ b/crates/dds/README.md @@ -12,15 +12,20 @@ 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) | BC1, BC2, BC3 | -| Headers | legacy and DX10 | legacy | +| 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 DXT2/DXT4 and the other DXGI formats -are refused with `DdsError::Unsupported` rather than read in part. +Cubemaps, texture arrays, volume textures, premultiplied DXT2/DXT4, 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`). Block compressions are written from RGBA. +`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}; @@ -35,7 +40,9 @@ let decoded = texture.decode()?; 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 picks whichever alpha mode fits. +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 diff --git a/crates/dds/src/bc.rs b/crates/dds/src/bc.rs index 12bf15179..863aa3077 100644 --- a/crates/dds/src/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] { @@ -299,7 +329,7 @@ fn least_squares(block: &Block, opaque: Mask, bytes: &[u8; 8]) -> Option<(u16, u Some((to565(e0), to565(e1))) } -/// An interpolated block of 16 single-channel values (BC3's alpha): whichever of the two modes +/// 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] { @@ -343,13 +373,6 @@ fn value_fit(values: &[u8; 16], 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]] { @@ -419,6 +442,31 @@ 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. diff --git a/crates/dds/src/lib.rs b/crates/dds/src/lib.rs index 079b3e3b5..5c088052a 100644 --- a/crates/dds/src/lib.rs +++ b/crates/dds/src/lib.rs @@ -3,12 +3,16 @@ //! //! 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. +//! (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) 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. +//! 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 @@ -86,8 +90,10 @@ impl fmt::Display for DdsError { impl std::error::Error for DdsError {} -/// How a DDS texture stores its pixels. +/// 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. @@ -100,33 +106,55 @@ pub enum DdsCompression { 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; 4] = [DdsCompression::None, DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3]; + 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` or `bc3`. + /// 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 names (`dxt1`, `dxt3`, - /// `dxt5`), in any case. Anything else is `None`. + /// [`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 @@ -224,6 +252,10 @@ enum Encoding { Bc1, Bc2, Bc3, + /// One value block: gray. + Bc4, + /// Two value blocks: red, then green. + Bc5, } impl Encoding { @@ -247,10 +279,21 @@ impl Encoding { 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"); @@ -267,9 +310,8 @@ impl Encoding { } (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)) + 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)?; @@ -286,8 +328,14 @@ fn legacy_encoding(b: &[u8]) -> Result { 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 and DXT5 are)", fourcc_name(fourcc)))), + _ => Err(unsupported(format!("compression `{}` is not supported (DXT1, DXT3, DXT5, ATI1/BC4U and ATI2/BC5U are)", fourcc_name(fourcc)))), }; } if flags & DDPF_RGB != 0 { @@ -321,7 +369,12 @@ fn dx10_encoding(b: &[u8]) -> Result { 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)"))), + // 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)"))), } } @@ -386,7 +439,9 @@ impl<'a> Texture<'a> { let mut pixels = vec![0u8; 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 => decode_blocks(encoding, data, (w, channels), &mut pixels), + Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc4 | Encoding::Bc5 => { + decode_blocks(encoding, data, (w, channels), &mut pixels) + } } Ok(pixels) } @@ -455,16 +510,19 @@ fn decode_masks(m: Masks, data: &[u8], row_pitch: usize, pixels: &mut [u8], row_ /// 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 = if matches!(encoding, Encoding::Bc1) { 8 } else { 16 }; + 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 => 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)), + 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 @@ -485,29 +543,10 @@ fn decode_blocks(encoding: Encoding, data: &[u8], (width, channels): (usize, usi }); } -/// 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 = 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 = 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]) +/// 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] { @@ -527,6 +566,8 @@ 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()) @@ -554,10 +595,13 @@ enum Store { Bc1, Bc2, Bc3, + Bc4, + Bc5, } impl Store { - /// The storage for pixels of `layout`. Block compressions take RGBA only. + /// 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, @@ -567,6 +611,8 @@ impl Store { (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()))), }) } @@ -577,13 +623,22 @@ impl Store { Store::Luminance => 1, Store::LuminanceAlpha => 2, Store::Bgrx | Store::Bgra => 4, - Store::Bc1 => 8, - Store::Bc2 | Store::Bc3 => 16, + 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) + 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. @@ -606,6 +661,7 @@ impl Store { 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]), } } } @@ -620,7 +676,8 @@ fn half((w, h): (usize, usize)) -> (usize, usize) { } /// A DDS file of `width` × `height` `pixels` in `layout`, interleaved and top row first. -/// Block compressions take [`Layout::Rgba`] pixels; uncompressed textures take every layout. +/// 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> { 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())); @@ -636,14 +693,18 @@ pub fn encode(width: u32, height: u32, layout: Layout, pixels: &[u8], options: D 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 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)?; - out.get_mut(..HEADER).ok_or_else(|| encode_err("output buffer too small"))?.copy_from_slice(&header); + 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, HEADER); + 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)?; @@ -657,9 +718,10 @@ pub fn encode(width: u32, height: u32, layout: Layout, pixels: &[u8], options: D 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], DdsError> { - let mut b = [0u8; HEADER]; +/// 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()); @@ -686,6 +748,12 @@ fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Res 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) } @@ -739,10 +807,40 @@ fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst } }); } + 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]; @@ -831,9 +929,17 @@ mod tests { } #[test] - fn block_compressions_take_rgba_only() { + 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] diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 27ddddb69..1bdf1418d 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 | no | 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) | [`craft-dds`](../dds/README.md) | +| 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` | @@ -94,19 +94,27 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them * **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) 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 + (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 DXT2/DXT4, 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/dds.rs b/crates/image-codecs/src/codecs/dds.rs index 9d682b03f..26a100fab 100644 --- a/crates/image-codecs/src/codecs/dds.rs +++ b/crates/image-codecs/src/codecs/dds.rs @@ -19,7 +19,7 @@ fn error(e: DdsError) -> CodecError { } } -fn channel_layout(layout: Layout) -> ChannelLayout { +pub(crate) fn channel_layout(layout: Layout) -> ChannelLayout { match layout { Layout::Gray => ChannelLayout::Gray, Layout::GrayA => ChannelLayout::GrayA, 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 26696ae2a..4b6ee5bb9 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/tests/it/dds.rs b/crates/image-codecs/tests/it/dds.rs index 4f766a54c..ad927019a 100644 --- a/crates/image-codecs/tests/it/dds.rs +++ b/crates/image-codecs/tests/it/dds.rs @@ -318,10 +318,83 @@ 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]; + +#[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_write.rs b/crates/image-codecs/tests/it/dds_write.rs index f9d9add8e..bc92c87b6 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:?}"); } 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"); } From c27333683a190ddd0aebd9e355b94a4538ba6692 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 23:38:25 +0100 Subject: [PATCH 19/57] DDS: time decoding a 30 MP texture too An ignored test beside the encode timings: the best of five decodes of the same texture written with each compression. It uses only the API the reader had before, so it runs on the old code for comparison. --- crates/image-codecs/tests/it/dds_write.rs | 36 ++++++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/image-codecs/tests/it/dds_write.rs b/crates/image-codecs/tests/it/dds_write.rs index bc92c87b6..af6a2c7d2 100644 --- a/crates/image-codecs/tests/it/dds_write.rs +++ b/crates/image-codecs/tests/it/dds_write.rs @@ -479,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); @@ -490,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); } } From fc808abd499b624f06cd7ff6c1f7ea1c61dad95d Mon Sep 17 00:00:00 2001 From: vangel76 <271991477+vangel76@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:12:22 +0100 Subject: [PATCH 20/57] DOCX: read and write the "gutter at top" setting (w:gutterAtTop) The reader ignored w:gutterAtTop in settings.xml (it was only carried through on save), so an app using the model could not tell that Word adds the gutter to the top margin instead of the left one. Add Settings::gutter_at_top (document-wide, off by default), read it with the shared on/off helper, write it after w:mirrorMargins and before w:attachedTemplate, and make the settings merge treat it as a modelled child so turning it off removes it. Tests: round trip and default off, every on/off spelling, merge into a settings part from another writer (keep, remove, insert in schema order). Co-Authored-By: Claude Sonnet 5.5 --- crates/docx/src/read/meta.rs | 1 + crates/docx/src/write/settings.rs | 4 ++ crates/docx/src/write/settings_merge.rs | 17 +++++ crates/docx/tests/it/roundtrip.rs | 96 +++++++++++++++++++++++++ crates/wordmodel/src/settings.rs | 5 ++ 5 files changed, 123 insertions(+) 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/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..01b7d27c6 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,20 @@ 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}"); + assert!(out.find("") < out.find("") && out.find("") < out.find(""#)); + } } diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 8f3bbdd0b..3ba2f326a 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -2926,3 +2926,99 @@ 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), + ] { + 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(" Date: Mon, 16 Nov 2026 00:17:26 +0100 Subject: [PATCH 21/57] DOCX: make the gutter-at-top tests check the order and False/FALSE The merge unit test compared Options, and its generated part had no w:mirrorMargins, so the order check proved nothing; put the element in and look the positions up. Add the False and FALSE spellings to the value test. Co-Authored-By: Claude Sonnet 5.5 --- crates/docx/src/write/settings_merge.rs | 8 +++++--- crates/docx/tests/it/roundtrip.rs | 7 ++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 01b7d27c6..a72046e83 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -390,16 +390,18 @@ mod tests { #[test] fn gutter_at_top_comes_from_the_generated_part() { - let orig = r#""#; + 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}"); - assert!(out.find("") < out.find("") && out.find("") < out.find("") < at("") && at("") < at(""#)); } diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 3ba2f326a..4bb6cab35 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -2981,6 +2981,8 @@ fn gutter_at_top_reads_every_value_spelling() { (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:?}"); @@ -2997,9 +2999,8 @@ fn gutter_at_top_is_merged_into_a_foreign_settings_part() { let xml = settings_part(&plain); let zoom = r#""#; let foreign = |element: &str| { - let extra = format!( - r#"{zoom}{element}"# - ); + let extra = + format!(r#"{zoom}{element}"#); replace_part(&plain, "word/settings.xml", xml.replace(zoom, &extra).as_bytes()) }; From 39e1d41af7368926a16c979ec2bc61fefea02c64 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 01:34:20 +0100 Subject: [PATCH 22/57] DDS: refuse premultiplied-alpha DX10 textures The DX10 header's alpha mode (miscFlags2, low three bits) was never read, so RGBA, BGRA, BC2 and BC3 files marked premultiplied were read as straight alpha. They are refused as Unsupported, like the legacy DXT2/DXT4 FourCCs. Alpha modes 0, 1, 3 and 4 and the formats without alpha are unchanged. --- crates/dds/README.md | 2 +- crates/dds/src/lib.rs | 5 +++++ crates/image-codecs/README.md | 2 +- crates/image-codecs/tests/it/dds.rs | 29 +++++++++++++++++++++++++++++ 4 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/dds/README.md b/crates/dds/README.md index 720ec9ba7..e3c3f4956 100644 --- a/crates/dds/README.md +++ b/crates/dds/README.md @@ -16,7 +16,7 @@ craft-dds = { git = "https://github.com/storytold/craft-libs", rev = "" | 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 DXT2/DXT4, signed (SNORM) BC4/BC5 and +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. diff --git a/crates/dds/src/lib.rs b/crates/dds/src/lib.rs index 5c088052a..2d026a660 100644 --- a/crates/dds/src/lib.rs +++ b/crates/dds/src/lib.rs @@ -359,6 +359,11 @@ fn dx10_encoding(b: &[u8]) -> Result { 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]; diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index 1bdf1418d..11ed6b40c 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -100,7 +100,7 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them 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 DXT2/DXT4, signed (SNORM) BC4/BC5 and other formats + 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 diff --git a/crates/image-codecs/tests/it/dds.rs b/crates/image-codecs/tests/it/dds.rs index ad927019a..d174255b2 100644 --- a/crates/image-codecs/tests/it/dds.rs +++ b/crates/image-codecs/tests/it/dds.rs @@ -327,6 +327,35 @@ 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. From e76bf4bad443c5b74773175538ef7985b0356f53 Mon Sep 17 00:00:00 2001 From: vangel76 <271991477+vangel76@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:04:08 +0100 Subject: [PATCH 23/57] DOCX: an Office 2016 chart with a text-only fallback keeps its size as a placeholder read_chartex_alternate built the chart object only from a picture fallback. With a fallback that holds only text (for example "Chart not available."), it returned None and the reader used the fallback words, so the chart's 432 x 252 pt frame was never reserved and the pages collapsed. Now such a chart becomes a Chart graphic of the choice's wp:extent, drawn as the same kind of placeholder unsupported classic charts get (frame, title, chart type), with the choice and fallback kept so saving writes them back unchanged. A fallback that holds runs or paragraphs is still read as before, because the writer puts the fallback inside the object's own run. The frame reading at the top of read_drawing moves into drawing_frame so both paths share it. Part of storytold/wordcraft#6820 Co-Authored-By: Claude Sonnet 5.5 --- crates/docx/src/read/chart.rs | 50 ++++++++++++++++- crates/docx/src/read/chart/tests.rs | 24 ++++++++ crates/docx/src/read/story/drawing.rs | 79 ++++++++++++++++++++------- crates/docx/tests/it/fixtures.rs | 59 ++++++++++++++++++++ 4 files changed, 192 insertions(+), 20 deletions(-) diff --git a/crates/docx/src/read/chart.rs b/crates/docx/src/read/chart.rs index 5b02603d6..42c7a311c 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,54 @@ 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: Some(Rgb::WHITE), 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| { + let mut s = String::new(); + t.find_all("a:t").for_each(|r| s.push_str(&r.text())); + if s.is_empty() { + s = t.find("cx:v").map(|v| v.text().into_owned()).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/story/drawing.rs b/crates/docx/src/read/story/drawing.rs index cb1152da8..ab820904d 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) } 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)?; 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(""); @@ -188,14 +172,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")?)?; + 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). @@ -598,6 +607,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) -> 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) } 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/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 348d6239e..295b788b9 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1861,6 +1861,65 @@ 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(); + } +} + +/// A fallback that holds a run (not run content) can't be written back inside the object's own +/// run, so it is read as before: its text, no chart object. +#[test] +fn office_2016_chart_with_a_run_fallback_is_read_as_before() { + let d = craft_docx::read(&chartex_text_fallback_docx("Chart not available.")).unwrap(); + assert!(graphics(&d).is_empty()); + assert!(paras(&d).iter().any(|p| p.text.contains("Chart not available."))); +} + #[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(); From 5e3632533f8db0763cfcd5720b2462f82c7744ea Mon Sep 17 00:00:00 2001 From: vangel76 <271991477+vangel76@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:18:25 +0100 Subject: [PATCH 24/57] DOCX: read the placeholder chart title from its text, leave the frame unfilled Take the title of an Office 2016 chart from its rich text (all runs) or its text data, and draw the placeholder frame without a fill so it does not become a white box on a coloured page. The run-fallback test is a guard and says so. Part of storytold/wordcraft#6820 Co-Authored-By: Claude Sonnet 5.5 --- crates/docx/src/read/chart.rs | 9 +++------ crates/docx/tests/it/fixtures.rs | 14 ++++++++------ 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/crates/docx/src/read/chart.rs b/crates/docx/src/read/chart.rs index 42c7a311c..4b7696eee 100644 --- a/crates/docx/src/read/chart.rs +++ b/crates/docx/src/read/chart.rs @@ -150,15 +150,12 @@ pub(crate) fn chartex_items(space: Option<&El>, w: f32, h: f32) -> Vec 0.0 && h > 0.0) { return out; } - out.push(GraphicItem::Shape { rect: [0.0, 0.0, w, h], kind: ShapeKind::Rectangle, fill: Some(Rgb::WHITE), stroke: Some(AXIS), stroke_width: 0.75 }); + 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| { - let mut s = String::new(); - t.find_all("a:t").for_each(|r| s.push_str(&r.text())); - if s.is_empty() { - s = t.find("cx:v").map(|v| v.text().into_owned()).unwrap_or_default(); - } + // 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) }); diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 295b788b9..5ddfb151f 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -1893,7 +1893,10 @@ fn office_2016_chart_with_a_text_fallback_keeps_its_size_through_saves() { 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 + .iter() + .any(|i| matches!(i, craft_wordmodel::graphic::GraphicItem::Text { text, .. } if text.starts_with("Waterfall chart"))), "{:?}", graphic.items ); @@ -1911,13 +1914,12 @@ fn office_2016_chart_with_a_text_fallback_keeps_its_size_through_saves() { } } -/// A fallback that holds a run (not run content) can't be written back inside the object's own -/// run, so it is read as before: its text, no chart object. +/// 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_read_as_before() { +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()); - assert!(paras(&d).iter().any(|p| p.text.contains("Chart not available."))); + assert!(graphics(&d).is_empty(), "{:?}", graphics(&d)); } #[test] From ce8ab5cc6d5ba4df57a29da6a43f3ccbd1c7205d Mon Sep 17 00:00:00 2001 From: Diego Guerini Date: Mon, 16 Nov 2026 08:52:44 +0100 Subject: [PATCH 25/57] craft-docx: a locked canvas's paragraph falls back on its level's alignment and the list style's defaults; bold or italic set off stays off --- crates/docx/src/read/story/locked_canvas.rs | 35 ++++++++++++++------- crates/docx/tests/it/locked_canvas.rs | 20 ++++++++++++ 2 files changed, 43 insertions(+), 12 deletions(-) diff --git a/crates/docx/src/read/story/locked_canvas.rs b/crates/docx/src/read/story/locked_canvas.rs index 01e8f2872..59a52cea2 100644 --- a/crates/docx/src/read/story/locked_canvas.rs +++ b/crates/docx/src/read/story/locked_canvas.rs @@ -102,17 +102,22 @@ fn picture(pic: &El) -> El { fn paragraphs(body: &El, theme: &[Rgb]) -> Vec { body.children("a:p") .map(|p| { - // A run's properties default to its paragraph's own (`a:pPr/a:defRPr`), then to the - // list style's for the paragraph's level (`lvl`, 0–8), property by property. + // 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 level_style = body.child("a:lstStyle").and_then(|l| l.child(&format!("a:lvl{}pPr", level + 1))); - let defaults: Vec<&El> = - [ppr_el.and_then(|pp| pp.child("a:defRPr")), level_style.and_then(|l| l.child("a:defRPr"))].into_iter().flatten().collect(); + 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 ppr_el.and_then(|pp| pp.attr("algn")) { + let jc = match paragraph_styles.iter().find_map(|pp| pp.attr("algn")) { Some("ctr") => Some("center"), Some("r") => Some("right"), Some("just") => Some("both"), @@ -151,7 +156,12 @@ fn paragraphs(body: &El, theme: &[Rgb]) -> Vec { 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))); - let on = |n: &str| get(n).is_some_and(|v| v == "1" || v == "true"); + // 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. @@ -169,11 +179,12 @@ fn run_props(rpr: Option<&El>, defaults: &[&El], theme: &[Rgb]) -> El { if !fonts.is_empty() { push("w:rFonts", &fonts); } - if on("b") { - push("w:b", &[]); - } - if on("i") { - push("w:i", &[]); + 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", &[]), diff --git a/crates/docx/tests/it/locked_canvas.rs b/crates/docx/tests/it/locked_canvas.rs index 8fa7a0a20..fb01406a4 100644 --- a/crates/docx/tests/it/locked_canvas.rs +++ b/crates/docx/tests/it/locked_canvas.rs @@ -122,6 +122,26 @@ fn a_locked_canvas_text_shape_and_paragraph_defaults() { } } +/// 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() { From 69d26616e0881d90ad5132b225e76d6faa86b35a Mon Sep 17 00:00:00 2001 From: tsw2k Date: Mon, 16 Nov 2026 11:34:11 +0000 Subject: [PATCH 26/57] craft-rtf: tables keep their column grid on odd rows Moves storytold/wordcraft#4595 into craft-rtf, where WordCraft's RTF reader now lives (#778). column_grid dropped the whole grid, so every spanning cell fell back to one of N equal columns, when a table had more than 63 distinct cell edges, a zero-width cell, a cell without \cellx, or two edges under a point apart (which the document model rejects as a column width). Forms exported from spreadsheets, with many narrow columns, hit this: a report title wrapped a few words per line in a quarter of the page and the document grew to hundreds of pages. Now the narrowest column merges into the next, one at a time, while there are over 63 columns, a column of a point or less, or a column under 6 pt with more columns left than the widest row has cells; each cell edge snaps to the nearest grid edge, and a zero-width or undefined cell takes a column in its own row only. --- crates/rtf/src/doc/parse.rs | 140 +++++++++++++++++++++++++++++++----- crates/rtf/src/doc/tests.rs | 135 ++++++++++++++++++++++++++++++++++ 2 files changed, 256 insertions(+), 19 deletions(-) diff --git a/crates/rtf/src/doc/parse.rs b/crates/rtf/src/doc/parse.rs index 60a65740a..f44d666ce 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,142 @@ 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 under this width, in twips (6 pt), merge while the rows leave room: import widens +/// any narrower column to 6 pt, which grows the table, and files exported from spreadsheets put +/// edges a few twips apart. +const MIN_GRID_GAP: i64 = 120; +/// 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 closer than [`MIN_GRID_GAP`], merge, leaving a column +/// for each cell of the widest row ([`coarse_edges`]); each cell edge moves to the nearest +/// grid edge. +/// - 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, rows.iter().map(Vec::len).max().unwrap_or(0)); + // 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, and while a column is under +/// [`MIN_GRID_GAP`] and more columns remain than the `widest_row`'s cells. The table's right edge +/// is always kept. +fn coarse_edges(edges: &[i32], widest_row: usize) -> 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 && (w >= MIN_GRID_GAP || count <= widest_row) { + 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..fda05f3b4 100644 --- a/crates/rtf/src/doc/tests.rs +++ b/crates/rtf/src/doc/tests.rs @@ -460,6 +460,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_merges_columns_import_would_widen() { + // Columns under 6 pt that no row needs: import raises each one to 6 pt, so this table of + // 3 pt columns doubled in width. Merged, it 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!(widths.iter().all(|&w| w >= 6.0), "{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. From fe68ce8c51d770a9586cfe6939ee2a28f2ecbc17 Mon Sep 17 00:00:00 2001 From: tsw2k Date: Mon, 16 Nov 2026 11:40:14 +0000 Subject: [PATCH 27/57] craft-flow: narrow table columns keep their width on import Moves the import part of storytold/wordcraft#4964 into craft-flow, where WordCraft's RTF and ODT import now builds its tables (#778). Import raised every column under 6 pt to 6 pt, so a form with many narrow columns came out wider than its source. Columns over 1 pt now keep the width the file gives; one of a point or less, none or not a number still gives the table equal columns, so nothing below a point, negative or NaN reaches layout. craft-rtf merged grid columns under 6 pt that no row needed, because import would widen them. With import keeping them, that merge only moved cell edges, so it goes: grid columns merge only while there are over 63 or one is a point or less. Stacked on the craft-rtf column grid change. --- crates/flow/src/to_doc.rs | 3 ++- crates/odf/src/text/tests.rs | 35 +++++++++++++++++++++++++++++++++++ crates/rtf/src/doc/parse.rs | 21 ++++++++------------- crates/rtf/src/doc/tests.rs | 28 ++++++++++++++++++++++++---- 4 files changed, 69 insertions(+), 18 deletions(-) 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/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/rtf/src/doc/parse.rs b/crates/rtf/src/doc/parse.rs index f44d666ce..01978da1e 100644 --- a/crates/rtf/src/doc/parse.rs +++ b/crates/rtf/src/doc/parse.rs @@ -267,10 +267,6 @@ fn finalize(mut r: Reader) -> Parsed { /// Most grid columns a table gets (the document model's own cap). const MAX_GRID_COLS: usize = 63; -/// Grid columns under this width, in twips (6 pt), merge while the rows leave room: import widens -/// any narrower column to 6 pt, which grows the table, and files exported from spreadsheets put -/// edges a few twips apart. -const MIN_GRID_GAP: i64 = 120; /// 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; @@ -282,9 +278,9 @@ const NO_GRID_GAP: i64 = 20; /// /// 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 closer than [`MIN_GRID_GAP`], merge, leaving a column -/// for each cell of the widest row ([`coarse_edges`]); each cell edge moves to the nearest -/// grid edge. +/// - 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. @@ -298,7 +294,7 @@ pub(super) fn column_grid(rows: &mut [Vec], rights: &[Vec]) -> Vec> = Vec::with_capacity(rows.len()); for (row, x) in rows.iter().zip(rights) { @@ -339,10 +335,9 @@ pub(super) fn column_grid(rows: &mut [Vec], rights: &[Vec]) -> Vec Vec { +/// [`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(); @@ -360,7 +355,7 @@ fn coarse_edges(edges: &[i32], widest_row: usize) -> Vec { if !kept.get(i).copied().unwrap_or(false) || w != width(i, &left) { continue; } - if count <= MAX_GRID_COLS && w > NO_GRID_GAP && (w >= MIN_GRID_GAP || count <= widest_row) { + 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. diff --git a/crates/rtf/src/doc/tests.rs b/crates/rtf/src/doc/tests.rs index fda05f3b4..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. @@ -565,16 +585,16 @@ fn table_grid_keeps_a_column_for_each_cell_of_the_widest_row() { } #[test] -fn table_grid_merges_columns_import_would_widen() { - // Columns under 6 pt that no row needs: import raises each one to 6 pt, so this table of - // 3 pt columns doubled in width. Merged, it keeps its 60 pt. +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!(widths.iter().all(|&w| w >= 6.0), "{widths:?}"); + 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); From 8b876291a1547ebe57b282b8f86b35644f731496 Mon Sep 17 00:00:00 2001 From: tsw2k Date: Mon, 16 Nov 2026 11:46:35 +0000 Subject: [PATCH 28/57] craft-docx: a frame preset shape is a border with a hole Moves the format part of storytold/wordcraft#6162 into craft-wordmodel, craft-docx, craft-flow and craft-odf, where WordCraft's DOCX and ODT I/O now live (#778). A DrawingML `prstGeom frame` (a letterhead's page border) was read as a rectangle, so its fill covered the whole page behind the text. It is now ShapeKind::Frame, its border width read from `adj1` (capped, as a rounded rectangle's corner is) and written back as the same preset. connector::frame_width gives the border in points. Formats with no frame shape (ODT and the other flow formats) get the freeform it draws: its outline and, wound the other way, its hole, so the hole stays empty under either fill rule. --- crates/docx/src/read/shape_style.rs | 1 + crates/docx/src/read/story/drawing.rs | 13 ++++--- crates/docx/src/write/story/drawing.rs | 12 +++++-- crates/docx/tests/it/fixtures.rs | 33 ++++++++++++++++++ crates/flow/src/from_doc.rs | 20 ++++++++++- crates/odf/src/text/shapes.rs | 3 +- crates/odf/src/text/tests_more/shapes.rs | 41 +++++++++++++++++++++++ crates/wordmodel/src/connector.rs | 12 +++++++ crates/wordmodel/src/para/inline_kinds.rs | 3 ++ crates/wordmodel/src/wrap.rs | 1 + 10 files changed, 130 insertions(+), 9 deletions(-) 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/drawing.rs b/crates/docx/src/read/story/drawing.rs index cb1152da8..6bc697a3b 100644 --- a/crates/docx/src/read/story/drawing.rs +++ b/crates/docx/src/read/story/drawing.rs @@ -526,12 +526,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 diff --git a/crates/docx/src/write/story/drawing.rs b/crates/docx/src/write/story/drawing.rs index 7c03cca6e..1479d2bd8 100644 --- a/crates/docx/src/write/story/drawing.rs +++ b/crates/docx/src/write/story/drawing.rs @@ -117,16 +117,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", &[]), diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 348d6239e..47663008d 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -2729,6 +2729,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() { diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index 810e67d55..b7204f1bf 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/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_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/wordmodel/src/connector.rs b/crates/wordmodel/src/connector.rs index 366679070..2233b67f6 100644 --- a/crates/wordmodel/src/connector.rs +++ b/crates/wordmodel/src/connector.rs @@ -201,6 +201,8 @@ pub struct ShapeExtra { pub end_style: ArrowStyle, /// A rounded rectangle's corner radius (`roundRect`'s `adj`, ECMA-376 §20.1.10.56): in /// 100000ths of the shorter side, at most [`MAX_CORNER`]; `None` draws [`DEFAULT_CORNER`]. + /// A [`ShapeKind::Frame`]'s border width (`frame`'s `adj1`), in the same units; `None` + /// draws [`DEFAULT_FRAME`]. #[serde(skip_serializing_if = "Option::is_none")] pub corner: Option, /// The outline dash pattern; absent in older saved documents means solid. @@ -273,6 +275,16 @@ pub const MAX_CORNER: u32 = 50_000; /// A rounded rectangle's corner radius without its own: 16% of the shorter side. pub const DEFAULT_CORNER: f32 = 0.16; +/// A frame's border width without its own: `frame`'s default `adj1`, 12.5% of the shorter side. +pub const DEFAULT_FRAME: f32 = 0.125; + +/// The border width, in points, of a `w` × `h` [`ShapeKind::Frame`] with `corner` (see +/// [`ShapeExtra::corner`]): at most half the shorter side, which leaves no hole. +pub fn frame_width(corner: Option, w: f32, h: f32) -> f32 { + let side = crate::geom::finite(w).min(crate::geom::finite(h)).max(0.0); + side * corner.map_or(DEFAULT_FRAME, |c| c.min(MAX_CORNER) as f32 / 100_000.0) +} + /// The corner radius, in points, of a `w` × `h` rounded rectangle with `corner` (see /// [`ShapeExtra::corner`]). pub fn corner_radius(corner: Option, w: f32, h: f32) -> f32 { diff --git a/crates/wordmodel/src/para/inline_kinds.rs b/crates/wordmodel/src/para/inline_kinds.rs index 686089f7f..c36bd8fe6 100644 --- a/crates/wordmodel/src/para/inline_kinds.rs +++ b/crates/wordmodel/src/para/inline_kinds.rs @@ -24,6 +24,9 @@ pub enum ShapeKind { ArrowDown, Star, Heart, + /// A picture frame (DrawingML's `frame`): a rectangle with a rectangular hole, its border as + /// wide as [`crate::connector::frame_width`] says. + Frame, /// A text box (rectangle with a text story). TextBox, /// A shape drawn point by point, such as ink (its geometry is the shape's `freeform`). diff --git a/crates/wordmodel/src/wrap.rs b/crates/wordmodel/src/wrap.rs index 1c235d73e..9b305fafe 100644 --- a/crates/wordmodel/src/wrap.rs +++ b/crates/wordmodel/src/wrap.rs @@ -70,6 +70,7 @@ pub fn shape_outline(kind: ShapeKind, w: f32, h: f32, corner: Option) -> Op | ShapeKind::TextBox | ShapeKind::Line | ShapeKind::Freeform + | ShapeKind::Frame | ShapeKind::StraightConnector | ShapeKind::ElbowConnector | ShapeKind::CurvedConnector => return None, From 16bf5f8578893dd318334010da6c8ff5e0fbdc37 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:52:55 +0100 Subject: [PATCH 29/57] media: add a pooled FileReader ByteSource FileReader reads a file in place and keeps at most MAX_OPEN_FILES descriptors open in a shared LRU pool, reopening by path when a file was closed. A project with hundreds of clips can stay under the process file-descriptor limit. A file truncated since it was opened is refused. Part of #778 and effectcraft#781. --- crates/media/src/file.rs | 206 +++++++++++++++++++++++++++++++++++++++ crates/media/src/lib.rs | 6 ++ 2 files changed, 212 insertions(+) create mode 100644 crates/media/src/file.rs diff --git a/crates/media/src/file.rs b/crates/media/src/file.rs new file mode 100644 index 000000000..93e36e648 --- /dev/null +++ b/crates/media/src/file.rs @@ -0,0 +1,206 @@ +//! Pooled file [`ByteSource`]s: many clips can be open at once without holding a descriptor each. +//! +//! Past [`MAX_OPEN_FILES`] 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). + +#![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") +} + +/// Files [`FileReader`]s keep open at most, together. Past this many, the least recently read file +/// is closed and its reader reopens it on demand. +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 { + let file = std::fs::File::open(path)?; + let m = file.metadata()?; + if !m.is_file() { + return Err(io::Error::new(io::ErrorKind::NotFound, format!("{} is not a file", path.display()))); + } + let id = pool.next_id(); + pool.insert(id, file); + Ok(Self { path: path.to_path_buf(), 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) { + return Ok(file); + } + let file = std::fs::File::open(&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(); + } +} 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}; From 43db2f024e8ae7f46c83556bb5fe5d1f50cc95ce Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:58:40 +0100 Subject: [PATCH 30/57] media: refuse FIFOs before opening a FileReader Opening a named pipe with no writer blocks. Check the path is a regular file first, then open with O_NONBLOCK (as filmcraft-media does), and check the handle again so a FIFO swapped in after the path check cannot hang the open or a reopen after eviction. --- crates/media/src/file.rs | 83 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 80 insertions(+), 3 deletions(-) diff --git a/crates/media/src/file.rs b/crates/media/src/file.rs index 93e36e648..67ba07c32 100644 --- a/crates/media/src/file.rs +++ b/crates/media/src/file.rs @@ -16,6 +16,53 @@ 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())) +} + /// Files [`FileReader`]s keep open at most, together. Past this many, the least recently read file /// is closed and its reader reopens it on demand. pub const MAX_OPEN_FILES: usize = 128; @@ -103,10 +150,14 @@ impl FileReader { } pub(crate) fn open_in(path: &Path, pool: &Arc) -> io::Result { - let file = std::fs::File::open(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(io::Error::new(io::ErrorKind::NotFound, format!("{} is not a file", path.display()))); + return Err(not_a_file(path)); } let id = pool.next_id(); pool.insert(id, file); @@ -120,7 +171,7 @@ impl FileReader { if let Some(file) = self.pool.get(self.id) { return Ok(file); } - let file = std::fs::File::open(&self.path)?; + 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()))); @@ -203,4 +254,30 @@ mod tests { 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(); + } } From f71eeae5fabfcae2fe0c1c61c9463ba3f371cdaf Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:58:59 +0100 Subject: [PATCH 31/57] Add craft-color and craft-frame for compositor pictures craft-color holds ColorInfo, HdrMetadata, Y'CbCr matrices, transfer functions and the small helpers display conversion needs. It is not a colour-managed pipeline (no LUTs, log, grade or tone mapping). craft-frame holds VideoFrame, PixelData, Chroma and Region: the compositor and display picture type MediaSource will return. It is distinct from craft-video's decoder-output VideoFrame (#1231 / #1768). Came from the metadata and picture parts of filmcraft-color and filmcraft-frame. Part of #778 and effectcraft#781. --- Cargo.lock | 18 ++ Cargo.toml | 2 + crates/color/Cargo.toml | 17 ++ crates/color/src/lib.rs | 411 ++++++++++++++++++++++++++++++++++++++++ crates/frame/Cargo.toml | 17 ++ crates/frame/src/lib.rs | 376 ++++++++++++++++++++++++++++++++++++ 6 files changed, 841 insertions(+) create mode 100644 crates/color/Cargo.toml create mode 100644 crates/color/src/lib.rs create mode 100644 crates/frame/Cargo.toml create mode 100644 crates/frame/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 1d5c223cf..c462980f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1451,6 +1451,14 @@ dependencies = [ "encoding_rs", ] +[[package]] +name = "craft-color" +version = "0.1.0" +dependencies = [ + "proptest", + "serde", +] + [[package]] name = "craft-control-protocol" version = "0.1.0" @@ -1868,6 +1876,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" diff --git a/Cargo.toml b/Cargo.toml index f1a09e32a..beec53ea3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,6 +50,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" } 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..5bf6426b8 --- /dev/null +++ b/crates/color/src/lib.rs @@ -0,0 +1,411 @@ +//! 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), + 9 | 10 => Some(Matrix::Bt2020Ncl), + _ => None, + } + } +} + +/// Transfer characteristics. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Transfer { + /// BT.709 / BT.1886 display (pure 2.4 gamma is what NLEs use for display-referred 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), Some(m)) => c.min(m), + (Some(c), None) => 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))] +} + +/// 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) -> f32 { + let scale = (1u32 << (bits - 8)) as f32; + 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) -> f32 { + let scale = (1u32 << (bits - 8)) as f32; + 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 limited_range_levels() { + assert_eq!(normalize_y(16, 8, Range::Limited), 0.0); + assert_eq!(normalize_y(235, 8, Range::Limited), 1.0); + assert_eq!(normalize_y(940, 10, Range::Limited), 1.0); + assert_eq!(normalize_c(128, 8, Range::Limited), 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(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(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/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..2a7c82d1a --- /dev/null +++ b/crates/frame/src/lib.rs @@ -0,0 +1,376 @@ +//! 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}; + +/// 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) -> Self { + debug_assert_eq!(data.len(), (width * height * 4) as usize); + Self { width, height, data: PixelData::Rgba8(Arc::new(data)), color: ColorInfo::SRGB_FULL, par: (1, 1), pts: Tick::ZERO } + } + + /// A linear premultiplied RGBA f32 frame, sRGB-full tags, 1:1, zero pts. + pub fn rgba_f32(width: u32, height: u32, data: Vec) -> Self { + debug_assert_eq!(data.len(), (width * height * 4) as usize); + Self { width, height, data: PixelData::RgbaF32(Arc::new(data)), color: ColorInfo::SRGB_FULL, par: (1, 1), pts: Tick::ZERO } + } + + /// A transparent linear RGBA f32 frame of the given size. + pub fn transparent_f32(width: u32, height: u32) -> Self { + Self::rgba_f32(width, height, vec![0.0; (width * height * 4) as usize]) + } + + /// 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() * 4, + PixelData::Yuv8 { planes, alpha, .. } => planes.iter().map(|p| p.len()).sum::() + alpha.as_ref().map_or(0, |a| a.len()), + PixelData::Yuv16 { planes, alpha, .. } => (planes.iter().map(|p| p.len()).sum::() + alpha.as_ref().map_or(0, |a| a.len())) * 2, + } + } + + /// Premultiplied linear-light RGBA f32, one pixel per source pixel, row-major, 4 samples each. + pub fn to_linear_f32(&self) -> Vec { + let (w, h) = (self.width as usize, self.height as usize); + let mut out = vec![0.0; w.saturating_mul(h).saturating_mul(4)]; + if w == 0 || h == 0 { + return 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; + } + } + } + } + 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) -> Vec { + let (w, h) = (self.width as usize, self.height as usize); + match &self.data { + PixelData::Rgba8(d) => d.as_ref().clone(), + 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 = vec![0u8; w * h * 4]; + 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; + } + }); + out + } + _ => { + let lin = self.to_linear_f32(); + let mut out = vec![0u8; w * h * 4]; + out.par_chunks_mut(w * 4).zip(lin.par_chunks(w * 4)).for_each(|(o, s)| linear_premul_to_srgb8(s, o)); + 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) -> Vec { + match &self.data { + PixelData::Yuv8 { planes, .. } => planes[0].as_ref().clone(), + _ => self + .to_rgba8() + .as_chunks::<4>() + .0 + .iter() + .map(|p| (0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32) as u8) + .collect(), + } + } +} + +/// 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 rgba8_roundtrips_through_to_rgba8() { + let px = vec![10u8, 20, 30, 255, 0, 0, 0, 0]; + let f = VideoFrame::rgba8(2, 1, px.clone()).with_pts(Tick(42)); + assert_eq!(f.pts, Tick(42)); + assert_eq!(f.to_rgba8(), 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]); + let lin = f.to_linear_f32(); + 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(); + 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(); + 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(), 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); + assert_eq!(f.to_rgba8(), vec![0; 8]); + assert_eq!(f.byte_size(), 32); // 2 pixels × 4 f32 channels × 4 bytes + } +} From a1f8141307dbe3e3c93adfc1a55e263b7bead8e0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:04:19 +0100 Subject: [PATCH 32/57] media: reopen FileReader from the path resolved at open A relative path was stored as given, so after the pool evicted the handle a later working-directory change could reopen a different same-length file. Resolve std::path::absolute once before the first open and reuse that path. The regression runs in a subprocess so it does not change other tests' cwd. --- crates/media/src/file.rs | 61 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 5 deletions(-) diff --git a/crates/media/src/file.rs b/crates/media/src/file.rs index 67ba07c32..d87b323c0 100644 --- a/crates/media/src/file.rs +++ b/crates/media/src/file.rs @@ -150,18 +150,21 @@ impl FileReader { } 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)); + if !std::fs::metadata(&path)?.is_file() { + return Err(not_a_file(&path)); } - let file = open_nonblocking(path)?; + let file = open_nonblocking(&path)?; let m = file.metadata()?; if !m.is_file() { - return Err(not_a_file(path)); + return Err(not_a_file(&path)); } let id = pool.next_id(); pool.insert(id, file); - Ok(Self { path: path.to_path_buf(), len: m.len(), id, pool: pool.clone() }) + 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 @@ -280,4 +283,52 @@ mod tests { } 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(); + } } From c864e1e8c9e0f7e2c9f24fca1faa6f298a068bca Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 09:46:17 -0500 Subject: [PATCH 33/57] psd: support caller-budgeted prediction scratch --- crates/psd/src/compression.rs | 40 ++++++++++++++++++++++++++--- crates/psd/src/compression/tests.rs | 36 ++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 3 deletions(-) diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index b41936a04..f9d4a744e 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -745,8 +745,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 => { @@ -763,8 +797,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 6e0d86a7e..ed0fd2dbc 100644 --- a/crates/psd/src/compression/tests.rs +++ b/crates/psd/src/compression/tests.rs @@ -771,3 +771,39 @@ fn rle_chunks_use_the_callers_pool_and_report_panics() { assert!(map_chunks(2, vec![0, 1], |_| panic!("worker")).is_err()); }); } + +#[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(); + } +} From e44720af47b02670b3ec42da3b65473de77a78c1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:02:40 +0100 Subject: [PATCH 34/57] media: refuse a truncated file on a FileReader cache hit file() only checked length when reopening after eviction, so a prefix read could still succeed if the handle was pooled. Check metadata on the cached handle too, and drop the entry if the file is shorter or no longer a regular file. MAX_OPEN_FILES is documented as a bound on retained pool entries, not in-flight Arc handles. --- crates/media/src/file.rs | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/media/src/file.rs b/crates/media/src/file.rs index d87b323c0..f343737b3 100644 --- a/crates/media/src/file.rs +++ b/crates/media/src/file.rs @@ -1,8 +1,9 @@ //! Pooled file [`ByteSource`]s: many clips can be open at once without holding a descriptor each. //! -//! Past [`MAX_OPEN_FILES`] 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). +//! 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"))] @@ -63,8 +64,10 @@ fn not_a_file(path: &Path) -> io::Error { io::Error::new(io::ErrorKind::NotFound, format!("{} is not a file", path.display())) } -/// Files [`FileReader`]s keep open at most, together. Past this many, the least recently read file -/// is closed and its reader reopens it on demand. +/// 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. @@ -172,7 +175,12 @@ impl FileReader { /// being written) is read up to the opened length. fn file(&self) -> io::Result> { if let Some(file) = self.pool.get(self.id) { - return Ok(file); + 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()?; @@ -331,4 +339,23 @@ mod tests { ); 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(); + } } From ed850ede0f26ef0b8ff9b4d1fc08466a1cf21375 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 10:06:40 -0500 Subject: [PATCH 35/57] stream-codecs: append TIFF PackBits rows with shared packet encoder --- crates/stream-codecs/src/runlength.rs | 39 ++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/stream-codecs/src/runlength.rs b/crates/stream-codecs/src/runlength.rs index a6df9e19d..dceb78f66 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).unwrap(), row); + } + } + } } From 9fc471fc5c18f467394a043adf17f021c2b27cae Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:09:54 +0100 Subject: [PATCH 36/57] psd: add Descriptor::parse_prefix for mid-stream reads (#1887) from_bytes still requires the slice to be fully consumed. parse_prefix returns the descriptor and the number of bytes used, matching VersionedDescriptor, so apps can read a descriptor that is followed by more data (layer effects, fill and adjustment blocks). Part of #778 and effectcraft#786. --- crates/psd/src/descriptor.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index f3afae64a..96ad47a7b 100644 --- a/crates/psd/src/descriptor.rs +++ b/crates/psd/src/descriptor.rs @@ -300,6 +300,15 @@ 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())) + } + /// Serializes the descriptor. pub fn to_bytes(&self) -> Vec { let mut v = Vec::new(); @@ -705,6 +714,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()); From 963a52ec95d260937cbf3be13d7ade6caed2974f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 10:21:41 -0500 Subject: [PATCH 37/57] test: report PackBits codec errors without requiring Failure Debug --- crates/stream-codecs/src/runlength.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/stream-codecs/src/runlength.rs b/crates/stream-codecs/src/runlength.rs index dceb78f66..a13a1d4fb 100644 --- a/crates/stream-codecs/src/runlength.rs +++ b/crates/stream-codecs/src/runlength.rs @@ -141,7 +141,7 @@ mod tests { 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).unwrap(), row); + assert_eq!(decode(&encoded, n).map_err(|failure| failure.error).unwrap(), row); } } } From 45ad9df6370213c1e1b0ad242d1c74c413963e15 Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 16 Nov 2026 16:21:55 +0100 Subject: [PATCH 38/57] craft-xlsx: decode XLSB defined names after the workbook's tables are indexed A defined name's formula may use a structured reference (PtgList). Names were decoded inside xlsb::workbook, before Package::workbook indexed the table parts, so such a name was left out and the cells using it kept only their saved results. xlsb::workbook now returns the names undecoded (Names), and Package::workbook decodes them with xlsb::read_names after index_tables. Regression: a_name_using_a_structured_reference_is_decoded_after_tables_are_indexed fails without the reorder. --- crates/xlsx/src/package.rs | 4 +++- crates/xlsx/src/xlsb.rs | 28 +++++++++++++++++++++------- crates/xlsx/tests/xlsb.rs | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 8 deletions(-) diff --git a/crates/xlsx/src/package.rs b/crates/xlsx/src/package.rs index ce7d7756f..a75874e71 100644 --- a/crates/xlsx/src/package.rs +++ b/crates/xlsx/src/package.rs @@ -149,10 +149,12 @@ impl<'a> Package<'a> { if self.binary.is_some() { let bytes = self.required(&self.workbook_part.clone())?; let rels = self.workbook_rels()?; - let (wb, mut links) = xlsb::workbook(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings)?; + let (mut wb, mut links, names) = xlsb::workbook(&bytes, &rels, &self.limits, &self.budget, &mut self.warnings)?; if let Some(links) = links.as_mut() { self.index_tables(&wb, links)?; } + // Names after tables: a name's formula may use a structured reference. + xlsb::read_names(&mut wb, names, links.as_mut(), &self.limits, &self.budget, &mut self.warnings); self.binary_links = Some(links); return Ok(wb); } diff --git a/crates/xlsx/src/xlsb.rs b/crates/xlsx/src/xlsb.rs index 7ec6be839..b45b48808 100644 --- a/crates/xlsx/src/xlsb.rs +++ b/crates/xlsx/src/xlsb.rs @@ -289,14 +289,16 @@ impl<'a, 'l> Records<'a, 'l> { /// The workbook part: BrtBeginBook, BrtWbProp, the BrtBundleSh list. /// The workbook part, and the tables its formulas refer to ([`Links`]): `None` when those can't -/// be read, so that the workbook still opens, with every formula kept as its saved result. +/// be read, so that the workbook still opens, with every formula kept as its saved result. Its +/// defined names come back undecoded ([`Names`]): [`read_names`] decodes them once the workbook's +/// tables are indexed, so a name's formula can use a structured reference. pub(crate) fn workbook( bytes: &[u8], rels: &Rels, limits: &Limits, budget: &Budget, warnings: &mut Warnings, -) -> Result<(Workbook, Option), Error> { +) -> Result<(Workbook, Option, Names), Error> { let mut records = Records::new(bytes, limits, budget); records.first(131, warnings)?; let mut wb = Workbook::default(); @@ -320,11 +322,7 @@ pub(crate) fn workbook( if wb.sheets.is_empty() { return Err(invalid("no supported worksheets")); } - match links.as_mut() { - Some(l) => wb.defined_names = defined_names(pending, &bundle_sheets, l, limits, budget, warnings), - None => warnings.warn("XLSB: the workbook's sheet links or names could not be read; formulas keep their saved results"), - } - return Ok((wb, links)); + return Ok((wb, links, Names { pending, sheets: bundle_sheets })); } 39 | 355 | 357 | 358 | 362 | 667 => { if let Some(l) = links.as_mut() @@ -423,6 +421,22 @@ struct PendingName { help: Option, } +/// The workbook part's defined names, not yet decoded, and each BrtBundleSh's place in +/// [`Workbook::sheets`] (`None` for a skipped one). +pub(crate) struct Names { + pending: Vec, + sheets: Vec>, +} + +/// Decodes the workbook part's defined names `names` into `wb`, after the tables in `links` are +/// indexed. Without `links` none can be read, and formulas keep their saved results. +pub(crate) fn read_names(wb: &mut Workbook, names: Names, links: Option<&mut Links>, limits: &Limits, budget: &Budget, warnings: &mut Warnings) { + match links { + Some(l) => wb.defined_names = defined_names(names.pending, &names.sheets, l, limits, budget, warnings), + None => warnings.warn("XLSB: the workbook's sheet links or names could not be read; formulas keep their saved results"), + } +} + /// The workbook's defined names, as `.xlsx` has them in `definedNames`: every `BrtName` but the /// hidden ones for newer functions and LET parameters, which Excel doesn't write there. `sheets` /// maps a name's `itab` (its sheet's place in `BrtBundleSh` order) to [`Workbook::sheets`]. diff --git a/crates/xlsx/tests/xlsb.rs b/crates/xlsx/tests/xlsb.rs index 16220df9e..cd5494c03 100644 --- a/crates/xlsx/tests/xlsb.rs +++ b/crates/xlsx/tests/xlsb.rs @@ -1803,6 +1803,42 @@ fn tables_of(bytes: &[u8]) -> (Vec
, Vec) { (tables, p.warnings().to_vec()) } +#[test] +fn a_name_using_a_structured_reference_is_decoded_after_tables_are_indexed() { + // `Vals` = `Sales[Val]`. Names are decoded after the workbook's tables are indexed, so + // the formula and a cell that uses it are kept, instead of only their saved results. + let name = brt_name(0, 0, WORKBOOK, "Vals", &ptg_list(0, 1, 1, 1, 1), None); + let list = [record(660, &1u32.to_le_bytes()), record(661, &wide("t1")), record(662, &[])]; + let mut data = row(0); + data.extend(formula_cell(1, &[0x23, 5, 0, 0, 0], &[])); // =Vals, after the four names of `book_with_links` + let types = { + let t = TYPES.trim_end_matches(""); + format!(r#"{t}"#) + }; + let sheet_rels = r#""#; + let (one, two, strings, table) = (worksheet(&data, &list.concat()), worksheet(&[], &[]), sst(), sales(&sales_filters())); + let book = { + let plain = book_with_links(&xti()); + let end = record(132, &[]); + [&plain[..plain.len() - end.len()], name.as_slice(), end.as_slice()].concat() + }; + let bytes = zip(&[ + ("[Content_Types].xml", types.as_bytes()), + ("_rels/.rels", ROOT.as_bytes()), + ("records/book.bin", book.as_slice()), + ("records/_rels/book.bin.rels", RELS.as_bytes()), + ("data/one.bin", one.as_slice()), + ("data/_rels/one.bin.rels", sheet_rels.as_bytes()), + ("data/two.bin", two.as_slice()), + ("text/strings.bin", strings.as_slice()), + ("tables/t1.bin", table.as_slice()), + ]); + let names = Package::open(&bytes, &Limits::default()).unwrap().workbook().unwrap().defined_names; + assert_eq!(names.iter().find(|n| n.name == "Vals").map(|n| n.formula.as_str()), Some("Sales[Val]")); + let wb = read(&bytes).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 1)), Some("Vals"), "{:?}", wb.warnings); +} + #[test] fn tables_are_read_as_their_xlsx_spelling() { // Spacing flags: 0x80 inside the outer brackets, 0x100 after commas. From dd3015c678052b9a1f1732e70f83576c0a72e75f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:23:22 +0100 Subject: [PATCH 39/57] wordmodel: keep the kashida length of a justified paragraph (#1875) * wordmodel: keep the kashida length of a justified paragraph ST_Jc lowKashida, mediumKashida and highKashida were all read as Align::Justify, so the length was lost. ParaProps and ResolvedPara now keep it; a direct both/justify cancels an inherited length. The DOCX reader and writer round-trip the three values. * docx: keep a style's kashida length when writing justify w:jc encodes alignment and kashida together. A paragraph or style with Align::Justify and kashida unset still inherits a length from the style chain; writing "both" would read back as Some(Kashida::None) and cancel it. Use the resolved length in that case. --- crates/docx/src/read/props.rs | 11 +- crates/docx/src/write.rs | 5 + crates/docx/src/write/props.rs | 11 +- crates/docx/src/write/story/para.rs | 6 + crates/docx/src/write/styles.rs | 8 +- crates/docx/tests/it/kashida.rs | 136 +++++++++++++++++++++++ crates/docx/tests/it/main.rs | 1 + crates/docx/tests/it/roundtrip.rs | 5 +- crates/wordmodel/src/props.rs | 2 +- crates/wordmodel/src/props/para_props.rs | 45 +++++++- crates/wordmodel/src/resolve.rs | 35 +++++- 11 files changed, 254 insertions(+), 11 deletions(-) create mode 100644 crates/docx/tests/it/kashida.rs diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index dc61b3a28..4d86ae164 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), _ => {} diff --git a/crates/docx/src/write.rs b/crates/docx/src/write.rs index 1d9eb0818..4ba486a6c 100644 --- a/crates/docx/src/write.rs +++ b/crates/docx/src/write.rs @@ -151,6 +151,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/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/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/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/main.rs b/crates/docx/tests/it/main.rs index 8696981c7..8d6be8a97 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -20,6 +20,7 @@ mod emphasis_marks; mod fixtures; mod glossary; mod heading_levels; +mod kashida; mod legacy_forms; mod ligatures; mod line_numbering; diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 65a01e6b4..2037f9849 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}; @@ -163,6 +163,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), diff --git a/crates/wordmodel/src/props.rs b/crates/wordmodel/src/props.rs index 65a59592c..318779acb 100644 --- a/crates/wordmodel/src/props.rs +++ b/crates/wordmodel/src/props.rs @@ -27,7 +27,7 @@ pub use char_props::{ }; pub use color::{Rgb, TextColor}; pub use para_props::{ - Align, Border, BorderStyle, Borders, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, TAB_POS_EPS, TabAlign, TabLeader, TabStop, + Align, Border, BorderStyle, Borders, Kashida, LineSpacing, NumRef, ParaProps, ParagraphTextDirection, TAB_POS_EPS, TabAlign, TabLeader, TabStop, TextAlignment, TextFrame, }; pub use table_props::{ diff --git a/crates/wordmodel/src/props/para_props.rs b/crates/wordmodel/src/props/para_props.rs index a48540248..b3dec00ad 100644 --- a/crates/wordmodel/src/props/para_props.rs +++ b/crates/wordmodel/src/props/para_props.rs @@ -26,6 +26,45 @@ impl Align { } } +/// The kashida (tatweel) length a justified paragraph uses (`ST_Jc` in ECMA-376 §17.18.44). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum Kashida { + /// No kashidas: justified lines widen their word spaces (`both`, `justify`). + #[default] + None, + /// `lowKashida`. + Short, + /// `mediumKashida`. + Medium, + /// `highKashida`. + Long, +} + +impl Kashida { + /// The length named by a `w:jc` value, if that value is a kashida or ordinary justify form. + /// Other alignments return `None` so they leave an inherited length. + pub fn from_jc(value: &str) -> Option { + match value { + "both" | "justify" => Some(Kashida::None), + "lowKashida" => Some(Kashida::Short), + "mediumKashida" => Some(Kashida::Medium), + "highKashida" => Some(Kashida::Long), + _ => None, + } + } + + /// The `w:jc` value for a justified paragraph of this length. + pub fn jc(self) -> &'static str { + match self { + Kashida::None => "both", + Kashida::Short => "lowKashida", + Kashida::Medium => "mediumKashida", + Kashida::Long => "highKashida", + } + } +} + /// Paragraph-level text flow (`w:pPr/w:textDirection`, ECMA-376 §17.3.1.41). /// /// Kept separate from [`super::TextDirection`], whose three values model the table-cell direction @@ -383,6 +422,10 @@ pub struct ParaProps { pub style: Option, #[serde(skip_serializing_if = "Option::is_none")] pub align: Option, + /// Kashida length for a justified paragraph. `None` inherits; `Some(Kashida::None)` is + /// ordinary justification (`both` / `justify`) and cancels an inherited length. + #[serde(skip_serializing_if = "Option::is_none")] + pub kashida: Option, /// Left indent, points. #[serde(skip_serializing_if = "Option::is_none")] pub indent_left: Option, @@ -516,7 +559,7 @@ impl ParaProps { } fn overlay_layout(&mut self, patch: &ParaProps) { - overlay_fields!(self, patch; style, align, indent_left, indent_right, indent_first, indent_left_chars, indent_right_chars, indent_first_chars, + overlay_fields!(self, patch; style, align, kashida, indent_left, indent_right, indent_first, indent_left_chars, indent_right_chars, indent_first_chars, space_before, space_after, space_before_auto, space_after_auto, line_spacing, contextual_spacing, mirror_indents, adjust_right_indent, tabs, shading, borders); } diff --git a/crates/wordmodel/src/resolve.rs b/crates/wordmodel/src/resolve.rs index 7ef12ccdc..85a7a1550 100644 --- a/crates/wordmodel/src/resolve.rs +++ b/crates/wordmodel/src/resolve.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use crate::props::{ - Align, Border, Borders, CharProps, Highlight, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, Underline, VertAlign, + Align, Border, Borders, CharProps, Highlight, Kashida, LineSpacing, NumRef, ParaProps, Rgb, TabAlign, TabStop, TextColor, Underline, VertAlign, }; use crate::styles::{StyleKind, StyleSheet}; @@ -173,6 +173,9 @@ fn default_adjust_right_indent() -> bool { pub struct ResolvedPara { pub style: String, pub align: Align, + /// Kashida length when `align` is Justify; ignored for other alignments. + #[serde(default)] + pub kashida: Kashida, pub indent_left: f32, pub indent_right: f32, pub indent_first: f32, @@ -268,6 +271,7 @@ impl ResolvedPara { ResolvedPara { style: style.to_string(), align: p.align.unwrap_or_default(), + kashida: p.kashida.unwrap_or_default(), indent_left: clampi(p.indent_left), indent_right: clampi(p.indent_right), indent_first: clampi(p.indent_first), @@ -634,4 +638,33 @@ mod tests { assert_eq!(back.padding, [0.0; 4]); assert_eq!(back, ResolvedPara { padding: [0.0; 4], ..p }); } + + /// A style's kashida length is inherited, and a direct `both` / `justify` cancels it. + #[test] + fn kashida_length_follows_the_style_chain_and_direct_formatting() { + use crate::styles::{Style, StyleKind}; + let mut styles = StyleSheet::builtin(); + styles.upsert(Style { + id: "Body".into(), + name: "Body".into(), + kind: StyleKind::Paragraph, + based_on: Some("Normal".into()), + para: ParaProps { align: Some(Align::Justify), kashida: Some(Kashida::Short), ..Default::default() }, + ..Default::default() + }); + let inherited = styles.resolve_para(&ParaProps { style: Some("Body".into()), ..Default::default() }); + assert_eq!(inherited.align, Align::Justify); + assert_eq!(inherited.kashida, Kashida::Short); + + let cleared = styles.resolve_para(&ParaProps { + style: Some("Body".into()), + align: Some(Align::Justify), + kashida: Some(Kashida::None), + ..Default::default() + }); + assert_eq!(cleared.kashida, Kashida::None); + + let longer = styles.resolve_para(&ParaProps { style: Some("Body".into()), kashida: Some(Kashida::Long), ..Default::default() }); + assert_eq!(longer.kashida, Kashida::Long); + } } From a58989cae9173c7402a125bdd42e48fb5c878e09 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:26:36 +0100 Subject: [PATCH 40/57] image-codecs: skip a SubIFDs array whose offset is cut off (#1889) camera_raw_mode read a missing SubIFDs offset as 0, so it walked the TIFF header as the pointer array and could classify a malformed TIFF as RAW. Skip the entry instead, matching LightCraft's classifier. --- crates/image-codecs/src/codecs/tiff.rs | 6 ++++-- crates/image-codecs/tests/legacy_tiff_raw.rs | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) 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/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)); +} From fb2b27b1f02b603d696480d03345827e8b44124a Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 16 Nov 2026 16:50:42 +0100 Subject: [PATCH 41/57] craft-xlsx: preserve spacing in simple structured references --- crates/xlsx/src/xlsb/formula.rs | 6 +++++- crates/xlsx/tests/xlsb.rs | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/xlsx/src/xlsb/formula.rs b/crates/xlsx/src/xlsb/formula.rs index 5d4cfa619..40d461db1 100644 --- a/crates/xlsx/src/xlsb/formula.rs +++ b/crates/xlsx/src/xlsb/formula.rs @@ -681,17 +681,22 @@ fn list(t: &mut Bytes<'_>, links: &Links) -> Result { 2 if first <= last => Some((column(first)?, Some(column(last)?))), _ => return Err(Unsupported("invalid structured reference columns")), }; + let pad = if bits & 0x80 != 0 { " " } else { "" }; let mut s = table.name.clone(); match (rows, &columns) { ([], None) => s.push_str("[]"), ([], Some((c, None))) => { s.push('['); + s.push_str(pad); s.push_str(c); + s.push_str(pad); s.push(']'); } ([row], None) => { s.push('['); + s.push_str(pad); s.push_str(row); + s.push_str(pad); s.push(']'); } _ => { @@ -701,7 +706,6 @@ fn list(t: &mut Bytes<'_>, links: &Links) -> Result { Some((a, None)) => items.push(format!("[{a}]")), None => {} } - let pad = if bits & 0x80 != 0 { " " } else { "" }; let comma = if bits & 0x100 != 0 { ", " } else { "," }; s.push('['); s.push_str(pad); diff --git a/crates/xlsx/tests/xlsb.rs b/crates/xlsx/tests/xlsb.rs index cd5494c03..a7253df22 100644 --- a/crates/xlsx/tests/xlsb.rs +++ b/crates/xlsx/tests/xlsb.rs @@ -1839,6 +1839,27 @@ fn a_name_using_a_structured_reference_is_decoded_after_tables_are_indexed() { assert_eq!(wb.sheets[0].formula(CellRef::new(0, 1)), Some("Vals"), "{:?}", wb.warnings); } +#[test] +fn simple_table_references_preserve_square_bracket_spacing() { + let cases = [ + (1, "Sales[Val]"), + (1 | 0x80, "Sales[ Val ]"), + (rows(1), "Sales[#All]"), + (rows(1) | 0x80, "Sales[ #All ]"), + (1 | 0x100, "Sales[Val]"), + (rows(1) | 0x100, "Sales[#All]"), + ]; + let mut data = row(0); + for (i, (bits, _)) in cases.iter().enumerate() { + data.extend(formula_cell(i as u32 + 1, &ptg_list(0, *bits, 1, 1, 1), &[])); + } + let bytes = book_with_tables(&data, &[sales(&sales_filters())]); + let wb = read(&bytes).unwrap(); + for (i, (_, want)) in cases.iter().enumerate() { + assert_eq!(wb.sheets[0].formula(CellRef::new(0, i as u32 + 1)), Some(*want), "{:?}", wb.warnings); + } +} + #[test] fn tables_are_read_as_their_xlsx_spelling() { // Spacing flags: 0x80 inside the outer brackets, 0x100 after commas. From b84343883d546731e658df8a9a8b77b71ffa1489 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:04:27 +0100 Subject: [PATCH 42/57] Validate compositor frame inputs and return allocation errors --- crates/color/src/lib.rs | 45 ++++++-- crates/frame/src/lib.rs | 226 +++++++++++++++++++++++++++++++--------- 2 files changed, 211 insertions(+), 60 deletions(-) diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 5bf6426b8..01fbf3b18 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -154,24 +154,41 @@ pub fn rgb_to_ycbcr(r: f32, g: f32, b: f32, m: Matrix) -> [f32; 3] { [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) -> f32 { +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; - match range { + 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) -> f32 { +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; - match range { + 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). @@ -355,12 +372,20 @@ mod tests { } } + #[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), 0.0); - assert_eq!(normalize_y(235, 8, Range::Limited), 1.0); - assert_eq!(normalize_y(940, 10, Range::Limited), 1.0); - assert_eq!(normalize_c(128, 8, Range::Limited), 0.0); + 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] diff --git a/crates/frame/src/lib.rs b/crates/frame/src/lib.rs index 09f95e0b8..ad294b10f 100644 --- a/crates/frame/src/lib.rs +++ b/crates/frame/src/lib.rs @@ -23,6 +23,53 @@ 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, + 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::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 { @@ -103,20 +150,51 @@ impl Region { 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) -> Self { - debug_assert_eq!(data.len(), (width * height * 4) as usize); - Self { width, height, data: PixelData::Rgba8(Arc::new(data)), color: ColorInfo::SRGB_FULL, par: (1, 1), pts: Tick::ZERO } + 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) -> Self { - debug_assert_eq!(data.len(), (width * height * 4) as usize); - Self { width, height, data: PixelData::RgbaF32(Arc::new(data)), color: ColorInfo::SRGB_FULL, par: (1, 1), pts: Tick::ZERO } + 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) -> Self { - Self::rgba_f32(width, height, vec![0.0; (width * height * 4) as usize]) + 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())) + } + _ => Err(FrameError::InvalidLayout), + } } /// Sets the presentation timestamp and returns the frame. @@ -139,18 +217,27 @@ impl VideoFrame { pub fn byte_size(&self) -> usize { match &self.data { PixelData::Rgba8(d) => d.len(), - PixelData::RgbaF32(d) => d.len() * 4, - PixelData::Yuv8 { planes, alpha, .. } => planes.iter().map(|p| p.len()).sum::() + alpha.as_ref().map_or(0, |a| a.len()), - PixelData::Yuv16 { planes, alpha, .. } => (planes.iter().map(|p| p.len()).sum::() + alpha.as_ref().map_or(0, |a| a.len())) * 2, + 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) -> Vec { + 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 = vec![0.0; w.saturating_mul(h).saturating_mul(4)]; + let mut out = buffer::(elements(self.width, self.height, 4)?, max_bytes)?; if w == 0 || h == 0 { - return out; + return Ok(out); } match &self.data { PixelData::RgbaF32(d) => { @@ -173,8 +260,8 @@ impl VideoFrame { 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 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]; @@ -200,9 +287,9 @@ impl VideoFrame { 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 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; @@ -214,19 +301,28 @@ impl VideoFrame { } } } - out + 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) -> Vec { + 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 Vec::new(); + return Ok(Vec::new()); } match &self.data { - PixelData::Rgba8(d) => d.as_ref().clone(), + 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); @@ -238,7 +334,7 @@ impl VideoFrame { }; 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 = vec![0u8; w * h * 4]; + 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]; @@ -255,30 +351,33 @@ impl VideoFrame { o[3] = 255; } }); - out + Ok(out) } _ => { - let lin = self.to_linear_f32(); - let mut out = vec![0u8; w * h * 4]; + 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)); - out + 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) -> Vec { + 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, .. } => planes[0].as_ref().clone(), - _ => self - .to_rgba8() - .as_chunks::<4>() - .0 - .iter() - .map(|p| (0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32) as u8) - .collect(), + 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) } } @@ -307,22 +406,49 @@ pub fn default_matrix(width: u32, height: u32) -> Matrix { 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 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); - assert!(frame.to_rgba8().is_empty()); - assert!(frame.to_linear_f32().is_empty()); - assert!(frame.luma8().is_empty()); + 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()).with_pts(Tick(42)); + let f = VideoFrame::rgba8(2, 1, px.clone()).unwrap().with_pts(Tick(42)); assert_eq!(f.pts, Tick(42)); - assert_eq!(f.to_rgba8(), px); + 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); @@ -331,14 +457,14 @@ mod tests { #[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]); - let lin = f.to_linear_f32(); + 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(); + let back = f.to_rgba8().unwrap(); assert_eq!(back[0], 128); assert_eq!(back[3], 128); } @@ -356,14 +482,14 @@ mod tests { par: (1, 1), pts: Tick::ZERO, }; - let rgba = f.to_rgba8(); + 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(), vec![126, 126, 126, 126]); + assert_eq!(f.luma8().unwrap(), vec![126, 126, 126, 126]); assert_eq!(f.format_label(), "YUV 4:4:4 8-bit"); } @@ -383,8 +509,8 @@ mod tests { #[test] fn transparent_float_encodes_as_zero_rgba8() { - let f = VideoFrame::transparent_f32(2, 1); - assert_eq!(f.to_rgba8(), vec![0; 8]); + 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 } } From d839db7d4a1a24cb21bcd44162aba1a5055ad2f0 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:06:42 +0100 Subject: [PATCH 43/57] Test odd planar layouts and independent storage validation --- crates/frame/src/lib.rs | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/crates/frame/src/lib.rs b/crates/frame/src/lib.rs index ad294b10f..7f3a993c7 100644 --- a/crates/frame/src/lib.rs +++ b/crates/frame/src/lib.rs @@ -424,6 +424,52 @@ mod tests { 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 frame_allocations_are_checked_before_reserving() { assert!(matches!(VideoFrame::transparent_f32(u32::MAX, u32::MAX), Err(FrameError::TooLarge))); From 10a585c3e2f7486b8bbd179edb6dc167e0eaea99 Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 16 Nov 2026 17:14:31 +0100 Subject: [PATCH 44/57] fix(psd): preserve consumer resource limits (#786) --- crates/psd/src/descriptor.rs | 60 ++++++++++++++++++----- crates/psd/src/float.rs | 28 ++++++++--- crates/psd/src/smart.rs | 7 ++- crates/psd/tests/resource_limits.rs | 76 +++++++++++++++++++++++++++++ 4 files changed, 153 insertions(+), 18 deletions(-) create mode 100644 crates/psd/tests/resource_limits.rs diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index 96ad47a7b..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)] @@ -309,6 +329,14 @@ impl Descriptor { 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(); @@ -317,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) { @@ -391,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()?; @@ -428,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) } @@ -472,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)))); @@ -625,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:?}"), } 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/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()); +} From ecb92f4554042b2a6a5e7fb07b9b56be8fc67a31 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 16 Nov 2026 11:24:32 -0500 Subject: [PATCH 45/57] timeline: extract attributed allocation-free XML and JSON preflight scans --- crates/timeline/src/lib.rs | 1 + crates/timeline/src/preflight.rs | 82 ++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 crates/timeline/src/preflight.rs 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..49995667c --- /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, originally by Brandon Thomas. +//! 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""); + } 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 +} From a2560df05b4c58631f53a57e65fb05f0e0e6cf76 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 11:25:03 -0500 Subject: [PATCH 46/57] timeline: cover lexical preflight compatibility and deep inputs --- crates/timeline/tests/preflight.rs | 31 ++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 crates/timeline/tests/preflight.rs 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#"]]>"#; + 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"