From ce819906a58fc8ce0482ed159f11c4d1e7fa2d3b Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Tue, 13 Oct 2026 12:28:12 -0700 Subject: [PATCH 001/144] 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 f50f2d6639..9e2795cd85 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 613d0db6bf..31dc6b1ab4 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 ef8cbcee67..9c428179d5 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 0000000000..eecd8883e4 --- /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 f7fcdd0ca1..f958ffc511 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 002/144] 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 e03128e811..c992180857 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 8f2c5efc6b..820132836d 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 65aab0eb8a..13e687d2c5 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 197644a333..96dc8f03a9 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 3a6960b399..7cc820ff89 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 0000000000..71e8f3d921 --- /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 950dc88471..3a0228275b 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 003/144] 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 05c1a673c3..216ed49a09 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 004/144] 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 216ed49a09..2d173b3251 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 88c52213b45509b3f1c7aec43029592b2af2acd7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 18:38:29 +0100 Subject: [PATCH 005/144] 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 27215f85d4..c3e530dd8d 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 9e9f8ff3e6..012c205521 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 f60f232361..8fe0244e14 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 69d7c2af69..9b663b86e9 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 29e49dc933..24b882b3a1 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 5e95e57eb2..98a87f3a28 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 25bfb89dbe..da3f10d79e 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 006/144] 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 c3e530dd8d..37d99481d3 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 24b882b3a1..0f4e4b2f07 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 98a87f3a28..bc46d59e3a 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 007/144] 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 37d99481d3..a251d4f3cb 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 2632c41eb4d4a0d07eda816b7a17eb436a791954 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 15 Nov 2026 20:47:25 +0100 Subject: [PATCH 008/144] 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 a251d4f3cb..af2f6b736b 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 012c205521..f26bf20737 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 8fe0244e14..135d070f92 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 009/144] 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 135d070f92..dc34cf10fa 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 5fe263f02c..fd03d2d981 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 010/144] 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 d31616b399..27fa58dc7d 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 bec5fb2393..b6315375a4 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 011/144] 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 b6315375a4..46f7513e7f 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 012/144] 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 0000000000..05d000a73b --- /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 4eda74a263..78762de5f3 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 013/144] 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 7ed5164639..4063407341 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 48a2edf1dc..4d31e635de 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 0b4b9a4151..af98f90e76 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 0000000000..e3cee56960 --- /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 0000000000..465975ff29 --- /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 0000000000..a98a086318 --- /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 208ff3ce79..ef8d7b76ee 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 a0e1afaa42..27ddddb69f 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 00b94b7ec0..f647809af0 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 9ed4e3f358..9d682b03f1 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 71f6030b3c..d0ef8ee9a6 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 014/144] 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 e3cee56960..ca40bd69af 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 465975ff29..3871452dfe 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 df60e462cd..1641a9e56d 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 a98a086318..079b3e3b5e 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 015/144] 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 1641a9e56d..12bf151790 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 016/144] 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 af98f90e76..7b0c88ded0 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 ca40bd69af..f93e8cbcc9 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 3871452dfe..720ec9ba7c 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 12bf151790..863aa30771 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 079b3e3b5e..5c088052a8 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 27ddddb69f..1bdf1418db 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 9d682b03f1..26a100fab6 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 12c285d7bd..52d6eaa239 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 26696ae2af..4b6ee5bb95 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 4f766a54c7..ad927019a2 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 f9d9add8ef..bc92c87b62 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 907e73763a..eec7ac0d56 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 7e705da998..a9aa7c4c66 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 afb9066aa2..d5c482aa7d 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 017/144] 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 bc92c87b62..af6a2c7d20 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 018/144] 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 bb4804e0d2..8cf4c99dd0 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 18f9f8239f..199676e162 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 981b9c0988..01b7d27c67 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 8f3bbdd0bd..3ba2f326a4 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 019/144] 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 01b7d27c67..a72046e831 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 3ba2f326a4..4bb6cab35f 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 020/144] 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 720ec9ba7c..e3c3f49562 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 5c088052a8..2d026a6607 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 1bdf1418db..11ed6b40ce 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 ad927019a2..d174255b2e 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 021/144] 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 5b02603d6c..42c7a311c3 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 ae80c028eb..d785d44005 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 cb1152da89..ab820904db 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 348d6239e1..295b788b94 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 022/144] 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 42c7a311c3..4b7696eee4 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 295b788b94..5ddfb151f0 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 2e5e69091a1d41217f93f9f18678351c3ff8653f Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Mon, 16 Nov 2026 00:41:54 -0300 Subject: [PATCH 023/144] craft-odf: preserve page background bitmap fill and legacy fallback (#1784) - Preserves page background images and bitmap fills (`draw:fill="bitmap"`) alongside legacy `` fallbacks on ODT export, preventing orphaned duplicate backgrounds and resolving naming collisions with header pictures. - Reuses kept picture files or fill images with identical bytes on export instead of duplicating background files and definitions on every save. - Allocates distinct fill names for replaced page pictures and maps colliding names in linear time. - Falls back to legacy `` when modern bitmap fill is missing or contains non-image bytes. - Adds comprehensive round-trip tests in `crates/odf/src/text/tests_more/page_setup.rs`. --- crates/odf/src/text/import.rs | 101 ++- crates/odf/src/text/kept.rs | 2 +- crates/odf/src/text/package.rs | 138 +++- crates/odf/src/text/tests_more/page_setup.rs | 659 +++++++++++++++++++ 4 files changed, 859 insertions(+), 41 deletions(-) diff --git a/crates/odf/src/text/import.rs b/crates/odf/src/text/import.rs index 486e67a260..fcd98b164e 100644 --- a/crates/odf/src/text/import.rs +++ b/crates/odf/src/text/import.rs @@ -823,8 +823,8 @@ struct Parsed { kept: super::parts::Kept, /// Hidden form controls, kept for the next save. hidden_controls: Vec, - /// The page background picture's bytes and fill. - page_image: Option<(Vec, &'static str)>, + /// The page background picture's bytes, fill, and optional fill image name. + page_image: Option<(Vec, &'static str, Option)>, } /// Hyphenation is a paragraph's in ODF (`fo:hyphenate`) and the document's in WordCraft (as in @@ -911,8 +911,19 @@ fn parse_tracked(bytes: &[u8], paper: (f32, f32)) -> Result { // A frame may point at any entry, as often as it likes: `Pictures` keeps that bounded. pictures.get(&mut z, path) }; - // The page background picture's bytes. - let page_image = pages.doc.page_image.clone().and_then(|(href, fill)| fetch(&href).map(|b| (b, fill))); + // The page background picture's bytes: modern draw:fill="bitmap" preferred when valid, + // falling back to legacy style:background-image if modern is missing or not an image. + let page_image = { + let modern = pages.doc.page_image.clone().and_then(|(href, fill, name)| { + let bytes = fetch(&href)?; + if model::sniff_image(&bytes).is_some() { Some((bytes, fill, name)) } else { None } + }); + modern.or_else(|| { + let (href, fill) = pages.doc.legacy_image.clone()?; + let bytes = fetch(&href)?; + if model::sniff_image(&bytes).is_some() { Some((bytes, fill, None)) } else { None } + }) + }; let objects = (entries.as_slice(), &manifest); // One `text:s` budget for the headers and footers and then the body. let mut spaces_left = MAX_EXTRA_SPACES; @@ -1096,11 +1107,15 @@ pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result doc.settings.odf = Some(craft_wordmodel::OdfLayout { tabs_from_indent }); doc.settings.sum_paragraph_spacing = sum_spacing; // The page background picture (Design › Page Color › Fill Effects › Picture). - if let Some((bytes, fill)) = page_image + if let Some((bytes, fill, name)) = page_image && let Some(ext) = model::sniff_image(&bytes) { let media = doc.add_media(bytes, ext); - doc.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: fill.to_string(), title: String::new() }); + doc.settings.page_picture = Some(craft_wordmodel::PagePicture { + media, + fill_type: fill.to_string(), + title: name.map(|n| n.chars().take(255).collect()).unwrap_or_default(), + }); } if let Some((fmt, props)) = page_doc.notes[0] { (doc.settings.footnote_format, doc.settings.footnote_pr) = (fmt, props); @@ -1172,9 +1187,11 @@ pub(super) struct Pages { #[derive(Clone, Default)] pub(super) struct PageDoc { pub(super) page_color: Option, - /// The first page style's background picture (§17.3 `style:background-image`): its package - /// path and WordCraft's fill for its repeat (tiled, stretched, or centred at its size). - pub(super) page_image: Option<(String, &'static str)>, + /// The first page style's background picture (§17.3 `style:background-image` or §16.42 + /// `draw:fill-image` with `draw:fill="bitmap"`): package path, fill, and optional fill name. + pub(super) page_image: Option<(String, &'static str, Option)>, + /// Legacy fallback background picture from §17.3 `style:background-image`. + pub(super) legacy_image: Option<(String, &'static str)>, /// Footnotes', then endnotes', number format and options. pub(super) notes: [Option<(craft_wordmodel::section::NumFormat, craft_wordmodel::section::NoteProps)>; 2], } @@ -1248,12 +1265,43 @@ struct Layout { attrs: Attrs, /// Its background picture: package path and fill (see [`PageDoc::page_image`]). image: Option<(String, &'static str)>, + /// Its bitmap fill image name (`draw:fill-image-name`). + image_name: Option, + /// Its legacy background picture: package path and fill (§17.3 `style:background-image`). + legacy_image: Option<(String, &'static str)>, columns: Option, column_specs: Vec, header: Band, footer: Band, } +/// The background fill picture and its fill-image name from `page-layout-properties` +/// attributes `a` when modern `draw:fill="bitmap"` is declared (§16.42). +fn page_layout_fill(a: &super::xml::Attrs, fill_images: &HashMap) -> Option<((String, &'static str), String)> { + if get(a, "draw:fill") != Some("bitmap") { + return None; + } + let name = get(a, "draw:fill-image-name")?; + let href = fill_images.get(name)?; + let fill = match get(a, "style:repeat").map(str::trim) { + Some("no-repeat") => "center", + Some("stretch") => "frame", + _ => "tile", + }; + Some(((href.clone(), fill), name.to_string())) +} + +/// The page background picture and fill from legacy `background-image` attributes `a` (§17.3). +fn legacy_background_fill(a: &super::xml::Attrs) -> Option<(String, &'static str)> { + let href = get(a, "xlink:href").map(str::trim).filter(|h| !h.is_empty() && h.len() <= 1024)?; + let fill = match get(a, "style:repeat").map(str::trim) { + Some("no-repeat") => "center", + Some("stretch") => "frame", + _ => "tile", + }; + Some((href.trim_start_matches("./").to_string(), fill)) +} + /// A page stating nothing, `paper` (width, height) in size: no margins (§20.206–20.209 refer to /// XSL's margins, whose initial value is 0; whether it comes with the reference the standard /// doesn't say). @@ -1271,6 +1319,7 @@ fn unstated_page(paper: (f32, f32)) -> SectionProps { fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { let mut layouts: HashMap = HashMap::new(); + let mut fill_images: HashMap = HashMap::new(); let mut cur: Option = None; // Inside a layout's footer style (else its header style). let mut in_footer = false; @@ -1289,6 +1338,12 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { } } "linenumbering-configuration" if q.starts_with("text:") => lines = line_numbering(&a), + // Modern ODF 1.2/1.3 fill image definitions (§16.42 `draw:fill-image` in `office:styles`). + "fill-image" if q.starts_with("draw:") => { + if let (Some(name), Some(href)) = (get(&a, "draw:name"), get(&a, "xlink:href")) { + fill_images.insert(name.to_string(), href.trim_start_matches("./").to_string()); + } + } "page-layout" if q.starts_with("style:") => { cur = get(&a, "style:name").map(String::from); // A layout stating nothing is still one: the defaults' page. @@ -1300,16 +1355,14 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { } // A page background picture (§17.3, in `style:page-layout-properties`): §20.249 // `style:repeat` (repeat is the default) as WordCraft's tile, stretch, or centre. + // Preserved as a fallback when modern `draw:fill="bitmap"` is missing or non-image. "background-image" if q.starts_with("style:") => { - if let (Some(l), Some(href)) = - (cur.as_ref().and_then(|n| layouts.get_mut(n)), get(&a, "xlink:href").map(str::trim).filter(|h| !h.is_empty() && h.len() <= 1024)) - { - let fill = match get(&a, "style:repeat").map(str::trim) { - Some("no-repeat") => "center", - Some("stretch") => "frame", - _ => "tile", - }; - l.image = Some((href.trim_start_matches("./").to_string(), fill)); + if let Some(l) = cur.as_ref().and_then(|n| layouts.get_mut(n)) { + let leg = legacy_background_fill(&a); + if l.image.is_none() { + l.image = leg.clone(); + } + l.legacy_image = leg; } } // A band whose height isn't stated is LibreOffice's default, 0.5 cm (measured; see @@ -1327,6 +1380,10 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { } "page-layout-properties" => { if let Some(l) = cur.as_ref().and_then(|n| layouts.get_mut(n)) { + if let Some((img, name)) = page_layout_fill(&a, &fill_images) { + l.image = Some(img); + l.image_name = Some(name); + } l.attrs = a; } } @@ -1380,14 +1437,18 @@ fn read_pages(xml: &[u8], paper: (f32, f32)) -> Pages { }); let mut pages = Pages { doc, next: nexts, ..Default::default() }; for (name, layout, header, footer) in masters { - let Some(Layout { attrs: a, columns: cols, column_specs, header: hb, footer: fb, image }) = layouts.get(&layout) else { continue }; + let Some(Layout { attrs: a, columns: cols, column_specs, header: hb, footer: fb, image, image_name, legacy_image }) = layouts.get(&layout) + else { + continue; + }; // What a layout leaves unsaid: the default paper, and no margins. let mut sec = unstated_page(paper); apply_layout(a, &mut sec); sec.line_numbers.clone_from(&lines); if pages.first.is_none() { pages.doc.page_color = get(a, "fo:background-color").and_then(model::parse_color); - pages.doc.page_image.clone_from(image); + pages.doc.page_image = image.as_ref().map(|(href, fill)| (href.clone(), *fill, image_name.clone())); + pages.doc.legacy_image.clone_from(legacy_image); } // ODF starts a header at the page margin and the text after the header's band; Word // measures the header's distance and the text's margin from the edge. How the band's diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index e9efebdec3..da49b30541 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -307,7 +307,7 @@ fn with_as_read( /// graphic style (the `Graphics` and `Frame` styles drawings derive from) is the file's: its /// drawings written as read derive from it, and those written from the model derived from it /// when read (what WordCraft models of it is in theirs). -fn drawing_def(xml: &str) -> bool { +pub(super) fn drawing_def(xml: &str) -> bool { xml.split('>').next().unwrap_or("").starts_with(", } /// The package files the file's own definitions refer to, and those the markup written as read -/// links to (`used`), written as read with them (added to `files` and `manifest` where no file -/// `taken` has the path). A picture only an edited paragraph showed isn't written. +/// links to (`w.kept_files_used`, `w.kept_used`), written as read with them (added to `files` and +/// `manifest` where no file `taken` has the path). A picture only an edited paragraph showed isn't written. fn with_kept_files( + doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, - used: &std::collections::BTreeSet, + styles: &str, + w: &Writer, taken: &dyn Fn(&str) -> bool, files: &mut Vec<(String, std::sync::Arc>)>, manifest: &mut String, ) { let Some(k) = kept else { return }; - let mut wanted = used.clone(); - for d in k.defs.values() { + let mut wanted = w.kept_files_used.clone(); + let pages_kept = k.pages_as_read(doc); + let styles_kept = k.styles_as_read(doc); + for (key, d) in &k.defs { + if !pages_kept && (key.starts_with("sauto:") || key.starts_with("master:")) { + continue; + } + if key.starts_with("common:") { + // The file's definition is written back whole (`styles_as_read`, non-`draw:` + // definitions win), or this one is restored for markup naming it. WordCraft's own + // definition takes a drawing definition's place: its href is no longer used. + let written = if styles_kept { + !(super::kept::drawing_def(d) && super::kept::defined(styles, d)) + } else { + key.strip_prefix("common:").is_some_and(|n| w.kept_used.1.contains_key(n)) && !super::kept::defined(styles, d) + }; + if !written { + continue; + } + } super::kept::hrefs(d, &mut wanted); } // A file linked, or one in a folder linked (an object's). @@ -1234,7 +1254,7 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { w.objects.iter().map(|(d, _, _)| d).chain(w.object_dirs.iter().map(|(d, _)| d)).map(|d| format!("{}/", d.trim_end_matches('/'))).collect(); let taken = |p: &str| w.pictures.iter().any(|(n, _, _)| n == p) || dirs.iter().any(|d| p.starts_with(d.as_str())); let mut kept_files: Vec<_> = kept_files.into_iter().filter(|(p, _)| !taken(p)).collect(); - with_kept_files(kept, &w.kept_files_used, &taken, &mut kept_files, &mut manifest); + with_kept_files(doc, kept, &styles, &w, &taken, &mut kept_files, &mut manifest); for (path, mime) in &kept_entries { if (path.ends_with('/') && kept_files.iter().any(|(p, _)| p.starts_with(path.as_str()))) || kept_files.iter().any(|(p, _)| p == path) { manifest.push_str(&format!("\n", x(path), x(mime))); @@ -1384,43 +1404,121 @@ fn variables(doc: &Document) -> std::collections::BTreeSet { out } +/// A `draw:fill-image` definition's name and picture path, when `xml` starts with one. +fn fill_image_of(xml: &str) -> Option<(String, String)> { + let tag = xml.split('>').next()?; + if !tag.trim_start_matches('<').starts_with("draw:fill-image") { + return None; + } + let name = super::kept::raw_attr(tag, "draw:name").map(super::kept::attr_text)?; + let href = super::kept::raw_attr(tag, "xlink:href").map(super::kept::attr_text)?; + Some((name.into_owned(), href.into_owned())) +} + +/// `name` as a `draw:name` (§16.42) may read: an NCName — letters, digits, `-`, `_` and `.`, not +/// starting with `-`, `.` or a digit. Characters outside those are turned into `_`. +fn fill_image_name(name: &str) -> String { + let mut out = String::with_capacity(name.len().min(255)); + for c in name.chars().take(255) { + let ok = c.is_alphanumeric() || c == '-' || c == '_' || c == '.'; + let start_ok = c.is_alphabetic() || c == '_'; + if out.is_empty() { + out.push(if start_ok { c } else { '_' }); + } else { + out.push(if ok { c } else { '_' }); + } + } + if out.is_empty() { "PageBackground".to_string() } else { out } +} + /// `styles` with the page background picture (Design › Page Color › Fill Effects › Picture) in -/// each page layout (§17.3 `style:background-image`, first in `style:page-layout-properties`), -/// the picture written into the package by `w`: tiled, stretched, or centred at its own size -/// (§20.249 `style:repeat`). -fn page_background(doc: &Document, w: &mut Writer, styles: String) -> String { +/// each page layout (§17.3 `style:background-image`, first in `style:page-layout-properties`, and +/// modern ODF 1.2/1.3 §16.42 `draw:fill="bitmap"` with `draw:fill-image`), the picture written +/// into the package by `w`: tiled, stretched, or centred at its own size (§20.249 `style:repeat`). +fn page_background(doc: &Document, w: &mut Writer, mut styles: String) -> String { let Some(pic) = doc.settings.page_picture.as_ref() else { return styles }; let Some(data) = doc.media.get(&pic.media) else { return styles }; let Some(ext) = model::sniff_image(data) else { return styles }; - let name = format!("Pictures/page-background.{ext}"); - if !w.pictures.iter().any(|(n, _, _)| *n == name) { - w.pictures.push((name.clone(), data.clone(), model::mime_of(ext).to_string())); + let kept = doc.kept.of("odt"); + // A kept package file holding these bytes is this picture already: its path is reused, so + // saving what was opened doesn't add a copy on every save. + let same_kept = |path: &str| kept.is_some_and(|k| k.files.get(path).is_some_and(|b| b.as_slice() == data.as_slice())); + let mut name = format!("Pictures/page-background.{ext}"); + let mut pic_n = 1; + while (w.reserved.contains(&name) && !same_kept(&name)) || w.pictures.iter().any(|(n, d, _)| n == &name && d.as_slice() != data.as_slice()) { + name = format!("Pictures/page-background-{pic_n}.{ext}"); + pic_n += 1; } let repeat = match pic.fill_type.to_ascii_lowercase().as_str() { "tile" => "repeat", "center" => "no-repeat", _ => "stretch", }; - let el = format!( + // The fill-image definitions already written, by name, once: renaming looks each up rather + // than scanning every definition for it (a hostile file names thousands alike). + let mut fill_images: std::collections::HashMap = std::collections::HashMap::new(); + for d in w.kept_defs.values() { + if let Some((n, h)) = fill_image_of(d) { + fill_images.insert(n, h); + } + } + for (i, _) in styles.match_indices("", x(&fill_name), x(&name)); + if !super::kept::defined(&styles, &fill_image_def) { + styles = styles.replacen("", &format!("{fill_image_def}"), 1); + } + let bg_el = format!( "", x(&name) ); + let fill_attrs = format!(" draw:fill=\"bitmap\" draw:fill-image-name=\"{}\" style:repeat=\"{repeat}\"", x(&fill_name)); + // After each layout's properties' opening tag. - let mut out = String::with_capacity(styles.len() + el.len() * 4); + let mut out = String::with_capacity(styles.len() + bg_el.len() * 4); let mut rest = styles.as_str(); while let Some(at) = rest.find("')).map(|e| at + e) else { break }; let self_closing = rest.get(end.saturating_sub(1)..end) == Some("/"); if self_closing { - out.push_str(rest.get(..end.saturating_sub(1)).unwrap_or_default()); + let before_slash = end.saturating_sub(1); + out.push_str(rest.get(..tag_start).unwrap_or_default()); + out.push_str(&fill_attrs); + out.push_str(rest.get(tag_start..before_slash).unwrap_or_default()); out.push('>'); - out.push_str(&el); + out.push_str(&bg_el); out.push_str(""); } else { - out.push_str(rest.get(..=end).unwrap_or_default()); - out.push_str(&el); + out.push_str(rest.get(..tag_start).unwrap_or_default()); + out.push_str(&fill_attrs); + out.push_str(rest.get(tag_start..=end).unwrap_or_default()); + out.push_str(&bg_el); } - rest = rest.get(end + 1..).unwrap_or_default(); + rest = rest.get(end.saturating_add(1)..).unwrap_or_default(); } out.push_str(rest); out diff --git a/crates/odf/src/text/tests_more/page_setup.rs b/crates/odf/src/text/tests_more/page_setup.rs index af687bd454..79b74f2487 100644 --- a/crates/odf/src/text/tests_more/page_setup.rs +++ b/crates/odf/src/text/tests_more/page_setup.rs @@ -233,3 +233,662 @@ fn a_page_borders_padding_keeps_the_text_where_it_was() { } assert_eq!(s.page_borders.and_then(|b| b.left).map(|b| (b.width, b.space)), Some((3.0, 24.0))); } + +/// An ODT document with a page background and an active header containing a logo +/// preserves the page background (both modern draw:fill and legacy fallback) and the header logo (#5803). +#[test] +fn background_plus_small_header_logo_keeps_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let logo_png = { + let img = image::RgbImage::from_pixel(4, 4, image::Rgb([30, 200, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: "PageBackground".into() }); + let logo_media = d.add_media(logo_png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("Company {}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: logo_media, + w: 50.0, + h: 20.0, + alt: "Logo".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![ + craft_wordmodel::para::Run { len: 8, props: Default::default() }, + craft_wordmodel::para::Run { len: craft_wordmodel::para::OBJ.len_utf8(), props: Default::default() }, + ]; + d.parts.insert( + 1, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + d.last_section.headers.default = Some(1); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + // Verify both draw:fill="bitmap" and style:background-image are emitted consistently + assert!(s.contains("draw:fill=\"bitmap\""), "page layout must declare draw:fill=\"bitmap\": {s}"); + assert!(s.contains("style:background-image"), "legacy background-image fallback must be present: {s}"); + assert!(s.contains(""# + ); + let content = format!( + r#"Cell test"# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/cell-bg.png", &png)]); + let d = import(&pkg).unwrap(); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "cell style background-image must survive on kept path: {s}"); + assert!(s.contains("Pictures/cell-bg.png"), "cell background picture path must survive: {s}"); +} + +/// An ODT document with a text-only header retains its legacy page background image +/// and writes the image into the package archive. +#[test] +fn text_header_keeps_page_background_picture() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = "Header text".into(); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 1, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + d.last_section.headers.default = Some(1); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "page background must be written when header has no picture: {s}"); + assert!(s.contains("Pictures/page-background.png")); +} + +/// Every picture written into the ODT zip archive must be referenced by styles.xml or content.xml (#5803). +#[test] +fn no_unreferenced_images_left_in_package() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let ns = crate::text::tests::NS_T; + let nsd = r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:xlink="http://www.w3.org/1999/xlink""#; + // An imported ODT with modern draw:fill="bitmap" and draw:fill-image + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/original.png", &png)]); + let mut d = import(&pkg).unwrap(); + + // Now insert a header picture into the document, changing page setup + let header_media = d.add_media(png.clone(), "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 50.0, + alt: "Header logo".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 1, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + d.last_section.headers.default = Some(1); + + let saved = export(&d).unwrap(); + let styles_xml = crate::text::tests::entry(&saved, "styles.xml"); + let content_xml = crate::text::tests::entry(&saved, "content.xml"); + + // Verify modern draw:fill bitmap and legacy style:background-image resolve to the same image target + let fill_name = + styles_xml.split("draw:fill-image-name=\"").nth(1).and_then(|s| s.split('"').next()).expect("styles.xml must contain draw:fill-image-name"); + let draw_fill_pattern = format!(" = (0..archive.len()).map(|i| archive.by_index(i).unwrap().name().unwrap().to_string()).collect(); + + let pic_files: Vec<&String> = file_names.iter().filter(|n| n.starts_with("Pictures/")).collect(); + assert!(!pic_files.is_empty(), "package should contain picture files"); + + for pic in pic_files { + let is_referenced = styles_xml.contains(pic.as_str()) || content_xml.contains(pic.as_str()); + assert!(is_referenced, "package image {pic} must be referenced in styles.xml or content.xml: styles={styles_xml}"); + } +} + +/// An inactive header (e.g. `first` when `title_page` is false, or `even` when `even_odd_headers` +/// is false) containing an image does NOT suppress the page background picture (#5803). +#[test] +fn inactive_header_picture_does_not_suppress_page_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + + let header_media = d.add_media(png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 100.0, + alt: "Inactive header picture".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 100, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + + // Point headers.first to the header with picture, but title_page is FALSE. + d.last_section.headers.first = Some(100); + d.last_section.title_page = false; + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "background-image must be preserved when header picture is in an inactive header: {s}"); + assert!(s.contains("Pictures/page-background.png")); +} + +/// A noninitial continuous section header containing a picture does NOT produce a master page +/// and does not suppress the page background (#5803). +#[test] +fn continuous_section_header_picture_does_not_suppress_page_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + + // Body with a first section ending paragraph + let mut p1 = craft_wordmodel::Paragraph::new(); + p1.text = "First paragraph in section 1".into(); + p1.runs = vec![craft_wordmodel::para::Run { len: p1.text.len(), props: Default::default() }]; + p1.section = Some(Box::new(craft_wordmodel::SectionProps::default())); + d.body.push(craft_wordmodel::para_block(p1)); + + // Second section (last_section) is continuous + let header_media = d.add_media(png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 100.0, + alt: "Continuous section header picture".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 200, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + + d.last_section.start = craft_wordmodel::section::SectionStart::Continuous; + d.last_section.headers.default = Some(200); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!( + s.contains("style:background-image"), + "page background must not be suppressed by continuous section header that emits no master page: {s}" + ); + assert!(s.contains("Pictures/page-background.png")); +} + +/// A non-continuous `last_section` without any body blocks following the section break +/// does not produce an exported page and does not suppress the page background (#5803). +#[test] +fn trailing_empty_last_section_header_picture_does_not_suppress_page_background() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let bg_media = d.add_media(png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: bg_media, fill_type: "frame".into(), title: String::new() }); + + // Body with a single paragraph ending section 1 (nothing follows it) + let mut p1 = craft_wordmodel::Paragraph::new(); + p1.text = "Sole paragraph ending section 1".into(); + p1.runs = vec![craft_wordmodel::para::Run { len: p1.text.len(), props: Default::default() }]; + p1.section = Some(Box::new(craft_wordmodel::SectionProps::default())); + d.body.push(craft_wordmodel::para_block(p1)); + + // last_section is NextPage and has a header with a picture, but has no blocks following + let header_media = d.add_media(png, "png"); + let mut hp = craft_wordmodel::Paragraph::new(); + hp.text = format!("{}", craft_wordmodel::para::OBJ); + hp.objects.push(craft_wordmodel::InlineObject::Image { + media: header_media, + w: 100.0, + h: 100.0, + alt: "Unused trailing section header picture".into(), + float: Default::default(), + crop: [0.0; 4], + fx: Default::default(), + ole: None, + }); + hp.runs = vec![craft_wordmodel::para::Run { len: hp.text.len(), props: Default::default() }]; + d.parts.insert( + 300, + craft_wordmodel::Part { kind: craft_wordmodel::PartKind::Header, blocks: vec![craft_wordmodel::para_block(hp)], body: Default::default() }, + ); + + d.last_section.start = craft_wordmodel::section::SectionStart::NextPage; + d.last_section.headers.default = Some(300); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("style:background-image"), "page background must not be suppressed by an unexported trailing last_section header: {s}"); + assert!(s.contains("Pictures/page-background.png")); +} + +/// When a page background picture is replaced with a new image while retaining an existing +/// fill-image name that belongs to a graphic style, export allocates a distinct fill name, +/// references it in page layouts, and preserves the retained definition and image (#5803). +#[test] +fn replaced_page_picture_allocates_distinct_fill_name_and_keeps_retained_def() { + let orig_png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([100, 200, 100])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let new_png = { + let img = image::RgbImage::from_pixel(4, 8, image::Rgb([200, 100, 200])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let ns = crate::text::tests::NS_T; + let nsd = "xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\""; + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text"# + ); + let pkg = + crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/original.png", &orig_png)]); + let mut d = import(&pkg).unwrap(); + let new_media = d.add_media(new_png.clone(), "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media: new_media, fill_type: "stretch".into(), title: "SharedBg".into() }); + + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains(r#" Vec { + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut out: Vec = + (0..archive.len()).map(|i| archive.by_index(i).unwrap().name().unwrap().to_string()).filter(|n| n.starts_with("Pictures/")).collect(); + out.sort(); + out +} + +/// Saving a page background picture and opening it again keeps one picture and one fill-image +/// definition: the kept file is reused while its bytes are the document's, not renamed (#5856). +#[test] +fn page_background_round_trips_do_not_grow_the_package() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: "frame".into(), title: "PageBackground".into() }); + let mut current = d; + for generation in 1..=4 { + let saved = export(¤t).unwrap(); + let styles = crate::text::tests::entry(&saved, "styles.xml"); + assert_eq!(styles.matches(""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/original.png", &png)]); + let d = import(&pkg).unwrap(); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert_eq!(s.matches(""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/para.png", &png)]); + let d = import(&pkg).unwrap(); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains("Pictures/para.png"), "the style's background reference must stay: {s}"); + assert_eq!(picture_paths(&saved), ["Pictures/para.png"], "the referenced picture must be written"); +} + +/// A DOCX texture name (`o:title`, "Blue tissue paper") is not an XML NCName: the fill image it +/// names is written with one (#5856). +#[test] +fn a_texture_name_is_written_as_an_ncname() { + let png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let mut d = Document::new(); + let media = d.add_media(png, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: "frame".into(), title: "Blue tissue paper".into() }); + let saved = export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains(r#""#)); + } + let styles = format!( + r#"{defs}"# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[ + ("content.xml", content.as_bytes()), + ("styles.xml", styles.as_bytes()), + ("Pictures/bg.png", &bg), + ("Pictures/other.png", &other), + ]); + let mut d = import(&pkg).unwrap(); + // The user replaces the picture: its fill-image name now meets every kept name. + let media = d.add_media(replacement, "png"); + d.settings.page_picture = Some(craft_wordmodel::PagePicture { media, fill_type: "stretch".into(), title: "X".into() }); + let start = std::time::Instant::now(); + let saved = export(&d).unwrap(); + assert!(start.elapsed() < std::time::Duration::from_secs(5), "export took {:?}", start.elapsed()); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(s.contains(r#"` if present and valid (#1784). +#[test] +fn legacy_background_fallback_when_modern_bitmap_missing() { + let legacy_png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([10, 150, 20])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let ns = crate::text::tests::NS_T; + let nsd = r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:xlink="http://www.w3.org/1999/xlink""#; + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = + crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/legacy.png", &legacy_png)]); + let d = import(&pkg).unwrap(); + let pic = d.settings.page_picture.as_ref().expect("legacy fallback background picture must be imported"); + assert_eq!(d.media.get(&pic.media).map(|b| b.as_slice()), Some(legacy_png.as_slice())); + assert_eq!(pic.fill_type, "frame"); +} + +/// When modern `draw:fill="bitmap"` references a file with non-image bytes, +/// import falls back to legacy `` if present and valid (#1784). +#[test] +fn legacy_background_fallback_when_modern_bitmap_non_image() { + let legacy_png = { + let img = image::RgbImage::from_pixel(8, 4, image::Rgb([10, 150, 20])); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + }; + let corrupt_data = b"This is plain text and definitely not a valid image format."; + let ns = crate::text::tests::NS_T; + let nsd = r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:xlink="http://www.w3.org/1999/xlink""#; + let styles = format!( + r#""# + ); + let content = format!( + r#"Body text."# + ); + let pkg = crate::text::tests::zip_of(&[ + ("content.xml", content.as_bytes()), + ("styles.xml", styles.as_bytes()), + ("Pictures/corrupt.bin", corrupt_data), + ("Pictures/legacy.png", &legacy_png), + ]); + let d = import(&pkg).unwrap(); + let pic = d.settings.page_picture.as_ref().expect("legacy fallback background picture must be imported when modern is non-image"); + assert_eq!(d.media.get(&pic.media).map(|b| b.as_slice()), Some(legacy_png.as_slice())); + assert_eq!(pic.fill_type, "frame"); +} From a57f393d974be3c865ea20b20139f6cc4721b95a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:21:19 -0800 Subject: [PATCH 024/144] craft-video: the ffmpeg MJPEG round-trip test encodes the same picture every run we_decode_what_ffmpeg_encodes_to_what_ffmpeg_decodes built its input with ffmpeg's gradients source, which picks random colors on every run, so the agreement it measured changed from run to run. On one CI run the 4:2:0 case scored 30.5 dB against the 38 dB floor. The test now writes the file's own picture(67, 41, 3) as raw RGB and feeds it to ffmpeg through rawvideo, for both the plain and the default-tables encodes. --- crates/video/tests/mjpeg.rs | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/crates/video/tests/mjpeg.rs b/crates/video/tests/mjpeg.rs index d83b61438c..fcd9cacd62 100644 --- a/crates/video/tests/mjpeg.rs +++ b/crates/video/tests/mjpeg.rs @@ -150,12 +150,14 @@ fn we_decode_what_ffmpeg_encodes_to_what_ffmpeg_decodes() { let Some(ff) = craft_media_testkit::ffmpeg() else { return }; let dir = craft_media_testkit::fixture_subdir("mjpeg"); let s = |p: &Path| p.to_str().expect("path").to_string(); + // the same input every run: ffmpeg's own test sources draw random colors + let input = dir.join("input.rgb"); + std::fs::write(&input, picture(67, 41, 3)).expect("write"); + let input = s(&input); + let source = ["-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "67x41", "-i", input.as_str()]; for (name, pix_fmt, rgb_pix, channels) in [("420", "yuvj420p", "rgb24", 3), ("422", "yuvj422p", "rgb24", 3), ("444", "yuvj444p", "rgb24", 3)] { let jpg = dir.join(format!("{name}.jpg")); - ffmpeg( - &ff, - &["-f", "lavfi", "-i", "gradients=size=67x41:rate=1", "-frames:v", "1", "-c:v", "mjpeg", "-pix_fmt", pix_fmt, "-q:v", "2", &s(&jpg)], - ); + ffmpeg(&ff, &[&source[..], &["-frames:v", "1", "-c:v", "mjpeg", "-pix_fmt", pix_fmt, "-q:v", "2", &s(&jpg)]].concat()); let reference = dir.join(format!("{name}.raw")); ffmpeg(&ff, &["-i", &s(&jpg), "-f", "rawvideo", "-pix_fmt", rgb_pix, &s(&reference)]); let packet = std::fs::read(&jpg).expect("read"); @@ -170,23 +172,7 @@ fn we_decode_what_ffmpeg_encodes_to_what_ffmpeg_decodes() { let plain = dir.join(format!("{name}_default_tables.jpg")); ffmpeg( &ff, - &[ - "-f", - "lavfi", - "-i", - "gradients=size=67x41:rate=1", - "-frames:v", - "1", - "-c:v", - "mjpeg", - "-pix_fmt", - pix_fmt, - "-q:v", - "2", - "-huffman", - "default", - &s(&plain), - ], + &[&source[..], &["-frames:v", "1", "-c:v", "mjpeg", "-pix_fmt", pix_fmt, "-q:v", "2", "-huffman", "default", &s(&plain)]].concat(), ); let stripped = without_huffman_tables(&std::fs::read(&plain).expect("read")); let with_tables = Decoder::new().decode(&std::fs::read(&plain).expect("read")).expect("decode"); From 0b0e5accd59f3347bcb4c19d0561f09932366050 Mon Sep 17 00:00:00 2001 From: StDenis1980 <288736242+StDenis1980@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:37:04 +0100 Subject: [PATCH 025/144] docx: set_application_name for apps that embed the writer An app that ships the writer under its own name names itself in docProps/app.xml (); "WordCraft" until set. Co-Authored-By: Claude Opus 5.5 --- crates/docx/src/lib.rs | 13 +++++++++++++ crates/docx/src/write/settings.rs | 2 +- crates/docx/tests/application_name.rs | 19 +++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 crates/docx/tests/application_name.rs diff --git a/crates/docx/src/lib.rs b/crates/docx/src/lib.rs index 7f47d948b3..c3c3e8df3d 100644 --- a/crates/docx/src/lib.rs +++ b/crates/docx/src/lib.rs @@ -20,6 +20,19 @@ mod custom; mod flat; mod fonts; mod package; + +static APPLICATION_NAME: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Names the application written to `docProps/app.xml` (``), for an app that +/// embeds this writer under its own name; "WordCraft" until set. Only the first call counts. +pub fn set_application_name(name: &str) { + let _ = APPLICATION_NAME.set(name.to_owned()); +} + +/// The application `docProps/app.xml` names (see [`set_application_name`]). +pub fn application_name() -> &'static str { + APPLICATION_NAME.get().map_or("WordCraft", String::as_str) +} mod read; mod smart_art; #[cfg(test)] diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index 18f9f8239f..3371986c4f 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -349,7 +349,7 @@ pub(super) fn app_xml(doc: &Document) -> Vec { ("xmlns:vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"), ], ); - w.leaf("Application", &[], "WordCraft"); + w.leaf("Application", &[], crate::application_name()); w.leaf("Words", &[], &doc.word_count().to_string()); w.leaf("Paragraphs", &[], &doc.paragraph_count().to_string()); w.leaf("DocSecurity", &[], "0"); diff --git a/crates/docx/tests/application_name.rs b/crates/docx/tests/application_name.rs new file mode 100644 index 0000000000..1973e63ae3 --- /dev/null +++ b/crates/docx/tests/application_name.rs @@ -0,0 +1,19 @@ +//! An app that embeds the writer names itself in `docProps/app.xml` (its own test binary: the +//! name is set once per process). + +use std::io::Read; + +#[test] +fn the_embedding_app_names_itself_in_app_xml() { + assert_eq!(craft_docx::application_name(), "WordCraft", "the default"); + craft_docx::set_application_name("Example Writer"); + craft_docx::set_application_name("Other"); + assert_eq!(craft_docx::application_name(), "Example Writer", "only the first call counts"); + let mut d = craft_wordmodel::Document::new(); + d.body = vec![craft_wordmodel::para_block(craft_wordmodel::Paragraph::with_text("Text", Default::default()))]; + let bytes = craft_docx::write(&d).unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); + let mut app = String::new(); + z.by_name("docProps/app.xml").unwrap().read_to_string(&mut app).unwrap(); + assert!(app.contains("Example Writer"), "{app}"); +} From ab87149855cf6cf4c16b23dc9a207929d21fd2ea Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 16 Nov 2026 18:51:40 +0500 Subject: [PATCH 026/144] craft-csv: decode Excel's character escapes in SYLK text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Excel writes a character outside ASCII in a SYLK text value as ESC N and one byte, the character's ISO 6937 code less 0x80; a diacritic's code is followed by the letter it goes on. The reader kept those bytes, so Größe für Köln opened as GrNHoN{e fNHur KNHoln (storytold/gridcraft#4321). Text values now decode them: a diacritic and letter become the precomposed letter (or the letter and its combining mark when Unicode has no single character), a spacing code its character; a code ISO 6937 doesn't define is kept as written. --- crates/csv/src/sylk.rs | 146 ++++++++++++++++++++++++++++++++++++++- crates/csv/tests/sylk.rs | 25 +++++++ 2 files changed, 168 insertions(+), 3 deletions(-) diff --git a/crates/csv/src/sylk.rs b/crates/csv/src/sylk.rs index f9a74405a8..d8c0ebec52 100644 --- a/crates/csv/src/sylk.rs +++ b/crates/csv/src/sylk.rs @@ -219,12 +219,13 @@ fn position(arg: &str, max: u32) -> Option { arg.trim().parse::().ok().filter(|n| (1..=max).contains(n)).map(|n| n - 1) } -/// A `K` value: `"text"` (everything between the first and the last quote, as written), a -/// boolean, a number, or other text (an error value when it starts with `#`). +/// A `K` value: `"text"` (everything between the first and the last quote, with Excel's +/// character escapes decoded), a boolean, a number, or other text (an error value when it starts +/// with `#`). fn parse_value(arg: &str) -> Value { if let Some(text) = arg.strip_prefix('"') { let text = text.strip_suffix('"').unwrap_or(text); - return Value::Text(text.to_string()); + return Value::Text(decode_escapes(text)); } if arg.eq_ignore_ascii_case("TRUE") || arg.eq_ignore_ascii_case("FALSE") { return Value::Bool(arg.eq_ignore_ascii_case("TRUE")); @@ -238,6 +239,145 @@ fn parse_value(arg: &str) -> Value { } } +/// ISO 6937's diacritics (codes 0xC1–0xCF): each code, its combining mark, and the letters it +/// composes with, as pairs of letter and precomposed letter (from Unicode's canonical composition). +const ISO6937_DIACRITICS: [(u8, char, &str); 13] = [ + (0xC1, '\u{0300}', "AÀaàEÈeèIÌiìNǸnǹOÒoòUÙuùWẀwẁYỲyỳ"), // grave + (0xC2, '\u{0301}', "AÁaáCĆcćEÉeéGǴgǵIÍiíKḰkḱLĹlĺMḾmḿNŃnńOÓoóPṔpṕRŔrŕSŚsśUÚuúWẂwẃYÝyýZŹzź"), // acute + (0xC3, '\u{0302}', "AÂaâCĈcĉEÊeêGĜgĝHĤhĥIÎiîJĴjĵOÔoôSŜsŝUÛuûWŴwŵYŶyŷZẐzẑ"), // circumflex + (0xC4, '\u{0303}', "AÃaãEẼeẽIĨiĩNÑnñOÕoõUŨuũVṼvṽYỸyỹ"), // tilde + (0xC5, '\u{0304}', "AĀaāEĒeēGḠgḡIĪiīOŌoōUŪuūYȲyȳ"), // macron + (0xC6, '\u{0306}', "AĂaăEĔeĕGĞgğIĬiĭOŎoŏUŬuŭ"), // breve + (0xC7, '\u{0307}', "AȦaȧBḂbḃCĊcċDḊdḋEĖeėFḞfḟGĠgġHḢhḣIİMṀmṁNṄnṅOȮoȯPṖpṗRṘrṙSṠsṡTṪtṫWẆwẇXẊxẋYẎyẏZŻzż"), // dot above + (0xC8, '\u{0308}', "AÄaäEËeëHḦhḧIÏiïOÖoötẗUÜuüWẄwẅXẌxẍYŸyÿ"), // diaeresis + (0xCA, '\u{030a}', "AÅaåUŮuůwẘyẙ"), // ring + (0xCB, '\u{0327}', "CÇcçDḐdḑEȨeȩGĢgģHḨhḩKĶkķLĻlļNŅnņRŖrŗSŞsşTŢtţ"), // cedilla + (0xCD, '\u{030b}', "OŐoőUŰuű"), // double acute + (0xCE, '\u{0328}', "AĄaąEĘeęIĮiįOǪoǫUŲuų"), // ogonek + (0xCF, '\u{030c}', "AǍaǎCČcčDĎdďEĚeěGǦgǧHȞhȟIǏiǐjǰKǨkǩLĽlľNŇnňOǑoǒRŘrřSŠsšTŤtťUǓuǔZŽzž"), // caron +]; + +/// ISO 6937's spacing characters above ASCII (codes 0xA1–0xFE that aren't diacritics). +const ISO6937_SPACING: [(u8, char); 71] = [ + (0xA1, '¡'), + (0xA2, '¢'), + (0xA3, '£'), + (0xA5, '¥'), + (0xA7, '§'), + (0xA8, '¤'), + (0xA9, '‘'), + (0xAA, '“'), + (0xAB, '«'), + (0xAC, '←'), + (0xAD, '↑'), + (0xAE, '→'), + (0xAF, '↓'), + (0xB0, '°'), + (0xB1, '±'), + (0xB2, '²'), + (0xB3, '³'), + (0xB4, '×'), + (0xB5, 'µ'), + (0xB6, '¶'), + (0xB7, '·'), + (0xB8, '÷'), + (0xB9, '’'), + (0xBA, '”'), + (0xBB, '»'), + (0xBC, '¼'), + (0xBD, '½'), + (0xBE, '¾'), + (0xBF, '¿'), + (0xD0, '―'), + (0xD1, '¹'), + (0xD2, '®'), + (0xD3, '©'), + (0xD4, '™'), + (0xD5, '♪'), + (0xD6, '¬'), + (0xD7, '¦'), + (0xDC, '⅛'), + (0xDD, '⅜'), + (0xDE, '⅝'), + (0xDF, '⅞'), + (0xE0, 'Ω'), + (0xE1, 'Æ'), + (0xE2, 'Đ'), + (0xE3, 'ª'), + (0xE4, 'Ħ'), + (0xE6, 'IJ'), + (0xE7, 'Ŀ'), + (0xE8, 'Ł'), + (0xE9, 'Ø'), + (0xEA, 'Œ'), + (0xEB, 'º'), + (0xEC, 'Þ'), + (0xED, 'Ŧ'), + (0xEE, 'Ŋ'), + (0xEF, 'ʼn'), + (0xF0, 'ĸ'), + (0xF1, 'æ'), + (0xF2, 'đ'), + (0xF3, 'ð'), + (0xF4, 'ħ'), + (0xF5, 'ı'), + (0xF6, 'ij'), + (0xF7, 'ŀ'), + (0xF8, 'ł'), + (0xF9, 'ø'), + (0xFA, 'œ'), + (0xFB, 'ß'), + (0xFC, 'þ'), + (0xFD, 'ŧ'), + (0xFE, 'ŋ'), +]; + +/// Text with Excel's SYLK character escapes decoded. Excel writes a character outside ASCII as +/// `ESC N` and one byte, the character's ISO 6937 code less 0x80. A diacritic's code is followed +/// by the letter it goes on (`ESC N H o` is `ö`, `ESC N {` is `ß`). A code ISO 6937 doesn't define, +/// or an `ESC` that isn't followed by `N` and a code, is kept as written. +fn decode_escapes(text: &str) -> String { + if !text.contains('\u{1b}') { + return text.to_string(); + } + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars(); + while let Some(c) = chars.next() { + let mut ahead = chars.clone(); + let code = (c == '\u{1b}' && ahead.next() == Some('N')) + .then(|| ahead.next()) + .flatten() + .and_then(|b| u8::try_from(b).ok()) + .filter(|b| (0x20..0x80).contains(b)); + let Some(code) = code.map(|b| b + 0x80) else { + out.push(c); + continue; + }; + if let Some(&(_, mark, pairs)) = ISO6937_DIACRITICS.iter().find(|(d, _, _)| *d == code) { + // The letter it goes on: precomposed where Unicode has the pair, else letter and mark. + let Some(base) = ahead.next() else { + out.push(c); + continue; + }; + let letters: Vec = pairs.chars().collect(); + match letters.chunks(2).find(|p| p.first() == Some(&base)).and_then(|p| p.get(1)) { + Some(&composed) => out.push(composed), + None => { + out.push(base); + out.push(mark); + } + } + } else if let Some(&(_, ch)) = ISO6937_SPACING.iter().find(|(s, _)| *s == code) { + out.push(ch); + } else { + out.push(c); + continue; + } + chars = ahead; + } + out +} + /// One part of an R1C1 reference: `R`/`C` followed by an absolute number, a bracketed offset or /// nothing (the cell's own row or column). #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/csv/tests/sylk.rs b/crates/csv/tests/sylk.rs index 7635089832..b91d074272 100644 --- a/crates/csv/tests/sylk.rs +++ b/crates/csv/tests/sylk.rs @@ -115,3 +115,28 @@ fn survives_huge_relative_offsets_and_width_floods() { let _ = read(&b); } } + +#[test] +fn decodes_excels_character_escapes_in_text() { + // storytold/gridcraft#4321: Excel writes `Größe für Köln` with `ESC N` escapes (ISO 6937 codes + // less 0x80: `H` is the diaeresis, put on the next letter; `{` is ß). + let file = "ID;PWXL;N;E\r\nC;Y1;X1;K\"Gr\u{1b}NHo\u{1b}N{e f\u{1b}NHur K\u{1b}NHoln\"\r\nC;Y2;X1;K\"Plain ASCII 123\"\r\n\ + C;Y3;X1;K\"\u{1b}NBe \u{1b}NAa \u{1b}NCa \u{1b}NKc \u{1b}NOs \u{1b}NMo \u{1b}NJa \u{1b}NDn\"\r\n\ + C;Y4;X1;K\"\u{1b}NAa \u{1b}NAZ\"\r\nC;Y5;X1;K\"\u{1b}Nq \u{1b}NyStra\u{1b}N{e \u{1b}Na\u{1b}Ni\"\r\n\ + C;Y6;X1;K\"\u{1b}NHq \u{1b}N\u{1b}NHo end\u{1b}N\"\r\nC;Y7;X1;K\"\u{1b}N\u{7f} \u{1b}NL \u{1b}X\"\r\nE\r\n"; + let sh = read(file.as_bytes()).unwrap(); + let value = |a: &str| sh.cells.get(&at(a)).map(|c| c.value.clone()).unwrap_or_default(); + let text = |s: &str| Value::Text(s.into()); + assert_eq!(value("A1"), text("Größe für Köln")); + assert_eq!(value("A2"), text("Plain ASCII 123"), "plain ASCII is unchanged"); + // Acute, grave, circumflex, cedilla, caron, double acute, ring, tilde. + assert_eq!(value("A3"), text("é à â ç š ő å ñ")); + // A letter the mark has no precomposed form with keeps the combining mark. + assert_eq!(value("A4"), text("à Z\u{300}")); + // Spacing characters, one code each: `q` æ, `y` ø, `{` ß, `a` Æ, `i` Ø. + assert_eq!(value("A5"), text("æ øStraße ÆØ")); + // A diacritic on a letter with no precomposed form, and a stray `ESC N` before an escape. + assert_eq!(value("A6"), text("q\u{308} \u{1b}Nö end\u{1b}N")); + // Codes ISO 6937 doesn't define (0xFF, 0xCC) and an `ESC` without `N` stay as written. + assert_eq!(value("A7"), text("\u{1b}N\u{7f} \u{1b}NL \u{1b}X")); +} 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 027/144] 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 1d5c223cfd..c462980f15 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 f1a09e32a8..beec53ea33 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 0000000000..44578baede --- /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 0000000000..5bf6426b80 --- /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 0000000000..f74bf93659 --- /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 0000000000..2a7c82d1a4 --- /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 e096b5eb9b565596f06e083de7efd2ebc0db9b63 Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 16 Nov 2026 19:07:27 +0500 Subject: [PATCH 028/144] craft-csv: a diacritic before another escape keeps it as written MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An escape's diacritic took the next character as its letter even when that was the next escape (ESC N H ESC N H o gave ESC + U+0308 + NHo). A control character is no letter: the first escape is kept as written and the next one decodes on its own (ESC N H ö). --- crates/csv/src/sylk.rs | 4 +++- crates/csv/tests/sylk.rs | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/csv/src/sylk.rs b/crates/csv/src/sylk.rs index d8c0ebec52..576ceb8c23 100644 --- a/crates/csv/src/sylk.rs +++ b/crates/csv/src/sylk.rs @@ -355,7 +355,9 @@ fn decode_escapes(text: &str) -> String { }; if let Some(&(_, mark, pairs)) = ISO6937_DIACRITICS.iter().find(|(d, _, _)| *d == code) { // The letter it goes on: precomposed where Unicode has the pair, else letter and mark. - let Some(base) = ahead.next() else { + // The base is an ordinary character: another escape (or any control character) after a + // diacritic leaves this escape as written, and the next one is decoded on its own. + let Some(base) = ahead.next().filter(|b| !b.is_control()) else { out.push(c); continue; }; diff --git a/crates/csv/tests/sylk.rs b/crates/csv/tests/sylk.rs index b91d074272..9fa7cb7d38 100644 --- a/crates/csv/tests/sylk.rs +++ b/crates/csv/tests/sylk.rs @@ -123,7 +123,7 @@ fn decodes_excels_character_escapes_in_text() { let file = "ID;PWXL;N;E\r\nC;Y1;X1;K\"Gr\u{1b}NHo\u{1b}N{e f\u{1b}NHur K\u{1b}NHoln\"\r\nC;Y2;X1;K\"Plain ASCII 123\"\r\n\ C;Y3;X1;K\"\u{1b}NBe \u{1b}NAa \u{1b}NCa \u{1b}NKc \u{1b}NOs \u{1b}NMo \u{1b}NJa \u{1b}NDn\"\r\n\ C;Y4;X1;K\"\u{1b}NAa \u{1b}NAZ\"\r\nC;Y5;X1;K\"\u{1b}Nq \u{1b}NyStra\u{1b}N{e \u{1b}Na\u{1b}Ni\"\r\n\ - C;Y6;X1;K\"\u{1b}NHq \u{1b}N\u{1b}NHo end\u{1b}N\"\r\nC;Y7;X1;K\"\u{1b}N\u{7f} \u{1b}NL \u{1b}X\"\r\nE\r\n"; + C;Y6;X1;K\"\u{1b}NHq \u{1b}N\u{1b}NHo end\u{1b}N\"\r\nC;Y7;X1;K\"\u{1b}N\u{7f} \u{1b}NL \u{1b}X\"\r\nC;Y8;X1;K\"\u{1b}NH\u{1b}NHo \u{1b}NB\tx\"\r\nE\r\n"; let sh = read(file.as_bytes()).unwrap(); let value = |a: &str| sh.cells.get(&at(a)).map(|c| c.value.clone()).unwrap_or_default(); let text = |s: &str| Value::Text(s.into()); @@ -139,4 +139,7 @@ fn decodes_excels_character_escapes_in_text() { assert_eq!(value("A6"), text("q\u{308} \u{1b}Nö end\u{1b}N")); // Codes ISO 6937 doesn't define (0xFF, 0xCC) and an `ESC` without `N` stay as written. assert_eq!(value("A7"), text("\u{1b}N\u{7f} \u{1b}NL \u{1b}X")); + // A diacritic followed by another escape (or a control character) is kept as written, and the + // next escape still decodes. + assert_eq!(value("A8"), text("\u{1b}NHö \u{1b}NB\tx")); } From 503caef9c4da1a03ce27dd121280aefd1f07c22f Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 16 Nov 2026 19:20:31 +0500 Subject: [PATCH 029/144] craft-csv: a SYLK diacritic on a space is the spacing accent ISO 6937 writes a spacing accent as its diacritic followed by SPACE. ESC N B SPACE was read as a space and a combining acute; it is now the acute accent itself, and likewise for the other nine marks glibc's ISO_6937 map gives a spacing form. --- crates/csv/src/sylk.rs | 22 ++++++++++++---------- crates/csv/tests/sylk.rs | 7 ++++++- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/crates/csv/src/sylk.rs b/crates/csv/src/sylk.rs index 576ceb8c23..53283cb912 100644 --- a/crates/csv/src/sylk.rs +++ b/crates/csv/src/sylk.rs @@ -241,20 +241,22 @@ fn parse_value(arg: &str) -> Value { /// ISO 6937's diacritics (codes 0xC1–0xCF): each code, its combining mark, and the letters it /// composes with, as pairs of letter and precomposed letter (from Unicode's canonical composition). +/// A diacritic on a SPACE is the spacing accent (`´`, `¨`, `ˇ`, ...), as in glibc's ISO_6937 map; the +/// grave, circumflex and tilde have none, since `` ` ``, `^` and `~` are plain ASCII. const ISO6937_DIACRITICS: [(u8, char, &str); 13] = [ (0xC1, '\u{0300}', "AÀaàEÈeèIÌiìNǸnǹOÒoòUÙuùWẀwẁYỲyỳ"), // grave - (0xC2, '\u{0301}', "AÁaáCĆcćEÉeéGǴgǵIÍiíKḰkḱLĹlĺMḾmḿNŃnńOÓoóPṔpṕRŔrŕSŚsśUÚuúWẂwẃYÝyýZŹzź"), // acute + (0xC2, '\u{0301}', " ´AÁaáCĆcćEÉeéGǴgǵIÍiíKḰkḱLĹlĺMḾmḿNŃnńOÓoóPṔpṕRŔrŕSŚsśUÚuúWẂwẃYÝyýZŹzź"), // acute (0xC3, '\u{0302}', "AÂaâCĈcĉEÊeêGĜgĝHĤhĥIÎiîJĴjĵOÔoôSŜsŝUÛuûWŴwŵYŶyŷZẐzẑ"), // circumflex (0xC4, '\u{0303}', "AÃaãEẼeẽIĨiĩNÑnñOÕoõUŨuũVṼvṽYỸyỹ"), // tilde - (0xC5, '\u{0304}', "AĀaāEĒeēGḠgḡIĪiīOŌoōUŪuūYȲyȳ"), // macron - (0xC6, '\u{0306}', "AĂaăEĔeĕGĞgğIĬiĭOŎoŏUŬuŭ"), // breve - (0xC7, '\u{0307}', "AȦaȧBḂbḃCĊcċDḊdḋEĖeėFḞfḟGĠgġHḢhḣIİMṀmṁNṄnṅOȮoȯPṖpṗRṘrṙSṠsṡTṪtṫWẆwẇXẊxẋYẎyẏZŻzż"), // dot above - (0xC8, '\u{0308}', "AÄaäEËeëHḦhḧIÏiïOÖoötẗUÜuüWẄwẅXẌxẍYŸyÿ"), // diaeresis - (0xCA, '\u{030a}', "AÅaåUŮuůwẘyẙ"), // ring - (0xCB, '\u{0327}', "CÇcçDḐdḑEȨeȩGĢgģHḨhḩKĶkķLĻlļNŅnņRŖrŗSŞsşTŢtţ"), // cedilla - (0xCD, '\u{030b}', "OŐoőUŰuű"), // double acute - (0xCE, '\u{0328}', "AĄaąEĘeęIĮiįOǪoǫUŲuų"), // ogonek - (0xCF, '\u{030c}', "AǍaǎCČcčDĎdďEĚeěGǦgǧHȞhȟIǏiǐjǰKǨkǩLĽlľNŇnňOǑoǒRŘrřSŠsšTŤtťUǓuǔZŽzž"), // caron + (0xC5, '\u{0304}', " ¯AĀaāEĒeēGḠgḡIĪiīOŌoōUŪuūYȲyȳ"), // macron + (0xC6, '\u{0306}', " ˘AĂaăEĔeĕGĞgğIĬiĭOŎoŏUŬuŭ"), // breve + (0xC7, '\u{0307}', " ˙AȦaȧBḂbḃCĊcċDḊdḋEĖeėFḞfḟGĠgġHḢhḣIİMṀmṁNṄnṅOȮoȯPṖpṗRṘrṙSṠsṡTṪtṫWẆwẇXẊxẋYẎyẏZŻzż"), // dot above + (0xC8, '\u{0308}', " ¨AÄaäEËeëHḦhḧIÏiïOÖoötẗUÜuüWẄwẅXẌxẍYŸyÿ"), // diaeresis + (0xCA, '\u{030a}', " ˚AÅaåUŮuůwẘyẙ"), // ring + (0xCB, '\u{0327}', " ¸CÇcçDḐdḑEȨeȩGĢgģHḨhḩKĶkķLĻlļNŅnņRŖrŗSŞsşTŢtţ"), // cedilla + (0xCD, '\u{030b}', " ˝OŐoőUŰuű"), // double acute + (0xCE, '\u{0328}', " ˛AĄaąEĘeęIĮiįOǪoǫUŲuų"), // ogonek + (0xCF, '\u{030c}', " ˇAǍaǎCČcčDĎdďEĚeěGǦgǧHȞhȟIǏiǐjǰKǨkǩLĽlľNŇnňOǑoǒRŘrřSŠsšTŤtťUǓuǔZŽzž"), // caron ]; /// ISO 6937's spacing characters above ASCII (codes 0xA1–0xFE that aren't diacritics). diff --git a/crates/csv/tests/sylk.rs b/crates/csv/tests/sylk.rs index 9fa7cb7d38..de3c38d0bc 100644 --- a/crates/csv/tests/sylk.rs +++ b/crates/csv/tests/sylk.rs @@ -123,7 +123,8 @@ fn decodes_excels_character_escapes_in_text() { let file = "ID;PWXL;N;E\r\nC;Y1;X1;K\"Gr\u{1b}NHo\u{1b}N{e f\u{1b}NHur K\u{1b}NHoln\"\r\nC;Y2;X1;K\"Plain ASCII 123\"\r\n\ C;Y3;X1;K\"\u{1b}NBe \u{1b}NAa \u{1b}NCa \u{1b}NKc \u{1b}NOs \u{1b}NMo \u{1b}NJa \u{1b}NDn\"\r\n\ C;Y4;X1;K\"\u{1b}NAa \u{1b}NAZ\"\r\nC;Y5;X1;K\"\u{1b}Nq \u{1b}NyStra\u{1b}N{e \u{1b}Na\u{1b}Ni\"\r\n\ - C;Y6;X1;K\"\u{1b}NHq \u{1b}N\u{1b}NHo end\u{1b}N\"\r\nC;Y7;X1;K\"\u{1b}N\u{7f} \u{1b}NL \u{1b}X\"\r\nC;Y8;X1;K\"\u{1b}NH\u{1b}NHo \u{1b}NB\tx\"\r\nE\r\n"; + C;Y6;X1;K\"\u{1b}NHq \u{1b}N\u{1b}NHo end\u{1b}N\"\r\nC;Y7;X1;K\"\u{1b}N\u{7f} \u{1b}NL \u{1b}X\"\r\nC;Y8;X1;K\"\u{1b}NH\u{1b}NHo \u{1b}NB\tx\"\r\n\ + C;Y9;X1;K\"\u{1b}NB |\u{1b}NE |\u{1b}NF |\u{1b}NG |\u{1b}NH |\u{1b}NJ |\u{1b}NK |\u{1b}NM |\u{1b}NN |\u{1b}NO |\u{1b}NA |\u{1b}NC \"\r\nE\r\n"; let sh = read(file.as_bytes()).unwrap(); let value = |a: &str| sh.cells.get(&at(a)).map(|c| c.value.clone()).unwrap_or_default(); let text = |s: &str| Value::Text(s.into()); @@ -142,4 +143,8 @@ fn decodes_excels_character_escapes_in_text() { // A diacritic followed by another escape (or a control character) is kept as written, and the // next escape still decodes. assert_eq!(value("A8"), text("\u{1b}NHö \u{1b}NB\tx")); + // A diacritic on a SPACE is the spacing accent: acute, macron, breve, dot above, diaeresis, ring, + // cedilla, double acute, ogonek, caron. The grave and circumflex have none (`` ` `` and `^` are + // ASCII), so they stay a space with the combining mark. + assert_eq!(value("A9"), text("´|¯|˘|˙|¨|˚|¸|˝|˛|ˇ| \u{300}| \u{302}")); } From ed850ede0f26ef0b8ff9b4d1fc08466a1cf21375 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 10:06:40 -0500 Subject: [PATCH 030/144] 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 a6df9e19da..dceb78f669 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 963a52ec95d260937cbf3be13d7ade6caed2974f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 10:21:41 -0500 Subject: [PATCH 031/144] 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 dceb78f669..a13a1d4fbf 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 032/144] 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 ce7d7756fe..a75874e71b 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 7ec6be8398..b45b488089 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 16220df9e3..cd5494c031 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 fb2b27b1f02b603d696480d03345827e8b44124a Mon Sep 17 00:00:00 2001 From: FredApps Date: Mon, 16 Nov 2026 16:50:42 +0100 Subject: [PATCH 033/144] 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 5d4cfa6195..40d461db1f 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 cd5494c031..a7253df220 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 034/144] 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 5bf6426b80..01fbf3b183 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 09f95e0b85..ad294b10f9 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 035/144] 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 ad294b10f9..7f3a993c7b 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 036/144] 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 96ad47a7b5..1a6f2000e4 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 6e26cd75b0..658538bc22 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 a2195bf5da..d4d98c695c 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 0000000000..624aaf2874 --- /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 037/144] 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 b638fd3ecc..8c409120e0 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 0000000000..49995667c8 --- /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 038/144] 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 0000000000..bbe485d67f --- /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""), + _ if rest.starts_with(b" past(b, i + 2, b"?>"), + _ => i + 1, + }; + } + b.len() +} + +/// Past the comment, character data or instruction that starts at `at` inside a declaration's +/// literal ending at `end`, when it closes before `end`. `missed` holds, for each kind, the literal +/// end at which its close was last not found, so a literal full of openers is searched once. +fn closed_in_literal(b: &[u8], at: usize, end: usize, missed: &mut [usize; 3]) -> Option { + const KINDS: [(&[u8], &[u8]); 3] = [(b""), (b""), (b"")]; + let rest = b.get(at..end)?; + let (kind, (open, close)) = KINDS.iter().enumerate().find(|(_, (open, _))| rest.starts_with(open))?; + let miss = missed.get_mut(kind)?; + if *miss == end { + return None; + } + let found = rest.get(open.len()..).and_then(|r| r.windows(close.len()).position(|w| w == *close)).map(|n| at + open.len() + n + close.len()); + if found.is_none() { + *miss = end; + } + found +} + /// The internal general entities declared in `svg`: name → every value declared for it. Text that /// only looks like a declaration in another entity's value is kept too: the largest value counts, /// so it can only make the estimate larger. Comments and CDATA are skipped, so markers there are -/// not treated as declarations. +/// not treated as declarations. A `") { - Some(n) => at + 1 + 3 + n + 3, - None => svg.len(), - }; - continue; - } - if let Some(body) = after.strip_prefix("![CDATA[") { - i = match body.find("]]>") { - Some(n) => at + 1 + 8 + n + 3, - None => svg.len(), - }; - continue; + if at >= literal_end { + if let Some(body) = after.strip_prefix("!--") { + i = match body.find("-->") { + Some(n) => at + 1 + 3 + n + 3, + None => svg.len(), + }; + continue; + } + if let Some(body) = after.strip_prefix("![CDATA[") { + i = match body.find("]]>") { + Some(n) => at + 1 + 8 + n + 3, + None => svg.len(), + }; + continue; + } + if after.starts_with('?') { + literal_end = past(b, at + 2, b"?>"); + } else if after.starts_with('!') { + literal_end = declaration_end(b, at); + } } if let Some(rest) = after.strip_prefix("!ENTITY") { let rest = rest.trim_start(); @@ -199,11 +266,10 @@ pub fn too_wide(svg: &str, most: usize, most_work: usize) -> bool { } else if rest.starts_with(b""); } else if rest.starts_with(b"` closing its subset (the first `>` when it has none). - let end = match (rest.iter().position(|b| *b == b'['), rest.iter().position(|b| *b == b'>')) { - (Some(o), Some(g)) if o < g => find(i, b"]>"), - _ => find(i, b">"), - }; + // To the `>` after the `]` closing its subset (its first `>` when it has none), + // quoted literals, comments and instructions skipped. + let head = declaration_end(data, i); + let end = if data.get(head.wrapping_sub(1)) == Some(&b'[') { find(subset_end(data, head), b">") } else { head }; let quotes = data.get(i..end).unwrap_or(&[]).iter().filter(|b| matches!(**b, b'"' | b'\'')).count(); if over(quotes / 2) { return true; @@ -318,24 +384,40 @@ pub fn prescan(svg: &str, most: usize) -> Prescan<'_> { // (now, deepest) of the elements, and of the markup inside the document type. let (mut elements, mut entities, mut open_depth) = ((0usize, 0usize), (0usize, 0usize), 0usize); let mut doctype_end = 0; + // The end of the declaration the scan is in: a `").unwrap_or(b.len()) - } else if rest.starts_with(b"").unwrap_or(b.len()) - } else if rest.starts_with(b"").unwrap_or(b.len()) - } else if rest.starts_with(b"` that ends it: after its internal subset (`[` … `]`) when it has one. - let plain = tag_end(at, false).0; - let subset = b.get(at..plain).is_some_and(|head| head.contains(&b'[')); - doctype_end = if subset { find(at, b"]>").unwrap_or(b.len()) } else { plain }; + } else if let Some(end) = (!open).then(|| closed_in_literal(b, at, literal_end, &mut missed)).flatten() { + // A comment, character data or instruction that closes inside the literal holds no + // element of the entity's markup. + end + } else if open && rest.starts_with(b"`. + let head = declaration_end(b, at); + literal_end = head; + doctype_end = if b.get(head.wrapping_sub(1)) == Some(&b'[') { subset_end(b, head) } else { head }; at + 2 } else if rest.starts_with(b""); + for hidden in [ + format!("{large}]>"), + format!("{large}]>"), + format!(""), + format!("{large}]>"), + format!(""), + format!("{large}]>"), + ] { + assert!(expansion_too_large(&format!("{hidden}"))); + } + assert!(entity_holds_markup("'>]>")); + // A real comment still hides a declaration-like text. + assert!(!entity_holds_markup("'> -->]>")); + } + + #[test] + fn markers_in_a_literal_hide_no_markup_from_the_depth_or_attribute_counts() { + let tenth = DEPTH / 10 + 1; + let nested = format!("{}{}", "".repeat(tenth), "".repeat(tenth)); + for bait in ["", "", "\">"] { + assert!(too_deep(&format!("]>&a;")), "{bait}"); + } + // Comments and instructions in a value open and close no element. + let quiet = format!("", "".repeat(DEPTH)); + assert!(!too_deep(&format!("{}", svg(&groups(8))))); + let closers = format!("", "?></g>".repeat(tenth)); + assert!(too_deep(&format!("&a;"))); + // Openers that never close in the value are read once each. + let openers = format!("", ""), _ if rest.starts_with(b" past(b, i + 2, b"?>"), _ => i + 1, @@ -552,6 +563,7 @@ mod tests { format!("{large}]>"), format!(""), format!("{large}]>"), + format!("{large}]>"), ] { assert!(expansion_too_large(&format!("{hidden}"))); } @@ -564,7 +576,7 @@ mod tests { fn markers_in_a_literal_hide_no_markup_from_the_depth_or_attribute_counts() { let tenth = DEPTH / 10 + 1; let nested = format!("{}{}", "".repeat(tenth), "".repeat(tenth)); - for bait in ["", "", "\">"] { + for bait in ["", "", "\">", ""] { assert!(too_deep(&format!("]>&a;")), "{bait}"); } // Comments and instructions in a value open and close no element. @@ -577,6 +589,8 @@ mod tests { assert!(!too_deep(&format!("{}", svg(&groups(8))))); let many = (0..5000).map(|i| format!(" a{i}=\"1\"")).collect::(); assert!(wide(&format!("\">'>]>&e;"))); + // An element declaration ends at its first `>`, so a `]` inside it does not end the subset. + assert!(wide(&format!("'>]>&e;"))); } #[test] From 227ea620b1388a8e7ac62fcb3b2051af2fc152e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 12:05:10 -0800 Subject: [PATCH 051/144] craft-metafile: count refused bitmaps and lost pen textures, empty line clips - A bitmap that the item or byte limit refuses is counted in dropped_images once, however many pieces a clip cuts it into. - An EMF+ pen whose texture brush was not read is counted in dropped_images, as a lost texture brush object is. - An EMF+ clip path or region path whose figures all lie on a line encloses no area, so it gives an empty area instead of its bounding rectangle. --- crates/metafile/README.md | 2 +- crates/metafile/src/canvas.rs | 5 +++++ crates/metafile/src/emfplus.rs | 16 ++++++++++++---- crates/metafile/src/lib.rs | 8 ++++---- crates/metafile/src/tests.rs | 28 ++++++++++++++++++++++++++++ crates/metafile/src/tests/model.rs | 30 ++++++++++++++++++++++++++++++ 6 files changed, 80 insertions(+), 9 deletions(-) diff --git a/crates/metafile/README.md b/crates/metafile/README.md index 4e246de515..226c956adf 100644 --- a/crates/metafile/README.md +++ b/crates/metafile/README.md @@ -39,7 +39,7 @@ differently: | Field | Reports | |---|---| | `truncated` | The parse stopped at a limit that ends it (items, bytes kept, `SAVEDC` depth, clip paths), in the file or in an EMF+ metafile image drawn in it. | -| `dropped_images` | Images that were not read: bitmaps past a size, byte or decode limit or not decodable, EMF+ metafile images that do not parse or are nested too deep, and pattern or texture brushes whose bitmap was not read (counted when the brush is created). An image with no pixels, or drawn from a source rectangle that selects none, is not counted. | +| `dropped_images` | Images that were not read: bitmaps past a size, item, byte or decode limit or not decodable, EMF+ metafile images that do not parse or are nested too deep, and pattern or texture brushes whose bitmap was not read, a pen's brush included (counted when the brush or pen is created). An image with no pixels, or drawn from a source rectangle that selects none, is not counted. | | `ignored_clips` | Clip changes not applied as the file asks: `SELECTCLIPPATH` with `RGN_OR`, `RGN_XOR` or `RGN_DIFF`, EMF+ clips combined with XOR, exclude or complement, EMF+ unions drawn as the rectangle around both areas, and EMF+ clips whose area stands in for the one the file gives (a path that is not one convex figure, drawn as its rectangle, or a region built with XOR, exclude or complement). A change that cannot alter the clip is not counted: an area whose figures all lie on a line (except in an EMF+ complement of a clip that encloses some area, which would empty it), `RGN_OR` on a clip that is still the whole surface, and a union whose rectangle is no larger than the union. | | `unplayed_raster_ops` | Raster operations not played: bitmaps drawn as plain copies because their operation is not one of `SRCCOPY`, `SRCAND`, `SRCPAINT` and `SRCINVERT`, and operations without a source (such as `DSTINVERT` or `PATINVERT`) that are left out. | diff --git a/crates/metafile/src/canvas.rs b/crates/metafile/src/canvas.rs index 67cc43f0fd..916e8ac9ae 100644 --- a/crates/metafile/src/canvas.rs +++ b/crates/metafile/src/canvas.rs @@ -1335,7 +1335,12 @@ impl Canvas { let (x0, x1) = (xs.iter().copied().fold(f64::INFINITY, f64::min), xs.iter().copied().fold(f64::NEG_INFINITY, f64::max)); let (y0, y1) = (ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)); let dev = if xf[1] == 0.0 && xf[2] == 0.0 { dev } else { [x0, y0, x1 - x0, y1 - y0] }; + let was_full = self.full; self.push(Raw::Bitmap { rect: dev, xf, img, region: RawClip::default() }); + // A bitmap the item or byte limit refuses is counted once, however many pieces a clip cuts it into. + if self.full && !was_full { + self.drop_image(); + } } /// Draws a bitmap that a record asked to combine with raster operation `rop` (already applied by diff --git a/crates/metafile/src/emfplus.rs b/crates/metafile/src/emfplus.rs index 32786bc5f4..505149371f 100644 --- a/crates/metafile/src/emfplus.rs +++ b/crates/metafile/src/emfplus.rs @@ -1181,7 +1181,11 @@ fn pen(r: Bytes) -> Option { off += 4 + (r.u32(off)? as usize).min(1 << 20); } } - let color = brush(r, off)?.color(); + // A pen whose texture brush was not read is counted like a lost brush object. + let Some(fill) = brush(r, off) else { + return lost_texture(r.tail(off)?).then_some(Obj::LostBrush); + }; + let color = fill.color(); Some(Obj::Pen { color, width: if width.is_finite() { width.clamp(0.0, 1.0e5) } else { 0.0 } }) } @@ -1290,16 +1294,20 @@ fn region_node(r: Bytes, off: usize, depth: usize, work: &mut usize) -> Option<( } } -/// The area a path encloses: its outline when that is one convex figure, else the rectangle -/// around it. The flag is set when the rectangle stands in for a path that encloses some area. +/// The area a path encloses: its outline when that is one convex figure, none when its figures all +/// lie on a line, else the rectangle around it. The flag is set when the rectangle stands in for +/// the path. fn area_of_ops(ops: &[Op]) -> (Vec

, bool) { + if !crate::geom::encloses_area(ops) { + return (Vec::new(), false); + } let subs = flatten(ops); if let [(pts, _)] = subs.as_slice() && let Some(c) = convex(pts) { return (c, false); } - (ops_bbox(ops).map(rect_poly).unwrap_or_default(), crate::geom::encloses_area(ops)) + (ops_bbox(ops).map(rect_poly).unwrap_or_default(), true) } /// Two areas' intersection, and whether it ran out of work and kept the first area instead. diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 6a2338a78c..26a406d312 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -78,10 +78,10 @@ pub struct Picture { /// the picture holds what came before. The limits that cut one path, string, region or dash /// pattern short do not set it. pub truncated: bool, - /// Images the file asks to draw that the reader did not read: bitmaps past a size, byte or decode - /// limit or in a form the reader cannot decode, EMF+ metafile images that do not parse or are - /// nested deeper than 3 levels, and pattern or texture brushes whose bitmap was not read (counted - /// when the brush is created). An image whose source rectangle selects none of its pixels, or that + /// Images the file asks to draw that the reader did not read: bitmaps past a size, item, byte or + /// decode limit or in a form the reader cannot decode, EMF+ metafile images that do not parse or + /// are nested deeper than 3 levels, and pattern or texture brushes whose bitmap was not read, a + /// pen's brush included (counted when the brush or pen is created). An image whose source rectangle selects none of its pixels, or that /// has no pixels, draws nothing and is not counted. Bitmaps left out while clipping to an EMF+ /// clip (see the README's limits) are not counted here. pub dropped_images: u32, diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index fa1cbb33a8..9f929108b3 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -486,6 +486,34 @@ fn canvas_stops_at_the_byte_budget() { assert_eq!(cv.items.len(), 2); } +#[test] +fn a_bitmap_the_byte_budget_refuses_is_counted_once() { + let img = || Rgba { w: 4, h: 4, px: vec![0u8; 64] }; + let diamond = || Some(vec![(2.0, 0.0), (4.0, 2.0), (2.0, 4.0), (0.0, 2.0)]); + let mut cv = Canvas::new(); + cv.set_clip(diamond()); + cv.bitmap([0.0, 0.0, 4.0, 4.0], img()); + assert!(!cv.full() && !cv.items.is_empty() && cv.dropped_images == 0, "a bitmap that is kept"); + // The clip cuts the bitmap into pieces, and none of them fits: one image is counted. + let mut cv = Canvas::new(); + cv.hold(MAX_BYTES - 1); + cv.set_clip(diamond()); + cv.bitmap([0.0, 0.0, 4.0, 4.0], img()); + assert!(cv.full() && cv.items.is_empty()); + assert_eq!(cv.dropped_images, 1); + // A clip that leaves none of the bitmap refuses nothing. + let mut cv = Canvas::new(); + cv.hold(MAX_BYTES - 1); + cv.set_clip(Some(vec![(100.0, 100.0), (110.0, 100.0), (110.0, 110.0)])); + cv.bitmap([0.0, 0.0, 4.0, 4.0], img()); + assert!(!cv.full() && cv.dropped_images == 0); + // A bitmap drawn with a raster operation is counted the same way. + let mut cv = Canvas::new(); + cv.hold(MAX_BYTES - 1); + cv.bitmap_rop([0.0, 0.0, 4.0, 4.0], img(), 0x00CC_0020); + assert!(cv.full() && cv.dropped_images == 1 && cv.unplayed_raster_ops == 0); +} + #[test] fn oversized_dib_header_size_is_rejected_without_overflow() { let mut info = info_header(2, 2, 24, 16); diff --git a/crates/metafile/src/tests/model.rs b/crates/metafile/src/tests/model.rs index 73186cb4c1..5053606c4d 100644 --- a/crates/metafile/src/tests/model.rs +++ b/crates/metafile/src/tests/model.rs @@ -485,6 +485,17 @@ fn pattern_and_texture_brushes_that_are_not_read_are_counted() { let none = cat(vec![h32(0xDBC0_1002), h32(1), h32(0), h32(4), h32(16), h32(0x0026_200A), h32(0)]); assert_eq!(parse(&texture(none)).unwrap().dropped_images, 0); assert_eq!(parse(&texture(bitmap_2x2())).unwrap().dropped_images, 0); + // A pen whose brush is such a texture brush. + let pen = |image: Vec| { + let brush = cat(vec![h32(0xDBC0_1002), h32(2), h32(0), h32(0), image]); + let pen = cat(vec![h32(0xDBC0_1002), h32(0), h32(0), h32(0), f32s(&[1.0]), brush]); + emf(&[plus_comment(&[plus_header(false), prec(0x4008, 0x0200 | 5, &pen)])], [0; 4], [0; 4]) + }; + let short = cat(vec![h32(0xDBC0_1002), h32(1), h32(4), h32(4), h32(16), h32(0x0026_200A), h32(0), vec![1, 2, 3]]); + assert_eq!(parse(&pen(short)).unwrap().dropped_images, 1); + let none = cat(vec![h32(0xDBC0_1002), h32(1), h32(0), h32(4), h32(16), h32(0x0026_200A), h32(0)]); + assert_eq!(parse(&pen(none)).unwrap().dropped_images, 0); + assert_eq!(parse(&pen(bitmap_2x2())).unwrap().dropped_images, 0); } #[test] @@ -643,6 +654,25 @@ fn emfplus_clips_that_are_not_applied_are_counted() { assert_eq!(plus(vec![clip(1, [0.0, 0.0, 50.0, 50.0]), clip(0, [1.0, 1.0, 5.0, 5.0])]), 0, "intersect and replace are applied"); } +#[test] +fn an_emfplus_clip_on_a_diagonal_line_encloses_nothing() { + let fill = prec(0x400A, 0x8000, &cat(vec![h32(0xFF00_0000), h32(1), f32s(&[0.0, 0.0, 100.0, 100.0])])); + let drawn = |clip: Vec>| { + let mut all = vec![plus_header(false)]; + all.extend(clip); + all.push(fill.clone()); + let p = parse(&emf(&[plus_comment(&all)], [0; 4], [0; 4])).unwrap(); + (p.items.len(), p.ignored_clips) + }; + let line = cat(vec![h32(0xDBC0_1002), h32(2), h32(0), f32s(&[0.0, 0.0, 10.0, 10.0]), vec![0, 1]]); + // SetClipPath with the line replaces the clip with nothing. + assert_eq!(drawn(vec![prec(0x4008, 0x0300 | 9, &line), prec(0x4033, 9, &[])]), (0, 0)); + // A region whose one node is the line. + let node = cat(vec![h32(0x1000_0001), h32(line.len() as u32), line]); + let region = cat(vec![h32(0xDBC0_1002), h32(1), node]); + assert_eq!(drawn(vec![prec(0x4008, 0x0400 | 6, ®ion), prec(0x4034, 6, &[])]), (0, 0)); +} + #[test] fn a_parse_stopped_at_a_limit_is_truncated() { assert!(!parse_emf(&[rect(0, 0, 10, 10)]).truncated); From 443a2b05ffa2588b7737f70b913126c7ad1899ea Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 15:51:23 -0500 Subject: [PATCH 052/144] docx: preserve partial table margins in current and tracked properties (#1924) --- crates/docx/src/read/props.rs | 11 ++++++ crates/docx/src/read/story/blocks.rs | 27 +++++++++++++- .../docx/tests/it/cell_margin_inheritance.rs | 15 ++++++++ crates/docx/tests/it/main.rs | 1 + crates/docx/tests/it/partial_table_margins.rs | 36 +++++++++++++++++++ 5 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 crates/docx/tests/it/partial_table_margins.rs diff --git a/crates/docx/src/read/props.rs b/crates/docx/src/read/props.rs index 4d86ae1641..618ef8c10b 100644 --- a/crates/docx/src/read/props.rs +++ b/crates/docx/src/read/props.rs @@ -562,6 +562,17 @@ pub fn margins(e: &El) -> [f32; 4] { margin_sides(e).map(|side| side.unwrap_or(0.0)) } +/// Word's own cell margins (the Normal Table style): 0.08" left and right, none above or below. +pub const WORD_CELL_MARGINS: [f32; 4] = [0.0, 5.4, 0.0, 5.4]; + +/// A table's `w:tblCellMar` over the margins it would have without one (its +/// style's, else Word's). A side the element leaves out keeps the underlying margin, as in Word: +/// a form table that sets only `w:left` keeps its style's right margin, not none. +pub fn margins_over(e: &El, base: [f32; 4]) -> [f32; 4] { + let sides = margin_sides(e); + std::array::from_fn(|i| sides.get(i).copied().flatten().or_else(|| base.get(i).copied()).unwrap_or(0.0)) +} + fn margin_sides(e: &El) -> [Option; 4] { let get = |names: &[&str]| names.iter().find_map(|n| e.child(n)).and_then(|c| tw(c, "w:w")).map(|v| v.clamp(0.0, 1584.0)); [get(&["w:top"]), get(&["w:left", "w:start"]), get(&["w:bottom"]), get(&["w:right", "w:end"])] diff --git a/crates/docx/src/read/story/blocks.rs b/crates/docx/src/read/story/blocks.rs index 8784294544..91c54714fd 100644 --- a/crates/docx/src/read/story/blocks.rs +++ b/crates/docx/src/read/story/blocks.rs @@ -333,12 +333,37 @@ impl Reader<'_> { } } + /// Omitted table-margin sides inherit from that property set's style. + fn table_margin_base(&self, style: Option<&str>) -> [f32; 4] { + style.and_then(|id| self.doc.styles.table_style(id)).and_then(|st| st.parts.cell_margins).unwrap_or(if self.no_default_table_style { + [0.0; 4] + } else { + crate::read::props::WORD_CELL_MARGINS + }) + } + fn read_table(&mut self, sc: &mut StoryCtx, t: &El, rels: &Rels, depth: usize) -> Option

{ let mut table = Table::default(); if let Some(p) = t.child("w:tblPr") { table.props = self.pc.tblpr(p); + // Sides `w:tblCellMar` leaves out keep the style's margins; without a style, Word's + // 0.08" left and right, or none in a file with no default table style. + if let Some(m) = p.child("w:tblCellMar") { + let base = self.table_margin_base(table.props.style.as_deref()); + table.props.cell_margins = Some(crate::read::props::margins_over(m, base)); + } if let Some(ch) = p.child("w:tblPrChange") { - let mut old = ch.child("w:tblPr").map(|o| self.pc.tblpr(o)).unwrap_or_default(); + let mut old = ch + .child("w:tblPr") + .map(|o| { + let mut props = self.pc.tblpr(o); + if let Some(m) = o.child("w:tblCellMar") { + let base = self.table_margin_base(props.style.as_deref()); + props.cell_margins = Some(crate::read::props::margins_over(m, base)); + } + props + }) + .unwrap_or_default(); // Rejecting the change brings back these properties: with the same margins. self.no_default_margins(&mut old); table.props.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, ch), old); diff --git a/crates/docx/tests/it/cell_margin_inheritance.rs b/crates/docx/tests/it/cell_margin_inheritance.rs index 83aafc7d0a..dc5cba6441 100644 --- a/crates/docx/tests/it/cell_margin_inheritance.rs +++ b/crates/docx/tests/it/cell_margin_inheritance.rs @@ -98,3 +98,18 @@ fn no_default_table_style_means_no_cell_margins() { let reopened = craft_docx::read(&bytes).unwrap(); assert_eq!(reopened.body[0].as_table().unwrap().props.cell_margins, Some([0.0; 4])); } + +#[test] +fn tracked_partial_table_margins_keep_the_old_styles_other_sides() { + let body = r#""#; + let styles = r#""#; + let doc = craft_docx::read(&package(body, Some(styles))).unwrap(); + let table = doc.body[0].as_table().unwrap(); + assert_eq!(table.props.cell_margins, Some([3.0, 5.0, 0.0, 9.0])); + let old = &table.props.fmt_change.as_ref().unwrap().old; + assert_eq!( + old.cell_margins, + Some([1.0, 0.0, 2.0, 8.0]), + "explicit zero overrides left, omitted sides come from the old style, not the current one" + ); +} diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index 8d6be8a97f..6d521effb7 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -29,6 +29,7 @@ mod malformed; mod missing_pictures; mod nested_block_controls; mod note_comments; +mod partial_table_margins; mod passthrough; mod picture_links; mod positional_tabs; diff --git a/crates/docx/tests/it/partial_table_margins.rs b/crates/docx/tests/it/partial_table_margins.rs new file mode 100644 index 0000000000..7cf3c5f491 --- /dev/null +++ b/crates/docx/tests/it/partial_table_margins.rs @@ -0,0 +1,36 @@ +//! a table's partial cell margins keep the other sides. + +use std::io::Write; + +#[test] +fn a_left_only_table_margin_keeps_the_other_sides() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let root = r#""#; + let rels = r#""#; + let styles = format!( + r#""# + ); + let table = |style: &str| { + format!( + r#"{style}Cell"# + ) + }; + let document = format!(r#"{}{}"#, table(r#""#), table("")); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, data) in [ + ("_rels/.rels", root), + ("word/_rels/document.xml.rels", rels), + ("word/document.xml", document.as_str()), + ("word/styles.xml", styles.as_str()), + ] { + zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(data.as_bytes()).unwrap(); + } + let doc = craft_docx::read(&zip.finish().unwrap().into_inner()).unwrap(); + let margins: Vec<_> = doc.body.iter().filter_map(|b| b.as_table()).map(|t| t.props.cell_margins).collect(); + assert_eq!( + margins, + vec![Some([1.0, 5.35, 2.0, 8.0]), Some([0.0, 5.35, 0.0, 0.0])], + "the left side is the table's, the rest the style's (none without one: the file has no default table style)" + ); +} From 20220807a4c33a35a72c7b4dfad90edd29205e34 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 15:51:27 -0500 Subject: [PATCH 053/144] psd: preserve PhotoCraft lenient TySh prefix parsing (#1923) --- crates/psd/src/text/envelope.rs | 75 +++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/crates/psd/src/text/envelope.rs b/crates/psd/src/text/envelope.rs index 73345fa83d..16fac87377 100644 --- a/crates/psd/src/text/envelope.rs +++ b/crates/psd/src/text/envelope.rs @@ -29,6 +29,33 @@ pub fn transform_is_safe(t: &[f64; 6]) -> bool { t.iter().all(|v| v.is_finite() && v.abs() <= f64::from(i32::MAX)) } +/// Recovers the text and raw transform of a `TySh` prefix, even if its descriptor is damaged. +/// +/// This is PhotoCraft's preservation fallback, not a rendering-ready type layer. It keeps +/// line endings, the trailing paragraph terminator and non-finite transform values verbatim. +/// Callers must validate geometry before rendering. A complete 52-byte prefix is required; +/// a missing, unsupported or malformed text descriptor produces empty text. Warp and bounds +/// are not interpreted. Above [`MAX_BYTES`], the descriptor is not parsed and text is empty, +/// retaining the fixed transform so consumers can preserve the original block without decoding +/// an oversized descriptor. Inputs within that cap retain the shared parser's allocation limits. +pub fn parse_tysh_text_prefix(data: &[u8]) -> Option<(String, [f64; 6])> { + let f = |at: usize| data.get(at..at + 8).map(|b| f64::from_be_bytes(b.try_into().unwrap_or([0; 8]))); + let mut m = [0.0; 6]; + for (i, v) in m.iter_mut().enumerate() { + *v = f(2 + i * 8)?; + } + // text version (2) at 50, descriptor version (4) at 52, descriptor at 56. + let rest = data.get(52..)?; + if data.len() > MAX_BYTES { + return Some((String::new(), m)); + } + let text = VersionedDescriptor::parse_prefix(rest).ok().and_then(|(d, _)| match d.descriptor.get("Txt ") { + Some(D::Text(t)) => Some(t.to_string_lossy()), + _ => None, + }); + Some((text.unwrap_or_default(), m)) +} + /// Parses a `TySh` block. pub fn parse_tysh(data: &[u8]) -> Option { if data.len() > MAX_BYTES { @@ -246,6 +273,54 @@ mod tests { bounds: [-1.0, 2.0, 30.0, 40.0], } } + #[test] + fn recovery_prefix_preserves_text_and_ignores_damaged_tail() { + let mut t = sample(); + t.text = t.text.with("Txt ", D::Text(UnicodeString::new_nul("Hello\r\nWorld\r"))); + let mut bytes = write_tysh(&t).unwrap(); + let (_, n) = VersionedDescriptor::parse_prefix(&bytes[52..]).unwrap(); + bytes.truncate(52 + n); + bytes.extend_from_slice(b"broken warp"); + assert_eq!(parse_tysh_text_prefix(&bytes), Some(("Hello\r\nWorld\r".into(), t.transform))); + } + + #[test] + fn recovery_prefix_needs_only_complete_fixed_header() { + let bytes = write_tysh(&sample()).unwrap(); + for cut in 0..52 { + assert!(parse_tysh_text_prefix(&bytes[..cut]).is_none(), "{cut}"); + } + for cut in 52..56 { + assert_eq!(parse_tysh_text_prefix(&bytes[..cut]), Some((String::new(), sample().transform))); + } + let mut unsupported = bytes.clone(); + unsupported[52..56].copy_from_slice(&99u32.to_be_bytes()); + assert_eq!(parse_tysh_text_prefix(&unsupported), Some((String::new(), sample().transform))); + assert_eq!(parse_tysh_text_prefix(&bytes), Some((String::new(), sample().transform))); + } + + #[test] + fn recovery_prefix_bounds_descriptor_work_without_losing_preservation_geometry() { + let mut t = sample(); + t.text = t.text.with("Txt ", D::Text(UnicodeString::new_nul("kept"))); + let mut bytes = write_tysh(&t).unwrap(); + bytes.resize(MAX_BYTES, 0); + assert_eq!(parse_tysh_text_prefix(&bytes), Some(("kept".into(), t.transform))); + bytes.push(0); + assert_eq!(parse_tysh_text_prefix(&bytes), Some((String::new(), t.transform))); + assert!(parse_tysh(&bytes).is_none()); + } + + #[test] + fn recovery_prefix_retains_geometry_but_is_not_render_validation() { + let mut bytes = write_tysh(&sample()).unwrap(); + bytes[2..10].copy_from_slice(&f64::NAN.to_be_bytes()); + let (_, transform) = parse_tysh_text_prefix(&bytes).unwrap(); + assert!(transform[0].is_nan()); + assert!(!transform_is_safe(&transform)); + assert!(parse_tysh(&bytes).is_none()); + } + #[test] fn roundtrip_preserves_descriptors_transform_and_bounds() { let t = sample(); From 617a3cea3ba6a7fbad366b7e834109d9648376cc Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:51:32 +0100 Subject: [PATCH 054/144] Add craft-media-source: MediaSource, open_bytes, and open_reader (#1891) --- Cargo.lock | 14 + Cargo.toml | 1 + crates/media-source/Cargo.toml | 23 ++ crates/media-source/src/lib.rs | 563 +++++++++++++++++++++++++++++++++ 4 files changed, 601 insertions(+) create mode 100644 crates/media-source/Cargo.toml create mode 100644 crates/media-source/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 9275d46463..8679e4eac8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2281,6 +2281,20 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-media-source" +version = "0.1.0" +dependencies = [ + "craft-audio", + "craft-color", + "craft-frame", + "craft-media", + "craft-time", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-media-testkit" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index bdcb8201d4..c8ae36287e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -119,6 +119,7 @@ craft-macho = { path = "crates/macho" } craft-math = { path = "crates/math" } # No default features: craft-audio turns on the craft-media modules each of its features needs. craft-media = { path = "crates/media", default-features = false } +craft-media-source = { path = "crates/media-source" } craft-materialx = { path = "crates/materialx" } craft-media-testkit = { path = "crates/media-testkit" } craft-midi = { path = "crates/midi" } diff --git a/crates/media-source/Cargo.toml b/crates/media-source/Cargo.toml new file mode 100644 index 0000000000..3edda0b2e8 --- /dev/null +++ b/crates/media-source/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "craft-media-source" +description = "Compositor MediaSource trait and a pluggable open_bytes / open_reader registry" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-audio = { workspace = true } +craft-color = { workspace = true } +craft-frame = { workspace = true } +craft-media = { workspace = true } +craft-time = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/media-source/src/lib.rs b/crates/media-source/src/lib.rs new file mode 100644 index 0000000000..c27aea6889 --- /dev/null +++ b/crates/media-source/src/lib.rs @@ -0,0 +1,563 @@ +//! Compositor media sources and a pluggable opener registry. +//! +//! This crate is the EffectCraft / FilmCraft opener hub: a [`MediaSource`] yields compositor +//! [`VideoFrame`]s and [`AudioBuffer`]s, and [`open_bytes`] / [`open_reader`] try caller-supplied +//! openers in order. It lives in its own crate rather than `craft-media` so it can depend on +//! `craft-audio` without a cycle (`craft-audio` already depends on `craft-media`). +//! +//! Built-in still-image, WAV, and generator openers stay in the apps. [`open_bytes`] only runs the +//! `extra` openers; [`open_reader`] tries `reader_openers` and otherwise reads the file whole +//! (up to `max_whole`) and falls back to [`open_bytes`]. Container sources register themselves +//! from later PRs. +//! +//! [`SharedSource`] is `Arc`. It is not `craft_audio::SharedSource`, which is a +//! `ByteSource` marker used by the audio decoder. + +#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] + +use std::io; +use std::path::Path; +use std::sync::Arc; + +use craft_audio::AudioBuffer; +use craft_color::{ColorInfo, HdrMetadata}; +use craft_frame::VideoFrame; +use craft_media::ByteSource; +use craft_time::{FrameRate, Tick}; +use serde::{Deserialize, Serialize}; + +/// Errors from opening or reading a media source. +#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] +pub enum MediaError { + #[error("unsupported media: {0}")] + Unsupported(String), + #[error("I/O error: {0}")] + Io(String), + #[error("decode error: {0}")] + Decode(String), + #[error("no {0} stream")] + NoStream(&'static str), + #[error("media offline: {0}")] + Offline(String), + /// The request was cancelled. + #[error("cancelled")] + Cancelled, +} + +impl From for MediaError { + fn from(e: io::Error) -> Self { + MediaError::Io(e.to_string()) + } +} + +pub type Result = std::result::Result; + +/// Kind of media a source reports. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum MediaKind { + /// Video, possibly with audio. + Movie, + AudioOnly, + Still, + ImageSequence, + Synthetic, +} + +/// Video stream metadata a source reports. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct VideoStreamInfo { + pub width: u32, + pub height: u32, + pub frame_rate: FrameRate, + pub par: (u32, u32), + pub codec: String, + pub pixel_format: String, + pub color: ColorInfo, + pub has_alpha: bool, + /// Bitrate in bits/s when known. + pub bitrate: Option, + /// HDR static metadata when the file carries it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub hdr: Option, +} + +/// Most audio streams a source reports (the count comes from the file: never trusted). +pub const MAX_AUDIO_STREAMS: usize = 64; + +/// Audio stream metadata a source reports. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct AudioStreamInfo { + pub sample_rate: u32, + pub channels: u32, + pub codec: String, + pub bits_per_sample: Option, +} + +/// Identity and streams of an open source. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct MediaInfo { + pub name: String, + pub kind: MediaKind, + /// Media duration. Stills typically report a default duration chosen by the app. + pub duration: Tick, + pub video: Option, + /// Every audio stream the container carries, in file order. Stream 0 is the one + /// [`MediaSource::audio`] reads; the others are read with [`MediaSource::audio_stream`]. + /// Project files written before multi-stream support hold a single `audio` object (or + /// `null`): both still load. + #[serde(default, alias = "audio", deserialize_with = "deserialize_audio_streams")] + pub audio_streams: Vec, + pub container: String, + /// Timecode of the first frame (in frames at `video.frame_rate`), if the file carries one. + pub start_timecode: Option, + pub file_size: Option, +} + +/// Reads `audio_streams` from a list, or from the single optional stream older project files wrote. +fn deserialize_audio_streams<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { + struct StreamsVisitor; + struct RejectExtra; + impl<'de> serde::de::DeserializeSeed<'de> for RejectExtra { + type Value = (); + fn deserialize>(self, _d: D) -> std::result::Result<(), D::Error> { + Err(serde::de::Error::custom("audio stream count exceeds MAX_AUDIO_STREAMS")) + } + } + impl<'de> serde::de::Visitor<'de> for StreamsVisitor { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("at most 64 audio streams, a legacy audio object, or null") + } + fn visit_unit(self) -> std::result::Result { + Ok(Vec::new()) + } + fn visit_none(self) -> std::result::Result { + Ok(Vec::new()) + } + fn visit_map>(self, map: A) -> std::result::Result { + AudioStreamInfo::deserialize(serde::de::value::MapAccessDeserializer::new(map)).map(|stream| vec![stream]) + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let mut streams = Vec::new(); + // Do not reserve from an untrusted size hint or buffer an untagged sequence. + while streams.len() < MAX_AUDIO_STREAMS { + let Some(stream) = seq.next_element()? else { return Ok(streams) }; + streams.push(stream); + } + // Detect an excess entry without deserializing or allocating its contents. + seq.next_element_seed(RejectExtra)?; + Ok(streams) + } + } + d.deserialize_any(StreamsVisitor) +} + +impl MediaInfo { + pub fn frame_rate(&self) -> FrameRate { + self.video.as_ref().map(|v| v.frame_rate).unwrap_or_default() + } + pub fn has_video(&self) -> bool { + self.video.is_some() + } + pub fn has_audio(&self) -> bool { + !self.audio_streams.is_empty() + } + /// The primary audio stream (stream 0), the one [`MediaSource::audio`] reads. + pub fn audio(&self) -> Option<&AudioStreamInfo> { + self.audio_streams.first() + } +} + +/// A request for a video frame. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FrameRequest { + /// Media time. + pub time: Tick, + /// Desired scale relative to full resolution (1.0 = full). Sources may return a larger frame. + pub scale: f32, +} + +impl FrameRequest { + pub fn full(time: Tick) -> Self { + Self { time, scale: 1.0 } + } +} + +/// A decoded or generated media source that can yield compositor frames and audio. +pub trait MediaSource: Send + Sync { + fn info(&self) -> &MediaInfo; + /// The frame displayed at media time `req.time`. + fn video_frame(&self, req: FrameRequest) -> Result>; + /// `frames` audio frames starting at sample index `start` (at `sample_rate`, media time). + fn audio(&self, start: i64, frames: usize, sample_rate: u32) -> Result; + /// Like [`audio`](Self::audio) for audio stream `stream` (an index into + /// [`MediaInfo::audio_streams`]). Sources with a single audio stream need not override this: + /// stream 0 is `audio`, any other index is [`MediaError::NoStream`]. + fn audio_stream(&self, stream: usize, start: i64, frames: usize, sample_rate: u32) -> Result { + if stream == 0 { self.audio(start, frames, sample_rate) } else { Err(MediaError::NoStream("audio")) } + } +} + +/// Shared compositor source. Distinct from [`craft_audio::SharedSource`], a `ByteSource` marker. +pub type SharedSource = Arc; + +/// Random-access bytes used by [`open_reader`]. +pub type SharedBytes = Arc; + +/// File extensions recognised at import (the media browser filters on these). +pub const STILL_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "tga", "dpx", "exr", "hdr", "dng"]; +pub const AUDIO_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "mp3", "mp2", "m4a", "aac", "flac", "ogg", "opus"]; +pub const VIDEO_EXTENSIONS: &[&str] = &[ + "mp4", "m4v", "mov", "mkv", "webm", "avi", "mxf", "mts", "m2ts", "m2t", "ts", "mpg", "mpeg", "vob", "mod", "tod", "m2v", "m1v", "mpv", "3gp", + "y4m", "apv", +]; + +/// True when `path` has a still, audio, or video extension we recognise, ignoring case. +pub fn is_importable(path: &Path) -> bool { + let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + STILL_EXTENSIONS.contains(&ext.as_str()) || AUDIO_EXTENSIONS.contains(&ext.as_str()) || VIDEO_EXTENSIONS.contains(&ext.as_str()) +} + +/// A pluggable in-memory opener. Returns `None` when the format is not this opener's. +pub type Opener = fn(name: &str, bytes: Arc<[u8]>) -> Option>; + +/// Opens a container from a reader: `head` is the first bytes of the file (for sniffing). +/// Returns `None` when the format is not this opener's. +pub type ReaderOpener = fn(name: &str, head: &[u8], reader: &SharedBytes) -> Option>; + +/// Bytes sniffed by [`open_reader`]. +pub const HEAD_LEN: usize = 64 * 1024; + +/// Default ceiling for a whole-file fallback or an offline output buffer (256 MiB). +/// Streaming openers are tried first. Use open_reader_within for an explicit different file budget. +pub const DEFAULT_MAX_MEDIA_BYTES: usize = 256 << 20; + +fn allocate(len: usize, max_bytes: usize) -> io::Result> { + if len.checked_mul(std::mem::size_of::()).is_none_or(|bytes| bytes > max_bytes || bytes > isize::MAX as usize) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "media buffer exceeds allocation limit")); + } + let mut out = Vec::new(); + out.try_reserve_exact(len).map_err(|e| io::Error::other(format!("cannot allocate media buffer: {e}")))?; + out.resize(len, T::default()); + Ok(out) +} + +fn io_named(name: &str, e: io::Error) -> MediaError { + MediaError::Io(format!("{name}: {e}")) +} + +/// Read `len` bytes at `offset` (fewer at the end of the source). +pub fn read_range(r: &dyn ByteSource, offset: u64, len: usize) -> io::Result> { + read_range_within(r, offset, len, DEFAULT_MAX_MEDIA_BYTES) +} + +fn read_range_within(r: &dyn ByteSource, offset: u64, len: usize, max_bytes: usize) -> io::Result> { + let n = usize::try_from(r.len().saturating_sub(offset).min(len as u64)) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "media length is not representable"))?; + let mut v = allocate(n, max_bytes)?; + r.read_at(offset, &mut v)?; + Ok(v) +} + +/// Open media from bytes by trying `extra` openers in order. There is no built-in fallback: +/// stills, WAV, and generators stay in the apps and register here. +pub fn open_bytes(name: &str, bytes: Arc<[u8]>, extra: &[Opener]) -> Result { + for o in extra { + if let Some(r) = o(name, bytes.clone()) { + return r; + } + } + Err(MediaError::Unsupported(format!("{name}: unrecognised format"))) +} + +/// Open media from a reader: `reader_openers` first; otherwise read the whole file (if it fits in +/// `max_whole`) and use [`open_bytes`] with `extra`. +pub fn open_reader(name: &str, reader: SharedBytes, reader_openers: &[ReaderOpener], extra: &[Opener]) -> Result { + open_reader_within(name, reader, reader_openers, extra, DEFAULT_MAX_MEDIA_BYTES as u64) +} + +/// Like [`open_reader`], but a file no reader opener takes is read whole only up to `max_whole` +/// bytes; a larger one is refused instead. For looking at files rather than importing them: +/// reading a multi-gigabyte file into memory to show its duration, or to find out it isn't +/// supported, thrashes the disk. +pub fn open_reader_within( + name: &str, + reader: SharedBytes, + reader_openers: &[ReaderOpener], + extra: &[Opener], + max_whole: u64, +) -> Result { + let head = read_range(&*reader, 0, HEAD_LEN).map_err(|e| io_named(name, e))?; + for o in reader_openers { + if let Some(r) = o(name, &head, &reader) { + return r; + } + } + if extra.is_empty() { + return Err(MediaError::Unsupported(format!("{name}: unrecognised format"))); + } + if reader.len() > max_whole { + return Err(MediaError::Unsupported(format!("{name}: no streaming reader for this format, and it is too large to read whole here"))); + } + let len = usize::try_from(reader.len()).map_err(|_| MediaError::Unsupported(format!("{name}: media length is not representable")))?; + let budget = usize::try_from(max_whole).unwrap_or(usize::MAX); + let all = read_range_within(&*reader, 0, len, budget).map_err(|e| io_named(name, e))?; + open_bytes(name, all.into(), extra) +} + +/// Open a regular file through the shared pooled FileReader. Non-files (including FIFOs) +/// are refused without a blocking open, using the same contract as other media readers. +#[cfg(not(target_arch = "wasm32"))] +pub fn open_path(path: &Path, reader_openers: &[ReaderOpener], extra: &[Opener]) -> Result { + let file = craft_media::FileReader::open(path).map_err(|e| MediaError::Io(format!("{}: {e}", path.display())))?; + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + open_reader(&name, Arc::new(file), reader_openers, extra) +} + +fn audio_channels(info: &MediaInfo) -> u16 { + info.audio().map_or(2, |a| u16::try_from(a.channels).unwrap_or(u16::MAX).max(1)) +} + +/// A source that renders a solid slate (used for offline media). +pub struct OfflineSource { + pub info: MediaInfo, +} + +impl MediaSource for OfflineSource { + fn info(&self) -> &MediaInfo { + &self.info + } + fn video_frame(&self, req: FrameRequest) -> Result> { + let v = self.info.video.as_ref().ok_or(MediaError::NoStream("video"))?; + if !req.scale.is_finite() || req.scale <= 0.0 || v.width == 0 || v.height == 0 { + return Err(MediaError::Decode("invalid offline frame dimensions or scale".into())); + } + let s = req.scale.clamp(0.02, 1.0); + let (w, h) = (((v.width as f32 * s) as u32).max(2), ((v.height as f32 * s) as u32).max(2)); + let samples = usize::try_from(w) + .ok() + .and_then(|w| usize::try_from(h).ok().and_then(|h| w.checked_mul(h))) + .and_then(|pixels| pixels.checked_mul(4)) + .ok_or_else(|| MediaError::Decode("offline frame dimensions overflow".into()))?; + let mut px = allocate::(samples, DEFAULT_MAX_MEDIA_BYTES)?; + for p in px.as_chunks_mut::<4>().0 { + p.copy_from_slice(&[140, 16, 16, 255]); + } + Ok(Arc::new(VideoFrame::rgba8(w, h, px).map_err(|e| MediaError::Decode(e.to_string()))?.with_pts(req.time))) + } + fn audio(&self, _start: i64, frames: usize, sample_rate: u32) -> Result { + let channels = usize::from(audio_channels(&self.info)); + let bytes = frames + .checked_mul(channels) + .and_then(|n| n.checked_mul(std::mem::size_of::())) + .ok_or_else(|| MediaError::Decode("offline audio dimensions overflow".into()))?; + if bytes > DEFAULT_MAX_MEDIA_BYTES { + return Err(MediaError::Decode("offline audio exceeds allocation limit".into())); + } + let mut planes = Vec::new(); + planes.try_reserve_exact(channels).map_err(|e| MediaError::Io(e.to_string()))?; + for _ in 0..channels { + planes.push(allocate::(frames, DEFAULT_MAX_MEDIA_BYTES)?); + } + Ok(AudioBuffer { sample_rate, channels: planes }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn silent(name: &str, kind: MediaKind) -> OfflineSource { + OfflineSource { + info: MediaInfo { + name: name.into(), + kind, + duration: Tick::from_seconds_f64(1.0), + video: Some(VideoStreamInfo { + width: 16, + height: 8, + frame_rate: FrameRate::FPS_24, + par: (1, 1), + codec: "slate".into(), + pixel_format: "rgba8".into(), + color: ColorInfo::default(), + has_alpha: false, + bitrate: None, + hdr: None, + }), + audio_streams: vec![AudioStreamInfo { sample_rate: 48000, channels: 2, codec: "pcm".into(), bits_per_sample: Some(32) }], + container: "none".into(), + start_timecode: None, + file_size: None, + }, + } + } + + fn accept_ok(name: &str, _bytes: Arc<[u8]>) -> Option> { + if name.ends_with(".ok") { Some(Ok(Arc::new(silent(name, MediaKind::Synthetic)))) } else { None } + } + + fn reject_all(_name: &str, _bytes: Arc<[u8]>) -> Option> { + None + } + + fn boom(name: &str, _bytes: Arc<[u8]>) -> Option> { + Some(Err(MediaError::Decode(format!("{name}: boom")))) + } + + fn reader_ok(name: &str, head: &[u8], _reader: &SharedBytes) -> Option> { + if head.starts_with(b"OK") { Some(Ok(Arc::new(silent(name, MediaKind::Movie)))) } else { None } + } + + struct HugeSource; + impl ByteSource for HugeSource { + fn len(&self) -> u64 { + u64::MAX + } + fn read_at(&self, _offset: u64, buf: &mut [u8]) -> io::Result<()> { + assert!(buf.len() <= HEAD_LEN, "must reject whole-file allocation before reading"); + buf.fill(0); + Ok(()) + } + } + + #[test] + fn whole_file_fallback_and_explicit_ranges_are_bounded() { + let reader: SharedBytes = Arc::new(HugeSource); + assert!(open_reader("large.ok", reader.clone(), &[], &[accept_ok]).is_err()); + assert!(open_reader_within("large.ok", reader.clone(), &[], &[accept_ok], u64::MAX).is_err()); + assert!(read_range(&HugeSource, 0, usize::MAX).is_err()); + assert!(read_range_within(&HugeSource, 0, 10, 9).is_err()); + assert_eq!(read_range_within(&HugeSource, 0, 10, 10).unwrap(), vec![0; 10]); + } + + struct SniffOnlySource(std::sync::atomic::AtomicUsize); + impl ByteSource for SniffOnlySource { + fn len(&self) -> u64 { + u64::MAX + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + assert_eq!(offset, 0); + assert_eq!(buf.len(), HEAD_LEN); + assert_eq!(self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst), 0, "must only sniff once"); + buf.fill(0); + buf[..2].copy_from_slice(b"OK"); + Ok(()) + } + } + + #[test] + fn no_fallback_stops_after_sniff_and_streaming_opener_precedes_size_cap() { + let reader = Arc::new(SniffOnlySource(std::sync::atomic::AtomicUsize::new(0))); + let error = open_reader("unknown", reader.clone(), &[], &[]).err().unwrap(); + assert!(matches!(error, MediaError::Unsupported(_))); + assert_eq!(reader.0.load(std::sync::atomic::Ordering::SeqCst), 1); + let reader = Arc::new(SniffOnlySource(std::sync::atomic::AtomicUsize::new(0))); + let source = open_reader_within("large.mov", reader.clone(), &[reader_ok], &[accept_ok], 0).unwrap(); + assert_eq!(source.info().kind, MediaKind::Movie); + assert_eq!(reader.0.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + #[test] + fn hostile_offline_metadata_and_requests_are_errors() { + let mut source = silent("bad", MediaKind::Synthetic); + source.info.video.as_mut().unwrap().width = u32::MAX; + source.info.video.as_mut().unwrap().height = u32::MAX; + assert!(source.video_frame(FrameRequest::full(Tick::ZERO)).is_err()); + assert!(source.audio(0, usize::MAX, 48000).is_err()); + let source = silent("bad-scale", MediaKind::Synthetic); + for scale in [f32::NAN, f32::INFINITY, 0.0, -1.0] { + assert!(source.video_frame(FrameRequest { time: Tick::ZERO, scale }).is_err()); + } + } + + #[cfg(unix)] + #[test] + fn open_path_refuses_a_fifo_without_waiting_for_a_writer() { + let root = std::env::temp_dir().join(format!("craft-media-source-fifo-{}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + let path = root.join("fifo"); + if std::process::Command::new("mkfifo").arg(&path).status().is_ok_and(|s| s.success()) { + assert!(open_path(&path, &[], &[]).is_err()); + std::fs::remove_file(&path).unwrap(); + } + std::fs::remove_dir(&root).unwrap(); + } + + #[test] + fn importable_extensions_match_regardless_of_case() { + for name in ["clip.mov", "clip.MOV", "clip.Mov", "shot.MP4", "IMG_0001.JPG", "sound.WAV", "take.M2TS"] { + assert!(is_importable(Path::new(name)), "{name}"); + } + assert!(!is_importable(Path::new("notes.txt"))); + } + + #[test] + fn open_bytes_tries_extra_in_order_and_otherwise_is_unsupported() { + let bytes: Arc<[u8]> = Arc::from(&b"xxxx"[..]); + let err = open_bytes("a.bin", bytes.clone(), &[]).err().expect("expected error"); + assert!(matches!(err, MediaError::Unsupported(_))); + let err = open_bytes("a.bin", bytes.clone(), &[reject_all, accept_ok]).err().expect("expected error"); + assert!(matches!(err, MediaError::Unsupported(_))); + let src = open_bytes("clip.ok", bytes.clone(), &[reject_all, accept_ok]).unwrap(); + assert_eq!(src.info().name, "clip.ok"); + let err = open_bytes("clip.ok", bytes, &[boom, accept_ok]).err().expect("expected error"); + assert!(matches!(err, MediaError::Decode(_))); + } + + #[test] + fn open_reader_uses_reader_openers_then_falls_back_within_max_whole() { + let small: SharedBytes = Arc::new(b"HELLO".to_vec()); + let err = open_reader("a.bin", small.clone(), &[], &[]).err().expect("expected error"); + assert!(matches!(err, MediaError::Unsupported(_))); + + let ok: SharedBytes = Arc::new(b"OK-file".to_vec()); + let src = open_reader("clip.mov", ok, &[reader_ok], &[]).unwrap(); + assert_eq!(src.info().kind, MediaKind::Movie); + + let tagged: SharedBytes = Arc::new(b"xxxx".to_vec()); + let src = open_reader("clip.ok", tagged.clone(), &[], &[accept_ok]).unwrap(); + assert_eq!(src.info().name, "clip.ok"); + + let big = vec![0u8; HEAD_LEN + 8]; + let r: SharedBytes = Arc::new(big); + let e = open_reader_within("a.avi", r, &[], &[accept_ok], HEAD_LEN as u64).err().expect("expected error"); + assert!(matches!(e, MediaError::Unsupported(s) if s.contains("too large"))); + } + + #[test] + fn audio_streams_serde_accepts_legacy_single_object() { + let stream = r#"{"sample_rate":48000,"channels":2,"codec":"pcm","bits_per_sample":null}"#; + let prefix = r#"{"name":"a","kind":"Movie","duration":0,"video":null,"audio_streams":["#; + let suffix = r#"],"container":"wav","start_timecode":null,"file_size":null}"#; + let full = std::iter::repeat_n(stream, MAX_AUDIO_STREAMS).collect::>().join(","); + let info: MediaInfo = serde_json::from_str(&format!("{prefix}{full}{suffix}")).unwrap(); + assert_eq!(info.audio_streams.len(), MAX_AUDIO_STREAMS); + for extra in [stream, r#"{"malformed":"not an audio stream"}"#] { + let error = serde_json::from_str::(&format!("{prefix}{full},{extra}{suffix}")).unwrap_err(); + assert!(error.to_string().contains("MAX_AUDIO_STREAMS"), "{error}"); + } + let many = r#"{"name":"a","kind":"Movie","duration":0,"video":null,"audio_streams":[{"sample_rate":48000,"channels":2,"codec":"pcm","bits_per_sample":null}],"container":"wav","start_timecode":null,"file_size":null}"#; + let info: MediaInfo = serde_json::from_str(many).unwrap(); + assert_eq!(info.audio_streams.len(), 1); + let one = r#"{"name":"a","kind":"AudioOnly","duration":0,"video":null,"audio":{"sample_rate":44100,"channels":1,"codec":"pcm","bits_per_sample":16},"container":"wav","start_timecode":null,"file_size":null}"#; + let info: MediaInfo = serde_json::from_str(one).unwrap(); + assert_eq!(info.audio().map(|a| a.sample_rate), Some(44100)); + let none = r#"{"name":"a","kind":"Still","duration":0,"video":null,"audio":null,"container":"png","start_timecode":null,"file_size":null}"#; + let info: MediaInfo = serde_json::from_str(none).unwrap(); + assert!(info.audio_streams.is_empty()); + } + + #[test] + fn offline_source_returns_slate_and_silence() { + let src = silent("off", MediaKind::Synthetic); + let frame = src.video_frame(FrameRequest::full(Tick::ZERO)).unwrap(); + assert_eq!((frame.width, frame.height), (16, 8)); + assert_eq!(frame.pts, Tick::ZERO); + let audio = src.audio(0, 8, 48000).unwrap(); + assert_eq!(audio.sample_rate, 48000); + assert_eq!(audio.num_channels(), 2); + assert_eq!(audio.frames(), 8); + assert!(src.audio_stream(1, 0, 8, 48000).is_err()); + } +} From f200f1c91df2c8b5ba8ef3c3c853382ced75df1f Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 21:53:12 +0100 Subject: [PATCH 055/144] dds: 16-bit input and output (R16, R16G16, R16G16B16A16; BC4/BC5 fitted to 16-bit values) encode16 writes 16-bit pixels uncompressed as R16_UNORM, R16G16_UNORM or R16G16B16A16_UNORM with the DX10 header, and fits BC4/BC5 endpoints and indices against the 16-bit values; BC1-BC3 round to 8 bits first. Texture::decode16 reads these formats (and legacy FourCC 36, wide channel masks, BC4/BC5 interpolated at 16 bits) without losing precision. --- crates/dds/README.md | 18 +- crates/dds/src/bc.rs | 120 ++++++++++- crates/dds/src/lib.rs | 453 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 545 insertions(+), 46 deletions(-) diff --git a/crates/dds/README.md b/crates/dds/README.md index a3f81e50b6..7a25eb36e3 100644 --- a/crates/dds/README.md +++ b/crates/dds/README.md @@ -11,22 +11,32 @@ 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 | +| Uncompressed | 8, 16, 24 or 32 bits per pixel described by channel masks, RGB or luminance, with or without alpha; padded rows (`DDSD_PITCH`); 16 bits per channel: `R16_UNORM`, `R16G16_UNORM`, `R16G16B16A16_UNORM` (DXGI 56, 35, 11 and their typeless forms; legacy FourCC 36) | BGRA, BGRX, luminance, luminance with alpha; from 16-bit pixels `R16_UNORM`, `R16G16_UNORM`, `R16G16B16A16_UNORM` | | 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 | +| Headers | legacy and DX10 | legacy; DX10 for BC4, BC5 and the 16-bit formats | | Mip levels | the top level only | optional full chain, box-filtered | Cubemaps, texture arrays, volume textures, premultiplied-alpha textures (DXT2/DXT4, or DX10 alpha mode 2), signed (SNORM) BC4/BC5 and -the other DXGI formats (BC6H, BC7, float) are refused with `DdsError::Unsupported` rather than read +the other DXGI formats (BC6H, BC7, float, signed or integer 16-bit) 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`, +Pixels are 8 bits per channel (`encode`, `Texture::decode`) or 16 bits per channel (`encode16`, +`Texture::decode16`), interleaved and top row first, in one of four `Layout`s (`Gray`, `GrayA`, `Rgb`, `Rgba`). BC1 to BC3 are written from RGBA, BC4 from gray and BC5 from RGB (`DdsCompression::layout` names it). BC4 reads back as gray. BC5 stores red and green only, so it reads back as RGB with blue 0: for a tangent-space normal map, X and Y, with Z left to the renderer. ATI2 files are read as Microsoft's tools read them (red in the first block), not with the two blocks swapped as FFmpeg does. +From 16-bit pixels, uncompressed textures keep 16 bits per channel: gray as `R16_UNORM`, gray +and alpha (or any two channels, such as a normal map's X and Y) as `R16G16_UNORM`, RGB (alpha +65535) and RGBA as `R16G16B16A16_UNORM`, all with the DX10 header; they read back as gray, gray +and alpha, and RGBA. BC4 and BC5 keep 8-bit endpoints, as the formats store them, but pick them +and the indices against the 16-bit values, so a smooth height or normal map has less error than +when its 8-bit rounding is compressed. BC1 to BC3 round the pixels to 8 bits first. +`Texture::decode` rounds 16-bit formats to 8 bits; `Texture::decode16` returns them exactly, +interpolates BC4 and BC5 at 16 bits, and scales every 8-bit format by 257. + ```rust use craft_dds::{DdsCompression, DdsOptions, Layout, Texture}; diff --git a/crates/dds/src/bc.rs b/crates/dds/src/bc.rs index 863aa30771..c19a393f3d 100644 --- a/crates/dds/src/bc.rs +++ b/crates/dds/src/bc.rs @@ -4,7 +4,9 @@ //! 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. +//! two of them, red then green. [`value_block`] and [`decode_values`] serve all three; +//! [`value_block16`] and [`decode_values16`] are the same blocks for 16-bit values (BC4 and BC5 +//! from 16-bit sources). //! //! 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 @@ -69,6 +71,26 @@ pub(crate) fn decode_colour(block: &[u8], one_bit_alpha: bool) -> Block { std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) } +/// [`alpha_palette`] at 16 bits: the same eight values before they are rounded to 8 bits, as a +/// decoder that interpolates at a higher precision shows them (endpoints scaled by 257, so 255 +/// is 65535). +pub(crate) fn alpha_palette16(a0: u8, a1: u8) -> [u16; 8] { + let (a0, a1) = (u32::from(a0) * 257, u32::from(a1) * 257); + let mut palette = [a0, a1, 0, 0, 0, 0, 0, 65535]; + if a0 > a1 { + for (k, v) in palette.iter_mut().enumerate().skip(2) { + let k = k as u32; + *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7; + } + } else { + for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) { + let k = k as u32; + *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5; + } + } + palette.map(|v| v as u16) +} + /// 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))); @@ -84,6 +106,14 @@ pub(crate) fn decode_values(block: &[u8]) -> [u8; 16] { std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize]) } +/// [`decode_values`] at 16 bits, from [`alpha_palette16`]. +pub(crate) fn decode_values16(block: &[u8]) -> [u16; 16] { + let byte = |i: usize| block.get(i).copied().unwrap_or(0); + let palette = alpha_palette16(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] { @@ -369,6 +399,64 @@ fn value_fit(values: &[u8; 16], inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u32) ([a0, a1, b[0], b[1], b[2], b[3], b[4], b[5]], error) } +/// [`value_block`] for 16-bit values: the endpoints are still 8 bits, but each end of each mode +/// tries the 8-bit levels just below and above the 16-bit extreme, and every candidate is scored +/// against the 16-bit palette ([`alpha_palette16`]). A block that spans less than one 8-bit level +/// is flat from 8-bit values but gets the interpolated steps between two adjacent levels here. +pub(crate) fn value_block16(values: &[u16; 16], inside: Mask) -> [u8; 8] { + let mut all: Option<(u16, u16)> = None; + let mut mid = all; + let widen = |r: Option<(u16, u16)>, v: u16| 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 | 65535) { + mid = widen(mid, v); + } + } + } + let (lo, hi) = all.unwrap_or((0, 0)); + let (mid_lo, mid_hi) = mid.unwrap_or((0, 0)); + let (down, up) = (|v: u16| (v / 257) as u8, |v: u16| v.div_ceil(257) as u8); + // The eight-value mode's pairs first (a0 the high end), then the six-value mode's: on a tie + // the eight-value mode wins, as in `value_block`. Each pair's palette follows its order, so a + // pair that lands in the other mode is still scored as the decoder reads it. + let candidates = [ + (up(hi), down(lo)), + (up(hi), up(lo)), + (down(hi), down(lo)), + (down(hi), up(lo)), + (down(mid_lo), down(mid_hi)), + (down(mid_lo), up(mid_hi)), + (up(mid_lo), down(mid_hi)), + (up(mid_lo), up(mid_hi)), + ]; + let mut best: Option<([u8; 8], u64)> = None; + for (a0, a1) in candidates { + let fit = value_fit16(values, inside, a0, a1); + if best.is_none_or(|(_, e)| fit.1 < e) { + best = Some(fit); + } + } + best.map_or([0; 8], |(bytes, _)| bytes) +} + +fn value_fit16(values: &[u16; 16], inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u64) { + let palette = alpha_palette16(a0, a1); + let mut bits = 0u64; + let mut error = 0u64; + for (t, &v) in values.iter().enumerate() { + if inside >> t & 1 == 0 { + continue; + } + let (i, d) = nearest(&palette, |&p| u32::from(p.abs_diff(v)).pow(2)); + error += u64::from(d); + bits |= (i as u64) << (3 * t); + } + let b = bits.to_le_bytes(); + ([a0, a1, b[0], b[1], b[2], b[3], b[4], b[5]], error) +} + #[cfg(test)] mod tests { use super::*; @@ -484,6 +572,36 @@ mod tests { assert_eq!(nearest::(&[], |_| 7), (0, 0)); } + #[test] + fn value_blocks_decode_the_frozen_vectors_at_16_bits() { + // Eight-value mode (200 > 50): index 2 is (6 * 200 + 50) / 7 of 255 at 16 bits, which + // the 8-bit palette rounds to 179. + let bits: u64 = (0..16).fold(0, |b, t| b | 2 << (3 * t)); + let b = bits.to_le_bytes(); + let block = [200, 50, b[0], b[1], b[2], b[3], b[4], b[5]]; + assert_eq!(decode_values16(&block), [((6 * 200 + 50) * 257 + 3) / 7; 16]); + assert_eq!(decode_values(&block), [179; 16]); + // Six-value mode's indices 6 and 7 are 0 and 65535. + let bits: u64 = (0..16).fold(0, |b, t| b | (6 + (t % 2)) << (3 * t)); + let b = bits.to_le_bytes(); + let got = decode_values16(&[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 { 65535 })); + } + + #[test] + fn value_blocks_from_16_bits_step_between_two_8_bit_levels() { + // A ramp across 0.8 of one 8-bit level: from 8 bits it is one or two flat values; from 16 + // bits the endpoints straddle it and the steps between them follow the ramp. + let values: [u16; 16] = std::array::from_fn(|t| 25_700 + (t as u16) * 13); + let error = |got: [u16; 16]| values.iter().zip(got).map(|(a, b)| u64::from(a.abs_diff(b)).pow(2)).sum::(); + let ours = error(decode_values16(&value_block16(&values, u16::MAX))); + let from_8_bits = error(decode_values16(&value_block(&values.map(|v| ((u32::from(v) + 128) / 257) as u8), u16::MAX))); + assert!(ours * 4 < from_8_bits, "{ours} vs {from_8_bits} from 8 bits"); + // Values outside the image don't count. + let solid = value_block16(&std::array::from_fn(|t| if t == 0 { 1000 } else { 60_000 }), 1); + assert!(decode_values16(&solid)[0].abs_diff(1000) < 129); + } + #[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 f7b44fc7a8..3369942856 100644 --- a/crates/dds/src/lib.rs +++ b/crates/dds/src/lib.rs @@ -2,7 +2,8 @@ //! "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 +//! described by channel masks, RGB or luminance, or 16 bits per channel: `R16_UNORM`, +//! `R16G16_UNORM`, `R16G16B16A16_UNORM`) or block-compressed BC1/BC2/BC3 //! (DXT1/DXT3/DXT5) or unsigned BC4/BC5 (ATI1/ATI2), with or without the DX10 header. BC4 opens //! as gray and BC5 as RGB with blue 0: BC5 stores only red and green, and a normal map's Z is //! left for the caller to reconstruct. Cubemaps, texture arrays and volume textures are refused @@ -14,7 +15,12 @@ //! 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 +//! Pixels are 8 bits per channel ([`encode`], [`Texture::decode`]) or 16 bits per channel +//! ([`encode16`], [`Texture::decode16`]), interleaved, top row first, in one of the [`Layout`]s. +//! Uncompressed 16-bit pixels are written with the DX10 header as `R16_UNORM` (gray), +//! `R16G16_UNORM` (gray and alpha, or any two channels such as a normal map's X and Y) or +//! `R16G16B16A16_UNORM` (RGB, with alpha 65535, and RGBA). BC4 and BC5 fit their 8-bit endpoints +//! and their indices to the 16-bit values; BC1 to BC3 round the pixels to 8 bits first. The //! crate has no dependencies; the `parallel` feature encodes and decodes rows of blocks (and mip //! levels) on several threads with rayon. //! @@ -38,7 +44,7 @@ use std::fmt; use bc::{Block, Mask}; -/// The channels of a pixel, 8 bits each, in this order. +/// The channels of a pixel, 8 or 16 bits each, in this order. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Layout { Gray, @@ -187,6 +193,8 @@ const DDSCAPS2_CUBEMAP_FACES: u32 = 0xfc00; const DDSCAPS2_VOLUME: u32 = 0x20_0000; const DIMENSION_TEXTURE2D: u32 = 3; const MISC_TEXTURECUBE: u32 = 0x4; +/// The legacy FourCC (a number, not text) of 16-bit RGBA. +const D3DFMT_A16B16G16R16: u32 = 36; fn bad(reason: impl fmt::Display) -> DdsError { DdsError::Malformed(reason.to_string()) @@ -242,6 +250,12 @@ impl Field { let max = u64::from(self.max); ((v * 255 + max / 2) / max) as u8 } + + fn get16(self, pixel: u32) -> u16 { + let v = u64::from((pixel >> self.shift) & self.max); + let max = u64::from(self.max); + ((v * 65535 + max / 2) / max) as u16 + } } #[derive(Clone, Copy)] @@ -255,6 +269,8 @@ enum Encoding { Bc1, Bc2, Bc3, + /// 16 bits per channel, little-endian: gray, gray and alpha (or red and green), or RGBA. + Unorm16 { channels: usize }, /// One value block: gray. Bc4, /// Two value blocks: red, then green. @@ -282,6 +298,8 @@ 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::Unorm16 { channels: 1 } => Layout::Gray, + Encoding::Unorm16 { channels: 2 } => Layout::GrayA, Encoding::Bc4 => Layout::Gray, Encoding::Bc5 => Layout::Rgb, _ => Layout::Rgba, @@ -291,7 +309,7 @@ impl Encoding { /// Bytes per 4×4 block; 0 for uncompressed pixels. fn block_size(&self) -> usize { match self { - Encoding::Masks { .. } => 0, + Encoding::Masks { .. } | Encoding::Unorm16 { .. } => 0, Encoding::Bc1 | Encoding::Bc4 => 8, Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc5 => 16, } @@ -301,9 +319,14 @@ impl Encoding { 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 pixel_bytes = match self { + Encoding::Masks { bytes, .. } => Some(*bytes), + Encoding::Unorm16 { channels } => Some(2 * channels), + _ => None, + }; + let (row_bytes, rows) = match pixel_bytes { + Some(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, @@ -313,9 +336,7 @@ impl Encoding { } (row_bytes, h) } - Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc4 | Encoding::Bc5 => { - (w.div_ceil(4).checked_mul(self.block_size()).ok_or_else(overflow)?, h.div_ceil(4)) - } + None => (w.div_ceil(4).checked_mul(self.block_size()).ok_or_else(overflow)?, h.div_ceil(4)), }; let size = row_bytes.checked_mul(rows).ok_or_else(overflow)?; Ok((row_bytes, size)) @@ -327,6 +348,10 @@ 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 { + // D3DFMT_A16B16G16R16, the legacy name of R16G16B16A16_UNORM (DirectXTex writes it so). + if fourcc == D3DFMT_A16B16G16R16 { + return Ok(Encoding::Unorm16 { channels: 4 }); + } return match &fourcc.to_le_bytes() { b"DXT1" => Ok(Encoding::Bc1), b"DXT3" => Ok(Encoding::Bc2), @@ -364,7 +389,7 @@ fn dx10_encoding(b: &[u8]) -> Result { } // 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) { + if le32(b, HEADER + 16)? & 0x7 == 2 && matches!(dxgi, 9 | 11 | 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]; @@ -372,6 +397,10 @@ fn dx10_encoding(b: &[u8]) -> Result { const BGRX: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0]; match dxgi { 27..=29 => Encoding::masks(32, RGBA, false), + // Typeless, then UNORM, as for BC4 and BC5 below. + 9 | 11 => Ok(Encoding::Unorm16 { channels: 4 }), + 33 | 35 => Ok(Encoding::Unorm16 { channels: 2 }), + 53 | 56 => Ok(Encoding::Unorm16 { channels: 1 }), 87 | 90 | 91 => Encoding::masks(32, BGRA, false), 88 | 92 | 93 => Encoding::masks(32, BGRX, false), 70..=72 => Ok(Encoding::Bc1), @@ -382,7 +411,7 @@ fn dx10_encoding(b: &[u8]) -> Result { 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)"))), + _ => Err(unsupported(format!("DXGI format {dxgi} is not supported (BC1 to BC5, 8-bit RGBA or BGRA and 16-bit R, RG or RGBA are)"))), } } @@ -448,6 +477,65 @@ impl<'a> Texture<'a> { /// Decode with an explicit per-buffer output byte budget; allocation remains fallible. pub fn decode_with_limit(&self, max_bytes: u64) -> Result, DdsError> { + let encoding = self.encoding; + let (data, row_pitch, total) = self.top_level(1, max_bytes)?; + let (w, channels) = (self.width as usize, encoding.layout().channels()); + let row_size = w * channels; + let mut pixels = alloc_zeroed(total)?; + match encoding { + Encoding::Masks { bytes, gray, fields } => decode_masks(Masks { bytes, gray, fields }, data, row_pitch, &mut pixels, row_size), + // Each 16-bit sample rounded to the nearest 8-bit level. + Encoding::Unorm16 { .. } => rows(&mut pixels, row_size, |y, dst| { + let src = data.get(y * row_pitch..).unwrap_or_default(); + for (d, s) in dst.iter_mut().zip(src.as_chunks::<2>().0) { + *d = to8(u16::from_le_bytes(*s)); + } + }), + Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc4 | Encoding::Bc5 => { + decode_blocks(encoding, data, (w, channels), &mut pixels) + } + } + Ok(pixels) + } + + /// The top mip level's pixels in [`Texture::layout`] at 16 bits per channel, bounded by + /// [`DEFAULT_MAX_DECODE_BYTES`]. 16-bit formats come back exactly, as do channel masks wider + /// than 8 bits; BC4 and BC5 values are interpolated at 16 bits; every other format is its + /// 8-bit value times 257 (so 255 is 65535). + pub fn decode16(&self) -> Result, DdsError> { + self.decode16_with_limit(DEFAULT_MAX_DECODE_BYTES) + } + + /// [`Texture::decode16`] with an explicit per-buffer output byte budget (two bytes a sample). + pub fn decode16_with_limit(&self, max_bytes: u64) -> Result, DdsError> { + let encoding = self.encoding; + let (data, row_pitch, total) = self.top_level(2, max_bytes)?; + let (w, channels) = (self.width as usize, encoding.layout().channels()); + let row_size = w * channels; + let mut pixels = alloc_zeroed(total / 2)?; + match encoding { + Encoding::Masks { bytes, gray, fields } => decode_masks16(Masks { bytes, gray, fields }, data, row_pitch, &mut pixels, row_size), + Encoding::Unorm16 { .. } => rows(&mut pixels, row_size, |y, dst| { + let src = data.get(y * row_pitch..).unwrap_or_default(); + for (d, s) in dst.iter_mut().zip(src.as_chunks::<2>().0) { + *d = u16::from_le_bytes(*s); + } + }), + Encoding::Bc4 | Encoding::Bc5 => decode_value_blocks16(encoding, data, (w, channels), &mut pixels), + Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 => { + // The limit was checked above for the 16-bit buffer, which is twice this one. + let narrow = self.decode_with_limit(u64::MAX)?; + for (d, v) in pixels.iter_mut().zip(narrow) { + *d = u16::from(v) * 257; + } + } + } + Ok(pixels) + } + + /// The top level's stored bytes and row stride, and the decoded size in bytes at + /// `sample_bytes` a sample, checked against `max_bytes` before the stored data is. + fn top_level(&self, sample_bytes: usize, max_bytes: u64) -> Result<(&'a [u8], usize, usize), 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. @@ -455,23 +543,21 @@ impl<'a> Texture<'a> { let (row_pitch, size) = encoding.level_layout(width, height, pitch)?; let (w, h) = (width as usize, height as usize); let channels = encoding.layout().channels(); - let row_size = w.checked_mul(channels).ok_or_else(|| bad("pixel size overflow"))?; + let row_size = w.checked_mul(channels).and_then(|n| n.checked_mul(sample_bytes)).ok_or_else(|| bad("pixel size overflow"))?; let total = row_size.checked_mul(h).ok_or_else(|| bad("pixel size overflow"))?; if total as u64 > max_bytes { return Err(DdsError::LimitExceeded { required: total, limit: max_bytes }); } let data = b.get(self.start..).and_then(|d| d.get(..size)).ok_or_else(|| bad(format!("truncated pixel data: {size} bytes needed")))?; - let mut pixels = alloc_zeroed(total)?; - match encoding { - Encoding::Masks { bytes, gray, fields } => decode_masks(Masks { bytes, gray, fields }, data, row_pitch, &mut pixels, row_size), - Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 | Encoding::Bc4 | Encoding::Bc5 => { - decode_blocks(encoding, data, (w, channels), &mut pixels) - } - } - Ok(pixels) + Ok((data, row_pitch, total)) } } +/// A 16-bit sample rounded to the nearest 8-bit level. +fn to8(v: u16) -> u8 { + ((u32::from(v) + 128) / 257) as u8 +} + /// An uncompressed pixel format: bytes per pixel, luminance or RGB, and the red (or /// luminance), green, blue and alpha fields. struct Masks { @@ -531,6 +617,51 @@ fn decode_masks(m: Masks, data: &[u8], row_pitch: usize, pixels: &mut [u8], row_ }); } +/// [`decode_masks`] at 16 bits: every field scaled to 0..=65535, so fields wider than 8 bits +/// (luminance or red and green of 16 bits) keep their precision. +fn decode_masks16(m: Masks, data: &[u8], row_pitch: usize, pixels: &mut [u16], 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()) }; + rows(pixels, row_size, |y, dst_row| { + let src_row = data.get(y * row_pitch..).unwrap_or_default(); + 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.get16(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]); + } + }); +} + +/// BC4 or BC5 blocks into 16-bit `pixels` of `width` × `channels` samples a row: gray, or red and +/// green with blue 0, interpolated at 16 bits. +fn decode_value_blocks16(encoding: Encoding, data: &[u8], (width, channels): (usize, usize), pixels: &mut [u16]) { + 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 red = bc::decode_values16(block); + let green = if matches!(encoding, Encoding::Bc5) { bc::decode_values16(block.get(8..).unwrap_or_default()) } else { [0; 16] }; + let x0 = bx * 4; + for (ty, line) in band.chunks_exact_mut(row_size).enumerate() { + let dst = line.get_mut(x0 * channels..).unwrap_or_default(); + for (tx, d) in dst.chunks_exact_mut(channels).take(4).enumerate() { + let t = ty * 4 + tx; + for (c, v) in d.iter_mut().enumerate() { + *v = match c { + 0 => red[t], + 1 => green[t], + _ => 0, + }; + } + } + } + } + }); +} + /// 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. @@ -593,19 +724,47 @@ const DDSCAPS_TEXTURE: u32 = 0x1000; const DDSCAPS_MIPMAP: u32 = 0x40_0000; const DXGI_BC4_UNORM: u32 = 80; const DXGI_BC5_UNORM: u32 = 83; +const DXGI_R16G16B16A16_UNORM: u32 = 11; +const DXGI_R16G16_UNORM: u32 = 35; +const DXGI_R16_UNORM: u32 = 56; 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> { +/// A zeroed buffer of `len` samples, or [`DdsError::Alloc`] (in bytes) 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); + v.try_reserve_exact(len).map_err(|_| DdsError::Alloc(len.saturating_mul(size_of::())))?; + v.resize(len, T::default()); Ok(v) } +/// A sample of 8 or 16 bits: what the mip chain averages and the buffers hold. +trait Sample: Copy + Default + Send + Sync { + fn wide(self) -> u32; + /// An average already within the sample's range. + fn from_average(v: u32) -> Self; +} + +impl Sample for u8 { + fn wide(self) -> u32 { + u32::from(self) + } + fn from_average(v: u32) -> u8 { + v as u8 + } +} + +impl Sample for u16 { + fn wide(self) -> u32 { + u32::from(self) + } + fn from_average(v: u32) -> u16 { + v as u16 + } +} + /// How a written texture stores its pixels. #[derive(Clone, Copy, PartialEq, Eq)] enum Store { @@ -622,6 +781,14 @@ enum Store { Bc3, Bc4, Bc5, + /// 16-bit gray (`R16_UNORM`). + R16, + /// 16-bit gray and alpha, or any two channels (`R16G16_UNORM`). + Rg16, + /// 16-bit RGB with alpha 65535 (`R16G16B16A16_UNORM`). + Rgb16, + /// 16-bit RGBA (`R16G16B16A16_UNORM`). + Rgba16, } impl Store { @@ -642,12 +809,24 @@ impl Store { }) } + /// [`Store::new`] for 16-bit pixels: uncompressed ones keep 16 bits per channel. + fn new16(compression: DdsCompression, layout: Layout) -> Result { + Ok(match (compression, layout) { + (DdsCompression::None, Layout::Gray) => Store::R16, + (DdsCompression::None, Layout::GrayA) => Store::Rg16, + (DdsCompression::None, Layout::Rgb) => Store::Rgb16, + (DdsCompression::None, Layout::Rgba) => Store::Rgba16, + _ => Store::new(compression, layout)?, + }) + } + /// 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::LuminanceAlpha | Store::R16 => 2, + Store::Bgrx | Store::Bgra | Store::Rg16 => 4, + Store::Rgb16 | Store::Rgba16 => 8, Store::Bc1 | Store::Bc4 => 8, Store::Bc2 | Store::Bc3 | Store::Bc5 => 16, } @@ -662,6 +841,9 @@ impl Store { match self { Store::Bc4 => Some(DXGI_BC4_UNORM), Store::Bc5 => Some(DXGI_BC5_UNORM), + Store::R16 => Some(DXGI_R16_UNORM), + Store::Rg16 => Some(DXGI_R16G16_UNORM), + Store::Rgb16 | Store::Rgba16 => Some(DXGI_R16G16B16A16_UNORM), _ => None, } } @@ -686,7 +868,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]), + Store::Bc4 | Store::Bc5 | Store::R16 | Store::Rg16 | Store::Rgb16 | Store::Rgba16 => (DDPF_FOURCC, *b"DX10", 0, [0; 4]), } } } @@ -708,11 +890,40 @@ pub fn encode(width: u32, height: u32, layout: Layout, pixels: &[u8], options: D return Err(encode_err("texture dimensions must be nonzero")); } let store = Store::new(options.compression, layout)?; + encode_levels((width, height), layout, pixels, store, options.mipmaps, write_level) +} + +/// [`encode`] for 16-bit pixels. Uncompressed, they keep 16 bits per channel: gray as +/// `R16_UNORM`, gray and alpha (or any two channels, such as a normal map's X and Y) as +/// `R16G16_UNORM`, RGB (with alpha 65535) and RGBA as `R16G16B16A16_UNORM`, all with the DX10 +/// header. BC4 and BC5 pick their endpoints and indices against the 16-bit values; BC1 to BC3 +/// round the pixels to 8 bits and write what [`encode`] writes from them. +pub fn encode16(width: u32, height: u32, layout: Layout, pixels: &[u16], options: DdsOptions) -> Result, DdsError> { + if width == 0 || height == 0 { + return Err(encode_err("texture dimensions must be nonzero")); + } + let store = Store::new16(options.compression, layout)?; + if matches!(store, Store::Bc1 | Store::Bc2 | Store::Bc3) { + let mut narrow = alloc_zeroed(pixels.len())?; + for (d, &v) in narrow.iter_mut().zip(pixels) { + *d = to8(v); + } + return encode(width, height, layout, &narrow, options); + } + encode_levels((width, height), layout, pixels, store, options.mipmaps, write_level16) +} + +/// A level writer: one level of `width` × `height` pixels (in the image's layout) into `dst`. +type WriteLevel = fn(Store, &[T], (usize, usize), &mut [u8]) -> Result<(), DdsError>; + +/// The header and every level of `pixels`, each written by `write`. +fn encode_levels((width, height): (u32, u32), layout: Layout, pixels: &[T], store: Store, mipmaps: bool, write: WriteLevel) -> Result, DdsError> { 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 unit = if size_of::() == 1 { "bytes" } else { "16-bit samples" }; + return Err(encode_err(format!("{} {unit} of pixels for a {width}x{height} {layout:?} texture", pixels.len()))); } - let levels = if options.mipmaps { mip_levels(width, height) } else { 1 }; + let levels = if 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(); @@ -724,7 +935,7 @@ pub fn encode(width: u32, height: u32, layout: Layout, pixels: &[u8], options: D let head = if store.dxgi().is_some() { HEADER + DX10_HEADER } else { HEADER }; let total = sizes.iter().try_fold(head, |total, &s| total.checked_add(s)).ok_or_else(|| encode_err("texture size overflow"))?; let header = header(width, height, store, levels, sizes.first().copied().unwrap_or(0))?; - let mut out = alloc_zeroed(total)?; + let mut out = alloc_zeroed::(total)?; let (Some(dst), Some(src)) = (out.get_mut(..head), header.get(..head)) else { return Err(encode_err("output buffer too small")); }; @@ -735,7 +946,7 @@ pub fn encode(width: u32, height: u32, layout: Layout, pixels: &[u8], options: D 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)?; + write(store, &level, size, dst)?; at += bytes; if i + 1 < sizes.len() { let next = half(size); @@ -777,7 +988,8 @@ fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Res } 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). + // One 2D texture, no misc flags, alpha mode unknown (straight for the one format with + // alpha, RGBA16, as readers take it). put(HEADER, dxgi); put(HEADER + 4, DIMENSION_TEXTURE2D); put(HEADER + 12, 1); @@ -788,7 +1000,7 @@ fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Res /// 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) { +fn rows(out: &mut [T], len: usize, f: impl Fn(usize, &mut [T]) + Send + Sync) { #[cfg(feature = "parallel")] { use rayon::prelude::*; @@ -804,6 +1016,8 @@ fn rows(out: &mut [u8], len: usize, f: impl Fn(usize, &mut [u8]) + Send + Sync) 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 { + // 16-bit stores are written by `write_level16`. + Store::R16 | Store::Rg16 | Store::Rgb16 | Store::Rgba16 => return Err(encode_err("16-bit storage needs 16-bit pixels")), 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"))?; @@ -851,10 +1065,44 @@ fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst Ok(()) } +/// [`write_level`] for 16-bit pixels: little-endian samples, or BC4/BC5 blocks fitted to them. +fn write_level16(store: Store, pixels: &[u16], (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::R16 | Store::Rg16 | Store::Rgba16 => { + // The image's samples, in the same order. + for (d, s) in dst.as_chunks_mut::<2>().0.iter_mut().zip(pixels) { + *d = s.to_le_bytes(); + } + } + Store::Rgb16 => rows(dst, row_bytes, |y, row| { + let src = pixels.get(y * width * 3..).unwrap_or_default(); + for (d, s) in row.as_chunks_mut::<8>().0.iter_mut().zip(src.as_chunks::<3>().0) { + let [r, g, b, a] = [s[0], s[1], s[2], u16::MAX].map(u16::to_le_bytes); + *d = [r[0], r[1], g[0], g[1], b[0], b[1], a[0], a[1]]; + } + }), + Store::Bc4 | Store::Bc5 => { + 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_block16(&values, inside); + } + } + }); + } + // `encode16` rounds BC1 to BC3 to 8 bits; the 8-bit stores take 8-bit pixels. + _ => return Err(encode_err("8-bit storage needs 8-bit pixels")), + } + 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]; +fn gather_channel(pixels: &[T], (width, height): (usize, usize), channels: usize, c: usize, (bx, by): (usize, usize)) -> ([T; 16], Mask) { + let mut values = [T::default(); 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); @@ -902,7 +1150,7 @@ fn gather(texels: &[[u8; 4]], (width, height): (usize, usize), bx: usize, by: us /// 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> { +fn downsample(src: &[T], (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 }; @@ -919,8 +1167,8 @@ fn downsample(src: &[u8], (w, h): (usize, usize), (nw, nh): (usize, usize), chan 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; + let sum = a[c].wide() + a[ch + c].wide() + b[c].wide() + b[ch + c].wide(); + *v = T::from_average((sum + 2) / 4); } } edge = interior; @@ -932,12 +1180,12 @@ fn downsample(src: &[u8], (w, h): (usize, usize), (nw, nh): (usize, usize), chan 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); + sum += s.wide(); n += 1; } } } - *v = ((sum + n / 2) / n.max(1)) as u8; + *v = T::from_average((sum + n / 2) / n.max(1)); } } }); @@ -980,4 +1228,127 @@ mod tests { assert!(matches!(texture.decode(), Err(DdsError::Malformed(_)))); assert_eq!(Texture::parse(&file).and_then(|t| t.decode()), Ok(vec![7; 64])); } + + /// Samples spread over the whole 16-bit range, `channels` a pixel. + fn spread16(width: usize, height: usize, channels: usize) -> Vec { + (0..width * height * channels).map(|i| (i as u32 * 7919 % 65536) as u16).collect() + } + + #[test] + fn uncompressed_16_bit_pixels_round_trip_exactly() { + let (w, h) = (7, 5); + for (layout, dxgi, read_as, pixel_bytes) in [(Layout::Gray, 56, Layout::Gray, 2), (Layout::GrayA, 35, Layout::GrayA, 4), (Layout::Rgb, 11, Layout::Rgba, 8), (Layout::Rgba, 11, Layout::Rgba, 8)] { + let pixels = spread16(w, h, layout.channels()); + let want: Vec = if layout == Layout::Rgb { pixels.chunks(3).flat_map(|p| [p[0], p[1], p[2], 65535]).collect() } else { pixels.clone() }; + for mipmaps in [false, true] { + let file = encode16(w as u32, h as u32, layout, &pixels, DdsOptions { compression: DdsCompression::None, mipmaps }).unwrap(); + assert_eq!(le32(&file, HEADER).unwrap(), dxgi, "{layout:?}"); + // 7×5, then 3×2 and 1×1. + let samples = if mipmaps { 7 * 5 + 3 * 2 + 1 } else { 7 * 5 }; + assert_eq!(file.len(), HEADER + DX10_HEADER + samples * pixel_bytes); + let texture = Texture::parse(&file).unwrap(); + assert_eq!(texture.layout(), read_as); + assert_eq!(texture.decode16().unwrap(), want); + assert_eq!(texture.decode().unwrap(), want.iter().map(|&v| to8(v)).collect::>()); + if layout == Layout::Rgba { + let mut premultiplied = file.clone(); + premultiplied[HEADER + 16] = 2; + assert!(matches!(Texture::parse(&premultiplied), Err(DdsError::Unsupported(_)))); + } + } + } + } + + #[test] + fn mip_levels_of_16_bit_pixels_average_at_16_bits() { + // 1000 to 1003 average to 1002 (rounded), which 8 bits can't hold. + let file = encode16(2, 2, Layout::Gray, &[1000, 1001, 1002, 1003], DdsOptions { compression: DdsCompression::None, mipmaps: true }).unwrap(); + assert_eq!(le32(&file, 28).unwrap(), 2); + assert_eq!(file[file.len() - 2..], 1002u16.to_le_bytes()); + } + + #[test] + fn legacy_16_bit_textures_decode_at_16_bits() { + // D3DFMT_A16B16G16R16: the legacy header's numeric FourCC 36, the same pixels as the + // DX10 file. + let pixels = spread16(3, 2, 4); + let file = encode16(3, 2, Layout::Rgba, &pixels, DdsOptions::default()).unwrap(); + let mut legacy = file[..HEADER].to_vec(); + legacy[84..88].copy_from_slice(&36u32.to_le_bytes()); + legacy.extend_from_slice(&file[HEADER + DX10_HEADER..]); + let texture = Texture::parse(&legacy).unwrap(); + assert_eq!((texture.layout(), texture.decode16().unwrap()), (Layout::Rgba, pixels)); + // L16: a 16-bit luminance mask keeps its 16 bits through `decode16`. + let mut l16 = encode(2, 1, Layout::Gray, &[0, 0], DdsOptions::default()).unwrap(); + l16[20..24].copy_from_slice(&4u32.to_le_bytes()); + l16[88..92].copy_from_slice(&16u32.to_le_bytes()); + l16[92..96].copy_from_slice(&0xffffu32.to_le_bytes()); + l16.truncate(HEADER); + l16.extend([300u16, 65000].iter().flat_map(|v| v.to_le_bytes())); + let texture = Texture::parse(&l16).unwrap(); + assert_eq!(texture.decode16().unwrap(), [300, 65000]); + assert_eq!(texture.decode().unwrap(), [1, 253]); + } + + #[test] + fn bc4_and_bc5_from_16_bits_beat_the_8_bit_rounded_source() { + // Smooth ramps, about half an 8-bit level across a block, as in height and normal maps. + // 62×61 leaves partial blocks on the right and bottom edges. + let (w, h) = (62usize, 61usize); + let at = |i: usize| (i % w, i / w); + let height: Vec = (0..w * h).map(|i| (20_000 + at(i).0 * 29 + at(i).1 * 11) as u16).collect(); + let normal: Vec = (0..w * h).flat_map(|i| [(10_000 + at(i).0 * 23 + at(i).1 * 7) as u16, (40_000 + at(i).1 * 27 + at(i).0 * 5) as u16, 65535]).collect(); + for (compression, layout, pixels) in [(DdsCompression::Bc4, Layout::Gray, &height), (DdsCompression::Bc5, Layout::Rgb, &normal)] { + let options = DdsOptions { compression, mipmaps: true }; + let rounded: Vec = pixels.iter().map(|&v| to8(v)).collect(); + let from16 = Texture::parse(&encode16(w as u32, h as u32, layout, pixels, options).unwrap()).unwrap(); + let from8 = Texture::parse(&encode(w as u32, h as u32, layout, &rounded, options).unwrap()).unwrap(); + let channels = layout.channels(); + // Root-mean-square error of the stored channels (BC5: red and green), in 16-bit units. + let rms = |got: &[u16]| { + let stored = pixels.iter().zip(got).enumerate().filter(|(i, _)| i % channels < 2); + let (sum, n) = stored.fold((0f64, 0f64), |(sum, n), (_, (&a, &b))| (sum + (f64::from(a) - f64::from(b)).powi(2), n + 1.0)); + (sum / n).sqrt() + }; + let (ours, theirs) = (rms(&from16.decode16().unwrap()), rms(&from8.decode16().unwrap())); + eprintln!("{compression:?}: RMS error {ours:.1} from 16 bits, {theirs:.1} from the 8-bit rounded source (16-bit units)"); + assert!(ours * 2.0 < theirs, "{compression:?}: {ours} vs {theirs}"); + // `decode` and `decode16` read the same blocks: 8 bits are the 16-bit values rounded, + // give or take the 8-bit palette's own rounding. + for texture in [&from16, &from8] { + let (narrow, wide) = (texture.decode().unwrap(), texture.decode16().unwrap()); + assert!(narrow.iter().zip(&wide).all(|(&a, &b)| a.abs_diff(to8(b)) <= 1)); + } + } + } + + #[test] + fn bc1_to_bc3_from_16_bits_write_what_the_rounded_pixels_write() { + let pixels = spread16(6, 5, 4); + let rounded: Vec = pixels.iter().map(|&v| to8(v)).collect(); + for compression in [DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3] { + for mipmaps in [false, true] { + let options = DdsOptions { compression, mipmaps }; + assert_eq!(encode16(6, 5, Layout::Rgba, &pixels, options), encode(6, 5, Layout::Rgba, &rounded, options)); + } + } + // `encode16` takes the layouts `encode` takes, and checks the buffer size the same way. + for compression in DdsCompression::ALL { + for layout in [Layout::Gray, Layout::GrayA, Layout::Rgb, Layout::Rgba] { + let options = DdsOptions { compression, mipmaps: false }; + let n = layout.channels(); + assert_eq!(encode16(1, 1, layout, &[9; 4][..n], options).is_ok(), encode(1, 1, layout, &[9; 4][..n], options).is_ok(), "{compression:?} from {layout:?}"); + } + } + assert!(matches!(encode16(2, 2, Layout::Rgb, &[0; 11], DdsOptions::default()), Err(DdsError::Encode(_)))); + assert!(matches!(encode16(0, 2, Layout::Rgb, &[], DdsOptions::default()), Err(DdsError::Encode(_)))); + } + + #[test] + fn decode16_checks_its_budget_in_bytes() { + let file = encode16(4, 4, Layout::Gray, &[7; 16], DdsOptions::default()).unwrap(); + let texture = Texture::parse(&file).unwrap(); + assert!(matches!(texture.decode16_with_limit(31), Err(DdsError::LimitExceeded { required: 32, limit: 31 }))); + assert_eq!(texture.decode16_with_limit(32).unwrap(), [7; 16]); + } } From 5ef5134ccc28db3a3aaba1e1a0c189340c5d277c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 15:55:15 -0500 Subject: [PATCH 056/144] image-codecs: keep stored WebP dimensions independent of EXIF compatibility (#1921) --- crates/image-codecs/src/webp_probe.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/image-codecs/src/webp_probe.rs b/crates/image-codecs/src/webp_probe.rs index 07d6e0269e..4a31def009 100644 --- a/crates/image-codecs/src/webp_probe.rs +++ b/crates/image-codecs/src/webp_probe.rs @@ -25,9 +25,10 @@ pub fn header(bytes: &[u8]) -> Result<(u32, u32, u16), CodecError> { if !has_image { return Err(err("no image data")); } - let (w, h) = crate::probe_size(bytes)?; + // Read stored dimensions directly. Undoing probe_size with the compatibility EXIF + // orientation is incorrect when its lenient parser disagrees with the strict one. + let (w, h, _) = crate::codecs::webp::probe(bytes, &crate::Limits::default())?; let orientation = exif.map_or(1, craft_metadata::compat_orientation::orientation); - let (w, h) = if (5..=8).contains(&orientation) { (h, w) } else { (w, h) }; Ok((w, h, orientation)) } @@ -47,6 +48,20 @@ mod tests { assert_eq!(header(&bytes).unwrap(), (2, 3, 6)); } + #[test] + fn malformed_exif_does_not_swap_stored_dimensions() { + let mut image = crate::Image::from_u8(2, 3, crate::ChannelLayout::Rgb, vec![42; 18]).unwrap(); + image.meta.exif = Some(b"II\x2a\x00\x08\x00\x00\x00\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00\x00\x00\x00\x00".to_vec()); + let mut bytes = crate::encode(&image, Format::WebP, &crate::EncodeOptions::default()).unwrap(); + let exif = bytes.windows(4).position(|v| v == b"EXIF").unwrap() + 8; + bytes[exif + 18] = 6; + // Compatibility metadata preserves orientation despite a malformed count; + // the strict orientation used by probe_size rejects it. Stored size is neither. + bytes[exif + 14..exif + 18].copy_from_slice(&0u32.to_le_bytes()); + assert_eq!(crate::probe_size(&bytes).unwrap(), (2, 3)); + assert_eq!(header(&bytes).unwrap(), (2, 3, 6)); + } + #[test] fn rejects_missing_and_truncated_image_chunks() { let mut bytes = b"RIFF\x00\x00\x00\x00WEBP".to_vec(); From e4d27fc1cd030be8c1d163220d07f9a00ee0fb8d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 21:58:20 +0100 Subject: [PATCH 057/144] fcproj-format: schema v18 for camera raw Source Settings A no-op v17 -> v18 step so FilmCraft can save per-clip camera raw Source Settings (Interpretation::raw) and older builds refuse such projects instead of dropping the settings on save. Library part of storytold/filmcraft#1078 (Part of storytold/filmcraft#1065); the MXF CinemaDNG part already landed in #1145. --- crates/fcproj-format/src/lib.rs | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/fcproj-format/src/lib.rs b/crates/fcproj-format/src/lib.rs index 98e50cf590..4ac1b72439 100644 --- a/crates/fcproj-format/src/lib.rs +++ b/crates/fcproj-format/src/lib.rs @@ -13,7 +13,7 @@ pub type Migration = fn(Value) -> Result; /// edit a shipped one. pub const MIGRATIONS: &[Migration] = &[ v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9, v9_to_v10, v10_to_v11, v11_to_v12, v12_to_v13, v13_to_v14, - v14_to_v15, v15_to_v16, v16_to_v17, + v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, ]; /// The schema version this build writes (and the newest it reads). @@ -252,6 +252,14 @@ fn v16_to_v17(doc: Value) -> Result { Ok(doc) } +/// v17 → v18: camera raw Source Settings on media items (`Interpretation::raw`: white balance, +/// exposure, highlights, demosaic quality and output colour space of DNG / CinemaDNG footage; +/// absent = as the file says). Existing data needs no change; older builds must refuse such +/// projects instead of silently dropping the settings when saving. +fn v17_to_v18(doc: Value) -> Result { + Ok(doc) +} + #[cfg(test)] mod tests { use super::*; @@ -262,10 +270,10 @@ mod tests { let bare = json!({"version": 2, "items": {}, "root": {}, "extra": [1, 2]}); assert_eq!(detect_version(&bare).unwrap(), 1); let migrated = migrate_with(MIGRATIONS, bare, 1).unwrap(); - assert_eq!(migrated["schema_version"], 17); + assert_eq!(migrated["schema_version"], 18); assert_eq!(migrated["project"]["extra"], json!([1, 2])); assert_eq!(migrated["generator"], "FilmCraft (schema v1)"); - assert_eq!(detect_bytes(serde_json::to_string(&migrated).unwrap().as_bytes()).unwrap(), 17); + assert_eq!(detect_bytes(serde_json::to_string(&migrated).unwrap().as_bytes()).unwrap(), 18); let parsed: EnvelopeIn = serde_json::from_value(migrated).unwrap(); assert!(parsed.view.is_none()); assert_eq!(parsed.project["extra"], json!([1, 2])); @@ -286,10 +294,27 @@ mod tests { assert_eq!(version, 1); assert_eq!(file.project["name"], "Cut"); } + /// Schema 18 (camera raw Source Settings): a v17 project upgrades with its data untouched, and a + /// v18 project with `interpret.raw` settings is read rather than refused as too new. + #[test] + fn v17_upgrades_and_v18_raw_settings_are_read() { + let item = json!({"Media": {"interpret": {"par": [1, 1]}}}); + let v17 = json!({"format": FORMAT_ID, "schema_version": 17, "project": {"items": {"1": {"kind": item}}, "root": {}}}); + let up = migrate_with(MIGRATIONS, v17.clone(), 17).unwrap(); + assert_eq!(up["schema_version"], 18); + assert_eq!(up["project"], v17["project"]); + let raw = json!({"white_balance": {"Custom": {"temperature": 3200.0, "tint": 12.5}}, "exposure": -0.75}); + let mut v18 = up; + v18["project"]["items"]["1"]["kind"]["Media"]["interpret"]["raw"] = raw.clone(); + let bytes = serde_json::to_vec(&v18).unwrap(); + let (file, version): (EnvelopeIn, _) = decode(&bytes).unwrap(); + assert_eq!(version, 18); + assert_eq!(file.project["items"]["1"]["kind"]["Media"]["interpret"]["raw"], raw); + } #[test] fn rejects_wrong_future_and_damaged_envelopes() { assert!(matches!(detect_bytes(br#"{"format":"other","schema_version":1}"#), Err(FormatError::NotAProject(_)))); - assert!(matches!(detect_bytes(br#"{"schema_version":18}"#), Err(FormatError::TooNew { found: 18, supported: 17 }))); + assert!(matches!(detect_bytes(br#"{"schema_version":19}"#), Err(FormatError::TooNew { found: 19, supported: 18 }))); assert!(matches!(detect_bytes(br#"{"schema_version":0}"#), Err(FormatError::TooOld { found: 0, oldest: 1 }))); assert!(matches!(detect_bytes(b"{"), Err(FormatError::Corrupt(_)))); assert!(matches!(migrate_with(MIGRATIONS, json!([]), 1), Err(FormatError::Migration { from: 1, .. }))); From 853f630d6d54eccc90a6a018fc03fabe698880fc Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 16 Nov 2026 21:59:19 +0100 Subject: [PATCH 058/144] dds: review fixes for 16-bit support Reword decode16 and DdsCompression::None docs, check the 16-bit buffer length before narrowing for BC1-BC3, and test typeless DXGI codes, padded 16-bit rows, G16R16 masks and decode16 of BC1. --- crates/dds/README.md | 4 +- crates/dds/src/bc.rs | 2 +- crates/dds/src/lib.rs | 105 +++++++++++++++++++++++++++++++++++------- 3 files changed, 92 insertions(+), 19 deletions(-) diff --git a/crates/dds/README.md b/crates/dds/README.md index 7a25eb36e3..2dae26bc10 100644 --- a/crates/dds/README.md +++ b/crates/dds/README.md @@ -35,7 +35,9 @@ and alpha, and RGBA. BC4 and BC5 keep 8-bit endpoints, as the formats store them and the indices against the 16-bit values, so a smooth height or normal map has less error than when its 8-bit rounding is compressed. BC1 to BC3 round the pixels to 8 bits first. `Texture::decode` rounds 16-bit formats to 8 bits; `Texture::decode16` returns them exactly, -interpolates BC4 and BC5 at 16 bits, and scales every 8-bit format by 257. +rescales channel-mask fields from their own width (a 16-bit luminance field exactly), +interpolates BC4 and BC5 at 16 bits, and scales BC1 to BC3 by 257. `craft-image-codecs` still +reads DDS at 8 bits. ```rust use craft_dds::{DdsCompression, DdsOptions, Layout, Texture}; diff --git a/crates/dds/src/bc.rs b/crates/dds/src/bc.rs index c19a393f3d..7000a09e41 100644 --- a/crates/dds/src/bc.rs +++ b/crates/dds/src/bc.rs @@ -579,7 +579,7 @@ mod tests { let bits: u64 = (0..16).fold(0, |b, t| b | 2 << (3 * t)); let b = bits.to_le_bytes(); let block = [200, 50, b[0], b[1], b[2], b[3], b[4], b[5]]; - assert_eq!(decode_values16(&block), [((6 * 200 + 50) * 257 + 3) / 7; 16]); + assert_eq!(decode_values16(&block), [(((6 * 200 + 50) * 257 + 3) / 7_u32) as u16; 16]); assert_eq!(decode_values(&block), [179; 16]); // Six-value mode's indices 6 and 7 are 0 and 65535. let bits: u64 = (0..16).fold(0, |b, t| b | (6 + (t % 2)) << (3 * t)); diff --git a/crates/dds/src/lib.rs b/crates/dds/src/lib.rs index 3369942856..183ec4fa14 100644 --- a/crates/dds/src/lib.rs +++ b/crates/dds/src/lib.rs @@ -11,7 +11,7 @@ //! //! 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 +//! but BC4, BC5 and the 16-bit formats, 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. //! @@ -105,7 +105,7 @@ impl std::error::Error for DdsError {} #[non_exhaustive] pub enum DdsCompression { /// Uncompressed, 8 bits per channel: BGRA (BGRX without alpha), or luminance with or - /// without alpha for grayscale. Lossless. + /// without alpha for grayscale. From [`encode16`], 16 bits per channel instead. Lossless. #[default] None, /// BC1 (DXT1): 4 bits per pixel. Alpha is on or off: texels under half opacity become @@ -270,7 +270,9 @@ enum Encoding { Bc2, Bc3, /// 16 bits per channel, little-endian: gray, gray and alpha (or red and green), or RGBA. - Unorm16 { channels: usize }, + Unorm16 { + channels: usize, + }, /// One value block: gray. Bc4, /// Two value blocks: red, then green. @@ -499,9 +501,10 @@ impl<'a> Texture<'a> { } /// The top mip level's pixels in [`Texture::layout`] at 16 bits per channel, bounded by - /// [`DEFAULT_MAX_DECODE_BYTES`]. 16-bit formats come back exactly, as do channel masks wider - /// than 8 bits; BC4 and BC5 values are interpolated at 16 bits; every other format is its - /// 8-bit value times 257 (so 255 is 65535). + /// [`DEFAULT_MAX_DECODE_BYTES`]. 16-bit formats come back exactly; channel-mask fields are + /// rescaled from their own width to 0..=65535 (a 16-bit luminance field exactly, an 8-bit one + /// times 257); BC4 and BC5 values are interpolated at 16 bits; BC1 to BC3 are their 8-bit + /// values times 257 (so 255 is 65535). pub fn decode16(&self) -> Result, DdsError> { self.decode16_with_limit(DEFAULT_MAX_DECODE_BYTES) } @@ -903,6 +906,7 @@ pub fn encode16(width: u32, height: u32, layout: Layout, pixels: &[u16], options return Err(encode_err("texture dimensions must be nonzero")); } let store = Store::new16(options.compression, layout)?; + check_len((width, height), layout, pixels)?; if matches!(store, Store::Bc1 | Store::Bc2 | Store::Bc3) { let mut narrow = alloc_zeroed(pixels.len())?; for (d, &v) in narrow.iter_mut().zip(pixels) { @@ -913,16 +917,29 @@ pub fn encode16(width: u32, height: u32, layout: Layout, pixels: &[u16], options encode_levels((width, height), layout, pixels, store, options.mipmaps, write_level16) } -/// A level writer: one level of `width` × `height` pixels (in the image's layout) into `dst`. -type WriteLevel = fn(Store, &[T], (usize, usize), &mut [u8]) -> Result<(), DdsError>; - -/// The header and every level of `pixels`, each written by `write`. -fn encode_levels((width, height): (u32, u32), layout: Layout, pixels: &[T], store: Store, mipmaps: bool, write: WriteLevel) -> Result, DdsError> { +/// Refuses a pixel buffer that isn't `width` × `height` pixels of `layout`. +fn check_len((width, height): (u32, u32), layout: Layout, pixels: &[T]) -> Result<(), DdsError> { let expected = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(layout.channels())); if expected != Some(pixels.len()) { let unit = if size_of::() == 1 { "bytes" } else { "16-bit samples" }; return Err(encode_err(format!("{} {unit} of pixels for a {width}x{height} {layout:?} texture", pixels.len()))); } + Ok(()) +} + +/// A level writer: one level of `width` × `height` pixels (in the image's layout) into `dst`. +type WriteLevel = fn(Store, &[T], (usize, usize), &mut [u8]) -> Result<(), DdsError>; + +/// The header and every level of `pixels`, each written by `write`. +fn encode_levels( + (width, height): (u32, u32), + layout: Layout, + pixels: &[T], + store: Store, + mipmaps: bool, + write: WriteLevel, +) -> Result, DdsError> { + check_len((width, height), layout, pixels)?; let levels = if mipmaps { mip_levels(width, height) } else { 1 }; let top = (width as usize, height as usize); // Every level's size, checked before anything is allocated. @@ -1237,9 +1254,15 @@ mod tests { #[test] fn uncompressed_16_bit_pixels_round_trip_exactly() { let (w, h) = (7, 5); - for (layout, dxgi, read_as, pixel_bytes) in [(Layout::Gray, 56, Layout::Gray, 2), (Layout::GrayA, 35, Layout::GrayA, 4), (Layout::Rgb, 11, Layout::Rgba, 8), (Layout::Rgba, 11, Layout::Rgba, 8)] { + for (layout, dxgi, read_as, pixel_bytes) in [ + (Layout::Gray, 56, Layout::Gray, 2), + (Layout::GrayA, 35, Layout::GrayA, 4), + (Layout::Rgb, 11, Layout::Rgba, 8), + (Layout::Rgba, 11, Layout::Rgba, 8), + ] { let pixels = spread16(w, h, layout.channels()); - let want: Vec = if layout == Layout::Rgb { pixels.chunks(3).flat_map(|p| [p[0], p[1], p[2], 65535]).collect() } else { pixels.clone() }; + let want: Vec = + if layout == Layout::Rgb { pixels.chunks(3).flat_map(|p| [p[0], p[1], p[2], 65535]).collect() } else { pixels.clone() }; for mipmaps in [false, true] { let file = encode16(w as u32, h as u32, layout, &pixels, DdsOptions { compression: DdsCompression::None, mipmaps }).unwrap(); assert_eq!(le32(&file, HEADER).unwrap(), dxgi, "{layout:?}"); @@ -1288,6 +1311,40 @@ mod tests { let texture = Texture::parse(&l16).unwrap(); assert_eq!(texture.decode16().unwrap(), [300, 65000]); assert_eq!(texture.decode().unwrap(), [1, 253]); + // G16R16 as masks (red low, green high) reads as RGB at 16 bits, blue 0. + let mut g16r16 = l16[..HEADER].to_vec(); + g16r16[80..84].copy_from_slice(&DDPF_RGB.to_le_bytes()); + g16r16[20..24].copy_from_slice(&8u32.to_le_bytes()); + g16r16[88..92].copy_from_slice(&32u32.to_le_bytes()); + g16r16[96..100].copy_from_slice(&0xffff_0000u32.to_le_bytes()); + g16r16.extend([300u16, 40000, 65535, 7].iter().flat_map(|v| v.to_le_bytes())); + let texture = Texture::parse(&g16r16).unwrap(); + assert_eq!((texture.layout(), texture.decode16().unwrap()), (Layout::Rgb, vec![300, 40000, 0, 65535, 7, 0])); + } + + #[test] + fn typeless_and_padded_16_bit_textures_are_read() { + // Rows padded to 8 bytes, as other writers may store them: the padding is skipped. + let file = encode16(3, 2, Layout::Gray, &[1, 2, 3, 4, 5, 6], DdsOptions::default()).unwrap(); + let mut padded = file[..HEADER + DX10_HEADER].to_vec(); + padded[20..24].copy_from_slice(&8u32.to_le_bytes()); + for row in file[HEADER + DX10_HEADER..].chunks(6) { + padded.extend_from_slice(row); + padded.extend_from_slice(&[0xee, 0xee]); + } + assert_eq!(Texture::parse(&padded).unwrap().decode16().unwrap(), [1, 2, 3, 4, 5, 6]); + // The typeless forms read as the UNORM ones; typeless RGBA refuses premultiplied alpha too. + for (unorm, typeless, layout) in [(56u32, 53u32, Layout::Gray), (35, 33, Layout::GrayA), (11, 9, Layout::Rgba)] { + let pixels = spread16(3, 2, layout.channels()); + let file = encode16(3, 2, layout, &pixels, DdsOptions::default()).unwrap(); + assert_eq!(le32(&file, HEADER).unwrap(), unorm); + let mut retyped = file.clone(); + retyped[HEADER..HEADER + 4].copy_from_slice(&typeless.to_le_bytes()); + let texture = Texture::parse(&retyped).unwrap(); + assert_eq!((texture.layout(), texture.decode16().unwrap()), (layout, pixels)); + retyped[HEADER + 16] = 2; + assert_eq!(Texture::parse(&retyped).is_err(), layout == Layout::Rgba); + } } #[test] @@ -1297,12 +1354,15 @@ mod tests { let (w, h) = (62usize, 61usize); let at = |i: usize| (i % w, i / w); let height: Vec = (0..w * h).map(|i| (20_000 + at(i).0 * 29 + at(i).1 * 11) as u16).collect(); - let normal: Vec = (0..w * h).flat_map(|i| [(10_000 + at(i).0 * 23 + at(i).1 * 7) as u16, (40_000 + at(i).1 * 27 + at(i).0 * 5) as u16, 65535]).collect(); + let normal: Vec = + (0..w * h).flat_map(|i| [(10_000 + at(i).0 * 23 + at(i).1 * 7) as u16, (40_000 + at(i).1 * 27 + at(i).0 * 5) as u16, 65535]).collect(); for (compression, layout, pixels) in [(DdsCompression::Bc4, Layout::Gray, &height), (DdsCompression::Bc5, Layout::Rgb, &normal)] { let options = DdsOptions { compression, mipmaps: true }; let rounded: Vec = pixels.iter().map(|&v| to8(v)).collect(); - let from16 = Texture::parse(&encode16(w as u32, h as u32, layout, pixels, options).unwrap()).unwrap(); - let from8 = Texture::parse(&encode(w as u32, h as u32, layout, &rounded, options).unwrap()).unwrap(); + let (file16, file8) = + (encode16(w as u32, h as u32, layout, pixels, options).unwrap(), encode(w as u32, h as u32, layout, &rounded, options).unwrap()); + let from16 = Texture::parse(&file16).unwrap(); + let from8 = Texture::parse(&file8).unwrap(); let channels = layout.channels(); // Root-mean-square error of the stored channels (BC5: red and green), in 16-bit units. let rms = |got: &[u16]| { @@ -1337,10 +1397,21 @@ mod tests { for layout in [Layout::Gray, Layout::GrayA, Layout::Rgb, Layout::Rgba] { let options = DdsOptions { compression, mipmaps: false }; let n = layout.channels(); - assert_eq!(encode16(1, 1, layout, &[9; 4][..n], options).is_ok(), encode(1, 1, layout, &[9; 4][..n], options).is_ok(), "{compression:?} from {layout:?}"); + assert_eq!( + encode16(1, 1, layout, &[9; 4][..n], options).is_ok(), + encode(1, 1, layout, &[9; 4][..n], options).is_ok(), + "{compression:?} from {layout:?}" + ); } } assert!(matches!(encode16(2, 2, Layout::Rgb, &[0; 11], DdsOptions::default()), Err(DdsError::Encode(_)))); + let bc1 = DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }; + assert_eq!(encode16(1, 1, Layout::Rgba, &[0; 3], bc1), Err(DdsError::Encode("3 16-bit samples of pixels for a 1x1 Rgba texture".into()))); + // Reading BC1 to BC3 at 16 bits: their 8-bit values times 257. + let file = encode16(6, 5, Layout::Rgba, &pixels, bc1).unwrap(); + let texture = Texture::parse(&file).unwrap(); + let narrow = texture.decode().unwrap(); + assert_eq!(texture.decode16().unwrap(), narrow.iter().map(|&v| u16::from(v) * 257).collect::>()); assert!(matches!(encode16(0, 2, Layout::Rgb, &[], DdsOptions::default()), Err(DdsError::Encode(_)))); } From 892ef9116c432d7afb5c08aba93e93a4e0b1548f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 16:21:25 -0500 Subject: [PATCH 059/144] ci: accept moved stable rust toolchain pin (#1472) From deaee4e8e10ad3e4a2406b8fe7213562d5e538c2 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Mon, 16 Nov 2026 16:47:28 -0500 Subject: [PATCH 060/144] craft-mesh: decode a glTF data URI's percent escapes to bytes A base64 body with `%2B`, `%2F` or `%3D` escapes was refused as bad base64, and a plain body lost every escaped byte that was not UTF-8 to U+FFFD. Escapes are now decoded to bytes first, then base64 when the URI says so. `uri_decode` is unchanged for file names. Closes #1936 Co-Authored-By: Claude Opus 5.5 --- crates/mesh/src/gltf.rs | 13 ++++++++++--- crates/mesh/src/tests/gltf.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/mesh/src/gltf.rs b/crates/mesh/src/gltf.rs index 9d45a4453e..e92b1fcbaf 100644 --- a/crates/mesh/src/gltf.rs +++ b/crates/mesh/src/gltf.rs @@ -115,6 +115,11 @@ pub use crate::base64_decode; /// Percent-decode a URI. A `%` that two hex digits do not follow stays as it is. pub fn uri_decode(s: &str) -> String { + String::from_utf8_lossy(&percent_decode(s)).into_owned() +} + +/// [`uri_decode`] as bytes, so escaped bytes that are not UTF-8 survive. +fn percent_decode(s: &str) -> Vec { let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); let mut i = 0; @@ -128,7 +133,7 @@ pub fn uri_decode(s: &str) -> String { i += 1; } } - String::from_utf8_lossy(&out).into_owned() + out } /// The media type and bytes of a `data:` URI. @@ -137,10 +142,12 @@ fn data_uri(uri: &str) -> Option)>> { Some((|| { let (meta, data) = rest.split_once(',').ok_or_else(|| malformed(KIND, "a data URI without a comma"))?; let mime = meta.split(';').next().unwrap_or("").to_string(); + // Any character may be escaped (RFC 3986 2.1), base64's `+`, `/` and `=` included. + let bytes = percent_decode(data); let bytes = if meta.ends_with(";base64") { - base64_decode(data).ok_or_else(|| malformed(KIND, "bad base64 in a data URI"))? + std::str::from_utf8(&bytes).ok().and_then(base64_decode).ok_or_else(|| malformed(KIND, "bad base64 in a data URI"))? } else { - uri_decode(data).into_bytes() + bytes }; Ok((mime, bytes)) })()) diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index d35b63d579..d1386dce23 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -152,6 +152,34 @@ fn gltf_text(buffer: &str, image: &str) -> (Vec, Vec) { (serde_json::to_vec(&doc).unwrap(), b.bin) } +/// What a `.gltf` file holding `buffer` and `image` as URIs reads as: the image's bytes, or +/// the error. +fn embedded(buffer: &str, image: &str) -> std::result::Result>, Error> { + let (doc, _) = gltf_text(buffer, image); + read(&doc, &Limits::default(), &mut |_| None).map(|s| s.images[0].data.clone()) +} + +/// A data URI may escape any character (RFC 3986 §2.1), base64's `+`, `/` and `=` included. +#[test] +fn percent_escapes_in_a_data_uri_are_decoded_to_bytes() { + let bin = gltf_text("", "").1; + let buffer = format!("data:application/octet-stream;base64,{}", base64(&bin)); + // 0xFB 0xFF 0xBF: "+/+/" in base64. + let image = [0xFB, 0xFF, 0xBF, 0xFB, 0xFF, 0xBF]; + assert_eq!(base64(&image), "+/+/+/+/"); + let escaped = |s: &str| s.replace('+', "%2B").replace('/', "%2f").replace('=', "%3D"); + let want = Some(image.to_vec()); + let plain_image = format!("data:image/png;base64,{}", base64(&image)); + let (head, body) = buffer.split_once(',').unwrap(); + let every = format!("{head},{}", body.bytes().map(|c| format!("%{c:02X}")).collect::()); + assert_eq!(embedded(&every, &plain_image).unwrap(), want, "a buffer escaped throughout"); + assert_eq!(embedded(&buffer, &escaped(&plain_image)).unwrap(), want, "an escaped image"); + // Not base64: the escaped bytes as they are, high bytes too. + assert_eq!(embedded(&buffer, "data:image/png,%FB%FF%BF%FB%ff%bf").unwrap(), want); + assert_eq!(embedded(&buffer, "data:,a%20b%").unwrap(), Some(b"a b%".to_vec())); + assert_eq!(embedded(&buffer, "data:image/png;base64,%25").unwrap(), None, "an escaped % is not base64"); +} + #[test] fn embedded_and_external_resources() { // Embedded: data URIs for the buffer and the image. From 8c1498d1f82308ea4bc5ac744e83d1f62b11dbd8 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Mon, 16 Nov 2026 16:53:23 -0500 Subject: [PATCH 061/144] craft-mesh: warn when glTF morph targets or other scenes are left out A primitive's morph targets are not read, and only one scene becomes the roots. Both now add a warning: a count of the primitives drawn in their base shape, and which scene of how many was read. Closes #1938. Co-Authored-By: Claude Opus 5.5 --- crates/mesh/src/gltf.rs | 15 ++++++++++++--- crates/mesh/src/tests/gltf.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/mesh/src/gltf.rs b/crates/mesh/src/gltf.rs index 9d45a4453e..2581aeafdc 100644 --- a/crates/mesh/src/gltf.rs +++ b/crates/mesh/src/gltf.rs @@ -15,8 +15,9 @@ //! same accessors), and each primitive a [`Part`]. //! //! Not read: required extensions that change how geometry is stored (Draco, meshopt) are -//! [`Error::Unsupported`]; points, lines, morph targets and -//! other extensions are passed over (skipped primitives are counted in a warning). +//! [`Error::Unsupported`]; points, lines, morph targets, scenes other than the default and +//! other extensions are passed over (skipped primitives, primitives with morph targets and the +//! other scenes are named in warnings). //! //! Buffers are needed to read anything, so an external buffer is asked of the resolver (by its //! percent-decoded URI) and is [`Error::Missing`] when declined. External images are only named @@ -345,6 +346,7 @@ impl Doc<'_> { struct Skipped { triangles: usize, primitives: usize, + morphs: usize, } fn rows_of(v: &[f64]) -> impl Iterator + '_ { @@ -439,6 +441,7 @@ fn primitive(d: &Doc, p: &Value, mesh: &mut Mesh, shared: &mut Shared, materials return Ok(()); }; charge(&d.parts_left, 1, "primitives")?; + skipped.morphs += usize::from(!arr(p, "targets").is_empty()); let key = attrs.to_string(); let ([base, normal_base, uv_base, tangent_base], nv) = match shared.get(&key) { Some(known) => *known, @@ -648,7 +651,12 @@ fn nodes(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { children: indices(n, "children", list.len()), }); } - scene.roots = match arr(j, "scenes").get(idx(j, "scene").unwrap_or(0)).or_else(|| arr(j, "scenes").first()) { + let scenes = arr(j, "scenes"); + let chosen = idx(j, "scene").filter(|s| *s < scenes.len()).unwrap_or(0); + if scenes.len() > 1 { + scene.warnings.push(format!("scene {chosen} of {} was read; the others were left out", scenes.len())); + } + scene.roots = match scenes.get(chosen) { Some(s) => indices(s, "nodes", list.len()), None => { // No scene: every node that is nobody's child. @@ -832,6 +840,7 @@ pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result { animations(&d, limits, &mut scene)?; count_warning(&mut scene.warnings, skipped.primitives, "primitive(s) are points, lines or have no positions and were left out"); count_warning(&mut scene.warnings, skipped.triangles, "triangle(s) could not be read and were left out"); + count_warning(&mut scene.warnings, skipped.morphs, "primitive(s) have morph targets, which were left out (drawn in the base shape)"); // A hierarchy with a cycle, or one too deep to walk, is refused here rather than by every caller. scene.instances(limits)?; Ok(scene) diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index d35b63d579..0e6733b657 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -829,3 +829,33 @@ fn specular_glossiness_and_webp_textures() { let plain = &s.materials[1]; assert_eq!((plain.base_color, plain.metallic, plain.roughness, plain.base_color_texture), ([1.0; 4], 0.0, 0.0, None)); } + +#[test] +fn morph_targets_and_other_scenes_are_named_in_warnings() { + let mut b = B::default(); + let p = b.f32s(&QUAD[..9], "VEC3", 3); + let d = b.f32s(&[0.0; 9], "VEC3", 3); + let plain = json!({ "attributes": { "POSITION": p } }); + let morphed = json!({ "attributes": { "POSITION": p }, "targets": [{ "POSITION": d }] }); + let doc = |scene: Value, scenes: Value| { + b.glb(json!({ + "scene": scene, + "scenes": scenes, + "nodes": [{ "mesh": 0 }, { "mesh": 0 }], + "meshes": [{ "primitives": [plain, morphed, morphed] }], + })) + }; + let s = parse(&doc(json!(1), json!([{ "nodes": [0] }, { "nodes": [1] }, { "nodes": [] }]))).unwrap(); + assert_eq!(s.roots, [1]); + assert_eq!( + s.warnings, + ["scene 1 of 3 was read; the others were left out", "2 primitive(s) have morph targets, which were left out (drawn in the base shape)",] + ); + // The morphed primitives are still drawn, in their base shape. + assert_eq!(s.meshes[0].parts.len(), 3); + // One scene, or an out-of-range choice, is not a warning about scenes. + let one = parse(&doc(json!(5), json!([{ "nodes": [0] }]))).unwrap(); + assert_eq!((one.roots.as_slice(), one.warnings.len()), ([0].as_slice(), 1)); + let s = parse(&one_mesh(&b, plain.clone())).unwrap(); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); +} From 511e260d23fecfd5839cad2220999f998638097a Mon Sep 17 00:00:00 2001 From: KenM76 Date: Mon, 16 Nov 2026 16:55:57 -0500 Subject: [PATCH 062/144] craft-mesh: test every scene choice; README names the new warnings The README's glTF "Not read" line was doubled and listed sparse accessors and tangents, which are read. Co-Authored-By: Claude Opus 5.5 --- crates/mesh/README.md | 6 +++--- crates/mesh/src/tests/gltf.rs | 15 ++++++++++++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/mesh/README.md b/crates/mesh/README.md index 61074a2cb3..3b57208faa 100644 --- a/crates/mesh/README.md +++ b/crates/mesh/README.md @@ -110,9 +110,9 @@ FBX 6.x files (a `Model` holds its mesh, `Properties60`, objects connected by na geometry, transforms, the hierarchy and materials. Not read: FBX 5 and older, 6.x textures, animation, skin deformers, blend shapes, cameras, lights, NURBS. -Not read (glTF): required geometry extensions (Draco, meshopt) are -Not read (glTF): sparse accessors and required geometry extensions (Draco, meshopt) are -`Error::Unsupported`; points, lines, morph targets, tangents and other extensions are passed over. +Not read (glTF): required geometry extensions (Draco, meshopt) are `Error::Unsupported`. Points, +lines and morph targets are left out and counted in a warning; scenes other than the default are +named in one; other extensions are passed over. Not written: skins, animations, cameras, lights, and `.gltf` with separate files. ## Hostile input diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index 0e6733b657..09ae6eee38 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -853,9 +853,18 @@ fn morph_targets_and_other_scenes_are_named_in_warnings() { ); // The morphed primitives are still drawn, in their base shape. assert_eq!(s.meshes[0].parts.len(), 3); - // One scene, or an out-of-range choice, is not a warning about scenes. - let one = parse(&doc(json!(5), json!([{ "nodes": [0] }]))).unwrap(); - assert_eq!((one.roots.as_slice(), one.warnings.len()), ([0].as_slice(), 1)); + let morphs = "2 primitive(s) have morph targets, which were left out (drawn in the base shape)"; + // An out-of-range choice falls back to the first scene. + let s = parse(&doc(json!(5), json!([{ "nodes": [1] }, { "nodes": [0] }]))).unwrap(); + assert_eq!(s.roots, [1]); + assert_eq!(s.warnings, ["scene 0 of 2 was read; the others were left out", morphs]); + // One scene, or none, is not a warning about scenes. + let s = parse(&doc(json!(5), json!([{ "nodes": [0] }]))).unwrap(); + assert_eq!(s.roots, [0]); + assert_eq!(s.warnings, [morphs]); + let s = parse(&doc(json!(null), json!(null))).unwrap(); + assert_eq!(s.roots, [0, 1]); + assert_eq!(s.warnings, [morphs]); let s = parse(&one_mesh(&b, plain.clone())).unwrap(); assert!(s.warnings.is_empty(), "{:?}", s.warnings); } From a6b7bdce3ee3401a6148c6f3e8003b6dba109ae9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 14:01:25 -0800 Subject: [PATCH 063/144] ps: write numbers from their rounded integers instead of the float formatter push_num_places now writes the digits of round(v * 10^places) directly when that integer is below 2^52 in magnitude, placing the decimal point and trimming fractional zeros itself. Below 2^52 the integer is exact and dividing it by 10^places lands within half a decimal step of the exact quotient, so the text is the same as the formatter's. NaN, infinities, scaling overflow and larger rounded values take the existing formatter path unchanged. Requests for more than nine places are still clamped to nine first. Tests compare the output with the formatter path for places 0 to 12 over fixed boundary values (negative zero, ties, 1e15, 2^52, f64::MAX, non-finite values) and about 144,000 values in all (about 48,000 generated, plus the neighboring bit patterns of each). Widening the limit to 2^54 makes the comparison fail, for example -1709448349065955.5 at one place. On 1,200,000 path coordinates at four places (release build, wall clock on a Linux host running other builds at the same time, seven alternating runs), the formatter path took 362 to 373 ms and the integer path 38 to 44 ms. --- crates/ps/src/write.rs | 290 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 288 insertions(+), 2 deletions(-) diff --git a/crates/ps/src/write.rs b/crates/ps/src/write.rs index 97201771b6..89c2e39dfe 100644 --- a/crates/ps/src/write.rs +++ b/crates/ps/src/write.rs @@ -47,6 +47,9 @@ pub fn written(v: f64) -> f64 { /// finite). pub fn push_num_places(s: &mut String, v: f64, places: u32) { let places = places.min(9); + if push_num_scaled(s, v, places) { + return; + } let scale = 10f64.powi(places as i32); // Past where the scaling overflows, values have no fractional digits to round. let v = if !v.is_finite() { @@ -70,6 +73,75 @@ pub fn push_num_places(s: &mut String, v: f64, places: u32) { } } +/// `10^places` for `places` up to 9, each exact in an `f64`. +const POW10: [f64; 10] = [1.0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]; + +/// 2^52: below it every integer is an `f64`, and dividing one by `10^places` lands within half a +/// decimal step of the exact quotient, so the decimal digits are those of the integer. +const SCALED_LIMIT: f64 = 4_503_599_627_370_496.0; + +/// Append `v` with at most `places` decimals by writing the digits of the rounded integer +/// `v * 10^places`, the same text [`push_num_places`] writes. Returns false and appends nothing +/// when `places` is above 9, `v` is not finite, the scaling overflows or the rounded integer is +/// 2^52 or more in magnitude. +fn push_num_scaled(s: &mut String, v: f64, places: u32) -> bool { + let Some(&scale) = POW10.get(places as usize) else { + return false; + }; + let k = (v * scale).round(); + let magnitude = k.abs(); + if magnitude.is_nan() || magnitude >= SCALED_LIMIT { + return false; + } + // `magnitude` is a whole number below 2^52, so the cast is exact. + let mut m = magnitude as u64; + let mut decimals = places as usize; + while decimals > 0 && m.is_multiple_of(10) { + m /= 10; + decimals -= 1; + } + let unit = POW10_INT.get(decimals).copied().unwrap_or(1); + let (whole, fraction) = (m / unit, m % unit); + // A rounded negative zero has no sign: it is written `0`. + if k < 0.0 { + s.push('-'); + } + push_digits(s, whole, POW10_INT.iter().take_while(|&&p| p <= whole).count().max(1)); + if decimals > 0 { + s.push('.'); + push_digits(s, fraction, decimals); + } + true +} + +/// `10^n` for `n` up to 16, enough for every digit of an integer below 2^52. +const POW10_INT: [u64; 17] = [ + 1, + 10, + 100, + 1_000, + 10_000, + 100_000, + 1_000_000, + 10_000_000, + 100_000_000, + 1_000_000_000, + 10_000_000_000, + 100_000_000_000, + 1_000_000_000_000, + 10_000_000_000_000, + 100_000_000_000_000, + 1_000_000_000_000_000, + 10_000_000_000_000_000, +]; + +/// Append the last `width` decimal digits of `n`, leading zeros included. +fn push_digits(s: &mut String, n: u64, width: usize) { + for &p in POW10_INT.iter().take(width).rev() { + s.push(char::from(b'0' + ((n / p) % 10) as u8)); + } +} + /// `vs` as numbers separated by spaces, then a space. pub fn push_nums(s: &mut String, vs: &[f64]) { for v in vs { @@ -243,8 +315,8 @@ pub fn inflate(data: &[u8], max: u64) -> Option> { #[cfg(test)] mod tests { use super::{ - FillRule, PaintOps, PathOps, bytes, clip_op, deflate, fill_op, inflate, matrix, num, push_num, push_num_places, push_nums, push_path, string, - written, + FillRule, PaintOps, PathOps, bytes, clip_op, deflate, fill_op, inflate, matrix, num, push_num, push_num_places, push_num_scaled, push_nums, + push_path, string, written, }; use kurbo::{Affine, BezPath}; @@ -285,6 +357,220 @@ mod tests { assert_eq!(places(1e15 - 1.0, 0), "999999999999999"); } + /// `push_num_places` without the integer path: every value goes through the float formatter. + fn base_push_num_places(s: &mut String, v: f64, places: u32) { + use std::fmt::Write; + let places = places.min(9); + let scale = 10f64.powi(places as i32); + let v = if !v.is_finite() { + 0.0 + } else if (v * scale).is_finite() { + (v * scale).round() / scale + } else { + v + }; + if v == v.trunc() && v.abs() < 1e15 { + let _ = write!(s, "{}", v as i64); + return; + } + let start = s.len(); + let _ = write!(s, "{v:.*}", places as usize); + if s[start..].contains('.') { + let keep = s[start..].trim_end_matches('0').trim_end_matches('.').len(); + s.truncate(start + keep); + } + } + + /// A deterministic xorshift sequence. + fn next(state: &mut u64) -> u64 { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + *state + } + + /// Values that hit decimal ties, the 2^52 and 1e15 limits and their neighboring bit patterns, + /// coordinates of every magnitude, and arbitrary bit patterns. + fn number_samples() -> Vec { + let two52 = 4_503_599_627_370_496.0f64; + let mut values = vec![ + 0.0, + -0.0, + 1.0, + -1.0, + 0.5, + -0.5, + 1.5, + 2.5, + -2.5, + 0.1 + 0.2, + f64::from(0.4f32), + 0.123_456_78, + 123_456.789_012_345, + -0.000_04, + -0.000_05, + 0.000_05, + 1e-10, + -1e-10, + f64::MIN_POSITIVE, + -f64::MIN_POSITIVE, + 5e-324, + 1e15, + 1e15 - 1.0, + -1e15, + 1e15 + 0.5, + two52, + two52 - 1.0, + two52 - 0.5, + -two52, + 1e16, + 1e20, + 1.5e305, + f64::MAX, + f64::MIN, + f64::NAN, + f64::INFINITY, + f64::NEG_INFINITY, + ]; + let mut scale = 1.0; + for _ in 0..=9 { + for v in [two52 / scale, (two52 - 1.0) / scale, 1e15 / scale, 0.5 / scale, 1.5 / scale, 2.5 / scale] { + values.extend([v, -v]); + } + scale *= 10.0; + } + let mut state = 0x9e37_79b9_7f4a_7c15u64; + for _ in 0..12_000 { + let r = next(&mut state); + values.push(f64::from_bits(r)); + let exponent = (r % 24) as i32 - 8; + let mantissa = (next(&mut state) % 2_000_000_001) as f64 / 1e9 - 1.0; + values.push(mantissa * 10f64.powi(exponent)); + let places = (r % 10) as i32; + let tie = ((next(&mut state) % 20_000_000_001) as f64 - 1e10 + 0.5) / 10f64.powi(places); + values.push(tie); + values.push((next(&mut state) % 100_000_000) as f64 / 1e4 - 5_000.0); + } + let neighbors: Vec = values + .iter() + .filter(|v| v.is_finite() && **v != 0.0) + .flat_map(|v| [f64::from_bits(v.to_bits() - 1), f64::from_bits(v.to_bits() + 1)]) + .collect(); + values.extend(neighbors); + values + } + + #[test] + fn numbers_match_base_formatter() { + let mut integer_path = 0usize; + for places in 0..=12 { + for v in number_samples() { + let mut expected = String::from("x "); + base_push_num_places(&mut expected, v, places); + let mut got = String::from("x "); + push_num_places(&mut got, v, places); + assert_eq!(got, expected, "{v:e} ({:#x}) at {places} places", v.to_bits()); + if push_num_scaled(&mut String::new(), v, places.min(9)) { + integer_path += 1; + } + } + } + // The comparison covers the integer path, not only the fallback. + assert!(integer_path > 200_000, "{integer_path} values took the integer path"); + } + + #[test] + fn coordinates_are_written_through_integers() { + for (v, places) in [(0.0, 4), (-0.0, 4), (1.5, 4), (-2.25, 4), (4.3333, 4), (612.0, 0), (0.123_456_78, 7), (-0.000_05, 4), (1.23456789, 9)] { + let mut s = String::from("x "); + assert!(push_num_scaled(&mut s, v, places), "{v} at {places} places"); + let mut expected = String::from("x "); + base_push_num_places(&mut expected, v, places); + assert_eq!(s, expected); + } + let two52 = 4_503_599_627_370_496.0f64; + for (v, places) in [ + (f64::NAN, 4), + (f64::INFINITY, 4), + (f64::NEG_INFINITY, 0), + (f64::MAX, 4), + (f64::MIN, 0), + (1e305, 9), + (two52, 0), + (-two52, 0), + (two52 / 1e9, 9), + (1e20, 0), + (1.5, 10), + ] { + let mut s = String::from("x "); + assert!(!push_num_scaled(&mut s, v, places), "{v} at {places} places"); + assert_eq!(s, "x "); + } + } + + #[test] + fn number_boundaries_keep_base_text() { + let places = |v: f64, n: u32| { + let mut s = String::new(); + push_num_places(&mut s, v, n); + s + }; + let two52 = 4_503_599_627_370_496.0f64; + assert_eq!(places(1e15, 0), "1000000000000000"); + assert_eq!(places(-1e15, 0), "-1000000000000000"); + assert_eq!(places(two52 - 1.0, 0), "4503599627370495"); + assert_eq!(places(two52, 0), "4503599627370496"); + assert_eq!(places(1e20, 0), "100000000000000000000"); + assert_eq!(places(450_359_962_737_049.5, 1), "450359962737049.5"); + assert_eq!(places(-0.0, 4), "0"); + assert_eq!(places(-0.000_04, 4), "0"); + assert_eq!(places(-0.000_05, 4), "-0.0001"); + assert_eq!(places(0.5, 0), "1"); + assert_eq!(places(-1.5, 0), "-2"); + assert_eq!(places(0.000_000_001, 9), "0.000000001"); + assert_eq!(places(1.25, 20), "1.25"); + assert_eq!(places(10.5, 4), "10.5"); + assert_eq!(places(100.0, 4), "100"); + let mut s = String::from("x"); + push_nums(&mut s, &[]); + assert_eq!(s, "x"); + let mut scale = 1.0; + for (n, value) in super::POW10.iter().enumerate() { + assert_eq!(*value, scale, "10^{n}"); + assert_eq!(*value, 10f64.powi(n as i32), "10^{n}"); + scale *= 10.0; + } + } + + /// Times the base formatter against `push_num_places` on path coordinates. Run with + /// `cargo test --release -p craft-ps --features write number_writing_timing -- --ignored --nocapture`. + #[test] + #[ignore = "timing probe"] + fn number_writing_timing() { + use std::time::Instant; + let mut state = 0x2545_f491_4f6c_dd1du64; + let values: Vec = (0..1_200_000).map(|_| (next(&mut state) % 12_000_000_000) as f64 / 1e7 - 200.0).collect(); + let mut base_ms = vec![]; + let mut new_ms = vec![]; + for _ in 0..7 { + let start = Instant::now(); + let mut base = String::with_capacity(values.len() * 10); + for v in &values { + base_push_num_places(&mut base, *v, 4); + base.push(' '); + } + base_ms.push(start.elapsed().as_secs_f64() * 1e3); + let start = Instant::now(); + let mut new = String::with_capacity(values.len() * 10); + push_nums(&mut new, &values); + new_ms.push(start.elapsed().as_secs_f64() * 1e3); + assert_eq!(new, base); + } + println!("{} numbers at 4 places", values.len()); + println!("base formatter ms: {base_ms:.2?}"); + println!("integer path ms: {new_ms:.2?}"); + } + #[test] fn strings_and_bytes_are_escaped() { assert_eq!(string("ok"), "(ok)"); From 5541e248e86c923168866de7e183dee4ef4eeeda Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Mon, 16 Nov 2026 17:12:46 -0500 Subject: [PATCH 064/144] wordmodel: append to a paragraph in O(1) with push_text and push_object Building a paragraph through insert_text/insert_object at its end walked every run (and insert_object counted every object before the offset) on each call, so n appends cost O(n^2): one paragraph of 64k runs took 8.5 minutes. push_text and push_object extend the last run or start a new one, giving the same paragraph as inserting at len(). --- crates/wordmodel/src/para.rs | 31 +++++++++++++++++++++ crates/wordmodel/src/tests.rs | 51 +++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/crates/wordmodel/src/para.rs b/crates/wordmodel/src/para.rs index bbfeb9cbcf..901e300b6d 100644 --- a/crates/wordmodel/src/para.rs +++ b/crates/wordmodel/src/para.rs @@ -296,6 +296,37 @@ impl Paragraph { Ok(()) } + /// Append plain text (U+FFFC is dropped) with `props`. Returns the appended length. The same as + /// [`Self::insert_text`] at [`Self::len`], but it doesn't walk the runs or the text, so building + /// a paragraph of `n` pieces this way is linear rather than quadratic in `n`. + pub fn push_text(&mut self, s: &str, props: &CharProps) -> usize { + let clean: std::borrow::Cow = if s.contains(OBJ) { s.chars().filter(|c| *c != OBJ).collect::().into() } else { s.into() }; + if clean.is_empty() { + return 0; + } + self.text.push_str(&clean); + self.push_run(clean.len(), props); + self.touch(); + clean.len() + } + + /// Append an object with `props`: [`Self::insert_object`] at [`Self::len`], without counting + /// the objects already there. + pub fn push_object(&mut self, obj: InlineObject, props: &CharProps) { + self.text.push(OBJ); + self.objects.push(obj); + self.push_run(OBJ.len_utf8(), props); + self.touch(); + } + + /// Extend the last run by `len` when it has `props`, or start a new one. + fn push_run(&mut self, len: usize, props: &CharProps) { + match self.runs.last_mut() { + Some(last) if last.props == *props => last.len += len, + _ => self.runs.push(Run { len, props: props.clone() }), + } + } + fn insert_run(&mut self, off: usize, len: usize, props: CharProps) { // Split the run at `off`, insert, merge neighbours. let mut start = 0; diff --git a/crates/wordmodel/src/tests.rs b/crates/wordmodel/src/tests.rs index 088bd3bd2c..b4d1b17dd4 100644 --- a/crates/wordmodel/src/tests.rs +++ b/crates/wordmodel/src/tests.rs @@ -644,6 +644,57 @@ fn para_of_objects(objs: Vec) -> Paragraph { p } +/// push_text and push_object build the same paragraph as inserting at the end. +#[test] +fn pushing_matches_inserting_at_the_end() { + let bold = CharProps { bold: Some(true), ..Default::default() }; + let plain = CharProps::default(); + let (mut pushed, mut inserted) = (Paragraph::new(), Paragraph::new()); + let steps: [(&str, &CharProps, bool); 7] = [ + ("Hello ", &plain, false), + ("world", &bold, false), + ("", &bold, true), + (", again", &bold, false), + ("", &bold, false), + ("x\u{FFFC}y", &plain, false), + ("", &plain, true), + ]; + for (i, (text, props, object)) in steps.into_iter().enumerate() { + if object { + let obj = InlineObject::BookmarkStart { name: format!("b{i}") }; + pushed.push_object(obj.clone(), props); + inserted.insert_object(inserted.len(), obj, props).unwrap(); + } else { + let n = pushed.push_text(text, props); + assert_eq!(n, inserted.insert_text(inserted.len(), text, props).unwrap()); + } + assert_eq!(pushed, inserted, "after step {i}"); + } + assert_eq!(pushed.text, "Hello world\u{FFFC}, againxy\u{FFFC}"); + assert_eq!(pushed.runs.len(), 3, "equal neighbours merge: {:?}", pushed.runs); + assert_eq!(pushed.objects.len(), 2); +} + +#[test] +fn pushing_a_long_paragraph_is_linear() { + // Appending through insert_text/insert_object walked every run (and counted every object) on + // each call: 64k alternating runs took minutes. Pushing takes milliseconds. + let n = 64_000; + let bold = CharProps { bold: Some(true), ..Default::default() }; + let plain = CharProps::default(); + let t = std::time::Instant::now(); + let mut p = Paragraph::new(); + for i in 0..n { + p.push_text("word ", if i % 2 == 0 { &bold } else { &plain }); + if i % 8 == 0 { + p.push_object(InlineObject::BookmarkStart { name: format!("b{i}") }, &plain); + } + } + assert_eq!(p.runs.iter().map(|r| r.len).sum::(), p.text.len()); + assert_eq!(p.objects.len(), n / 8); + assert!(t.elapsed().as_secs_f32() < 10.0, "{:?}", t.elapsed()); +} + #[test] fn object_walks_are_linear_in_the_paragraph() { // #3614: loops of object_offsets + object_at recounted the objects before each one, so a From d5eddf0cc2dd43e4edc47669de9f90491448f579 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Mon, 16 Nov 2026 17:16:24 -0500 Subject: [PATCH 065/144] flow: a table with no style has no header row from the default look flow_table made a table's first row a header row whenever its look had header_row set, and the look defaults to Word's (header row on). The look is an option of the table's style (w:tblLook/@w:firstRow), so a table with no style, or a style the document doesn't have, got a header row Word never shows: RTF bolded it and marked it \trhdr (repeat on each page), HTML made it th, and ODT repeated it. Only Repeat as header row (RowProps::header) makes such a row a header now; styled tables are unchanged. --- crates/flow/src/from_doc.rs | 5 ++++- crates/flow/src/lib.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index b7204f1bf8..d85953a0a2 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -1101,7 +1101,10 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa let ncols = t.rows.iter().map(|r| r.first_grid() + r.cells.iter().map(|c| c.span()).sum::() + r.grid_after()).max().unwrap_or(0).max(t.grid.len()); for (ri, r) in t.rows.iter().enumerate() { - let header = r.props.header || (ri == 0 && t.props.look.header_row && t.rows.len() > 1); + // The look's header row is an option of the table's style (`w:tblLook/@w:firstRow`): with + // no table style there is nothing to apply, so the first row stays an ordinary row, as in + // Word. Only Repeat as header row makes it one then. + let header = r.props.header || (ri == 0 && style.is_some() && t.props.look.header_row && t.rows.len() > 1); let mut cells = Vec::new(); for (ci, c) in r.cells.iter().enumerate() { let styled = if bake { styled_cell(t, style.as_ref(), (ri, ci), ncols) } else { None }; diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index 774b5ffd17..7dc83c99d8 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -80,6 +80,32 @@ mod tests { assert!(kept); } + /// The default look's header row is an option of the table style: a table with no style (or a + /// style the document doesn't have) has an ordinary first row, so RTF doesn't bold it or + /// repeat it on each page, and HTML doesn't make it `th`. Repeat as header row still does. + #[test] + fn look_header_row_needs_a_table_style() { + use craft_wordmodel::{Block, Document, table::Table}; + let first_row_header = |style: Option<&str>, repeat: bool| { + let mut t = Table::new(2, 2, 200.0); + t.props.style = style.map(str::to_string); + assert!(t.props.look.header_row, "the default look has a header row"); + if let Some(r) = t.rows.first_mut() { + r.props.header = repeat; + } + let mut doc = Document::new(); + doc.body = vec![std::sync::Arc::new(Block::Table(t))]; + let flow = from_doc(&doc); + let Some(FBlock::Table(ft)) = flow.blocks.iter().find(|b| matches!(b, FBlock::Table(_))) else { panic!("no table in {:?}", flow.blocks) }; + assert!(ft.rows.get(1).is_some_and(|r| r.iter().all(|c| !c.header)), "the second row is never a header"); + ft.rows.first().is_some_and(|r| r.iter().all(|c| c.header)) + }; + assert!(first_row_header(Some("TableGrid"), false), "a table style applies the look's header row"); + assert!(!first_row_header(None, false), "no style, no header row"); + assert!(!first_row_header(Some("NoSuchStyle"), false), "a missing style applies nothing"); + assert!(first_row_header(None, true), "Repeat as header row"); + } + #[test] fn percent_decode_requires_hex_digits() { assert_eq!(percent_decode("%+A"), b"%+A".to_vec()); From 778493598fcca586745a502133fca1368b911a7c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 17:53:46 -0500 Subject: [PATCH 066/144] Migrate Flatpak updates to the OCI image and appimage pipeline (#1318) --- Cargo.lock | 8 +- crates/update/Cargo.toml | 2 + crates/update/src/detect.rs | 210 ++++++++++++++++- crates/update/src/install.rs | 381 +++++++++++++++++++++++++++++-- crates/update/src/packages.rs | 181 ++++++++++++++- crates/update/src/process.rs | 78 +++++++ crates/update/src/self_update.rs | 20 +- crates/update/src/status.rs | 17 ++ 8 files changed, 857 insertions(+), 40 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8679e4eac8..ef82f1afaf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2887,6 +2887,10 @@ dependencies = [ name = "craft-sniff" version = "0.1.0" +[[package]] +name = "craft-ssip" +version = "0.1.0" + [[package]] name = "craft-stencilcraft-document" version = "0.1.0" @@ -2900,10 +2904,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "craft-ssip" -version = "0.1.0" - [[package]] name = "craft-stencilcraft-format" version = "0.1.0" diff --git a/crates/update/Cargo.toml b/crates/update/Cargo.toml index 93a0719a5b..e130656e32 100644 --- a/crates/update/Cargo.toml +++ b/crates/update/Cargo.toml @@ -11,6 +11,8 @@ repository.workspace = true workspace = true [features] +# Opt-in migration of first party Flatpak bundles to the ArtCraft OCI remote. +oci_migration = [] default = [] egui = ["dep:egui", "dep:image"] local-mirror = [] diff --git a/crates/update/src/detect.rs b/crates/update/src/detect.rs index 437e315d72..53c000ebc9 100644 --- a/crates/update/src/detect.rs +++ b/crates/update/src/detect.rs @@ -67,6 +67,9 @@ fn from_manifest(app: &App, manifest: &Manifest) -> Option { source: InstallSource::Launcher, location: rec.path.display().to_string(), package: None, + externally_managed: false, + origin: None, + installation: None, }) } @@ -169,7 +172,15 @@ pub mod macos { let full_key = format!("{}Version", app.name); let text = [full_key.as_str(), "CFBundleShortVersionString", "CFBundleVersion"].iter().find_map(|k| dict.get(k).and_then(plist::Value::as_string)); - Some(Installed { version: text.and_then(version::parse), source: InstallSource::MacApp, location: path.display().to_string(), package: None }) + Some(Installed { + version: text.and_then(version::parse), + source: InstallSource::MacApp, + location: path.display().to_string(), + package: None, + externally_managed: false, + origin: None, + installation: None, + }) } } @@ -277,6 +288,9 @@ pub mod windows { source: InstallSource::Msi, location: m.exe.map_or_else(|| app.name.to_string(), |p| p.display().to_string()), package: Some(m.product_code), + externally_managed: false, + origin: None, + installation: None, }) } } @@ -303,7 +317,14 @@ pub mod linux { let t = Duration::from_secs(10); let mut out = Vec::new(); let mut add = |manager, list: Vec<(String, String)>| { - out.extend(list.into_iter().filter(|(n, _)| ours(n)).map(|(name, version)| Package { manager, name, version })); + out.extend(list.into_iter().filter(|(n, _)| ours(n)).map(|(name, version)| Package { + manager, + name, + version, + user: false, + origin: None, + installation: None, + })); }; if let Some(list) = capture("dpkg-query", &["-W", "-f", "${Package}|${db:Status-Status}|${Version}\n"], t) { add(InstallSource::Deb, packages::parse_dpkg(&list)); @@ -319,15 +340,28 @@ pub mod linux { add(InstallSource::Pacman, packages::parse_pacman(&list)); } let arch = format!("--arch={}", std::env::consts::ARCH); - if let Some(list) = crate::process::capture_flatpak(&["list", "--app", &arch, "--columns=application,version"], t) { - let mut flatpaks = packages::parse_flatpak_list(&list); + if let Some(list) = crate::process::capture_flatpak(&["list", "--app", &arch, "--columns=application,version,origin,installation"], t) { + let mut flatpaks = packages::parse_flatpak_list_with_origin(&list); // Bundles built from a release tarball often list no version: ask Flatpak directly. - for (id, version) in flatpaks.iter_mut().filter(|(id, v)| v.is_empty() && id.starts_with("ai.storyteller.")) { - if let Some(v) = crate::process::capture_flatpak(&["info", &arch, id], t).as_deref().and_then(packages::parse_flatpak_info) { + for (id, version, _, installation) in flatpaks.iter_mut().filter(|(id, v, _, _)| v.is_empty() && id.starts_with("ai.storyteller.")) { + let custom_scope; + let scope_arg = match installation.as_deref() { + Some("user") => vec!["--user"], + Some("system") | None => vec!["--system"], + Some(named) => { + custom_scope = format!("--installation={named}"); + vec![custom_scope.as_str()] + } + }; + let info_args = [&["info"][..], &scope_arg, &[&arch, id]].concat(); + if let Some(v) = crate::process::capture_flatpak(&info_args, t).as_deref().and_then(packages::parse_flatpak_info) { *version = v; } } - add(InstallSource::Flatpak, flatpaks); + out.extend(flatpaks.into_iter().filter(|(n, _, _, _)| ours(n)).map(|(name, version, origin, installation)| { + let is_user = installation.as_deref() == Some("user"); + Package { manager: InstallSource::Flatpak, name, version, user: is_user, origin, installation } + })); } out } @@ -402,12 +436,41 @@ pub mod linux { pub fn detect(app: &App, snapshot: &Snapshot) -> Option { if let Some((path, version)) = appimages(app).into_iter().next() { - return Some(Installed { version, source: InstallSource::AppImage, location: path.display().to_string(), package: None }); + return Some(Installed { + version, + source: InstallSource::AppImage, + location: path.display().to_string(), + package: None, + externally_managed: false, + origin: None, + installation: None, + }); } let order = [InstallSource::Deb, InstallSource::Rpm, InstallSource::Pacman, InstallSource::Flatpak]; if let Some(p) = packages::find(app, &snapshot.packages, &order) { - let location = if p.manager == InstallSource::Flatpak { app.bundle_id() } else { binary_on_path(app.id) }; - return Some(Installed { version: packages::version_of(p), source: p.manager, location, package: Some(p.name.clone()) }); + let location = if p.manager == InstallSource::Flatpak { p.name.clone() } else { binary_on_path(app.id) }; + let externally_managed = p.manager == InstallSource::Flatpak + && p.origin.as_deref().is_none_or(|origin| { + if packages::is_flatpark_origin(origin) { + return true; + } + let scope = match p.installation.as_deref() { + Some("user") => "--user".to_string(), + Some("system") | None => "--system".to_string(), + Some(name) => format!("--installation={name}"), + }; + crate::process::capture_flatpak(&["remotes", &scope, "--show-disabled", "--columns=name,url"], Duration::from_secs(10)) + .is_none_or(|remotes| packages::remote_manages_flatpak(origin, &remotes)) + }); + return Some(Installed { + version: packages::version_of(p), + source: p.manager, + location, + package: Some(p.name.clone()), + externally_managed, + origin: p.origin.clone(), + installation: p.installation.clone(), + }); } detect_system_install(app) } @@ -418,7 +481,15 @@ pub mod linux { /// to whatever installed it, since it can't tell which package manager that was. fn detect_system_install(app: &App) -> Option { let bin = find_binary(app.id)?; - Some(Installed { version: binary_version(&bin, app), source: InstallSource::Binary, location: bin.display().to_string(), package: None }) + Some(Installed { + version: binary_version(&bin, app), + source: InstallSource::Binary, + location: bin.display().to_string(), + package: None, + externally_managed: true, + origin: None, + installation: None, + }) } fn find_binary(id: &str) -> Option { @@ -445,7 +516,15 @@ pub mod freebsd { if !bin.exists() { return None; } - Some(Installed { version: binary_version(&bin, app), source: InstallSource::Binary, location: bin.display().to_string(), package: None }) + Some(Installed { + version: binary_version(&bin, app), + source: InstallSource::Binary, + location: bin.display().to_string(), + package: None, + externally_managed: true, + origin: None, + installation: None, + }) } /// ` --version` prints ` 0.5.0 (sha, date)`. @@ -690,6 +769,113 @@ mod tests { assert!(strip_cli_prefix("photocraft-cli 1.0.0", "photocraft").is_none()); } + /// The launcher's own record is the first thing detection trusts, and its source is the + /// launcher rather than whatever installed the file underneath. + #[test] + fn a_manifest_record_for_a_file_that_is_there_is_a_launcher_install() { + let app = App::by_id("photocraft").unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("photocraft.AppImage"); + std::fs::write(&path, b"").unwrap(); + let mut manifest = crate::manifest::Manifest::default(); + manifest.apps.insert( + app.id.to_string(), + crate::manifest::Record { + version: "0.6.1".into(), + kind: crate::PackageKind::AppImage, + path: path.clone(), + installed_at: 0, + files: Vec::new(), + needs_root: false, + }, + ); + let found = from_manifest(app, &manifest).expect("the record names a file that is there"); + assert_eq!(found.source, InstallSource::Launcher); + assert_eq!(found.version.map(|v| v.to_string()).as_deref(), Some("0.6.1")); + assert_eq!(found.location, path.display().to_string()); + assert!(!found.externally_managed); + assert_eq!(found.origin, None); + assert_eq!(found.installation, None); + } + + /// A record whose file the user removed is not an install, so detection keeps looking. + #[test] + fn a_manifest_record_for_a_file_that_is_gone_is_not_an_install() { + let app = App::by_id("photocraft").unwrap(); + let dir = tempfile::tempdir().unwrap(); + let mut manifest = crate::manifest::Manifest::default(); + manifest.apps.insert( + app.id.to_string(), + crate::manifest::Record { + version: "0.6.0".into(), + kind: crate::PackageKind::AppImage, + path: dir.path().join("gone.AppImage"), + installed_at: 0, + files: Vec::new(), + needs_root: false, + }, + ); + assert!(from_manifest(app, &manifest).is_none()); + } + + /// A package the snapshot already found, as the launcher sees it after a package-manager + /// query: only the fields detection reads are varied. + #[cfg(target_os = "linux")] + fn injected(manager: InstallSource, installation: Option<&str>, origin: Option<&str>) -> crate::packages::Package { + crate::packages::Package { + manager, + name: match manager { + InstallSource::Flatpak => "ai.storyteller.photocraft".to_string(), + _ => "photocraft".to_string(), + }, + version: "0.6.2".into(), + user: installation == Some("user"), + origin: origin.map(str::to_string), + installation: installation.map(str::to_string), + } + } + + #[cfg(target_os = "linux")] + #[test] + fn a_deb_package_is_reported_with_its_manager_and_version() { + let app = App::by_id("photocraft").unwrap(); + let snapshot = Snapshot { packages: vec![injected(InstallSource::Deb, None, None)] }; + let found = linux::detect(app, &snapshot).expect("the injected package is installed"); + assert_eq!(found.source, InstallSource::Deb); + assert_eq!(found.version.map(|v| v.to_string()).as_deref(), Some("0.6.2")); + assert_eq!(found.package.as_deref(), Some("photocraft")); + assert!(!found.externally_managed); + assert_eq!(found.installation, None); + } + + /// A Flatpak from a remote the launcher doesn't drive stays externally managed, in every + /// scope the `flatpak remotes` query can need. + #[cfg(target_os = "linux")] + #[test] + fn a_flatpak_from_a_repository_remote_is_externally_managed() { + let app = App::by_id("photocraft").unwrap(); + for installation in [Some("user"), Some("system"), Some("custom"), None] { + let snapshot = Snapshot { packages: vec![injected(InstallSource::Flatpak, installation, Some("flathub"))] }; + let found = linux::detect(app, &snapshot).expect("the injected Flatpak is installed"); + assert_eq!(found.source, InstallSource::Flatpak); + assert!(found.externally_managed, "{installation:?}"); + assert_eq!(found.location, "ai.storyteller.photocraft"); + assert_eq!(found.origin.as_deref(), Some("flathub")); + assert_eq!(found.installation.as_deref(), installation); + } + } + + /// FlatPark's own remote is known to manage the copy without asking flatpak again. + #[cfg(target_os = "linux")] + #[test] + fn a_flatpark_flatpak_is_externally_managed_without_asking_its_remotes() { + let app = App::by_id("photocraft").unwrap(); + let snapshot = Snapshot { packages: vec![injected(InstallSource::Flatpak, Some("user"), Some("flatpark"))] }; + let found = linux::detect(app, &snapshot).expect("the injected Flatpak is installed"); + assert!(found.externally_managed); + assert_eq!(found.origin.as_deref(), Some("flatpark")); + } + #[cfg(target_os = "linux")] #[test] fn finds_appimages_in_every_folder_newest_first() { diff --git a/crates/update/src/install.rs b/crates/update/src/install.rs index 4b65e3af0e..0714345958 100644 --- a/crates/update/src/install.rs +++ b/crates/update/src/install.rs @@ -94,6 +94,11 @@ pub fn install_at( { not_running(app, process::running(Path::new(&inst.location)))?; } + if kind == PackageKind::Flatpak + && let Some(installed) = existing.filter(|installed| installed.source == InstallSource::Flatpak && installed.externally_managed) + { + return Err(managed_elsewhere(app, installed, false).unwrap_or_else(|| "Update this app through its Flatpak repository".into())); + } bind_artifact_version(app, release, asset)?; if !job.replace && let Some(inst) = existing @@ -104,6 +109,16 @@ pub fn install_at( } check_download_link(app, release, asset)?; log::info!("{}: starting {} to {} ({})", app.name, if existing.is_some() { "update" } else { "install" }, release.version_label(), kind.label()); + #[cfg(all(target_os = "linux", feature = "oci_migration"))] + if kind == PackageKind::Flatpak + && !job.replace + && !release.prerelease + && let Some(installed) = existing + && let Some(expected) = release.version.as_ref() + && linux::migrate_bundle_to_oci(app, installed, expected, job.stop)? + { + return Ok(None); + } let file = download(release, asset, job)?; log::info!("{}: download ready ({}), running installer...", app.name, file.display()); // Past this point the install can't be interrupted halfway. @@ -363,6 +378,9 @@ pub(crate) fn choose_kinds_with( // opens and removes them but never replaces them. InstallSource::Pacman if is_release_arch_package(app, inst) => Some(PackageKind::ArchPkg), InstallSource::Pacman => return Vec::new(), + // Repository-managed Flatpaks are externally managed: the launcher will not + // replace them with a downloaded local .flatpak bundle. + InstallSource::Flatpak if inst.externally_managed => return Vec::new(), InstallSource::Flatpak => Some(PackageKind::Flatpak), InstallSource::AppImage => Some(PackageKind::AppImage), InstallSource::Binary => Some(PackageKind::TarGz), @@ -463,6 +481,16 @@ fn managed_elsewhere_with(app: &App, installed: &Installed, uninstall: bool, rep let pkg = installed.package.clone().unwrap_or_else(|| app.id.to_string()); Some(pacman_update_hint(app, &pkg, repo_fn(&pkg).as_deref())) } + InstallSource::Flatpak if !uninstall && installed.externally_managed => { + let default_pkg = app.bundle_id(); + let pkg = installed.package.as_deref().unwrap_or(&default_pkg); + let scope = match installed.installation.as_deref() { + Some("user") => "--user".to_string(), + Some("system") | None => "--system".to_string(), + Some(name) => format!("--installation={name}"), + }; + Some(format!("{} was installed from a Flatpak repository. Update it with flatpak update {scope} {pkg}", app.name)) + } InstallSource::Binary => Some(format!("{} was installed outside the launcher. Update or remove it the way it was installed.", app.name)), _ => None, } @@ -805,8 +833,15 @@ fn cancelled(stop: &Stop) -> impl Fn() -> bool + '_ { || stop.check().is_err_and(|e| e == crate::protocol::CANCELLED) } +/// For a running helper command: only CANCELLED ends it. PAUSED lets the current command finish +/// (callers check `stop` before starting the next one). #[cfg(target_os = "linux")] -pub(crate) mod linux { +fn kill_on_cancel(stop: &Stop) -> impl Fn() -> Result<(), String> + '_ { + || if cancelled(stop)() { Err(crate::protocol::CANCELLED.into()) } else { Ok(()) } +} + +#[cfg(target_os = "linux")] +pub mod linux { use std::ffi::{OsStr, OsString}; use std::os::unix::fs::PermissionsExt; use std::time::Duration; @@ -817,7 +852,7 @@ pub(crate) mod linux { use super::{ App, INSTALLER, InstallSource, Installed, JobPhase, PackageKind, Path, PathBuf, Paths, Record, SHARED_CALL, SYSTEM_BIN_DIRS, Stop, cancelled, - find_in, pkexec, process, run_as_root, swap_into_place, tree, turn, + find_in, kill_on_cancel, pkexec, process, run_as_root, swap_into_place, tree, turn, }; /// apt waits this long for another package tool (a software centre, automatic updates) to @@ -1076,6 +1111,125 @@ pub(crate) mod linux { root.queue.alone(&cancelled(stop), &mut turn(phase, JobPhase::Installing), install).unwrap_or(Err(CANCELLED.into())) } + /// Opt-in OCI migration; only an absent ref permits bundle fallback. + #[cfg(feature = "oci_migration")] + pub fn migrate_bundle_to_oci(app: &App, installed: &Installed, expected: &super::version::Version, stop: &Stop) -> Result { + if installed.source != InstallSource::Flatpak || installed.externally_managed || !app.repo.starts_with("storytold/") { + return Ok(false); + } + // Only bundle-created origins qualify; never redirect another repository's install. + if !installed.origin.as_deref().is_some_and(|origin| origin.ends_with("-origin")) { + return Ok(false); + } + let id = installed.package.as_deref().ok_or("Flatpak installation has no package ID")?; + let scope = match installed.installation.as_deref() { + Some("user") => "--user".to_string(), + Some("system") => "--system".to_string(), + Some(name) => format!("--installation={name}"), + None => return Err("Flatpak installation scope is unknown".into()), + }; + // `cancellable` is false for steps that must not stop part-way: killing flatpak-spawn + // doesn't wait for the host transaction, and `--reinstall` removes the old ref first. + let flatpak = |args: &[&str], cancellable: bool| -> Result { + let mut cmd = if process::in_sandbox() { + let mut cmd = process::command("flatpak-spawn"); + cmd.args(["--host", "--watch-bus", "flatpak"]); + cmd + } else { + process::command("flatpak") + }; + cmd.arg(&scope).args(args); + if cancellable { + stop.check()?; // paused or cancelled: start no further command + } + let end = kill_on_cancel(stop); + let output = process::cancellable_output(cmd, || if cancellable { end() } else { Ok(()) })?; + if !output.status.success() { + return Err(format!("Flatpak OCI migration failed: {}", String::from_utf8_lossy(&output.stderr).trim())); + } + Ok(String::from_utf8_lossy(&output.stdout).into_owned()) + }; + let run = |args: &[&str]| flatpak(args, true); + let reference = run(&["info", "--show-ref", id])?; + let reference = reference.trim(); + if !reference.starts_with(&format!("app/{id}/")) || !reference.ends_with("/stable") { + return Ok(false); + } + let remotes = run(&["remotes", "--show-disabled", "--columns=name,url"])?; + let remote = remotes.lines().find_map(|line| { + let (name, _) = line.split_once('\t')?; + crate::packages::is_artcraft_remote(name, line).then(|| name.to_string()) + }); + let remote = match remote { + Some(remote) => remote, + None => { + if remotes.lines().any(|line| line.split('\t').next() == Some("artcraft-oci")) { + return Err("The artcraft-oci remote points to a different repository".into()); + } + // Another app's migration may add the remote first; the URL is checked below. + run(&["remote-add", "--if-not-exists", "artcraft-oci", "https://getartcraft.com/artcraft-oci.flatpakrepo"])?; + let remotes = run(&["remotes", "--show-disabled", "--columns=name,url"])?; + if !crate::packages::is_artcraft_remote("artcraft-oci", &remotes) { + return Err("The ArtCraft OCI descriptor configured an unexpected repository".into()); + } + "artcraft-oci".to_string() + } + }; + // The Version column comes from the remote's AppStream catalog, which Flatpak only fetches + // on demand; without a refresh a new remote lists refs with empty versions. + run(&["update", "--appstream", &remote])?; + let refs = run(&["remote-ls", "--app", "--columns=ref,version", &remote])?; + if !crate::packages::oci_ref_available(reference, expected, &refs)? { + return Ok(false); + } + stop.check()?; + if let Err(e) = flatpak(&["install", "--reinstall", "-y", "--noninteractive", &remote, reference], false) { + // The bundle origin has no repository to restore from, so point at the bundle itself. + if flatpak(&["info", id], false).is_err() { + return Err(format!("{e}. {} is no longer installed; reinstall it from the .flatpak bundle at {}", app.name, app.releases_url())); + } + return Err(e); + } + let origin = run(&["info", "--show-origin", id])?; + if origin.trim() != remote { + return Err("Flatpak did not switch the installed app to the ArtCraft OCI remote".into()); + } + Ok(true) + } + + /// Updates an installed Flatpak from its remote repository (such as FlatPark). + pub fn update_flatpak_app(app: &App, id: &str, installation: Option<&str>, stop: &Stop, phase: &mut dyn FnMut(JobPhase)) -> Result<(), String> { + phase(JobPhase::Installing); + stop.check()?; + let scope_arg = match installation { + Some("user") => "--user".to_string(), + Some("system") | None => "--system".to_string(), + Some(named) => format!("--installation={named}"), + }; + // Let Flatpak's system helper authorize system updates through polkit. + // watch-bus also terminates the host command if the sandbox proxy exits. + let mut cmd = if process::in_sandbox() { + let mut command = process::command("flatpak-spawn"); + command.args(["--host", "--watch-bus", "flatpak"]); + command + } else { + process::command("flatpak") + }; + cmd.args(["update", &scope_arg, "-y", "--noninteractive", id]); + let output = process::cancellable_output(cmd, kill_on_cancel(stop))?; + if output.status.success() { + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr); + let err = stderr.trim(); + if err.is_empty() { + Err(format!("Flatpak couldn't update {}", app.name)) + } else { + let clean = err.strip_prefix("error: ").or_else(|| err.strip_prefix("Error: ")).unwrap_or(err); + Err(format!("Flatpak couldn't update {}: {clean}", app.name)) + } + } + /// Whether a bundle install of `id` failed because the installation already has the bundle's /// commit: Flatpak's "already installed", in the C locale. Any other failure leaves the app alone. pub(crate) fn already_installed(err: &str, id: &str) -> bool { @@ -2481,6 +2635,9 @@ mod tests { source: InstallSource::Msi, location: dir.path().join("MSI/PhotoCraft/photocraft.exe").display().to_string(), package: None, + externally_managed: false, + origin: None, + installation: None, }; assert_eq!(destination(app, PackageKind::Msi, Some(&msi), Some(&old), &unavailable).unwrap(), Some(dir.path().join("MSI/PhotoCraft"))); assert!(destination(app, PackageKind::TarGz, None, None, &locations).unwrap_err().contains("aren't supported")); @@ -2492,8 +2649,24 @@ mod tests { let app = App::by_id("photocraft").unwrap(); let path = dir.path().join("old.AppImage"); let rec = record("0.5.0", PackageKind::AppImage, path.clone(), vec![], false); - let launcher = Installed { version: None, source: InstallSource::Launcher, location: path.display().to_string(), package: None }; - let users = Installed { version: None, source: InstallSource::AppImage, location: "/home/me/AppImages/p.AppImage".into(), package: None }; + let launcher = Installed { + version: None, + source: InstallSource::Launcher, + location: path.display().to_string(), + package: None, + externally_managed: false, + origin: None, + installation: None, + }; + let users = Installed { + version: None, + source: InstallSource::AppImage, + location: "/home/me/AppImages/p.AppImage".into(), + package: None, + externally_managed: false, + origin: None, + installation: None, + }; let chosen = dir.path().join("New apps"); std::fs::create_dir(&chosen).unwrap(); let mut locations = InstallLocations { root: Some(chosen.display().to_string()), ..Default::default() }; @@ -3333,7 +3506,15 @@ esac #[test] fn updates_keep_the_installed_format() { - let inst = |source| Installed { version: None, source, location: String::new(), package: None }; + let inst = |source| Installed { + version: None, + source, + location: String::new(), + package: None, + externally_managed: false, + origin: None, + installation: None, + }; let app = crate::App::by_id("photocraft").unwrap(); let available = available_kinds(); if let Some(first) = available.first() { @@ -3350,7 +3531,15 @@ esac #[test] fn only_the_release_arch_package_is_updated_by_the_launcher() { - let pacman = |name: &str| Installed { version: None, source: InstallSource::Pacman, location: String::new(), package: Some(name.into()) }; + let pacman = |name: &str| Installed { + version: None, + source: InstallSource::Pacman, + location: String::new(), + package: Some(name.into()), + externally_managed: false, + origin: None, + installation: None, + }; let app = crate::App::by_id("wordcraft").unwrap(); assert!(is_release_arch_package(app, &pacman("ai.storyteller.wordcraft"))); for aur in ["wordcraft", "wordcraft-bin", "wordcraft-git"] { @@ -3378,7 +3567,15 @@ esac #[test] fn aur_packages_are_not_updated_as_arch_pkg() { - let pacman = |name: &str| Installed { version: None, source: InstallSource::Pacman, location: String::new(), package: Some(name.into()) }; + let pacman = |name: &str| Installed { + version: None, + source: InstallSource::Pacman, + location: String::new(), + package: Some(name.into()), + externally_managed: false, + origin: None, + installation: None, + }; let app = crate::App::by_id("filmcraft").unwrap(); let installed = pacman("filmcraft-bin"); assert!(managed_elsewhere_with(app, &installed, false, |_| None).is_some()); @@ -3388,7 +3585,15 @@ esac #[test] fn release_arch_packages_are_updated_as_arch_pkg() { - let pacman = |name: &str| Installed { version: None, source: InstallSource::Pacman, location: String::new(), package: Some(name.into()) }; + let pacman = |name: &str| Installed { + version: None, + source: InstallSource::Pacman, + location: String::new(), + package: Some(name.into()), + externally_managed: false, + origin: None, + installation: None, + }; let app = crate::App::by_id("filmcraft").unwrap(); let installed = pacman("ai.storyteller.filmcraft"); assert_eq!(managed_elsewhere_with(app, &installed, false, |_| None), None); @@ -3396,6 +3601,102 @@ esac assert_eq!(choose_kinds_with(app, Some(&installed), None, &[], &[PackageKind::ArchPkg], false), vec![PackageKind::ArchPkg]); } + #[test] + fn flatpark_flatpaks_are_externally_managed_and_not_updated_via_bundle() { + let app = crate::App::by_id("photocraft").unwrap(); + let flatpark_installed = Installed { + version: version::parse("0.19.0"), + source: InstallSource::Flatpak, + location: "ai.storyteller.photocraft".into(), + package: Some("ai.storyteller.photocraft".into()), + externally_managed: true, + origin: Some("flatpark".into()), + installation: Some("user".into()), + }; + assert!(flatpark_installed.is_externally_managed()); + assert_eq!(choose_kinds_with(app, Some(&flatpark_installed), None, &[], &[PackageKind::Flatpak], false), Vec::::new()); + let hint = managed_elsewhere_with(app, &flatpark_installed, false, |_| None); + assert_eq!( + hint.as_deref(), + Some("PhotoCraft was installed from a Flatpak repository. Update it with flatpak update --user ai.storyteller.photocraft") + ); + // During uninstall, managed_elsewhere returns None so it can be removed + assert_eq!(managed_elsewhere_with(app, &flatpark_installed, true, |_| None), None); + + // When installed under a former bundle ID, the hint targets that detected ID + let former_installed = Installed { + version: version::parse("0.19.0"), + source: InstallSource::Flatpak, + location: "ai.storyteller.photocraft-old".into(), + package: Some("ai.storyteller.photocraft-old".into()), + externally_managed: true, + origin: Some("flatpark".into()), + installation: Some("system".into()), + }; + let hint_former = managed_elsewhere_with(app, &former_installed, false, |_| None); + assert_eq!( + hint_former.as_deref(), + Some("PhotoCraft was installed from a Flatpak repository. Update it with flatpak update --system ai.storyteller.photocraft-old") + ); + + let bundle_installed = Installed { + version: version::parse("0.19.0"), + source: InstallSource::Flatpak, + location: "ai.storyteller.photocraft".into(), + package: Some("ai.storyteller.photocraft".into()), + externally_managed: false, + origin: Some("photocraft-origin".into()), + installation: Some("user".into()), + }; + assert!(!bundle_installed.is_externally_managed()); + assert_eq!(choose_kinds_with(app, Some(&bundle_installed), None, &[], &[PackageKind::Flatpak], false), vec![PackageKind::Flatpak]); + assert_eq!(managed_elsewhere_with(app, &bundle_installed, false, |_| None), None); + } + + /// A copy in a named Flatpak installation is addressed through that installation, not the + /// default system scope. + #[test] + fn a_named_flatpak_installation_is_addressed_by_name() { + let app = crate::App::by_id("photocraft").unwrap(); + let installed = Installed { + version: version::parse("0.19.0"), + source: InstallSource::Flatpak, + location: "ai.storyteller.photocraft".into(), + package: Some("ai.storyteller.photocraft".into()), + externally_managed: true, + origin: Some("flatpark".into()), + installation: Some("work".into()), + }; + assert_eq!( + managed_elsewhere_with(app, &installed, false, |_| None).as_deref(), + Some("PhotoCraft was installed from a Flatpak repository. Update it with flatpak update --installation=work ai.storyteller.photocraft") + ); + } + + #[test] + #[cfg(target_os = "linux")] + fn update_flatpak_app_respects_cancellation() { + let app = crate::App::by_id("photocraft").unwrap(); + let stop = Stop::default(); + stop.cancel(); + let mut phase = |_| (); + assert_eq!(linux::update_flatpak_app(app, "ai.storyteller.photocraft", Some("user"), &stop, &mut phase), Err(CANCELLED.into())); + } + + #[test] + #[cfg(target_os = "linux")] + fn pause_lets_a_running_flatpak_command_finish_and_only_cancel_ends_it() { + let stop = Stop::default(); + stop.pause(); + assert_eq!(kill_on_cancel(&stop)(), Ok(())); + let app = crate::App::by_id("photocraft").unwrap(); + let mut phase = |_| (); + // A paused job starts no further command. + assert_eq!(linux::update_flatpak_app(app, "ai.storyteller.photocraft", Some("user"), &stop, &mut phase), Err(crate::protocol::PAUSED.into())); + stop.cancel(); + assert_eq!(kill_on_cancel(&stop)(), Err(CANCELLED.into())); + } + #[test] fn unavailable_arch_package_not_selected_for_new_install() { let app = crate::App::by_id("filmcraft").unwrap(); @@ -3419,6 +3720,9 @@ esac source: InstallSource::Launcher, location: dir.path().join("PhotoCraft.AppImage").display().to_string(), package: None, + externally_managed: false, + origin: None, + installation: None, }; let stop = Stop::default(); let mut job = Job { http: &http, paths: &paths, stop: &stop, phase, install_locations: &locations, replace: false }; @@ -3595,8 +3899,15 @@ esac let old = dir.path().join("Apps").join("PhotoCraft.AppImage"); std::fs::create_dir_all(old.parent().unwrap()).unwrap(); std::fs::write(&old, b"the installed 0.4.0").unwrap(); - let installed = - Installed { version: version::parse("0.4.0"), source: InstallSource::Launcher, location: old.display().to_string(), package: None }; + let installed = Installed { + externally_managed: false, + origin: None, + installation: None, + version: version::parse("0.4.0"), + source: InstallSource::Launcher, + location: old.display().to_string(), + package: None, + }; let previous = record("0.4.0", PackageKind::AppImage, old.clone(), vec![], false); let mut phases = Vec::new(); let mut phase = |p: JobPhase| phases.push(p); @@ -3637,7 +3948,15 @@ esac #[cfg(unix)] let _probe = crate::process::tests::RunningProbe::start(&location); assert!(process::is_running(Path::new(&location)), "{location} should be seen as running"); - let installed = Installed { version: version::parse("0.4.0"), source: InstallSource::Launcher, location, package: None }; + let installed = Installed { + externally_managed: false, + origin: None, + installation: None, + version: version::parse("0.4.0"), + source: InstallSource::Launcher, + location, + package: None, + }; let stop = Stop::default(); stop.cancel(); let mut job = Job { http: &http, paths: &paths, stop: &stop, phase, install_locations: &locations, replace: false }; @@ -3881,7 +4200,15 @@ esac } fn found_at(bundle: &Path) -> Installed { - Installed { version: None, source: InstallSource::MacApp, location: bundle.display().to_string(), package: None } + Installed { + version: None, + source: InstallSource::MacApp, + location: bundle.display().to_string(), + package: None, + externally_managed: false, + origin: None, + installation: None, + } } /// What [`check`] says when `codesign` fails with `failure`. @@ -4062,7 +4389,15 @@ esac let dir = tempfile::tempdir().unwrap(); let apps = dir.path().join("Applications"); let current = bundle(&apps, "0.5.0"); - let existing = Installed { version: None, source: InstallSource::MacApp, location: current.display().to_string(), package: None }; + let existing = Installed { + version: None, + source: InstallSource::MacApp, + location: current.display().to_string(), + package: None, + externally_managed: false, + origin: None, + installation: None, + }; let paths = Paths::under(dir.path()); let image = dmg(dir.path(), "0.6.0"); @@ -4095,7 +4430,15 @@ esac let dir = tempfile::tempdir().unwrap(); let apps = dir.path().join("Applications"); let current = bundle(&apps, "0.5.0"); - let existing = Installed { version: None, source: InstallSource::MacApp, location: current.display().to_string(), package: None }; + let existing = Installed { + version: None, + source: InstallSource::MacApp, + location: current.display().to_string(), + package: None, + externally_managed: false, + origin: None, + installation: None, + }; let image = dmg(dir.path(), "0.6.0"); let release = Release { tag: "v0.6.0".into(), version: version::parse("0.6.0"), ..Release::default() }; @@ -4125,7 +4468,15 @@ esac let dir = tempfile::tempdir().unwrap(); let apps = dir.path().join("Applications"); let current = bundle(&apps, "0.5.0"); - let existing = Installed { version: None, source: InstallSource::MacApp, location: current.display().to_string(), package: None }; + let existing = Installed { + version: None, + source: InstallSource::MacApp, + location: current.display().to_string(), + package: None, + externally_managed: false, + origin: None, + installation: None, + }; let paths = Paths::under(dir.path()); let image = dmg(dir.path(), "0.6.0"); diff --git a/crates/update/src/packages.rs b/crates/update/src/packages.rs index 1820c2f150..72c93a4b0c 100644 --- a/crates/update/src/packages.rs +++ b/crates/update/src/packages.rs @@ -13,6 +13,12 @@ pub struct Package { pub name: String, /// As the package manager reports it (`0.5.0-1`); empty when it doesn't say. pub version: String, + /// Whether this is a user installation (`true`) or system installation (`false`). + pub user: bool, + /// The origin remote (`flatpark`, `-origin`, `flathub`), when known. + pub origin: Option, + /// The installation scope or name (`user`, `system`, or a named installation), for Flatpak installs. + pub installation: Option, } /// `dpkg-query -W -f '${Package}|${db:Status-Status}|${Version}\n'`: installed packages only. @@ -46,18 +52,35 @@ pub fn parse_pacman(text: &str) -> Vec<(String, String)> { .collect() } -/// `flatpak list --app --columns=application,version`: the version column is often empty for -/// bundles built from a release tarball. -pub fn parse_flatpak_list(text: &str) -> Vec<(String, String)> { +/// `flatpak list --app --columns=application,version,origin,installation`: parses id, version, origin, and installation. +pub fn parse_flatpak_list_with_origin(text: &str) -> Vec<(String, String, Option, Option)> { text.lines() .filter_map(|line| { let mut f = line.split('\t'); let id = f.next()?.trim(); - (!id.is_empty()).then(|| (id.to_string(), f.next().unwrap_or("").trim().to_string())) + if id.is_empty() { + return None; + } + let version = f.next().unwrap_or("").trim().to_string(); + let origin = f.next().map(str::trim).filter(|o| !o.is_empty()).map(ToString::to_string); + let installation = f.next().map(str::trim).filter(|i| !i.is_empty()).map(ToString::to_string); + Some((id.to_string(), version, origin, installation)) }) .collect() } +/// `flatpak list --app --columns=application,version`: the version column is often empty for +/// bundles built from a release tarball. +pub fn parse_flatpak_list(text: &str) -> Vec<(String, String)> { + parse_flatpak_list_with_origin(text).into_iter().map(|(id, v, _, _)| (id, v)).collect() +} + +/// Whether an origin string indicates an install from FlatPark. +pub fn is_flatpark_origin(origin: &str) -> bool { + let o = origin.trim(); + o.eq_ignore_ascii_case("flatpark") || o.to_ascii_lowercase().contains("flatpark") +} + /// The `Version:` line of `flatpak info `. pub fn parse_flatpak_info(text: &str) -> Option { text.lines().find_map(|l| l.trim().strip_prefix("Version:").map(|v| v.trim().to_string())).filter(|v| !v.is_empty()) @@ -78,11 +101,14 @@ pub fn candidate_names(app: &App, manager: InstallSource) -> Vec { } } -/// The package of `app` among `installed`, preferring the manager listed first in `order`. +/// The package of `app` among `installed`, preferring the manager listed first in `order`. A user +/// install beats a system one under any of the app's ids; within a scope the current id wins. pub fn find<'a>(app: &App, installed: &'a [Package], order: &[InstallSource]) -> Option<&'a Package> { order.iter().find_map(|manager| { let names = candidate_names(app, *manager); - names.iter().find_map(|n| installed.iter().find(|p| p.manager == *manager && p.name == *n)) + [true, false] + .into_iter() + .find_map(|user| names.iter().find_map(|n| installed.iter().find(|p| p.manager == *manager && p.user == user && p.name == *n))) }) } @@ -96,7 +122,7 @@ mod tests { use super::*; fn pkgs(manager: InstallSource, list: Vec<(String, String)>) -> Vec { - list.into_iter().map(|(name, version)| Package { manager, name, version }).collect() + list.into_iter().map(|(name, version)| Package { manager, name, version, user: false, origin: None, installation: None }).collect() } #[test] @@ -111,6 +137,8 @@ mod tests { parse_flatpak_list("ai.storyteller.wordcraft\t\nai.storyteller.cadcraft\t0.3.0\n"), [("ai.storyteller.wordcraft".into(), String::new()), ("ai.storyteller.cadcraft".into(), "0.3.0".into())] ); + // A row with no id is not a package listing. + assert!(parse_flatpak_list_with_origin("\t0.2.0\tflatpark\tuser\n").is_empty()); let info = "\nWordCraft - Word processor\n\n ID: ai.storyteller.wordcraft\n Version: 0.3.0\n Branch: master\n"; assert_eq!(parse_flatpak_info(info).as_deref(), Some("0.3.0")); assert_eq!(parse_flatpak_info("Version: \n"), None); @@ -158,4 +186,143 @@ mod tests { assert_eq!(version_of(hit).unwrap().to_string(), "0.5.0"); assert_eq!(find(photo, &installed, &[InstallSource::Flatpak]).unwrap().version, "0.4.0"); } + + #[test] + fn parses_flatpak_list_with_origin_and_spots_flatpark() { + let text = "ai.storyteller.photocraft\t0.19.0\tflatpark\tuser\nai.storyteller.cadcraft\t0.16.0\tcadcraft-origin\tsystem\nai.storyteller.wordcraft\t0.14.0\t\t\n"; + let list = parse_flatpak_list_with_origin(text); + assert_eq!( + list, + [ + ("ai.storyteller.photocraft".into(), "0.19.0".into(), Some("flatpark".into()), Some("user".into())), + ("ai.storyteller.cadcraft".into(), "0.16.0".into(), Some("cadcraft-origin".into()), Some("system".into())), + ("ai.storyteller.wordcraft".into(), "0.14.0".into(), None, None), + ] + ); + assert!(is_flatpark_origin("flatpark")); + assert!(is_flatpark_origin("FlatPark")); + assert!(is_flatpark_origin("flatpark-origin")); + assert!(!is_flatpark_origin("cadcraft-origin")); + assert!(!is_flatpark_origin("flathub")); + assert!(!is_flatpark_origin("")); + } + + #[test] + fn flatpak_find_prioritizes_user_over_system() { + let photo = App::by_id("photocraft").unwrap(); + let installed = vec![ + Package { + manager: InstallSource::Flatpak, + name: "ai.storyteller.photocraft".into(), + version: "0.18.0".into(), + user: false, + origin: Some("flathub".into()), + installation: Some("system".into()), + }, + Package { + manager: InstallSource::Flatpak, + name: "ai.storyteller.photocraft".into(), + version: "0.19.0".into(), + user: true, + origin: Some("flatpark".into()), + installation: Some("user".into()), + }, + ]; + let found = find(photo, &installed, &[InstallSource::Flatpak]).unwrap(); + assert!(found.user); + assert_eq!(found.version, "0.19.0"); + assert_eq!(found.origin.as_deref(), Some("flatpark")); + assert_eq!(found.installation.as_deref(), Some("user")); + } +} + +/// Matches the OCI URL from https://getartcraft.com/artcraft-oci.flatpakrepo, +/// independently of its local remote name (normally `artcraft-oci`). +pub fn is_artcraft_remote(origin: &str, remotes: &str) -> bool { + remotes.lines().any(|line| { + let Some((name, url)) = line.split_once('\t') else { return false }; + let url = url.trim().trim_end_matches('/'); + name.trim() == origin && url == "oci+https://getartcraft.com" + }) +} + +#[cfg(test)] +mod remote_url_tests { + use super::*; + #[test] + fn recognizes_custom_names_and_rejects_unrelated_urls() { + assert!(is_artcraft_remote("artcraft-oci", "artcraft-oci\toci+https://getartcraft.com\n")); + assert!(is_artcraft_remote("custom", "custom\toci+https://getartcraft.com/\n")); + for url in [ + "oci+https://getartcraft.com.evil", + "oci+https://getartcraft.com/other", + "oci+http://getartcraft.com", + "https://getartcraft.com/linux", + "https://getartcraft.com/artcraft-oci.flatpakrepo", + "https://getartcraft.com", + ] { + assert!(!is_artcraft_remote("custom", &format!("custom\t{url}"))); + } + assert!(!is_artcraft_remote("other", "custom\toci+https://getartcraft.com")); + } +} + +/// A missing ref permits bundle fallback; an unknown or different version must not replace it. +#[cfg(all(target_os = "linux", feature = "oci_migration"))] +pub(crate) fn oci_ref_available(reference: &str, expected: &version::Version, listing: &str) -> Result { + for line in listing.lines() { + let mut fields = line.split('\t'); + if fields.next().map(str::trim) != Some(reference) { + continue; + } + let candidate = fields.next().and_then(|value| version::parse(value.trim())); + if candidate.as_ref() != Some(expected) { + return Err("The ArtCraft OCI repository does not yet provide the selected version".into()); + } + return Ok(true); + } + Ok(false) +} + +#[cfg(all(test, target_os = "linux", feature = "oci_migration"))] +mod migration_tests { + use super::*; + #[test] + fn migration_requires_the_exact_ref_and_selected_version() { + let reference = "app/ai.storyteller.photocraft/x86_64/stable"; + let expected = version::parse("1.2.3").unwrap(); + assert_eq!(oci_ref_available(reference, &expected, &format!("{reference}\t1.2.3")), Ok(true)); + assert_eq!(oci_ref_available(reference, &expected, "app/ai.storyteller.photocraft/aarch64/stable\t1.2.3"), Ok(false)); + for value in ["", "1.2.2", "1.2.4", "unknown"] { + assert!(oci_ref_available(reference, &expected, &format!("{reference}\t{value}")).is_err()); + } + } +} + +/// Only a confirmed bundle origin with no repository URL permits bundle replacement. +/// Missing rows are unknown, so preserve remote ownership conservatively. +pub fn remote_manages_flatpak(origin: &str, remotes: &str) -> bool { + remotes + .lines() + .find_map(|line| { + let mut fields = line.split('\t'); + if fields.next().map(str::trim) != Some(origin) { + return None; + } + Some(fields.next().is_some_and(|url| !url.trim().is_empty())) + }) + .unwrap_or(true) +} + +#[cfg(test)] +mod remote_ownership_tests { + use super::*; + #[test] + fn only_confirmed_empty_urls_allow_bundle_replacement() { + assert!(!remote_manages_flatpak("app-origin", "app-origin\t\n")); + assert!(remote_manages_flatpak("renamed", "renamed\thttps://example.org/repo\n")); + assert!(remote_manages_flatpak("renamed", "renamed\toci+https://getartcraft.com\n")); + assert!(remote_manages_flatpak("missing", "other\t\n")); + assert!(!remote_manages_flatpak("app-origin", "app-origin")); + } } diff --git a/crates/update/src/process.rs b/crates/update/src/process.rs index 13ed8dda40..c20c3bc458 100644 --- a/crates/update/src/process.rs +++ b/crates/update/src/process.rs @@ -839,3 +839,81 @@ mod inherited_pipe_tests { } } } + +/// Runs a helper while polling cancellation and draining its bounded output. +#[cfg(target_os = "linux")] +pub(crate) fn cancellable_output(mut cmd: Command, check: impl Fn() -> Result<(), String>) -> Result { + check()?; + let mut child = + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().map_err(|e| format!("couldn't run flatpak ({e})"))?; + let stdout = read_all(child.stdout.take()).map_err(|e| format!("couldn't read flatpak output ({e})"))?; + let stderr = read_all(child.stderr.take()).map_err(|e| format!("couldn't read flatpak output ({e})"))?; + let started = Instant::now(); + let status = loop { + if started.elapsed() >= Duration::from_secs(60 * 60) { + let _ = child.kill(); + let _ = child.wait(); + return Err("Flatpak did not finish within one hour".into()); + } + if let Err(e) = check() { + let _ = child.kill(); + let _ = child.wait(); + return Err(e); + } + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) => std::thread::sleep(Duration::from_millis(25)), + Err(e) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("couldn't wait for flatpak ({e})")); + } + } + }; + let deadline = Instant::now(); + while !stdout.is_finished() || !stderr.is_finished() { + check()?; + if deadline.elapsed() > Duration::from_secs(5) { + return Err("Flatpak output did not close after completion".into()); + } + std::thread::sleep(Duration::from_millis(25)); + } + Ok(std::process::Output { status, stdout: stdout.join().unwrap_or_default(), stderr: stderr.join().unwrap_or_default() }) +} + +#[cfg(all(test, target_os = "linux"))] +mod update_cancel_tests { + use super::*; + + #[test] + fn cancels_a_running_helper_promptly() { + let mut cmd = command("sleep"); + cmd.arg("30"); + let start = Instant::now(); + let result = cancellable_output(cmd, || if start.elapsed() >= Duration::from_millis(100) { Err("cancelled".into()) } else { Ok(()) }); + assert_eq!(result.unwrap_err(), "cancelled"); + assert!(start.elapsed() < Duration::from_secs(5)); + } + + /// A descendant that outlives the helper keeps the pipes open; the caller gets an error at + /// the deadline instead of waiting for it. + #[test] + fn output_held_open_by_a_descendant_fails_at_the_deadline() { + let mut cmd = command("sh"); + cmd.args(["-c", "sleep 8 &"]); + let start = Instant::now(); + let err = cancellable_output(cmd, || Ok(())).expect_err("a descendant holding the pipes should time out"); + assert!(err.contains("did not close after completion"), "{err}"); + assert!(start.elapsed() < Duration::from_secs(8), "{:?}", start.elapsed()); + } + + #[test] + fn retains_both_output_streams_and_exit_status() { + let mut cmd = command("sh"); + cmd.args(["-c", "printf output; printf error >&2; exit 7"]); + let output = cancellable_output(cmd, || Ok(())).unwrap(); + assert_eq!(output.status.code(), Some(7)); + assert_eq!(output.stdout, b"output"); + assert_eq!(output.stderr, b"error"); + } +} diff --git a/crates/update/src/self_update.rs b/crates/update/src/self_update.rs index a20f466ce1..f96c3af633 100644 --- a/crates/update/src/self_update.rs +++ b/crates/update/src/self_update.rs @@ -878,7 +878,15 @@ pub fn prepare_update_with_options( match install { #[cfg(target_os = "macos")] Install::MacApp(bundle) => { - let existing = Installed { version: None, source: InstallSource::MacApp, location: bundle.display().to_string(), package: None }; + let existing = Installed { + version: None, + source: InstallSource::MacApp, + location: bundle.display().to_string(), + package: None, + externally_managed: false, + origin: None, + installation: None, + }; let wait = install::macos::CheckTurn { stop, phase: &mut *phase }; let placed = install::macos::install_dmg(app, &file, Some(&existing), None, false, paths, &install::macos::Expect::self_update(release), wait); @@ -3535,7 +3543,15 @@ mod tests { assert!(ok, "hdiutil create failed"); drop(one_at_a_time); let current = apps.join("ArtCraft Launcher.app"); - let existing = Installed { version: None, source: InstallSource::MacApp, location: current.display().to_string(), package: None }; + let existing = Installed { + version: None, + source: InstallSource::MacApp, + location: current.display().to_string(), + package: None, + externally_managed: false, + origin: None, + installation: None, + }; // An unsigned test bundle: the signature check has its own tests in `install`. let expect = install::macos::Expect { team: None, version: None, quit_first: false }; let stop = Stop::default(); diff --git a/crates/update/src/status.rs b/crates/update/src/status.rs index 1cd0cf76cb..cc985df0a0 100644 --- a/crates/update/src/status.rs +++ b/crates/update/src/status.rs @@ -61,4 +61,21 @@ pub struct Installed { /// The package that installed it, for package-manager installs (`photocraft-bin`). #[serde(default)] pub package: Option, + /// Whether this copy is managed externally (such as a Flatpak from FlatPark) and + /// will not be replaced with a downloaded bundle. + #[serde(default)] + pub externally_managed: bool, + /// The remote repository or origin (`flatpark`, `-origin`), when known. + #[serde(default)] + pub origin: Option, + /// The installation scope or name (`user`, `system`, or a named installation), for Flatpak installs. + #[serde(default)] + pub installation: Option, +} + +impl Installed { + /// Whether this copy is managed externally and should not be replaced by a downloaded bundle. + pub fn is_externally_managed(&self) -> bool { + self.externally_managed + } } From a9efd722b49924588448fba5c59f36d3aee3f4c6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 17:56:38 -0500 Subject: [PATCH 067/144] Expose bounded BMP header recognition for consumer cutovers (#1929) * Expose supported BMP header recognition Port the BMP routing check from LightCraft commit 304180a500d1b3f87c8c841f269d305161d6c8b9, preserving minimum length and DIB allowlist. * Test BMP routing boundaries and unsupported DIB sizes --------- Co-authored-by: Brandon Thomas --- crates/image-codecs/src/bmp_probe.rs | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/crates/image-codecs/src/bmp_probe.rs b/crates/image-codecs/src/bmp_probe.rs index 59c78ca1e6..5b47721bca 100644 --- a/crates/image-codecs/src/bmp_probe.rs +++ b/crates/image-codecs/src/bmp_probe.rs @@ -1,5 +1,18 @@ //! Header-only BMP dimensions and pixel-data coverage, without allocating a canvas. +/// Recognize a BMP file header with a supported DIB header kind. +/// +/// This is a format-routing check, not full validation: dimensions and pixel data may still +/// be invalid. Unlike the broad signature detector, it requires the minimum 26-byte core +/// header and a known DIB size, preserving callers that reject arbitrary `BM` prefixes. +pub fn is_supported_header(b: &[u8]) -> bool { + if b.len() >= 26 && b.starts_with(b"BM") { + let dib = u32::from_le_bytes([b[14], b[15], b[16], b[17]]); + return matches!(dib, 12 | 16 | 40 | 52 | 56 | 64 | 108 | 124); + } + false +} + /// Coverage of the declared pixel array. Row byte counts include row padding; RLE coverage /// counts the pixels drawn by commands and may be smaller than the canvas. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -142,4 +155,23 @@ mod tests { let nibble = bmp(2, &[0, 3, 0x12, 0x30, 0, 1]); assert_eq!(coverage(&nibble, 4, 2).pixels, 3); } + #[test] + fn supported_header_recognition_preserves_length_signature_and_dib_rules() { + let mut b = [0_u8; 26]; + b[..2].copy_from_slice(b"BM"); + for dib in [12_u32, 16, 40, 52, 56, 64, 108, 124] { + b[14..18].copy_from_slice(&dib.to_le_bytes()); + assert!(is_supported_header(&b), "DIB {dib}"); + for n in 0..26 { + assert!(!is_supported_header(&b[..n]), "prefix {n}"); + } + } + for dib in [0_u32, 13, 39, 41, 125, u32::MAX] { + b[14..18].copy_from_slice(&dib.to_le_bytes()); + assert!(!is_supported_header(&b), "DIB {dib}"); + } + b[14..18].copy_from_slice(&40_u32.to_le_bytes()); + b[0] = b'X'; + assert!(!is_supported_header(&b)); + } } From be0b1e655229e34f1ad263ef3d2170e46449c39b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 18:22:56 -0500 Subject: [PATCH 068/144] cover the Flatpak repository guard and its update command (#1956) The Flatpak/OCI migration left update_flatpak_app and the refusal to replace a repository-managed Flatpak without tests. A stand-in flatpak on PATH, in child processes so the environment stays private, covers every scope flag, both command shapes, a successful update and Flatpak's error text; the guard test asserts the refusal happens before anything is downloaded. --- crates/update/src/install.rs | 111 +++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/crates/update/src/install.rs b/crates/update/src/install.rs index 0714345958..3b35132948 100644 --- a/crates/update/src/install.rs +++ b/crates/update/src/install.rs @@ -3673,6 +3673,117 @@ esac ); } + /// A Flatpak the user installed from a repository is never replaced by the launcher's bundle: + /// the refusal names the repository's own update command, and nothing is downloaded. + #[test] + #[cfg(target_os = "linux")] + fn a_repository_flatpak_is_not_replaced_by_a_bundle_install() { + let app = crate::App::by_id("photocraft").unwrap(); + let dir = tempfile::tempdir().unwrap(); + let paths = Paths::under(dir.path()); + let http = Http::new(crate::TEST_AGENT).unwrap(); + let mut phases = Vec::new(); + let mut phase = |p: JobPhase| phases.push(p); + let mut job = Job { + http: &http, + paths: &paths, + stop: &Stop::default(), + phase: &mut phase, + install_locations: &InstallLocations::default(), + replace: false, + }; + let release = Release { version: version::parse("0.20.0"), tag: "v0.20.0".into(), ..Release::default() }; + let asset = Asset { name: "photocraft-0.20.0-linux-x86_64.flatpak".into(), ..Asset::default() }; + let installed = Installed { + version: version::parse("0.19.0"), + source: InstallSource::Flatpak, + location: app.bundle_id(), + package: Some(app.bundle_id()), + externally_managed: true, + origin: Some("flatpark".into()), + installation: Some("work".into()), + }; + let error = install(app, &release, &asset, PackageKind::Flatpak, Some(&installed), None, &mut job).unwrap_err(); + assert_eq!( + error, + "PhotoCraft was installed from a Flatpak repository. Update it with flatpak update --installation=work ai.storyteller.photocraft" + ); + assert!(phases.is_empty(), "the bundle installer started for a Flatpak the user manages"); + assert!(!paths.cache.exists(), "the refusal must come before anything is downloaded"); + } + + /// `update_flatpak_app` drives the user's own copy: the scope flag for the installation it sits + /// in, a successful update, and Flatpak's error text with its `error: ` prefix removed. A + /// stand-in `flatpak` on PATH reports what it was asked to run; the test runs in child + /// processes so that PATH stays private to it (as `updater`'s pretend-version test does). + #[test] + #[cfg(target_os = "linux")] + fn a_flatpak_from_a_repository_is_updated_through_its_own_installation() { + const NAME: &str = "install::tests::a_flatpak_from_a_repository_is_updated_through_its_own_installation"; + const DIR: &str = "CRAFT_UPDATE_FAKE_FLATPAK_DIR"; + if std::env::var_os(DIR).is_none() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let script = r#"#!/bin/sh +echo "$(basename "$0") $*" >> "$CRAFT_UPDATE_FAKE_FLATPAK_CALLS" +case "$*" in +*denied.app*) echo "error: Permission denied" >&2; exit 1 ;; +*diskfull.app*) echo "Error: Disk full" >&2; exit 1 ;; +*silent.app*) exit 1 ;; +esac +exit 0 +"#; + for program in ["flatpak", "flatpak-spawn"] { + let path = dir.path().join(program); + std::fs::write(&path, script).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let path = format!("{}:{}", dir.path().display(), std::env::var("PATH").unwrap_or_default()); + for sandboxed in [false, true] { + let calls = dir.path().join(format!("calls-{sandboxed}")); + let mut cmd = std::process::Command::new(std::env::current_exe().unwrap()); + cmd.args(["--exact", NAME, "--nocapture"]) + .env(DIR, dir.path()) + .env("CRAFT_UPDATE_FAKE_FLATPAK_CALLS", &calls) + .env("PATH", &path) + .env_remove("FLATPAK_ID"); + if sandboxed { + cmd.env("FLATPAK_ID", "ai.storyteller.photocraft"); + } + let status = cmd.status().unwrap(); + assert!(status.success(), "the sandboxed={sandboxed} run failed"); + } + return; + } + let calls = std::env::var_os("CRAFT_UPDATE_FAKE_FLATPAK_CALLS").map(PathBuf::from).unwrap(); + let app = crate::App::by_id("photocraft").unwrap(); + let stop = Stop::default(); + let mut phase = |_| (); + let id = app.bundle_id(); + assert_eq!(linux::update_flatpak_app(app, &id, None, &stop, &mut phase), Ok(())); + assert_eq!( + linux::update_flatpak_app(app, "denied.app", Some("user"), &stop, &mut phase), + Err("Flatpak couldn't update PhotoCraft: Permission denied".to_string()) + ); + assert_eq!( + linux::update_flatpak_app(app, "diskfull.app", Some("work"), &stop, &mut phase), + Err("Flatpak couldn't update PhotoCraft: Disk full".to_string()) + ); + assert_eq!( + linux::update_flatpak_app(app, "silent.app", Some("system"), &stop, &mut phase), + Err("Flatpak couldn't update PhotoCraft".to_string()) + ); + let prefix = if process::in_sandbox() { "flatpak-spawn --host --watch-bus flatpak" } else { "flatpak" }; + let expected: Vec = vec![ + format!("{prefix} update --system -y --noninteractive {id}"), + format!("{prefix} update --user -y --noninteractive denied.app"), + format!("{prefix} update --installation=work -y --noninteractive diskfull.app"), + format!("{prefix} update --system -y --noninteractive silent.app"), + ]; + let calls = std::fs::read_to_string(&calls).unwrap(); + assert_eq!(calls.lines().map(str::to_string).collect::>(), expected); + } + #[test] #[cfg(target_os = "linux")] fn update_flatpak_app_respects_cancellation() { From a0cd0e2afbe5c3c1a232c21b0ba36e39e03f07a5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 20:10:44 -0500 Subject: [PATCH 069/144] fix(flow): use CSS percentage scale for numeric HSL channels --- crates/flow/src/color.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/flow/src/color.rs b/crates/flow/src/color.rs index a80fdf60a7..941b25902c 100644 --- a/crates/flow/src/color.rs +++ b/crates/flow/src/color.rs @@ -131,7 +131,8 @@ pub fn parse_color(s: &str) -> Option { if let Some(p) = x.strip_suffix('%') { Some((p.trim().parse::().ok()? / 100.0).clamp(0.0, 1.0)) } else { - Some(x.parse::().ok()?.clamp(0.0, 1.0)) + // CSS Color 4: numeric saturation and lightness use the same 0–100 scale as percentages. + Some((x.parse::().ok()? / 100.0).clamp(0.0, 1.0)) } }; let s = parse_pct(parts[1])?; @@ -193,4 +194,20 @@ mod tests { assert_eq!(parse_color("rgba(0, 0, 0, inf)"), Some(Rgb(0, 0, 0))); assert_eq!(parse_color("rgba(0, 0, 0, nan%)"), Some(Rgb(0, 0, 0))); } + + #[test] + fn numeric_hsl_channels_use_the_percentage_scale() { + for (numeric, percent, expected) in [ + ("hsl(0 0 50)", "hsl(0 0% 50%)", Rgb(128, 128, 128)), + ("hsl(0 100 50)", "hsl(0 100% 50%)", Rgb(255, 0, 0)), + ("hsl(120 50 50)", "hsl(120 50% 50%)", Rgb(64, 191, 64)), + ("hsl(0 0 1)", "hsl(0 0% 1%)", Rgb(3, 3, 3)), + ("hsl(0 -10 150)", "hsl(0 -10% 150%)", Rgb(255, 255, 255)), + ("hsl(0 100 -10)", "hsl(0 100% -10%)", Rgb(0, 0, 0)), + ("hsla(0.5turn 100 50 / 50%)", "hsla(0.5turn 100% 50% / 50%)", Rgb(128, 255, 255)), + ] { + assert_eq!(parse_color(numeric), Some(expected), "{numeric}"); + assert_eq!(parse_color(numeric), parse_color(percent), "{numeric} == {percent}"); + } + } } From e2bf53f2bdba4828e21097774a568ed9c74b0004 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 20:25:09 -0500 Subject: [PATCH 070/144] craft-audio: share non-seeking canonical WAV streaming primitives (#1962) --- ATTRIBUTION.md | 4 ++ crates/audio/src/lib.rs | 4 ++ crates/audio/src/wav_stream.rs | 119 +++++++++++++++++++++++++++++++++ 3 files changed, 127 insertions(+) create mode 100644 crates/audio/src/wav_stream.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index ab167207cf..8840199b25 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -103,3 +103,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso `crates/tga/src/metadata_tests.rs` and metadata-boundary helpers in `crates/tga/src/lib.rs` are adapted from nuclearspike's FilmCraft #1932 at `e7842f76f887005c460c64a8ab51d59d086e6f27` (MIT OR Apache-2.0). Synthetic fixtures are original contributor test data; primary Git author retained. The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper are ported from Craft Anything `8f3b775157d331dd31cfa4da911e26d8856b8c77` (same MIT OR Apache-2.0 source licenses). Brandon Thomas is the primary import author; retained hardening credits include Afloat, BFlat, Rahul, RRFZ and NetterSilver. The finite-real fix preserves gmrmad1 as author from Craft Anything #1905 (`d85e104f`); quoted-attribute/line-ending regressions preserve RRFZ. Bounds/adaptation and bounded entity scanning are subsequent Dylan M. Taylor changes. App-specific JSON projections and keyed-archive interpretation remain outside this crate. + +## Non-seeking WAV primitives + +`crates/audio/src/wav_stream.rs` is extracted from AniCraft `crates/audio/src/wav.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0). Tanish Manku is retained as the primary import author, from original commit `30c121d269a49d9abe54a3834ed4aa0201542535`. Odd-data padding accounting, shared API documentation and regression tests are subsequent Dylan M. Taylor changes. diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index c7382a973d..e4a1c16952 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -775,3 +775,7 @@ mod tests { /// DVD and Blu-ray LPCM packet decoding. pub mod lpcm; + +/// Non-seeking canonical WAV streaming primitives. +#[cfg(feature = "pcm-encode")] +pub mod wav_stream; diff --git a/crates/audio/src/wav_stream.rs b/crates/audio/src/wav_stream.rs new file mode 100644 index 0000000000..9da2bdcc9d --- /dev/null +++ b/crates/audio/src/wav_stream.rs @@ -0,0 +1,119 @@ +//! Canonical RIFF/WAVE header and interleaved sample blocks for non-seekable sinks. +//! +//! Extracted from AniCraft's WAV writer, preserving its byte-level compatibility. +//! Unlike `FileEncoder`, these primitives do not require `Seek` and leave final lengths, +//! chunk padding and sink error handling to the caller. The caller must supply a complete +//! frame count and append exactly that many frames. For odd-length data, append a pad byte +//! (the header includes that padding in the RIFF size); current AniCraft output is always stereo (even). +//! Non-finite samples become silence, including float output. This deliberately differs +//! from the general encoder's infinity handling. Prefer `FileEncoder` for new seekable sinks. + +/// Sample formats written. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Bits { + /// Signed 16-bit PCM. + Int16, + /// Signed 24-bit PCM. + Int24, + /// IEEE 754 32-bit float. + Float32, +} + +impl Bits { + fn bytes(self) -> u16 { + match self { + Bits::Int16 => 2, + Bits::Int24 => 3, + Bits::Float32 => 4, + } + } +} + +const PCM: u16 = 1; +const FLOAT: u16 = 3; + +/// A WAV header for `frames` frames of `channels` channels. +/// Returns `None` for zero rate/channels or any size/byte-rate field overflow. +pub fn header(rate: u32, channels: u16, bits: Bits, frames: u64) -> Option> { + if rate == 0 || channels == 0 { + return None; + } + let b = bits.bytes(); + let data = u32::try_from(frames.checked_mul(u64::from(b) * u64::from(channels))?).ok()?; + let riff = data.checked_add(36)?.checked_add(data & 1)?; + let block = channels.checked_mul(b)?; + let byte_rate = rate.checked_mul(u32::from(block))?; + let tag = if bits == Bits::Float32 { FLOAT } else { PCM }; + let mut h = Vec::with_capacity(44); + h.extend_from_slice(b"RIFF"); + h.extend_from_slice(&riff.to_le_bytes()); + h.extend_from_slice(b"WAVEfmt "); + h.extend_from_slice(&16u32.to_le_bytes()); + h.extend_from_slice(&tag.to_le_bytes()); + h.extend_from_slice(&channels.to_le_bytes()); + h.extend_from_slice(&rate.to_le_bytes()); + h.extend_from_slice(&byte_rate.to_le_bytes()); + h.extend_from_slice(&block.to_le_bytes()); + h.extend_from_slice(&(b * 8).to_le_bytes()); + h.extend_from_slice(b"data"); + h.extend_from_slice(&data.to_le_bytes()); + Some(h) +} + +/// Appends samples in `bits` format. Integers are rounded and clipped to range; `x · 32768` +/// for 16-bit, so 16-bit sources read by [`crate::decode`] come back bit-identical. +pub fn append(out: &mut Vec, samples: &[f32], bits: Bits) { + out.reserve(samples.len() * usize::from(bits.bytes())); + for &s in samples { + let s = if s.is_finite() { s } else { 0.0 }; + match bits { + Bits::Int16 => out.extend_from_slice(&((s * 32_768.0).round().clamp(-32_768.0, 32_767.0) as i16).to_le_bytes()), + Bits::Int24 => { + let v = (f64::from(s) * 8_388_608.0).round().clamp(-8_388_608.0, 8_388_607.0) as i32; + out.extend_from_slice(v.to_le_bytes().get(..3).unwrap_or(&[0, 0, 0])); + } + Bits::Float32 => out.extend_from_slice(&s.to_le_bytes()), + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::indexing_slicing)] +mod tests { + use super::*; + + #[test] + fn canonical_header_and_odd_padding() { + let h = header(48_000, 2, Bits::Int16, 1).unwrap(); + assert_eq!(h.len(), 44); + assert_eq!(&h[..12], b"RIFF\x28\0\0\0WAVE"); + assert_eq!(&h[28..36], &[0, 238, 2, 0, 4, 0, 16, 0]); + let h = header(8_000, 1, Bits::Int24, 1).unwrap(); + assert_eq!(&h[4..8], &40u32.to_le_bytes()); + assert_eq!(&h[40..44], &3u32.to_le_bytes()); + assert!(header(0, 2, Bits::Int16, 1).is_none()); + assert!(header(48_000, 0, Bits::Int16, 1).is_none()); + assert!(header(u32::MAX, 2, Bits::Int16, 1).is_none()); + assert!(header(48_000, 2, Bits::Float32, u64::MAX).is_none()); + assert!(header(48_000, u16::MAX, Bits::Float32, 0).is_none()); + } + + #[test] + fn samples_preserve_rounding_clipping_silence_and_chunk_boundaries() { + let samples = [-2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY]; + let mut pcm = Vec::new(); + append(&mut pcm, &samples, Bits::Int16); + let expected = [-32768i16, -32768, -16384, 0, 16384, 32767, 32767, 0, 0, 0]; + assert_eq!(pcm, expected.iter().flat_map(|s| s.to_le_bytes()).collect::>()); + for bits in [Bits::Int16, Bits::Int24, Bits::Float32] { + let mut whole = Vec::new(); + append(&mut whole, &samples, bits); + let mut blocks = Vec::new(); + for block in samples.chunks(3) { + append(&mut blocks, block, bits); + } + assert_eq!(whole, blocks); + assert_eq!(&whole[whole.len() - 3 * usize::from(bits.bytes())..], vec![0; 3 * usize::from(bits.bytes())]); + } + } +} From 8479a1f3bbabb0e0b25194c508ab2eb14aa5490f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 20:30:05 -0500 Subject: [PATCH 071/144] pkcs7: CMS signing with caller-owned key providers (#1963) --- crates/pkcs7/src/cms.rs | 116 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 106 insertions(+), 10 deletions(-) diff --git a/crates/pkcs7/src/cms.rs b/crates/pkcs7/src/cms.rs index 083aa43029..2bccf50995 100644 --- a/crates/pkcs7/src/cms.rs +++ b/crates/pkcs7/src/cms.rs @@ -449,25 +449,55 @@ struct SignedDataInput<'a> { content_digest: &'a [u8], } -fn build(input: SignedDataInput<'_>) -> Result, Error> { - let SignedDataInput { key, cert, chain, alg, content_type, content, content_digest } = input; - let cert_hash = DigestAlg::Sha256.digest(&[&cert.raw]); - let general_names = der::seq(&[&der::explicit(4, &cert.issuer.raw)]); +/// Public certificate material used by the CMS writer. `serial` is the original INTEGER +/// contents, including its sign padding; `issuer_der` and `der` are complete DER encodings. +/// Callers obtain these fields from an already parsed certificate. No private key is held. +#[derive(Clone, Copy, Debug)] +pub struct SigningCertificate<'a> { + pub der: &'a [u8], + pub issuer_der: &'a [u8], + pub serial: &'a [u8], +} + +/// Inputs for a CAdES SignedData envelope. The caller computes `content_digest` using `alg`. +/// `content` is absent for detached signatures, or the bytes to encapsulate for a token. +/// Certificate-chain entries are complete DER certificates; the signer is deduplicated. +#[derive(Clone, Copy, Debug)] +pub struct SigningInput<'a> { + pub cert: SigningCertificate<'a>, + pub chain: &'a [&'a [u8]], + pub alg: DigestAlg, + pub content_type: &'a str, + pub content: Option<&'a [u8]>, + pub content_digest: &'a [u8], + /// Complete DER AlgorithmIdentifier matching the callback's signing operation. + pub signature_algorithm: &'a [u8], +} + +/// Build the same signed attributes and envelope as [`sign_detached`] / [`sign_encapsulated`], +/// signing through a caller-owned key provider. The callback receives the exact DER SET +/// of signed attributes once (not its digest). It must sign those bytes using `alg` and the +/// supplied signature AlgorithmIdentifier. Its error is returned unchanged, without retry. +/// This lets apps retain platform/keychain/token signing without exporting a private key. +pub fn sign_with(input: SigningInput<'_>, sign: impl FnOnce(&[u8]) -> Result, E>) -> Result, E> { + let SigningInput { cert, chain, alg, content_type, content, content_digest, signature_algorithm } = input; + let cert_hash = DigestAlg::Sha256.digest(&[cert.der]); + let general_names = der::seq(&[&der::explicit(4, cert.issuer_der)]); // The serial as the certificate has it: `cert.serial` is the INTEGER's own bytes, so one with // its high bit set gets no leading zero here. - let serial = der::tlv(tag::INTEGER, if cert.serial.is_empty() { &[0] } else { &cert.serial }); + let serial = der::tlv(tag::INTEGER, if cert.serial.is_empty() { &[0] } else { cert.serial }); let ess = der::seq(&[&der::seq(&[&der::seq(&[&der::octets(&cert_hash), &der::seq(&[&general_names, &serial])])])]); let attrs = [attribute(CONTENT_TYPE, &der::oid(content_type)), attribute(MESSAGE_DIGEST, &der::octets(content_digest)), attribute(SIGNING_CERT_V2, &ess)]; let refs: Vec<&[u8]> = attrs.iter().map(Vec::as_slice).collect(); let set = der::set_of(&refs); - let signature = key.sign(alg, &set)?; + let signature = sign(&set)?; let mut signed_attrs = set.clone(); signed_attrs[0] = tag::ctx(0); - let sid = der::seq(&[&cert.issuer.raw, &serial]); - let signer = der::seq(&[&der::int(1), &sid, &alg.algorithm(), &signed_attrs, &key.signature_algorithm(alg), &der::octets(&signature)]); - let mut certs: Vec<&[u8]> = vec![&cert.raw]; - certs.extend(chain.iter().filter(|c| c.raw != cert.raw).map(|c| c.raw.as_slice())); + let sid = der::seq(&[cert.issuer_der, &serial]); + let signer = der::seq(&[&der::int(1), &sid, &alg.algorithm(), &signed_attrs, signature_algorithm, &der::octets(&signature)]); + let mut certs: Vec<&[u8]> = vec![cert.der]; + certs.extend(chain.iter().copied().filter(|c| *c != cert.der)); let encap = match content { Some(c) => der::seq(&[&der::oid(content_type), &der::explicit(0, &der::octets(c))]), None => der::seq(&[&der::oid(content_type)]), @@ -477,10 +507,76 @@ fn build(input: SignedDataInput<'_>) -> Result, Error> { Ok(der::seq(&[&der::oid(SIGNED_DATA), &der::explicit(0, &signed_data)])) } +fn build(input: SignedDataInput<'_>) -> Result, Error> { + let SignedDataInput { key, cert, chain, alg, content_type, content, content_digest } = input; + let chain: Vec<&[u8]> = chain.iter().map(|c| c.raw.as_slice()).collect(); + sign_with( + SigningInput { + cert: SigningCertificate { der: &cert.raw, issuer_der: &cert.issuer.raw, serial: &cert.serial }, + chain: &chain, + alg, + content_type, + content, + content_digest, + signature_algorithm: &key.signature_algorithm(alg), + }, + |attrs| key.sign(alg, attrs), + ) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn callback_signer_matches_builtin_and_returns_provider_error_once() -> Result<(), Box> { + use crate::x509::Name; + let key = PrivateKey::generate_p256()?; + let name = Name::build("Callback signer", "", "", "", ""); + let from = Time { year: 2026, month: 1, day: 1, hour: 0, minute: 0, second: 0 }; + let cert = Certificate::self_signed(&name, &key, from, 1, &[1])?; + let alg = DigestAlg::Sha256; + let bytes = b"content"; + let digest = alg.digest(&[bytes]); + let algorithm = key.signature_algorithm(alg); + let chain = [cert.raw.as_slice()]; + for content in [None, Some(bytes.as_slice())] { + let input = SigningInput { + cert: SigningCertificate { der: &cert.raw, issuer_der: &cert.issuer.raw, serial: &cert.serial }, + chain: &chain, + alg, + content_type: DATA, + content, + content_digest: &digest, + signature_algorithm: &algorithm, + }; + let mut calls = 0; + let via_callback = sign_with(input, |attrs| { + calls += 1; + assert_eq!(Tlv::parse_all(attrs)?.tag, tag::SET); + key.sign(alg, attrs) + })?; + assert_eq!(calls, 1); + let builtin = match content { + Some(c) => sign_encapsulated(&key, &cert, std::slice::from_ref(&cert), alg, DATA, c)?, + None => sign_detached(&key, &cert, std::slice::from_ref(&cert), alg, &digest)?, + }; + assert_eq!(via_callback, builtin); + let parsed = SignedData::parse(&via_callback)?; + assert_eq!(parsed.certificates.len(), 1); + assert!(parsed.verify_signature(&cert, &digest)?); + assert_eq!(parsed.content.as_deref(), content); + let mut calls = 0; + let failed = sign_with(input, |_| { + calls += 1; + Err(42u32) + }); + assert_eq!(failed, Err(42)); + assert_eq!(calls, 1); + } + Ok(()) + } + #[test] fn strip_removes_multiple_leading_zero_bytes() { assert_eq!(strip(&[0, 0, 0, 0x42]), &[0x42]); From 472462df9f1cb7316a92d1be21cdbf90e0980300 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 20:36:13 -0500 Subject: [PATCH 072/144] craft-hdr: direct RGBA decoding and preallocation axis limits (#1961) --- crates/hdr/src/lib.rs | 40 ++++++++++++++++++++++++++++++++++------ crates/hdr/src/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/crates/hdr/src/lib.rs b/crates/hdr/src/lib.rs index d462323062..731737ce12 100644 --- a/crates/hdr/src/lib.rs +++ b/crates/hdr/src/lib.rs @@ -43,16 +43,19 @@ pub type Result = std::result::Result; #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[non_exhaustive] pub struct Limits { - /// Most pixels (width × height) a picture may have; each takes 12 bytes decoded. Default 2^26. + /// Most pixels (width × height) a picture may have; each takes 12 bytes as RGB or 16 as RGBA. Default 2^26. /// A picture over the target's largest allocation is refused at any setting. pub max_pixels: u64, /// Longest header read, in bytes (real ones are a few hundred). Default 64 KiB. pub max_header: usize, + /// Largest width or height, checked before allocating the validation scan line. + /// Defaults to `u32::MAX`, preserving the existing RGB decoder limit. + pub max_axis: u32, } impl Default for Limits { fn default() -> Self { - Self { max_pixels: 1 << 26, max_header: 64 << 10 } + Self { max_pixels: 1 << 26, max_header: 64 << 10, max_axis: u32::MAX } } } @@ -65,6 +68,15 @@ pub struct Picture { pub rgb: Vec, } +/// A decoded opaque RGBA picture, without an intermediate RGB allocation. +#[derive(Debug, Clone, PartialEq)] +pub struct RgbaPicture { + pub width: u32, + pub height: u32, + /// Scene-linear RGBA, top row first. Every alpha sample is 1.0. + pub rgba: Vec, +} + /// The largest allocation in bytes that a `Vec` or `String` can make on the target. const MAX_ALLOC_BYTES: u64 = isize::MAX as u64; @@ -187,6 +199,19 @@ pub fn decode(b: &[u8], limits: &Limits) -> Result { /// [`decode`] with `max_alloc_bytes` as the largest allocation the target allows. fn decode_within(b: &[u8], limits: &Limits, max_alloc_bytes: u64) -> Result { + let (width, height, rgb) = decode_channels::<3>(b, limits, max_alloc_bytes)?; + Ok(Picture { width, height, rgb }) +} + +/// Decodes directly to opaque linear float RGBA, with no intermediate RGB image. +/// The allocation limit includes all four channels; scan lines are validated first. +pub fn decode_rgba(b: &[u8], limits: &Limits) -> Result { + let (width, height, rgba) = decode_channels::<4>(b, limits, MAX_ALLOC_BYTES)?; + Ok(RgbaPicture { width, height, rgba }) +} + +// Only the RGB and RGBA entry points call this helper. +fn decode_channels(b: &[u8], limits: &Limits, max_alloc_bytes: u64) -> Result<(u32, u32, Vec)> { if !sniff(b) { return Err(Error::NotHdr); } @@ -235,13 +260,16 @@ fn decode_within(b: &[u8], limits: &Limits, max_alloc_bytes: u64) -> Result limits.max_axis || height > limits.max_axis { + return Err(Error::LimitExceeded("axis length")); + } let pixels = u64::from(width) * u64::from(height); if pixels > limits.max_pixels { return Err(Error::LimitExceeded("pixel count")); } // One scan line of RGBE pixels and the float picture, each within the target's largest allocation. let scan_len = alloc_len(u64::from(if x1 { height } else { width }), size_of::<[u8; 4]>(), max_alloc_bytes); - let rgb_len = pixels.checked_mul(3).and_then(|floats| alloc_len(floats, size_of::(), max_alloc_bytes)); + let rgb_len = pixels.checked_mul(CHANNELS as u64).and_then(|floats| alloc_len(floats, size_of::(), max_alloc_bytes)); let (Some(scan_len), Some(total)) = (scan_len, rgb_len) else { return Err(Error::LimitExceeded("pixel count")) }; // A scan line takes at least a few bits of file, so a header cannot ask for more than the data has. if (b.len().saturating_sub(pos) as u64).saturating_mul(4096) < pixels { @@ -255,7 +283,7 @@ fn decode_within(b: &[u8], limits: &Limits, max_alloc_bytes: u64) -> Result Result(bytes, &Limits::default(), 28).is_ok()); + assert_eq!(decode_channels::<4>(bytes, &Limits::default(), 28), Err(Error::LimitExceeded("pixel count"))); +} + +#[test] +fn axis_limit_precedes_pixel_data_and_scratch_allocation() { + let limits = Limits { max_axis: 32768, ..Limits::default() }; + for resolution in ["-Y 1 +X 32769", "-Y 32769 +X 1", "+X 1 -Y 32769"] { + let bytes = format!("#?RADIANCE\n\n{resolution}\n"); + assert_eq!(decode_rgba(bytes.as_bytes(), &limits), Err(Error::LimitExceeded("axis length"))); + assert_eq!(decode(bytes.as_bytes(), &limits), Err(Error::LimitExceeded("axis length"))); + } +} From 006ed3d965d5f3b77829b87a43eacd5ca0b4f997 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 20:46:05 -0500 Subject: [PATCH 073/144] svg: share bounded simple stylesheet parsing and matching (#1968) --- crates/svg/README.md | 15 ++ crates/svg/src/lib.rs | 3 + crates/svg/src/simple_css.rs | 346 +++++++++++++++++++++++++++++++++++ 3 files changed, 364 insertions(+) create mode 100644 crates/svg/README.md create mode 100644 crates/svg/src/simple_css.rs diff --git a/crates/svg/README.md b/crates/svg/README.md new file mode 100644 index 0000000000..a387e58c2c --- /dev/null +++ b/crates/svg/README.md @@ -0,0 +1,15 @@ + +### Simple stylesheet compatibility subset + +`simple_css` preserves EffectCraft's compound tag/class/id stylesheet grammar and indexed +matching budget, rather than substituting the richer selector semantics of `paths`. +Property values remain text; color precision, path-prefix behavior and geometry policy +stay with the importer. Call `parse` for each sheet, then `StyleSheet::index`; discard the +sheet after a parse error and reject the import when its matching-work callback refuses. + +The parser/matcher and structural tests were ported from EffectCraft +`60e2cbbbe3d73c0a9074c25a1a615ccfec18721c`, originally by FredApps. Nested at-rule skipping +and its regression test preserve NetterSilver's +`10e173c0e49696ad335e3da8a069889c089b09a6`; both contributors retain primary Git authorship +for their respective port commits. Source and destination use MIT OR Apache-2.0. +The shared adapter adds an aggregate 64 MiB stylesheet-text limit and idempotent indexing. diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 7cd36692ef..286bd36d55 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -30,3 +30,6 @@ pub mod svgz; #[cfg(feature = "tree")] pub mod tree; pub mod write; + +/// Compatibility CSS subset for simple SVG importers. +pub mod simple_css; diff --git a/crates/svg/src/simple_css.rs b/crates/svg/src/simple_css.rs new file mode 100644 index 0000000000..767b252577 --- /dev/null +++ b/crates/svg/src/simple_css.rs @@ -0,0 +1,346 @@ +//! Compatibility stylesheet subset for simple SVG importers, extracted from EffectCraft. +//! +//! Supports compound tag/class/id selectors and comma lists. Unsupported selectors/at-rules +//! are skipped; malformed trailing rules keep the accepted prefix. This deliberately is not +//! the richer `paths` cascade or a full CSS parser. Property values are retained as text, so +//! caller colour precision and geometry policy are unaffected. `!important` is stripped as in +//! the source importer; it does not change precedence here. +//! +//! Call `parse` for each style element, then `StyleSheet::index` before matching. Discard a +//! sheet after a parse error. Matching charges the caller's aggregate budget before applying +//! any declarations. The caller must stop using results when its budget callback refuses. +use std::collections::HashMap; + +/// Aggregate stylesheet byte bound before copying or allocating declaration strings. +pub const MAX_CSS_BYTES: usize = 64 * 1024 * 1024; + +/// A stylesheet exceeds its byte, selector or declaration limit. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(pub String); +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} +impl std::error::Error for Error {} + +/// The most selectors (each entry of a comma list counts) the `

x

"), &|_| None, true); } } + +/// Ensure container elements (such as `div` and `p`) with background colors do not leak +/// character shading onto their child text runs (#1786). +#[test] +fn container_background_color_does_not_leak_into_character_shading() { + let html = r#"
code
"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert!(!p.runs.is_empty(), "expected nonempty runs"); + assert_eq!(&p.text, "code"); + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(0x1e, 0x1e, 0x1e)), "container div background is preserved as paragraph shading"); + for r in &p.runs { + assert_eq!(r.props.shading, None, "character should have no shading from container div"); + } +} + +/// Verify that table background colors cascade down to cell shading through implicit or explicit +/// row groups (`tbody`, `thead`, `tfoot`), but do not leak into cell character shading. +#[test] +fn table_background_inherits_through_row_groups() { + let html = r#"
y
cell1
+
cell2
+
head
"#; + let doc = import(html); + let tables: Vec<_> = doc + .body + .iter() + .filter_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .collect(); + assert_eq!(tables.len(), 3); + for (t, want_hex) in tables.iter().zip(["e8f0fa", "d0e0f0", "c0d0e0"]) { + let cell = &t.rows[0].cells[0]; + assert_eq!( + cell.props.shading.map(|c| c.hex().to_ascii_lowercase()), + Some(want_hex.to_string()), + "cell should inherit shading from table or row group" + ); + let p = &cell.blocks[0]; + let craft_wordmodel::Block::Para(p) = &**p else { + panic!("expected table cell block to be a paragraph"); + }; + assert!(!p.runs.is_empty(), "expected nonempty runs"); + for r in &p.runs { + assert_eq!(r.props.shading, None, "cell text should have no character shading"); + } + } +} + +/// Verify that block-level container backgrounds (`p`, `pre`, `div`) are preserved as paragraph +/// shading on paragraphs rather than character shading on individual runs (#1786). +#[test] +fn block_element_backgrounds_preserve_paragraph_shading() { + let html = r#"

text

code

inner

"#; + let doc = import(html); + assert_eq!(doc.body.len(), 3); + let craft_wordmodel::Block::Para(p1) = &*doc.body[0] else { panic!("expected Para") }; + let craft_wordmodel::Block::Para(p2) = &*doc.body[1] else { panic!("expected Para") }; + let craft_wordmodel::Block::Para(p3) = &*doc.body[2] else { panic!("expected Para") }; + assert_eq!(p1.props.shading, Some(craft_wordmodel::Rgb(0x1e, 0x1e, 0x1e))); + assert_eq!(p2.props.shading, Some(craft_wordmodel::Rgb(0x2a, 0x2a, 0x2a))); + assert_eq!(p3.props.shading, Some(craft_wordmodel::Rgb(0x3a, 0x3a, 0x3a))); + assert_eq!(&p1.text, "text"); + assert_eq!(&p2.text, "code"); + assert_eq!(&p3.text, "inner"); + assert!(!p1.runs.is_empty()); + assert!(!p2.runs.is_empty()); + assert!(!p3.runs.is_empty()); + for r in &p1.runs { + assert_eq!(r.props.shading, None, "character should have no shading from paragraph background"); + } + for r in &p2.runs { + assert_eq!(r.props.shading, None, "character should have no shading from pre background"); + } + for r in &p3.runs { + assert_eq!(r.props.shading, None, "character should have no shading from container div background"); + } +} + +/// Verify that paragraph shading created by a container background survives an HTML round trip (#1786). +#[test] +fn paragraph_shading_survives_an_html_round_trip() { + let html = r#"

code

pre
"#; + let doc = import(html); + let out = export(&doc); + assert!(out.contains("background-color:#1E1E1E"), "paragraph shading is exported: {out}"); + assert!(out.contains("background-color:#2A2A2A"), "code block shading is exported: {out}"); + + let back = import(&out); + let craft_wordmodel::Block::Para(p1) = &*back.body[0] else { panic!("expected Para") }; + let craft_wordmodel::Block::Para(p2) = &*back.body[1] else { panic!("expected Para") }; + assert_eq!(p1.props.shading, Some(craft_wordmodel::Rgb(0x1e, 0x1e, 0x1e))); + assert_eq!(p2.props.shading, Some(craft_wordmodel::Rgb(0x2a, 0x2a, 0x2a))); +} + +/// Verify that paragraph shading inside a single-paragraph table cell survives an HTML round trip (#1786). +#[test] +fn table_cell_paragraph_shading_survives_an_html_round_trip() { + let html = r#"

text

"#; + let doc = import(html); + let out = export(&doc); + assert!(out.contains("background-color:#123456"), "paragraph shading is exported: {out}"); + + let back = import(&out); + let table = back + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .expect("expected table"); + let cell = &table.rows[0].cells[0]; + assert_eq!(cell.props.shading, None, "paragraph shading must not become cell shading"); + let craft_wordmodel::Block::Para(p) = &*cell.blocks[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); +} + +/// Verify that consecutive code paragraphs with different backgrounds export their own `
`.
+#[test]
+fn consecutive_code_blocks_keep_their_own_shading() {
+    let html = r#"
a
b
"#; + let out = export(&import(html)); + assert!(out.contains("
a
"), "{out}"); + assert!(out.contains("
b
"), "{out}"); +} + +/// Verify that paragraph shading inherited from a paragraph style is exported (#1786). +#[test] +fn paragraph_shading_from_a_style_survives_html_export() { + let mut doc = Document::new(); + std::sync::Arc::make_mut(&mut doc.styles).styles.push(craft_wordmodel::Style { + id: "Shaded".into(), + name: "Shaded".into(), + para: craft_wordmodel::props::ParaProps { shading: Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56)), ..Default::default() }, + ..Default::default() + }); + let mut p = craft_wordmodel::Paragraph::with_text("text", craft_wordmodel::CharProps::default()); + p.props.style = Some("Shaded".into()); + doc.body = vec![craft_wordmodel::para_block(p)]; + + let out = export(&doc); + assert!(out.contains("background-color:#123456"), "style shading is exported: {out}"); +} + +/// A closing parenthesis without an opening one invalidates the declaration (#1786). +#[test] +fn background_shorthand_unbalanced_closing_paren_is_ignored() { + let html = r#"text"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0xff, 0x00, 0x00)), "invalid shorthand must not clear inherited shading"); +} + +/// A shaded paragraph keeps its shading on both sides of an internal page break (#1786). +#[test] +fn paragraph_shading_survives_an_internal_page_break() { + let mut p = craft_wordmodel::Paragraph::with_text("before\u{000C}after", craft_wordmodel::CharProps::default()); + p.props.shading = Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56)); + let mut doc = Document::new(); + doc.body = vec![craft_wordmodel::para_block(p)]; + let out = export(&doc); + assert_eq!(out.matches("background-color:#123456").count(), 2, "{out}"); +} + +/// Verify that CSS-escaped quote characters in background shorthand URLs remain part of the URL +/// content and do not cause the shorthand declaration to be rejected. +#[test] +fn background_shorthand_escaped_quotes_in_url() { + let doc = import(r#"

text

"#); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(&p.text, "text"); + assert!(!p.runs.is_empty()); + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); +} + +/// Verify that valid multi-token CSS background shorthands without a color (such as `none repeat`) +/// reset character shading, while invalid declarations are ignored. +#[test] +fn background_shorthand_without_color_resets_background() { + let html = r#"plain"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, None); + + let html_invalid = r#"shaded"#; + let doc_invalid = import(html_invalid); + let p_invalid = match &*doc_invalid.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_invalid.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); +} + +/// Verify that CSS `background: inherit` keeps inherited character shading instead of removing it (#1786). +#[test] +fn background_inherit_retains_inline_shading() { + let html = r#"shaded"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0)), "background: inherit should retain inherited character shading"); + + // Also verify background-color: inherit retains shading. + let html_color = r#"shaded"#; + let doc_color = import(html_color); + let p_color = match &*doc_color.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!( + p_color.runs[0].props.shading, + Some(craft_wordmodel::Rgb(255, 0, 0)), + "background-color: inherit should retain inherited character shading" + ); + + // CSS-wide keyword inherit mixed with other values is invalid and ignored. + let html_mixed = r#"green"#; + let doc_mixed = import(html_mixed); + let p_mixed = match &*doc_mixed.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!( + p_mixed.runs[0].props.shading, + Some(craft_wordmodel::Rgb(0, 255, 0)), + "invalid shorthand mixing inherit with values should be ignored" + ); +} + +/// Verify that hostile background declarations with deeply nested slashes do not cause stack overflow (#1786). +#[test] +fn hostile_background_slashes_never_stack_overflow() { + let slashes = "/".repeat(20_000); + let html = format!(r#"hostile"#); + let doc = import(&html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, None); +} + +/// Verify that non-breaking space (U+00A0) is not treated as CSS whitespace when splitting tokens (#1786). +#[test] +fn background_whitespace_preserves_nbsp() { + let html = "shaded"; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!( + p.runs[0].props.shading, + Some(craft_wordmodel::Rgb(255, 0, 0)), + "non-breaking space is not CSS whitespace and should not clear shading" + ); +} + +/// Verify that background shorthands exceeding the token limit are rejected and unapplied (#1786). +#[test] +fn background_shorthand_truncated_rejects_unapplied() { + let mut layers = String::new(); + for i in 0..64 { + layers.push_str(&format!("url(img{i}.png), ")); + } + layers.push_str("#00ff00"); + let html = format!(r#"retained"#); + let doc = import(&html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!( + p.runs[0].props.shading, + Some(craft_wordmodel::Rgb(255, 0, 0)), + "truncated shorthand should be rejected and leave inherited background untouched" + ); +} + +/// Verify that shorthands with image-set or calc functions parse and preserve colors (#1786). +#[test] +fn background_shorthand_valid_functions_preserve_color() { + let html_image_set = r#"image-set"#; + let doc = import(html_image_set); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); + + let html_calc = r#"calc"#; + let doc_calc = import(html_calc); + let p_calc = match &*doc_calc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_calc.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); +} + +/// Verify that multi-layer background shorthands validate slashes per layer and preserve final-layer color (#1786). +#[test] +fn background_shorthand_multi_layer_slashes_apply_color() { + let html = r#"multi-layer"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); + + // Color in a non-final layer is invalid CSS and must be ignored. + let html_invalid_color = r#"invalid"#; + let doc_invalid_color = import(html_invalid_color); + let p_invalid_color = match &*doc_invalid_color.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_invalid_color.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + // Multiple slashes in a single layer makes the declaration invalid. + let html_multi_slash = + r#"invalid"#; + let doc_multi_slash = import(html_multi_slash); + let p_multi_slash = match &*doc_multi_slash.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_multi_slash.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); +} + +/// Verify that background shorthands with empty layers (leading, trailing, or double commas) are rejected (#1786). +#[test] +fn background_shorthand_rejects_empty_layers() { + // Leading comma + let html_leading = r#"leading"#; + let doc_leading = import(html_leading); + let p_leading = match &*doc_leading.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_leading.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + // Trailing comma + let html_trailing = r#"trailing"#; + let doc_trailing = import(html_trailing); + let p_trailing = match &*doc_trailing.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_trailing.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + // Double comma + let html_double = r#"double"#; + let doc_double = import(html_double); + let p_double = match &*doc_double.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_double.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); +} + +/// Verify that zero-alpha colors in background shorthands or declarations remain transparent (#1786). +#[test] +fn background_zero_alpha_colors_are_transparent() { + for decl in ["rgb(0 0 0 / 0)", "rgba(0, 0, 0, 0)", "#0000", "#00000000", "#ffffff00", "hsla(120, 100%, 50%, 0)", "hsl(120 100% 50% / 0)"] { + let html = format!(r#"transparent"#); + let doc = import(&html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, None, "zero-alpha color `{decl}` must clear background rather than composite over white"); + } +} + +/// Verify that ancestor table shading is preserved beneath transparent table layers (#1786). +#[test] +fn transparent_table_layers_preserve_ancestor_table_shading() { + let html = r#" + + + + + + +
transparent_layersexplicit_cell
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!( + table.rows[0].cells[0].props.shading, + Some(craft_wordmodel::Rgb(0xe8, 0xf0, 0xfa)), + "table background must show through transparent tbody, tr, and td" + ); + assert_eq!( + table.rows[0].cells[1].props.shading, + Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56)), + "cell with explicit background must override table background" + ); +} + +/// Verify that block-level container background is available to immediate inline children using explicit `inherit` (#1786). +#[test] +fn block_background_explicit_inherit() { + // When the immediate parent

has no background, an inline span inheriting background gets transparent (None): + let html_indirect = r#"

text

"#; + let doc_indirect = import(html_indirect); + let p_indirect = match &*doc_indirect.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_indirect.runs[0].props.shading, None); + + // When the span is an immediate child of the styled div, it inherits the div's computed background: + let html_direct = r#"
text
"#; + let doc_direct = import(html_direct); + let p_direct = match &*doc_direct.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_direct.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + let html_shorthand = r#"
text
"#; + let doc_shorthand = import(html_shorthand); + let p_shorthand = match &*doc_shorthand.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_shorthand.runs[0].props.shading, Some(craft_wordmodel::Rgb(0, 255, 0))); +} + +/// Verify that CSS-escaped quotes inside background URLs do not close the quote or drop declaration colors (#1786). +#[test] +fn background_escaped_quote_url() { + let html = r#"text"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); + + let html_single = r#"text"#; + let doc_single = import(html_single); + let p_single = match &*doc_single.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_single.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x65, 0x43, 0x21))); +} + +/// Verify that invalid hex color declarations like `#ggg0` do not clear inherited shading (#1786). +#[test] +fn background_invalid_hex_retains_shading() { + let html = r#"text"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); +} + +/// Verify that background size keywords (`cover`, `contain`) without preceding position and slash are invalid and retain shading (#1786). +#[test] +fn background_cover_without_slash_invalid() { + let html_cover = r#"text"#; + let doc_cover = import(html_cover); + let p_cover = match &*doc_cover.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_cover.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + let html_contain = r#"text"#; + let doc_contain = import(html_contain); + let p_contain = match &*doc_contain.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_contain.runs[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + let html_valid = r#"text"#; + let doc_valid = import(html_valid); + let p_valid = match &*doc_valid.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p_valid.runs[0].props.shading, None); +} + +/// Verify that table backgrounds declared on thead or tbody are applied to cells (#1786). +#[test] +fn table_row_group_background_inheritance() { + let html = r#" + + + + + + +
head
body
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(0, 255, 0))); + assert_eq!(table.rows[1].cells[0].props.shading, Some(craft_wordmodel::Rgb(0, 0, 255))); +} + +/// Verify that background shorthand with slashes inside URL functions correctly identifies the position/size slash (#1786). +#[test] +fn background_url_with_slashes_and_position_size() { + let html = r#"text"#; + let doc = import(html); + let p = match &*doc.body[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); +} + +/// Verify that a table inside an inline element with background shading does not turn character shading into table/cell background (#1786). +#[test] +fn table_inside_inline_element_does_not_inherit_character_shading() { + let html = r#"
cell
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows[0].cells[0].props.shading, None); +} + +/// Verify that a child with `background: inherit` inside an unstyled cell in a shaded table does not inherit the table fallback (#1786). +#[test] +fn cell_inherit_uses_cell_background_not_table_fallback() { + let html = r#"
text
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + let p = match &*table.rows[0].cells[0].blocks[0] { + craft_wordmodel::Block::Para(p) => p, + _ => panic!("expected paragraph"), + }; + assert_eq!(p.runs[0].props.shading, None); +} + +/// Verify that CSS `background: transparent` overrides HTML `bgcolor` presentational attribute (#1786). +#[test] +fn bgcolor_overridden_by_css_transparent() { + let html = r##"
cell
"##; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows[0].cells[0].props.shading, None); +} + +/// Verify that nested container shading is preserved when merging list continuation paragraphs (#1786). +#[test] +fn list_continuation_preserves_nested_container_shading() { + let html = r#"
  • before
    inside
    after
"#; + let flow = parse(html); + assert_eq!(flow.blocks.len(), 1); + let FBlock::Para(p) = &flow.blocks[0] else { panic!("expected Para") }; + assert!(p.list.is_some(), "expected list item"); + let dark = Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11)); + let inside = p + .inlines + .iter() + .find_map(|i| match i { + Inline::Text(t, fmt) if t.contains("inside") => Some(fmt.background), + _ => None, + }) + .expect("inside text inline"); + assert_eq!(inside, dark, "nested container shading should be preserved on merged run"); + + let doc = import(html); + let craft_wordmodel::Block::Para(p_doc) = &*doc.body[0] else { panic!("expected Para") }; + let mut offset = 0usize; + let mut inside_shading = None; + for r in &p_doc.runs { + let text_slice = &p_doc.text[offset..offset + r.len]; + if text_slice.contains("inside") { + inside_shading = Some(r.props.shading); + } else if text_slice.contains("before") || text_slice.contains("after") { + assert_eq!(r.props.shading, None); + } + offset += r.len; + } + assert_eq!(inside_shading, Some(dark)); +} + +/// Verify that starting a new row group implicitly closes any preceding sibling row group so +/// cell shading is not inherited from an omitted-end-tag preceding group (#1786). +#[test] +fn consecutive_row_groups_with_omitted_end_tag_do_not_leak_shading() { + let html = r#"
a
b
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows.len(), 2); + assert_eq!(table.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + assert_eq!(table.rows[1].cells[0].props.shading, None, "second cell should not inherit shading from closed tbody"); +} + +/// Verify that a list item with a shaded container followed by unshaded text preserves separate +/// background regions so the trailing text does not inherit the container's background (#1786). +#[test] +fn shaded_container_first_in_list_item_preserves_unshaded_trailing_text() { + let html = r#"
  • inside
    after
"#; + let doc = import(html); + assert_eq!(doc.body.len(), 1); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, None, "list paragraph as a whole should have no background when regions differ"); + let dark = Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11)); + let mut offset = 0usize; + let mut inside_shading = None; + let mut after_shading = None; + for r in &p.runs { + let text_slice = &p.text[offset..offset + r.len]; + if text_slice.contains("inside") { + inside_shading = Some(r.props.shading); + } else if text_slice.contains("after") { + after_shading = Some(r.props.shading); + } + offset += r.len; + } + assert_eq!(inside_shading, Some(dark)); + assert_eq!(after_shading, Some(None), "trailing text should have no shading"); +} + +/// Verify that container backgrounds behind tables are preserved on table cells (#1786). +#[test] +fn container_background_behind_table_preserved_on_cells() { + let html = r#"
text
"#; + let doc = import(html); + let table = doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(table.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11))); + + // Nested table inside an unshaded cell stops at the cell boundary: + let nested_html = r#"
nested
"#; + let nested_doc = import(nested_html); + let outer_table = nested_doc + .body + .iter() + .find_map(|b| match &**b { + craft_wordmodel::Block::Table(t) => Some(t), + _ => None, + }) + .unwrap(); + assert_eq!(outer_table.rows[0].cells[0].props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11))); + let inner_table = match &*outer_table.rows[0].cells[0].blocks[0] { + craft_wordmodel::Block::Table(t) => t, + _ => panic!("expected nested Table"), + }; + assert_eq!(inner_table.rows[0].cells[0].props.shading, None, "nested table in unshaded cell must stop at cell boundary"); +} + +/// Verify that page imports preserve root (body/html) backgrounds while pasted fragments do not (#1786). +#[test] +fn root_background_preserved_on_page_import_only() { + let html = r#"

text

"#; + let page_doc = import_page(html, &|_| None); + let craft_wordmodel::Block::Para(p_page) = &*page_doc.body[0] else { panic!("expected Para") }; + assert_eq!(p_page.props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11)), "page import must preserve body background on paragraphs"); + assert_eq!( + p_page.runs[0].props.color, + Some(craft_wordmodel::TextColor::Rgb(craft_wordmodel::Rgb(0xff, 0xff, 0xff))), + "page import keeps the root foreground with its background" + ); + + let frag_doc = import(html); + let craft_wordmodel::Block::Para(p_frag) = &*frag_doc.body[0] else { panic!("expected Para") }; + assert_eq!(p_frag.props.shading, None, "fragment paste must not turn body background into paragraph shading"); + assert_eq!(p_frag.runs[0].props.color, None, "fragment paste drops the root foreground with its background"); +} + +/// Verify that an inline child with `background: inherit` does not receive character shading from a pasted body background (#1786). +#[test] +fn pasted_body_background_not_inherited_by_inline_child() { + let html = r#"text"#; + let frag_doc = import(html); + let craft_wordmodel::Block::Para(p_frag) = &*frag_doc.body[0] else { panic!("expected Para") }; + assert_eq!(p_frag.runs[0].props.shading, None, "inline child in pasted fragment must not inherit character shading from body background"); + + let page_doc = import_page(html, &|_| None); + let craft_wordmodel::Block::Para(p_page) = &*page_doc.body[0] else { panic!("expected Para") }; + assert_eq!( + p_page.runs[0].props.shading, + Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11)), + "inline child in page import inherits body background via inherit" + ); +} + +#[test] +fn root_background_on_html_and_foreground_on_body() { + let html = r#"

text

"#; + let frag_doc = import(html); + let craft_wordmodel::Block::Para(p_frag) = &*frag_doc.body[0] else { panic!("expected Para") }; + assert_eq!(p_frag.props.shading, None, "fragment paste drops html background"); + assert_eq!(p_frag.runs[0].props.color, None, "fragment paste drops body foreground when html supplied suppressed background"); + + let page_doc = import_page(html, &|_| None); + let craft_wordmodel::Block::Para(p_page) = &*page_doc.body[0] else { panic!("expected Para") }; + assert_eq!(p_page.props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11))); + assert_eq!(p_page.runs[0].props.color, Some(craft_wordmodel::TextColor::Rgb(craft_wordmodel::Rgb(0xff, 0xff, 0xff)))); +} + +#[test] +fn background_unitless_zero_lengths() { + let html = r#"

text

"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(0x12, 0x34, 0x56))); + + let html2 = r#"

text

"#; + let doc2 = import(html2); + let craft_wordmodel::Block::Para(p2) = &*doc2.body[0] else { panic!("expected Para") }; + assert_eq!(p2.props.shading, Some(craft_wordmodel::Rgb(0x65, 0x43, 0x21))); +} + +#[test] +fn background_comments_skipped_outside_strings() { + let html = r#"

text

"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11))); + + let html2 = r#"

text

"#; + let doc2 = import(html2); + let craft_wordmodel::Block::Para(p2) = &*doc2.body[0] else { panic!("expected Para") }; + assert_eq!(p2.props.shading, Some(craft_wordmodel::Rgb(0x22, 0x22, 0x22))); +} + +#[test] +fn invalid_color_does_not_clear_preceding_background() { + let html = r#"

text

"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); + + let html2 = r#"

text

"#; + let doc2 = import(html2); + let craft_wordmodel::Block::Para(p2) = &*doc2.body[0] else { panic!("expected Para") }; + assert_eq!(p2.props.shading, Some(craft_wordmodel::Rgb(255, 0, 0))); +} + +#[test] +fn code_block_export_preserves_foreground_color() { + let html = r#"
const x = 1;
"#; + let doc = import_page(html, &|_| None); + let exported = export(&doc); + assert!(exported.contains("style=\"background-color:#000000\""), "exported pre must keep background: {}", exported); + assert!(exported.contains("color:#FFFFFF"), "exported code inlines must keep foreground: {}", exported); + assert!(exported.contains("const x = 1;"), "exported code text preserved: {}", exported); +} + +#[test] +fn background_comments_inside_functions() { + let html = r#"

text

"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, Some(craft_wordmodel::Rgb(0x11, 0x11, 0x11))); + assert_eq!(p.runs[0].props.color, Some(craft_wordmodel::TextColor::Rgb(craft_wordmodel::Rgb(0xff, 0xff, 0xff)))); +} + +#[test] +fn zero_alpha_colors_with_none_channels() { + let html = r#"

text

"#; + let doc = import(html); + let craft_wordmodel::Block::Para(p) = &*doc.body[0] else { panic!("expected Para") }; + assert_eq!(p.props.shading, None); + + let html2 = r#"

text

"#; + let doc2 = import(html2); + let craft_wordmodel::Block::Para(p2) = &*doc2.body[0] else { panic!("expected Para") }; + assert_eq!(p2.props.shading, None); +} From cfad8f0bcca6900ddd88361220fb5ed432ce817e Mon Sep 17 00:00:00 2001 From: el-j Date: Tue, 17 Nov 2026 03:30:57 +0100 Subject: [PATCH 101/144] craft-captions: PJS, RealText and JACOsub subtitle formats (#1557) (#1788) --- crates/captions/src/jacosub.rs | 242 +++++++++++++++++ crates/captions/src/lib.rs | 50 +++- crates/captions/src/pjs.rs | 102 ++++++++ crates/captions/src/realtext.rs | 247 ++++++++++++++++++ crates/captions/src/text.rs | 46 ++++ crates/captions/tests/it/main.rs | 1 + .../captions/tests/it/pjs_realtext_jacosub.rs | 174 ++++++++++++ 7 files changed, 860 insertions(+), 2 deletions(-) create mode 100644 crates/captions/src/jacosub.rs create mode 100644 crates/captions/src/pjs.rs create mode 100644 crates/captions/src/realtext.rs create mode 100644 crates/captions/tests/it/pjs_realtext_jacosub.rs diff --git a/crates/captions/src/jacosub.rs b/crates/captions/src/jacosub.rs new file mode 100644 index 0000000000..30233b6f1d --- /dev/null +++ b/crates/captions/src/jacosub.rs @@ -0,0 +1,242 @@ +//! JACOsub (`.jss`, `.js`): multi-feature scriptable subtitle format. +//! +//! ```text +//! # JACOsub file +//! #TimeRes 100 +//! 0:00:01.00 0:00:03.00 D0 First line\nsecond line +//! ``` +//! +//! Lines beginning with `#` are comments or header directives. Timed caption lines begin with +//! `START STOP [DIRECTIVE] Text`, where timestamps are `H:MM:SS.FF` (or `@units`) relative to +//! the declared `#TimeRes` (default 30). Inside the text, `\n` represents a newline. + +use crate::text::{escape_markup, ms_to_tick, plain_text, tick_to_ms}; +use crate::{Cue, Document, Error, Result}; + +/// Parse a JACOsub timestamp `H:MM:SS.FF` or `@units` into milliseconds. +pub(crate) fn parse_time(s: &str, time_res: i64) -> Option { + let s = s.trim(); + if s.is_empty() { + return None; + } + + if let Some(units_str) = s.strip_prefix('@') { + let units: i64 = units_str.trim().parse().ok()?; + let time_res = if time_res > 0 { time_res } else { 30 }; + return Some(units.saturating_mul(1000) / time_res); + } + + let (h_str, rest) = s.split_once(':')?; + let (m_str, rest) = rest.split_once(':')?; + let (s_str, f_str) = rest.split_once('.')?; + + let h: i64 = h_str.trim().parse().ok()?; + let m: i64 = m_str.trim().parse().ok()?; + let sec: i64 = s_str.trim().parse().ok()?; + let frac: i64 = f_str.trim().parse().ok()?; + + let time_res = if time_res > 0 { time_res } else { 30 }; + let frac_ms = frac.saturating_mul(1000) / time_res; + + let total_secs = h.saturating_mul(3600).saturating_add(m.saturating_mul(60)).saturating_add(sec); + Some(total_secs.saturating_mul(1000).saturating_add(frac_ms)) +} + +/// Format milliseconds into JACOsub timestamp string `H:MM:SS.cc` (at 100 centiseconds/sec). +pub(crate) fn format_time(ms: i64) -> String { + let ms = ms.max(0); + let total_secs = ms / 1000; + let centis = (ms % 1000) / 10; + let hours = total_secs / 3600; + let mins = (total_secs % 3600) / 60; + let secs = total_secs % 60; + + format!("{hours}:{mins:02}:{secs:02}.{centis:02}") +} + +/// Check if a line is a JACOsub timed caption line: `H:MM:SS.FF H:MM:SS.FF ...` or `@units @units ...`. +pub(crate) fn is_timed_line(line: &str) -> bool { + let line = line.trim(); + if line.starts_with('#') { + return false; + } + let mut parts = line.split_whitespace(); + let Some(t0) = parts.next() else { return false }; + let Some(t1) = parts.next() else { return false }; + (t0.contains(':') && t0.contains('.') && t1.contains(':') && t1.contains('.')) || (t0.starts_with('@') && t1.starts_with('@')) +} + +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut time_res: i64 = 30; // standard default + let mut shift_ms: i64 = 0; + let mut found = false; + + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + + if let Some(cmd) = line.strip_prefix('#') { + let cmd_lower = cmd.to_ascii_lowercase(); + if cmd_lower.starts_with("timeres") || cmd_lower.starts_with('t') { + let parts: Vec<&str> = cmd.split_whitespace().collect(); + if parts.len() >= 2 + && let Ok(res) = parts[1].parse::() + && res > 0 + { + time_res = res; + } + } else if cmd_lower.starts_with("shift") || cmd_lower.starts_with('s') { + let parts: Vec<&str> = cmd.split_whitespace().collect(); + if parts.len() >= 2 { + let s_val = parts[1].trim(); + let (neg, s_raw) = if let Some(stripped) = s_val.strip_prefix('-') { + (true, stripped) + } else if let Some(stripped) = s_val.strip_prefix('+') { + (false, stripped) + } else { + (false, s_val) + }; + if let Some(ms) = parse_time(s_raw, time_res) { + shift_ms = if neg { -ms } else { ms }; + } + } + } + continue; + } + + if !is_timed_line(line) { + continue; + } + + let mut parts = line.split_whitespace(); + let Some(start_str) = parts.next() else { continue }; + let Some(end_str) = parts.next() else { continue }; + + let start_ms = match parse_time(start_str, time_res) { + Some(ms) => ms.saturating_add(shift_ms).max(0), + None => { + doc.warnings.push(format!("line {}: invalid start timestamp, skipped", n + 1)); + continue; + } + }; + let end_ms = match parse_time(end_str, time_res) { + Some(ms) => ms.saturating_add(shift_ms).max(0), + None => { + doc.warnings.push(format!("line {}: invalid end timestamp, skipped", n + 1)); + continue; + } + }; + + found = true; + + // Skip to after the end timestamp in the original line to preserve exact spaces + let after_end_pos = match line.find(end_str) { + Some(idx) => idx + end_str.len(), + None => continue, + }; + let remainder = &line[after_end_pos..]; + let trimmed_rem = remainder.trim_start(); + + // Check if there is a directive prefix: either [Directive] or a single non-space word starting with D + let text_part = if let Some(stripped) = trimmed_rem.strip_prefix('[') { + match stripped.find(']') { + Some(end_bracket) => stripped[end_bracket + 1..].trim_start(), + None => trimmed_rem, + } + } else if let Some(space_idx) = trimmed_rem.find(' ') { + let first_token = &trimmed_rem[..space_idx]; + if first_token.starts_with('D') && first_token[1..].chars().all(|c| c.is_ascii_digit()) { + trimmed_rem[space_idx + 1..].trim_start() + } else { + trimmed_rem + } + } else { + trimmed_rem + }; + + // Text parsing: `\n` represents newline + let raw_lines: Vec<&str> = text_part.split(r"\n").map(str::trim).filter(|l| !l.is_empty()).collect(); + let lines: Vec = raw_lines.into_iter().map(escape_markup).collect(); + + let start = ms_to_tick(start_ms); + let end = ms_to_tick(end_ms); + if end <= start || lines.is_empty() { + doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1)); + continue; + } + + doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() }); + } + + if !found && !text.trim().is_empty() { + return Err(Error::NotFormat("JACOsub")); + } + + Ok(doc) +} + +pub fn write(doc: &Document) -> String { + let mut out = String::new(); + out.push_str("# JACOsub file\n"); + out.push_str("#TimeRes 100\n\n"); + + for c in &doc.cues { + let start_ms = tick_to_ms(c.start); + let end_ms = tick_to_ms(c.end).max(start_ms + 10); + let raw_lines = plain_text(&c.text); + let lines: Vec<&str> = raw_lines.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); + + if !lines.is_empty() { + let text = lines.join(r"\n"); + out.push_str(&format!("{} {} D0 {}\n", format_time(start_ms), format_time(end_ms), text)); + } + } + + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_write_roundtrip() { + let jss = "# JACOsub file\n#TimeRes 100\n\n0:00:01.00 0:00:03.00 D0 First line\\nsecond line\n0:00:04.50 0:00:06.00 D0 Second cue\n"; + let doc = parse(jss).expect("parse"); + assert_eq!(doc.cues.len(), 2); + assert_eq!(doc.cues[0].start, ms_to_tick(1000)); + assert_eq!(doc.cues[0].end, ms_to_tick(3000)); + assert_eq!(doc.cues[0].text, "First line\nsecond line"); + assert_eq!(doc.cues[1].start, ms_to_tick(4500)); + assert_eq!(doc.cues[1].end, ms_to_tick(6000)); + assert_eq!(doc.cues[1].text, "Second cue"); + + let written = write(&doc); + assert_eq!(written, jss); + } + + #[test] + fn parse_bracketed_directive() { + let jss = "#TimeRes 100\n0:00:01.00 0:00:03.00 [Style1] Bracketed style text\n"; + let doc = parse(jss).expect("parse"); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].text, "Bracketed style text"); + } + + #[test] + fn negative_shift_under_one_hour() { + let jss = "#TimeRes 100\n#Shift -0:00:01.00\n0:00:02.00 0:00:04.00 D0 Shifted line\n"; + let doc = parse(jss).expect("parse"); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].start, ms_to_tick(1000)); + assert_eq!(doc.cues[0].end, ms_to_tick(3000)); + } + + #[test] + fn rejects_non_jacosub() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nHello\n").is_err()); + } +} diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index e8a4927229..ca99dba439 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -34,7 +34,10 @@ struct ReadmeExamples; pub mod ass; pub mod cea608; +pub mod jacosub; pub mod mcc; +pub mod pjs; +pub mod realtext; pub mod scc; pub mod srt; pub mod stl; @@ -72,10 +75,28 @@ pub enum Format { Dfxp, /// Advanced SubStation Alpha (also reads SubStation Alpha). Ass, + /// Phoenix Japanimation Society (PJS) subtitles. + Pjs, + /// RealText streaming timed text markup. + RealText, + /// JACOsub scriptable subtitles. + JacoSub, } impl Format { - pub const ALL: [Format; 8] = [Format::Srt, Format::WebVtt, Format::Scc, Format::Mcc, Format::Stl, Format::Ttml, Format::Dfxp, Format::Ass]; + pub const ALL: [Format; 11] = [ + Format::Srt, + Format::WebVtt, + Format::Scc, + Format::Mcc, + Format::Stl, + Format::Ttml, + Format::Dfxp, + Format::Ass, + Format::Pjs, + Format::RealText, + Format::JacoSub, + ]; pub fn name(self) -> &'static str { match self { Format::Srt => "SubRip (SRT)", @@ -86,6 +107,9 @@ impl Format { Format::Ttml => "TTML (IMSC1)", Format::Dfxp => "DFXP (TTML1)", Format::Ass => "Advanced SubStation Alpha (ASS)", + Format::Pjs => "PJS", + Format::RealText => "RealText", + Format::JacoSub => "JACOsub", } } pub fn extension(self) -> &'static str { @@ -98,6 +122,9 @@ impl Format { Format::Ttml => "ttml", Format::Dfxp => "dfxp", Format::Ass => "ass", + Format::Pjs => "pjs", + Format::RealText => "rt", + Format::JacoSub => "jss", } } pub fn from_name(s: &str) -> Option { @@ -110,6 +137,9 @@ impl Format { "ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml), "dfxp" => Some(Format::Dfxp), "ass" | "ssa" => Some(Format::Ass), + "pjs" => Some(Format::Pjs), + "rt" | "realtext" => Some(Format::RealText), + "jss" | "js" | "jacosub" => Some(Format::JacoSub), _ => None, } } @@ -260,6 +290,16 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if head.starts_with("[Script Info]") { return Some(Format::Ass); } + if realtext::is_realtext(head) { + return Some(Format::RealText); + } + let first_lines: Vec<&str> = head.lines().map(str::trim).filter(|l| !l.is_empty()).take(3).collect(); + if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) { + return Some(Format::Pjs); + } + if first_lines.iter().any(|l| jacosub::is_timed_line(l)) || (head.starts_with('#') && (head.contains("TimeRes") || head.contains("#T"))) { + return Some(Format::JacoSub); + } let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase()); if (head.starts_with('<') && (head.contains("") || head.contains(":tt "))) && (head.contains("ns/ttml") || head.contains("ttaf1")) @@ -271,7 +311,7 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { match ext.as_deref() { Some("srt") if has_arrow_timing || head.is_empty() => Some(Format::Srt), Some("vtt") if has_arrow_timing => Some(Format::WebVtt), - Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa") => None, + Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "pjs" | "rt" | "jss" | "js") => None, _ if has_arrow_timing => Some(Format::Srt), _ => None, } @@ -306,6 +346,9 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result { Format::Mcc => mcc::parse(&text), Format::Ttml | Format::Dfxp => ttml::parse(&text), Format::Ass => ass::parse(&text), + Format::Pjs => pjs::parse(&text), + Format::RealText => realtext::parse(&text), + Format::JacoSub => jacosub::parse(&text), Format::Stl => stl::parse(bytes), } } @@ -344,6 +387,9 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec { Format::Ttml => ttml::write(doc, ttml::Flavor::Imsc1, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), Format::Dfxp => ttml::write(doc, ttml::Flavor::Dfxp, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), Format::Ass => ass::write(doc).into_bytes(), + Format::Pjs => pjs::write(doc).into_bytes(), + Format::RealText => realtext::write(doc).into_bytes(), + Format::JacoSub => jacosub::write(doc).into_bytes(), } } diff --git a/crates/captions/src/pjs.rs b/crates/captions/src/pjs.rs new file mode 100644 index 0000000000..91874941b3 --- /dev/null +++ b/crates/captions/src/pjs.rs @@ -0,0 +1,102 @@ +//! Phoenix Japanimation Society (PJS) subtitles (`.pjs`): times in tenths of a second. +//! +//! ```text +//! 10,50,"First line" +//! 60,120,"Second line|with break" +//! ``` +//! +//! Lines are comma-separated `start,end,"text"` with times in deciseconds (tenths of a second). +//! Inside the quotes, `|` breaks a line. + +use crate::text::{escape_markup, ms_to_tick, number, plain_lines, tick_to_ms}; +use crate::{Cue, Document, Error, Result}; + +/// `start,end,"text"` as its parts. +pub(crate) fn split_cue(line: &str) -> Option<(i64, i64, &str)> { + let (start_str, rest) = line.split_once(',')?; + let (end_str, text_str) = rest.split_once(',')?; + let start = number(start_str.trim())?; + let end = number(end_str.trim())?; + let text = text_str.trim(); + let text = if let Some(stripped) = text.strip_prefix('"').and_then(|t| t.strip_suffix('"')) { stripped } else { text }; + Some((start, end, text)) +} + +/// Parse a PJS subtitle document. +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut found = false; + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let Some((start_ds, end_ds, raw)) = split_cue(line) else { + doc.warnings.push(format!("line {}: not a PJS cue, skipped", n + 1)); + continue; + }; + found = true; + let mut lines = Vec::new(); + for l in raw.split('|') { + let trimmed = l.trim(); + if !trimmed.is_empty() { + let unquoted = trimmed.replace("\"\"", "\""); + lines.push(escape_markup(&unquoted)); + } + } + let start = ms_to_tick(start_ds.saturating_mul(100)); + let end = ms_to_tick(end_ds.saturating_mul(100)); + if end <= start || lines.is_empty() { + doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1)); + continue; + } + doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() }); + } + if !found && !text.trim().is_empty() { + return Err(Error::NotFormat("PJS")); + } + Ok(doc) +} + +/// Serialize a document into PJS format. +pub fn write(doc: &Document) -> String { + let mut out = String::new(); + let ds = |t| (tick_to_ms(t) + 50) / 100; + for c in &doc.cues { + let start = ds(c.start); + let end = ds(c.end).max(start + 1); + let lines: Vec = + plain_lines(&c.text).into_iter().map(|l| l.replace('"', "\"\"").replace('|', "|")).filter(|l| !l.is_empty()).collect(); + if !lines.is_empty() { + out.push_str(&format!("{start},{end},\"{}\"\n", lines.join("|"))); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_and_write_roundtrip() { + let pjs = "10,50,\"First line\"\n60,120,\"Second line|with break\"\n130,150,\"Say \"\"Hi\"\"\"\n"; + let doc = parse(pjs).expect("parse"); + assert_eq!(doc.cues.len(), 3); + assert_eq!(doc.cues[0].start, ms_to_tick(1000)); + assert_eq!(doc.cues[0].end, ms_to_tick(5000)); + assert_eq!(doc.cues[0].text, "First line"); + assert_eq!(doc.cues[1].start, ms_to_tick(6000)); + assert_eq!(doc.cues[1].end, ms_to_tick(12000)); + assert_eq!(doc.cues[1].text, "Second line\nwith break"); + assert_eq!(doc.cues[2].text, "Say \"Hi\""); + + let written = write(&doc); + assert_eq!(written, pjs); + } + + #[test] + fn rejects_non_pjs() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nHello\n").is_err()); + } +} diff --git a/crates/captions/src/realtext.rs b/crates/captions/src/realtext.rs new file mode 100644 index 0000000000..1c4328a3be --- /dev/null +++ b/crates/captions/src/realtext.rs @@ -0,0 +1,247 @@ +//! RealText (`.rt`): streaming HTML-like timed text markup. +//! +//! ```text +//! +//! +//! ``` +//! +//! RealText documents encapsulate timed text inside a `` container with `