From c71580a8b3455964db98c5f9b91e66891590d519 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:13:59 -0500 Subject: [PATCH 1/2] pipeline: cut Cube profile parsing over to craft-cms (#4339) --- Cargo.lock | 12 ++++- Cargo.toml | 1 + crates/pipeline/Cargo.toml | 1 + crates/pipeline/src/lut.rs | 63 ++++++++-------------- packaging/linux/flatpak/cargo-sources.json | 26 ++++++++- 5 files changed, 59 insertions(+), 44 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a5d50e3100..08a130312f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1196,6 +1196,15 @@ dependencies = [ "rayon", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=eeb134def2daa7e03512b4946bd59d6b419b9484#eeb134def2daa7e03512b4946bd59d6b419b9484" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-codepage" version = "0.1.0" @@ -3964,7 +3973,7 @@ name = "lightcraft-codecs" version = "0.21.1" dependencies = [ "bytemuck", - "craft-cms", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7f30d664695cd5ce14fc30659d36c3e32f234247)", "craft-gainmap", "craft-gif", "craft-heif", @@ -4226,6 +4235,7 @@ dependencies = [ name = "lightcraft-pipeline" version = "0.21.1" dependencies = [ + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eeb134def2daa7e03512b4946bd59d6b419b9484)", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", "dhat", "lightcraft-color", diff --git a/Cargo.toml b/Cargo.toml index e6537fecbb..551579938d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/lightcraft" [workspace.dependencies] +craft-cms-profile = { package = "craft-cms", git = "https://github.com/storytold/craft-libs", rev = "eeb134def2daa7e03512b4946bd59d6b419b9484" } craft-plist = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bea6ed1ff031b81df2d64be470485c1ca808847e" } craft-pdf-print = { package = "craft-pdf", git = "https://github.com/storytold/craft-libs", rev = "0fd30aeb3e02207d9d4c7c601540d9da45abf8de", default-features = false, features = ["write-raster"] } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] } diff --git a/crates/pipeline/Cargo.toml b/crates/pipeline/Cargo.toml index 89e69cce43..0a8c41149e 100644 --- a/crates/pipeline/Cargo.toml +++ b/crates/pipeline/Cargo.toml @@ -9,6 +9,7 @@ description = "LightCraft develop pipeline: scene-referred, float, resolution in workspace = true [dependencies] +craft-cms-profile = { workspace = true } lightcraft-geom = { workspace = true } lightcraft-color = { workspace = true } lightcraft-raster = { workspace = true } diff --git a/crates/pipeline/src/lut.rs b/crates/pipeline/src/lut.rs index 971599cbbf..29a9649a1c 100644 --- a/crates/pipeline/src/lut.rs +++ b/crates/pipeline/src/lut.rs @@ -19,48 +19,8 @@ pub struct Lut3d { impl Lut3d { /// Parse a `.cube` file. pub fn parse_cube(text: &str) -> Result { - let (mut size, mut title) = (0usize, None); - let (mut min, mut max) = ([0.0f32; 3], [1.0f32; 3]); - let mut data = Vec::new(); - let three = |rest: &str| -> Option<[f32; 3]> { - let v: Vec = rest.split_whitespace().filter_map(|x| x.parse().ok()).collect(); - (v.len() == 3 && v.iter().all(|x| x.is_finite())).then(|| [v[0], v[1], v[2]]) - }; - for line in text.lines() { - let l = line.trim(); - if l.is_empty() || l.starts_with('#') { - continue; - } - if let Some(r) = l.strip_prefix("TITLE") { - title = Some(r.trim().trim_matches('"').to_string()); - } else if let Some(r) = l.strip_prefix("LUT_3D_SIZE") { - size = r.trim().parse().map_err(|_| format!("bad LUT_3D_SIZE `{}`", r.trim()))?; - if !(2..=256).contains(&size) { - return Err(format!("LUT_3D_SIZE {size} out of range")); - } - } else if l.starts_with("LUT_1D_SIZE") { - return Err("1D LUTs are not supported (only 3D .cube files)".into()); - } else if let Some(r) = l.strip_prefix("DOMAIN_MIN") { - min = three(r).ok_or("bad DOMAIN_MIN")?; - } else if let Some(r) = l.strip_prefix("DOMAIN_MAX") { - max = three(r).ok_or("bad DOMAIN_MAX")?; - } else if l.starts_with(|c: char| c.is_ascii_alphabetic()) { - // a data line of `nan` / `inf` starts with a letter too: it is bad data, not a keyword - if l.split_whitespace().next().is_some_and(|w| w.parse::().is_ok()) { - return Err(format!("bad line `{l}`")); - } - // other keywords (LUT_IN_VIDEO_RANGE…) are ignored - } else { - data.push(three(l).ok_or_else(|| format!("bad line `{l}`"))?); - } - } - if size == 0 { - return Err("not a 3D .cube LUT (no LUT_3D_SIZE)".into()); - } - if data.len() != size * size * size { - return Err(format!("expected {} entries, found {}", size * size * size, data.len())); - } - Ok(Lut3d { size, data, domain_min: min, domain_max: max, title }) + let table = craft_cms_profile::lutfile::parse_cube_3d(text, 256).map_err(|error| error.to_string())?; + Ok(Lut3d { size: table.size, data: table.data, domain_min: table.domain_min, domain_max: table.domain_max, title: table.title }) } /// Look up `c` (trilinear). @@ -132,6 +92,25 @@ mod tests { s } + #[test] + fn shared_profile_parser_keeps_domain_and_title_policy() { + let text = format!( + "TITLE \"literal # title\"\nDOMAIN_MIN 1 0 2\nDOMAIN_MAX 0 0 1\n{}", + cube(|c| c, 2).lines().skip(1).collect::>().join("\n") + ); + let profile = Lut3d::parse_cube(&text).unwrap(); + assert_eq!(profile.title.as_deref(), Some("literal # title")); + assert_eq!(profile.domain_min, [1.0, 0.0, 2.0]); + assert_eq!(profile.domain_max, [0.0, 0.0, 1.0]); + assert!(profile.apply([0.0; 3]).iter().all(|v| v.is_finite())); + let unlabelled = cube(|c| c, 2).lines().skip(1).collect::>().join("\n"); + assert_eq!(Lut3d::parse_cube(&unlabelled).unwrap().title, None); + assert!(Lut3d::parse_cube("LUT_3D_SIZE 256").unwrap_err().contains("16777216")); + for bad in ["0 ignored 0 0", "0 0 0 ignored", "NaN 0 0"] { + assert!(Lut3d::parse_cube(&format!("LUT_3D_SIZE 2\n{bad}\n{}", "0 0 0\n".repeat(7))).is_err()); + } + } + #[test] fn identity_and_swap() { let id = Lut3d::parse_cube(&cube(|c| c, 17)).unwrap(); diff --git a/packaging/linux/flatpak/cargo-sources.json b/packaging/linux/flatpak/cargo-sources.json index 534231be87..77ca3dabcb 100644 --- a/packaging/linux/flatpak/cargo-sources.json +++ b/packaging/linux/flatpak/cargo-sources.json @@ -5,6 +5,12 @@ "commit": "7f30d664695cd5ce14fc30659d36c3e32f234247", "dest": "flatpak-cargo/git/craft-libs-7f30d66" }, + { + "type": "git", + "url": "https://github.com/storytold/craft-libs", + "commit": "eeb134def2daa7e03512b4946bd59d6b419b9484", + "dest": "flatpak-cargo/git/craft-libs-eeb134d" + }, { "type": "git", "url": "https://github.com/storytold/craft-libs", @@ -1621,6 +1627,24 @@ "dest": "cargo/vendor-git/7afa30ca311804d863bbc144ec2c79a3a321ce72c30264402ae2c6af8a05da44/craft-cms", "dest-filename": ".cargo-checksum.json" }, + { + "type": "shell", + "commands": [ + "mkdir -p \"cargo/vendor-git/92168c1af4f3f511076af4245ec3ce22c5c554b4cc78c215ddf71587aac87d85\" && cp -r --reflink=auto \"flatpak-cargo/git/craft-libs-eeb134d/crates/cms\" \"cargo/vendor-git/92168c1af4f3f511076af4245ec3ce22c5c554b4cc78c215ddf71587aac87d85/craft-cms\"" + ] + }, + { + "type": "inline", + "contents": "[package]\nname = \"craft-cms\"\nversion = \"0.1.0\"\nedition = \"2024\"\nlicense = \"MIT OR Apache-2.0\"\nrust-version = \"1.95\"\nrepository = \"https://github.com/storytold/craft-libs\"\ndescription = \"Pure-Rust ICC v2/v4 colour management: profile parsing and writing, transforms, rendering intents, black point compensation\"\nexclude = [\"tests/data\", \"tests/fogra39.rs\"]\n\n[lints.rust]\nunsafe_code = \"forbid\"\nunused_workspace_dependencies = \"allow\"\n\n[lints.rust.unexpected_cfgs]\nlevel = \"warn\"\ncheck-cfg = [\"cfg(craft_pdf_unicode_fixtures)\"]\n\n[lints.clippy]\ncognitive_complexity = \"deny\"\ntoo_many_arguments = \"deny\"\nunused_workspace_dependencies = \"allow\"\nwildcard_imports = \"deny\"\ndbg_macro = \"warn\"\ntodo = \"warn\"\n\n[dependencies.md5]\npackage = \"md-5\"\nversion = \"0.10\"\ndefault-features = false\n\n[target.\"cfg(not(target_arch = \\\"wasm32\\\"))\".dependencies]\nrayon = \"1\"\n\n[dev-dependencies]\nmoxcms = \"0.8\"\n", + "dest": "cargo/vendor-git/92168c1af4f3f511076af4245ec3ce22c5c554b4cc78c215ddf71587aac87d85/craft-cms", + "dest-filename": "Cargo.toml" + }, + { + "type": "inline", + "contents": "{\"package\": null, \"files\": {}}", + "dest": "cargo/vendor-git/92168c1af4f3f511076af4245ec3ce22c5c554b4cc78c215ddf71587aac87d85/craft-cms", + "dest-filename": ".cargo-checksum.json" + }, { "type": "shell", "commands": [ @@ -10215,7 +10239,7 @@ }, { "type": "inline", - "contents": "[source.vendored-sources]\ndirectory = \"cargo/vendor\"\n\n[source.crates-io]\nreplace-with = \"vendored-sources\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=7f30d664695cd5ce14fc30659d36c3e32f234247\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-7afa30ca311804d863bbc144ec2c79a3a321ce72c30264402ae2c6af8a05da44\"\nrev = \"7f30d664695cd5ce14fc30659d36c3e32f234247\"\n\n[source.git-vendor-7afa30ca311804d863bbc144ec2c79a3a321ce72c30264402ae2c6af8a05da44]\ndirectory = \"cargo/vendor-git/7afa30ca311804d863bbc144ec2c79a3a321ce72c30264402ae2c6af8a05da44\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-bc00bd22a20692df38f25839a8568cd55b90e379a41719721bbc0f04fe5e29f7\"\nrev = \"f0f4758c01581d79577b9bf5046c06f4e77b1f18\"\n\n[source.git-vendor-bc00bd22a20692df38f25839a8568cd55b90e379a41719721bbc0f04fe5e29f7]\ndirectory = \"cargo/vendor-git/bc00bd22a20692df38f25839a8568cd55b90e379a41719721bbc0f04fe5e29f7\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-547b31fae2076d587e497f8a6226e18e0bfe27e9014d2bdf3cce7d69262df801\"\nrev = \"c28356d400aed7575b04ec1551b4665107cfe845\"\n\n[source.git-vendor-547b31fae2076d587e497f8a6226e18e0bfe27e9014d2bdf3cce7d69262df801]\ndirectory = \"cargo/vendor-git/547b31fae2076d587e497f8a6226e18e0bfe27e9014d2bdf3cce7d69262df801\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-11a22760e699d74db2deeccbdb390b343ad010ce425dcb15451f0e14e45ff298\"\nrev = \"c5a1cbfb5f9049f9270955caffb5bee5997aebf7\"\n\n[source.git-vendor-11a22760e699d74db2deeccbdb390b343ad010ce425dcb15451f0e14e45ff298]\ndirectory = \"cargo/vendor-git/11a22760e699d74db2deeccbdb390b343ad010ce425dcb15451f0e14e45ff298\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=9dcbd90c7d16e1a668b3afa057e940e2db328b93\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-36bf00be069421f8a8a7428c4360efee8b4243207a59d7b566c6f48fc5918f61\"\nrev = \"9dcbd90c7d16e1a668b3afa057e940e2db328b93\"\n\n[source.git-vendor-36bf00be069421f8a8a7428c4360efee8b4243207a59d7b566c6f48fc5918f61]\ndirectory = \"cargo/vendor-git/36bf00be069421f8a8a7428c4360efee8b4243207a59d7b566c6f48fc5918f61\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-a51e2c3f46af71f1caed91009f88b4f9982db0c4152c6659d11967a7731b1ccc\"\nrev = \"b77af389f30bb10de10d8436ca9b39fe94e3bb67\"\n\n[source.git-vendor-a51e2c3f46af71f1caed91009f88b4f9982db0c4152c6659d11967a7731b1ccc]\ndirectory = \"cargo/vendor-git/a51e2c3f46af71f1caed91009f88b4f9982db0c4152c6659d11967a7731b1ccc\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=4ffa307f1a0a6fbd8897318cc719440ab06e9c63\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-ded75ace3b48131a7498b2ad3ce7884b178155a1ef794dda2327c20c2979a816\"\nrev = \"4ffa307f1a0a6fbd8897318cc719440ab06e9c63\"\n\n[source.git-vendor-ded75ace3b48131a7498b2ad3ce7884b178155a1ef794dda2327c20c2979a816]\ndirectory = \"cargo/vendor-git/ded75ace3b48131a7498b2ad3ce7884b178155a1ef794dda2327c20c2979a816\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-9100d311acc530b0286234c55b78dbdc0325d5e30950478c5c7864bfed7a4545\"\nrev = \"5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a\"\n\n[source.git-vendor-9100d311acc530b0286234c55b78dbdc0325d5e30950478c5c7864bfed7a4545]\ndirectory = \"cargo/vendor-git/9100d311acc530b0286234c55b78dbdc0325d5e30950478c5c7864bfed7a4545\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=478c50560d3c6fad3d613af2a30b35c3bc9f4c0f\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-cb31475a7a9d19c00f48b4c43603f2f1a464c6dce15da1d21bba4c653eeba6b2\"\nrev = \"478c50560d3c6fad3d613af2a30b35c3bc9f4c0f\"\n\n[source.git-vendor-cb31475a7a9d19c00f48b4c43603f2f1a464c6dce15da1d21bba4c653eeba6b2]\ndirectory = \"cargo/vendor-git/cb31475a7a9d19c00f48b4c43603f2f1a464c6dce15da1d21bba4c653eeba6b2\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-6f5ad8618176b3fc0aac703e6e74df7229b0350b4574c7edbe0bb86c53c1cb6c\"\nrev = \"5c91598ccc86537a779f438d520fa6406c26efe6\"\n\n[source.git-vendor-6f5ad8618176b3fc0aac703e6e74df7229b0350b4574c7edbe0bb86c53c1cb6c]\ndirectory = \"cargo/vendor-git/6f5ad8618176b3fc0aac703e6e74df7229b0350b4574c7edbe0bb86c53c1cb6c\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=0fd30aeb3e02207d9d4c7c601540d9da45abf8de\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-fafb086755da4e9bf32b4ac1b53a42a6017167d56ec0071462788465fa35eb30\"\nrev = \"0fd30aeb3e02207d9d4c7c601540d9da45abf8de\"\n\n[source.git-vendor-fafb086755da4e9bf32b4ac1b53a42a6017167d56ec0071462788465fa35eb30]\ndirectory = \"cargo/vendor-git/fafb086755da4e9bf32b4ac1b53a42a6017167d56ec0071462788465fa35eb30\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=bea6ed1ff031b81df2d64be470485c1ca808847e\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-32c3b4109a3afdabed8bce488e027fa99fcc1b06e4fbe9ee85802b6b73337040\"\nrev = \"bea6ed1ff031b81df2d64be470485c1ca808847e\"\n\n[source.git-vendor-32c3b4109a3afdabed8bce488e027fa99fcc1b06e4fbe9ee85802b6b73337040]\ndirectory = \"cargo/vendor-git/32c3b4109a3afdabed8bce488e027fa99fcc1b06e4fbe9ee85802b6b73337040\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=16d838105b07965832bb43132880176f299634d5\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-879b5ad1e55c0c2de1d740528f2a8f8e2ffec953302517957e516331e9525f03\"\nrev = \"16d838105b07965832bb43132880176f299634d5\"\n\n[source.git-vendor-879b5ad1e55c0c2de1d740528f2a8f8e2ffec953302517957e516331e9525f03]\ndirectory = \"cargo/vendor-git/879b5ad1e55c0c2de1d740528f2a8f8e2ffec953302517957e516331e9525f03\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-4765c8f813a43ec0005270c9f4b16bff2eb2e09aeb15e4230bcd10e5bba1c4ba\"\nrev = \"6e03f65bf45181db77ba6229716e6624db9eb25b\"\n\n[source.git-vendor-4765c8f813a43ec0005270c9f4b16bff2eb2e09aeb15e4230bcd10e5bba1c4ba]\ndirectory = \"cargo/vendor-git/4765c8f813a43ec0005270c9f4b16bff2eb2e09aeb15e4230bcd10e5bba1c4ba\"\n\n[source.\"https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a\"]\ngit = \"https://github.com/storytold/egui\"\nreplace-with = \"git-vendor-11e349eb0774eb3ab9192b38c47d748bf18abba91a0e3952d8f196513da96ee6\"\nrev = \"6d518fc799681571963842f95b55a6b68431b15a\"\n\n[source.git-vendor-11e349eb0774eb3ab9192b38c47d748bf18abba91a0e3952d8f196513da96ee6]\ndirectory = \"cargo/vendor-git/11e349eb0774eb3ab9192b38c47d748bf18abba91a0e3952d8f196513da96ee6\"\n\n[source.\"https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc\"]\ngit = \"https://github.com/storytold/winit\"\nreplace-with = \"git-vendor-9c7f809a50c4212d761a5b6359c5e4a02fcf86376d330a441c4ce9d112706ee9\"\nrev = \"a517b3846ee8457d84ee4975110bfda6797c44dc\"\n\n[source.git-vendor-9c7f809a50c4212d761a5b6359c5e4a02fcf86376d330a441c4ce9d112706ee9]\ndirectory = \"cargo/vendor-git/9c7f809a50c4212d761a5b6359c5e4a02fcf86376d330a441c4ce9d112706ee9\"\n", + "contents": "[source.vendored-sources]\ndirectory = \"cargo/vendor\"\n\n[source.crates-io]\nreplace-with = \"vendored-sources\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=7f30d664695cd5ce14fc30659d36c3e32f234247\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-7afa30ca311804d863bbc144ec2c79a3a321ce72c30264402ae2c6af8a05da44\"\nrev = \"7f30d664695cd5ce14fc30659d36c3e32f234247\"\n\n[source.git-vendor-7afa30ca311804d863bbc144ec2c79a3a321ce72c30264402ae2c6af8a05da44]\ndirectory = \"cargo/vendor-git/7afa30ca311804d863bbc144ec2c79a3a321ce72c30264402ae2c6af8a05da44\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=eeb134def2daa7e03512b4946bd59d6b419b9484\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-92168c1af4f3f511076af4245ec3ce22c5c554b4cc78c215ddf71587aac87d85\"\nrev = \"eeb134def2daa7e03512b4946bd59d6b419b9484\"\n\n[source.git-vendor-92168c1af4f3f511076af4245ec3ce22c5c554b4cc78c215ddf71587aac87d85]\ndirectory = \"cargo/vendor-git/92168c1af4f3f511076af4245ec3ce22c5c554b4cc78c215ddf71587aac87d85\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-bc00bd22a20692df38f25839a8568cd55b90e379a41719721bbc0f04fe5e29f7\"\nrev = \"f0f4758c01581d79577b9bf5046c06f4e77b1f18\"\n\n[source.git-vendor-bc00bd22a20692df38f25839a8568cd55b90e379a41719721bbc0f04fe5e29f7]\ndirectory = \"cargo/vendor-git/bc00bd22a20692df38f25839a8568cd55b90e379a41719721bbc0f04fe5e29f7\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-547b31fae2076d587e497f8a6226e18e0bfe27e9014d2bdf3cce7d69262df801\"\nrev = \"c28356d400aed7575b04ec1551b4665107cfe845\"\n\n[source.git-vendor-547b31fae2076d587e497f8a6226e18e0bfe27e9014d2bdf3cce7d69262df801]\ndirectory = \"cargo/vendor-git/547b31fae2076d587e497f8a6226e18e0bfe27e9014d2bdf3cce7d69262df801\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-11a22760e699d74db2deeccbdb390b343ad010ce425dcb15451f0e14e45ff298\"\nrev = \"c5a1cbfb5f9049f9270955caffb5bee5997aebf7\"\n\n[source.git-vendor-11a22760e699d74db2deeccbdb390b343ad010ce425dcb15451f0e14e45ff298]\ndirectory = \"cargo/vendor-git/11a22760e699d74db2deeccbdb390b343ad010ce425dcb15451f0e14e45ff298\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=9dcbd90c7d16e1a668b3afa057e940e2db328b93\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-36bf00be069421f8a8a7428c4360efee8b4243207a59d7b566c6f48fc5918f61\"\nrev = \"9dcbd90c7d16e1a668b3afa057e940e2db328b93\"\n\n[source.git-vendor-36bf00be069421f8a8a7428c4360efee8b4243207a59d7b566c6f48fc5918f61]\ndirectory = \"cargo/vendor-git/36bf00be069421f8a8a7428c4360efee8b4243207a59d7b566c6f48fc5918f61\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-a51e2c3f46af71f1caed91009f88b4f9982db0c4152c6659d11967a7731b1ccc\"\nrev = \"b77af389f30bb10de10d8436ca9b39fe94e3bb67\"\n\n[source.git-vendor-a51e2c3f46af71f1caed91009f88b4f9982db0c4152c6659d11967a7731b1ccc]\ndirectory = \"cargo/vendor-git/a51e2c3f46af71f1caed91009f88b4f9982db0c4152c6659d11967a7731b1ccc\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=4ffa307f1a0a6fbd8897318cc719440ab06e9c63\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-ded75ace3b48131a7498b2ad3ce7884b178155a1ef794dda2327c20c2979a816\"\nrev = \"4ffa307f1a0a6fbd8897318cc719440ab06e9c63\"\n\n[source.git-vendor-ded75ace3b48131a7498b2ad3ce7884b178155a1ef794dda2327c20c2979a816]\ndirectory = \"cargo/vendor-git/ded75ace3b48131a7498b2ad3ce7884b178155a1ef794dda2327c20c2979a816\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-9100d311acc530b0286234c55b78dbdc0325d5e30950478c5c7864bfed7a4545\"\nrev = \"5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a\"\n\n[source.git-vendor-9100d311acc530b0286234c55b78dbdc0325d5e30950478c5c7864bfed7a4545]\ndirectory = \"cargo/vendor-git/9100d311acc530b0286234c55b78dbdc0325d5e30950478c5c7864bfed7a4545\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=478c50560d3c6fad3d613af2a30b35c3bc9f4c0f\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-cb31475a7a9d19c00f48b4c43603f2f1a464c6dce15da1d21bba4c653eeba6b2\"\nrev = \"478c50560d3c6fad3d613af2a30b35c3bc9f4c0f\"\n\n[source.git-vendor-cb31475a7a9d19c00f48b4c43603f2f1a464c6dce15da1d21bba4c653eeba6b2]\ndirectory = \"cargo/vendor-git/cb31475a7a9d19c00f48b4c43603f2f1a464c6dce15da1d21bba4c653eeba6b2\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-6f5ad8618176b3fc0aac703e6e74df7229b0350b4574c7edbe0bb86c53c1cb6c\"\nrev = \"5c91598ccc86537a779f438d520fa6406c26efe6\"\n\n[source.git-vendor-6f5ad8618176b3fc0aac703e6e74df7229b0350b4574c7edbe0bb86c53c1cb6c]\ndirectory = \"cargo/vendor-git/6f5ad8618176b3fc0aac703e6e74df7229b0350b4574c7edbe0bb86c53c1cb6c\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=0fd30aeb3e02207d9d4c7c601540d9da45abf8de\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-fafb086755da4e9bf32b4ac1b53a42a6017167d56ec0071462788465fa35eb30\"\nrev = \"0fd30aeb3e02207d9d4c7c601540d9da45abf8de\"\n\n[source.git-vendor-fafb086755da4e9bf32b4ac1b53a42a6017167d56ec0071462788465fa35eb30]\ndirectory = \"cargo/vendor-git/fafb086755da4e9bf32b4ac1b53a42a6017167d56ec0071462788465fa35eb30\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=bea6ed1ff031b81df2d64be470485c1ca808847e\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-32c3b4109a3afdabed8bce488e027fa99fcc1b06e4fbe9ee85802b6b73337040\"\nrev = \"bea6ed1ff031b81df2d64be470485c1ca808847e\"\n\n[source.git-vendor-32c3b4109a3afdabed8bce488e027fa99fcc1b06e4fbe9ee85802b6b73337040]\ndirectory = \"cargo/vendor-git/32c3b4109a3afdabed8bce488e027fa99fcc1b06e4fbe9ee85802b6b73337040\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=16d838105b07965832bb43132880176f299634d5\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-879b5ad1e55c0c2de1d740528f2a8f8e2ffec953302517957e516331e9525f03\"\nrev = \"16d838105b07965832bb43132880176f299634d5\"\n\n[source.git-vendor-879b5ad1e55c0c2de1d740528f2a8f8e2ffec953302517957e516331e9525f03]\ndirectory = \"cargo/vendor-git/879b5ad1e55c0c2de1d740528f2a8f8e2ffec953302517957e516331e9525f03\"\n\n[source.\"https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b\"]\ngit = \"https://github.com/storytold/craft-libs\"\nreplace-with = \"git-vendor-4765c8f813a43ec0005270c9f4b16bff2eb2e09aeb15e4230bcd10e5bba1c4ba\"\nrev = \"6e03f65bf45181db77ba6229716e6624db9eb25b\"\n\n[source.git-vendor-4765c8f813a43ec0005270c9f4b16bff2eb2e09aeb15e4230bcd10e5bba1c4ba]\ndirectory = \"cargo/vendor-git/4765c8f813a43ec0005270c9f4b16bff2eb2e09aeb15e4230bcd10e5bba1c4ba\"\n\n[source.\"https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a\"]\ngit = \"https://github.com/storytold/egui\"\nreplace-with = \"git-vendor-11e349eb0774eb3ab9192b38c47d748bf18abba91a0e3952d8f196513da96ee6\"\nrev = \"6d518fc799681571963842f95b55a6b68431b15a\"\n\n[source.git-vendor-11e349eb0774eb3ab9192b38c47d748bf18abba91a0e3952d8f196513da96ee6]\ndirectory = \"cargo/vendor-git/11e349eb0774eb3ab9192b38c47d748bf18abba91a0e3952d8f196513da96ee6\"\n\n[source.\"https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc\"]\ngit = \"https://github.com/storytold/winit\"\nreplace-with = \"git-vendor-9c7f809a50c4212d761a5b6359c5e4a02fcf86376d330a441c4ce9d112706ee9\"\nrev = \"a517b3846ee8457d84ee4975110bfda6797c44dc\"\n\n[source.git-vendor-9c7f809a50c4212d761a5b6359c5e4a02fcf86376d330a441c4ce9d112706ee9]\ndirectory = \"cargo/vendor-git/9c7f809a50c4212d761a5b6359c5e4a02fcf86376d330a441c4ce9d112706ee9\"\n", "dest": "cargo", "dest-filename": "config" } From 27b755a93c8091a6f0c71151184a88f0b90144ce Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:14:04 -0500 Subject: [PATCH 2/2] raw: cut DCP camera-profile files over to craft-raw (#4332) --- Cargo.toml | 2 - crates/raw/src/convert.rs | 2 +- crates/raw/src/dcp.rs | 246 +++++++--------------------- crates/raw/src/dcp_legacy_tests.rs | 247 +++++++++++++++++++++++++++++ crates/raw/tests/it/dng.rs | 4 +- 5 files changed, 304 insertions(+), 197 deletions(-) create mode 100644 crates/raw/src/dcp_legacy_tests.rs diff --git a/Cargo.toml b/Cargo.toml index 551579938d..c4914f86bc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,8 +49,6 @@ lightcraft-color = { path = "crates/color" } lightcraft-raster = { path = "crates/raster" } # TIFF/IFD: the shared reader and writer (moved from crates/tiff; craft-libs#783). craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" } -# Camera raw files, the format layer: every maker but CR3, ARW, RAF, RW2 and ORF (craft-libs#862 and the maker PRs). -# On the same commit as craft-tiff: its errors and IFDs are shared. craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" } lightcraft-raw = { path = "crates/raw" } lightcraft-codecs = { path = "crates/codecs" } diff --git a/crates/raw/src/convert.rs b/crates/raw/src/convert.rs index c6ab36eea9..d0224d698a 100644 --- a/crates/raw/src/convert.rs +++ b/crates/raw/src/convert.rs @@ -120,7 +120,7 @@ fn orientation(o: craft_raw::Orientation) -> Orientation { Orientation::from_exif(o.to_exif()) } -fn color(c: craft_raw::ColorData) -> ColorData { +pub(crate) fn color(c: craft_raw::ColorData) -> ColorData { let m = |p: [Option; 2]| p.map(|m| m.map(Mat3)); ColorData { illuminant: c.illuminant, diff --git a/crates/raw/src/dcp.rs b/crates/raw/src/dcp.rs index e0cbea7939..0694d3b31d 100644 --- a/crates/raw/src/dcp.rs +++ b/crates/raw/src/dcp.rs @@ -4,15 +4,13 @@ //! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the //! hue/saturation map, look table and tone curve. Nothing here ships a profile. -use craft_tiff::{ByteOrder, Ifd, ParseOptions, Tiff, tags as t}; -use lightcraft_color::Xy; +#[cfg(test)] +use craft_tiff::tags as t; -use crate::gaintable::GainTableMap; -use crate::profile::{HsvTable, ProfileLook, ToneCurve}; -use crate::{ColorData, Mat3}; +use crate::ColorData; /// The magic number of a DNG camera profile file (`IIRC` / `MMCR`). -pub const DCP_MAGIC: u16 = 0x4352; +pub use craft_raw::dcp::DCP_MAGIC; /// A parsed camera profile. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] @@ -49,201 +47,30 @@ impl DcpProfile { } } -/// Errors reading a `.dcp`. -#[derive(Debug, thiserror::Error, PartialEq, Eq)] -pub enum DcpError { - #[error("not a DNG camera profile (.dcp)")] - NotDcp, - #[error("damaged camera profile: {0}")] - Damaged(String), - #[error("the camera profile has no usable colour matrix")] - NoMatrix, -} +pub use craft_raw::dcp::{DcpError, MAX_DCP_BYTES, is_dcp, read_dcp}; -/// Is `bytes` a DCP file (by its header)? -pub fn is_dcp(bytes: &[u8]) -> bool { - matches!(bytes.get(0..4), Some([b'I', b'I', b'R', b'C'] | [b'M', b'M', b'C', b'R'])) -} - -/// The largest `.dcp` file read or parsed (real profiles are kilobytes to a few MB). -pub const MAX_DCP_BYTES: u64 = 64 << 20; - -/// Read the `.dcp` file at `path`, reading at most [`MAX_DCP_BYTES`] + 1 bytes: a larger file is refused -/// before it is loaded into memory. -pub fn read_dcp(path: &std::path::Path) -> std::io::Result> { - use std::io::Read; - let mut bytes = Vec::new(); - std::fs::File::open(path)?.take(MAX_DCP_BYTES.saturating_add(1)).read_to_end(&mut bytes)?; - if bytes.len() as u64 > MAX_DCP_BYTES { - return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "the camera profile is larger than 64 MiB")); - } - Ok(bytes) -} - -/// Parse a `.dcp` file. Files above 64 MiB ([`MAX_DCP_BYTES`]) are refused. +/// Parse the shared file model, keeping application color types at the boundary. pub fn parse_dcp(bytes: &[u8]) -> Result { - if !is_dcp(bytes) { - return Err(DcpError::NotDcp); - } - if bytes.len() as u64 > MAX_DCP_BYTES { - return Err(DcpError::Damaged("larger than 64 MiB".into())); - } - // the TIFF reader only knows 42 / BigTIFF / raw magics: give it a header with 42 in place of RC - let mut data = bytes.to_vec(); - let forty_two: [u8; 2] = if bytes.first() == Some(&b'I') { [42, 0] } else { [0, 42] }; - if let Some(m) = data.get_mut(2..4) { - m.copy_from_slice(&forty_two); - } - let opts = ParseOptions { follow_children: false, max_ifds: 4, value_budget: Some(64 << 20), ..Default::default() }; - let tiff = Tiff::parse_with(&data, &opts).map_err(|e| DcpError::Damaged(e.to_string()))?; - let ifd: &Ifd = tiff.ifds.first().ok_or_else(|| DcpError::Damaged("no IFD".into()))?; - let mut color = color_data(ifd, ifd, tiff.order); - // a profile carries no white balance or calibration of a particular shot - color.as_shot_neutral = None; - color.as_shot_white_xy = None; - color.analog_balance = None; - color.camera_calibration = [None, None]; - color.baseline_sharpness = None; - color.profile.gain_table_map = None; - // only BaselineExposureOffset belongs to a profile (BaselineExposure is the camera's) - color.baseline_exposure = - ifd.f64s(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-4.0, 4.0); - // a single-illuminant profile names one illuminant; its second matrix slot stays empty - if color.color_matrix[0].is_none() { - // the first slot is the one every profile must fill (DNG: ColorMatrix1 is required) - return Err(DcpError::NoMatrix); - } - let text = |tag: u16| ifd.string(tag).map(|s| s.trim_matches(char::from(0)).trim().to_string()).unwrap_or_default(); - Ok(DcpProfile { name: text(t::PROFILE_NAME), camera_model: text(t::UNIQUE_CAMERA_MODEL), color }) + let p = craft_raw::dcp::parse_dcp(bytes)?; + Ok(DcpProfile { name: p.name, camera_model: p.camera_model, color: crate::convert::color(p.color) }) } -/// Write `p` as a `.dcp` file (little-endian): its name, camera, illuminants, matrices, hue/saturation -/// map, look table, tone curve and baseline exposure offset. +/// Write profile wire fields through craft-raw; shot/application policy is not serialized. pub fn write_dcp(p: &DcpProfile) -> Result, DcpError> { - use craft_tiff::writer::srational; - use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; - let c = &p.color; - let mut ifd = IfdBuilder::new(); - ifd.set(t::UNIQUE_CAMERA_MODEL, Value::Ascii(p.camera_model.clone())); - ifd.set(t::PROFILE_NAME, Value::Ascii(p.name.clone())); - let mat = |m: &lightcraft_color::Mat3| Value::SRational(m.0.iter().flatten().map(|v| srational(*v)).collect()); - for i in 0..2 { - if let Some(m) = &c.color_matrix[i] { - ifd.set([t::CALIBRATION_ILLUMINANT_1, t::CALIBRATION_ILLUMINANT_2][i], Value::Short(vec![c.illuminant[i]])); - ifd.set([t::COLOR_MATRIX_1, t::COLOR_MATRIX_2][i], mat(m)); - } - if let Some(m) = &c.forward_matrix[i] { - ifd.set([t::FORWARD_MATRIX_1, t::FORWARD_MATRIX_2][i], mat(m)); - } - } - let flat = |table: &crate::profile::HsvTable| Value::Float(table.data.iter().flatten().copied().collect()); - let dims = - |table: &crate::profile::HsvTable| Value::Long(vec![table.hue_divisions as u32, table.sat_divisions as u32, table.val_divisions as u32]); - if let Some(a) = c.profile.hue_sat_map[0].as_ref() { - ifd.set(t::PROFILE_HUE_SAT_MAP_DIMS, dims(a)); - ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_1, flat(a)); - if a.srgb_value { - ifd.set(t::PROFILE_HUE_SAT_MAP_ENCODING, Value::Long(vec![1])); - } - if let Some(b) = c.profile.hue_sat_map[1] - .as_ref() - .filter(|b| (b.hue_divisions, b.sat_divisions, b.val_divisions) == (a.hue_divisions, a.sat_divisions, a.val_divisions)) - { - ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_2, flat(b)); - } - } - if let Some(l) = &c.profile.look_table { - ifd.set(t::PROFILE_LOOK_TABLE_DIMS, dims(l)); - ifd.set(t::PROFILE_LOOK_TABLE_DATA, flat(l)); - if l.srgb_value { - ifd.set(t::PROFILE_LOOK_TABLE_ENCODING, Value::Long(vec![1])); - } - } - if let Some(tc) = &c.profile.tone_curve { - ifd.set(t::PROFILE_TONE_CURVE, Value::Float(tc.points.iter().flatten().copied().collect())); - } - if c.baseline_exposure != 0.0 { - ifd.set(t::BASELINE_EXPOSURE_OFFSET, Value::SRational(vec![srational(c.baseline_exposure)])); - } - let mut out = TiffWriter::new(ByteOrder::Little, false).write(&[ifd]).map_err(|e| DcpError::Damaged(e.to_string()))?; - // the DCP magic in place of 42 - if let Some(m) = out.get_mut(2..4) { - m.copy_from_slice(&DCP_MAGIC.to_le_bytes()); - } - Ok(out) -} - -// The colour tags a profile shares with DNG, read as DNG reads them (a DNG's own are read by `craft-raw`). - -fn mat3(v: Option>) -> Option { - let v = v?; - if v.len() != 9 || v.iter().any(|x| !x.is_finite()) { - return None; - } - let m = Mat3([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]); - (m.determinant().abs() > 1e-12).then_some(m) -} - -fn vec3(v: Option>) -> Option<[f64; 3]> { - let v = v?; - (v.len() == 3 && v.iter().all(|x| x.is_finite() && *x > 0.0)).then(|| [v[0], v[1], v[2]]) -} - -/// Colour tags: DNG puts them in IFD0, but some writers use the raw IFD; prefer the raw IFD. -/// `order` is the file's byte order (for the binary gain-table-map tags). -fn color_data(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ColorData { - let get = |tag: u16| raw.f64s(tag).or_else(|| ifd0.f64s(tag)); - let geti = |tag: u16| raw.u16(tag).or_else(|| ifd0.u16(tag)); - ColorData { - illuminant: [geti(t::CALIBRATION_ILLUMINANT_1).unwrap_or(0), geti(t::CALIBRATION_ILLUMINANT_2).unwrap_or(0)], - color_matrix: [mat3(get(t::COLOR_MATRIX_1)), mat3(get(t::COLOR_MATRIX_2))], - forward_matrix: [mat3(get(t::FORWARD_MATRIX_1)), mat3(get(t::FORWARD_MATRIX_2))], - camera_calibration: [mat3(get(t::CAMERA_CALIBRATION_1)), mat3(get(t::CAMERA_CALIBRATION_2))], - analog_balance: vec3(get(t::ANALOG_BALANCE)), - as_shot_neutral: vec3(get(t::AS_SHOT_NEUTRAL)), - as_shot_white_xy: get(t::AS_SHOT_WHITE_XY).filter(|v| v.len() == 2 && v[0] > 0.0 && v[1] > 0.0).map(|v| Xy::new(v[0], v[1])), - baseline_exposure: get(t::BASELINE_EXPOSURE).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0) - + get(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0), - // DNG 1.7 BaselineSharpness (IFD 0 or the enhanced IFD); implausible values are ignored - baseline_sharpness: get(t::BASELINE_SHARPNESS).and_then(|v| v.first().copied()).filter(|v| v.is_finite() && *v > 0.0 && *v <= 16.0), - profile: profile_look(ifd0, raw, order), - kelvin_presets: None, - } -} - -/// The profile look tags (`ProfileHueSatMap*`, `ProfileLookTable*`, `ProfileToneCurve`, -/// `ProfileGainTableMap*`); malformed ones are ignored. Like the colour tags, read from the raw IFD -/// first, else IFD 0. -fn profile_look(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ProfileLook { - let pick = |tag: u16| if raw.contains(tag) { raw } else { ifd0 }; - let table = |dims: u16, data: u16, enc: u16| { - let ifd = pick(dims); - let dims = ifd.u64s(dims)?; - let data = ifd.f64s(data)?; - HsvTable::from_tags(&dims, &data, ifd.u64s(enc).and_then(|v| v.first().copied()).unwrap_or(0)) + let color = craft_raw::ColorData { + illuminant: p.color.illuminant, + color_matrix: p.color.color_matrix.map(|m| m.map(|m| m.0)), + forward_matrix: p.color.forward_matrix.map(|m| m.map(|m| m.0)), + baseline_exposure: p.color.baseline_exposure, + profile: p.color.profile.clone(), + ..Default::default() }; - ProfileLook { - hue_sat_map: [ - table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_1, t::PROFILE_HUE_SAT_MAP_ENCODING), - table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_2, t::PROFILE_HUE_SAT_MAP_ENCODING), - ], - look_table: table(t::PROFILE_LOOK_TABLE_DIMS, t::PROFILE_LOOK_TABLE_DATA, t::PROFILE_LOOK_TABLE_ENCODING), - tone_curve: pick(t::PROFILE_TONE_CURVE).f64s(t::PROFILE_TONE_CURVE).and_then(|v| ToneCurve::from_tag(&v)), - gain_table_map: gain_table_map(ifd0, raw, order), - } + craft_raw::dcp::write_dcp(&craft_raw::dcp::DcpProfile { name: p.name.clone(), camera_model: p.camera_model.clone(), color }) } -/// The gain table map (DNG 1.7 precedence): `ProfileGainTableMap2` from IFD 0 (the embedded -/// camera profile), else from the raw IFD; else `ProfileGainTableMap` from the raw IFD (where DNG -/// 1.6 put it, and where Apple writes it), else from IFD 0 (where DNG 1.7 says it was meant to be). -/// A malformed tag falls through to the next one. -fn gain_table_map(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> Option { - let parse = |ifd: &Ifd, tag: u16| ifd.bytes(tag).and_then(|b| GainTableMap::parse(b, order, tag == t::PROFILE_GAIN_TABLE_MAP_2)); - parse(ifd0, t::PROFILE_GAIN_TABLE_MAP_2) - .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP_2)) - .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP)) - .or_else(|| parse(ifd0, t::PROFILE_GAIN_TABLE_MAP)) -} +#[cfg(test)] +#[path = "dcp_legacy_tests.rs"] +mod legacy; #[cfg(test)] mod tests { @@ -407,3 +234,36 @@ mod tests { assert!((c.baseline_exposure - 0.25).abs() < 1e-12); } } + +#[cfg(test)] +mod shared_parity { + use super::*; + fn check(bytes: &[u8]) { + let old = legacy::parse_dcp(bytes); + let new = parse_dcp(bytes); + match (old, new) { + (Ok(a), Ok(b)) => { + assert_eq!((a.name.as_str(), a.camera_model.as_str(), &a.color), (b.name.as_str(), b.camera_model.as_str(), &b.color)); + assert_eq!(legacy::write_dcp(&a).map_err(|e| e.to_string()), write_dcp(&b).map_err(|e| e.to_string())); + } + (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()), + other => panic!("different DCP acceptance: {other:?}"), + } + } + #[test] + fn shared_reader_and_writer_match_original_on_both_endian_mutations() { + for little in [false, true] { + let bytes = super::tests::synthetic_dcp(little, true); + for n in 0..=bytes.len() { + check(&bytes[..n]); + } + for at in 0..bytes.len() { + for value in [0, 0xff, 0x80] { + let mut mutated = bytes.clone(); + mutated[at] = value; + check(&mutated); + } + } + } + } +} diff --git a/crates/raw/src/dcp_legacy_tests.rs b/crates/raw/src/dcp_legacy_tests.rs new file mode 100644 index 0000000000..6144de0bf1 --- /dev/null +++ b/crates/raw/src/dcp_legacy_tests.rs @@ -0,0 +1,247 @@ +#![allow(dead_code)] +//! DNG Camera Profiles (`.dcp`): the user's own camera colour profiles, read at run time from +//! files they supply (DNG specification, chapter 6 "Camera Profiles"). A `.dcp` is a TIFF-structured +//! file whose header carries the magic `RC` (0x4352) in place of 42, with the profile tags in IFD 0: +//! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the +//! hue/saturation map, look table and tone curve. Nothing here ships a profile. + +use craft_tiff::{ByteOrder, Ifd, ParseOptions, Tiff, tags as t}; +use lightcraft_color::Xy; + +use crate::gaintable::GainTableMap; +use crate::profile::{HsvTable, ProfileLook, ToneCurve}; +use crate::{ColorData, Mat3}; + +/// The magic number of a DNG camera profile file (`IIRC` / `MMCR`). +pub const DCP_MAGIC: u16 = 0x4352; + +/// A parsed camera profile. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct DcpProfile { + /// `ProfileName` (empty when the file has none). + pub name: String, + /// `UniqueCameraModel`: the camera the profile was made for (empty when absent). + pub camera_model: String, + /// The colour model: illuminants, matrices and the profile look (hue/sat map, look table, tone curve). + pub color: ColorData, +} + +impl DcpProfile { + /// `color` (a raw file's own colour facts) with this profile's colour model in place of the + /// file's: its matrices, illuminants and look. The file's white balance (as-shot neutral or + /// white, and its white-balance presets), analog balance and baseline exposure stay, plus its + /// camera calibration when the profile has the same calibration illuminants (DNG 6.3: + /// calibration belongs to the camera, the profile to the look). + pub fn applied_to(&self, color: &ColorData) -> ColorData { + let calibration = if self.color.illuminant == color.illuminant { color.camera_calibration } else { [None, None] }; + ColorData { + illuminant: self.color.illuminant, + color_matrix: self.color.color_matrix, + forward_matrix: self.color.forward_matrix, + camera_calibration: calibration, + analog_balance: color.analog_balance, + as_shot_neutral: color.as_shot_neutral, + as_shot_white_xy: color.as_shot_white_xy, + baseline_exposure: color.baseline_exposure + self.color.baseline_exposure, + baseline_sharpness: color.baseline_sharpness, + profile: crate::profile::ProfileLook { gain_table_map: color.profile.gain_table_map.clone(), ..self.color.profile.clone() }, + kelvin_presets: color.kelvin_presets.clone(), + } + } +} + +/// Errors reading a `.dcp`. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum DcpError { + #[error("not a DNG camera profile (.dcp)")] + NotDcp, + #[error("damaged camera profile: {0}")] + Damaged(String), + #[error("the camera profile has no usable colour matrix")] + NoMatrix, +} + +/// Is `bytes` a DCP file (by its header)? +pub fn is_dcp(bytes: &[u8]) -> bool { + matches!(bytes.get(0..4), Some([b'I', b'I', b'R', b'C'] | [b'M', b'M', b'C', b'R'])) +} + +/// The largest `.dcp` file read or parsed (real profiles are kilobytes to a few MB). +pub const MAX_DCP_BYTES: u64 = 64 << 20; + +/// Read the `.dcp` file at `path`, reading at most [`MAX_DCP_BYTES`] + 1 bytes: a larger file is refused +/// before it is loaded into memory. +pub fn read_dcp(path: &std::path::Path) -> std::io::Result> { + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(path)?.take(MAX_DCP_BYTES.saturating_add(1)).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_DCP_BYTES { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "the camera profile is larger than 64 MiB")); + } + Ok(bytes) +} + +/// Parse a `.dcp` file. Files above 64 MiB ([`MAX_DCP_BYTES`]) are refused. +pub fn parse_dcp(bytes: &[u8]) -> Result { + if !is_dcp(bytes) { + return Err(DcpError::NotDcp); + } + if bytes.len() as u64 > MAX_DCP_BYTES { + return Err(DcpError::Damaged("larger than 64 MiB".into())); + } + // the TIFF reader only knows 42 / BigTIFF / raw magics: give it a header with 42 in place of RC + let mut data = bytes.to_vec(); + let forty_two: [u8; 2] = if bytes.first() == Some(&b'I') { [42, 0] } else { [0, 42] }; + if let Some(m) = data.get_mut(2..4) { + m.copy_from_slice(&forty_two); + } + let opts = ParseOptions { follow_children: false, max_ifds: 4, value_budget: Some(64 << 20), ..Default::default() }; + let tiff = Tiff::parse_with(&data, &opts).map_err(|e| DcpError::Damaged(e.to_string()))?; + let ifd: &Ifd = tiff.ifds.first().ok_or_else(|| DcpError::Damaged("no IFD".into()))?; + let mut color = color_data(ifd, ifd, tiff.order); + // a profile carries no white balance or calibration of a particular shot + color.as_shot_neutral = None; + color.as_shot_white_xy = None; + color.analog_balance = None; + color.camera_calibration = [None, None]; + color.baseline_sharpness = None; + color.profile.gain_table_map = None; + // only BaselineExposureOffset belongs to a profile (BaselineExposure is the camera's) + color.baseline_exposure = + ifd.f64s(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-4.0, 4.0); + // a single-illuminant profile names one illuminant; its second matrix slot stays empty + if color.color_matrix[0].is_none() { + // the first slot is the one every profile must fill (DNG: ColorMatrix1 is required) + return Err(DcpError::NoMatrix); + } + let text = |tag: u16| ifd.string(tag).map(|s| s.trim_matches(char::from(0)).trim().to_string()).unwrap_or_default(); + Ok(DcpProfile { name: text(t::PROFILE_NAME), camera_model: text(t::UNIQUE_CAMERA_MODEL), color }) +} + +/// Write `p` as a `.dcp` file (little-endian): its name, camera, illuminants, matrices, hue/saturation +/// map, look table, tone curve and baseline exposure offset. +pub fn write_dcp(p: &DcpProfile) -> Result, DcpError> { + use craft_tiff::writer::srational; + use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value}; + let c = &p.color; + let mut ifd = IfdBuilder::new(); + ifd.set(t::UNIQUE_CAMERA_MODEL, Value::Ascii(p.camera_model.clone())); + ifd.set(t::PROFILE_NAME, Value::Ascii(p.name.clone())); + let mat = |m: &lightcraft_color::Mat3| Value::SRational(m.0.iter().flatten().map(|v| srational(*v)).collect()); + for i in 0..2 { + if let Some(m) = &c.color_matrix[i] { + ifd.set([t::CALIBRATION_ILLUMINANT_1, t::CALIBRATION_ILLUMINANT_2][i], Value::Short(vec![c.illuminant[i]])); + ifd.set([t::COLOR_MATRIX_1, t::COLOR_MATRIX_2][i], mat(m)); + } + if let Some(m) = &c.forward_matrix[i] { + ifd.set([t::FORWARD_MATRIX_1, t::FORWARD_MATRIX_2][i], mat(m)); + } + } + let flat = |table: &crate::profile::HsvTable| Value::Float(table.data.iter().flatten().copied().collect()); + let dims = + |table: &crate::profile::HsvTable| Value::Long(vec![table.hue_divisions as u32, table.sat_divisions as u32, table.val_divisions as u32]); + if let Some(a) = c.profile.hue_sat_map[0].as_ref() { + ifd.set(t::PROFILE_HUE_SAT_MAP_DIMS, dims(a)); + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_1, flat(a)); + if a.srgb_value { + ifd.set(t::PROFILE_HUE_SAT_MAP_ENCODING, Value::Long(vec![1])); + } + if let Some(b) = c.profile.hue_sat_map[1] + .as_ref() + .filter(|b| (b.hue_divisions, b.sat_divisions, b.val_divisions) == (a.hue_divisions, a.sat_divisions, a.val_divisions)) + { + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_2, flat(b)); + } + } + if let Some(l) = &c.profile.look_table { + ifd.set(t::PROFILE_LOOK_TABLE_DIMS, dims(l)); + ifd.set(t::PROFILE_LOOK_TABLE_DATA, flat(l)); + if l.srgb_value { + ifd.set(t::PROFILE_LOOK_TABLE_ENCODING, Value::Long(vec![1])); + } + } + if let Some(tc) = &c.profile.tone_curve { + ifd.set(t::PROFILE_TONE_CURVE, Value::Float(tc.points.iter().flatten().copied().collect())); + } + if c.baseline_exposure != 0.0 { + ifd.set(t::BASELINE_EXPOSURE_OFFSET, Value::SRational(vec![srational(c.baseline_exposure)])); + } + let mut out = TiffWriter::new(ByteOrder::Little, false).write(&[ifd]).map_err(|e| DcpError::Damaged(e.to_string()))?; + // the DCP magic in place of 42 + if let Some(m) = out.get_mut(2..4) { + m.copy_from_slice(&DCP_MAGIC.to_le_bytes()); + } + Ok(out) +} + +// The colour tags a profile shares with DNG, read as DNG reads them (a DNG's own are read by `craft-raw`). + +fn mat3(v: Option>) -> Option { + let v = v?; + if v.len() != 9 || v.iter().any(|x| !x.is_finite()) { + return None; + } + let m = Mat3([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]); + (m.determinant().abs() > 1e-12).then_some(m) +} + +fn vec3(v: Option>) -> Option<[f64; 3]> { + let v = v?; + (v.len() == 3 && v.iter().all(|x| x.is_finite() && *x > 0.0)).then(|| [v[0], v[1], v[2]]) +} + +/// Colour tags: DNG puts them in IFD0, but some writers use the raw IFD; prefer the raw IFD. +/// `order` is the file's byte order (for the binary gain-table-map tags). +fn color_data(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ColorData { + let get = |tag: u16| raw.f64s(tag).or_else(|| ifd0.f64s(tag)); + let geti = |tag: u16| raw.u16(tag).or_else(|| ifd0.u16(tag)); + ColorData { + illuminant: [geti(t::CALIBRATION_ILLUMINANT_1).unwrap_or(0), geti(t::CALIBRATION_ILLUMINANT_2).unwrap_or(0)], + color_matrix: [mat3(get(t::COLOR_MATRIX_1)), mat3(get(t::COLOR_MATRIX_2))], + forward_matrix: [mat3(get(t::FORWARD_MATRIX_1)), mat3(get(t::FORWARD_MATRIX_2))], + camera_calibration: [mat3(get(t::CAMERA_CALIBRATION_1)), mat3(get(t::CAMERA_CALIBRATION_2))], + analog_balance: vec3(get(t::ANALOG_BALANCE)), + as_shot_neutral: vec3(get(t::AS_SHOT_NEUTRAL)), + as_shot_white_xy: get(t::AS_SHOT_WHITE_XY).filter(|v| v.len() == 2 && v[0] > 0.0 && v[1] > 0.0).map(|v| Xy::new(v[0], v[1])), + baseline_exposure: get(t::BASELINE_EXPOSURE).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0) + + get(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0), + // DNG 1.7 BaselineSharpness (IFD 0 or the enhanced IFD); implausible values are ignored + baseline_sharpness: get(t::BASELINE_SHARPNESS).and_then(|v| v.first().copied()).filter(|v| v.is_finite() && *v > 0.0 && *v <= 16.0), + profile: profile_look(ifd0, raw, order), + kelvin_presets: None, + } +} + +/// The profile look tags (`ProfileHueSatMap*`, `ProfileLookTable*`, `ProfileToneCurve`, +/// `ProfileGainTableMap*`); malformed ones are ignored. Like the colour tags, read from the raw IFD +/// first, else IFD 0. +fn profile_look(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ProfileLook { + let pick = |tag: u16| if raw.contains(tag) { raw } else { ifd0 }; + let table = |dims: u16, data: u16, enc: u16| { + let ifd = pick(dims); + let dims = ifd.u64s(dims)?; + let data = ifd.f64s(data)?; + HsvTable::from_tags(&dims, &data, ifd.u64s(enc).and_then(|v| v.first().copied()).unwrap_or(0)) + }; + ProfileLook { + hue_sat_map: [ + table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_1, t::PROFILE_HUE_SAT_MAP_ENCODING), + table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_2, t::PROFILE_HUE_SAT_MAP_ENCODING), + ], + look_table: table(t::PROFILE_LOOK_TABLE_DIMS, t::PROFILE_LOOK_TABLE_DATA, t::PROFILE_LOOK_TABLE_ENCODING), + tone_curve: pick(t::PROFILE_TONE_CURVE).f64s(t::PROFILE_TONE_CURVE).and_then(|v| ToneCurve::from_tag(&v)), + gain_table_map: gain_table_map(ifd0, raw, order), + } +} + +/// The gain table map (DNG 1.7 precedence): `ProfileGainTableMap2` from IFD 0 (the embedded +/// camera profile), else from the raw IFD; else `ProfileGainTableMap` from the raw IFD (where DNG +/// 1.6 put it, and where Apple writes it), else from IFD 0 (where DNG 1.7 says it was meant to be). +/// A malformed tag falls through to the next one. +fn gain_table_map(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> Option { + let parse = |ifd: &Ifd, tag: u16| ifd.bytes(tag).and_then(|b| GainTableMap::parse(b, order, tag == t::PROFILE_GAIN_TABLE_MAP_2)); + parse(ifd0, t::PROFILE_GAIN_TABLE_MAP_2) + .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP_2)) + .or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP)) + .or_else(|| parse(ifd0, t::PROFILE_GAIN_TABLE_MAP)) +} diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index dbce6d042d..1b4909c366 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -1045,7 +1045,9 @@ fn malformed_semantic_masks_are_skipped() { assert_eq!(decode(&bytes).unwrap().cpp, 3); let masks = lightcraft_raw::semantic_masks(&bytes); let names: Vec<&str> = masks.iter().map(|m| m.name.as_str()).collect(); - // Truncated strip pixels are rejected by the shared reader instead of zero-filled. + // A 4×4, 8-bit uncompressed mask needs 16 bytes: the three-byte strip + // is truncated, not a valid mask with zero-filled missing pixels. Keep the + // separate complete mask to test invalid MaskSubArea handling. assert_eq!(names, ["sub area too small"]); assert!(masks.iter().all(|m| m.sub_area.is_none()), "sub areas the mask doesn't fit are ignored"); for m in &masks {