Merge storytold main into next (17 Nov sync)

storytold main 83cb1133dd (291 commits) into the integration head bab1a99b85; 47 conflicted files.

- Domain test files (metafile, prepress, pdf plates, settings store, heif, media-testkit, atomic): tests next cut stay cut; tests new on main are kept, as trials where the crate's test target runs trials.
- atomic: main's group-bits test and Faulty::set_group go to src/tests.rs. audio: main's GSM and SBC oracles join tests/main.rs. cms constructors, pdf knockout_backdrop and testing_pdf join their crates' one test binary; timeline's preflight tests become src/preflight_tests.rs trials.
- update: main's changes to detect, install (linux, macos) and the tests land in next's split modules. The app's own offer is inspected on a thread of its own, picked up by tick's polling; settle_for_tests settles offers too. Later on a ready update drops the close it asked for. updater_pin_tests.rs stays deleted; its new pin test is in tests/it/update.rs.
- craft-color: main added a different crate at crates/color (the colour tags of compositor and display frames); it is next's craft-color module `tags`, re-exported at the root.
- Old crates/ui (combo, docking, testing, README) and keymap's ui/view.rs stay deleted; main's new crates/ui/src/testing files are dropped with them.
- New crates in the craft facade: ai, control, dds, frame, ipc, media-source, palette, press-print, score, ssip. testkit and xtask are listed outside it.
- Cargo.lock: the union of both locks, resolved by cargo metadata. Workflow: main's nextest Windows leg, with next's --keep-going clippy.
This commit is contained in:
aiongg
2026-11-17 12:44:52 +00:00
581 changed files with 77998 additions and 3002 deletions
+41
View File
@@ -29,6 +29,47 @@ pub fn srgb_trc() -> Curve {
}
impl Curve {
/// Creates a gamma curve `y = x^g`. Returns `Identity` if `g == 1.0` (within 1e-6).
pub fn gamma(g: f64) -> Result<Self, crate::CmsError> {
if !crate::math::fits_s15f16(g) || crate::math::s15f16_round(g) <= 0.0 {
return Err(crate::CmsError::InvalidArgument("gamma must remain positive and representable in ICC fixed point".into()));
}
if (g - 1.0).abs() < 1e-6 { Ok(Curve::Identity) } else { Ok(Curve::Gamma(g)) }
}
/// Creates an ICC parametric curve (types 0 to 4).
pub fn parametric(kind: u16, p: [f64; 7]) -> Result<Self, crate::CmsError> {
if kind > 4 {
return Err(crate::CmsError::InvalidArgument(format!("parametric curve kind {kind} must be <= 4")));
}
let count = Self::param_count(kind);
if !p.iter().take(count).all(|&v| crate::math::fits_s15f16(v)) {
return Err(crate::CmsError::InvalidArgument("parametric curve parameters must be representable in ICC fixed point".into()));
}
Ok(Curve::Parametric { kind, p })
}
/// Creates a sampled lookup table curve over evenly spaced inputs in `[0, 1]`.
pub fn from_table(samples: Vec<f32>) -> Result<Self, crate::CmsError> {
if samples.len() < 2 {
return Err(crate::CmsError::InvalidArgument("sampled curve must contain at least 2 entries".into()));
}
if !samples.iter().all(|s| s.is_finite() && (0.0..=1.0).contains(s)) {
return Err(crate::CmsError::InvalidArgument("sampled curve values must be finite and within [0, 1]".into()));
}
Ok(Curve::Table(samples))
}
/// Validate public enum variants before a profile stores them in ICC tags.
pub(crate) fn validate_icc(&self) -> Result<(), crate::CmsError> {
match self {
Self::Identity => Ok(()),
Self::Gamma(g) => Self::gamma(*g).map(|_| ()),
Self::Parametric { kind, p } => Self::parametric(*kind, *p).map(|_| ()),
Self::Table(t) if t.len() >= 2 && u32::try_from(t.len()).is_ok() && t.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)) => Ok(()),
Self::Table(_) => Err(crate::CmsError::InvalidArgument("sampled curve must contain representable finite normalized samples".into())),
}
}
/// Number of parameters stored for a parametric function type.
pub fn param_count(kind: u16) -> usize {
match kind {
+1
View File
@@ -46,6 +46,7 @@ pub use curve::Curve;
pub use gamut::GamutCheck;
pub use gpu_matrix_shaper::GpuMatrixShaper;
pub use lut3d::Lut3d;
pub use math::Mat3;
pub use named::{NamedColor, NamedColors};
pub use normalize::normalize_for_embedding;
pub use profile::{ColorSpace, Pcs, Profile, ProfileClass};
+6
View File
@@ -221,6 +221,12 @@ pub fn d50_quantized() -> [f64; 3] {
[s15f16_round(D50[0]), s15f16_round(D50[1]), s15f16_round(D50[2])]
}
/// Whether ICC s15Fixed16 encoding can round this value without saturation.
pub(crate) fn fits_s15f16(v: f64) -> bool {
let scaled = (v * 65536.0).round();
scaled.is_finite() && scaled >= f64::from(i32::MIN) && scaled <= f64::from(i32::MAX)
}
#[cfg(test)]
mod tests {
use super::*;
+122
View File
@@ -228,6 +228,128 @@ pub struct Profile {
}
impl Profile {
/// Builds a matrix/TRC display profile from an already PCS D50-adapted colorant matrix,
/// a white point, and per-channel tone reproduction curves.
///
/// # Matrix Coordinate Space
/// In accordance with ICC.1:2010 §9.2.35–37, the colorant matrix tags (`rXYZ`, `gXYZ`, `bXYZ`)
/// stored in an ICC profile must be chromatically adapted to the D50 Profile Connection Space (PCS).
/// `pcs_matrix` must therefore be expressed relative to D50 (e.g. as read directly from ICC profile tags).
///
/// If `white` is not D50, the profile's `chad` tag is populated with the Bradford chromatic adaptation
/// matrix mapping `white` to D50.
pub fn matrix_shaper(white: [f64; 3], pcs_matrix: Mat3, trc: [Curve; 3]) -> Result<Profile, CmsError> {
for curve in &trc {
curve.validate_icc()?;
}
if !white.iter().all(|&c| math::fits_s15f16(c) && math::s15f16_round(c) > 0.0) {
return Err(CmsError::InvalidArgument("white point must remain positive and representable in ICC fixed point".into()));
}
if !pcs_matrix.iter().flatten().all(|&v| v.is_finite()) {
return Err(CmsError::InvalidArgument("matrix elements must be finite".into()));
}
if math::invert(&pcs_matrix).is_none() {
return Err(CmsError::InvalidArgument("colorant matrix must be invertible".into()));
}
let d50 = math::d50_quantized();
let is_d50 = (white[0] - math::D50[0]).abs() < 1e-4 && (white[1] - math::D50[1]).abs() < 1e-4 && (white[2] - math::D50[2]).abs() < 1e-4;
let chad = if is_d50 { None } else { Some(math::bradford(white, math::D50)) };
// Quantize and normalize to ensure (1, 1, 1) maps exactly to PCS D50
let mut q = pcs_matrix.map(|row| row.map(math::s15f16_round));
for (i, row) in q.iter_mut().enumerate() {
let err = d50[i] - row.iter().sum::<f64>();
let k = (0..3).max_by(|a, b| row[*a].abs().total_cmp(&row[*b].abs())).unwrap_or(0);
row[k] = math::s15f16_round(row[k] + err);
}
if !q.iter().flatten().all(|&v| math::fits_s15f16(v)) || math::invert(&q).is_none() {
return Err(CmsError::InvalidArgument("colorant matrix is singular or unrepresentable after quantization/normalization".into()));
}
let chad_quantized = chad.map(|a| a.map(|row| row.map(math::s15f16_round)));
// Positive finite XYZ inputs can still overflow Bradford cone ratios or quantization.
// Refuse invalid stored adaptation rather than serializing nonfinite coefficients.
if chad_quantized.as_ref().is_some_and(|a| !a.iter().flatten().all(|&v| math::fits_s15f16(v)) || math::invert(a).is_none()) {
return Err(CmsError::InvalidArgument("chromatic adaptation must remain representable and invertible after quantization".into()));
}
Ok(Profile {
version: (4, 0x30),
class: ProfileClass::Display,
color_space: ColorSpace::Rgb,
pcs: Pcs::Xyz,
rendering_intent: Intent::RelativeColorimetric,
description: "Parametric Matrix/TRC".into(),
copyright: "".into(),
white_point: if is_d50 { d50 } else { white },
black_point: None,
chad: chad_quantized,
matrix: Some(q),
trc: Some(trc),
gray_trc: None,
a2b: [None, None, None],
b2a: [None, None, None],
bytes: None,
hash: Default::default(),
})
}
/// Builds a matrix/TRC display profile from unadapted source primaries relative to `white`.
///
/// The unadapted `source_matrix` (whose columns sum to `white`) is chromatically adapted to PCS D50
/// using the Bradford transform before storage in the profile's matrix tags.
pub fn from_source_matrix(white: [f64; 3], source_matrix: Mat3, trc: [Curve; 3]) -> Result<Profile, CmsError> {
if !white.iter().all(|&c| math::fits_s15f16(c) && math::s15f16_round(c) > 0.0) {
return Err(CmsError::InvalidArgument("white point must remain positive and representable in ICC fixed point".into()));
}
if !source_matrix.iter().flatten().all(|&v| v.is_finite()) {
return Err(CmsError::InvalidArgument("matrix elements must be finite".into()));
}
if math::invert(&source_matrix).is_none() {
return Err(CmsError::InvalidArgument("colorant matrix must be invertible".into()));
}
let is_d50 = (white[0] - math::D50[0]).abs() < 1e-4 && (white[1] - math::D50[1]).abs() < 1e-4 && (white[2] - math::D50[2]).abs() < 1e-4;
let pcs_matrix = if is_d50 {
source_matrix
} else {
let adapt = math::bradford(white, math::D50);
math::mul(&adapt, &source_matrix)
};
Self::matrix_shaper(white, pcs_matrix, trc)
}
/// Builds a monochrome profile from a white point and tone reproduction curve.
pub fn gray(white: [f64; 3], trc: Curve) -> Result<Profile, CmsError> {
trc.validate_icc()?;
if !white.iter().all(|&c| math::fits_s15f16(c) && math::s15f16_round(c) > 0.0) {
return Err(CmsError::InvalidArgument("white point must remain positive and representable in ICC fixed point".into()));
}
let is_d50 = (white[0] - math::D50[0]).abs() < 1e-4 && (white[1] - math::D50[1]).abs() < 1e-4 && (white[2] - math::D50[2]).abs() < 1e-4;
Ok(Profile {
version: (4, 0x30),
class: ProfileClass::Display,
color_space: ColorSpace::Gray,
pcs: Pcs::Xyz,
rendering_intent: Intent::RelativeColorimetric,
description: "Parametric Gray".into(),
copyright: "".into(),
white_point: if is_d50 { math::d50_quantized() } else { white },
black_point: None,
chad: None,
matrix: None,
trc: None,
gray_trc: Some(trc),
a2b: [None, None, None],
b2a: [None, None, None],
bytes: None,
hash: Default::default(),
})
}
/// Parses ICC profile bytes.
pub fn parse(bytes: &[u8]) -> Result<Profile, CmsError> {
parse::reset_budgets();
+183
View File
@@ -0,0 +1,183 @@
use craft_cms::{Builtin, Curve, Intent, Mat3, Profile, Transform};
#[test]
fn test_curve_constructors() {
// Gamma
let g22 = Curve::gamma(2.2).expect("valid gamma");
assert_eq!(g22, Curve::Gamma(2.2));
let g10 = Curve::gamma(1.0).expect("gamma 1.0 is identity");
assert_eq!(g10, Curve::Identity);
let g_near = Curve::gamma(1.0 + 1e-7).expect("near-identity gamma normalized");
assert_eq!(g_near, Curve::Identity);
assert!(Curve::gamma(0.0).is_err());
assert!(Curve::gamma(-2.2).is_err());
assert!(Curve::gamma(f64::NAN).is_err());
assert!(Curve::gamma(f64::INFINITY).is_err());
// Parametric
let p0 = Curve::parametric(0, [2.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]).expect("valid parametric type 0");
assert_eq!(p0, Curve::Parametric { kind: 0, p: [2.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] });
assert!(Curve::parametric(5, [0.0; 7]).is_err());
assert!(Curve::parametric(0, [f64::NAN, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]).is_err());
// Sampled table
let table = Curve::from_table(vec![0.0, 0.5, 1.0]).expect("valid sampled table");
assert_eq!(table, Curve::Table(vec![0.0, 0.5, 1.0]));
assert!(Curve::from_table(vec![0.5]).is_err());
assert!(Curve::from_table(vec![0.0, f32::NAN]).is_err());
assert!(Curve::from_table(vec![0.0, -0.1, 1.0]).is_err());
assert!(Curve::from_table(vec![0.0, 2.0]).is_err());
assert!(Curve::from_table(vec![0.0, 1.0001]).is_err());
}
#[test]
fn test_profile_constructors() {
let srgb = Builtin::Srgb.profile();
let white_d65 = [0.95047, 1.0, 1.08883];
// 1. Matrix shaper with already PCS D50-adapted matrix (e.g. read from ICC tags)
let pcs_d50_matrix: Mat3 = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]];
let trc = [craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc()];
let custom_from_pcs = Profile::matrix_shaper(white_d65, pcs_d50_matrix, trc.clone()).expect("matrix shaper from PCS D50");
assert_eq!(custom_from_pcs.color_space, craft_cms::ColorSpace::Rgb);
assert!(custom_from_pcs.same_colors(srgb), "custom profile from PCS D50 matrix should match reference sRGB");
// 2. Matrix shaper from unadapted D65 source primaries (undergoes single Bradford adaptation)
let source_d65_matrix: Mat3 = [[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]];
let custom_from_source = Profile::from_source_matrix(white_d65, source_d65_matrix, trc).expect("matrix shaper from source");
assert!(custom_from_source.same_colors(srgb), "custom profile adapted from source primaries should match reference sRGB");
// Evaluate transform
let xform = Transform::new(&custom_from_pcs, srgb, Intent::RelativeColorimetric, true).expect("transform from custom RGB to sRGB");
let mut out = [0.0f32; 3];
xform.eval(&[0.5, 0.5, 0.5], &mut out).expect("eval");
assert!((out[0] - 0.5).abs() < 1e-2);
assert!((out[1] - 0.5).abs() < 1e-2);
assert!((out[2] - 0.5).abs() < 1e-2);
// Invalid matrix shaper inputs
assert!(Profile::matrix_shaper([0.0, 1.0, 1.0], pcs_d50_matrix, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err());
assert!(Profile::matrix_shaper([f64::NAN, 1.0, 1.0], pcs_d50_matrix, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err());
let singular: Mat3 = [[0.0; 3]; 3];
assert!(Profile::matrix_shaper(white_d65, singular, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err());
// Near-degenerate matrix that is invertible before quantization but becomes singular after
let d50 = [0.9642, 1.0, 0.8249];
let near_degenerate: Mat3 = [[d50[0] - 0.000001, 0.000001, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, d50[2]]];
assert!(Profile::matrix_shaper(d50, near_degenerate, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err());
// Gray profile
let gray = Profile::gray(white_d65, Curve::gamma(2.2).expect("curve")).expect("gray profile");
assert_eq!(gray.color_space, craft_cms::ColorSpace::Gray);
let gray_to_srgb = Transform::new(&gray, srgb, Intent::RelativeColorimetric, true).expect("transform from gray to sRGB");
let mut srgb_out = [0.0f32; 3];
gray_to_srgb.eval(&[0.5], &mut srgb_out).expect("eval");
assert!((srgb_out[0] - srgb_out[1]).abs() < 1e-3);
assert!((srgb_out[1] - srgb_out[2]).abs() < 1e-3);
}
#[test]
fn test_matrix_constructors_against_independent_moxcms_oracle() {
use moxcms::{ColorProfile, Layout, TransformOptions as MoxOpts};
let srgb = Builtin::Srgb.profile();
let white_d65 = [0.95047, 1.0, 1.08883];
// 1. PCS D50-adapted matrix profile
let pcs_d50_matrix: Mat3 = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]];
let trc = [craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc(), craft_cms::curve::srgb_trc()];
let custom_from_pcs = Profile::matrix_shaper(white_d65, pcs_d50_matrix, trc.clone()).expect("matrix shaper from PCS D50");
// 2. Unadapted source matrix profile
let source_d65_matrix: Mat3 = [[0.4124564, 0.3575761, 0.1804375], [0.2126729, 0.7151522, 0.0721750], [0.0193339, 0.1191920, 0.9503041]];
let custom_from_source = Profile::from_source_matrix(white_d65, source_d65_matrix, trc).expect("matrix shaper from source");
// Convert both to standard ICC bytes and parse with independent oracle moxcms
let mox_from_pcs = ColorProfile::new_from_slice(&custom_from_pcs.to_bytes()).expect("moxcms parse custom PCS profile");
let mox_from_source = ColorProfile::new_from_slice(&custom_from_source.to_bytes()).expect("moxcms parse custom source profile");
let mox_dst_srgb = ColorProfile::new_from_slice(&srgb.to_bytes()).expect("moxcms parse builtin sRGB");
let test_pixels: Vec<u8> = (0..512u32).flat_map(|i| [(i * 17 % 256) as u8, (i * 53 % 256) as u8, (i * 97 % 256) as u8]).collect();
// Verify 1: moxcms transforming custom_from_pcs -> builtin sRGB produces identity (diff <= 1)
let mox_xform_pcs = mox_from_pcs.create_transform_8bit(Layout::Rgb, &mox_dst_srgb, Layout::Rgb, MoxOpts::default()).unwrap();
let mut mox_out_pcs = vec![0u8; test_pixels.len()];
mox_xform_pcs.transform(&test_pixels, &mut mox_out_pcs).unwrap();
let max_diff_pcs = test_pixels.iter().zip(&mox_out_pcs).map(|(a, b)| (*a as i32 - *b as i32).abs()).max().unwrap();
assert!(max_diff_pcs <= 1, "moxcms PCS-adapted profile -> sRGB max diff was {max_diff_pcs}");
// Verify 2: moxcms transforming custom_from_source -> builtin sRGB produces identity (diff <= 1)
let mox_xform_src = mox_from_source.create_transform_8bit(Layout::Rgb, &mox_dst_srgb, Layout::Rgb, MoxOpts::default()).unwrap();
let mut mox_out_src = vec![0u8; test_pixels.len()];
mox_xform_src.transform(&test_pixels, &mut mox_out_src).unwrap();
let max_diff_src = test_pixels.iter().zip(&mox_out_src).map(|(a, b)| (*a as i32 - *b as i32).abs()).max().unwrap();
assert!(max_diff_src <= 1, "moxcms source-adapted profile -> sRGB max diff was {max_diff_src}");
// Verify 3: craft_cms and moxcms agree when converting from custom_from_source to DisplayP3
let p3 = Builtin::DisplayP3.profile();
let mox_dst_p3 = ColorProfile::new_from_slice(&p3.to_bytes()).expect("moxcms parse Display P3");
let mox_xform_p3 = mox_from_source.create_transform_8bit(Layout::Rgb, &mox_dst_p3, Layout::Rgb, MoxOpts::default()).unwrap();
let mut mox_p3_out = vec![0u8; test_pixels.len()];
mox_xform_p3.transform(&test_pixels, &mut mox_p3_out).unwrap();
let ours_xform_p3 = Transform::new(&custom_from_source, p3, Intent::RelativeColorimetric, false).unwrap();
let mut ours_p3_out = vec![0u8; test_pixels.len()];
ours_xform_p3.convert_u8(&test_pixels, 3, &mut ours_p3_out, 3, false).unwrap();
let max_p3_diff = ours_p3_out.iter().zip(&mox_p3_out).map(|(a, b)| (*a as i32 - *b as i32).abs()).max().unwrap();
assert!(max_p3_diff <= 1, "craft_cms vs moxcms custom source profile -> P3 max diff was {max_p3_diff}");
}
#[test]
fn constructor_never_returns_a_nonfinite_adaptation() {
let matrix = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]];
for white in [[f64::MAX; 3], [f64::MIN_POSITIVE; 3], [1.0, 1.0, (0.8951 + 0.2664) / 0.1614]] {
if let Ok(profile) = Profile::matrix_shaper(white, matrix, [Curve::Identity, Curve::Identity, Curve::Identity]) {
assert!(profile.chad.unwrap().iter().flatten().all(|v| v.is_finite()), "nonfinite adaptation for {white:?}");
}
}
}
#[test]
fn constructors_reject_values_that_saturate_icc_fixed_point() {
assert!(Profile::gray([f64::MAX; 3], Curve::Identity).is_err());
assert!(Profile::gray([f64::MIN_POSITIVE; 3], Curve::Identity).is_err());
assert!(Curve::gamma(32768.0).is_err());
assert!(Curve::gamma(f64::MIN_POSITIVE).is_err());
assert!(Curve::parametric(0, [32768.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]).is_err());
let matrix = [[40000.0, -39999.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
assert!(Profile::matrix_shaper([0.9642, 1.0, 0.8249], matrix, [Curve::Identity, Curve::Identity, Curve::Identity]).is_err());
}
#[test]
fn profile_constructors_validate_direct_curve_variants() {
let white = [0.9642, 1.0, 0.8249];
let matrix = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]];
for curve in [
Curve::Gamma(f64::NAN),
Curve::Gamma(32768.0),
Curve::Parametric { kind: 5, p: [0.0; 7] },
Curve::Table(vec![0.0, f32::NAN]),
Curve::Table(vec![]),
] {
assert!(Profile::gray(white, curve.clone()).is_err());
assert!(Profile::matrix_shaper(white, matrix, [curve.clone(), Curve::Identity, Curve::Identity]).is_err());
assert!(Profile::from_source_matrix(white, matrix, [Curve::Identity, Curve::Identity, curve]).is_err());
}
}
#[test]
fn icc_fixed_point_boundaries_remain_accepted() {
let max = f64::from(i32::MAX) / 65536.0;
let min = f64::from(i32::MIN) / 65536.0;
assert!(Curve::gamma(max).is_ok());
assert!(Curve::gamma(1.0 / 65536.0).is_ok());
assert!(Curve::parametric(4, [1.0, 1.0, min, max, 0.0, 0.0, 0.0]).is_ok());
assert!(Profile::gray([max; 3], Curve::Identity).is_ok());
}
+1
View File
@@ -2,6 +2,7 @@
mod bench;
mod cms;
mod constructors;
mod fogra39;
mod named;
mod profile_id;