diff --git a/Cargo.lock b/Cargo.lock index e2a14141a0..02c06ef432 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1190,7 +1190,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "md-5", "rayon", @@ -1199,12 +1199,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" [[package]] name = "craft-color" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "serde", ] @@ -1212,7 +1212,7 @@ dependencies = [ [[package]] name = "craft-color-transform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "craft-cms", "craft-color", @@ -1222,7 +1222,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "thiserror 2.0.21", ] @@ -1230,7 +1230,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "rayon", ] @@ -1238,7 +1238,7 @@ dependencies = [ [[package]] name = "craft-develop" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "craft-color", "craft-color-transform", @@ -1252,7 +1252,7 @@ dependencies = [ [[package]] name = "craft-develop-model" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "craft-geom", "craft-metadata", @@ -1264,17 +1264,17 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" [[package]] name = "craft-gainmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "thiserror 2.0.21", ] @@ -1282,7 +1282,7 @@ dependencies = [ [[package]] name = "craft-geom" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "serde", ] @@ -1290,7 +1290,7 @@ dependencies = [ [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "gif", "image", @@ -1299,7 +1299,7 @@ dependencies = [ [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "heic-rs", "rayon", @@ -1308,12 +1308,12 @@ dependencies = [ [[package]] name = "craft-http-url" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1336,7 +1336,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "avif-serialize", "craft-dds", @@ -1367,7 +1367,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "rayon", "thiserror 2.0.21", @@ -1376,7 +1376,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1387,7 +1387,7 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "thiserror 2.0.21", ] @@ -1395,7 +1395,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "brotli-decompressor 6.0.1", "chrono", @@ -1407,7 +1407,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "chrono", "craft-codepage", @@ -1417,7 +1417,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "flate2", "roxmltree", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "thiserror 2.0.21", ] @@ -1434,7 +1434,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "encoding_rs", "flate2", @@ -1445,7 +1445,7 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "chrono", "craft-crw", @@ -1463,17 +1463,17 @@ dependencies = [ [[package]] name = "craft-sniff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" [[package]] name = "craft-sqlite" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "serde", "thiserror 2.0.21", @@ -1482,7 +1482,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1503,7 +1503,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "chrono", "dunce", @@ -1530,7 +1530,7 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "craft-media", "rav1e", @@ -1541,7 +1541,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "egui", "objc2 0.6.5", @@ -1552,7 +1552,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "quick-xml 0.41.0", "serde", @@ -1562,7 +1562,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=52d2560c183b2df8b1ffc25ca2078683af146fd6#52d2560c183b2df8b1ffc25ca2078683af146fd6" +source = "git+https://github.com/storytold/craft-libs?rev=1507e63e6a8d79daacc14c1203992bdb01f95a70#1507e63e6a8d79daacc14c1203992bdb01f95a70" dependencies = [ "flate2", "thiserror 2.0.21", @@ -4197,6 +4197,7 @@ dependencies = [ name = "lightcraft-inpaint" version = "0.21.1" dependencies = [ + "craft-develop", "rayon", ] @@ -4258,7 +4259,11 @@ name = "lightcraft-pipeline" version = "0.21.1" dependencies = [ "craft-cms", + "craft-color", + "craft-color-transform", "craft-develop", + "craft-develop-model", + "craft-geom", "craft-image-codecs", "dhat", "lightcraft-color", @@ -4301,6 +4306,9 @@ name = "lightcraft-raw" version = "0.21.1" dependencies = [ "chrono", + "craft-color", + "craft-color-transform", + "craft-develop", "craft-image-codecs", "craft-jxl", "craft-raw", diff --git a/Cargo.toml b/Cargo.toml index b2cbefa622..91e7ca6fc7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,37 +10,40 @@ 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 = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-plist = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-pdf-print = { package = "craft-pdf", git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6", default-features = false, features = ["write-raster"] } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6", features = ["serde"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } +craft-cms-profile = { package = "craft-cms", git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-plist = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-pdf-print = { package = "craft-pdf", git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70", default-features = false, features = ["write-raster"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70", features = ["serde"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } # Canon CRW decoder shared with the other Craft apps -craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-color-transform = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6", version = "0.1.0" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6", features = ["frames"] } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6", default-features = false, features = ["decode", "encode"] } +craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-color-transform = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-color = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-geom = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70", version = "0.1.0" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70", features = ["frames"] } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70", default-features = false, features = ["decode", "encode"] } jixel = "=0.3.4" # Photo metadata: EXIF, IPTC-IIM, XMP packets and GPX track logs (craft-libs#949) -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-sniff = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-media = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6", default-features = false, features = ["isobmff", "matroska"] } -craft-video = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6", features = ["av1", "av1-large-encode", "threads"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-sniff = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-media = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70", default-features = false, features = ["isobmff", "matroska"] } +craft-video = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70", features = ["av1", "av1-large-encode", "threads"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6", features = ["egui"] } -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70", features = ["egui"] } # HDR gain maps: ISO 21496-1 and hdrgm metadata, compute and apply (moved from crates/codecs; craft-libs#904). -craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } +craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } # PSD/PSB: the header, colour mode data and image resources (craft-libs#885). -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-sqlite = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-sqlite = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } jpeg-encoder = { version = "0.7", default-features = false, features = ["std"] } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } @@ -52,8 +55,8 @@ lightcraft-wincolor = { path = "crates/wincolor" } 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 = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } lightcraft-raw = { path = "crates/raw" } lightcraft-codecs = { path = "crates/codecs" } lightcraft-meta = { path = "crates/meta" } @@ -72,7 +75,7 @@ lightcraft-ui-egui = { path = "crates/ui-egui" } lightcraft-mcp = { path = "crates/mcp" } lightcraft-fetch = { path = "crates/fetch" } # HEIC/HEIF: the shared decoder (moved from crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6", default-features = false } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70", default-features = false } lightcraft-segment = { path = "crates/segment" } lightcraft-geocode = { path = "crates/geocode" } lightcraft-slideshow = { path = "crates/slideshow" } diff --git a/crates/fetch/Cargo.toml b/crates/fetch/Cargo.toml index 62079cf5f7..6b2213d781 100644 --- a/crates/fetch/Cargo.toml +++ b/crates/fetch/Cargo.toml @@ -10,7 +10,7 @@ workspace = true # downloads run natively only (the web build fetches no models) [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -craft-http-url = { git = "https://github.com/storytold/craft-libs", rev = "52d2560c183b2df8b1ffc25ca2078683af146fd6" } +craft-http-url = { git = "https://github.com/storytold/craft-libs", rev = "1507e63e6a8d79daacc14c1203992bdb01f95a70" } log = { workspace = true } rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] } rustls-rustcrypto = "0.0.2-alpha" diff --git a/crates/inpaint/Cargo.toml b/crates/inpaint/Cargo.toml index b2d111fba8..7650f708ea 100644 --- a/crates/inpaint/Cargo.toml +++ b/crates/inpaint/Cargo.toml @@ -9,6 +9,7 @@ description = "Content-aware hole filling: PatchMatch-based patch completion and workspace = true [dependencies] +craft-develop = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } diff --git a/crates/inpaint/src/lib.rs b/crates/inpaint/src/lib.rs index fb76304af7..6bb4c8f91d 100644 --- a/crates/inpaint/src/lib.rs +++ b/crates/inpaint/src/lib.rs @@ -1,61 +1,6 @@ -//! Content-aware hole filling (inpainting) for the Remove tool. -//! -//! * [`complete`]: multi-scale patch-based completion (Wexler, Shechtman, Irani 2007) with the -//! nearest-neighbour field found by PatchMatch (Barnes et al. 2009). See [`patchmatch`]. -//! * [`membrane_fill`]: smooth harmonic fill, used to seed the coarsest level and as a fallback. -//! -//! Buffers are interleaved `w × h × ch` floats in any colour model plus a `w × h` hole mask. -//! Everything is deterministic (fixed-seed RNG, results independent of the thread count) and never -//! panics on mismatched sizes: such calls return `None` or the input unchanged. -//! -//! Sources: C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman, *PatchMatch: A Randomized -//! Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009; Y. Wexler, E. Shechtman, -//! M. Irani, *Space-Time Completion of Video*, PAMI 2007. -//! -//! Ported from PhotoCraft (`crates/algo/src/inpaint.rs`, `poisson.rs`, MIT OR Apache-2.0, same -//! organisation; see `NOTICE`). +//! Content-aware hole filling (inpainting) for the Remove tool, backed by `craft_develop::inpaint`. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -pub mod membrane; -pub mod patchmatch; - -pub use membrane::membrane_fill; -pub use patchmatch::{CompleteParams, complete, complete_with}; - -/// A cancelled [`complete_with`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Cancelled; - -impl std::fmt::Display for Cancelled { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("cancelled") - } -} - -impl std::error::Error for Cancelled {} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn hostile_sizes_do_not_panic() { - assert_eq!(complete(4, 4, 3, &[0.0; 5], &[true; 16], &CompleteParams::default()), None); - assert_eq!(complete(4, 4, 0, &[], &[true; 16], &CompleteParams::default()), None); - assert_eq!(complete(usize::MAX, 2, 3, &[0.0; 6], &[true; 2], &CompleteParams::default()), None); - assert_eq!(membrane_fill(4, 4, 1, &[0.5; 3], &[true; 16]), vec![0.5; 3]); - // A hole covering everything: nothing to copy from. - assert_eq!(complete(16, 16, 1, &[0.5; 256], &[true; 256], &CompleteParams::default()), None); - // A tiny image smaller than a patch. - let _ = complete(2, 2, 1, &[0.5; 4], &[true, false, false, false], &CompleteParams::default()); - } - - #[test] - fn cancellation_stops() { - let img = vec![0.5f32; 64 * 64]; - let hole: Vec = (0..64 * 64usize).map(|i| (i % 64).abs_diff(32) < 4 && (i / 64).abs_diff(32) < 4).collect(); - assert_eq!(complete_with(64, 64, 1, &img, &hole, &CompleteParams::default(), &|| true), Err(Cancelled)); - } -} +pub use craft_develop::inpaint::{Cancelled, CompleteParams, complete, complete_with, membrane, membrane_fill, patchmatch}; diff --git a/crates/inpaint/src/membrane.rs b/crates/inpaint/src/membrane.rs deleted file mode 100644 index 9fe3bf16fd..0000000000 --- a/crates/inpaint/src/membrane.rs +++ /dev/null @@ -1,207 +0,0 @@ -//! Membrane (harmonic) fill: `Δv = 0` inside a hole with the known pixels as Dirichlet boundary. -//! Used to initialise the coarsest level of [`crate::complete`] and as its fallback. -//! -//! Sources: the membrane interpolant of P. Pérez, M. Gangnet, A. Blake, *Poisson Image Editing*, -//! ACM SIGGRAPH 2003 (§3), solved by successive over-relaxation on the 4-connected grid, accelerated -//! cascadically (solve on a half-resolution grid, prolong bilinearly, a few SOR sweeps per level). -//! Ported from PhotoCraft's `algo::poisson` (MIT OR Apache-2.0). - -/// Convergence threshold (max per-sweep update) for the SOR sweeps. -const TOL: f32 = 2e-5; -/// SOR sweeps (cap) and relaxation factor on every level above the coarsest: tuned so a 96×72 disc -/// is within ~1e-3 of a fully converged Gauss–Seidel solve (below one 8-bit step). -const FINE_ITERS: usize = 30; -const FINE_OMEGA: f32 = 1.7; - -/// Solve `Δv = 0` on `unknown` pixels with Dirichlet values from the known pixels of `v` -/// (out-of-grid neighbours are ignored, i.e. a Neumann boundary). `v` holds the known values on -/// entry and the solution on exit. Cascadic multigrid + SOR. -pub(crate) fn solve_membrane(w: usize, h: usize, unknown: &[bool], v: &mut [f32]) { - if unknown.len() != w * h || v.len() != w * h { - return; - } - solve_rec(w, h, unknown, v, 0, &|| false); -} - -fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize, stop: &(dyn Fn() -> bool + Sync)) { - if stop() { - return; - } - let n_unknown = unknown.iter().filter(|u| **u).count(); - if n_unknown == 0 { - return; - } - let known: Vec = v.iter().zip(unknown).filter(|(_, u)| !**u).map(|(x, _)| *x).collect(); - if known.is_empty() { - return; // nothing to interpolate from - } - if w >= 8 && h >= 8 && n_unknown > 64 && depth < 16 { - // Restrict: a coarse pixel is known if any of its children is (value = mean of known children). - let (cw, chh) = (w.div_ceil(2), h.div_ceil(2)); - let mut cu = vec![true; cw * chh]; - let mut cv = vec![0.0f32; cw * chh]; - for cy in 0..chh { - for cx in 0..cw { - let (mut s, mut n) = (0.0f32, 0u32); - for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { - let (x, y) = (cx * 2 + dx, cy * 2 + dy); - if x < w && y < h && !unknown[y * w + x] { - s += v[y * w + x]; - n += 1; - } - } - if n > 0 { - cu[cy * cw + cx] = false; - cv[cy * cw + cx] = s / n as f32; - } - } - } - solve_rec(cw, chh, &cu, &mut cv, depth + 1, stop); - // Prolong: bilinear sample of the coarse solution as the initial guess. - for y in 0..h { - let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (chh - 1) as f32); - let y0 = fy.floor() as usize; - let y1 = (y0 + 1).min(chh - 1); - let ty = fy - y0 as f32; - for x in 0..w { - if !unknown[y * w + x] { - continue; - } - let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (cw - 1) as f32); - let x0 = fx.floor() as usize; - let x1 = (x0 + 1).min(cw - 1); - let tx = fx - x0 as f32; - let a = cv[y0 * cw + x0] + (cv[y0 * cw + x1] - cv[y0 * cw + x0]) * tx; - let b = cv[y1 * cw + x0] + (cv[y1 * cw + x1] - cv[y1 * cw + x0]) * tx; - v[y * w + x] = a + (b - a) * ty; - } - } - sor(w, h, unknown, v, FINE_ITERS, FINE_OMEGA, stop); - } else { - let mean = known.iter().sum::() / known.len() as f32; - for (x, u) in v.iter_mut().zip(unknown) { - if *u { - *x = mean; - } - } - sor(w, h, unknown, v, 2000, 1.85, stop); - } -} - -/// SOR sweeps over the unknown pixels until the largest update drops below [`TOL`]. -fn sor(w: usize, h: usize, unknown: &[bool], v: &mut [f32], max_iter: usize, omega: f32, stop: &(dyn Fn() -> bool + Sync)) { - // Precompute the unknown pixels and which neighbours exist. - let cells: Vec<(u32, u8)> = (0..w * h) - .filter(|&i| unknown[i]) - .map(|i| { - let (x, y) = (i % w, i / w); - let m = u8::from(x > 0) | (u8::from(x + 1 < w) << 1) | (u8::from(y > 0) << 2) | (u8::from(y + 1 < h) << 3); - (i as u32, m) - }) - .collect(); - for _ in 0..max_iter { - if stop() { - return; - } - let mut max_d = 0.0f32; - for &(i, m) in &cells { - let i = i as usize; - let (s, n) = if m == 0b1111 { - (v[i - 1] + v[i + 1] + v[i - w] + v[i + w], 4.0) - } else { - let mut s = 0.0; - let mut n = 0.0; - if m & 1 != 0 { - s += v[i - 1]; - n += 1.0; - } - if m & 2 != 0 { - s += v[i + 1]; - n += 1.0; - } - if m & 4 != 0 { - s += v[i - w]; - n += 1.0; - } - if m & 8 != 0 { - s += v[i + w]; - n += 1.0; - } - if n == 0.0 { - continue; - } - (s, n) - }; - let d = omega * (s / n - v[i]); - v[i] += d; - max_d = max_d.max(d.abs()); - } - if max_d < TOL { - break; - } - } -} - -/// Map `f` over the channels of an interleaved buffer as planar slices (parallel on native). -fn per_channel(w: usize, h: usize, ch: usize, f: impl Fn(usize) -> Vec + Sync + Send) -> Vec { - #[cfg(not(target_arch = "wasm32"))] - let planes: Vec> = if w * h >= 64 * 64 { - use rayon::prelude::*; - (0..ch).into_par_iter().map(&f).collect() - } else { - (0..ch).map(&f).collect() - }; - #[cfg(target_arch = "wasm32")] - let planes: Vec> = (0..ch).map(&f).collect(); - let mut out = vec![0.0f32; w * h * ch]; - for (c, p) in planes.iter().enumerate() { - for (i, v) in p.iter().enumerate() { - out[i * ch + c] = *v; - } - } - out -} - -/// Membrane fill (no source texture): harmonic interpolation of the known pixels into `hole`. -/// `img` is interleaved `w × h × ch`, `hole` has `w × h` entries; on a size mismatch `img` comes back -/// unchanged. -pub fn membrane_fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool]) -> Vec { - if Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) { - return img.to_vec(); - } - // no pixels: nothing to fill (and `ch` would otherwise size one plane per channel, whatever it claims) - if hole.is_empty() { - return img.to_vec(); - } - per_channel(w, h, ch, |c| { - let mut v: Vec = (0..w * h).map(|i| if hole[i] { 0.0 } else { img[i * ch + c] }).collect(); - solve_membrane(w, h, hole, &mut v); - v - }) -} -#[cfg(test)] -mod tests { - use super::*; - - fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec { - (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() - } - - #[test] - fn a_zero_area_image_comes_back_unchanged_whatever_its_channel_count() { - assert!(membrane_fill(0, 5, usize::MAX, &[], &[]).is_empty()); - assert!(membrane_fill(3, 0, 1 << 40, &[], &[]).is_empty()); - } - - #[test] - fn membrane_reproduces_linear_boundary() { - // A linear function is harmonic: the solve must reproduce it exactly inside the hole. - let (w, h) = (80, 60); - let unknown = disc(w, h, 40.0, 30.0, 20.0); - let truth: Vec = (0..w * h).map(|i| 0.2 + 0.005 * (i % w) as f32 + 0.003 * (i / w) as f32).collect(); - let mut v: Vec = truth.iter().zip(&unknown).map(|(t, u)| if *u { 0.0 } else { *t }).collect(); - solve_membrane(w, h, &unknown, &mut v); - let err = v.iter().zip(&truth).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); - assert!(err < 2e-3, "{err}"); - } -} diff --git a/crates/inpaint/src/patchmatch.rs b/crates/inpaint/src/patchmatch.rs deleted file mode 100644 index ea69f38d88..0000000000 --- a/crates/inpaint/src/patchmatch.rs +++ /dev/null @@ -1,587 +0,0 @@ -//! Hole filling for Spot Healing: patch-based completion, proximity match and texture synthesis. -//! -//! * [`complete`], content-aware fill: the multi-scale "space-time completion" EM scheme of -//! Y. Wexler, E. Shechtman, M. Irani, *Space-Time Completion of Video*, IEEE TPAMI 2007, with the -//! nearest-neighbour field computed by C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman, -//! *PatchMatch: A Randomized Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009 -//! (random init, propagation, exponentially shrinking random search). Each EM iteration finds, for -//! every patch overlapping the hole, its most similar fully-known patch, then re-estimates hole -//! pixels by a similarity-weighted vote of the overlapping matches. Coarse-to-fine over an image -//! pyramid (the coarsest level is initialised by membrane interpolation), so large holes stay cheap. -//! * [`best_offset`], proximity match: the single displacement whose surrounding ring best matches the -//! ring around the hole (sum of squared differences), i.e. an automatic Healing Brush source. -//! * [`synthesize`], create texture: patch-based texture synthesis in the style of A. Efros, -//! W. Freeman, *Image Quilting for Texture Synthesis and Transfer*, SIGGRAPH 2001 (blocks picked from -//! random candidates by overlap error, feathered overlap instead of a min-cut seam). -//! -//! Ported from PhotoCraft's `algo::inpaint` (MIT OR Apache-2.0); its proximity match and texture -//! synthesis are left out. -//! -//! All functions take interleaved `w × h × ch` normalised floats (any colour model/depth) and a -//! `w × h` hole mask, and return a full buffer equal to the input outside the hole. They are -//! deterministic (fixed-seed hash RNG, results independent of thread count). - -use crate::Cancelled; -use crate::membrane::membrane_fill; - -/// Below this many grid cells a level runs single-threaded (thread hand-off costs more than it saves). -#[cfg(not(target_arch = "wasm32"))] -const PAR_MIN: usize = 128 * 128; - -/// SplitMix64: tiny deterministic RNG. -#[derive(Clone)] -struct Rng(u64); -impl Rng { - fn new(seed: u64) -> Self { - Rng(seed ^ 0x9E37_79B9_7F4A_7C15) - } - fn next(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - /// Uniform integer in `lo..=hi`. - fn range(&mut self, lo: i32, hi: i32) -> i32 { - if hi <= lo { - return lo; - } - lo + (self.next() % (hi - lo + 1) as u64) as i32 - } -} - -/// Parameters for [`complete`]. -#[derive(Clone, Debug, PartialEq)] -pub struct CompleteParams { - /// Patch radius (patches are `2r+1` square). - pub patch_radius: usize, - /// EM iterations at the coarsest level (finer levels use fewer, down to `min_em_iters`). - pub em_iters: usize, - pub min_em_iters: usize, - /// PatchMatch passes per EM iteration. - pub pm_iters: usize, - /// Levels where the hole is wider than this (in that level's pixels) only *refine* the upsampled - /// match field (one local PatchMatch pass and one vote), which keeps big holes tractable: the - /// structure is decided at coarse scale, fine levels just add detail. - pub refine_extent: usize, - pub seed: u64, -} - -impl Default for CompleteParams { - fn default() -> Self { - Self { patch_radius: 3, em_iters: 8, min_em_iters: 2, pm_iters: 2, refine_extent: 96, seed: 1 } - } -} - -/// One pyramid level. -#[derive(Clone)] -struct Level { - w: usize, - h: usize, - img: Vec, - hole: Vec, -} - -fn downsample(l: &Level, ch: usize) -> Level { - let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2)); - let mut img = vec![0.0f32; w * h * ch]; - let mut hole = vec![false; w * h]; - for y in 0..h { - for x in 0..w { - let mut n = 0.0f32; - let o = (y * w + x) * ch; - for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { - let (sx, sy) = (x * 2 + dx, y * 2 + dy); - if sx >= l.w || sy >= l.h { - continue; - } - let si = sy * l.w + sx; - if l.hole[si] { - hole[y * w + x] = true; - } else { - for c in 0..ch { - img[o + c] += l.img[si * ch + c]; - } - n += 1.0; - } - } - if n > 0.0 { - for c in 0..ch { - img[o + c] /= n; - } - } - } - } - Level { w, h, img, hole } -} - -/// Summed-area table of a boolean grid (`(w+1) × (h+1)`). -fn integral(w: usize, h: usize, m: &[bool]) -> Vec { - let mut s = vec![0u32; (w + 1) * (h + 1)]; - for y in 0..h { - let mut row = 0u32; - for x in 0..w { - row += u32::from(m[y * w + x]); - s[(y + 1) * (w + 1) + x + 1] = s[y * (w + 1) + x + 1] + row; - } - } - s -} - -/// Count of set cells in the clipped window `[x0, x1) × [y0, y1)`. -fn window_count(s: &[u32], gw: usize, gh: usize, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 { - let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); - let (x1, y1) = ((x1.max(0) as usize).min(gw), (y1.max(0) as usize).min(gh)); - if x1 <= x0 || y1 <= y0 { - return 0; - } - let w1 = gw + 1; - s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0] -} - -fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize, usize)> { - let mut b: Option<(usize, usize, usize, usize)> = None; - for y in 0..h { - for x in 0..w { - if hole[y * w + x] { - b = Some(match b { - None => (x, y, x + 1, y + 1), - Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)), - }); - } - } - } - b -} - -/// Per-level PatchMatch/EM state. -struct Solver<'a> { - w: usize, - h: usize, - ch: usize, - r: i32, - img: &'a mut Vec, - hole: &'a [bool], - /// Valid source centres: the whole patch is inside the grid and contains no hole pixel. - valid: Vec, - valid_list: Vec<(i32, i32)>, - /// Target centres (patch overlaps the hole), row-major. - targets: Vec, - /// Cancellation: checked per row band; a cancelled solve's output is discarded. - ctl: &'a (dyn Fn() -> bool + Sync), -} - -impl Solver<'_> { - #[inline] - fn is_valid(&self, x: i32, y: i32) -> bool { - x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize] - } - - /// SSD between the (clipped) target patch at `t` and the source patch at `s`, per sample. - fn dist(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { - let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); - let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; - let mut sum = 0.0f32; - let mut n = 0usize; - for dy in -r..=r { - let ty = t.1 + dy; - if ty < 0 || ty >= h { - continue; - } - let sy = s.1 + dy; - for dx in -r..=r { - let tx = t.0 + dx; - if tx < 0 || tx >= w { - continue; - } - let ti = (ty as usize * self.w + tx as usize) * ch; - let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; - for c in 0..ch { - let d = self.img[ti + c] - self.img[si + c]; - sum += d * d; - } - n += ch; - } - // Early out: the mean can only be ≥ sum / (full patch size). - if sum > cutoff * full { - return f32::INFINITY; - } - } - if n == 0 { f32::INFINITY } else { sum / n as f32 } - } - - /// One PatchMatch pass over all target rows, in parallel bands (each band propagates within itself). - fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) { - const BAND: usize = 16; - let w = self.w; - let reverse = pass % 2 == 1; - let band_fn = |bi: usize, nn: &mut [(i32, i32)], co: &mut [f32]| { - if (self.ctl)() { - return; - } - let mut rng = Rng::new(seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40)); - let y0 = bi * BAND; - let rows = nn.len() / w; - let step: i32 = if reverse { -1 } else { 1 }; - for ry in 0..rows { - let ly = if reverse { rows - 1 - ry } else { ry }; - let y = y0 + ly; - for rx in 0..w { - let x = if reverse { w - 1 - rx } else { rx }; - let li = ly * w + x; - if !self.targets[y * w + x] { - continue; - } - let t = (x as i32, y as i32); - let (mut best, mut bc) = (nn[li], co[li]); - // Propagation from the already-visited neighbours (within this band). - let nx = x as i32 - step; - if nx >= 0 && (nx as usize) < w { - let c = nn[ly * w + nx as usize]; - let cand = (c.0 + step, c.1); - if self.is_valid(cand.0, cand.1) && cand != best { - let d = self.dist(t, cand, bc); - if d < bc { - (best, bc) = (cand, d); - } - } - } - let nly = ly as i32 - step; - if nly >= 0 && (nly as usize) < rows { - let c = nn[nly as usize * w + x]; - let cand = (c.0, c.1 + step); - if self.is_valid(cand.0, cand.1) && cand != best { - let d = self.dist(t, cand, bc); - if d < bc { - (best, bc) = (cand, d); - } - } - } - // Random search in exponentially shrinking windows. - let mut rad = search_radius; - while rad >= 1 { - let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad)); - if self.is_valid(cand.0, cand.1) && cand != best { - let d = self.dist(t, cand, bc); - if d < bc { - (best, bc) = (cand, d); - } - } - rad /= 2; - } - nn[li] = best; - co[li] = bc; - } - } - }; - #[cfg(not(target_arch = "wasm32"))] - if w * self.h >= PAR_MIN { - use rayon::prelude::*; - nnf.par_chunks_mut(BAND * w).zip(cost.par_chunks_mut(BAND * w)).enumerate().for_each(|(bi, (nn, co))| band_fn(bi, nn, co)); - return; - } - for (bi, (nn, co)) in nnf.chunks_mut(BAND * w).zip(cost.chunks_mut(BAND * w)).enumerate() { - band_fn(bi, nn, co); - } - } - - /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches. - fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) { - let (w, h, ch, r) = (self.w, self.h, self.ch, self.r); - // σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this). - let mut cs: Vec = cost.iter().zip(&self.targets).filter(|(c, t)| **t && c.is_finite()).map(|(c, _)| *c).collect(); - let sigma2 = if cs.is_empty() { - 1.0 - } else { - let k = (cs.len() * 3 / 4).min(cs.len() - 1); - let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b)); - v.max(1e-6) - }; - let img = &*self.img; - let row = |y: usize| -> Vec<(usize, Vec)> { - let mut out = Vec::new(); - if (self.ctl)() { - return out; - } - for x in 0..w { - if !self.hole[y * w + x] { - continue; - } - let mut acc = vec![0.0f32; ch]; - let mut wsum = 0.0f32; - for dy in -r..=r { - let ty = y as i32 + dy; - if ty < 0 || ty as usize >= h { - continue; - } - for dx in -r..=r { - let tx = x as i32 + dx; - if tx < 0 || tx as usize >= w { - continue; - } - let ti = ty as usize * w + tx as usize; - if !self.targets[ti] || !cost[ti].is_finite() { - continue; - } - let s = nnf[ti]; - let (sx, sy) = (s.0 - dx, s.1 - dy); - let wt = (-cost[ti] / (2.0 * sigma2)).exp().max(1e-8); - let si = (sy as usize * w + sx as usize) * ch; - for c in 0..ch { - acc[c] += img[si + c] * wt; - } - wsum += wt; - } - } - if wsum > 0.0 { - acc.iter_mut().for_each(|v| *v /= wsum); - out.push((x, acc)); - } - } - out - }; - #[cfg(not(target_arch = "wasm32"))] - let rows: Vec)>> = if w * h >= PAR_MIN { - use rayon::prelude::*; - (0..h).into_par_iter().map(row).collect() - } else { - (0..h).map(row).collect() - }; - #[cfg(target_arch = "wasm32")] - let rows: Vec)>> = (0..h).map(row).collect(); - for (y, r) in rows.into_iter().enumerate() { - for (x, v) in r { - self.img[(y * w + x) * ch..(y * w + x + 1) * ch].copy_from_slice(&v); - } - } - } -} - -/// Content-aware completion of `hole` (see module docs). Returns `None` when there is no fully-known -/// patch to copy from (the caller can fall back to [`membrane_fill`]). -pub fn complete(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], p: &CompleteParams) -> Option> { - // Never cancelled, so never `Err`. - complete_with(w, h, ch, img, hole, p, &|| false).unwrap_or(None) -} - -/// [`complete`] that can be cancelled (checked per EM iteration, PatchMatch pass and row band) -/// (`cancelled` is polled per EM iteration, PatchMatch pass and row band): `Err(Cancelled)` once it -/// returned `true`. `Ok(None)` also for mismatched buffer sizes or `ch == 0`. -pub fn complete_with( - w: usize, - h: usize, - ch: usize, - img: &[f32], - hole: &[bool], - p: &CompleteParams, - cancelled: &(dyn Fn() -> bool + Sync), -) -> Result>, Cancelled> { - let check = || if cancelled() { Err(Cancelled) } else { Ok(()) }; - if ch == 0 || Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) { - return Ok(None); - } - let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return Ok(Some(img.to_vec())) }; - let r = p.patch_radius.max(1); - let psz = 2 * r + 1; - // Pyramid: shrink until the hole is a few patches across. - let mut levels = vec![Level { w, h, img: img.to_vec(), hole: hole.to_vec() }]; - let mut ext = (bx1 - bx0).max(by1 - by0); - let mut exts = vec![ext]; - while let Some(l) = levels.last() { - check()?; - if ext <= 2 * psz || l.w / 2 < 3 * psz || l.h / 2 < 3 * psz { - break; - } - let d = downsample(l, ch); - levels.push(d); - ext = ext.div_ceil(2); - exts.push(ext); - } - let nlev = levels.len(); - let mut nnf: Vec<(i32, i32)> = Vec::new(); - let mut prev: Option<(usize, usize, Vec)> = None; - for li in (0..nlev).rev() { - check()?; - let Level { w: lw, h: lh, img: mut limg, hole: lhole } = levels[li].clone(); - // Initialise the hole: membrane at the coarsest level, upsampled result elsewhere. - match &prev { - None => limg = membrane_fill(lw, lh, ch, &limg, &lhole), - Some((pw, ph, pimg)) => { - for y in 0..lh { - for x in 0..lw { - if lhole[y * lw + x] { - let (sx, sy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1)); - let (d, s) = ((y * lw + x) * ch, (sy * pw + sx) * ch); - limg[d..d + ch].copy_from_slice(&pimg[s..s + ch]); - } - } - } - } - } - let ri = r as i32; - let hs = integral(lw, lh, &lhole); - let mut valid = vec![false; lw * lh]; - let mut valid_list = Vec::new(); - let mut targets = vec![false; lw * lh]; - for y in 0..lh as i32 { - if y % 32 == 0 { - check()?; - } - for x in 0..lw as i32 { - let cnt = window_count(&hs, lw, lh, x - ri, y - ri, x + ri + 1, y + ri + 1); - let inside = x >= ri && y >= ri && x + ri < lw as i32 && y + ri < lh as i32; - let i = y as usize * lw + x as usize; - if inside && cnt == 0 { - valid[i] = true; - valid_list.push((x, y)); - } - targets[i] = cnt > 0; - } - } - if valid_list.is_empty() { - if li == 0 { - return Ok(None); - } - prev = Some((lw, lh, limg)); - nnf.clear(); - continue; - } - let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, hole: &lhole, valid, valid_list, targets, ctl: cancelled }; - // NNF init: upsampled from the coarser level where possible, random otherwise. - let mut rng = Rng::new(p.seed ^ (li as u64) << 20); - let pw_prev = prev.as_ref().map_or(0, |p| p.0); - let old = std::mem::take(&mut nnf); - let mut new_nnf = vec![(0i32, 0i32); lw * lh]; - for y in 0..lh { - if y % 32 == 0 { - check()?; - } - for x in 0..lw { - if !solver.targets[y * lw + x] { - continue; - } - let mut cand = None; - if !old.is_empty() && pw_prev > 0 { - let pi = (y / 2) * pw_prev + (x / 2); - if let Some(&(sx, sy)) = old.get(pi) { - let c = (sx * 2 + (x % 2) as i32, sy * 2 + (y % 2) as i32); - if solver.is_valid(c.0, c.1) { - cand = Some(c); - } - } - } - new_nnf[y * lw + x] = cand.unwrap_or_else(|| solver.valid_list[(rng.next() % solver.valid_list.len() as u64) as usize]); - } - } - nnf = new_nnf; - let refine_only = li + 1 < nlev && exts[li] > p.refine_extent; - let em = if li + 1 == nlev { - p.em_iters - } else if refine_only { - 1 - } else { - (p.em_iters >> (nlev - 1 - li)).max(p.min_em_iters) - }; - let pm_iters = if refine_only { 1 } else { p.pm_iters }; - let full_search = (lw.max(lh)) as i32; - let mut cost = vec![f32::INFINITY; lw * lh]; - for it in 0..em { - // Costs change as hole pixels are re-estimated: refresh before each PatchMatch. - for (i, c) in cost.iter_mut().enumerate() { - if i % (lw * 32).max(1) == 0 { - check()?; - } - if solver.targets[i] { - *c = solver.dist(((i % lw) as i32, (i / lw) as i32), nnf[i], f32::INFINITY); - } - } - // Wide random search on coarse levels / first iteration, local refinement afterwards. - let radius = if refine_only { - 2 - } else if li + 1 == nlev || it == 0 { - full_search - } else { - (4 * psz as i32).min(full_search) - }; - for pass in 0..pm_iters { - check()?; - solver.patchmatch(&mut nnf, &mut cost, pass + it * pm_iters, p.seed.wrapping_add((li * 1000 + it) as u64), radius); - } - check()?; - solver.vote(&nnf, &cost); - check()?; - } - prev = Some((lw, lh, limg)); - } - Ok(prev.map(|(_, _, img)| img)) -} - -/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the -/// ring of `ring` pixels around the hole, with the displaced hole fully inside the grid and outside the -#[cfg(test)] -mod tests { - use super::*; - - /// Smooth gradient plus deterministic fine noise. - fn texture(w: usize, h: usize) -> Vec { - let mut rng = Rng::new(7); - (0..w * h) - .flat_map(|i| { - let (x, y) = ((i % w) as f32, (i / w) as f32); - let n = (rng.next() % 1000) as f32 / 1000.0 * 0.04 - 0.02; - [0.3 + 0.004 * x + n, 0.5 + 0.002 * y + n, 0.4 + n] - }) - .collect() - } - - fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec { - (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() - } - - fn hole_rmse(a: &[f32], b: &[f32], hole: &[bool], ch: usize) -> f32 { - let (mut e, mut n) = (0.0f32, 0); - for (i, hh) in hole.iter().enumerate() { - if *hh { - for c in 0..ch { - e += (a[i * ch + c] - b[i * ch + c]).powi(2); - n += 1; - } - } - } - (e / n as f32).sqrt() - } - - #[test] - fn completion_fills_blemish_from_texture() { - let (w, h, ch) = (96, 96, 3); - let clean = texture(w, h); - let hole = disc(w, h, 48.0, 48.0, 9.0); - let mut dirty = clean.clone(); - for (i, hh) in hole.iter().enumerate() { - if *hh { - dirty[i * ch..i * ch + ch].copy_from_slice(&[0.02, 0.02, 0.02]); - } - } - let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); - let before = hole_rmse(&dirty, &clean, &hole, ch); - let after = hole_rmse(&out, &clean, &hole, ch); - assert!(after < 0.06 && after < before * 0.15, "rmse before {before} after {after}"); - // Outside the hole untouched. - assert!(out.iter().zip(&dirty).zip(hole.iter().flat_map(|h| [*h; 3])).all(|((a, b), h)| h || a == b)); - // Deterministic. - assert_eq!(out, complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap()); - } - - #[test] - fn completion_continues_structure() { - // Vertical stripes: the filled hole should keep the stripes (not a blur). - let (w, h, ch) = (80, 80, 1); - let clean: Vec = (0..w * h).map(|i| if (i % w / 4) % 2 == 0 { 0.2 } else { 0.8 }).collect(); - let hole = disc(w, h, 40.0, 40.0, 7.0); - let dirty: Vec = clean.iter().zip(&hole).map(|(c, h)| if *h { 0.5 } else { *c }).collect(); - let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); - let err = hole_rmse(&out, &clean, &hole, ch); - assert!(err < 0.15, "{err}"); - } -} diff --git a/crates/pipeline/Cargo.toml b/crates/pipeline/Cargo.toml index 73aad87339..c68cab6092 100644 --- a/crates/pipeline/Cargo.toml +++ b/crates/pipeline/Cargo.toml @@ -10,7 +10,11 @@ workspace = true [dependencies] craft-cms-profile = { workspace = true } +craft-color = { workspace = true } +craft-color-transform = { workspace = true } craft-develop = { workspace = true } +craft-develop-model = { workspace = true } +craft-geom = { workspace = true } lightcraft-geom = { workspace = true } lightcraft-color = { workspace = true } lightcraft-raster = { workspace = true } diff --git a/crates/pipeline/src/auto.rs b/crates/pipeline/src/auto.rs index f3259b5d99..aa252883f2 100644 --- a/crates/pipeline/src/auto.rs +++ b/crates/pipeline/src/auto.rs @@ -1,303 +1,53 @@ -//! Auto tone (a Lightroom-like recipe, see [`auto_tone`]) and auto white balance (grey-world -//! statistics on a proxy). +//! Auto tone and auto white balance, backed by `craft_develop::auto`. -use lightcraft_color::cct::xy_to_temp_tint; -use lightcraft_color::{REC2020, Xy, bradford, luminance_2020}; use lightcraft_develop::DevelopSettings; use lightcraft_raster::Rgb32f; -use serde::Serialize; use crate::SourceInfo; -use crate::local::effective_wb; -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)] -pub struct AutoTone { - pub exposure: f64, - pub contrast: f64, - pub highlights: f64, - pub shadows: f64, - pub whites: f64, - pub blacks: f64, - pub vibrance: f64, - pub saturation: f64, -} +pub use craft_develop::auto::AutoTone; -/// Exposure in EV that Auto adds per EV of the scene's log-average luminance (the slope is negative: -/// darker scenes get more). The slope is Lightroom's: regressing the Exposure its Auto chose on 24 -/// raw photos against our own [`scene_log_mean`] of each gives -0.41 EV/EV (r = -0.92). -const EXPOSURE_SLOPE: f64 = -0.41; -/// Exposure for a scene whose log-average luminance is middle grey: fitted, with [`CONTRAST`] and -/// [`VIBRANCE`], so our renders match Lightroom's Auto results on those photos (see [`auto_tone`]). -const EXPOSURE_AT_GREY: f64 = -0.58; -/// Highlights and Shadows are Lightroom's own: the average its Auto chose on the 24 photos (our -/// sliders aim at the same as its). Freeing them as well matched no better on held-out photos and -/// left them poorly determined. -const HIGHLIGHTS: f64 = -66.0; -const SHADOWS: f64 = 52.0; -/// Contrast and Vibrance are fitted: our slider scales differ from Lightroom's, and our base tone is -/// flatter, so Contrast is far above its +6. Whites, Blacks and Saturation stay at 0 (Whites and -/// Blacks made no difference to the match; Lightroom leaves Saturation at about 0). -const CONTRAST: f64 = 68.0; -const VIBRANCE: f64 = 30.0; - -/// The scene's log-average luminance under the current white balance, in EV relative to middle grey -/// (the mean of log2(Y / 0.18) over a 512 px proxy, scene-linear, before any tone curve). Pixels that -/// aren't finite (a damaged decode) are left out: they get no weight when the proxy is made, and -/// proxy pixels made only of them are skipped. `None` when no pixel is valid. +/// The scene's log-average luminance under the current white balance, in EV relative to middle grey. pub fn scene_log_mean(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Option { - let (mut clean, mut weight) = (src.clone(), Rgb32f::new(src.width, src.height)); - let mut any = false; - for (p, w) in clean.data.iter_mut().zip(weight.data.iter_mut()) { - if p.iter().all(|v| v.is_finite()) { - *w = [1.0; 3]; - any = true; - } else { - *p = [0.0; 3]; - } - } - if !any { - return None; - } - let fit = |img: &Rgb32f| lightcraft_raster::resample::fit(img, 512, 512, lightcraft_raster::resample::Filter::Box); - let (img, weight) = (fit(&clean), fit(&weight)); - // the mean of the valid pixels under each proxy pixel - let kept: Vec<[f32; 3]> = img.data.iter().zip(&weight.data).filter(|(_, w)| w[0] > 1e-6).map(|(p, w)| p.map(|v| v / w[0])).collect(); - let mut kept = Rgb32f { width: kept.len(), height: 1, data: kept }; - let base = DevelopSettings { wb: s.wb, process: s.process, ..DevelopSettings::default() }; - // (white balance is per pixel: the valid pixels can be balanced in a row of their own) - crate::local::scene_linear_pre(&mut kept, info, &base); - let (mut sum, mut n) = (0f64, 0usize); - for c in &kept.data { - let ev = (luminance_2020(*c).max(1e-6) / 0.18).log2(); - if ev.is_finite() { - sum += ev as f64; - n += 1; - } - } - (n > 0).then(|| sum / n as f64) + craft_develop::auto::scene_log_mean( + &crate::bridge::to_craft_rgb32f(src), + &crate::bridge::to_craft_wb_source(info), + &crate::bridge::to_craft_settings(s), + ) } -/// Auto settings for `src` under the current white balance (ignores current tone values), aiming at -/// what Lightroom's Auto does: the Exposure a scene needs follows its log-average luminance -/// ([`scene_log_mean`], scene-linear, so the rule doesn't depend on the base tone curve), and the -/// other sliders are one fixed recipe. Calibrated black-box against Lightroom's observed behaviour -/// (the values its Auto chose and its exported results) on 24 Sony raw photos, of which 16 have a -/// starting look that Sony's in-camera DRO doesn't brighten. Held out one photo at a time, those 16 -/// come out at a median dE76 of 6.4 from Lightroom's Auto results (8.3 unedited; 18.8 with the -/// previous percentile rule, which ended about 16 L* too bright); all 24 at 7.7 (7.9 unedited). -/// Rendered sources (JPEGs) are already toned, so their log-average reads brighter and Auto changes -/// their exposure less. A source without a single valid pixel gets Exposure 0 (and the rest of the -/// recipe). +/// Auto tone settings for `src`. pub fn auto_tone(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> AutoTone { - let exposure = scene_log_mean(src, info, s).map_or(0.0, |m| (EXPOSURE_AT_GREY + EXPOSURE_SLOPE * m).clamp(-2.0, 3.0)); - AutoTone { - exposure: (exposure * 100.0).round() / 100.0, - contrast: CONTRAST, - highlights: HIGHLIGHTS, - shadows: SHADOWS, - whites: 0.0, - blacks: 0.0, - vibrance: VIBRANCE, - saturation: 0.0, - } + craft_develop::auto::auto_tone( + &crate::bridge::to_craft_rgb32f(src), + &crate::bridge::to_craft_wb_source(info), + &crate::bridge::to_craft_settings(s), + ) } -/// An automatic black & white mix (slider values, red … magenta) for `src` under `s`'s white -/// balance and tone: each hue band's colourful pixels are pushed away from the image's mean -/// lightness — bands brighter than average get brighter, darker ones darker — so areas that -/// differ only in colour stay apart in grey. Bands with almost no colourful pixels stay at 0. +/// Auto B&W mix for `src`. pub fn auto_bw_mix(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> [f64; 8] { - use lightcraft_color::perceptual::{lab_to_lch, oklab_from_2020}; - let mut img = lightcraft_raster::resample::fit(src, 512, 512, lightcraft_raster::resample::Filter::Box); - let base = DevelopSettings { wb: s.wb, light: s.light, process: s.process, ..DevelopSettings::default() }; - crate::local::scene_linear_pre(&mut img, info, &base); - let gain = 2f32.powf(base.light.exposure as f32); - let (mut mass, mut sum_l) = ([0f64; 8], [0f64; 8]); - let (mut all_l, mut n) = (0f64, 0usize); - for p in &img.data { - let lch = lab_to_lch(oklab_from_2020(p.map(|v| (v * gain).max(0.0)))); - all_l += lch[0] as f64; - n += 1; - let k = (lch[1] / 0.2).min(1.0) as f64; // as in the B&W conversion - if k < 0.05 { - continue; - } - let w = crate::colorops::band_weights(lch[2]); - for i in 0..8 { - mass[i] += w[i] as f64 * k; - sum_l[i] += w[i] as f64 * k * lch[0] as f64; - } - } - if n == 0 { - return [0.0; 8]; - } - let mean = all_l / n as f64; - let total: f64 = mass.iter().sum(); - std::array::from_fn(|i| { - if total <= 0.0 || mass[i] / total < 0.01 { - return 0.0; - } - let sep = sum_l[i] / mass[i] - mean; - (sep * 400.0).clamp(-60.0, 60.0).round() - }) + craft_develop::auto::auto_bw_mix( + &crate::bridge::to_craft_rgb32f(src), + &crate::bridge::to_craft_wb_source(info), + &crate::bridge::to_craft_settings(s), + ) } -/// Grey-world white balance weighted towards mid-tone, low-chroma pixels. Returns (temp, tint). +/// Auto white balance `(temp, tint)` for `src`. pub fn auto_wb(src: &Rgb32f, info: &SourceInfo) -> (f64, f64) { - let img = lightcraft_raster::resample::fit(src, 256, 256, lightcraft_raster::resample::Filter::Box); - let (mut acc, mut wsum) = ([0.0f64; 3], 0.0f64); - for c in &img.data { - let y = luminance_2020(*c); - if !(0.01..=2.0).contains(&y) { - continue; - } - let mx = c[0].max(c[1]).max(c[2]); - let mn = c[0].min(c[1]).min(c[2]); - let chroma = (mx - mn) / (mx + 1e-6); - let w = (1.0 - chroma).powi(2) as f64 * (1.0 - ((y.log2() + 2.5) / 4.0).abs().min(1.0)) as f64; - for i in 0..3 { - acc[i] += c[i] as f64 * w; - } - wsum += w; - } - if wsum <= 0.0 { - return (info.as_shot_temp, info.as_shot_tint); - } - let avg = acc.map(|v| v / wsum); - // the white that makes `avg` neutral, through the same model the white balance renders with - // (`local::wb_matrix_for`): the camera's own colour model, else a Bradford adaptation - let camera = info.camera_color.as_deref().filter(|_| info.raw && !info.relative_wb); - let seen = match camera.and_then(|cc| lightcraft_raw::color::neutral_white(&cc.tags, cc.developed_for, avg)) { - Some(white) => white, - None => { - let shot = lightcraft_color::cct::temp_tint_to_xy(info.as_shot_temp, info.as_shot_tint); - Xy::from_xyz(bradford(REC2020.white, shot).apply(REC2020.to_xyz().apply(avg))) - } + let craft_src = crate::bridge::to_craft_rgb32f(src); + let wb_src = crate::bridge::to_craft_wb_source(info); + let neutral = |rgb: [f64; 3]| { + let cc = info.camera_color.as_deref()?; + lightcraft_raw::color::neutral_white(&cc.tags, cc.developed_for, rgb).map(crate::bridge::to_craft_xy) }; - let (t, tint) = xy_to_temp_tint(seen); - (t.clamp(2000.0, 50000.0).round(), tint.clamp(-150.0, 150.0).round()) + let cb: Option<&dyn Fn([f64; 3]) -> Option> = + (info.camera_color.is_some() && info.raw && !info.relative_wb).then_some(&neutral); + craft_develop::auto::auto_wb_with(&craft_src, &wb_src, cb) } -/// Temperature/tint currently in effect (for UI display). +/// Current white balance `(temp, tint)` for `info` and `s`. pub fn current_wb(info: &SourceInfo, s: &DevelopSettings) -> (f64, f64) { - effective_wb(info, s) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn exposure_follows_the_log_average_luminance() { - let flat = |y: f32| Rgb32f::filled(64, 64, [y; 3]); - let auto = |img: &Rgb32f| auto_tone(img, &SourceInfo::default(), &DevelopSettings::default()); - let log_mean = |img: &Rgb32f| scene_log_mean(img, &SourceInfo::default(), &DevelopSettings::default()).unwrap(); - // a scene at middle grey gets the exposure at grey; each EV darker adds 0.41 EV - assert!(log_mean(&flat(0.18)).abs() < 1e-3); - assert_eq!(auto(&flat(0.18)).exposure, -0.58); - assert!((auto(&flat(0.18 / 8.0)).exposure - (-0.58 + 3.0 * 0.41)).abs() < 1e-9); - // darker scenes get more, brighter ones less, within -2..3 EV - let ramp = |lo: f32, step: f32| Rgb32f::from_fn(64, 64, |x, _| [lo + x as f32 * step; 3]); - let (dark, bright) = (auto(&ramp(0.01, 0.0003)), auto(&ramp(0.8, 0.01))); - assert!(dark.exposure > 0.5 && bright.exposure < -1.0, "{dark:?} {bright:?}"); - assert_eq!(auto(&flat(1e-9)).exposure, 3.0); - assert_eq!(auto(&flat(1e6)).exposure, -2.0); - // the rest is one recipe - assert_eq!( - (dark.contrast, dark.highlights, dark.shadows, dark.whites, dark.blacks, dark.vibrance, dark.saturation), - (68.0, -66.0, 52.0, 0.0, 0.0, 30.0, 0.0) - ); - assert_eq!((dark.contrast, dark.shadows), (bright.contrast, bright.shadows)); - } - - #[test] - fn pixels_that_are_not_finite_are_left_out() { - let auto = |img: &Rgb32f| auto_tone(img, &SourceInfo::default(), &DevelopSettings::default()); - // half middle grey, half NaN (or infinite): the grey half alone decides, as if the rest weren't there - for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - let half = Rgb32f::from_fn(64, 64, |x, _| if x < 32 { [0.18; 3] } else { [bad; 3] }); - assert_eq!(auto(&half).exposure, -0.58, "{bad}"); - // also through the resampling of a source larger than the proxy (proxy pixels on the border mix both halves) - let big = Rgb32f::from_fn(1030, 700, |x, _| if x < 515 { [0.045; 3] } else { [bad; 3] }); - assert!((auto(&big).exposure - (-0.58 + 2.0 * 0.41)).abs() < 1e-9, "{bad}"); - // a few broken pixels scattered over a grey image change nothing - let speckled = Rgb32f::from_fn(1030, 700, |x, y| if (x * 7 + y * 13) % 97 == 0 { [bad; 3] } else { [0.18; 3] }); - assert_eq!(auto(&speckled).exposure, -0.58, "{bad}"); - } - // with no valid pixel at all (or none at all) there is nothing to measure: Exposure 0, the recipe as usual - for img in [Rgb32f::filled(8, 8, [f32::NAN; 3]), Rgb32f::filled(600, 600, [f32::INFINITY; 3]), Rgb32f::new(0, 0)] { - let a = auto(&img); - assert_eq!((a.exposure, a.contrast, a.vibrance), (0.0, 68.0, 30.0)); - } - } - - #[test] - fn neutral_image_keeps_as_shot_wb() { - let img = Rgb32f::from_fn(32, 32, |x, y| [0.05 + (x + y) as f32 * 0.004; 3]); - let (t, tint) = auto_wb(&img, &SourceInfo::default()); - assert!((t - 6500.0).abs() < 150.0, "{t}"); - assert!(tint.abs() < 6.0, "{tint}"); - } - - #[test] - fn blue_cast_is_corrected_by_higher_temp() { - // A bluish cast should be neutralised by telling the pipeline the light was bluer (higher K). - let img = Rgb32f::from_fn(32, 32, |_, _| [0.16, 0.18, 0.24]); - let (t, _) = auto_wb(&img, &SourceInfo::default()); - assert!(t > 7000.0, "{t}"); - let mut s = DevelopSettings::default(); - s.wb.mode = lightcraft_develop::WbMode::Custom; - s.wb.temp = t; - let (t2, tint2) = auto_wb(&img, &SourceInfo::default()); - let _ = (t2, tint2); - let mut out = img.clone(); - let (tt, ti) = auto_wb(&img, &SourceInfo::default()); - s.wb.temp = tt; - s.wb.tint = ti; - crate::local::scene_linear_pre(&mut out, &SourceInfo::default(), &s); - let c = out.get(0, 0); - assert!((c[0] - c[2]).abs() < 0.02, "{c:?}"); - } -} - -#[cfg(test)] -mod bw_tests { - use super::*; - - #[test] - fn auto_bw_mix_pushes_light_and_dark_hues_apart() { - // left: a light yellow, right: a dark blue (scene-linear Rec. 2020) - let src = Rgb32f::from_fn(64, 32, |x, _| if x < 32 { [0.55, 0.5, 0.05] } else { [0.01, 0.02, 0.12] }); - let m = auto_bw_mix(&src, &SourceInfo::default(), &DevelopSettings::default()); - let (yellow, blue) = (m[2], m[5]); - assert!(yellow > 0.0 && blue < 0.0, "{m:?}"); - // an image without colour leaves the mix alone - let grey = Rgb32f::from_fn(16, 16, |x, _| [x as f32 / 16.0; 3]); - assert_eq!(auto_bw_mix(&grey, &SourceInfo::default(), &DevelopSettings::default()), [0.0; 8]); - } -} - -#[cfg(test)] -mod tint_tests { - use super::*; - - #[test] - fn auto_wb_and_picker_correct_green_with_positive_tint() { - // The picker delegates a sampled patch to this same auto_wb implementation. - for (rgb, sign) in [([0.18, 0.24, 0.18], 1.0), ([0.24, 0.18, 0.24], -1.0)] { - let img = Rgb32f::filled(16, 16, rgb); - let info = SourceInfo { raw: true, relative_wb: true, ..Default::default() }; - let (temp, tint) = auto_wb(&img, &info); - assert!(tint * sign > 0.0, "{rgb:?}: temp {temp}, tint {tint}"); - let mut s = DevelopSettings::default(); - s.wb.mode = lightcraft_develop::WbMode::Custom; - s.wb.temp = temp; - s.wb.tint = tint; - let mut corrected = img; - crate::local::white_balance(&mut corrected, &info, &s); - let p = corrected.get(0, 0); - let spread = p[0].max(p[1]).max(p[2]) - p[0].min(p[1]).min(p[2]); - assert!(spread < 0.003, "{rgb:?} -> {p:?}"); - } - } + craft_develop::auto::current_wb(&crate::bridge::to_craft_wb_source(info), &crate::bridge::to_craft_settings(s)) } diff --git a/crates/pipeline/src/bridge.rs b/crates/pipeline/src/bridge.rs new file mode 100644 index 0000000000..716f35b4fb --- /dev/null +++ b/crates/pipeline/src/bridge.rs @@ -0,0 +1,395 @@ +//! Adapters between `lightcraft_*` types and `craft_*` types for delegating to `craft_develop`. + +use craft_color_transform::{Mat3 as CraftMat3, Xy as CraftXy}; +use craft_develop::local::{Quality as CraftQuality, WbSource}; +use craft_develop::raster::{Plane as CraftPlane, Rgb32f as CraftRgb32f}; +use craft_develop_model::{ + BwMix, Calibration, ColorAdj, ColorGrading, Detail, DevelopSettings, Effects, Grain, Hsl, Light, LocalAdjustments, Mask, MaskComponent, MaskOp, + MaskShape, Mixer, PointColor, ProcessVersion, Profile, ToneCurve, Treatment, WbMode, WbScale, Wheel, WhiteBalance, +}; +use craft_geom::Point as CraftPoint; +use lightcraft_color::{Mat3, Xy}; +use lightcraft_develop as lc; +use lightcraft_raster::{Plane, Rgb32f}; + +use crate::{Quality, SourceInfo}; + +pub fn to_craft_xy(xy: Xy) -> CraftXy { + CraftXy { x: xy.x, y: xy.y } +} + +pub fn from_craft_xy(xy: CraftXy) -> Xy { + Xy { x: xy.x, y: xy.y } +} + +pub fn to_craft_mat3(m: Mat3) -> CraftMat3 { + CraftMat3(m.0) +} + +pub fn to_craft_quality(q: Quality) -> CraftQuality { + match q { + Quality::Full => CraftQuality::Full, + Quality::Draft => CraftQuality::Draft, + } +} + +pub fn to_craft_wb_source(info: &SourceInfo) -> WbSource { + WbSource { + raw: info.raw, + as_shot_temp: info.as_shot_temp, + as_shot_tint: info.as_shot_tint, + relative_wb: info.relative_wb, + legacy_relative_wb: info.legacy_relative_wb, + } +} + +pub fn to_craft_rgb32f(img: &Rgb32f) -> CraftRgb32f { + CraftRgb32f { width: img.width, height: img.height, data: img.data.clone() } +} + +pub fn take_craft_rgb32f(img: &mut Rgb32f) -> CraftRgb32f { + CraftRgb32f { width: img.width, height: img.height, data: std::mem::take(&mut img.data) } +} + +pub fn put_craft_rgb32f(img: &mut Rgb32f, craft: CraftRgb32f) { + img.width = craft.width; + img.height = craft.height; + img.data = craft.data; +} + +pub fn to_craft_plane(p: &Plane) -> CraftPlane { + CraftPlane { width: p.width, height: p.height, data: p.data.clone() } +} + +pub fn from_craft_plane(p: CraftPlane) -> Plane { + Plane { width: p.width, height: p.height, data: p.data } +} + +pub fn to_craft_treatment(t: lc::Treatment) -> Treatment { + match t { + lc::Treatment::Color => Treatment::Color, + lc::Treatment::Bw => Treatment::Bw, + } +} + +pub fn from_craft_treatment(t: Treatment) -> lc::Treatment { + match t { + Treatment::Color => lc::Treatment::Color, + Treatment::Bw => lc::Treatment::Bw, + } +} + +pub fn to_craft_wb_mode(m: lc::WbMode) -> WbMode { + match m { + lc::WbMode::AsShot => WbMode::AsShot, + lc::WbMode::Auto => WbMode::Auto, + lc::WbMode::Daylight => WbMode::Daylight, + lc::WbMode::Cloudy => WbMode::Cloudy, + lc::WbMode::Shade => WbMode::Shade, + lc::WbMode::Tungsten => WbMode::Tungsten, + lc::WbMode::Fluorescent => WbMode::Fluorescent, + lc::WbMode::Flash => WbMode::Flash, + lc::WbMode::Custom => WbMode::Custom, + } +} + +pub fn from_craft_wb_mode(m: WbMode) -> lc::WbMode { + match m { + WbMode::AsShot => lc::WbMode::AsShot, + WbMode::Auto => lc::WbMode::Auto, + WbMode::Daylight => lc::WbMode::Daylight, + WbMode::Cloudy => lc::WbMode::Cloudy, + WbMode::Shade => lc::WbMode::Shade, + WbMode::Tungsten => lc::WbMode::Tungsten, + WbMode::Fluorescent => lc::WbMode::Fluorescent, + WbMode::Flash => lc::WbMode::Flash, + WbMode::Custom => lc::WbMode::Custom, + } +} + +pub fn to_craft_wb_scale(s: lc::WbScale) -> WbScale { + match s { + lc::WbScale::Legacy => WbScale::Legacy, + lc::WbScale::Kelvin => WbScale::Kelvin, + } +} + +pub fn from_craft_wb_scale(s: WbScale) -> lc::WbScale { + match s { + WbScale::Legacy => lc::WbScale::Legacy, + WbScale::Kelvin => lc::WbScale::Kelvin, + } +} + +fn to_craft_points(pts: &[lightcraft_geom::Point]) -> Vec { + pts.iter().map(|p| CraftPoint::new(p.x, p.y)).collect() +} + +fn from_craft_points(pts: &[CraftPoint]) -> Vec { + pts.iter().map(|p| lightcraft_geom::Point::new(p.x, p.y)).collect() +} + +pub fn to_craft_tone_curve(c: &lc::ToneCurve) -> ToneCurve { + ToneCurve { + highlights: c.highlights, + lights: c.lights, + darks: c.darks, + shadows: c.shadows, + split_shadows: c.split_shadows, + split_mid: c.split_mid, + split_highlights: c.split_highlights, + master: to_craft_points(&c.master), + red: to_craft_points(&c.red), + green: to_craft_points(&c.green), + blue: to_craft_points(&c.blue), + refine_saturation: c.refine_saturation, + } +} + +pub fn from_craft_tone_curve(c: &ToneCurve) -> lc::ToneCurve { + lc::ToneCurve { + highlights: c.highlights, + lights: c.lights, + darks: c.darks, + shadows: c.shadows, + split_shadows: c.split_shadows, + split_mid: c.split_mid, + split_highlights: c.split_highlights, + master: from_craft_points(&c.master), + red: from_craft_points(&c.red), + green: from_craft_points(&c.green), + blue: from_craft_points(&c.blue), + refine_saturation: c.refine_saturation, + } +} + +fn to_craft_hsl(h: lc::Hsl) -> Hsl { + Hsl { hue: h.hue, sat: h.sat, lum: h.lum } +} + +fn from_craft_hsl(h: Hsl) -> lc::Hsl { + lc::Hsl { hue: h.hue, sat: h.sat, lum: h.lum } +} + +fn to_craft_wheel(w: lc::Wheel) -> Wheel { + Wheel { hue: w.hue, sat: w.sat, lum: w.lum } +} + +fn from_craft_wheel(w: Wheel) -> lc::Wheel { + lc::Wheel { hue: w.hue, sat: w.sat, lum: w.lum } +} + +pub fn to_craft_grain(g: &lc::Grain) -> Grain { + Grain { amount: g.amount, size: g.size, roughness: g.roughness, seed: g.seed } +} + +pub fn to_craft_calibration(c: &lc::Calibration) -> Calibration { + Calibration { + shadows_tint: c.shadows_tint, + red_hue: c.red_hue, + red_sat: c.red_sat, + green_hue: c.green_hue, + green_sat: c.green_sat, + blue_hue: c.blue_hue, + blue_sat: c.blue_sat, + } +} + +pub fn from_craft_calibration(c: &Calibration) -> lc::Calibration { + lc::Calibration { + shadows_tint: c.shadows_tint, + red_hue: c.red_hue, + red_sat: c.red_sat, + green_hue: c.green_hue, + green_sat: c.green_sat, + blue_hue: c.blue_hue, + blue_sat: c.blue_sat, + } +} + +pub fn to_craft_point_color(p: &lc::PointColor) -> PointColor { + PointColor { + lum: p.lum, + chroma: p.chroma, + hue: p.hue, + hue_shift: p.hue_shift, + sat_shift: p.sat_shift, + lum_shift: p.lum_shift, + range: p.range, + variance: p.variance, + hue_range: p.hue_range, + lum_range: p.lum_range, + sat_range: p.sat_range, + } +} + +pub fn to_craft_settings(s: &lc::DevelopSettings) -> DevelopSettings { + DevelopSettings { + version: s.version, + process: ProcessVersion(s.process.0), + profile: Profile { id: s.profile.id.clone(), amount: s.profile.amount, camera_local_tone: s.profile.camera_local_tone }, + treatment: to_craft_treatment(s.treatment), + wb: WhiteBalance { mode: to_craft_wb_mode(s.wb.mode), temp: s.wb.temp, tint: s.wb.tint, scale: to_craft_wb_scale(s.wb.scale) }, + light: Light { + exposure: s.light.exposure, + contrast: s.light.contrast, + highlights: s.light.highlights, + shadows: s.light.shadows, + whites: s.light.whites, + blacks: s.light.blacks, + }, + curve: to_craft_tone_curve(&s.curve), + color: ColorAdj { vibrance: s.color.vibrance, saturation: s.color.saturation }, + mixer: Mixer { + red: to_craft_hsl(s.mixer.red), + orange: to_craft_hsl(s.mixer.orange), + yellow: to_craft_hsl(s.mixer.yellow), + green: to_craft_hsl(s.mixer.green), + aqua: to_craft_hsl(s.mixer.aqua), + blue: to_craft_hsl(s.mixer.blue), + purple: to_craft_hsl(s.mixer.purple), + magenta: to_craft_hsl(s.mixer.magenta), + }, + point_colors: s.point_colors.iter().map(to_craft_point_color).collect(), + bw_mix: BwMix { + red: s.bw_mix.red, + orange: s.bw_mix.orange, + yellow: s.bw_mix.yellow, + green: s.bw_mix.green, + aqua: s.bw_mix.aqua, + blue: s.bw_mix.blue, + purple: s.bw_mix.purple, + magenta: s.bw_mix.magenta, + }, + grading: ColorGrading { + shadows: to_craft_wheel(s.grading.shadows), + midtones: to_craft_wheel(s.grading.midtones), + highlights: to_craft_wheel(s.grading.highlights), + global: to_craft_wheel(s.grading.global), + blending: s.grading.blending, + balance: s.grading.balance, + }, + effects: Effects { texture: s.effects.texture, clarity: s.effects.clarity, dehaze: s.effects.dehaze }, + grain: to_craft_grain(&s.grain), + detail: Detail { + sharpen_amount: s.detail.sharpen_amount, + sharpen_radius: s.detail.sharpen_radius, + sharpen_detail: s.detail.sharpen_detail, + sharpen_masking: s.detail.sharpen_masking, + nr_luminance: s.detail.nr_luminance, + nr_detail: s.detail.nr_detail, + nr_contrast: s.detail.nr_contrast, + nr_color: s.detail.nr_color, + nr_color_detail: s.detail.nr_color_detail, + nr_color_smoothness: s.detail.nr_color_smoothness, + nr_outliers: s.detail.nr_outliers, + }, + calibration: to_craft_calibration(&s.calibration), + masks: s + .masks + .iter() + .map(|m| Mask { + id: m.id, + visible: m.visible, + invert: m.invert, + components: if m.components.is_empty() { + Vec::new() + } else { + vec![MaskComponent { + name: None, + op: MaskOp::Add, + invert: false, + shape: MaskShape::Linear { start: CraftPoint::new(0.0, 0.0), end: CraftPoint::new(1.0, 1.0) }, + }] + }, + adjust: LocalAdjustments { + temp: m.adjust.temp, + tint: m.adjust.tint, + exposure: m.adjust.exposure, + contrast: m.adjust.contrast, + highlights: m.adjust.highlights, + shadows: m.adjust.shadows, + whites: m.adjust.whites, + blacks: m.adjust.blacks, + texture: m.adjust.texture, + clarity: m.adjust.clarity, + dehaze: m.adjust.dehaze, + hue: m.adjust.hue, + saturation: m.adjust.saturation, + sharpness: m.adjust.sharpness, + noise: m.adjust.noise, + moire: m.adjust.moire, + defringe: m.adjust.defringe, + lens_blur: m.adjust.lens_blur, + lens_blur_off: m.adjust.lens_blur_off, + lens_blur_outside: m.adjust.lens_blur_outside, + lens_blur_boost: m.adjust.lens_blur_boost, + lens_blur_transition: m.adjust.lens_blur_transition, + color_hue: m.adjust.color_hue, + color_sat: m.adjust.color_sat, + amount: m.adjust.amount, + }, + ..Default::default() + }) + .collect(), + disabled_sections: s.disabled_sections.clone(), + ..Default::default() + } +} + +pub fn apply_craft_profile_fields(dst: &mut lc::DevelopSettings, src: &DevelopSettings) { + dst.treatment = from_craft_treatment(src.treatment); + dst.light = lc::Light { + exposure: src.light.exposure, + contrast: src.light.contrast, + highlights: src.light.highlights, + shadows: src.light.shadows, + whites: src.light.whites, + blacks: src.light.blacks, + }; + dst.curve = from_craft_tone_curve(&src.curve); + dst.color = lc::ColorAdj { vibrance: src.color.vibrance, saturation: src.color.saturation }; + dst.mixer = lc::Mixer { + red: from_craft_hsl(src.mixer.red), + orange: from_craft_hsl(src.mixer.orange), + yellow: from_craft_hsl(src.mixer.yellow), + green: from_craft_hsl(src.mixer.green), + aqua: from_craft_hsl(src.mixer.aqua), + blue: from_craft_hsl(src.mixer.blue), + purple: from_craft_hsl(src.mixer.purple), + magenta: from_craft_hsl(src.mixer.magenta), + }; + dst.bw_mix = lc::BwMix { + red: src.bw_mix.red, + orange: src.bw_mix.orange, + yellow: src.bw_mix.yellow, + green: src.bw_mix.green, + aqua: src.bw_mix.aqua, + blue: src.bw_mix.blue, + purple: src.bw_mix.purple, + magenta: src.bw_mix.magenta, + }; + dst.grading = lc::ColorGrading { + shadows: from_craft_wheel(src.grading.shadows), + midtones: from_craft_wheel(src.grading.midtones), + highlights: from_craft_wheel(src.grading.highlights), + global: from_craft_wheel(src.grading.global), + blending: src.grading.blending, + balance: src.grading.balance, + }; + dst.effects = lc::Effects { texture: src.effects.texture, clarity: src.effects.clarity, dehaze: src.effects.dehaze }; + dst.detail = lc::Detail { + sharpen_amount: src.detail.sharpen_amount, + sharpen_radius: src.detail.sharpen_radius, + sharpen_detail: src.detail.sharpen_detail, + sharpen_masking: src.detail.sharpen_masking, + nr_luminance: src.detail.nr_luminance, + nr_detail: src.detail.nr_detail, + nr_contrast: src.detail.nr_contrast, + nr_color: src.detail.nr_color, + nr_color_detail: src.detail.nr_color_detail, + nr_color_smoothness: src.detail.nr_color_smoothness, + nr_outliers: src.detail.nr_outliers, + }; + dst.calibration = from_craft_calibration(&src.calibration); +} diff --git a/crates/pipeline/src/colorops.rs b/crates/pipeline/src/colorops.rs index ff32779313..21a4e98bd8 100644 --- a/crates/pipeline/src/colorops.rs +++ b/crates/pipeline/src/colorops.rs @@ -1,458 +1,32 @@ -//! Colour tools in OkLCh on display-linear Rec.2020 values: vibrance, saturation, the 8-band colour -//! mixer, B&W mix, and 3-way colour grading; plus the camera-calibration matrix (scene linear). +//! Colour tools in OkLCh on display-linear Rec.2020 values, backed by `craft_develop::colorops`. -use std::f32::consts::{PI, TAU}; -use std::sync::OnceLock; +use std::ops::Deref; -use lightcraft_color::perceptual::{hsv_to_rgb, lab_to_lch, lch_to_lab, oklab_from_2020, oklab_to_2020}; -use lightcraft_color::{Mat3, REC2020, SRGB}; -use lightcraft_develop::{Calibration, DevelopSettings, MIXER_HUES, PointColor}; +use lightcraft_develop::{Calibration, DevelopSettings}; -/// OkLCh hue angle (radians) of a pure sRGB colour with HSV hue `deg`. -pub fn oklch_hue_of_srgb_hue(deg: f64) -> f32 { - let c = hsv_to_rgb(deg as f32, 1.0, 1.0); - let lin = c.map(lightcraft_color::transfer::srgb_to_linear); - let m = SRGB.to_space(&REC2020).apply_f32(lin); - lab_to_lch(oklab_from_2020(m))[2] -} - -/// OkLCh hue (radians) of each colour-mixer band centre. -pub fn band_hues() -> &'static [f32; 8] { - static H: OnceLock<[f32; 8]> = OnceLock::new(); - H.get_or_init(|| MIXER_HUES.map(oklch_hue_of_srgb_hue)) -} - -#[inline] -fn wrap(a: f32) -> f32 { - (a + PI).rem_euclid(TAU) - PI -} - -/// Partition-of-unity weights of hue `h` over the 8 bands (raised cosine between neighbours). -#[inline] -pub fn band_weights(h: f32) -> [f32; 8] { - let hues = band_hues(); - let mut w = [0.0f32; 8]; - for i in 0..8 { - let a = hues[i]; - let b = hues[(i + 1) % 8]; - let span = wrap(b - a).rem_euclid(TAU); - let d = wrap(h - a).rem_euclid(TAU); - if d <= span { - let t = d / span; - let s = 0.5 - 0.5 * (t * PI).cos(); - w[i] += 1.0 - s; - w[(i + 1) % 8] += s; - break; - } - } - w -} - -/// A colour-grading wheel as an OkLab offset (a, b) and a lightness shift. -#[derive(Clone, Copy, Debug)] -pub struct WheelK { - pub a: f32, - pub b: f32, - pub lum: f32, -} - -/// Number of `f32`s per Point Color sample in [`PointK::words`] (the GPU parameter layout). -pub const POINT_WORDS: usize = 10; - -/// A Point Color sample resolved for the per-pixel stage: the sample (OkLab lightness, chroma, hue -/// in radians), the adjustment (hue rotation in radians, chroma scale − 1, lightness shift, -/// variance factor − 1) and the half-widths of the range box (hue radians, chroma, lightness). -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct PointK { - pub l: f32, - pub c: f32, - pub h: f32, - pub dh: f32, - pub sat: f32, - pub dl: f32, - pub var: f32, - pub wh: f32, - pub wc: f32, - pub wl: f32, -} - -impl PointK { - pub fn new(p: &PointColor) -> PointK { - let k = (p.range.clamp(0.0, 100.0) / 50.0).max(0.05) as f32; - let f = |v: f64| (v.clamp(0.0, 100.0) / 100.0) as f32; - PointK { - l: p.lum as f32, - c: p.chroma.max(0.0) as f32, - h: (p.hue as f32).to_radians(), - dh: (p.hue_shift.clamp(-100.0, 100.0) / 100.0) as f32 * 0.5, - sat: (p.sat_shift.clamp(-100.0, 100.0) / 100.0) as f32, - dl: (p.lum_shift.clamp(-100.0, 100.0) / 100.0) as f32 * 0.2, - var: (p.variance.clamp(-100.0, 100.0) / 100.0) as f32 * 0.8, - wh: (0.1 + 0.6 * f(p.hue_range)) * k, - wc: (0.02 + 0.12 * f(p.sat_range)) * k, - wl: (0.05 + 0.4 * f(p.lum_range)) * k, - } - } - - pub fn words(&self) -> [f32; POINT_WORDS] { - [self.l, self.c, self.h, self.dh, self.sat, self.dl, self.var, self.wh, self.wc, self.wl] - } - - /// How much an OkLCh colour belongs to this sample's range (0..1, soft edges). - #[inline] - pub fn weight(&self, l: f32, c: f32, h: f32) -> f32 { - // hue is meaningless for near-neutral colours: a chromatic sample ignores them, a - // near-neutral sample selects by chroma and lightness only - let wh = if self.c < 0.02 { 1.0 } else { (1.0 - smooth(0.5 * self.wh, self.wh, wrap(h - self.h).abs())) * smooth(0.005, 0.025, c) }; - if wh <= 0.0 { - return 0.0; - } - let wc = 1.0 - smooth(0.5 * self.wc, self.wc, (c - self.c).abs()); - let wl = 1.0 - smooth(0.5 * self.wl, self.wl, (l - self.l).abs()); - wh * wc * wl - } - - /// Apply this sample's adjustment to an OkLCh colour. - #[inline] - pub fn apply(&self, lch: [f32; 3]) -> [f32; 3] { - let [mut l, mut c, mut h] = lch; - let w = self.weight(l, c, h); - if w <= 0.0 { - return lch; - } - h += w * (self.var * wrap(h - self.h) + self.dh); - c += w * self.var * (c - self.c); - c = (c * (1.0 + w * self.sat)).max(0.0); - l += w * (self.var * (l - self.l) + self.dl); - [l, c, h] - } -} +pub use craft_develop::colorops::{ + CALIB_HUE, CALIB_SAT, POINT_WORDS, PointK, SHADOW_TINT, WheelK, band_hues, band_weights, calibrate, oklch_hue_of_srgb_hue, +}; /// The colour tools' parameters, resolved once per render (fields are read by the GPU kernel). #[derive(Clone, Debug)] -pub struct ColorOps { - pub vibrance: f32, - pub saturation: f32, - pub hue: [f32; 8], - pub sat: [f32; 8], - pub lum: [f32; 8], - pub mixer: bool, - /// Point Color samples that change something (applied after the mixer). - pub points: Vec, - pub bw: Option<[f32; 8]>, - /// Wheels (shadows, midtones, highlights, global), blending, balance. - pub grading: Option<([WheelK; 4], f32, f32)>, - /// OkLCh hue of skin tones (protected by vibrance). - pub skin: f32, -} +pub struct ColorOps(pub craft_develop::colorops::ColorOps); -fn wheel(w: &lightcraft_develop::Wheel) -> WheelK { - let h = oklch_hue_of_srgb_hue(w.hue); - let s = (w.sat / 100.0) as f32 * 0.09; - WheelK { a: s * h.cos(), b: s * h.sin(), lum: (w.lum / 100.0) as f32 * 0.12 } +impl Deref for ColorOps { + type Target = craft_develop::colorops::ColorOps; + + fn deref(&self) -> &Self::Target { + &self.0 + } } impl ColorOps { pub fn new(s: &DevelopSettings) -> ColorOps { - let bands = s.mixer.bands(); - let g = &s.grading; - ColorOps { - vibrance: (s.color.vibrance / 100.0) as f32, - saturation: (s.color.saturation / 100.0) as f32, - hue: bands.map(|b| (b.hue / 100.0) as f32 * 0.5), - sat: bands.map(|b| (b.sat / 100.0) as f32), - lum: bands.map(|b| (b.lum / 100.0) as f32 * 0.18), - mixer: !s.mixer.is_neutral(), - points: if crate::is_bw(s) { - Vec::new() - } else { - s.point_colors.iter().take(lightcraft_develop::MAX_POINT_COLORS).filter(|p| !p.is_neutral()).map(PointK::new).collect() - }, - bw: crate::is_bw(s).then(|| s.bw_mix.bands().map(|v| (v / 100.0) as f32)), - grading: (!g.is_neutral()).then(|| { - ( - [wheel(&g.shadows), wheel(&g.midtones), wheel(&g.highlights), wheel(&g.global)], - (g.blending / 100.0) as f32, - (g.balance / 100.0) as f32, - ) - }), - skin: oklch_hue_of_srgb_hue(25.0), - } - } - - pub fn is_identity(&self) -> bool { - self.vibrance == 0.0 && self.saturation == 0.0 && !self.mixer && self.points.is_empty() && self.bw.is_none() && self.grading.is_none() - } - - /// `local_sat` (−1..1) and `local_hue` (radians) come from masks. - #[inline] - pub fn apply(&self, rgb: [f32; 3], local_sat: f32, local_hue: f32) -> [f32; 3] { - if self.is_identity() && local_sat == 0.0 && local_hue == 0.0 { - return rgb; - } - let lab = oklab_from_2020(rgb); - // only chroma changes (vibrance / saturation, maybe grading): scale a, b directly — the same - // result as the OkLCh round trip without its sin / cos (and atan2 unless vibrance needs the hue) - if !self.mixer && self.points.is_empty() && self.bw.is_none() && local_hue == 0.0 { - let mut lab = lab; - let c0 = (lab[1] * lab[1] + lab[2] * lab[2]).sqrt(); - let mut c = c0; - if self.vibrance != 0.0 { - let low = 1.0 - (c / 0.22).clamp(0.0, 1.0); - let skin = if self.vibrance > 0.0 { 1.0 - 0.6 * (-(wrap(lab[2].atan2(lab[1]) - self.skin) / 0.35).powi(2)).exp() } else { 1.0 }; - c *= (1.0 + self.vibrance * low * low * skin * 1.2).max(0.0); - } - if self.saturation != 0.0 || local_sat != 0.0 { - c *= (1.0 + self.saturation + local_sat).max(0.0); - } - if c0 > 0.0 { - let k = c / c0; - lab[1] *= k; - lab[2] *= k; - } - return self.grade(lab); - } - let [mut l, mut c, mut h] = lab_to_lch(lab); - if self.mixer { - let w = band_weights(h); - let (mut dh, mut ds, mut dl) = (0.0, 0.0, 0.0); - for i in 0..8 { - dh += w[i] * self.hue[i]; - ds += w[i] * self.sat[i]; - dl += w[i] * self.lum[i]; - } - let chroma_w = (c / 0.12).min(1.0); - h += dh * chroma_w; - c *= (1.0 + ds).max(0.0); - l += dl * chroma_w * l.max(0.05).sqrt(); - } - for p in &self.points { - [l, c, h] = p.apply([l, c, h]); - } - if self.vibrance != 0.0 { - let low = 1.0 - (c / 0.22).clamp(0.0, 1.0); - let skin = if self.vibrance > 0.0 { 1.0 - 0.6 * (-(wrap(h - self.skin) / 0.35).powi(2)).exp() } else { 1.0 }; - c *= (1.0 + self.vibrance * low * low * skin * 1.2).max(0.0); - } - if self.saturation != 0.0 || local_sat != 0.0 { - c *= (1.0 + self.saturation + local_sat).max(0.0); - } - h += local_hue; - if let Some(bw) = &self.bw { - let w = band_weights(h); - let mix: f32 = (0..8).map(|i| w[i] * bw[i]).sum(); - l = (l + mix * (c / 0.2).min(1.0) * 0.25).max(0.0); - c = 0.0; - } - self.grade(lch_to_lab([l, c, h])) - } - - /// Colour grading on OkLab, then back to linear Rec.2020. - #[inline] - fn grade(&self, mut lab: [f32; 3]) -> [f32; 3] { - if let Some((wheels, blending, balance)) = &self.grading { - let m = 0.5 - balance * 0.25; - let width = 0.15 + blending * 0.5; - let ws = 1.0 - smooth(m - width, m + width * 0.25, lab[0]); - let wh = smooth(m - width * 0.25, m + width, lab[0]); - let wm = (1.0 - ws - wh).max(0.0); - for (k, wt) in wheels.iter().zip([ws, wm, wh, 1.0]) { - lab[1] += k.a * wt; - lab[2] += k.b * wt; - lab[0] += k.lum * wt; - } - } - oklab_to_2020(lab) + ColorOps(craft_develop::colorops::ColorOps::new(&crate::bridge::to_craft_settings(s))) } } -/// Hue rotation (OkLCh radians) of a calibration primary at ±100. -pub const CALIB_HUE: f32 = 0.5; -/// Chroma scale of a calibration primary at ±100 (`1 ± CALIB_SAT`). -pub const CALIB_SAT: f32 = 0.6; - -/// The calibration panel's primaries as a white-preserving 3×3 matrix on linear Rec.2020 (row-major): -/// each primary is rotated in OkLCh hue and scaled in chroma at constant OkLab lightness, then the -/// columns are rescaled so that neutral (1, 1, 1) maps to itself. `None` when neutral. +/// The calibration panel's primaries as a white-preserving 3×3 matrix on linear Rec.2020. pub fn calibration_matrix(c: &Calibration) -> Option<[[f32; 3]; 3]> { - let prim = c.primaries(); - if prim.iter().all(|(h, s)| *h == 0.0 && *s == 0.0) { - return None; - } - let mut p = [[0.0f64; 3]; 3]; - for (i, (hue, sat)) in prim.iter().enumerate() { - let mut e = [0.0f32; 3]; - e[i] = 1.0; - let [l, ch, h] = lab_to_lch(oklab_from_2020(e)); - let h2 = h + (hue.clamp(-100.0, 100.0) / 100.0) as f32 * CALIB_HUE; - let c2 = ch * (1.0 + (sat.clamp(-100.0, 100.0) / 100.0) as f32 * CALIB_SAT); - let q = oklab_to_2020(lch_to_lab([l, c2, h2])); - for (r, row) in p.iter_mut().enumerate() { - row[i] = q[r] as f64; - } - } - let m = Mat3(p); - let k = m.inverse()?.apply([1.0, 1.0, 1.0]); - Some(std::array::from_fn(|r| std::array::from_fn(|col| (p[r][col] * k[col]) as f32))) -} - -/// Shadows-tint strength at ±100: the green channel's relative change in deep shadows. -pub const SHADOW_TINT: f32 = 0.3; - -/// Calibration in scene-linear light (before tone mapping): the primaries matrix, then the shadows -/// tint (green ↔ magenta, weighted towards dark tones, luminance kept). -#[inline] -pub fn calibrate(c: [f32; 3], m: Option<&[[f32; 3]; 3]>, shadow_tint: f32) -> [f32; 3] { - let mut c = c; - if let Some(m) = m { - c = std::array::from_fn(|r| (m[r][0] * c[0] + m[r][1] * c[1] + m[r][2] * c[2]).max(0.0)); - } - if shadow_tint != 0.0 { - let y0 = lightcraft_color::luminance_2020(c); - let w = 1.0 - smooth(-5.0, -0.5, (y0.max(1e-7) / 0.18).log2()); - c[1] *= (1.0 - SHADOW_TINT * shadow_tint * w).max(0.0); - let y1 = lightcraft_color::luminance_2020(c).max(1e-9); - c = c.map(|v| v * y0 / y1); - } - c -} - -#[inline] -fn smooth(e0: f32, e1: f32, x: f32) -> f32 { - let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) -} - -#[cfg(test)] -mod tests { - use super::*; - use lightcraft_color::perceptual::lab_to_lch; - - #[test] - fn weights_partition_unity() { - for i in 0..360 { - let h = (i as f32).to_radians() - PI; - let w = band_weights(h); - let s: f32 = w.iter().sum(); - assert!((s - 1.0).abs() < 1e-4, "{i}: {s}"); - } - // at a band centre, that band dominates - let w = band_weights(band_hues()[5]); - assert!(w[5] > 0.99); - } - - #[test] - fn neutral_is_identity() { - let ops = ColorOps::new(&DevelopSettings::default()); - assert!(ops.is_identity()); - assert_eq!(ops.apply([0.2, 0.3, 0.4], 0.0, 0.0), [0.2, 0.3, 0.4]); - } - - #[test] - fn saturation_and_bw() { - let mut s = DevelopSettings::default(); - s.color.saturation = -100.0; - let g = ColorOps::new(&s).apply([0.4, 0.1, 0.05], 0.0, 0.0); - assert!((g[0] - g[1]).abs() < 1e-3 && (g[1] - g[2]).abs() < 1e-3, "{g:?}"); - let mut s = DevelopSettings { treatment: lightcraft_develop::Treatment::Bw, ..Default::default() }; - let ops = ColorOps::new(&s); - let b = ops.apply([0.05, 0.1, 0.5], 0.0, 0.0); - assert!((b[0] - b[2]).abs() < 1e-3); - // raising blue in the B&W mix brightens blue things - s.bw_mix.blue = 80.0; - let b2 = ColorOps::new(&s).apply([0.05, 0.1, 0.5], 0.0, 0.0); - assert!(b2[1] > b[1]); - } - - #[test] - fn mixer_targets_its_band() { - let mut s = DevelopSettings::default(); - s.mixer.blue.sat = -100.0; - let ops = ColorOps::new(&s); - let blue = [0.02, 0.05, 0.4]; - let red = [0.4, 0.03, 0.02]; - let cb = lab_to_lch(oklab_from_2020(ops.apply(blue, 0.0, 0.0)))[1]; - let cr0 = lab_to_lch(oklab_from_2020(red))[1]; - let cr = lab_to_lch(oklab_from_2020(ops.apply(red, 0.0, 0.0)))[1]; - assert!(cb < 0.02, "{cb}"); - assert!((cr - cr0).abs() < 0.01); - } - - #[test] - fn calibration_keeps_white_and_moves_primaries() { - assert!(calibration_matrix(&Calibration::default()).is_none()); - let cal = Calibration { red_hue: 60.0, blue_sat: -50.0, ..Default::default() }; - let m = calibration_matrix(&cal).unwrap(); - let grey = calibrate([0.3, 0.3, 0.3], Some(&m), 0.0); - assert!(grey.iter().all(|v| (v - 0.3).abs() < 1e-4), "{grey:?}"); - // red rotates in hue, blue loses chroma - let red = [0.4, 0.05, 0.03]; - let h0 = lab_to_lch(oklab_from_2020(red))[2]; - let h1 = lab_to_lch(oklab_from_2020(calibrate(red, Some(&m), 0.0)))[2]; - assert!(h1 - h0 > 0.05, "{h0} -> {h1}"); - let blue = [0.03, 0.05, 0.4]; - let c0 = lab_to_lch(oklab_from_2020(blue))[1]; - let c1 = lab_to_lch(oklab_from_2020(calibrate(blue, Some(&m), 0.0)))[1]; - assert!(c1 < c0 * 0.97, "{c0} -> {c1}"); - } - - #[test] - fn shadow_tint_targets_shadows() { - let dark = calibrate([0.01, 0.01, 0.01], None, 1.0); - let bright = calibrate([0.8, 0.8, 0.8], None, 1.0); - assert!(dark[1] < dark[0] * 0.85, "magenta shadows: {dark:?}"); - assert!((bright[1] - bright[0]).abs() < 1e-3, "{bright:?}"); - let y = |c: [f32; 3]| lightcraft_color::luminance_2020(c); - assert!((y(dark) - 0.01).abs() < 1e-5); - let green = calibrate([0.01, 0.01, 0.01], None, -1.0); - assert!(green[1] > green[0]); - } - - #[test] - fn point_color_targets_its_range() { - let skin = [0.35, 0.16, 0.09]; - let [l, c, h] = lab_to_lch(oklab_from_2020(skin)); - let sample = - PointColor { lum: l as f64, chroma: c as f64, hue: (h as f64).to_degrees(), hue_shift: 60.0, sat_shift: -50.0, ..Default::default() }; - let mut s = DevelopSettings::default(); - s.point_colors.push(sample); - let ops = ColorOps::new(&s); - let out = lab_to_lch(oklab_from_2020(ops.apply(skin, 0.0, 0.0))); - assert!(out[1] < c * 0.7, "chroma {c} -> {}", out[1]); - assert!(wrap(out[2] - h) > 0.2, "hue {h} -> {}", out[2]); - // far colours are untouched - for far in [[0.02, 0.05, 0.4], [0.05, 0.3, 0.05], [0.3, 0.3, 0.3]] { - let o = ops.apply(far, 0.0, 0.0); - assert!(far.iter().zip(&o).all(|(a, b)| (a - b).abs() < 1e-4), "{far:?} -> {o:?}"); - } - // weight: 1 at the sample, falling to 0 outside the range; a wider range reaches further - let k = PointK::new(&sample); - assert!((k.weight(l, c, h) - 1.0).abs() < 1e-6); - assert_eq!(k.weight(l, c, h + 1.0), 0.0); - let wide = PointK::new(&PointColor { range: 100.0, ..sample }); - assert!(wide.weight(l, c, h + 0.45) > k.weight(l, c, h + 0.45)); - } - - #[test] - fn point_color_variance_compresses_towards_the_sample() { - let p = PointColor { lum: 0.6, chroma: 0.1, hue: 40.0, variance: -100.0, range: 100.0, ..Default::default() }; - let k = PointK::new(&p); - let (h0, near) = (40f32.to_radians(), 40f32.to_radians() + 0.1); - let o = k.apply([0.62, 0.11, near]); - assert!((o[2] - h0).abs() < 0.1 && (o[1] - 0.1).abs() < 0.01 && (o[0] - 0.6).abs() < 0.02, "{o:?}"); - let k = PointK::new(&PointColor { variance: 100.0, ..p }); - let o = k.apply([0.62, 0.11, near]); - assert!(o[2] - h0 > 0.1, "{o:?}"); - } - - #[test] - fn grading_tints_shadows_only() { - let mut s = DevelopSettings::default(); - s.grading.shadows = lightcraft_develop::Wheel { hue: 220.0, sat: 60.0, lum: 0.0 }; - let ops = ColorOps::new(&s); - let dark = ops.apply([0.01, 0.01, 0.01], 0.0, 0.0); - let bright = ops.apply([0.8, 0.8, 0.8], 0.0, 0.0); - assert!(dark[2] > dark[0]); - assert!((bright[2] - bright[0]).abs() < 0.02); - } + craft_develop::colorops::calibration_matrix(&crate::bridge::to_craft_calibration(c)) } diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index 325329d3ff..21f2cf59cc 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -1,803 +1,10 @@ -//! Crystal-layer film grain, the grain of process V7 and later ([`crate::finish::GrainModel`]). -//! -//! After the model of Aurélien Pierre, *Stochastic photographic grain synthesis from -//! crystallographic structure simulation* (2023), implemented from the article's description of -//! the method; no code was taken from it or from any implementation. `docs/grain.md` has the -//! method, the calibration and the measurements. -//! -//! - **Emulsion.** A stack of layers. Each layer has one crystal shape (a regular polygon of 3–8 -//! vertices, a random rotation, a log-normal width) and is a Boolean model: Poisson seeds grown -//! into crystals, at the density that leaves half the layer covered ([`FILLING`]). -//! - **Capture.** A point's grain is the number of layers covering it, less its mean: many -//! independent layers of different crystal sizes give dense, soft, cloudy grain. -//! - **Print.** The light a point captures is proportional to the light falling on it, and the -//! print shows less grain towards paper white: the grain is `Y·(1 − Y)` in linear light, so -//! it fades out at black and at white. It is added in the display-encoded domain (first order), -//! where it is symmetric: it neither darkens shadows nor greys blown highlights. -//! -//! **Resolution independence.** The emulsion is drawn once per setting on two periodic tiles -//! (tori) in frame coordinates, at twice the resolution of a 6000 px export ([`PITCH`]). Each -//! output pixel takes the exact mean of the emulsion under its footprint from the tiles' summed -//! area tables (a rotated frame's pixel: of an axis-aligned square of its size), so a preview -//! shows exactly the export's grain box-downscaled to its size, and an -//! export larger than 6000 px still has crystals rather than enlarged pixels. The layers are -//! split between two tori of different sizes ([`TORI`]); their pattern only repeats as a whole -//! after tens of thousands of pixels. -//! -//! **Cost.** Drawing the tiles takes a few milliseconds and is cached per setting -//! ([`CrystalGrain::new`]); a pixel then costs two box sums (16 table reads), on the CPU and in the -//! GPU kernel (`finish.wgsl`, which reads the same tables). +//! Crystal-layer film grain, backed by `craft_develop::crystal`. -use std::f64::consts::TAU; -use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError}; +use std::sync::Arc; -use lightcraft_color::transfer::srgb_to_linear; use lightcraft_develop::Grain; -use lightcraft_raster::par_rows; -/// Long edge (output pixels) at which grain sizes and strengths are specified: a 24 MP export. -pub const REF_LONG: f64 = 6000.0; -/// Size of a tile pixel in reference pixels: tiles are drawn at twice the reference resolution. -pub const PITCH: f64 = 0.5; -/// Tile pixels per long edge of the frame. -pub const TILE_PER_LONG: f64 = REF_LONG / PITCH; -/// Sides of the two tori (tile pixels: 640 and 567 reference pixels). Layers alternate between -/// them; the sizes share no small factor, so the sum repeats only after 362,880 reference pixels. -pub const TORI: [usize; 2] = [1280, 1134]; -/// Fraction of each layer covered by its crystals. -pub const FILLING: f64 = 0.5; -/// Rows per band when drawing a tile (each band is drawn in parallel). -const BAND: usize = 64; -/// Encoded luminance at which the strength is specified (mid grey, 128 of 255). -const MID_GREY: f32 = 128.0 / 255.0; -/// A footprint this large (tile pixels: a render 24 px long or less) gets no grain. -const MAX_FOOTPRINT: f32 = 500.0; -/// Settings whose tiles are kept (a preview and an export, a few thumbnails). -const CACHE: usize = 4; - -/// The look of a grain setting: what the tiles are drawn from. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct CrystalLook { - /// Median crystal width (circumscribed diameter, reference pixels). - pub width: f64, - /// Log standard deviation of the layers' crystal widths. - pub spread: f64, - /// Number of layers. - pub layers: usize, -} - -/// Piecewise-linear interpolation through `(x, y)` knots sorted by `x`, constant outside them. -fn interp(knots: &[(f64, f64)], x: f64) -> f64 { - let (Some(first), Some(last)) = (knots.first(), knots.last()) else { return 0.0 }; - if x <= first.0 { - return first.1; - } - for w in knots.windows(2) { - if let [(x0, y0), (x1, y1)] = *w - && x <= x1 - { - return y0 + (y1 - y0) * (x - x0) / (x1 - x0).max(1e-9); - } - } - last.1 -} - -/// Median crystal width at Roughness 50 by Size (reference pixels), fitted so the grain's width -/// matches Lightroom Classic's (`fit_widths`, `docs/grain.md`). Size 0 is as fine as the model -/// gets: crystals narrower than a pixel, uncorrelated pixels. -const WIDTH_BY_SIZE: [(f64, f64); 6] = [(0.0, 0.55), (10.0, 1.39), (25.0, 2.95), (50.0, 5.17), (75.0, 8.78), (100.0, 12.38)]; -/// Width factor by Roughness. -const WIDTH_BY_ROUGHNESS: [(f64, f64); 3] = [(0.0, 0.734), (50.0, 1.0), (100.0, 1.422)]; -/// Layers by Size: coarser grain averages more layers, so it stays a soft clump texture. -const LAYERS_BY_SIZE: [(f64, f64); 4] = [(0.0, 16.0), (25.0, 31.0), (50.0, 54.0), (100.0, 70.0)]; - -/// Log-width spread every look has on top of Roughness's. The look the tables were chosen from (a -/// prototype on whole-pixel crystals, `docs/grain.md`) rounded crystal widths to whole pixels, -/// which spreads their sizes by about this much; with it, the anti-aliased crystals here have the -/// prototype's texture at every scale, not just its width. -const SPREAD_FLOOR: f64 = 0.45; - -/// A slider value as a number in `0..=100`; `fallback` for NaN. -fn slider(v: f64, fallback: f64) -> f64 { - if v.is_nan() { fallback } else { v.clamp(0.0, 100.0) } -} - -impl CrystalLook { - pub fn new(size: f64, roughness: f64) -> CrystalLook { - let (s, r) = (slider(size, 25.0), slider(roughness, 50.0)); - CrystalLook { - width: interp(&WIDTH_BY_SIZE, s) * interp(&WIDTH_BY_ROUGHNESS, r), - spread: (0.1 + 0.6 * r / 100.0).hypot(SPREAD_FLOOR), - layers: interp(&LAYERS_BY_SIZE, s).round().clamp(2.0, 120.0) as usize, - } - } -} - -/// Grain strength (8-bit levels at mid grey on a 6000 px export) for Amount, Size and Roughness, -/// measured on Lightroom Classic exports (the fit of open PR #1060's `docs/grain.md`). -pub fn strength_levels(amount: f64, size: f64, roughness: f64) -> f64 { - let (s, d) = (slider(size, 25.0), slider(roughness, 50.0) / 100.0 - 0.5); - slider(amount, 0.0) / 100.0 * (2.447 + 1.386 * (-s / 19.88).exp()).exp() * (1.0 - 0.084 * d + 1.6384 * d * d) -} - -// ---- hashing - -#[inline] -fn mix(mut x: u32) -> u32 { - x ^= x >> 16; - x = x.wrapping_mul(0x7feb_352d); - x ^= x >> 15; - x = x.wrapping_mul(0x846c_a68b); - x ^ (x >> 16) -} - -#[inline] -fn hash(a: u32, b: u32, c: u32, d: u32) -> u32 { - mix(mix(mix(mix(a ^ 0x9e37_79b9) ^ b) ^ c.wrapping_mul(0x85eb_ca6b)) ^ d.wrapping_mul(0xc2b2_ae35)) -} - -/// A hash as a number in (0, 1]. -#[inline] -fn unit(h: u32) -> f64 { - (h as f64 + 0.5) / 4_294_967_296.0 -} - -/// The standard normal quantile of `p` in (0, 1) (Acklam's rational approximation, ~1e-9). -fn normal_quantile(p: f64) -> f64 { - const A: [f64; 6] = - [-39.696_830_286_653_76, 220.946_098_424_520_5, -275.928_510_446_968_7, 138.357_751_867_269, -30.664_798_066_147_16, 2.506_628_277_459_239]; - const B: [f64; 5] = [-54.476_098_798_224_06, 161.585_836_858_040_9, -155.698_979_859_886_6, 66.801_311_887_719_72, -13.280_681_552_885_72]; - const C: [f64; 6] = [ - -0.007_784_894_002_430_293, - -0.322_396_458_041_136_5, - -2.400_758_277_161_838, - -2.549_732_539_343_734, - 4.374_664_141_464_968, - 2.938_163_982_698_783, - ]; - const D: [f64; 4] = [0.007_784_695_709_041_462, 0.322_467_129_070_039_8, 2.445_134_137_142_996, 3.754_408_661_907_416]; - let p = p.clamp(1e-12, 1.0 - 1e-12); - let tail = - |q: f64| (((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5]) / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0); - if p < 0.024_25 { - tail((-2.0 * p.ln()).sqrt()) - } else if p > 1.0 - 0.024_25 { - -tail((-2.0 * (1.0 - p).ln()).sqrt()) - } else { - let q = p - 0.5; - let r = q * q; - (((((A[0] * r + A[1]) * r + A[2]) * r + A[3]) * r + A[4]) * r + A[5]) * q - / (((((B[0] * r + B[1]) * r + B[2]) * r + B[3]) * r + B[4]) * r + 1.0) - } -} - -/// The emulsion's layers. Their crystal widths are the `layers` quantiles of the log-normal -/// width distribution, dealt to the layers in an order the seed shuffles: every seed has the same -/// mix of sizes (so the same grain width and strength), in a different arrangement. -fn emulsion(seed: u32, look: &CrystalLook) -> Vec { - let n = look.layers.max(1); - let mut order: Vec<(u32, usize)> = (0..n).map(|l| (hash(seed, l as u32, 0x5047, 0), l)).collect(); - order.sort_unstable(); - let mut rank = vec![0usize; n]; - for (r, &(_, l)) in order.iter().enumerate() { - if let Some(slot) = rank.get_mut(l) { - *slot = r; - } - } - (0..n).map(|l| Layer::new(seed, l as u32, look, normal_quantile((rank.get(l).copied().unwrap_or(0) as f64 + 0.5) / n as f64))).collect() -} - -fn normal(h1: u32, h2: u32) -> f64 { - (-2.0 * unit(h1).ln()).sqrt() * (TAU * unit(h2)).cos() -} - -/// The cumulative distribution of a Poisson count of mean `mu`, up to where it reaches 1 (at -/// most 512 entries; `mu` stays below ~150 here). -fn poisson_cdf(mu: f64) -> Vec { - let mut cdf = Vec::new(); - let mut p = (-mu).exp(); - let mut cum = p; - for k in 1..512u32 { - cdf.push(cum); - if cum >= 1.0 - 1e-12 { - break; - } - p *= mu / k as f64; - cum += p; - } - cdf -} - -/// A Poisson count drawn from its `cdf` by hash `h`. -#[inline] -fn poisson(cdf: &[f64], h: u32) -> usize { - let u = unit(h); - cdf.partition_point(|&c| c < u) -} - -// ---- one layer - -/// A stream of hashes: a Weyl sequence through [`mix`]. -struct Stream(u32); - -impl Stream { - #[inline] - fn next(&mut self) -> u32 { - self.0 = self.0.wrapping_add(0x9e37_79b9); - mix(self.0) - } -} - -/// Sub-pixel positions a crystal centre is rounded to, per axis, when drawn from its [`Stamp`]. -const PHASES: usize = 16; -/// Crystals up to this circumradius (tile pixels) are drawn from a stamp. -const STAMP_R: f64 = 16.0; - -/// A layer's crystal rasterised at every sub-pixel phase of its centre: for a centre at -/// `(X + qx/PHASES, Y + qy/PHASES)` (`X`, `Y` integers) it covers rows `Y + rows[qy].0 ..= Y + -/// rows[qy].1`, and in row `Y + rows[qy].0 + k` the pixels `X + o.0 ..= X + o.1`, with -/// `o = spans[(qy·PHASES + qx)·height + k]`. -/// -/// The same rows as bit masks, for drawing a crystal without a branch per row: phase -/// `p = qy·PHASES + qx` spans pixels `X + extent[p].0 ..= X + extent[p].1`, and its row `k` is -/// `masks[p·height + k]` shifted to `X + extent[p].0` (rows past the phase's own are empty). -/// `masks` is empty when a phase is wider than 64 pixels. -#[derive(Clone, Debug)] -struct Stamp { - rows: [(i32, i32); PHASES], - height: usize, - spans: Vec<(i32, i32)>, - extent: Vec<(i32, i32)>, - masks: Vec, -} - -/// Where [`Layer::draw`] draws: rows `y0..y0 + rows` of a torus of side `t`, `w` words per row, -/// after `margin` scratch rows. -#[derive(Clone, Copy)] -struct Band { - t: usize, - y0: usize, - rows: usize, - w: usize, - margin: usize, -} - -/// One emulsion layer: its crystal (a regular polygon) and seed density, in tile pixels. -#[derive(Clone, Debug)] -struct Layer { - /// The crystal as half-planes, relative to its centre: `x ≥ a + s·y` for each `(a, s)` of - /// `left` (`nl` used), `x ≤ a + s·y` for `right` (`nr` used), `y0 ≤ y ≤ y1`. - left: [(f64, f64); 8], - right: [(f64, f64); 8], - nl: usize, - nr: usize, - y0: f64, - y1: f64, - /// Circumradius. - r: f64, - /// Seeds per tile pixel. - lambda: f64, - seed: u32, - index: u32, - stamp: Option, -} - -/// Crystals narrower than this (tile pixels) cover at most two neighbouring pixel centres: their -/// layer is drawn as independent pixels. -const FINE: f64 = 1.5; - -impl Layer { - /// Layer `index` of the emulsion of `seed`, its crystal width `z` log standard deviations - /// from the median. - fn new(seed: u32, index: u32, look: &CrystalLook, z: f64) -> Layer { - let h = |k: u32| hash(seed, index, k, 0x51ed); - let n = (4.5 + normal(h(1), h(2))).round().clamp(3.0, 8.0) as usize; - let rot = TAU * unit(h(3)); - let width = look.width.max(0.05) * (look.spread * z.clamp(-2.5, 2.5)).exp(); - let r = width / 2.0 / PITCH; - let vert = |k: usize| { - let a = rot + TAU * k as f64 / n as f64; - (r * a.cos(), r * a.sin()) - }; - let mut layer = Layer { - left: [(0.0, 0.0); 8], - right: [(0.0, 0.0); 8], - nl: 0, - nr: 0, - y0: f64::INFINITY, - y1: f64::NEG_INFINITY, - r, - lambda: -(1.0 - FILLING).ln() / (0.5 * n as f64 * r * r * (TAU / n as f64).sin()).max(1e-9), - seed, - index, - stamp: None, - }; - for k in 0..n { - let ((x0, y0), (x1, y1)) = (vert(k), vert(k + 1)); - layer.y0 = layer.y0.min(y0); - layer.y1 = layer.y1.max(y0); - let dy = y1 - y0; - if dy.abs() < 1e-12 { - continue; - } - // counter-clockwise: the inside is left of each edge - let sl = (x1 - x0) / dy; - let line = (x0 - sl * y0, sl); - if dy > 0.0 { - if let Some(slot) = layer.right.get_mut(layer.nr) { - *slot = line; - layer.nr += 1; - } - } else if let Some(slot) = layer.left.get_mut(layer.nl) { - *slot = line; - layer.nl += 1; - } - } - if r <= STAMP_R && 2.0 * r >= FINE { - layer.stamp = Some(layer.stamp()); - } - layer - } - - fn stamp(&self) -> Stamp { - let q = PHASES as f64; - let mut rows = [(0, -1); PHASES]; - for (qy, r) in rows.iter_mut().enumerate() { - let g = qy as f64 / q; - *r = ((g + self.y0 - 0.5).ceil() as i32, (g + self.y1 - 0.5).floor() as i32); - } - let height = rows.iter().map(|(a, b)| (b - a + 1).max(0) as usize).max().unwrap_or(0); - let mut spans = vec![(0, -1); PHASES * PHASES * height]; - for (qy, &(a, b)) in rows.iter().enumerate() { - for k in 0..(b - a + 1).max(0) { - let (xl, xr) = self.span((a + k) as f64 + 0.5 - qy as f64 / q); - for qx in 0..PHASES { - let f = qx as f64 / q; - if let Some(o) = spans.get_mut((qy * PHASES + qx) * height + k as usize) { - *o = ((f + xl - 0.5).ceil() as i32, (f + xr - 0.5).floor() as i32); - } - } - } - } - let mut extent = vec![(0, -1); PHASES * PHASES]; - let mut masks = vec![0u64; PHASES * PHASES * height]; - let mut fits = true; - for (p, e) in extent.iter_mut().enumerate() { - let Some(rows) = spans.get(p * height..(p + 1) * height) else { continue }; - let used = || rows.iter().filter(|(o0, o1)| o0 <= o1); - let (Some(lo), Some(hi)) = (used().map(|o| o.0).min(), used().map(|o| o.1).max()) else { continue }; - *e = (lo, hi); - fits &= hi - lo < 64; - for (m, &(o0, o1)) in masks.iter_mut().skip(p * height).zip(rows) { - if o0 <= o1 && o1 - lo < 64 { - *m = (!0u64 >> (63 - (o1 - o0))) << (o0 - lo); - } - } - } - if !fits { - masks.clear(); - } - Stamp { rows, height, spans, extent, masks } - } - - /// The crystal's horizontal extent at height `y` above its centre (convex: one interval). - #[inline] - fn span(&self, y: f64) -> (f64, f64) { - let lo = self.left.iter().take(self.nl).fold(f64::NEG_INFINITY, |m, &(a, s)| m.max(a + s * y)); - let hi = self.right.iter().take(self.nr).fold(f64::INFINITY, |m, &(a, s)| m.min(a + s * y)); - (lo, hi) - } - - /// Sets the bits of the pixels the layer covers in rows `y0..` of a torus of side `t`: - /// `cover` holds whole rows of `w` words (bit `i % 64` of word `i / 64` is pixel `i`), the - /// band's rows between `margin` rows above and below it (scratch: what lands there is not part - /// of the band; `margin` is at least the stamp's height). - fn draw(&self, t: usize, y0: usize, w: usize, margin: usize, cover: &mut [u64]) { - let rows = (cover.len() / w.max(1)).saturating_sub(2 * margin); - if 2.0 * self.r < FINE { - // each pixel covered with probability FILLING (one half: one random bit) - for (j, row) in cover.chunks_mut(w.max(1)).skip(margin).take(rows).enumerate() { - let mut bits = Stream(hash(self.seed, self.index, (y0 + j) as u32, 0xb175)); - for v in row.iter_mut() { - *v = bits.next() as u64 | (bits.next() as u64) << 32; - } - if let (Some(last), r @ 1..=63) = (row.last_mut(), t % 64) { - *last &= (1u64 << r) - 1; - } - } - return; - } - let tf = t as f64; - let m = (tf / (4.0 * self.r).max(16.0)).floor().clamp(1.0, tf) as i64; - let c = tf / m as f64; - let cdf = poisson_cdf(self.lambda * c * c); - let (lo, hi) = (y0 as f64 - self.r - 1.0, (y0 + rows) as f64 + self.r + 1.0); - for cy in (lo / c).floor() as i64..=(hi / c).floor() as i64 { - let wy = cy.rem_euclid(m) as u32; - for cx in 0..m { - let mut h = Stream(hash(self.seed ^ (self.index << 20), cx as u32, wy, 0xce11)); - for _ in 0..poisson(&cdf, h.next()) { - let (u, v) = (unit(h.next()), unit(h.next())); - self.splat((cx as f64 + u) * c, (cy as f64 + v) * c, Band { t, y0, rows, w, margin }, cover); - } - } - } - } - - /// Marks the pixels whose centres the crystal at (`px`, `py`) covers (see [`Self::draw`]). - #[inline] - fn splat(&self, px: f64, py: f64, band: Band, cover: &mut [u64]) { - let Band { t, y0, rows, w, margin } = band; - if let Some(st) = &self.stamp { - let (bx, by) = (px.floor(), py.floor()); - let (qx, qy) = ((((px - bx) * PHASES as f64) as usize).min(PHASES - 1), (((py - by) * PHASES as f64) as usize).min(PHASES - 1)); - let (bx, by) = (bx as i64, by as i64); - let Some(&(a, b)) = st.rows.get(qy) else { return }; - let (lo, hi) = ((by + a as i64).max(y0 as i64), (by + b as i64).min((y0 + rows) as i64 - 1)); - if hi < lo { - return; - } - // within the torus across: the whole stamp, a fixed number of rows of masks (those - // above or below the band land in the margins) - let p = qy * PHASES + qx; - if let (Some(&(e0, e1)), Some(masks)) = (st.extent.get(p), st.masks.get(p * st.height..(p + 1) * st.height)) { - let (xs, top) = (bx + e0 as i64, by + a as i64 - y0 as i64 + margin as i64); - if xs >= 0 && bx + (e1 as i64) < t as i64 && top >= 0 { - let (word, shift) = ((xs >> 6) as usize, (xs & 63) as u32); - // a bit past the row's last word would be a pixel ≥ t: the high word is then 0 - let start = top as usize * w + word; - for (k, &m) in masks.iter().enumerate() { - let v = (m as u128) << shift; - let i = start + k * w; - if let Some(c) = cover.get_mut(i) { - *c |= v as u64; - } - if let Some(c) = cover.get_mut(i + 1) { - *c |= (v >> 64) as u64; - } - } - return; - } - } - // rows `lo..=hi` of the band, spans `k0..` of the stamp's rows (`hi ≤ by + b`: within its height) - let (k0, n) = ((lo - by - a as i64) as usize, (hi - lo + 1) as usize); - let base = (qy * PHASES + qx) * st.height + k0; - let (r0, r1) = (lo as usize - y0 + margin, hi as usize + 1 - y0 + margin); - let (Some(spans), Some(band)) = (st.spans.get(base..base + n), cover.get_mut(r0 * w..r1 * w)) else { return }; - for (row, &(o0, o1)) in band.chunks_exact_mut(w.max(1)).zip(spans) { - if o0 <= o1 { - set_wrapped(row, t, bx + o0 as i64, bx + o1 as i64); - } - } - return; - } - let first = (py + self.y0 - 0.5).ceil().max(y0 as f64); - let last = (py + self.y1 - 0.5).floor().min((y0 + rows) as f64 - 1.0); - if last < first { - return; - } - for j in first as usize..=last as usize { - let (xl, xr) = self.span(j as f64 + 0.5 - py); - let (i0, i1) = ((px + xl - 0.5).ceil() as i64, (px + xr - 0.5).floor() as i64); - if i1 < i0 { - continue; - } - let Some(row) = cover.get_mut((j - y0 + margin) * w..(j - y0 + margin + 1) * w) else { continue }; - set_wrapped(row, t, i0, i1); - } - } -} - -/// Sets bits `a..=b` (`a ≤ b`) of a row of words. -#[inline] -fn set_bits(row: &mut [u64], a: usize, b: usize) { - let (wa, wb) = (a >> 6, b >> 6); - let (lo, hi) = (!0u64 << (a & 63), !0u64 >> (63 - (b & 63))); - if wa == wb { - if let Some(v) = row.get_mut(wa) { - *v |= lo & hi; - } - return; - } - if let Some(v) = row.get_mut(wa) { - *v |= lo; - } - for v in row.iter_mut().take(wb).skip(wa + 1) { - *v = !0; - } - if let Some(v) = row.get_mut(wb) { - *v |= hi; - } -} - -/// Sets pixels `i0..=i1` of a periodic row of `t` pixels (`i0 ≤ i1`, within one period of -/// `0..t`: the crystal centres are in `0..t`). -#[inline] -fn set_wrapped(row: &mut [u64], t: usize, i0: i64, i1: i64) { - let ti = t as i64; - if i0 >= 0 && i1 < ti { - set_bits(row, i0 as usize, i1 as usize); - return; - } - if t == 0 { - return; - } - if i1 - i0 + 1 >= ti { - set_bits(row, 0, t - 1); - return; - } - let (a, b) = if i0 < 0 { - (i0 + ti, i1 + ti) - } else if i0 >= ti { - (i0 - ti, i1 - ti) - } else { - (i0, i1) - }; - let (a, b) = (a.clamp(0, ti - 1) as usize, b.max(0) as usize); - if b < t { - set_bits(row, a, b); - } else { - set_bits(row, a, t - 1); - set_bits(row, 0, (b - t).min(t - 1)); - } -} - -/// Bit planes of the layer counts (enough for 127 layers per torus). -const PLANES: usize = 7; - -/// Adds one layer's `cover` bits to the bit-sliced counters `planes` (`PLANES × cover.len()`). -#[inline] -fn add_layer(planes: &mut [u64], cover: &[u64]) { - let n = cover.len(); - for (i, &c) in cover.iter().enumerate() { - let mut carry = c; - for p in 0..PLANES { - if carry == 0 { - break; - } - let Some(slot) = planes.get_mut(p * n + i) else { break }; - let s = *slot; - *slot = s ^ carry; - carry &= s; - } - } -} - -// ---- tiles - -/// The emulsion drawn on the two tori: each as a summed-area table of its grain (layer count less -/// its mean), scaled so that the sum of both, averaged over a reference pixel, has unit variance. -pub struct CrystalTile { - pub look: CrystalLook, - /// `(side + 1)²` entries each: `sat[t][y·(side + 1) + x]` = sum over `[0, x) × [0, y)`. - pub sats: [Vec; 2], -} - -impl std::fmt::Debug for CrystalTile { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("CrystalTile").field("look", &self.look).finish_non_exhaustive() - } -} - -/// Layer counts of torus `which` (side `t`): `t × t`, row-major. -fn draw_torus(which: usize, t: usize, seed: u32, look: &CrystalLook) -> Vec { - let layers: Vec = emulsion(seed, look).into_iter().filter(|l| l.index as usize % 2 == which).collect(); - let w = t.div_ceil(64); - // scratch rows above and below a band, for the stamps' rows outside it (`Layer::splat`) - let margin = layers.iter().filter_map(|l| l.stamp.as_ref().map(|s| s.height)).max().unwrap_or(0); - let mut count = vec![0u8; t * t]; - par_rows(&mut count, t * BAND, |band, out| { - let rows = out.len() / t.max(1); - let n = rows * w; - let (mut cover, mut planes) = (vec![0u64; n + 2 * margin * w], vec![0u64; PLANES * n]); - for layer in &layers { - cover.fill(0); - layer.draw(t, band * BAND, w, margin, &mut cover); - add_layer(&mut planes, cover.get(margin * w..margin * w + n).unwrap_or_default()); - } - for (j, row) in out.chunks_mut(t.max(1)).enumerate() { - for (i, o) in row.iter_mut().enumerate() { - let (word, bit) = (j * w + i / 64, i % 64); - *o = (0..PLANES).fold(0u8, |c, p| c | ((planes.get(p * n + word).map_or(0, |v| (v >> bit) & 1) as u8) << p)); - } - } - }); - count -} - -/// Integer summed-area table of `count` (`t × t`): `(t + 1)²` entries. -fn summed_area(count: &[u8], t: usize) -> Vec { - let s = t + 1; - let mut sat = vec![0u32; s * s]; - // row prefix sums in parallel, then each row adds the one above - par_rows(&mut sat, s, |y, row| { - let Some(src) = y.checked_sub(1).and_then(|y| count.get(y * t..(y + 1) * t)) else { return }; - let mut acc = 0u32; - for (o, &c) in row.iter_mut().skip(1).zip(src) { - acc += c as u32; - *o = acc; - } - }); - for y in 1..s { - let (above, below) = sat.split_at_mut(y * s); - let (Some(prev), Some(row)) = (above.get((y - 1) * s..), below.get_mut(..s)) else { continue }; - for (o, &p) in row.iter_mut().zip(prev) { - *o = o.wrapping_add(p); - } - } - sat -} - -/// Sum over the reference pixels (2 × 2 tile pixels) of torus `count` (`t × t`, `t` even) of -/// their squared deviation from `mean` (per tile pixel), and the number of reference pixels. -fn reference_square_sum(count: &[u8], t: usize, mean: f64) -> (f64, usize) { - let h = t / 2; - let mut rows = vec![0.0f64; h]; - par_rows(&mut rows, 1, |y, out| { - let (Some(a), Some(b)) = (count.get(2 * y * t..(2 * y + 1) * t), count.get((2 * y + 1) * t..(2 * y + 2) * t)) else { return }; - let mut s = 0.0; - for (&[a0, a1], &[b0, b1]) in a.as_chunks::<2>().0.iter().zip(b.as_chunks::<2>().0) { - let q = (a0 as u32 + a1 as u32 + b0 as u32 + b1 as u32) as f64 / 4.0 - mean; - s += q * q; - } - if let Some(o) = out.first_mut() { - *o = s; - } - }); - (rows.iter().sum(), h * h) -} - -impl CrystalTile { - /// Draws the emulsion of `look` with `seed`, or `None` if it has no grain (no variance). - pub fn new(look: CrystalLook, seed: u32) -> Option { - let [t0, t1] = TORI; - let (c0, c1) = lightcraft_raster::par_join(|| draw_torus(0, t0, seed, &look), || draw_torus(1, t1, seed, &look)); - let mut var = 0.0; - let mut tori = Vec::with_capacity(2); - for (count, t) in [(c0, t0), (c1, t1)] { - let mean = count.iter().map(|&c| c as u64).sum::() as f64 / (t * t).max(1) as f64; - let (sq, n) = reference_square_sum(&count, t, mean); - var += sq / n.max(1) as f64; - tori.push((summed_area(&count, t), t, mean)); - } - if !(var > 1e-12 && var.is_finite()) { - return None; - } - let k = 1.0 / var.sqrt(); - let mut sats = tori.into_iter().map(|(sat, t, mean)| { - let s = t + 1; - let mut out = vec![0.0f32; s * s]; - par_rows(&mut out, s, |y, row| { - for (x, (o, &v)) in row.iter_mut().zip(sat.get(y * s..).unwrap_or_default()).enumerate() { - *o = ((v as f64 - mean * (x * y) as f64) * k) as f32; - } - }); - out - }); - Some(CrystalTile { look, sats: [sats.next()?, sats.next()?] }) - } - - /// Sum of torus `which`'s grain over the box `[x0, x0 + w] × [y0, y0 + w]` (tile pixels, - /// `0 ≤ w < side`), the table bilinearly interpolated: the exact integral of the pixels. - #[inline] - fn box_sum(&self, which: usize, x0: f32, y0: f32, w: f32) -> f32 { - let (Some(sat), Some(&t)) = (self.sats.get(which), TORI.get(which)) else { return 0.0 }; - let tf = t as f32; - let (x0, y0) = (x0 - (x0 / tf).floor() * tf, y0 - (y0 / tf).floor() * tf); - let at = |x: f32, y: f32| integral(sat, t, x, y); - at(x0 + w, y0 + w) - at(x0, y0 + w) - at(x0 + w, y0) + at(x0, y0) - } - - /// Mean grain over the square of side `w` centred on (`x`, `y`) (tile pixels): unit variance - /// at `w` = 2 (a 6000 px render). - #[inline] - pub fn field(&self, x: f32, y: f32, w: f32) -> f32 { - let (x0, y0) = (x - 0.5 * w, y - 0.5 * w); - (self.box_sum(0, x0, y0, w) + self.box_sum(1, x0, y0, w)) / (w * w) - } -} - -/// The table `sat` (side `t + 1`) bilinearly interpolated at (`x`, `y`) in `0..=t`. -#[inline] -fn bilinear(sat: &[f32], t: usize, x: f32, y: f32) -> f32 { - let s = t + 1; - let (i, j) = ((x.max(0.0) as usize).min(t - 1), (y.max(0.0) as usize).min(t - 1)); - let (fx, fy) = (x - i as f32, y - j as f32); - let g = |i: usize, j: usize| sat.get(j * s + i).copied().unwrap_or(0.0); - let a = g(i, j) + (g(i + 1, j) - g(i, j)) * fx; - let b = g(i, j + 1) + (g(i + 1, j + 1) - g(i, j + 1)) * fx; - a + (b - a) * fy -} - -/// The periodic grain's integral over `[0, x) × [0, y)` for `x`, `y` in `0..2t`. -#[inline] -fn integral(sat: &[f32], t: usize, x: f32, y: f32) -> f32 { - let tf = t as f32; - let (wx, wy) = (x >= tf, y >= tf); - let (rx, ry) = (if wx { x - tf } else { x }, if wy { y - tf } else { y }); - let mut v = bilinear(sat, t, rx, ry); - if wx { - v += bilinear(sat, t, tf, ry); - } - if wy { - v += bilinear(sat, t, rx, tf); - } - if wx && wy { - v += bilinear(sat, t, tf, tf); - } - v -} - -/// The integral of torus `sat` (side `t`) over `[0, i) × [0, across)` (`along_x`) or -/// `[0, across) × [0, i)`, for `i` in `0..=t`: the table cut along a line, with the periodic part -/// of `across` folded in (`across` in `0..2t`). -fn line(sat: &[f32], t: usize, along_x: bool, across: f32, out: &mut Vec) { - let (tf, n) = (t as f32, t + 1); - let wrap = across >= tf; - let a = (if wrap { across - tf } else { across }).clamp(0.0, tf); - let j = (a as usize).min(t.saturating_sub(1)); - let f = (a - j as f32) as f64; - out.clear(); - out.resize(n, 0.0); - // entry `i` of table line `k` (a row when cutting along x, a column when along y) - let at = |k: usize, i: usize| if along_x { sat.get(k * n + i) } else { sat.get(i * n + k) }.copied().unwrap_or(0.0) as f64; - for (i, o) in out.iter_mut().enumerate() { - let (p, q) = (at(j, i), at(j + 1, i)); - *o = p + (q - p) * f + if wrap { at(t, i) } else { 0.0 }; - } -} - -/// [`line`] interpolated at `x ≥ 0` (any number of periods along). -#[inline] -fn along(line: &[f64], t: usize, inv_t: f64, x: f64) -> f64 { - let tf = t as f64; - let q = (x * inv_t).floor().max(0.0); - let r = (x - q * tf).clamp(0.0, tf); - let i = (r as usize).min(t.saturating_sub(1)); - let f = r - i as f64; - let (Some(&a), Some(&b), Some(&end)) = (line.get(i), line.get(i + 1), line.get(t)) else { return 0.0 }; - a + (b - a) * f + q * end -} - -impl CrystalTile { - /// The grain of a line of `out.len()` output pixels side by side, each a square of side `w` - /// (tile pixels), the first centred on (`x`, `y`), the next `step` (`±w`) along x (`along_x`) - /// or y. The table is cut once along the line's two box edges; each pixel then costs one - /// interpolation per torus instead of [`Self::field`]'s eight table lookups. - pub fn row_field(&self, x: f32, y: f32, w: f32, step: f32, along_x: bool, out: &mut [f32]) { - out.fill(0.0); - let n = out.len(); - let (pos, across) = if along_x { (x, y) } else { (y, x) }; - let sign = if step < 0.0 { -1.0 } else { 1.0 }; - let first = pos as f64 - 0.5 * step as f64; - let lowest = first.min(first + n as f64 * step as f64); - let (mut near, mut far) = (Vec::new(), Vec::new()); - for (which, &t) in TORI.iter().enumerate() { - let Some(sat) = self.sats.get(which) else { continue }; - let tf = t as f32; - let lo = across - 0.5 * w; - let lo = lo - (lo / tf).floor() * tf; - line(sat, t, along_x, lo, &mut near); - line(sat, t, along_x, lo + w, &mut far); - let shift = (lowest / t as f64).floor() * t as f64; - let inv_t = 1.0 / t as f64; - let edge = |k: usize| { - let e = first + k as f64 * step as f64 - shift; - along(&far, t, inv_t, e) - along(&near, t, inv_t, e) - }; - let mut prev = edge(0); - for (k, o) in out.iter_mut().enumerate() { - let next = edge(k + 1); - *o += (sign * (next - prev)) as f32; - prev = next; - } - } - let area = w * w; - out.iter_mut().for_each(|v| *v /= area); - } -} - -// ---- the render's grain +pub use craft_develop::crystal::{CrystalLook, CrystalTile, FILLING, PITCH, REF_LONG, TILE_PER_LONG, TORI, lift, strength_levels}; /// The crystal grain of one render. #[derive(Clone, Debug)] @@ -809,274 +16,34 @@ pub struct CrystalGrain { pub foot: f32, } -type Key = (u64, u64, u32); - -/// The cache key of the tile of `look` and `seed`. -fn key_of(look: CrystalLook, seed: u32) -> Key { - (look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed) -} -/// Recently drawn tiles (the most recent last). -type Cache = Mutex)>>; -static TILES: Cache = Mutex::new(Vec::new()); - -/// The tile being drawn in the background for a drag ([`tile`]): one at a time. -static DRAWING: Mutex> = Mutex::new(None); - -/// The tile a drawing hands to the renders waiting for it, set when it is drawn. -type Slot = Arc>>; - -/// The tiles being drawn, by cache and key, and the condition their drawers signal when done: a -/// render that misses a tile another is drawing waits for it rather than drawing it again. The -/// drawer hands the tile over in its slot, so the waiters get it even if the cache has evicted it -/// by the time they wake. -static IN_FLIGHT: Mutex> = Mutex::new(Vec::new()); -static DRAWN: Condvar = Condvar::new(); - -/// Marks a tile drawn (or failed) when dropped and wakes the renders waiting for it. -struct Drawing { - id: (usize, Key), - done: Slot, -} - -impl Drawing { - /// Registers the draw of `id` in `busy` (the locked [`IN_FLIGHT`]). - fn register(busy: &mut Vec<((usize, Key), Slot)>, id: (usize, Key)) -> Drawing { - let done = Slot::default(); - busy.push((id, done.clone())); - Drawing { id, done } - } - - /// Hands `t` to the renders waiting for it (they wake when this is dropped). - fn finish(&self, t: &Arc) { - // (already set: only the first tile counts, and every drawing draws the same one) - let _ = self.done.set(t.clone()); - } -} - -impl Drop for Drawing { - fn drop(&mut self) { - IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| *d != self.id); - DRAWN.notify_all(); - } -} - -/// Registers the tile of `id` as being drawn, or `None` if another thread is drawing it. -fn start_drawing(id: (usize, Key)) -> Option { - let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); - if busy.iter().any(|(d, _)| *d == id) { - return None; - } - Some(Drawing::register(&mut busy, id)) -} - -/// The tile of `key` in `cache`. -fn cached(cache: &Cache, key: Key) -> Option> { - let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); - tiles.iter().find(|(k, _)| *k == key).map(|(_, t)| t.clone()) -} - -/// The tile of `look` and `seed`, drawn or from the cache. Unless `wait`, a tile not drawn yet -/// is drawn in the background and the last one drawn for `seed` stands in for it meanwhile: a -/// Size or Roughness drag doesn't wait for every step's tile (tens of milliseconds on a slow -/// CPU), and the full-quality render when it ends waits for the exact one. With no tile cached -/// for `seed` nothing can stand in, so even without `wait` this waits for a draw already running -/// or draws the tile. -fn tile(look: CrystalLook, seed: u32, wait: bool) -> Option> { - tile_in(&TILES, look, seed, wait) -} - -/// [`tile`] with the tiles cached in `cache` (a test's own, which other tests can't evict from). -fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> Option> { - let key = key_of(look, seed); - { - let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); - if let Some((_, t)) = tiles.iter().find(|(k, _)| *k == key) { - return Some(t.clone()); - } - // (wasm has no threads to draw on) - if !wait - && !cfg!(target_arch = "wasm32") - && let Some((_, stand_in)) = tiles.iter().rev().find(|(k, _)| k.2 == seed) - { - let stand_in = stand_in.clone(); - drop(tiles); - draw_in_background(cache, key, look, seed); - return Some(stand_in); - } - } - let id = (std::ptr::from_ref(cache) as usize, key); - // a pool worker draws the tile itself: blocked, it could hold up the drawing it waits for - // (its stack may carry a part of that drawing's parallel work); wasm has no other threads - let drawing = if !cfg!(target_arch = "wasm32") && rayon::current_thread_index().is_none() { - // checked, waited for and registered under one lock: two renders that miss the tile - // together can't both find it neither cached nor being drawn (`cached` takes the cache's - // lock under this one; nothing takes them the other way round) - let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); - let mut waited_for: Option = None; - loop { - if let Some(t) = waited_for.as_ref().and_then(|done| done.get().cloned()).or_else(|| cached(cache, key)) { - return Some(t); - } - let Some((_, done)) = busy.iter().find(|(d, _)| *d == id) else { break }; - waited_for = Some(done.clone()); - busy = DRAWN.wait(busy).unwrap_or_else(PoisonError::into_inner); - } - Some(Drawing::register(&mut busy, id)) - } else { - start_drawing(id) - }; - #[cfg(test)] - if let Some(d) = &drawing { - tests::hold_for_waiters(d); - } - let t = Arc::new(CrystalTile::new(look, seed)?); - if let Some(d) = &drawing { - d.finish(&t); - } - keep(cache, key, t.clone()); - #[cfg(test)] - if let Some(d) = &drawing { - tests::evict_before_waking(cache, d); - } - Some(t) -} - -/// Adds `t` to `cache` (the most recent last). -fn keep(cache: &Cache, key: Key, t: Arc) { - let mut tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); - tiles.retain(|(k, _)| *k != key); - if tiles.len() >= CACHE { - tiles.remove(0); - } - tiles.push((key, t)); -} - -/// Draws the tile of `key` on the thread pool unless another is being drawn (the next render -/// asks again for what it needs then). -fn draw_in_background(cache: &'static Cache, key: Key, look: CrystalLook, seed: u32) { - let marker = { - let mut drawing = DRAWING.lock().unwrap_or_else(PoisonError::into_inner); - if drawing.is_some() { - return; - } - // (`None`: a render is drawing it already) - let Some(marker) = start_drawing((std::ptr::from_ref(cache) as usize, key)) else { return }; - *drawing = Some(key); - marker - }; - spawn_in_background(move || { - if let Some(t) = CrystalTile::new(look, seed) { - let t = Arc::new(t); - marker.finish(&t); - keep(cache, key, t); - } - drop(marker); - *DRAWING.lock().unwrap_or_else(PoisonError::into_inner) = None; - }); -} - -/// Runs `draw` on the background pool. -fn spawn_in_background(draw: impl FnOnce() + Send + 'static) { - // on a pool of its own: the renders of the drag don't queue behind its parallel bands - match background_pool() { - Some(pool) => pool.spawn(draw), - None => rayon::spawn(draw), - } -} - -/// Half the cores, for tiles drawn in the background (`None`: the pool couldn't be made). -fn background_pool() -> Option<&'static rayon::ThreadPool> { - static POOL: OnceLock> = OnceLock::new(); - POOL.get_or_init(|| { - let n = std::thread::available_parallelism().map_or(2, |n| n.get()).div_ceil(2); - rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("grain-tile-{i}")).build().ok() - }) - .as_ref() -} - -/// The tone weight of an encoded channel value `v` (0..1): `Y·dV/dY` of the sRGB curve, i.e. how -/// much `v` moves when the channel's linear light is scaled. -#[inline] -pub fn lift(v: f32) -> f32 { - let v = v.clamp(0.0, 1.0); - if v <= 0.040_45 { v } else { (v + 0.055) / 2.4 } -} - -/// The tone weight at mid grey (what [`CrystalGrain::k`] is calibrated at). -fn mid_weight() -> f32 { - lift(MID_GREY) * (1.0 - srgb_to_linear(MID_GREY)) -} - impl CrystalGrain { - /// The grain of `g` at `px_per_long` output pixels per long edge (`None`: no grain). + fn from_craft(g: craft_develop::crystal::CrystalGrain) -> CrystalGrain { + CrystalGrain { tile: g.tile, k: g.k, foot: g.foot } + } + + fn as_craft(&self) -> craft_develop::crystal::CrystalGrain { + craft_develop::crystal::CrystalGrain { tile: self.tile.clone(), k: self.k, foot: self.foot } + } + pub fn new(g: &Grain, px_per_long: f64) -> Option { - Self::with(g, px_per_long, true) + craft_develop::crystal::CrystalGrain::new(&crate::bridge::to_craft_grain(g), px_per_long).map(Self::from_craft) } - /// [`Self::new`] for a draft render (a drag): while its tile is drawn, the last tile drawn for - /// the same seed stands in for it (see [`tile`]). pub fn draft(g: &Grain, px_per_long: f64) -> Option { - Self::with(g, px_per_long, false) + craft_develop::crystal::CrystalGrain::draft(&crate::bridge::to_craft_grain(g), px_per_long).map(Self::from_craft) } - fn with(g: &Grain, px_per_long: f64, wait: bool) -> Option { - let levels = strength_levels(g.amount, g.size, g.roughness); - if !(levels > 0.0 && px_per_long.is_finite() && px_per_long > 0.0) { - return None; - } - let foot = (TILE_PER_LONG / px_per_long) as f32; - if !(foot.is_finite() && foot > 0.0 && foot < MAX_FOOTPRINT) { - return None; - } - let tile = tile(CrystalLook::new(g.size, g.roughness), g.seed, wait)?; - Some(CrystalGrain { tile, k: (levels / 255.0) as f32 / mid_weight(), foot }) - } - - /// Display-encoded colour `e` with grain, at frame position (`gx`, `gy`) (fractions of the - /// frame's long edge): the mean over an axis-aligned square footprint centred there, which - /// for a rotated frame's pixel stands in for its rotated footprint (`docs/grain.md`). #[inline] pub fn apply(&self, e: [f32; 3], gx: f32, gy: f32) -> [f32; 3] { - if !(gx.is_finite() && gy.is_finite()) { - return e; - } - let tpl = TILE_PER_LONG as f32; - self.apply_field(e, self.tile.field(gx * tpl, gy * tpl, self.foot)) + self.as_craft().apply(e, gx, gy) } - /// The grain field of a row of `out.len()` pixels whose first centre is at (`gx`, `gy`) and - /// which step (`dx`, `dy`) (fractions of the long edge), when the step is along x or y (an - /// unrotated frame in any orientation) and the pixels are squares of the render's size - /// (`false` otherwise: use [`Self::apply`] per pixel). pub fn row(&self, gx: f64, gy: f64, dx: f64, dy: f64, out: &mut [f32]) -> bool { - let tpl = TILE_PER_LONG; - let ((sx, sy), w) = ((dx * tpl, dy * tpl), self.foot as f64); - let (step, along_x) = if sy.abs() <= 1e-6 { - (sx, true) - } else if sx.abs() <= 1e-6 { - (sy, false) - } else { - return false; - }; - if !(gx.is_finite() && gy.is_finite() && step.is_finite()) || (step.abs() - w).abs() > 1e-4 * w { - return false; - } - self.tile.row_field((gx * tpl) as f32, (gy * tpl) as f32, self.foot, step as f32, along_x, out); - true + self.as_craft().row(gx, gy, dx, dy, out) } - /// Display-encoded colour `e` with grain field value `g` (see [`CrystalTile::field`]). #[inline] pub fn apply_field(&self, e: [f32; 3], g: f32) -> [f32; 3] { - let lum = (0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]).clamp(0.0, 1.0); - let k = self.k * g * (1.0 - srgb_to_linear(lum)); - if !k.is_finite() { - return e; - } - e.map(|v| v + k * lift(v)) + self.as_craft().apply_field(e, g) } } - -#[cfg(test)] -#[path = "tests_crystal.rs"] -mod tests; diff --git a/crates/pipeline/src/curve.rs b/crates/pipeline/src/curve.rs index b2c2b0b141..16b3df808e 100644 --- a/crates/pipeline/src/curve.rs +++ b/crates/pipeline/src/curve.rs @@ -1,238 +1,32 @@ -//! The parametric tone curve model shared by the pipeline renderer and the UI curve editor. -//! -//! Lightroom-style tone curve parametric model: four regions (shadows, darks, lights, highlights) -//! separated by three split points. Each region contributes a cosine-windowed bump, summed and -//! forced monotone. +//! The parametric tone curve model shared by the pipeline renderer and the UI curve editor, +//! backed by `craft_develop::curve`. + +use std::ops::Deref; use lightcraft_color::spline::Lut1; use lightcraft_develop::ToneCurve; -/// The four shape controls of the parametric curve, in graph order: region 0 is the darkest. -pub const PARAM_AMOUNTS: [&str; 4] = ["curve.shadows", "curve.darks", "curve.lights", "curve.highlights"]; +pub use craft_develop::curve::{PARAM_AMOUNTS, PARAM_LUT}; -/// Resolution the parametric curve is sampled at, matching the renderer's LUT. -pub const PARAM_LUT: usize = 1024; - -/// The parametric (region) curve of a [`ToneCurve`]: the four region amounts, each a cosine bump -/// over its window between two splits, summed and then forced monotone. -/// -/// This is the renderer's curve, not an approximation of it — both `curve_luts` in the pipeline -/// and the curve editor in the UI use this struct so they can never disagree. +/// The parametric (region) curve of a [`ToneCurve`], backed by `craft_develop::curve::ParametricCurve`. #[derive(Clone, Debug)] -pub struct ParametricCurve { - /// The curve, sampled and already forced monotone. - lut: [f32; PARAM_LUT], - /// The three region boundaries as fractions of the graph (0..1). - pub splits: [f64; 3], - /// The four region amounts, in graph order (0 = shadows, 3 = highlights). - pub amounts: [f64; 4], +pub struct ParametricCurve(craft_develop::curve::ParametricCurve); + +impl Deref for ParametricCurve { + type Target = craft_develop::curve::ParametricCurve; + + fn deref(&self) -> &Self::Target { + &self.0 + } } impl ParametricCurve { pub fn new(c: &ToneCurve) -> ParametricCurve { - let s0 = if c.split_shadows.is_nan() { 0.25 } else { (c.split_shadows / 100.0).clamp(0.0, 1.0) as f32 }; - let s1 = if c.split_mid.is_nan() { 0.50_f32.max(s0) } else { (c.split_mid / 100.0).clamp(s0 as f64, 1.0) as f32 }; - let s2 = if c.split_highlights.is_nan() { 0.75_f32.max(s1) } else { (c.split_highlights / 100.0).clamp(s1 as f64, 1.0) as f32 }; - let clean_amt = |a: f64| if a.is_nan() { 0.0 } else { a.clamp(-100.0, 100.0) }; - let (a0, a1, a2, a3) = (clean_amt(c.shadows), clean_amt(c.darks), clean_amt(c.lights), clean_amt(c.highlights)); - let splits = [s0 as f64, s1 as f64, s2 as f64]; - let amounts = [a0, a1, a2, a3]; - let regions = [(0.0, s0, a0), (s0, s1, a1), (s1, s2, a2), (s2, 1.0, a3)]; - let mut lut = [0.0_f32; PARAM_LUT]; - let mut prev = 0.0_f32; - for (i, entry) in lut.iter_mut().enumerate() { - let x = i as f32 / (PARAM_LUT - 1) as f32; - let mut d = 0.0_f32; - for (a, b, amt) in regions { - if amt == 0.0 { - continue; - } - let (ctr, half) = ((a + b) / 2.0, (b - a) * 0.75 + 0.05); - if half <= f32::EPSILON { - continue; - } - let t = ((x - ctr) / half).clamp(-1.0, 1.0); - d += (amt / 100.0) as f32 * 0.22 * (0.5 + 0.5 * (t * std::f32::consts::PI).cos()); - } - let y = (x + d * 4.0 * x * (1.0 - x)).clamp(0.0, 1.0); - prev = prev.max(y); - *entry = prev; - } - ParametricCurve { lut, splits, amounts } + ParametricCurve(craft_develop::curve::ParametricCurve::new(&crate::bridge::to_craft_tone_curve(c))) } /// Convert the evaluated parametric curve into a 1024-entry [`Lut1`]. pub fn to_lut(&self) -> Lut1 { - Lut1 { v: self.lut.to_vec() } - } - - /// The curve at `x` (0 = black, 1 = white), read off the table (so it never overshoots the ends). - pub fn at(&self, x: f64) -> f64 { - let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) as f32 }; - let at = x * (PARAM_LUT - 1) as f32; - let i = at.floor().clamp(0.0, (PARAM_LUT - 1) as f32) as usize; - let cur = self.lut.get(i).copied().unwrap_or(0.0); - let next = self.lut.get(i + 1).copied().unwrap_or(cur); - let f = at - i as f32; - (cur + (next - cur) * f) as f64 - } - - /// Where region `region`'s handle sits on the input axis: the middle of its own window, so a - /// handle never has to cross a split to be grabbed. - pub fn region_x(&self, region: usize) -> f64 { - let (a, b) = self.region_window(region); - (a + b) / 2.0 - } - - /// The window (two splits, as fractions of the graph) region `region` owns. - pub fn region_window(&self, region: usize) -> (f64, f64) { - let s0 = self.split_x(0); - let s1 = self.split_x(1); - let s2 = self.split_x(2); - match region { - 0 => (0.0, s0), - 1 => (s0, s1), - 2 => (s1, s2), - _ => (s2, 1.0), - } - } - - /// The half-width of region `region`'s own bump, as fraction of the graph. - pub fn region_half(&self, region: usize) -> f64 { - let (a, b) = self.region_window(region); - (b - a) * 0.75 + 0.05 - } - - /// The cosine window region `region` applies at `x` (1 at its centre, 0 at the window edges). - pub fn region_window_at(&self, region: usize, x: f64) -> f64 { - let ctr = self.region_x(region); - let half = self.region_half(region); - if half <= f64::EPSILON { - return 0.0; - } - let t = ((x - ctr) / half).clamp(-1.0, 1.0); - 0.5 + 0.5 * (t * std::f64::consts::PI).cos() - } - - /// The region that owns graph position `x`: the one whose own window contains it. The four - /// windows tile 0..1, so this is always defined and a drag anywhere on the curve moves exactly - /// one slider — the region under the pointer. - pub fn region_at(&self, x: f64) -> usize { - let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }; - let s0 = self.split_x(0); - let s1 = self.split_x(1); - let s2 = self.split_x(2); - if x <= s0 { - 0 - } else if x <= s1 { - 1 - } else if x <= s2 { - 2 - } else { - 3 - } - } - - /// How much output level region `region`'s bump gains at `x` per unit of its slider: the bump is - /// linear in the amount, so this is a constant for a given `x`. A drag converts the pointer's - /// vertical motion into a slider change through it. - pub fn level_per_unit(&self, region: usize, x: f64) -> f64 { - let x = x.clamp(0.0, 1.0); - 0.22 / 100.0 * self.region_window_at(region, x) * 4.0 * x * (1.0 - x) - } - - /// The baseline level at `x` from the identity diagonal plus the contributions of all regions - /// *except* `region`. Used when inverting the model for `region` while holding the other three - /// regions fixed. - pub fn base_level_without(&self, region: usize, x: f64) -> f64 { - let x = x.clamp(0.0, 1.0); - let mut d = 0.0; - for i in 0..4 { - if i == region { - continue; - } - let amt = self.amounts.get(i).copied().unwrap_or(0.0); - if amt == 0.0 { - continue; - } - d += (amt / 100.0) * 0.22 * self.region_window_at(i, x); - } - x + d * 4.0 * x * (1.0 - x) - } - - /// The curve level region `region` sits at when its slider holds `amount`, at graph position `x`, - /// holding the other regions fixed at their current settings. - pub fn handle_level_at(&self, region: usize, amount: f64, x: f64) -> f64 { - (self.base_level_without(region, x) + amount * self.level_per_unit(region, x)).clamp(0.0, 1.0) - } - - /// The amount that puts region `region`'s curve at `level` at `x`, with the other three - /// regions held fixed — the inverse of [`Self::handle_level_at`]. A level the region cannot - /// reach saturates rather than jumping. - pub fn amount_at_level(&self, region: usize, level: f64, x: f64) -> f64 { - let per_unit = self.level_per_unit(region, x); - if per_unit.abs() <= f64::EPSILON { - return self.amounts.get(region).copied().unwrap_or(0.0); - } - let base = self.base_level_without(region, x); - ((level.clamp(0.0, 1.0) - base) / per_unit).clamp(-100.0, 100.0).round() - } - - /// The graph position split `split` (0..=2) sits at, 0..1. - pub fn split_x(&self, split: usize) -> f64 { - self.splits.get(split).copied().unwrap_or(0.5) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn non_finite_or_inverted_splits_do_not_panic_or_poison_curve() { - let c = ToneCurve { - split_shadows: 80.0, - split_mid: 20.0, - split_highlights: f64::NAN, - shadows: f64::NAN, - lights: f64::INFINITY, - ..Default::default() - }; - let model = ParametricCurve::new(&c); - assert!(model.at(0.5).is_finite()); - assert!(model.at(f64::NAN).is_finite()); - assert!(model.region_at(f64::NAN) < 4); - assert!((model.splits[0] - 0.8).abs() < 1e-6); - assert!((model.splits[1] - 0.8).abs() < 1e-6); - assert!((model.splits[2] - 0.8).abs() < 1e-6); - } - - #[test] - fn horizontal_inversion_at_x_0_51_with_darks_60_preserves_zero_lights() { - let c = ToneCurve { darks: 60.0, lights: 0.0, ..Default::default() }; - let model = ParametricCurve::new(&c); - assert_eq!(model.region_at(0.51), 2, "x=0.51 is inside the Lights region"); - let level = model.at(0.51); - assert!((level - 0.5619).abs() < 0.001, "extracted model at 0.51 is ~0.5619: {level}"); - // With other regions held fixed, inverting at level ~0.5619 must return Lights = 0, NOT 45! - let lights = model.amount_at_level(2, level, 0.51); - assert_eq!(lights, 0.0, "zero vertical delta preserves Lights=0: {lights}"); - } - - #[test] - fn a_curve_level_and_its_amount_are_inverses_with_other_regions_present() { - let c = ToneCurve { shadows: 20.0, darks: -30.0, lights: 40.0, highlights: -10.0, ..Default::default() }; - let model = ParametricCurve::new(&c); - for region in 0..4 { - let centre = model.region_x(region); - let (_, upper) = model.region_window(region); - for x in [centre, centre + (upper - centre) * 0.5] { - for amount in [-100.0, -40.0, 0.0, 30.0, 100.0] { - let level = model.handle_level_at(region, amount, x); - let back = model.amount_at_level(region, level, x); - assert!((back - amount).abs() <= 1.0, "region {region} at {x}: {amount} -> {level} -> {back}"); - } - } - } + Lut1 { v: self.0.to_lut().v } } } diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index e3b4b67191..b3ea3874e7 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -25,6 +25,7 @@ pub mod auto; pub mod blemish; +mod bridge; pub mod colorops; pub mod crystal; pub mod cull; @@ -43,8 +44,6 @@ pub mod lut; pub mod mask_space; pub mod masks; pub mod nrc_joint; -#[cfg(test)] -mod nrc_joint_reference; pub mod optics; pub mod output; pub mod profiles; @@ -60,7 +59,7 @@ pub use curve::{PARAM_AMOUNTS, PARAM_LUT, ParametricCurve}; pub use output::{DeepImage, DeepSamples, DisplaySpace, OutputDepth, OutputSpace, OutputTrc, Proof, ProofLut, proof_profile, register_proof_profile}; pub use visualize::{MaskView, Overlay}; -use lightcraft_develop::{DevelopSettings, Treatment}; +use lightcraft_develop::DevelopSettings; use std::any::Any; use std::borrow::Cow; use std::sync::{Arc, Mutex}; @@ -896,10 +895,6 @@ pub fn before_settings(s: &DevelopSettings) -> DevelopSettings { b } -pub(crate) fn is_bw(s: &DevelopSettings) -> bool { - s.treatment == Treatment::Bw || s.profile.id == "lc.mono" || s.profile.id.starts_with("lc.bw.") -} - /// `LIGHTCRAFT_PROFILE` is set: print per-stage timings to stderr. pub fn profiling() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); diff --git a/crates/pipeline/src/light_v3.rs b/crates/pipeline/src/light_v3.rs index d9f4fac5d3..c214deb9ee 100644 --- a/crates/pipeline/src/light_v3.rs +++ b/crates/pipeline/src/light_v3.rs @@ -1,439 +1,50 @@ -//! Process V4's Contrast and Blacks on the camera-look path (a raw with its camera's tone -//! curve): pointwise operators fitted to how Lightroom's sliders move a photo's tones, applied -//! after the camera curve with V2 Whites. Method, operator family and the fitted constants' provenance: -//! `docs/light-v3.md`; the constants are in [`crate::light_v3_params`] (generated). -//! -//! Each slider is an operator `F_a` on encoded values `v` (linear ProPhoto RGB, D50, Bradford from -//! the D65 working space, through the sRGB transfer curve), anchored at `F_0` = identity: -//! -//! - `a > 0`: `F_a(v) = v + s(a)·D₊(v)`; `a < 0`: `F_a(v) = max(0, v − s(a)·D₋(v))`, with `D` piecewise -//! linear on 12 fixed knots (`D(1) = 0`, and for Contrast `D(0) = 0`) and the amount law -//! `s(t) = ((1 − e^(−t/τ)) / (1 − e^(−1/τ)))^q`, `t = |a|/100`, one `(τ, q)` per sign; -//! - applied per channel ([`Mode::PerChannel`]), to the encoded ProPhoto luminance with linear RGB -//! scaled by the luminance ratio ([`Mode::Luminance`]), or a blend of the two in linear light -//! ([`Mode::Mix`], one weight per sign). -//! -//! The functions here port `Family.curve`, `Family.apply`, `Family.law` of -//! `fit_pointwise.py` (the fitting tool) exactly; [`Fit::unpack`] is its `Family.unpack`. Each -//! active operator is tabulated once per render ([`LUT_N`] entries over `v` in 0..1, interpolated -//! linearly). High-bit-depth CPU exports and the GPU read these tables ([`LightOps`]); 8-bit CPU -//! renders compose per-channel operations over linear input ([`PreviewOps`]). Luminance operations -//! retain the original evaluation, including any preceding per-channel operation. +//! Process V4's Contrast and Blacks on the camera-look path, backed by `craft_develop::light_v3`. -use lightcraft_color::{Mat3, PROPHOTO, REC2020}; -use lightcraft_develop::{DevelopSettings, Process}; +use std::ops::Deref; + +use lightcraft_develop::DevelopSettings; use crate::SourceInfo; -use crate::light_v3_params as fitted; -/// Entries of an operator's table over encoded `v` in 0..=1. -pub const LUT_N: usize = 1024; - -/// Linear ProPhoto RGB luminance (the Y row of ProPhoto → XYZ D50), as the fit computes it. -pub const PRO_Y: [f32; 3] = [0.288_040_2, 0.711_874_1, 0.000_085_7]; - -/// How an operator is applied to a pixel. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Mode { - /// To each encoded ProPhoto channel. - PerChannel, - /// To the encoded ProPhoto luminance; linear RGB is scaled by the luminance ratio. - Luminance, - /// `w·PerChannel + (1 − w)·Luminance` in linear light, with a weight per sign. - Mix, -} - -impl Mode { - /// The GPU kernel's code (`LIGHT_MODE` in `crates/gpu/src/params.rs`). - pub fn code(self) -> u32 { - match self { - Mode::PerChannel => 0, - Mode::Luminance => 1, - Mode::Mix => 2, - } - } -} - -/// One slider's fitted parameters, laid out as `fit_pointwise.py`'s `Family`: 11 values of `D₊` at -/// the knots but the last (`D(1) = 0`), 11 of `D₋`, then `ln τ₊, ln q₊, ln τ₋, ln q₋`, then two mix -/// logits (positive, negative amounts) in [`Mode::Mix`]. -#[derive(Clone, Copy, Debug)] -pub struct Fit { - pub mode: Mode, - /// Contrast moves tones both ways around a pivot: its shapes are anchored at black too (`D(0) = 0`). - pub signed: bool, - pub params: &'static [f64], -} - -const KNOTS_N: usize = fitted::KNOTS.len(); - -/// A [`Fit`] unpacked (`Family.unpack`). -#[derive(Clone, Copy, Debug)] -pub struct Unpacked { - pub d_pos: [f64; KNOTS_N], - pub d_neg: [f64; KNOTS_N], - /// `(τ, q)` of the amount law, positive and negative amounts. - pub law_pos: (f64, f64), - pub law_neg: (f64, f64), - /// Mix weights of the per-channel result for positive and negative amounts (1 outside [`Mode::Mix`]). - pub weights: (f64, f64), -} - -fn sigmoid(x: f64) -> f64 { - 1.0 / (1.0 + (-x).exp()) -} - -impl Fit { - /// The parameters unpacked; `None` when their number doesn't fit the layout. - pub fn unpack(&self) -> Option { - let n = KNOTS_N - 1; - let p = self.params; - let mix = self.mode == Mode::Mix; - let len = 2 * n + 4 + if mix { 2 } else { 0 }; - if p.len() != len { - return None; - } - // D(1) = 0 is appended (the last knot stays 0) - let shape = |off: usize| -> Option<[f64; KNOTS_N]> { - let mut d = [0.0; KNOTS_N]; - for (k, slot) in d.iter_mut().take(n).enumerate() { - *slot = *p.get(off + k)?; - } - Some(d) - }; - let (mut d_pos, mut d_neg) = (shape(0)?, shape(n)?); - if self.signed { - d_pos[0] = 0.0; - d_neg[0] = 0.0; - } - let at = |i: usize| p.get(i).copied(); - let i = 2 * n; - let law_pos = (at(i)?.exp(), at(i + 1)?.exp()); - let law_neg = (at(i + 2)?.exp(), at(i + 3)?.exp()); - let weights = if mix { (sigmoid(at(i + 4)?), sigmoid(at(i + 5)?)) } else { (1.0, 1.0) }; - Some(Unpacked { d_pos, d_neg, law_pos, law_neg, weights }) - } -} - -/// The amount law `s(t)` (`Family.law`): 1 at `|a| = 100`, linear as `τ` grows, saturating as it -/// shrinks. -pub fn law((tau, q): (f64, f64), a: f64) -> f64 { - let t = (a.abs() / 100.0).min(1.0); - let tau = tau.clamp(1e-3, 1e3); - ((1.0 - (-t / tau).exp()) / (1.0 - (-1.0 / tau).exp())).powf(q) -} - -/// `numpy.interp(v, KNOTS, d)`: piecewise linear, constant beyond the ends. -fn interp(v: f64, d: &[f64; KNOTS_N]) -> f64 { - let k = &fitted::KNOTS; - if v <= k[0] { - return d[0]; - } - for i in 1..KNOTS_N { - if v <= k[i] { - let t = (v - k[i - 1]) / (k[i] - k[i - 1]); - return d[i - 1] + t * (d[i] - d[i - 1]); - } - } - d[KNOTS_N - 1] -} - -impl Unpacked { - /// `F_a(v)` on an encoded value (`Family.curve`). - pub fn curve(&self, a: f64, v: f64) -> f64 { - if a == 0.0 { - return v; - } - if a > 0.0 { - return v + law(self.law_pos, a) * interp(v, &self.d_pos); - } - (v - law(self.law_neg, a) * interp(v, &self.d_neg)).max(0.0) - } -} - -/// One slider's operator at one amount, tabulated: `lut[i]` is the *linear* value of -/// `F_a(i / (LUT_N − 1))` (decoded with the sRGB curve), made non-decreasing (see [`Operator::new`]). -#[derive(Clone, Debug)] -pub struct Operator { - pub mode: Mode, - /// Weight of the per-channel result ([`Mode::Mix`]; 1 for per channel, 0 for luminance). - pub weight: f32, - pub lut: Box<[f32; LUT_N]>, -} - -impl Operator { - /// `fit` at `amount` (-100..100); `None` at 0 (the identity) or for parameters that do not unpack. - /// - /// The table is the running maximum of `F_a`: where a fitted shape folds back (a `D` rising - /// faster than 1), it is flat instead, so no two tones swap. None of the shipped fits folds. - /// The fitting tool inverts `F` the same way. - pub fn new(fit: &Fit, amount: f64) -> Option { - let a = if amount.is_finite() { amount.clamp(-100.0, 100.0) } else { 0.0 }; - if a == 0.0 { - return None; - } - let u = fit.unpack()?; - let weight = match fit.mode { - Mode::PerChannel => 1.0, - Mode::Luminance => 0.0, - Mode::Mix => (if a > 0.0 { u.weights.0 } else { u.weights.1 }) as f32, - }; - let mut lut = Box::new([0.0f32; LUT_N]); - let mut top = 0.0f64; - for (i, slot) in lut.iter_mut().enumerate() { - let v = i as f64 / (LUT_N - 1) as f64; - top = top.max(u.curve(a, v)); - *slot = srgb_decode(top) as f32; - } - // The negative Blacks fit rounds to exactly 1 in f32. Avoid calculating a luminance - // result that contributes nothing, on both CPU and GPU. - let mode = if weight == 1.0 { - Mode::PerChannel - } else if weight == 0.0 { - Mode::Luminance - } else { - Mode::Mix - }; - Some(Operator { mode, weight, lut }) - } - - /// The table at encoded `v` (clamped to 0..=1), interpolated: linear output. - #[inline] - pub fn eval(&self, v: f32) -> f32 { - let f = v.clamp(0.0, 1.0) * (LUT_N - 1) as f32; - let i = (f as usize).min(LUT_N - 2); - let t = f - i as f32; - self.lut[i] + (self.lut[i + 1] - self.lut[i]) * t - } - - /// One linear value through the operator: values above 1 (HDR renders) pass unchanged, which - /// is continuous because `F_a(1) = 1`; values below 0 (outside ProPhoto's gamut) keep their - /// distance below the image of 0, `F_a(0) + x` (continuous and increasing). This is the - /// per-channel domain: on luminance ([`Self::apply`]) a component above 1 is scaled with its - /// pixel unless the pixel's luminance is above 1. - #[inline] - pub fn channel(&self, x: f32, encode: &impl Fn(f32) -> f32) -> f32 { - if x > 1.0 { - x - } else if x < 0.0 { - self.lut[0] + x - } else { - self.eval(encode(x)) - } - } - - /// The luminance mode: linear ProPhoto `p` scaled by `F` of its luminance over its luminance - /// (unchanged when the luminance is at most 1e-6, or above 1). - #[inline] - fn luminance(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { - let y = PRO_Y[0] * p[0] + PRO_Y[1] * p[1] + PRO_Y[2] * p[2]; - if y.is_nan() || y <= 1e-6 || y > 1.0 { - return p; - } - let r = self.channel(y, encode) / y; - p.map(|c| c * r) - } - - /// The operator on a linear ProPhoto pixel (`Family.apply`). Per channel, each component goes - /// through [`Self::channel`] (one above 1 passes unchanged). On luminance, the pixel is scaled - /// by `F(Y) / Y` as a whole, components above 1 included, and passes unchanged only when `Y` - /// itself is above 1 (or at most 1e-6). Mix blends the two results in linear light, so an HDR - /// component of a pixel with `Y ≤ 1` moves by the luminance part's share. - #[inline] - pub fn apply(&self, p: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { - match self.mode { - Mode::PerChannel => p.map(|c| self.channel(c, encode)), - Mode::Luminance => self.luminance(p, encode), - Mode::Mix => { - let (a, b) = (p.map(|c| self.channel(c, encode)), self.luminance(p, encode)); - let w = self.weight; - std::array::from_fn(|k| w * a[k] + (1.0 - w) * b[k]) - } - } - } -} - -/// sRGB decoding in f64 (the tables are built in f64, like the fit). -fn srgb_decode(e: f64) -> f64 { - if e <= 0.04045 { e / 12.92 } else { ((e + 0.055) / 1.055).powf(2.4) } -} - -/// Linear Rec.2020 (the working space) → linear ProPhoto RGB (D50, Bradford), and back. -pub fn prophoto_matrices() -> ([[f32; 3]; 3], [[f32; 3]; 3]) { - let to = REC2020.to_space(&PROPHOTO); - let from = to.inverse().unwrap_or(Mat3::IDENTITY); - (to.to_f32(), from.to_f32()) -} +pub use craft_develop::light_v3::{FITS, Fit, LUT_N, Mode, Operator, PRO_Y, Unpacked, law, prophoto_matrices}; /// The active operators of a render, in order (Contrast, Blacks), and the conversions to -/// and from the space they work in. Applied after the tone map, chroma scaling and highlight -/// desaturation, before the colour stage (`finish::finish_with`, the GPU's `finish.wgsl`). +/// and from the space they work in. #[derive(Clone, Debug)] -pub struct LightOps { - pub ops: Vec, - pub to_pro: [[f32; 3]; 3], - pub from_pro: [[f32; 3]; 3], +pub struct LightOps(pub craft_develop::light_v3::LightOps); + +impl Deref for LightOps { + type Target = craft_develop::light_v3::LightOps; + + fn deref(&self) -> &Self::Target { + &self.0 + } } -/// The fits of Contrast and Blacks, in the order they apply. -pub const FITS: [&Fit; 2] = [&fitted::CONTRAST, &fitted::BLACKS]; - -/// Whether `s` renders `info` with the V4 operators: process V4 or later and a raw with its camera's tone -/// curve (other sources keep the tone map's own Contrast and Blacks). +/// Whether `s` renders `info` with the V4 operators. pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool { - let camera_look = info.raw && info.camera_tone.is_some(); - match s.process.process() { - Process::V1 | Process::V2 | Process::V3 => false, - Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V10 => camera_look, - } + craft_develop::light_v3::applies(&crate::bridge::to_craft_settings(s), info.raw, info.camera_tone.is_some()) } impl LightOps { - /// The operators of `s` for `info` (see [`applies`]); `None` when they don't apply or every - /// slider is at 0. pub fn new(s: &DevelopSettings, info: &SourceInfo) -> Option { - if !applies(s, info) { - return None; - } - let l = &s.light; - let ops: Vec = FITS.iter().zip([l.contrast, l.blacks]).filter_map(|(f, a)| Operator::new(f, a)).collect(); - if ops.is_empty() { - return None; - } - let (to_pro, from_pro) = prophoto_matrices(); - Some(LightOps { ops, to_pro, from_pro }) - } - - /// The operators on a linear Rec.2020 pixel; `encode`: linear → sRGB-encoded on 0..1 (the - /// exact curve or the shared table, as the render encodes). - #[inline] - pub fn apply(&self, d: [f32; 3], encode: &impl Fn(f32) -> f32) -> [f32; 3] { - let mut p = mul3(&self.to_pro, d); - for op in &self.ops { - p = op.apply(p, encode); - } - mul3(&self.from_pro, p) + craft_develop::light_v3::LightOps::new(&crate::bridge::to_craft_settings(s), info.raw, info.camera_tone.is_some()).map(LightOps) } } -/// Number of intervals over linear input for 8-bit CPU renders. Deep exports retain [`LightOps`] -/// with the exact sRGB encoder; this approximation is not used for U16 or F32 samples. -const PREVIEW_INTERVALS: usize = 16_384; +/// CPU preview tables for per-channel operations, built once per render. +pub(crate) struct PreviewOps(craft_develop::light_v3::PreviewOps); -/// An operator with its sRGB encoding and decoding included in one linear-input table. -struct LinearOperator { - black: f32, - white: f32, - // Each linear interval stores [intercept, slope], so a lookup needs no integer-to-float - // conversion or subtraction of neighbouring samples in the pixel loop. - segments: Box<[[f32; 2]; PREVIEW_INTERVALS]>, -} +impl Deref for PreviewOps { + type Target = craft_develop::light_v3::PreviewOps; -impl LinearOperator { - fn new(channel: impl Fn(f32) -> f32) -> Self { - let black = channel(0.0); - let mut previous = black; - let mut segments = Box::new([[0.0; 2]; PREVIEW_INTERVALS]); - for (i, segment) in segments.iter_mut().enumerate() { - let next = channel((i + 1) as f32 / PREVIEW_INTERVALS as f32); - let slope = (next - previous) * PREVIEW_INTERVALS as f32; - let intercept = (previous as f64 - slope as f64 * (i as f64 / PREVIEW_INTERVALS as f64)) as f32; - *segment = [intercept, slope]; - previous = next; - } - Self { black, white: previous, segments } + fn deref(&self) -> &Self::Target { + &self.0 } - - #[inline(always)] - fn channel(&self, x: f32) -> f32 { - if x >= 1.0 { - if x == 1.0 { self.white } else { x } - } else if x < 0.0 { - self.black + x - } else { - let f = x * PREVIEW_INTERVALS as f32; - let i = (f as u32).min(PREVIEW_INTERVALS as u32 - 1) as usize; - let [intercept, slope] = self.segments[i]; - intercept + slope * x - } - } -} - -/// CPU preview tables for per-channel operations, built once per render. Luminance operations -/// use [`LightOps`] instead, so interpolation cannot change a nearly cancelling luminance sum. -pub(crate) struct PreviewOps { - ops: PreviewOperators, - to_pro: [[f32; 4]; 3], - from_pro: [[f32; 4]; 3], -} - -enum PreviewOperators { - PerChannel(LinearOperator), - Separate(Vec), } impl PreviewOps { pub(crate) fn new(exact: &LightOps, encode: &impl Fn(f32) -> f32) -> Option { - let ops = &exact.ops; - // Small per-channel errors can cross the luminance cutoff at 1e-6, or be amplified - // by F(Y) / Y. Keep every preceding operation exact too, including Contrast. - if ops.iter().any(|o| o.mode != Mode::PerChannel) { - return None; - } - // A preceding black lift could carry a negative input across zero. Only fuse when - // preceding operators fix zero, so the composed negative extension remains F(0) + x. - // Contrast fixes zero and negative Blacks is per channel, so their usual pair fuses. - let fuse = ops.iter().take(ops.len().saturating_sub(1)).all(|o| o.lut[0] == 0.0); - let ops = if fuse { - PreviewOperators::PerChannel(LinearOperator::new(|x| ops.iter().fold(x, |x, o| o.channel(x, encode)))) - } else { - PreviewOperators::Separate(ops.iter().map(|o| LinearOperator::new(|x| o.channel(x, encode))).collect()) - }; - let columns = |m: [[f32; 3]; 3]| std::array::from_fn(|i| [m[0][i], m[1][i], m[2][i], 0.0]); - Some(Self { ops, to_pro: columns(exact.to_pro), from_pro: columns(exact.from_pro) }) - } - - // Keep the single-table path in the finish loop. An out-of-line call per pixel saves - // little code here but adds register spills to this otherwise small operation. - #[inline(always)] - pub(crate) fn apply(&self, d: [f32; 3]) -> [f32; 3] { - let mut p = mul_preview(&self.to_pro, d); - match &self.ops { - PreviewOperators::PerChannel(op) => p = [op.channel(p[0]), op.channel(p[1]), op.channel(p[2])], - PreviewOperators::Separate(ops) => { - for op in ops { - p = p.map(|c| op.channel(c)); - } - } - } - mul_preview(&self.from_pro, p) + craft_develop::light_v3::PreviewOps::new(&exact.0, encode).map(PreviewOps) } } - -/// Padded columns let the compiler multiply the RGB rows together in vector registers. -/// The fourth lane is unused; each RGB row keeps the same arithmetic order as `mul3`. -#[inline(always)] -fn mul_preview(m: &[[f32; 4]; 3], d: [f32; 3]) -> [f32; 3] { - let out: [f32; 4] = std::array::from_fn(|i| m[0][i] * d[0] + m[1][i] * d[1] + m[2][i] * d[2]); - [out[0], out[1], out[2]] -} - -#[inline] -fn mul3(m: &[[f32; 3]; 3], d: [f32; 3]) -> [f32; 3] { - [ - m[0][0] * d[0] + m[0][1] * d[1] + m[0][2] * d[2], - m[1][0] * d[0] + m[1][1] * d[1] + m[1][2] * d[2], - m[2][0] * d[0] + m[2][1] * d[1] + m[2][2] * d[2], - ] -} - -/// `fit_pointwise.py`'s own values for one fit at one amount (generated into -/// [`crate::light_v3_params`]; the tests check the port against them). -#[cfg(test)] -pub struct Reference { - pub amount: f64, - /// `Family.curve` at `light_v3_params::REF_V`. - pub curve: &'static [f64], - /// `Family.apply` on `light_v3_params::REF_PIX` (encoded ProPhoto), where the curve increases. - pub apply: Option<&'static [[f64; 3]]>, -} diff --git a/crates/pipeline/src/light_v3_params.rs b/crates/pipeline/src/light_v3_params.rs index 07ce6dd0cd..63a9ce309a 100644 --- a/crates/pipeline/src/light_v3_params.rs +++ b/crates/pipeline/src/light_v3_params.rs @@ -1,315 +1,3 @@ -//! Fitted constants of process V4's Contrast and Blacks ([`crate::light_v3`]). -//! -//! GENERATED by `tools/light_v3_constants.py rust` from the committed fits named below: do not edit by hand, -//! regenerate (the script must reproduce this file byte for byte). -//! -//! The values are fitted to black-box Lightroom exports of one person's Sony ILCE-7CR photos (the exports' -//! pixels only: no Lightroom code, tables or files), each slider against the same photo's Neutral or another -//! amount exported in the same batch, on the tune photos; the check photos were held out. The exports are -//! private; errors are published only with at least three contributing photos. These are our operator family's -//! parameters (`docs/light-v3.md`), not Lightroom's. -//! -//! - Contrast: `tools/light_v3_fits/contrast.json` (fitted as `v2-contrast-pc.json`), mode `pc`; 155 tune pairs on 20 photos, 61 check pairs on 6 photos; -//! sha256 `2f04d078f1866ccb05fc279b493ccab545adbe2ac178b12df9ebc524c79c2ce1`. -//! - Blacks: `tools/light_v3_fits/blacks.json` (fitted as `v2-blacks-mix.json`), mode `mix`; 148 tune pairs on 19 photos, 60 check pairs on 6 photos; -//! sha256 `b8ee89df8f632d9559649fcba917607ade1511ecaa2041f481dd5b73a318c090`. +//! Generated parameters for [`crate::light_v3`], backed by `craft_develop::light_v3_params`. -use crate::light_v3::{Fit, Mode}; -#[cfg(test)] -use crate::light_v3::Reference; - -/// The family's knots: the displacement shapes are piecewise linear on them. -pub const KNOTS: [f64; 12] = [0.0, 0.02, 0.05, 0.09, 0.14, 0.2, 0.28, 0.38, 0.5, 0.65, 0.82, 1.0]; - -/// `tools/light_v3_fits/contrast.json`. -pub const CONTRAST: Fit = Fit { - mode: Mode::PerChannel, - signed: true, - params: &[ - 9.797174393178826e-18, -0.017053489024880908, -0.04260284838408044, -0.07195939270312468, -0.09738651081071477, - -0.1088504066519633, -0.10140378035603768, -0.06947815571389163, -0.007856500339789655, 0.08463087858854193, 0.1098534938016389, - 0.30583740028604467, -0.05850866310699469, -0.07854274245013221, -0.09074476735486797, -0.0906596002773617, -0.08429179542961336, - -0.07428102082426319, -0.05004459522573259, -0.00906946010144, 0.056653920573147026, 0.09818533983265328, 0.3070552562874873, - 0.10657448975892592, -0.13962415708911588, 0.37724097657204825, - ], -}; - -/// `tools/light_v3_fits/blacks.json`. -pub const BLACKS: Fit = Fit { - mode: Mode::Mix, - signed: false, - params: &[ - 0.0016748697345088984, 0.032126630862752484, 0.07188512588294256, 0.09530584096821723, 0.12925288090794965, 0.12680972925019743, - 0.10913227308994669, 0.10024857312175768, 0.0835198499581404, 0.05136152009684992, 0.02045048232256003, 0.00011845423640374467, - 0.2706623236742467, 0.42355931120492346, 0.37893058797626605, 0.22045052169596244, 0.20955478047682013, 0.2107908996685734, - 0.16685612159796198, 0.13055496600268582, 0.08667135921560576, 0.03499725744978859, 14.344979966519135, 0.1199976090379452, - 6.829791928600096, 0.5956122696562978, 0.6007994346537187, 22.053184691621333, - ], -}; - -/// Where the reference values are taken: encoded values and pixels (encoded ProPhoto). -#[cfg(test)] -pub const REF_V: [f64; 16] = [ - 0.0, 0.004, 0.012, 0.03, 0.07, 0.11, 0.17, 0.25, 0.33, 0.45, 0.58, 0.7, 0.81, 0.9, 0.97, 1.0, -]; -#[cfg(test)] -pub const REF_PIX: [[f64; 3]; 6] = [ - [0.02, 0.05, 0.01], [0.3, 0.25, 0.2], [0.55, 0.5, 0.62], [0.9, 0.85, 0.7], [0.15, 0.4, 0.35], [0.75, 0.97, 0.99], -]; - -/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/contrast.json` (12 significant -/// digits). -#[cfg(test)] -pub const CONTRAST_REFERENCE: &[Reference] = &[ - Reference { - amount: -100.0, - curve: &[ - 0.0, 0.0157017326214, 0.0471051978642, 0.0951866895547, 0.154643754903, 0.200710700524, 0.257475697853, 0.328035061301, - 0.392162808025, 0.47614243307, 0.554016990408, 0.631130956115, 0.71425768483, 0.845452588982, 0.953635776695, 1.0, - ], - apply: Some(&[ - [0.078508663107, 0.12854274245, 0.0392543315535], [0.369433735705, 0.328035061301, 0.28429179543], - [0.537161666543, 0.509069460101, 0.576490755562], [0.845452588982, 0.768178883473, 0.631130956115], - [0.239598299469, 0.443215406038, 0.407315522905], [0.668915832804, 0.953635776695, 0.984545258898], - ]), - }, - Reference { - amount: -63.0, - curve: &[ - 0.0, 0.0117558826379, 0.0352676479138, 0.0732055944278, 0.126101694535, 0.170122852746, 0.227978700093, 0.301721466955, - 0.371201372402, 0.467327147126, 0.562778518405, 0.654353749223, 0.746542204136, 0.86384609598, 0.959153828794, 1.0, - ], - apply: Some(&[ - [0.0587794131897, 0.102057956904, 0.0293897065949], [0.346020527272, 0.301721466955, 0.255868416571], - [0.541490780829, 0.506011218203, 0.591162168506], [0.86384609598, 0.79576914397, 0.654353749223], - [0.209385555774, 0.428643076049, 0.387988602489], [0.696257592365, 0.959153828794, 0.986384609598], - ]), - }, - Reference { - amount: -25.0, - curve: &[ - 0.0, 0.00669797632024, 0.0200939289607, 0.0450295815589, 0.0895156438599, 0.130914451725, 0.19016858264, 0.267991929431, - 0.344332389013, 0.456027454879, 0.574009302137, 0.684121407008, 0.787925448518, 0.887423433092, 0.966227029927, 1.0, - ], - apply: Some(&[ - [0.0334898816012, 0.0681089814742, 0.0167449408006], [0.316008789537, 0.267991929431, 0.219434495337], - [0.547039966578, 0.502091073979, 0.609968416216], [0.887423433092, 0.831135149637, 0.684121407008], - [0.170657974176, 0.409963835778, 0.363214788663], [0.73130506224, 0.966227029927, 0.988742343309], - ]), - }, - Reference { - amount: -4.0, - curve: &[ - 0.0, 0.0042211975466, 0.0126635926398, 0.0312322222928, 0.0716000186917, 0.111714702007, 0.171653550835, 0.251475094729, - 0.331175061939, 0.450494169731, 0.579508843847, 0.698698170259, 0.808190185513, 0.898968891712, 0.969690667514, 1.0, - ], - apply: Some(&[ - [0.021105987733, 0.0514846914124, 0.0105529938665], [0.301312504095, 0.251475094729, 0.201593365611], - [0.549757317317, 0.500171439768, 0.619177545887], [0.898968891712, 0.848453337568, 0.698698170259], - [0.151693674318, 0.400816899693, 0.351083433835], [0.748467268102, 0.969690667514, 0.989896889171], - ]), - }, - Reference { - amount: -1.0, - curve: &[ - 0.0, 0.00403003956988, 0.0120901187096, 0.0301673410408, 0.0702172893598, 0.110232863843, 0.170224559253, 0.250200324153, - 0.330159578421, 0.450067110356, 0.5799332989, 0.699823205971, 0.809754219477, 0.899859971098, 0.96995799133, 1.0, - ], - apply: Some(&[ - [0.0201501978494, 0.0502016274236, 0.0100750989247], [0.300178243652, 0.250200324153, 0.200216385843], - [0.549967042657, 0.500023282251, 0.619888307225], [0.899859971098, 0.849789956648, 0.699823205971], - [0.150230008193, 0.400110938461, 0.350147134934], [0.749791848474, 0.96995799133, 0.98998599711], - ]), - }, - Reference { - amount: 1.0, - curve: &[ - 0.0, 0.00397028327185, 0.0119108498156, 0.0297772142058, 0.0695009210477, 0.109284415638, 0.169101549483, 0.249092158771, - 0.329255569926, 0.449707840731, 0.580361320706, 0.700802007104, 0.810944204495, 0.900531739739, 0.970159521922, 1.0, - ], - apply: Some(&[ - [0.0198514163593, 0.0496288098987, 0.00992570817964], [0.29917212145, 0.249092158771, 0.199051608167], - [0.550200155898, 0.499931547883, 0.620576207118], [0.900531739739, 0.850797609609, 0.700802007104], - [0.149134843694, 0.399484133579, 0.349311202243], [0.750866642282, 0.970159521922, 0.990053173974], - ]), - }, - Reference { - amount: 4.0, - curve: &[ - 0.0, 0.00386276829016, 0.0115883048705, 0.0289711762573, 0.067695255762, 0.106695434805, 0.165850959769, 0.245807593504, - 0.326562225444, 0.44865080988, 0.581668577311, 0.70370366501, 0.814360331887, 0.902455571598, 0.970736671479, 1.0, - ], - apply: Some(&[ - [0.0193138414508, 0.0482858458702, 0.0096569207254], [0.296176860778, 0.245807593504, 0.195620331007], - [0.550924318987, 0.499683888448, 0.622660921742], [0.902455571598, 0.853683357397, 0.70370366501], - [0.146004712278, 0.397617731312, 0.34681913522], [0.754002149954, 0.970736671479, 0.99024555716], - ]), - }, - Reference { - amount: 25.0, - curve: &[ - 0.0, 0.00303130723309, 0.00909392169928, 0.0227377271685, 0.0537312449465, 0.0866736973109, 0.140712707247, 0.220406592954, - 0.305733397543, 0.440476321314, 0.591778172653, 0.726143473036, 0.840778760722, 0.917333416951, 0.975200025085, 1.0, - ], - apply: Some(&[ - [0.0151565361655, 0.0379001091744, 0.00757826808274], [0.273013181027, 0.220406592954, 0.169084742294], - [0.556524593466, 0.497768628155, 0.638782944901], [0.917333416951, 0.876000125426, 0.726143473036], - [0.121798017215, 0.383184014474, 0.327546875221], [0.778250421984, 0.975200025085, 0.991733341695], - ]), - }, - Reference { - amount: 63.0, - curve: &[ - 0.0, 0.00166203669924, 0.00498611009773, 0.0124723297827, 0.0307349682338, 0.0537014072028, 0.0993144142548, 0.178575600043, - 0.271431971089, 0.427014372342, 0.608426903093, 0.763097901214, 0.884285279574, 0.941834618872, 0.982550385662, 1.0, - ], - apply: Some(&[ - [0.00831018349621, 0.0207966223556, 0.00415509174811], [0.234866663076, 0.178575600043, 0.125385281671], - [0.56574726332, 0.494614530364, 0.665333089458], [0.941834618872, 0.912751928309, 0.763097901214], - [0.0819338359776, 0.35941421432, 0.295808843098], [0.818183073196, 0.982550385662, 0.994183461887], - ]), - }, - Reference { - amount: 100.0, - curve: &[ - 0.0, 0.000589302195024, 0.00176790658507, 0.00443005785539, 0.0127188794564, 0.0278697600538, 0.0668815412687, 0.145803734783, - 0.244559031965, 0.416467809921, 0.621470101755, 0.792049294828, 0.918369810554, 0.961029718779, 0.988308915634, 1.0, - ], - apply: Some(&[ - [0.00294651097512, 0.00739715161592, 0.00147325548756], [0.204981344572, 0.145803734783, 0.091149593348], - [0.57297262597, 0.49214349966, 0.686133402803], [0.961029718779, 0.941544578168, 0.792049294828], - [0.0507028398824, 0.340792120182, 0.270944156893], [0.849467711067, 0.988308915634, 0.996102971878], - ]), - }, -]; - -/// The family's own `curve` at [`REF_V`] and `apply` on [`REF_PIX`] for `tools/light_v3_fits/blacks.json` (12 significant -/// digits). -#[cfg(test)] -pub const BLACKS_REFERENCE: &[Reference] = &[ - Reference { - amount: -100.0, - curve: &[ - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0396726450283, 0.141176489367, 0.304319552499, 0.472849624284, 0.62852690601, - 0.771963089505, 0.880557079195, 0.964167123758, 1.0, - ], - apply: Some(&[ - [0.0, 0.0, 0.0], [0.0979960559384, 0.0396726450312, 8.67909201708e-12], [0.434072902922, 0.369445033999, 0.524551919414], - [0.880557079192, 0.820835618793, 0.628526906024], [1.62784132506e-11, 0.239194070991, 0.169963444981], - [0.693725171247, 0.964167123755, 0.988055707915], - ]), - }, - Reference { - amount: -63.0, - curve: &[ - 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0769799089595, 0.159002658298, 0.248306215942, 0.386971900482, 0.533641791607, 0.669077433807, - 0.793543473258, 0.891588093197, 0.967476427959, 1.0, - ], - apply: Some(&[ - [0.0, 0.0, 0.0], [0.212603750827, 0.159002658299, 0.109336909762], [0.49984457601, 0.443515883354, 0.578704745728], - [0.891588093196, 0.837382139795, 0.669077433813], [0.0554085751144, 0.330427917606, 0.27210785935], - [0.72565290629, 0.967476427958, 0.989158809318], - ]), - }, - Reference { - amount: -25.0, - curve: &[ - 0.0, 0.0, 0.0, 0.0039713718625, 0.0375281504298, 0.0844641752827, 0.152600319953, 0.232978681132, 0.314718938796, - 0.438210409673, 0.571328561555, 0.694215843567, 0.806921758549, 0.898426528234, 0.96952795847, 1.0, - ], - apply: Some(&[ - [1.38361828441e-12, 0.0157222994288, 6.91809142207e-13], [0.28365227602, 0.232978681132, 0.183041203846], - [0.540618281274, 0.489434480805, 0.612275601929], [0.898426528233, 0.84763979235, 0.694215843568], - [0.132306397362, 0.386986338539, 0.335430047312], [0.745445804924, 0.96952795847, 0.989842652823], - ]), - }, - Reference { - amount: -4.0, - curve: &[ - 0.0, 0.00384203333958, 0.0115267901451, 0.029063081396, 0.0688311531515, 0.109080820198, 0.169373686394, 0.249387305769, - 0.329449947556, 0.449575625482, 0.579687865532, 0.699791795259, 0.809889196554, 0.899943361788, 0.969983008536, 1.0, - ], - apply: Some(&[ - [0.0192115469507, 0.0487661502866, 0.00960560094376], [0.299411552286, 0.249387305769, 0.199389556317], - [0.549662298498, 0.499619686776, 0.61972195491], [0.899943361788, 0.849915042681, 0.699791795259], - [0.149363106446, 0.399531564189, 0.349475544402], [0.749836068575, 0.969983008536, 0.989994336179], - ]), - }, - Reference { - amount: -1.0, - curve: &[ - 0.0, 0.00398722513591, 0.0119617312187, 0.0299242307978, 0.0699054746135, 0.109925665346, 0.169949349621, 0.249950451029, - 0.32995551691, 0.449965680563, 0.579974757487, 0.69998316235, 0.809991039255, 0.899995419632, 0.96999862589, 1.0, - ], - apply: Some(&[ - [0.0199362373015, 0.0499002177906, 0.009968104698], [0.29995241186, 0.249950451029, 0.199950633032], - [0.549972689865, 0.499969243828, 0.619977514317], [0.899995419632, 0.849993129448, 0.69998316235], - [0.149948494014, 0.399962117299, 0.349957586943], [0.749986742762, 0.96999862589, 0.989999541963], - ]), - }, - Reference { - amount: 1.0, - curve: &[ - 9.31612027339e-06, 0.00404319245864, 0.0121109451354, 0.0302524139772, 0.0704649827756, 0.11060564863, 0.170712147943, - 0.250643898657, 0.330582319062, 0.450503332955, 0.580369162543, 0.700235118441, 0.810123865526, 0.900063195347, 0.970018958604, - 1.0, - ], - apply: Some(&[ - [0.0201752429349, 0.0503888012921, 0.0100906298252], [0.300630744288, 0.250626419466, 0.200631616538], - [0.550429399642, 0.500454032729, 0.620394920846], [0.90007223641, 0.850090998192, 0.700176696162], - [0.150565756988, 0.400578185286, 0.350572708933], [0.750135238759, 0.970032675648, 0.990024911688], - ]), - }, - Reference { - amount: 4.0, - curve: &[ - 4.44679248931e-05, 0.00420616726172, 0.0125295659354, 0.0312048283459, 0.0722194667453, 0.112890896317, 0.17339924135, - 0.253073472246, 0.332779539074, 0.452402520726, 0.581762095353, 0.701122272887, 0.810591237848, 0.900301645519, 0.970090493656, - 1.0, - ], - apply: Some(&[ - [0.0208391227968, 0.0518558616479, 0.0104339209625], [0.303010755867, 0.252990062923, 0.203015330491], - [0.55204964314, 0.502167204295, 0.621885228625], [0.900344802502, 0.850434355079, 0.700843514096], - [0.152703002383, 0.402759872928, 0.352733667786], [0.750645594216, 0.970155972394, 0.990118916658], - ]), - }, - Reference { - amount: 25.0, - curve: &[ - 0.000351031037929, 0.00562749010759, 0.0161804082469, 0.0395109485272, 0.0875205323187, 0.132820816064, 0.19683370592, - 0.274262075537, 0.351941758888, 0.468965565542, 0.593910029809, 0.708859253437, 0.814667248041, 0.902381198134, 0.97071435944, - 1.0, - ], - apply: Some(&[ - [0.0268094892594, 0.0646518089884, 0.0135180994291], [0.323771669718, 0.273605097162, 0.223833590382], - [0.566181459749, 0.517108276593, 0.63489439536], [0.902722015601, 0.853428836176, 0.7066658074], - [0.171494494367, 0.421790810113, 0.371579649929], [0.755101084946, 0.971231540587, 0.990939254456], - ]), - }, - Reference { - amount: 63.0, - curve: &[ - 0.000995014140305, 0.00861319796625, 0.0238495656181, 0.0569592350811, 0.11966278055, 0.174686686427, 0.246061413214, - 0.31877200482, 0.392194957135, 0.503758795817, 0.619428639797, 0.725111974413, 0.823229536124, 0.906749619145, 0.972024885744, - 1.0, - ], - apply: Some(&[ - [0.0404539765541, 0.0915381262658, 0.0205483468996], [0.367405560588, 0.316916949778, 0.267702217691], - [0.595875558955, 0.54849590131, 0.662288333975], [0.907716480454, 0.859719346711, 0.718935705489], - [0.211650252506, 0.461789763271, 0.411168543529], [0.764487032294, 0.973492582642, 0.992665468794], - ]), - }, - Reference { - amount: 100.0, - curve: &[ - 0.00167486973451, 0.0117652219602, 0.0319459264115, 0.0753794625361, 0.153595483426, 0.218884656944, 0.298031305079, - 0.36576131915, 0.434690423106, 0.540490151276, 0.646368740699, 0.742270038399, 0.832268778662, 0.911361379068, 0.97340841372, - 1.0, - ], - apply: Some(&[ - [0.055421940602, 0.119927912612, 0.0288346946948], [0.413495225374, 0.362648809539, 0.314154311953], - [0.627234264731, 0.5816340005, 0.691296631565], [0.912990263469, 0.866360468302, 0.731944464499], - [0.254705410536, 0.504042777472, 0.452962701964], [0.774433618221, 0.975881980047, 0.994492187831], - ]), - }, -]; +pub use craft_develop::light_v3_params::*; diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index ee947b0c1d..05b6509af9 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -1,16 +1,22 @@ //! Scene-linear preparation: white balance + exposure, and the spatial planes the per-pixel stage -//! needs (edge-aware base layer for highlights/shadows, clarity/texture bands, dehaze veil). +//! needs (edge-aware base layer for highlights/shadows, clarity/texture bands, dehaze veil), +//! backed by `craft_develop::local`. -use lightcraft_color::cct::{temp_tint_to_xy, wb_matrix, wb_matrix_checked, xy_to_temp_tint}; -use lightcraft_color::{REC2020, luminance_2020}; -use lightcraft_develop::{DevelopSettings, Process}; -use lightcraft_raster::blur::{gauss_taps, gaussian, gaussian_taps}; use std::sync::Arc; +use lightcraft_color::Xy; +use lightcraft_develop::DevelopSettings; +use lightcraft_raster::blur::{gauss_taps, gaussian, gaussian_taps}; use lightcraft_raster::{Plane, Rgb32f, par_join}; use crate::geometry::Frame; -use crate::{Prepared, Quality, SourceInfo, for_rows, masks, timed}; +use crate::{Prepared, Quality, SourceInfo, masks, timed}; + +pub use craft_develop::local::{ + AIRLIGHT_STEP, BASE_COARSE_STEP, BASE_DETAIL, BASE_DETAIL_MAX, BASE_EPS, BaseKey, CHROMA_SIGMA, CLARITY_EPS, NRC_SAMPLES, NrColor, NrLum, + NrcNoise, NrcParams, NrcPass, PlaneSigmas, SHARPEN_SIGMA_MAX, SHARPEN_SIGMA_MIN, SharpenKey, airlight_of, base_detail_radius, dark_of, + detail_scale, fit_nonneg_line, guided_fast_step, log_lum, plane_at, sharpen_gain, sharpen_sigma, texture_sigma, +}; /// White balance (relative to the source's as-shot white) and exposure, in place. pub fn scene_linear_pre(img: &mut Rgb32f, info: &SourceInfo, s: &DevelopSettings) { @@ -22,45 +28,10 @@ pub fn white_balance(img: &mut Rgb32f, info: &SourceInfo, s: &DevelopSettings) { wb_gain(img, info, s, 1.0); } -/// Whether `s` uses the checked Bradford white-balance adaptation (`Process::V10` on) instead -/// of the legacy matrix (V1 to V9, which stay frozen). -pub fn checked_wb(s: &DevelopSettings) -> bool { - s.process.process() >= Process::V10 -} - -/// The white-balance matrix (linear Rec.2020) for the settings, or `None` when the as-shot white -/// is kept. A raw source with its camera colour model ([`crate::CameraColor`]) is re-developed for -/// the new white in camera space, as Lightroom does (so a neutral under the chosen white renders -/// neutral and saturated colours move as the camera's matrices say); other sources are adapted -/// with Bradford, luminance-preserving. -pub fn wb_matrix_for(info: &SourceInfo, s: &DevelopSettings) -> Option<[[f32; 3]; 3]> { - let (t, tint) = effective_wb(info, s); - if (t - info.as_shot_temp).abs() < 1e-6 && (tint - info.as_shot_tint).abs() < 1e-6 { - return None; - } - if let Some(cc) = info.camera_color.as_deref().filter(|_| info.raw && !info.relative_wb) - && let Some(m) = lightcraft_raw::color::rebalance(&cc.tags, cc.developed_for, temp_tint_to_xy(t, tint)) - { - return Some(m.to_f32()); - } - let checked = checked_wb(s); - let set = if checked { wb_matrix_checked(&REC2020, effective_white(info, s)) } else { wb_matrix(&REC2020, effective_white(info, s)) }; - let shot = if checked { - wb_matrix_checked(&REC2020, temp_tint_to_xy(info.as_shot_temp, info.as_shot_tint)) - } else { - wb_matrix(&REC2020, temp_tint_to_xy(info.as_shot_temp, info.as_shot_tint)) - }; - let m = set.mul(&shot.inverse().unwrap_or(lightcraft_color::Mat3::IDENTITY)); - // Normalize so neutral luminance is preserved (WB shouldn't change exposure). - let g = m.apply([1.0, 1.0, 1.0]); - let y = g[0] * 0.2627 + g[1] * 0.6780 + g[2] * 0.0593; - Some(m.mul(&lightcraft_color::Mat3::diag(1.0 / y, 1.0 / y, 1.0 / y)).to_f32()) -} - fn wb_gain(img: &mut Rgb32f, info: &SourceInfo, s: &DevelopSettings, gain: f32) { let m = wb_matrix_for(info, s); let w = img.width; - for_rows(&mut img.data, w, |_, row| { + crate::for_rows(&mut img.data, w, |_, row| { for p in row.iter_mut() { let mut c = *p; if let Some(m) = &m { @@ -75,782 +46,142 @@ fn wb_gain(img: &mut Rgb32f, info: &SourceInfo, s: &DevelopSettings, gain: f32) }); } -/// The white balance actually in effect (presets resolve to their Kelvin values for raw files; settings written on -/// the relative scale before a raw's camera matrices reached its white balance give the same colour change on the -/// Kelvin scale, see [`legacy_to_kelvin`]). -pub fn effective_wb(info: &SourceInfo, s: &DevelopSettings) -> (f64, f64) { - use lightcraft_develop::WbMode; - match s.wb.mode { - WbMode::AsShot => (info.as_shot_temp, info.as_shot_tint), - _ if legacy_wb(info, s) => legacy_to_kelvin(s.wb.temp, s.wb.tint, (info.as_shot_temp, info.as_shot_tint)), - m if info.raw && !info.relative_wb => m.preset().unwrap_or((s.wb.temp, s.wb.tint)), - _ => (s.wb.temp, s.wb.tint), - } +/// Whether `s` uses the checked Bradford white-balance adaptation (`Process::V10` on) instead +/// of the legacy matrix (V1 to V9, which stay frozen). +pub fn checked_wb(s: &DevelopSettings) -> bool { + craft_develop::local::checked_wb(&crate::bridge::to_craft_settings(s)) } -/// The source white the render adapts from the as-shot white to: [`effective_wb`] as a chromaticity, except that a -/// white balance still on the relative scale is composed exactly ([`legacy_white`]) rather than read back through -/// its rounded Kelvin / tint. -fn effective_white(info: &SourceInfo, s: &DevelopSettings) -> lightcraft_color::Xy { - if legacy_wb(info, s) - && s.wb.mode != lightcraft_develop::WbMode::AsShot - && let Some(xy) = legacy_white(s.wb.temp, s.wb.tint, (info.as_shot_temp, info.as_shot_tint)) - { - return xy; - } - let (t, tint) = effective_wb(info, s); - temp_tint_to_xy(t, tint) -} - -/// Whether `s` holds a white balance written on the relative scale for a source that is edited in Kelvin today. -fn legacy_wb(info: &SourceInfo, s: &DevelopSettings) -> bool { - info.raw && !info.relative_wb && info.legacy_relative_wb && s.wb.scale == lightcraft_develop::WbScale::Legacy -} - -/// The white that renders exactly as `(temp, tint)` did on the relative scale, where 6500 K / 0 meant *as shot* and -/// the source's real as-shot white is `as_shot`. -/// -/// The relative render adapted the picture from 6500 K / 0 to `(temp, tint)` (Bradford, [`wb_matrix_for`]); the -/// Kelvin render adapts it from `as_shot` to the result. Bradford adaptations are von Kries scalings in one cone -/// space, so they compose exactly: the new white's cone response is the old target's times the as-shot white's -/// over the old reference's, and the two renders give the same matrix (up to the scale the luminance -/// normalisation removes). `None` when the arithmetic has nowhere to go (a non-finite input, a white outside the -/// chromaticity plane). -pub fn legacy_white(temp: f64, tint: f64, as_shot: (f64, f64)) -> Option { - use lightcraft_color::{BRADFORD, Xy}; - if !(temp.is_finite() && tint.is_finite() && as_shot.0.is_finite() && as_shot.1.is_finite()) { - return None; - } - let cones = |t: f64, tint: f64| BRADFORD.apply(temp_tint_to_xy(t, tint).to_xyz()); - let (old, reference, shot) = (cones(temp, tint), cones(6500.0, 0.0), cones(as_shot.0, as_shot.1)); - let inverse = BRADFORD.inverse()?; - let mut new = [0.0; 3]; - for i in 0..3 { - if reference[i].abs() < 1e-12 { - return None; - } - new[i] = old[i] * shot[i] / reference[i]; - } - let xy = Xy::from_xyz(inverse.apply(new)); - (xy.x.is_finite() && xy.y.is_finite() && xy.y > 0.0).then_some(xy) -} - -/// The Kelvin / tint of [`legacy_white`]: what a white balance written on the relative scale reads as, and becomes -/// when it is next edited ([`normalize_wb`]). Exact wherever the white has a Kelvin value (1000–50000 K after the -/// composition; the relative slider reached 2000–13550 K around 6500 K, so only a far-blue as-shot white pushed -/// to the slider's blue end lands beyond, and clamps), to the precision of the Kelvin / tint parametrisation -/// (better than 0.01 % away from its 4000 K seam). Unchanged when the arithmetic has nowhere to go. -pub fn legacy_to_kelvin(temp: f64, tint: f64, as_shot: (f64, f64)) -> (f64, f64) { - if temp == 6500.0 && tint == 0.0 && as_shot.0.is_finite() && as_shot.1.is_finite() { - // the relative scale's as-shot reference, exactly (a Custom value left where As Shot was stays as shot) - return as_shot; - } - match legacy_white(temp, tint, as_shot).map(xy_to_temp_tint) { - Some((t, tint)) if t.is_finite() && tint.is_finite() => (t, tint), - _ => (temp, tint), - } -} - -/// The relative-scale `(temp, tint)` that [`legacy_to_kelvin`] would read as the Kelvin `(temp, tint)` on a source -/// whose real as-shot white is `as_shot`: the inverse of [`legacy_white`]'s composition. It runs the Bradford step -/// backwards — the old target's cone response times the old reference's over the as-shot white's — and reads the -/// result back through [`xy_to_temp_tint`]. `(6500, 0)` is the relative scale's as-shot reference, so the Kelvin -/// white of the source itself maps exactly to it. `None` when the arithmetic has nowhere to go (a non-finite input, -/// a white outside the chromaticity plane, or an as-shot cone response of zero, where the forward step discarded it). -pub fn kelvin_to_legacy(temp: f64, tint: f64, as_shot: (f64, f64)) -> Option<(f64, f64)> { - use lightcraft_color::{BRADFORD, Xy}; - if !(temp.is_finite() && tint.is_finite() && as_shot.0.is_finite() && as_shot.1.is_finite()) { - return None; - } - if (temp - as_shot.0).abs() < 1e-9 && (tint - as_shot.1).abs() < 1e-9 { - // the source's own white: the relative scale's as-shot reference, exactly - return Some((6500.0, 0.0)); - } - let cones = |t: f64, tint: f64| BRADFORD.apply(temp_tint_to_xy(t, tint).to_xyz()); - let (target, reference, shot) = (cones(temp, tint), cones(6500.0, 0.0), cones(as_shot.0, as_shot.1)); - let inverse = BRADFORD.inverse()?; - let mut old = [0.0; 3]; - for i in 0..3 { - if shot[i].abs() < 1e-12 { - return None; - } - old[i] = target[i] * reference[i] / shot[i]; - } - let xy = Xy::from_xyz(inverse.apply(old)); - if !(xy.x.is_finite() && xy.y.is_finite() && xy.y > 0.0) { - return None; - } - let (t, tint) = xy_to_temp_tint(xy); - (t.is_finite() && tint.is_finite()).then_some((t, tint)) -} - -/// Bring the white balance of `d` onto the scale `info` is edited on, before a new value is written into it: on a -/// raw with a Kelvin scale the values are marked Kelvin, and ones still on the relative scale become the Custom -/// Kelvin / tint that renders the same ([`legacy_to_kelvin`]; a preset mode's look is kept as that custom -/// value, since the preset's Kelvin value would be a different look). Elsewhere the scale is cleared, so values -/// edited on a rendered photo or a raw without matrices never pass for Kelvin when pasted onto one that has them. -pub fn normalize_wb(d: &mut DevelopSettings, info: &SourceInfo) { - use lightcraft_develop::{WbMode, WbScale}; - if !info.raw || info.relative_wb { - d.wb.scale = WbScale::Legacy; - return; - } - if legacy_wb(info, d) && d.wb.mode != WbMode::AsShot { - let (t, tint) = legacy_to_kelvin(d.wb.temp, d.wb.tint, (info.as_shot_temp, info.as_shot_tint)); - d.wb.temp = t; - d.wb.tint = tint; - d.wb.mode = WbMode::Custom; - } - d.wb.scale = WbScale::Kelvin; -} - -/// Self-guided filter (He et al.) on a single plane with Gaussian windows of `sigma` px. -pub fn guided(p: &Plane, sigma: f32, eps: f32) -> Plane { - let (ma, mb) = guided_coeffs(p, sigma, eps); - guided_apply(p, &ma, &mb) -} - -/// Blurred guided-filter coefficients (mean a, mean b) of `p`; every pass row-parallel, and the -/// two independent blurs of each step run side by side. -fn guided_coeffs(p: &Plane, sigma: f32, eps: f32) -> (Plane, Plane) { - let (mean, corr) = par_join(|| gaussian(p, sigma), || gaussian(&p.map(|v| v * v), sigma)); - let a = corr.zip_map(&mean, |c, m| { - let var = (c - m * m).max(0.0); - var / (var + eps) - }); - let b = mean.zip_map(&a, |m, a| m - a * m); - par_join(|| gaussian(&a, sigma), || gaussian(&b, sigma)) -} - -/// `q = a·p + b` per pixel. Reduced coefficients are sampled with the same separable -/// weights and accumulation order as a bilinear resize, without full-size coefficient planes. -fn guided_apply(p: &Plane, a: &Plane, b: &Plane) -> Plane { - let mut q = Plane::new(p.width, p.height); - let w = p.width; - if (a.width, a.height) != (p.width, p.height) { - use lightcraft_raster::resample::{Filter, weights}; - let wx = weights(a.width, w, Filter::Bilinear); - let wy = weights(a.height, p.height, Filter::Bilinear); - // Bilinear upsampling has at most four taps (including zero-weight boundary taps). - // Keep only those horizontally sampled rows per band, reusing them for neighbouring - // output rows. Scratch scales with width and active bands, not image area. - const BAND: usize = 32; - for_rows(&mut q.data, w.saturating_mul(BAND), |band, rows| { - let mut cache: [(usize, Vec, Vec); 4] = std::array::from_fn(|_| (usize::MAX, vec![0.0; w], vec![0.0; w])); - let mut bias = vec![0.0; w]; - for (dy, row) in rows.chunks_mut(w).enumerate() { - let y = band * BAND + dy; - let (top, ys) = &wy[y]; - bias.fill(0.0); - for (dy, yw) in ys.iter().enumerate() { - let cy = top + dy; - let (cached_y, aa, bb) = &mut cache[cy % 4]; - if *cached_y != cy { - let (ar, br) = (a.row(cy), b.row(cy)); - for ((av, bv), (left, xs)) in aa.iter_mut().zip(bb.iter_mut()).zip(&wx) { - *av = 0.0; - *bv = 0.0; - for (dx, xw) in xs.iter().enumerate() { - *av += ar[left + dx] * xw; - *bv += br[left + dx] * xw; - } - } - *cached_y = cy; - } - for (av, ax) in row.iter_mut().zip(aa) { - *av += *ax * yw; - } - for (bv, bx) in bias.iter_mut().zip(bb) { - *bv += *bx * yw; - } - } - for ((v, pv), bv) in row.iter_mut().zip(p.row(y)).zip(&bias) { - *v = *v * pv + bv; - } - } - }); - return q; - } - for_rows(&mut q.data, w, |y, row| { - for ((v, pv), (av, bv)) in row.iter_mut().zip(p.row(y)).zip(a.row(y).iter().zip(b.row(y))) { - *v = av * pv + bv; - } - }); - q -} - -/// Fast guided filter (He & Sun 2015): coefficients computed on a `s×` subsampled plane and -/// sampled bilinearly at full resolution; the output keeps full-resolution edges. Equivalent to [`guided`] for -/// large windows at a fraction of the cost. -pub fn guided_fast(p: &Plane, sigma: f32, eps: f32) -> Plane { - use lightcraft_raster::resample::{Filter, resize}; - let s = guided_fast_step(sigma); - if s <= 1 { - return guided(p, sigma, eps); - } - let (lw, lh) = (p.width.div_ceil(s).max(1), p.height.div_ceil(s).max(1)); - let lo = resize(p, lw, lh, Filter::Box); - let (ma, mb) = guided_coeffs(&lo, sigma / s as f32, eps); - guided_apply(p, &ma, &mb) -} - -/// Separable median (`2r+1` px along each row, then each column; clamped edges). It keeps the -/// steps between regions where they are and removes features thinner than about `r` px. -pub fn median_hv(p: &Plane, r: usize) -> Plane { - if r == 0 || p.data.is_empty() { - return p.clone(); - } - let rows = |src: &Plane| { - let mut out = Plane::new(src.width, src.height); - for_rows(&mut out.data, src.width, |y, row| median_row(src.row(y), row, r)); - out +/// The white-balance matrix (linear Rec.2020) for the settings, or `None` when the as-shot white +/// is kept. +pub fn wb_matrix_for(info: &SourceInfo, s: &DevelopSettings) -> Option<[[f32; 3]; 3]> { + let rebalance = |target: craft_color_transform::Xy| { + let cc = info.camera_color.as_deref()?; + lightcraft_raw::color::rebalance(&cc.tags, cc.developed_for, crate::bridge::from_craft_xy(target)).map(crate::bridge::to_craft_mat3) }; - transpose(&rows(&transpose(&rows(p)))) + let cb: Option<&dyn Fn(craft_color_transform::Xy) -> Option> = + (info.camera_color.is_some() && info.raw && !info.relative_wb).then_some(&rebalance); + craft_develop::local::wb_matrix_for_with(&crate::bridge::to_craft_wb_source(info), &crate::bridge::to_craft_settings(s), cb) } -/// Running median of `src` over `2r+1` taps (clamped edges) into `out`: a sorted window that -/// drops the leaving value and inserts the entering one. -fn median_row(src: &[f32], out: &mut [f32], r: usize) { - let n = src.len(); - if n == 0 { - return; - } - let at = |i: isize| total_key(src[i.clamp(0, n as isize - 1) as usize]); - let r_ = r as isize; - let mut win: Vec = (-r_..=r_).map(at).collect(); - win.sort_unstable(); - for (x, o) in out.iter_mut().enumerate() { - *o = f32::from_bits(total_key_inv(win[r])); - let (old, new) = (at(x as isize - r_), at(x as isize + r_ + 1)); - if old != new { - // Ranks by counting the smaller keys in one branch-free pass the compiler vectorizes. - // Binary searches here mispredicted on most steps and, with `remove` + `insert`, cost - // 2.4 s per 24 MP at r = 9 on one core. - let (mut i, mut j) = (0u32, 0u32); - for &v in &win { - i += u32::from(v < old); - j += u32::from(v < new); - } - let (i, j) = (i as usize, j as usize); - // `old` sits at `i`; shift the keys between the two ranks by one over it - if j > i { - win.copy_within(i + 1..j, i); - win[j - 1] = new; - } else { - win.copy_within(j..i, j + 1); - win[j] = new; - } - } - } +pub fn effective_wb(info: &SourceInfo, s: &DevelopSettings) -> (f64, f64) { + craft_develop::local::effective_wb(&crate::bridge::to_craft_wb_source(info), &crate::bridge::to_craft_settings(s)) } -/// `v`'s bits as an `i32` that orders like [`f32::total_cmp`] (the same transform it applies), so -/// equal keys are equal bits. -fn total_key(v: f32) -> i32 { - let b = v.to_bits() as i32; - b ^ (((b >> 31) as u32) >> 1) as i32 +pub fn legacy_white(temp: f64, tint: f64, as_shot: (f64, f64)) -> Option { + craft_develop::local::legacy_white(temp, tint, as_shot).map(crate::bridge::from_craft_xy) } -/// The bits [`total_key`] came from (the transform is its own inverse: it keeps the sign bit). -fn total_key_inv(k: i32) -> u32 { - (k ^ (((k >> 31) as u32) >> 1) as i32) as u32 +pub fn legacy_to_kelvin(temp: f64, tint: f64, as_shot: (f64, f64)) -> (f64, f64) { + craft_develop::local::legacy_to_kelvin(temp, tint, as_shot) } -fn transpose(p: &Plane) -> Plane { - let (w, h) = (p.width, p.height); - let mut t = Plane::new(h, w); - for_rows(&mut t.data, h, |x, row| { - for (y, v) in row.iter_mut().enumerate() { - *v = p.data[y * w + x]; - } - }); - t +pub fn kelvin_to_legacy(temp: f64, tint: f64, as_shot: (f64, f64)) -> Option<(f64, f64)> { + craft_develop::local::kelvin_to_legacy(temp, tint, as_shot) } -/// Detail scale of the highlights/shadows base from process V2, as a fraction of the long edge: -/// the base is the edge-aware filter of log luminance without its detail at this radius, so -/// twigs, lines and fine texture brighter or darker than their surroundings take their -/// surroundings' shift (and keep their contrast, as with Exposure) while region boundaries stay -/// sharp (no halos). V1's base is the edge-aware filter of log luminance itself (issue #632). -pub const BASE_DETAIL: f64 = 0.0015; -/// Largest [`base_detail_radius`] (px). -pub const BASE_DETAIL_MAX: usize = 24; +pub fn normalize_wb(d: &mut DevelopSettings, info: &SourceInfo) { + let mut craft = crate::bridge::to_craft_settings(d); + craft_develop::local::normalize_wb(&mut craft, &crate::bridge::to_craft_wb_source(info)); + d.wb.mode = crate::bridge::from_craft_wb_mode(craft.wb.mode); + d.wb.temp = craft.wb.temp; + d.wb.tint = craft.wb.tint; + d.wb.scale = crate::bridge::from_craft_wb_scale(craft.wb.scale); +} -/// Median radius (px) of the highlights/shadows base at `px_per_long` (see [`BASE_DETAIL`]). -pub fn base_detail_radius(px_per_long: f64) -> usize { - ((BASE_DETAIL * px_per_long).round().max(0.0) as usize).min(BASE_DETAIL_MAX) +pub fn guided(p: &Plane, sigma: f32, eps: f32) -> Plane { + crate::bridge::from_craft_plane(craft_develop::local::guided(&crate::bridge::to_craft_plane(p), sigma, eps)) +} + +pub fn guided_fast(p: &Plane, sigma: f32, eps: f32) -> Plane { + crate::bridge::from_craft_plane(craft_develop::local::guided_fast(&crate::bridge::to_craft_plane(p), sigma, eps)) +} + +pub fn median_hv(p: &Plane, r: usize) -> Plane { + crate::bridge::from_craft_plane(craft_develop::local::median_hv(&crate::bridge::to_craft_plane(p), r)) } -/// Median radius (px) of the highlights/shadows base of `s`'s rendering process at `px_per_long`: -/// 0 (no median) under V1, [`base_detail_radius`] from V2 (later processes keep V2's base). pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { - match s.process.process() { - Process::V1 => 0, - Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 | Process::V10 => { - base_detail_radius(px_per_long) - } - } + craft_develop::local::tone_base_detail(&crate::bridge::to_craft_settings(s), px_per_long) } -/// The highlights/shadows base layer of log luminance `l`: the fast guided filter ([`BASE_EPS`]) -/// at `detail` px ([`tone_base_detail`]) of its [`detail_free`] plane when `keeps_gaps` -/// ([`base_keeps_gaps`], V8 on), else of its [`median_hv`] (V2 to V7); at 0, of `l` itself (V1). pub fn tone_base(l: &Plane, sigma: f32, detail: usize, keeps_gaps: bool) -> Plane { - if detail == 0 { - return guided_fast(l, sigma, BASE_EPS); - } - let m = if keeps_gaps { detail_free(l, detail) } else { median_hv(l, detail) }; - guided_fast(&m, sigma, BASE_EPS) + crate::bridge::from_craft_plane(craft_develop::local::tone_base(&crate::bridge::to_craft_plane(l), sigma, detail, keeps_gaps)) } -/// Downscale factor of the coarse median in [`detail_free`]: its radius at full size is this many -/// times the fine one's. -pub const BASE_COARSE_STEP: usize = 3; - -/// Log luminance `l` without detail finer than `r` px (the highlights/shadows base of process V8 -/// on takes its edge-aware filter): each value moves toward its [`median_hv`] at `r` only as far as the -/// median of a [`BASE_COARSE_STEP`]× wider neighbourhood agrees (`l` clamped between the two). -/// A twig, line or speck in an even surround has both medians on the surround's side and takes -/// its tone, as #632 wants. The gap between two letter strokes, which a median at `r` fills with the -/// strokes' tone, sits in a wider neighbourhood mostly of the panel's tone: the two medians -/// disagree and the gap keeps its own. The coarse median is taken at `r` of a box-downscaled copy and -/// enlarged bilinearly, like [`guided_fast`]'s coefficients. pub fn detail_free(l: &Plane, r: usize) -> Plane { - use lightcraft_raster::resample::{Filter, resize}; - if r == 0 || l.data.is_empty() { - return l.clone(); - } - let (w, h) = (l.width, l.height); - let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP).max(1), h.div_ceil(BASE_COARSE_STEP).max(1)); - if (lw, lh) == (w, h) { - // nothing to downscale: both medians are the same - return median_hv(l, r); - } - let lo = median_hv(&resize(l, lw, lh, Filter::Box), r); - // The bilinear enlargement of `lo` (`resize`'s horizontal pass, then its vertical pass taken - // row by row with the same sums) is clamped into `out` as it is made, not stored. - let wide = resize(&lo, w, lh, Filter::Bilinear); - let wy = lightcraft_raster::resample::weights(lh, h, Filter::Bilinear); - let mut out = median_hv(l, r); - for_rows(&mut out.data, w, |y, row| { - let Some((y0, ws)) = wy.get(y) else { return }; - let mut coarse = vec![0.0f32; w]; - for (k, &wt) in ws.iter().enumerate() { - let Some(t) = wide.data.get((y0 + k) * w..(y0 + k + 1) * w) else { continue }; - for (c, &v) in coarse.iter_mut().zip(t) { - *c += v * wt; - } - } - for ((o, &v), &c) in row.iter_mut().zip(l.row(y)).zip(&coarse) { - *o = clamp_between(v, *o, c); - } - }); - out + crate::bridge::from_craft_plane(craft_develop::local::detail_free(&crate::bridge::to_craft_plane(l), r)) } -/// `v` clamped between `a` and `b` (in either order); a NaN bound is ignored, not a panic. -fn clamp_between(v: f32, a: f32, b: f32) -> f32 { - let (lo, hi) = (a.min(b), a.max(b)); - if v < lo { - lo - } else if v > hi { - hi - } else { - v - } -} - -/// Subsampling step of [`guided_fast`] for `sigma` (1 = no subsampling: the plain guided filter). -pub fn guided_fast_step(sigma: f32) -> usize { - (sigma / 3.0).floor().clamp(1.0, 16.0) as usize -} - -/// Luminance noise reduction: guided filter of log luminance (`sigma` px, `eps`), blended by `k`. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct NrLum { - pub sigma: f32, - pub eps: f32, - pub k: f32, -} - -/// Colour noise reduction: chromaticity blurred by `sigma` px, mixed in by `t`. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct NrColor { - pub sigma: f32, - pub t: f32, -} - -/// Output pixels per pixel of the original photo for an output of `px_per_long` pixels per unit -/// of the long edge of an original `native_long` pixels long, at most 1 ([`crate::Plan::detail_scale`]). -pub fn detail_scale(px_per_long: f64, native_long: usize) -> f32 { - let k = (px_per_long / native_long.max(1) as f64) as f32; - if k.is_finite() { k.clamp(0.0, 1.0) } else { 1.0 } -} - -/// Smallest radius (px) noise reduction filters a preview with: [`gaussian`] makes no blur below -/// about 0.58 px and one 3-px box from there ([`lightcraft_raster::blur::box_sigma`]). -const NR_MIN_SIGMA: f32 = 1.0; - -/// Below this fade a preview's noise reduction is not drawn at all (less than 1 % of a 1-px blur). -const NR_MIN_BLEND: f32 = 0.01; - -/// Radius and blend weight that stand in for a blur of `sigma` px: below [`NR_MIN_SIGMA`] the -/// smallest blur the filter makes, blended in by the ratio of their variances, which keeps the -/// smoothing's second moment (how much it softens the finest detail) that of `sigma`. -fn nr_radius(sigma: f32) -> (f32, f32) { - if sigma >= NR_MIN_SIGMA { - return (sigma, 1.0); - } - let made = lightcraft_raster::blur::box_sigma(NR_MIN_SIGMA); - (NR_MIN_SIGMA, (sigma / made).powi(2).min(1.0)) -} - -/// Noise-reduction parameters at `scale` output pixels per pixel of the original -/// ([`crate::Plan::detail_scale`]; see [`denoise`]). Noise lives at the original's pixels, so the -/// radii are the full-size radii times `scale`, and the guided filter's `eps` (the variance it -/// treats as noise) follows the noise variance, which averaging `1/scale × 1/scale` pixels into one -/// multiplies by `scale²`. A radius below [`NR_MIN_SIGMA`] fades instead ([`nr_radius`]): previews look like -/// the full-size render scaled down (issue #960). At `scale` 1 these are the full-size parameters. pub fn nr_params(s: &DevelopSettings, scale: f32) -> (Option, Option) { - let lum = (s.detail.nr_luminance / 100.0) as f32; - let col = (s.detail.nr_color / 100.0) as f32; - let scale = if scale.is_finite() { scale.clamp(0.0, 1.0) } else { 1.0 }; - let l = (lum > 0.0).then(|| nr_radius((1.0 + 2.5 * lum) * scale)).filter(|&(_, w)| w >= NR_MIN_BLEND).map(|(sigma, w)| { - let detail = (s.detail.nr_detail / 100.0) as f32; - let eps = ((0.002 + lum * lum * 0.25 * (1.0 - 0.7 * detail)) * scale * scale).max(1e-7); - NrLum { sigma, eps, k: lum.sqrt() * w } - }); - let smooth = 1.0 + (s.detail.nr_color_smoothness / 100.0) as f32; - let c = (col > 0.0).then(|| nr_radius((1.5 + 6.0 * col) * scale * smooth)).filter(|&(_, w)| w >= NR_MIN_BLEND).map(|(sigma, w)| { - let keep = (s.detail.nr_color_detail / 100.0) as f32 * 0.5; - NrColor { sigma, t: col * (1.0 - keep) * w } - }); - (l, c) + craft_develop::local::nr_params(&crate::bridge::to_craft_settings(s), scale) } -/// Noise reduction at output resolution: luminance via an edge-aware self-guided filter on -/// log-luminance, colour by blurring chromaticity (rgb / Y) and re-applying the original luminance. -/// `scale`: output pixels per pixel of the original ([`nr_params`]). `colour_noise`: the whole -/// frame's noise model for the joint colour NR ([`crate::colour_noise`]; `None`: measured on `img`). pub fn denoise(img: &mut Rgb32f, s: &DevelopSettings, scale: f32, colour_noise: Option<&crate::nrc_joint::JointNoise>) { - let (lum, col) = nr_params(s, scale); - if col.is_some() && joint_colour_nr(s) { - apply_nr(img, lum, None); - if let Some(p) = nrc_params(s, scale) { - crate::nrc_joint::denoise(img, &p, (s.detail.nr_color_detail / 100.0) as f32, (s.detail.nr_color / 100.0) as f32, colour_noise); - } - return; - } - apply_nr(img, lum, col); + let mut craft = crate::bridge::take_craft_rgb32f(img); + craft_develop::local::denoise(&mut craft, &crate::bridge::to_craft_settings(s), scale, colour_noise); + crate::bridge::put_craft_rgb32f(img, craft); } -/// Noise reduction with explicit parameters (see [`denoise`]). pub fn apply_nr(img: &mut Rgb32f, lum: Option, col: Option) { - let w = img.width; - if let Some(nr) = lum { - let _t = crate::profiling().then(std::time::Instant::now); - let l = img.map(log_lum); - let f = guided(&l, nr.sigma, nr.eps); - for_rows(&mut img.data, w, |y, row| { - for (x, p) in row.iter_mut().enumerate() { - let i = y * w + x; - let d = (f.data[i] - l.data[i]) * nr.k; - let g = d.exp2(); - *p = p.map(|v| v * g); - } - }); - if let Some(t) = _t { - eprintln!(" nr luminance: {:.1} ms", t.elapsed().as_secs_f64() * 1e3); - } - } - if let Some(nr) = col { - let _t = crate::profiling().then(std::time::Instant::now); - let chroma = img.map(|c| { - let y = luminance_2020(c).max(1e-6); - [c[0] / y, c[1] / y, c[2] / y] - }); - let b = gaussian(&chroma, nr.sigma); - for_rows(&mut img.data, w, |y, row| { - for (x, p) in row.iter_mut().enumerate() { - let i = y * w + x; - let yl = luminance_2020(*p); - let c0 = chroma.data[i]; - let cb = b.data[i]; - *p = [0, 1, 2].map(|k| ((c0[k] + (cb[k] - c0[k]) * nr.t) * yl).max(0.0)); - } - }); - if let Some(t) = _t { - eprintln!(" nr colour: {:.1} ms", t.elapsed().as_secs_f64() * 1e3); - } - } + let mut craft = crate::bridge::take_craft_rgb32f(img); + craft_develop::local::apply_nr(&mut craft, lum, col); + crate::bridge::put_craft_rgb32f(img, craft); } -/// Most samples the noise level of the new colour noise reduction is measured from. The CPU and -/// the GPU sample the same pixels (see `nrc_joint::noise_sample_stride`). -pub const NRC_SAMPLES: usize = 131_072; - -/// One self-guided pass of the new colour noise reduction: Gaussian windows of `sigma` px, the -/// coefficients computed on a plane subsampled by `step`, `eps = k ×` the `pct`-quantile of the -/// local variance. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct NrcPass { - pub sigma: f32, - pub step: usize, - pub k: f32, - pub pct: f32, -} - -/// Parameters of the new colour noise reduction: the offset of the square roots and the passes -/// (fine, then coarse). -#[derive(Clone, Debug, PartialEq)] -pub struct NrcParams { - pub off: f32, - pub passes: Vec, -} - -/// The new colour noise reduction's parameters at `scale` output pixels per pixel of the original -/// ([`crate::Plan::detail_scale`]), `None` when Color is 0. pub fn nrc_params(s: &DevelopSettings, scale: f32) -> Option { - let amount = (s.detail.nr_color / 100.0) as f32; - if amount <= 0.0 { - return None; - } - let detail = (s.detail.nr_color_detail / 100.0) as f32; - let smooth = 1.0 + (s.detail.nr_color_smoothness / 100.0) as f32; - let scale = if scale.is_finite() { scale.clamp(0.05, 1.0) } else { 1.0 }; - let sigma = (2.0 + 10.0 * amount) * smooth * scale; - let k = 64.0 * amount * (1.5 - detail); - // the coefficients vary over about sigma: a grid of sigma / 2 holds them - let pass = |sigma: f32| NrcPass { sigma, step: (sigma / 2.0).floor().clamp(1.0, 16.0) as usize, k, pct: 0.2 }; - // fine, then coarse (three times wider); the joint method takes the coarse one's reach - Some(NrcParams { off: 0.003, passes: vec![pass(sigma), pass(sigma * 3.0)] }) + craft_develop::local::nrc_params(&crate::bridge::to_craft_settings(s), scale) } -/// Chroma noise variance per channel as a function of the local luminance: `α · Y + β` (shot plus read noise). -#[derive(Clone, Copy, Debug)] -pub struct NrcNoise { - pub alpha: [f32; 3], - pub beta: [f32; 3], -} - -impl NrcNoise { - #[inline] - pub fn var(&self, i: usize, y: f32) -> f32 { - (self.alpha[i] * y.max(0.0) + self.beta[i]).max(1e-14) - } -} - -/// Weighted least squares `v = a · l + b` over `(l, v, weight)` with `a, b ≥ 0`: the free fit if both come out -/// non-negative, else the better of the line through the origin (`b = 0`) and the constant (`a = 0`). -pub fn fit_nonneg_line(pts: &[(f64, f64, f64)]) -> (f64, f64) { - let sw: f64 = pts.iter().map(|p| p.2).sum::().max(1e-300); - let (ml, mv) = (pts.iter().map(|p| p.2 * p.0).sum::() / sw, pts.iter().map(|p| p.2 * p.1).sum::() / sw); - let (cov, vl) = pts.iter().fold((0.0, 0.0), |(c, v), p| (c + p.2 * (p.0 - ml) * (p.1 - mv), v + p.2 * (p.0 - ml) * (p.0 - ml))); - if vl > 0.0 { - let a = cov / vl; - let b = mv - a * ml; - if a >= 0.0 && b >= 0.0 { - return (a, b); - } - } - let sse = |a: f64, b: f64| pts.iter().map(|p| p.2 * (p.1 - a * p.0 - b).powi(2)).sum::(); - let ll: f64 = pts.iter().map(|p| p.2 * p.0 * p.0).sum(); - let origin = if ll > 0.0 { (pts.iter().map(|p| p.2 * p.0 * p.1).sum::() / ll).max(0.0) } else { 0.0 }; - let constant = mv.max(0.0); - if sse(origin, 0.0) < sse(0.0, constant) { (origin, 0.0) } else { (0.0, constant) } -} - -/// Whether `s` gets the joint colour noise reduction (`nrc_joint`, process V6 on), else main's -/// blurred chromaticity. pub fn joint_colour_nr(s: &DevelopSettings) -> bool { - s.process.process() >= lightcraft_develop::Process::V6 + craft_develop::local::joint_colour_nr(&crate::bridge::to_craft_settings(s)) } -pub fn log_lum(c: [f32; 3]) -> f32 { - (luminance_2020(c).max(1e-7) / crate::tone::GREY).log2() -} - -/// Spatial planes of one (pre-exposure) image, each tagged with the radius it was computed at. -/// `key` identifies the image; see [`crate::StageCache`]. #[derive(Clone, Default)] pub(crate) struct Planes { pub key: u64, - /// The image's key without its noise reduction (`Plan::pre_nr_key`). pub pre_nr: u64, pub log_l: Option>, - /// Keyed by its radius, process and median radius ([`BaseKey`]). pub base: Option<(BaseKey, Arc)>, pub clarity: Option<(u32, Arc)>, pub texture: Option<(u32, Arc)>, - /// Sharpening blur (exact Gaussian at the sharpen radius). pub sharpen: Option<(SharpenKey, Arc)>, - /// Dark channel and its airlight. pub dark: Option<(u32, Arc, f32)>, - /// Blurred chromaticity (local Moiré / Noise). pub chroma: Option<(u32, Arc)>, } impl Planes { - /// The planes that still fit an image differing from this one only in noise reduction, close - /// enough for a draft: the wide blurs (base, clarity, dehaze, chromaticity). Its `key` matches - /// no image, so only another draft takes them. pub fn for_other_nr(self) -> Planes { Planes { key: 0, pre_nr: self.pre_nr, log_l: None, texture: None, sharpen: None, ..self } } } -/// What the highlights/shadows base plane was computed with: its radius (`f32` bits), the -/// rendering process and the median radius ([`tone_base_detail`]). The base differs between -/// processes, so a photo moved to another one (Update to Current Process, undo) recomputes it. -pub type BaseKey = (u32, Process, usize); - -pub type SharpenKey = (u32, Process); - pub fn sharpen_key(s: &DevelopSettings, sigma: f32) -> SharpenKey { - (sigma.to_bits(), s.process.process()) + craft_develop::local::sharpen_key(&crate::bridge::to_craft_settings(s), sigma) } -/// Whether `s`'s highlights/shadows base takes [`detail_free`] (process V8 on) instead of V2's plain -/// [`median_hv`] (V2 to V7, which shipped with it and stay frozen). pub fn base_keeps_gaps(s: &DevelopSettings) -> bool { - s.process.process() >= Process::V8 + craft_develop::local::base_keeps_gaps(&crate::bridge::to_craft_settings(s)) } pub fn pixel_sharpen(s: &DevelopSettings) -> bool { - s.process.process() >= Process::V3 + craft_develop::local::pixel_sharpen(&crate::bridge::to_craft_settings(s)) } -/// The [`BaseKey`] of a base at `sigma` for `s` (`detail`: [`PlaneSigmas::base_detail`]). pub fn base_key(s: &DevelopSettings, sigma: f32, detail: usize) -> BaseKey { - (sigma.to_bits(), s.process.process(), detail) + craft_develop::local::base_key(&crate::bridge::to_craft_settings(s), sigma, detail) } -/// Reuse `slot` if it was computed with `key` (a radius's `f32` bits, or a [`BaseKey`]), else -/// compute and store it. -pub fn plane_at(slot: &mut Option<(K, Arc

)>, key: K, f: impl FnOnce() -> P) -> Arc

{ - match slot { - Some((k, p)) if *k == key => p.clone(), - _ => { - let p = Arc::new(f()); - *slot = Some((key, p.clone())); - p - } - } -} - -/// Guided-filter epsilons (EV²) of the highlights/shadows base and the clarity band. -pub const BASE_EPS: f32 = 0.35; -pub const CLARITY_EPS: f32 = 0.8; - -/// Dark channel of a pixel (dehaze). -#[inline] -pub fn dark_of(c: [f32; 3]) -> f32 { - c[0].min(c[1]).min(c[2]) -} - -/// Radius of the local Moiré / colour-noise chromaticity blur, as a fraction of the long edge. -pub const CHROMA_SIGMA: f32 = 0.004; - -/// Radii (px) of the spatial planes the settings need (`None` = not needed). -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub struct PlaneSigmas { - /// Edge-aware base for highlights/shadows ([`tone_base`]: fast guided filter, [`BASE_EPS`]; from - /// process V2 of a median at [`BASE_DETAIL`], from V8 of a detail-free plane). - pub base: Option, - /// Median radius (px) of that base ([`tone_base_detail`]: 0 under V1). - pub base_detail: usize, - /// Clarity band (fast guided filter, [`CLARITY_EPS`]). - pub clarity: Option, - /// Texture / sharpening band (Gaussian). - pub texture: Option, - /// Sharpening blur (exact Gaussian, see [`sharpen_sigma`]). - pub sharpen: Option, - /// Dehaze dark channel (Gaussian). - pub dark: Option, - /// Chromaticity blur for local Moiré / colour noise (Gaussian). - pub chroma: Option, -} - -/// Gaussian sigma (pixels) of the texture / sharpening band at `px_per_long`. -pub fn texture_sigma(px_per_long: f64) -> f32 { - (0.0018 * px_per_long as f32).max(0.6) -} - -/// Sharpening blur radius in output pixels before clamping: Radius (source pixels) times the -/// output pixels per original pixel (`native_long` = the original photo's long edge), so a preview and -/// an export show the same detail at the same displayed scale. pub fn sharpen_sigma_raw(s: &DevelopSettings, px_per_long: f64, native_long: f64) -> f32 { - let r = s.detail.sharpen_radius; - let radius = if r.is_finite() { r.clamp(0.1, 10.0) } else { 1.0 }; - (radius * px_per_long / native_long.max(1.0)) as f32 -} - -/// Smallest and largest sigma (px) of the sharpening blur. The largest is the most the Gaussian taps -/// support (CPU and GPU share them), so an enlarging export keeps every Radius step distinct. -pub const SHARPEN_SIGMA_MIN: f32 = 0.5; -pub const SHARPEN_SIGMA_MAX: f32 = lightcraft_raster::blur::GAUSS_SIGMA_MAX; - -/// The sharpening blur's sigma for a raw value of [`sharpen_sigma_raw`]. -pub fn sharpen_sigma(raw: f32) -> f32 { - raw.clamp(SHARPEN_SIGMA_MIN, SHARPEN_SIGMA_MAX) -} - -/// Match the continuous Gaussian's Nyquist response below half a pixel, using a representable -/// FIR blur. Blend the correction out between half and one pixel: no jump at the floor, and -/// full-pixel sharpening (including Radius 1 at native size) is unchanged. -pub fn sharpen_gain(raw: f32) -> f32 { - if !raw.is_finite() || raw <= 0.0 { - return 0.0; - } - if raw >= 1.0 { - return 1.0; - } - let taps = gauss_taps(sharpen_sigma(raw)); - let radius = taps.len() / 2; - let response = taps.iter().enumerate().map(|(i, &t)| if (i + radius).is_multiple_of(2) { t } else { -t }).sum::(); - let desired = -(-0.5 * std::f32::consts::PI.powi(2) * raw * raw).exp_m1(); - let ratio = desired / (1.0 - response).max(1e-6); - let blend = ((1.0 - raw) / 0.5).clamp(0.0, 1.0); - 1.0 + (ratio - 1.0) * blend + craft_develop::local::sharpen_sigma_raw(&crate::bridge::to_craft_settings(s), px_per_long, native_long) } pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, native_long: f64, q: Quality) -> PlaneSigmas { - let ppl = px_per_long as f32; - // A hidden mask, or one with no components, does not change the picture. Its sliders must - // not pick the tone base Clarity reads (#1214). - let live = |m: &&lightcraft_develop::Mask| m.visible && !m.components.is_empty(); - let local_any = |f: fn(&lightcraft_develop::LocalAdjustments) -> f64| s.masks.iter().filter(live).any(|m| f(&m.adjust) != 0.0); - let tone_active = s.light.highlights != 0.0 - || s.light.shadows != 0.0 - || s.masks.iter().filter(live).any(|m| m.adjust.highlights != 0.0 || m.adjust.shadows != 0.0); - // Edge-aware base at ~1.5% of the long edge (EV² epsilon: edges of > ~0.6 EV are preserved) - // From V2 it is taken of the median at 0.15%: lines and texture finer than that are detail, - // not tone (#632). - let base = tone_active.then(|| { - let sigma = (0.015 * ppl).max(1.0); - if q == Quality::Draft { sigma.min(24.0) } else { sigma } - }); - let clarity = (s.effects.clarity != 0.0 || local_any(|a| a.clarity)).then(|| (0.012 * ppl).max(1.0)); - // local Noise and Defringe read the fine detail band too - let texture = (s.effects.texture != 0.0 - || local_any(|a| a.texture) - || local_any(|a| a.noise) - || (!pixel_sharpen(s) && (s.detail.sharpen_amount != 0.0 || local_any(|a| a.sharpness))) - || s.masks.iter().filter(live).any(|m| m.adjust.defringe > 0.0)) - .then(|| texture_sigma(px_per_long)); - let dark = (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze)).then(|| (0.02 * ppl).max(1.0)); - let chroma = (local_any(|a| a.moire) || s.masks.iter().filter(live).any(|m| m.adjust.noise > 0.0)).then(|| (CHROMA_SIGMA * ppl).max(1.0)); - let base_detail = if base.is_some() { tone_base_detail(s, px_per_long) } else { 0 }; - // V1/V2 keep their texture-band sharpening; only V3 requests the pixel-scale plane. - let sharpen_raw = sharpen_sigma_raw(s, px_per_long, native_long); - let sharpen = (pixel_sharpen(s) && sharpen_gain(sharpen_raw) > 0.0 && (s.detail.sharpen_amount != 0.0 || local_any(|a| a.sharpness))) - .then(|| sharpen_sigma(sharpen_raw)); - PlaneSigmas { base, base_detail, clarity, texture, sharpen, dark, chroma } + craft_develop::local::plane_sigmas(&crate::bridge::to_craft_settings(s), px_per_long, native_long, crate::bridge::to_craft_quality(q)) } /// The spatial planes the per-pixel stage needs for `img` (white-balanced, before exposure), -/// reusing whatever `planes` already holds for it. Missing planes are computed side by side (each -/// one alone scales poorly: the guided filters work on small subsampled grids). +/// reusing whatever `planes` already holds for it. #[allow(clippy::too_many_arguments)] pub(crate) fn prepare( img: Arc, @@ -925,8 +256,7 @@ pub(crate) fn prepare( Prepared { img, log_l, base, clarity_blur, texture_blur, sharpen_blur, dark, chroma_blur, air, masks, px_per_long } } -/// The airlight of the whole output frame, estimated on a small render of it (`proxy_w` px wide): -/// a windowed render must dehaze with the frame's airlight, not that of the pixels it holds. +/// The airlight of the whole output frame, estimated on a small render of it (`proxy_w` px wide). pub(crate) fn frame_airlight(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, frame: &Frame, proxy_w: usize, proxy_h: usize) -> f32 { let mut img = Rgb32f::clone(&frame_proxy(src, frame, proxy_w, proxy_h)); white_balance(&mut img, info, s); @@ -934,12 +264,8 @@ pub(crate) fn frame_airlight(src: &Rgb32f, info: &SourceInfo, s: &DevelopSetting airlight(&gaussian(&img.map(dark_of), sigma)) } -/// How many airlight proxies [`frame_proxy`] keeps (one per photo and frame being zoomed into; each ≤ 1.8 MB). const FRAME_PROXIES_KEPT: usize = 4; -/// `frame.sample(src, w, h)`, kept for the last few (source, frame, size): sampling a 64 MP original down to the -/// airlight proxy reads all of it (~190 ms of CPU), and every window of a zoomed view with Dehaze asked for it again, -/// on each pan and slider tick. The proxy is taken before white balance, so a WB change still hits. fn frame_proxy(src: &Rgb32f, frame: &Frame, w: usize, h: usize) -> Arc { type Entry = (u64, Frame, usize, usize, Arc); static CACHE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); @@ -957,564 +283,7 @@ fn frame_proxy(src: &Rgb32f, frame: &Frame, w: usize, h: usize) -> Arc { img } -/// The airlight is estimated from every `AIRLIGHT_STEP`-th value of the dark channel. -pub const AIRLIGHT_STEP: usize = 7; - /// Airlight estimate: bright end of the dark channel. pub fn airlight(dark: &Plane) -> f32 { - airlight_of(dark.data.iter().step_by(AIRLIGHT_STEP).copied().collect()) -} - -/// Airlight from the sampled dark-channel values (see [`airlight`]): their 99.5th percentile. -pub fn airlight_of(mut v: Vec) -> f32 { - if v.is_empty() { - return 1.0; - } - let k = ((v.len() as f32) * 0.995) as usize; - let k = k.min(v.len() - 1); - v.select_nth_unstable_by(k, |a, b| a.total_cmp(b)); - v[k].max(0.05) -} - -#[cfg(test)] -mod tests { - /// Edits saved under V1 to V5 keep main's colour noise reduction (blurred chromaticity); V6 gets - /// the joint method of `nrc_joint`. - #[test] - fn colour_nr_follows_the_process() { - use lightcraft_develop::{DevelopSettings, Process}; - let (w, h) = (96usize, 64usize); - let img = Rgb32f::from_fn(w, h, |x, y| { - let n = |c: u32| { - let mut v = (x as u32).wrapping_mul(0x9e37_79b9) ^ (y as u32).wrapping_mul(0x85eb_ca6b) ^ c.wrapping_mul(0xc2b2_ae35) | 1; - v ^= v << 13; - v ^= v >> 17; - v ^= v << 5; - (v as f32 / u32::MAX as f32 - 0.5) * 0.02 - }; - let base = if x < w / 2 { [0.06, 0.03, 0.02] } else { [0.02, 0.04, 0.06] }; - [base[0] + n(1), base[1] + n(2), base[2] + n(3)] - }); - let run = |p: Process| { - let mut s = DevelopSettings { process: p.version(), ..Default::default() }; - s.detail.nr_color = 50.0; - let mut o = img.clone(); - denoise(&mut o, &s, 1.0, None); - o - }; - let (v1, v2, v5, v6) = (run(Process::V1), run(Process::V2), run(Process::V5), run(Process::V6)); - assert!(v1.data == v2.data && v2.data == v5.data, "V1 to V5 share main's colour NR"); - // main's colour NR clamps at 0 and keeps each pixel's luminance; the joint method keeps it too - assert!(v5.data != v6.data, "V6 takes the joint colour NR"); - let mut s = DevelopSettings { process: Process::V6.version(), ..Default::default() }; - s.detail.nr_color = 50.0; - let mut joint = img.clone(); - let p = nrc_params(&s, 1.0).expect("Color 50 has parameters"); - crate::nrc_joint::denoise(&mut joint, &p, (s.detail.nr_color_detail / 100.0) as f32, 0.5, None); - assert!(joint.data == v6.data, "V6 is the joint method"); - } - - /// Float mean of a flat, noisy dark patch over three noise realisations; linear modes assert drift bounds. - #[test] - #[ignore] - fn probe_nrc_mean_drift() { - use lightcraft_develop::DevelopSettings; - let (w, h) = (768usize, 768usize); - let mut worst = 0.0f64; - for seed0 in [0x2545_f491_4f6c_dd1du64, 0x9e37_79b9_7f4a_7c15, 0x1234_5678_9abc_def1] { - let mut seed = seed0; - let mut gauss = || { - (0..4) - .map(|_| { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5 - }) - .sum::() - * 1.732 - }; - for (name, base, sigma) in [ - ("dark warm, blue near 0", [0.006f32, 0.004, 0.0008], [0.002f32, 0.0015, 0.003]), - ("cat-like, red near 0", [0.0015, 0.004, 0.009], [0.004, 0.003, 0.005]), - ] { - let mut img = Rgb32f::new(w, h); - for p in img.data.iter_mut() { - *p = [0, 1, 2].map(|i| base[i] + sigma[i] * gauss()); - } - let mean = |im: &Rgb32f| { - let n = im.data.len() as f64; - [0, 1, 2].map(|i| im.data.iter().map(|p| p[i] as f64).sum::() / n) - }; - let m0 = mean(&img); - for nr in [25.0, 100.0] { - let mut s = DevelopSettings::default(); - s.detail.nr_color = nr; - let mut a = img.clone(); - denoise(&mut a, &s, 1.0, None); - let m = mean(&a); - let clipped0 = mean(&img.map(|p| p.map(|v| v.max(0.0)))); - let sd = |im: &Rgb32f, mm: [f64; 3]| { - [0, 1, 2].map(|i| (im.data.iter().map(|p| (p[i] as f64 - mm[i]).powi(2)).sum::() / im.data.len() as f64).sqrt()) - }; - worst = worst.max([0, 1, 2].iter().map(|&i| (m[i] / m0[i] - 1.0).abs()).fold(0.0, f64::max)); - println!( - "{name} NR {nr}: true mean {m0:.5?}, clipped noisy mean {clipped0:.5?}, after v2 {m:.5?} → {:+.3?} % vs true; noise sd {:.5?} → {:.5?}", - [0, 1, 2].map(|i| 100.0 * (m[i] / m0[i] - 1.0)), - sd(&img, m0), - sd(&a, m) - ); - } - } - } - println!("worst mean deviation {:.4} %", 100.0 * worst); - assert!(worst < 0.0005, "the joint colour NR moved a channel's mean by {:.3} %", 100.0 * worst); - } - - /// PROBE (prints, never fails): what colour NR v2 keeps of real colour. A clean synthetic scene (an - /// equal-luminance red/green edge, a 2 px red line on grey, a saturated blue patch near black, a flat grey - /// patch) plus noise; each measure compares the output with the clean scene. - #[test] - #[ignore] - fn probe_nrc_real_colour() { - use lightcraft_develop::DevelopSettings; - let (w, h) = (768usize, 512usize); - let y_of = |c: [f32; 3]| luminance_2020(c); - // two colours of the same luminance 0.03 - let red = [0.08f32, 0.0155, 0.02]; - let green = { - let g = [0.012f32, 0.04, 0.015]; - let k = y_of(red) / y_of(g); - g.map(|v| v * k) - }; - let grey = [0.03f32; 3]; - let blue_dark = [0.001f32, 0.0015, 0.02]; - // a bright saturated green next to black (a lit leaf against a dark background) - let leaf = [0.02f32, 0.12, 0.01]; - let clean = |x: usize, y: usize| -> [f32; 3] { - if y < 256 { - if x < 384 { red } else { green } - } else if x < 384 { - if (190..192).contains(&x) { red } else { grey } - } else if x < 576 { - blue_dark - } else if y < 384 { - grey - } else if x < 672 { - leaf - } else { - [0.0005f32; 3] - } - }; - let mut seed = 0x2545_f491_4f6c_dd1du64; - let mut gauss = || { - (0..4) - .map(|_| { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5 - }) - .sum::() - * 1.732 - }; - let mut img = Rgb32f::new(w, h); - for y in 0..h { - for x in 0..w { - let c = clean(x, y); - // shot + read noise per channel - img.data[y * w + x] = c.map(|v| v + (0.00002 + 0.004 * v.max(0.0)).sqrt() * 0.6 * gauss()); - } - } - let chroma = |c: [f32; 3]| { - let y = y_of(c); - c.map(|v| v - y) - }; - let dist = |a: [f32; 3], b: [f32; 3]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt(); - for nr in [25.0, 100.0] { - let mut s = DevelopSettings::default(); - s.detail.nr_color = nr; - let mut o = img.clone(); - denoise(&mut o, &s, 1.0, None); - let px = |x: usize, y: usize| o.data[y * w + x]; - // edge: chroma error 1..8 px either side, relative to the step between the two colours - let step = dist(chroma(red), chroma(green)); - let mut e = 0.0; - let mut n = 0.0; - for y in 40..216 { - for d in 1..=8 { - for x in [384 - d, 383 + d] { - e += dist(chroma(px(x, y)), chroma(clean(x, y))); - n += 1.0; - } - } - } - // line: share of the line's chroma kept (mean over its rows) - let (mut kept, mut m) = (0.0, 0.0); - for y in 300..480 { - for x in 190..192 { - let c = chroma(px(x, y)); - let r = chroma(red); - let rg = chroma(grey); - let full = [0, 1, 2].map(|i| r[i] - rg[i]); - let got = [0, 1, 2].map(|i| c[i] - rg[i]); - kept += (got[0] * full[0] + got[1] * full[1] + got[2] * full[2]) / (full[0] * full[0] + full[1] * full[1] + full[2] * full[2]); - m += 1.0; - } - } - // saturated blue near black: chroma of the patch's mean kept - let mut acc = [0.0f32; 3]; - let mut cnt = 0.0; - for y in 300..480 { - for x in 420..540 { - acc = [0, 1, 2].map(|i| acc[i] + px(x, y)[i]); - cnt += 1.0; - } - } - let mean = acc.map(|v| v / cnt); - let sat_kept = dist(chroma(mean), [0.0; 3]) / dist(chroma(blue_dark), [0.0; 3]); - // grey: residual chroma noise - let mut sd = 0.0; - let mut k = 0.0; - for y in 270..370 { - for x in 600..760 { - sd += dist(chroma(px(x, y)), [0.0; 3]).powi(2); - k += 1.0; - } - } - let mut sd0 = 0.0; - for y in 270..370 { - for x in 600..760 { - sd0 += dist(chroma(img.data[y * w + x]), [0.0; 3]).powi(2); - } - } - // leaf next to black: chroma kept in the leaf's 12 px next to the black (mean over rows) - let (mut lk, mut ln) = (0.0f32, 0.0f32); - for y in 400..500 { - for x in 660..672 { - let c = chroma(px(x, y)); - let r = chroma(leaf); - lk += (c[0] * r[0] + c[1] * r[1] + c[2] * r[2]) / (r[0] * r[0] + r[1] * r[1] + r[2] * r[2]); - ln += 1.0; - } - } - println!("NR {nr}: leaf next to black keeps {:.0} % of its chroma (12 px next to the black)", 100.0 * lk / ln); - println!( - "NR {nr}: edge error {:.1} % of the step | red line kept {:.0} % | dark blue chroma kept {:.0} % | grey chroma noise {:.5} → {:.5}", - 100.0 * e / n / step, - 100.0 * kept / m, - 100.0 * sat_kept, - (sd0 / k).sqrt(), - (sd / k).sqrt() - ); - } - } - - #[test] - fn nrc_noise_fit_is_non_negative() { - // a falling cloud would give a negative slope: the constant fits instead - let (a, b) = fit_nonneg_line(&[(0.0, 4.0, 1.0), (1.0, 3.0, 1.0), (2.0, 2.0, 1.0)]); - assert!(a == 0.0 && (b - 3.0).abs() < 1e-9); - // a line through a negative intercept: refitted through the origin - let (a, b) = fit_nonneg_line(&[(1.0, 1.0, 1.0), (2.0, 3.0, 1.0), (3.0, 5.0, 1.0)]); - assert!(a > 0.0 && b == 0.0); - // an exact shot + read noise line is found as it is - let (a, b) = fit_nonneg_line(&[(0.0, 2.0, 1.0), (1.0, 5.0, 1.0), (2.0, 8.0, 1.0)]); - assert!((a - 3.0).abs() < 1e-9 && (b - 2.0).abs() < 1e-9); - } - use super::*; - use lightcraft_color::cct::xy_to_uv; - - #[test] - fn guided_preserves_step_edges_and_flattens_texture() { - let p = Plane::from_fn(80, 20, |x, y| if x < 40 { -2.0 } else { 2.0 } + if (x + y) % 2 == 0 { 0.05 } else { -0.05 }); - let q = guided(&p, 4.0, 0.3); - // edge kept - assert!(q.get(35, 10) < -1.5 && q.get(45, 10) > 1.5); - // checkerboard texture removed away from the edge - assert!((q.get(10, 10) - q.get(11, 10)).abs() < 0.02); - } - - #[test] - fn wb_as_shot_is_identity_and_warming_adds_red() { - let s = DevelopSettings::default(); - let info = SourceInfo::default(); - let mut img = Rgb32f::filled(4, 4, [0.3, 0.3, 0.3]); - scene_linear_pre(&mut img, &info, &s); - assert!((img.get(0, 0)[0] - 0.3).abs() < 1e-6); - let mut warm = s.clone(); - warm.wb.mode = lightcraft_develop::WbMode::Custom; - warm.wb.temp = 9000.0; - let mut img2 = Rgb32f::filled(4, 4, [0.3, 0.3, 0.3]); - scene_linear_pre(&mut img2, &info, &warm); - let c = img2.get(0, 0); - assert!(c[0] > c[2], "{c:?}"); - // luminance preserved - assert!((luminance_2020(c) - 0.3).abs() < 0.01); - } - - // A windowed render's airlight proxy is kept per (source, frame, size): the airlight is the one sampling anew gives, - // and another source or frame of the same size gets its own, never the proxy kept for the last one - #[test] - fn the_kept_airlight_proxy_matches_a_fresh_one_and_misses_on_another_source_or_frame() { - let (info, s) = (SourceInfo::default(), DevelopSettings::default()); - let hazy = Rgb32f::from_fn(300, 200, |x, y| { - let v = 0.05 + 0.6 * x as f32 / 300.0; - [v, v * 0.95, v * (0.8 + 0.2 * y as f32 / 200.0)] - }); - let other = Rgb32f::from_fn(300, 200, |x, y| [0.02 + 0.1 * ((x + y) % 7) as f32 / 7.0; 3]); - let fresh = |src: &Rgb32f, frame: &Frame| { - let mut img = frame.sample(src, 48, 32); - white_balance(&mut img, &info, &s); - airlight(&gaussian(&img.map(dark_of), (0.02 * frame.px_per_long(48)).max(1.0) as f32)) - }; - let frame = crate::frame_for(&hazy, &info, &s, true); - let kept = frame_proxy(&hazy, &frame, 48, 32); - assert!(Arc::ptr_eq(&kept, &frame_proxy(&hazy, &frame, 48, 32)), "the second ask is served from the cache"); - assert_eq!(frame_airlight(&hazy, &info, &s, &frame, 48, 32).to_bits(), fresh(&hazy, &frame).to_bits()); - assert_eq!(frame_airlight(&hazy, &info, &s, &frame, 48, 32).to_bits(), fresh(&hazy, &frame).to_bits()); - // another source of the same size - assert_ne!(fresh(&other, &frame), fresh(&hazy, &frame)); - assert_eq!(frame_airlight(&other, &info, &s, &frame, 48, 32).to_bits(), fresh(&other, &frame).to_bits()); - // the same source, cropped to its darker half - let mut cropped = frame.clone(); - cropped.crop.rect.x1 = 0.5; - assert_ne!(fresh(&hazy, &cropped), fresh(&hazy, &frame)); - assert_eq!(frame_airlight(&hazy, &info, &s, &cropped, 48, 32).to_bits(), fresh(&hazy, &cropped).to_bits()); - } - - #[test] - fn a_hidden_or_empty_mask_does_not_request_the_tone_base() { - use lightcraft_develop::{Mask, MaskComponent, MaskOp, MaskShape}; - use lightcraft_geom::Point; - let shape = MaskShape::Linear { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0) }; - let component = MaskComponent { name: None, op: MaskOp::Add, invert: false, shape }; - let mut s = DevelopSettings::default(); - s.masks.push(Mask { - visible: false, - components: vec![component], - adjust: lightcraft_develop::LocalAdjustments { highlights: 40.0, ..Default::default() }, - ..Default::default() - }); - assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_none()); - s.masks[0].visible = true; - s.masks[0].components.clear(); - assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_none()); - s.masks[0].components.push(MaskComponent { - name: None, - op: MaskOp::Add, - invert: false, - shape: MaskShape::Linear { start: Point::new(0.0, 0.0), end: Point::new(1.0, 0.0) }, - }); - assert!(plane_sigmas(&s, 2000.0, 2000.0, Quality::Full).base.is_some()); - } - - #[test] - fn exposure_doubles() { - let mut s = DevelopSettings::default(); - s.light.exposure = 1.0; - let mut img = Rgb32f::filled(2, 2, [0.1, 0.2, 0.3]); - scene_linear_pre(&mut img, &SourceInfo::default(), &s); - assert!((img.get(1, 1)[2] - 0.6).abs() < 1e-5); - } - - /// [`kelvin_to_legacy`] inverts [`legacy_to_kelvin`] over the whole relative slider range and back: the - /// round trip returns the start, in both directions, to the precision of the Kelvin / tint parametrisation. - #[test] - fn kelvin_to_legacy_inverts_legacy_to_kelvin() { - for as_shot in [(4986.0, -2.0), (6500.0, 0.0), (3200.0, 14.0), (9500.0, -12.0)] { - // the relative slider's whole reach: temp 0..100 (2000–13550 K around 6500), tint −150..150 - for pct in [0.0, 12.5, 25.0, 50.0, 75.0, 100.0] { - for tint in [-150.0, -40.0, 0.0, 33.0, 150.0] { - let (lt, ltint) = controls_relative(pct, tint); - let (kt, ktint) = legacy_to_kelvin(lt, ltint, as_shot); - // past the Kelvin parametrisation's own reach (its search runs 1000–50000 K) the forward - // conversion has already clamped, so the pair is not expected to come back - if !(1050.0..=49_000.0).contains(&kt) { - continue; - } - let back = kelvin_to_legacy(kt, ktint, as_shot).unwrap(); - let (x1, y1) = xy_to_uv(temp_tint_to_xy(lt, ltint)); - let (x2, y2) = xy_to_uv(temp_tint_to_xy(back.0, back.1)); - // the pair may differ by more than the slider's own step at the extreme corners (the Kelvin - // parametrisation is read back through a search), but never by much, and the white it renders - // is the same - assert!( - (back.0 - lt).abs() <= lt.abs() * 0.01 && (back.1 - ltint).abs() < 0.5, - "as shot {as_shot:?}: relative ({lt}, {ltint}) -> kelvin ({kt}, {ktint}) -> {back:?}" - ); - assert!((x1 - x2).hypot(y1 - y2) < 1e-3, "as shot {as_shot:?}: relative ({lt}, {ltint}) -> kelvin ({kt}, {ktint}) -> {back:?}"); - } - } - // the other direction: every white the relative scale can hold maps back to a pair that renders the same - for kt in [as_shot.0, 2500.0, 4200.0, 6500.0, 12000.0] { - for ktint in [-60.0, 0.0, 45.0] { - let Some((lt, ltint)) = kelvin_to_legacy(kt, ktint, as_shot) else { continue }; - // outside the slider's reach the relative scale has no value for this white: the forward - // conversion would clamp, so the round trip is not expected to close there - if !(2000.0..=13550.0).contains(<) || ltint.abs() > 150.0 { - continue; - } - let (kt2, ktint2) = legacy_to_kelvin(lt, ltint, as_shot); - let (x1, y1) = xy_to_uv(temp_tint_to_xy(kt, ktint)); - let (x2, y2) = xy_to_uv(temp_tint_to_xy(kt2, ktint2)); - assert!( - (x1 - x2).hypot(y1 - y2) < 1e-3, - "as shot {as_shot:?}: kelvin ({kt}, {ktint}) -> relative ({lt}, {ltint}) -> ({kt2}, {ktint2})" - ); - } - } - // the source's own white is the relative scale's as-shot reference, exactly - assert_eq!(kelvin_to_legacy(as_shot.0, as_shot.1, as_shot), Some((6500.0, 0.0))); - } - // the exact inverse of the special case inside legacy_to_kelvin - assert_eq!(kelvin_to_legacy(4986.0, -2.0, (4986.0, -2.0)), Some((6500.0, 0.0))); - assert_eq!(legacy_to_kelvin(6500.0, 0.0, (4986.0, -2.0)), (4986.0, -2.0)); - // hostile numbers answer None, never a panic or a plausible lie - assert_eq!(kelvin_to_legacy(f64::NAN, 0.0, (5000.0, 0.0)), None); - assert_eq!(kelvin_to_legacy(5000.0, f64::INFINITY, (5000.0, 0.0)), None); - assert_eq!(kelvin_to_legacy(5000.0, 0.0, (f64::NAN, 0.0)), None); - } - - /// The relative scale's `(temp, tint)` for a slider temperature at `pct` % (2000–7000 K fill the left half) and tint. - fn controls_relative(pct: f64, tint: f64) -> (f64, f64) { - let t = if pct <= 50.0 { 2000.0 + pct * 100.0 } else { 7000.0 + (pct - 50.0) * 131.0 }; - (t, tint) - } -} - -#[cfg(test)] -mod fast_tests { - use super::*; - - /// [`detail_free`] enlarges the coarse median as it clamps; the result is the plain - /// composition of `resize` and [`median_hv`], bit for bit. - #[test] - fn detail_free_matches_its_reference() { - use lightcraft_raster::resample::{Filter, resize}; - for (w, h) in [(1, 1), (2, 1), (3, 3), (4, 7), (61, 47), (200, 31)] { - let p = Plane::from_fn(w, h, |x, y| ((x * 37 + y * 101) % 23) as f32 * 0.4 - 4.0 + if (x / 5 + y / 7) % 2 == 0 { 2.0 } else { 0.0 }); - for r in [1, 2, 5, 10] { - let fine = median_hv(&p, r); - let (lw, lh) = (w.div_ceil(BASE_COARSE_STEP), h.div_ceil(BASE_COARSE_STEP)); - let coarse = resize(&median_hv(&resize(&p, lw, lh, Filter::Box), r), w, h, Filter::Bilinear); - let want: Vec = (0..w * h).map(|i| clamp_between(p.data[i], fine.data[i], coarse.data[i]).to_bits()).collect(); - let got: Vec = detail_free(&p, r).data.iter().map(|v| v.to_bits()).collect(); - assert_eq!(got, want, "{w}×{h} r={r}"); - } - } - } - - /// CPU highlights/shadows base timings on the #3460 frame size: - /// `cargo test --release -p lightcraft-pipeline bench_tone_base_cpu -- --ignored --nocapture`. - #[test] - #[ignore] - fn bench_tone_base_cpu() { - let (w, h) = (6960, 4640); - let r = base_detail_radius(w as f64); - let p = Plane::from_fn(w, h, |x, y| ((x * 7 + y * 13) % 1000) as f32 / 250.0 - 6.0 + if (x / 40 + y / 40) % 2 == 0 { 1.0 } else { 0.0 }); - let sigma = 0.015 * w as f32; - let time = |name: &str, f: &dyn Fn() -> Plane| { - let mut ts: Vec = (0..5) - .map(|_| { - let t = std::time::Instant::now(); - std::hint::black_box(f()); - t.elapsed().as_secs_f64() * 1e3 - }) - .collect(); - ts.sort_by(f64::total_cmp); - eprintln!("{name:<20} min {:.1} ms median {:.1} ms", ts[0], ts[2]); - }; - time("median_hv", &|| median_hv(&p, r)); - time("detail_free", &|| detail_free(&p, r)); - time("guided_fast", &|| guided_fast(&p, sigma, BASE_EPS)); - time("tone_base", &|| tone_base(&p, sigma, r, true)); - } - - /// The previous fast path, including its two materialized coefficient resizes. - fn resized_reference(p: &Plane, sigma: f32, eps: f32) -> Plane { - use lightcraft_raster::resample::{Filter, resize}; - let s = guided_fast_step(sigma); - if s <= 1 { - return guided(p, sigma, eps); - } - let lo = resize(p, p.width.div_ceil(s).max(1), p.height.div_ceil(s).max(1), Filter::Box); - let (a, b) = guided_coeffs(&lo, sigma / s as f32, eps); - let (a, b) = (resize(&a, p.width, p.height, Filter::Bilinear), resize(&b, p.width, p.height, Filter::Bilinear)); - Plane::from_fn(p.width, p.height, |x, y| a.get(x, y) * p.get(x, y) + b.get(x, y)) - } - - #[test] - fn sampled_coefficients_match_materialized_resizes() { - for (w, h) in [(0, 0), (1, 1), (1, 19), (23, 1), (2, 3), (17, 13), (64, 48), (161, 119)] { - let planes = [ - Plane::filled(w, h, -3.25), - Plane::from_fn(w, h, |x, y| ((x * 7919 + y * 104729) % 97) as f32 / 7.0 - 8.0), - Plane::from_fn(w, h, |x, y| { - if x == w / 2 && y == h / 2 { - 9.0 - } else if x < w / 2 { - -5.0 - } else { - 2.0 - } - }), - ]; - // Step 1 fallback, every small step, Draft's cap, and the maximum step (16). - for sigma in [0.0, 2.99, 5.99, 6.0, 9.0, 12.0, 24.0, 48.0, 200.0] { - for eps in [BASE_EPS, CLARITY_EPS, 0.0001] { - for p in &planes { - let expected = resized_reference(p, sigma, eps); - let actual = guided_fast(p, sigma, eps); - assert_eq!((actual.width, actual.height), (w, h)); - assert_eq!(actual.data, expected.data, "{w}x{h}, sigma {sigma}, eps {eps}"); - } - } - } - } - } - - #[test] - fn sampled_tone_base_keeps_the_detail_free_plane_before_the_guided_filter() { - let p = Plane::from_fn(73, 51, |x, y| if x % 9 == 0 { 3.0 } else { -4.0 + ((x + y) % 7) as f32 * 0.03 }); - for sigma in [6.0, 24.0, 120.0] { - for detail in [0, 1, 3, BASE_DETAIL_MAX] { - let free = detail_free(&p, detail); - assert_eq!(tone_base(&p, sigma, detail, true).data, resized_reference(&free, sigma, BASE_EPS).data, "{sigma}, {detail}"); - } - } - } - - #[test] - fn fast_guided_close_to_reference() { - let p = Plane::from_fn(160, 120, |x, y| ((x as f32 * 0.13).sin() + (y as f32 * 0.07).cos()) * 2.0 + if x > 80 { 1.5 } else { 0.0 }); - let a = guided(&p, 12.0, 0.3); - let b = guided_fast(&p, 12.0, 0.3); - let err: f32 = a.data.iter().zip(&b.data).map(|(u, v)| (u - v).abs()).sum::() / a.len() as f32; - assert!(err < 0.08, "{err}"); - } -} - -#[cfg(test)] -mod nr_tests { - use super::*; - - #[test] - fn luminance_nr_reduces_noise_keeps_mean() { - let mut img = Rgb32f::from_fn(64, 64, |x, y| { - let n = (((x * 7919 + y * 104729) % 97) as f32 / 97.0 - 0.5) * 0.06; - [0.2 + n; 3] - }); - let var = |im: &Rgb32f| { - let m = im.data.iter().map(|p| p[1]).sum::() / im.len() as f32; - (im.data.iter().map(|p| (p[1] - m).powi(2)).sum::() / im.len() as f32, m) - }; - let (v0, m0) = var(&img); - let mut s = DevelopSettings::default(); - s.detail.nr_luminance = 80.0; - denoise(&mut img, &s, 1.0, None); - let (v1, m1) = var(&img); - assert!(v1 < v0 * 0.5, "{v0} -> {v1}"); - assert!((m1 - m0).abs() < 0.01); - } + craft_develop::local::airlight(&crate::bridge::to_craft_plane(dark)) } diff --git a/crates/pipeline/src/local_tone.rs b/crates/pipeline/src/local_tone.rs index cb2d7d3c29..4136cc5345 100644 --- a/crates/pipeline/src/local_tone.rs +++ b/crates/pipeline/src/local_tone.rs @@ -1,22 +1,11 @@ -//! The camera's local tone mapping: a raw's DNG `ProfileGainTableMap` (Apple ProRAW), rendered -//! when the photo's Profile option "Camera local tone mapping" is on. Off by default: Lightroom -//! Classic renders ProRAW without it (see `lightcraft_raw::gaintable`). -//! -//! The map is a per-pixel gain that depends on the pixel's position in the raw's active area and -//! on its colour after the baseline exposure (linear ProPhoto). The source the pipeline gets is -//! exactly that colour (scene-linear Rec.2020 after the baseline exposure), so the gain is -//! evaluated here, on the resampled source at output resolution: a preview colours only the pixels -//! it shows. A gain multiplies R, G and B alike, so it commutes with the white balance (a matrix) -//! that follows. Files that also carry a `ProfileLookTable` get the gain after the table instead of -//! before it (DNG 1.7.1); Apple ProRAW has none. +//! The camera's local tone mapping: a raw's DNG `ProfileGainTableMap`, backed by `craft_develop::local_tone`. -use lightcraft_color::{D50, D65, PROPHOTO, REC2020, bradford}; +use lightcraft_develop::DevelopSettings; use lightcraft_geom::Point; use lightcraft_raster::Rgb32f; -use lightcraft_raw::gaintable::{GainTableMap, GainTableMapApply, SourcePlacement}; +use lightcraft_raw::gaintable::{GainTableMap, SourcePlacement}; use crate::{Plan, SourceInfo}; -use lightcraft_develop::DevelopSettings; /// A raw's gain table map and where its developed source sits in the active area. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] @@ -34,29 +23,35 @@ pub fn enabled(info: &SourceInfo, s: &DevelopSettings) -> bool { /// local tone gain at each pixel. Blank canvas (outside a lens / perspective warp) is left alone. pub fn apply(img: &mut Rgb32f, info: &SourceInfo, p: &Plan<'_>) { let Some(lt) = info.local_tone.as_deref().filter(|_| enabled(info, &p.settings)) else { return }; - let Some(eval) = lt.map.evaluator() else { return }; let (w, h) = (img.width, img.height); let frame = &p.frame; let (ow, oh) = (frame.ow.max(1e-9), frame.oh.max(1e-9)); let o2t = frame.out_to_oriented(w, h); let user = frame.orient.inverse(); - let to_prophoto = PROPHOTO.from_xyz().mul(&bradford(D65, D50)).mul(&REC2020.to_xyz()).to_f32(); - crate::for_rows(&mut img.data, w, |y, row| { - for (x, px) in row.iter_mut().enumerate() { - // output pixel → user-oriented source px → EXIF-oriented source (0..1) → active area - let s = match &frame.warp { - Some(wp) => match wp.frame(&o2t, x, y) { - Some((_, s)) => s, - None => continue, - }, - None => o2t.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)), - }; - let (u, v) = user.map(s.x / ow, s.y / oh, 1.0, 1.0); - let (ax, ay) = lt.placement.active(u, v); - let m = &to_prophoto; - let q: [f32; 3] = std::array::from_fn(|i| m[i][0] * px[0] + m[i][1] * px[1] + m[i][2] * px[2]); - let g = eval.gain(q, ax, ay); - *px = px.map(|c| c * g); - } + let craft_lt = craft_develop::local_tone::LocalTone { + map: lt.map.clone(), + placement: craft_develop::sensor::gaintable::SourcePlacement { + rect: lt.placement.rect, + orientation: match lt.placement.orientation { + lightcraft_geom::Orientation::Normal => craft_geom::Orientation::Normal, + lightcraft_geom::Orientation::FlipH => craft_geom::Orientation::FlipH, + lightcraft_geom::Orientation::Rotate180 => craft_geom::Orientation::Rotate180, + lightcraft_geom::Orientation::FlipV => craft_geom::Orientation::FlipV, + lightcraft_geom::Orientation::Transpose => craft_geom::Orientation::Transpose, + lightcraft_geom::Orientation::Rotate90 => craft_geom::Orientation::Rotate90, + lightcraft_geom::Orientation::Transverse => craft_geom::Orientation::Transverse, + lightcraft_geom::Orientation::Rotate270 => craft_geom::Orientation::Rotate270, + }, + }, + }; + let mut craft = crate::bridge::take_craft_rgb32f(img); + craft_develop::local_tone::apply(&mut craft, &craft_lt, |x, y| { + let s = match &frame.warp { + Some(wp) => wp.frame(&o2t, x, y)?.1, + None => o2t.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)), + }; + let (u, v) = user.map(s.x / ow, s.y / oh, 1.0, 1.0); + Some(lt.placement.active(u, v)) }); + crate::bridge::put_craft_rgb32f(img, craft); } diff --git a/crates/pipeline/src/lut.rs b/crates/pipeline/src/lut.rs index 29a9649a1c..25942443c2 100644 --- a/crates/pipeline/src/lut.rs +++ b/crates/pipeline/src/lut.rs @@ -1,143 +1,3 @@ -//! 3D LUT profiles: `.cube` files (the plain-text Cube LUT format: `LUT_3D_SIZE`, optional -//! `DOMAIN_MIN` / `DOMAIN_MAX`, then size³ "r g b" lines with red changing fastest), applied to -//! the display-encoded output colour and blended by the profile amount. Profiles are registered -//! here by id (`lut:…`) and found by the finishing stage (CPU loop and GPU kernel alike). +//! 3D LUT profiles, backed by `craft_develop::lut`. -use std::collections::HashMap; -use std::sync::{Arc, OnceLock, RwLock}; - -/// A 3D colour lookup table. -#[derive(Clone, Debug, PartialEq)] -pub struct Lut3d { - pub size: usize, - pub data: Vec<[f32; 3]>, - pub domain_min: [f32; 3], - pub domain_max: [f32; 3], - pub title: Option, -} - -impl Lut3d { - /// Parse a `.cube` file. - pub fn parse_cube(text: &str) -> Result { - 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). - pub fn apply(&self, c: [f32; 3]) -> [f32; 3] { - let n = self.size; - let s = (n - 1) as f32; - let mut idx = [0usize; 3]; - let mut frac = [0.0f32; 3]; - for k in 0..3 { - let span = (self.domain_max[k] - self.domain_min[k]).max(1e-6); - let x = (((c[k] - self.domain_min[k]) / span).clamp(0.0, 1.0)) * s; - let i = (x.floor() as usize).min(n - 2); - idx[k] = i; - frac[k] = x - i as f32; - } - let at = |r: usize, g: usize, b: usize| self.data[r + n * (g + n * b)]; - let lerp = |a: [f32; 3], b: [f32; 3], t: f32| [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; - let (r, g, b) = (idx[0], idx[1], idx[2]); - let c00 = lerp(at(r, g, b), at(r + 1, g, b), frac[0]); - let c10 = lerp(at(r, g + 1, b), at(r + 1, g + 1, b), frac[0]); - let c01 = lerp(at(r, g, b + 1), at(r + 1, g, b + 1), frac[0]); - let c11 = lerp(at(r, g + 1, b + 1), at(r + 1, g + 1, b + 1), frac[0]); - lerp(lerp(c00, c10, frac[1]), lerp(c01, c11, frac[1]), frac[2]) - } -} - -fn registry() -> &'static RwLock>> { - static R: OnceLock>>> = OnceLock::new(); - R.get_or_init(Default::default) -} - -/// Make a LUT available to renders under profile id `id` (`lut:…`). -pub fn register(id: &str, lut: Lut3d) { - registry().write().unwrap_or_else(|e| e.into_inner()).insert(id.to_string(), Arc::new(lut)); -} - -/// The LUT registered for profile `id`. -pub fn get(id: &str) -> Option> { - if !id.starts_with("lut:") { - return None; - } - registry().read().unwrap_or_else(|e| e.into_inner()).get(id).cloned() -} - -/// Forget a LUT profile. -pub fn unregister(id: &str) { - registry().write().unwrap_or_else(|e| e.into_inner()).remove(id); -} - -/// Profile ids that render with a LUT. -pub fn is_lut_profile(id: &str) -> bool { - id.starts_with("lut:") -} - -#[cfg(test)] -mod tests { - use super::*; - - fn cube(f: impl Fn([f32; 3]) -> [f32; 3], n: usize) -> String { - let mut s = format!("TITLE \"test\"\nLUT_3D_SIZE {n}\n"); - for b in 0..n { - for g in 0..n { - for r in 0..n { - let c = f([r as f32 / (n - 1) as f32, g as f32 / (n - 1) as f32, b as f32 / (n - 1) as f32]); - s.push_str(&format!("{} {} {}\n", c[0], c[1], c[2])); - } - } - } - 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(); - assert_eq!(id.title.as_deref(), Some("test")); - let v = id.apply([0.2, 0.55, 0.9]); - assert!(v.iter().zip([0.2, 0.55, 0.9]).all(|(a, b)| (a - b).abs() < 1e-5), "{v:?}"); - let swap = Lut3d::parse_cube(&cube(|c| [c[2], c[1], c[0]], 9)).unwrap(); - let v = swap.apply([0.1, 0.5, 0.8]); - assert!((v[0] - 0.8).abs() < 1e-5 && (v[2] - 0.1).abs() < 1e-5, "{v:?}"); - assert!(Lut3d::parse_cube("LUT_1D_SIZE 4\n0 0 0").is_err()); - assert!(Lut3d::parse_cube("LUT_3D_SIZE 2\n0 0 0\n").is_err(), "too few entries"); - } - - #[test] - fn non_finite_entries_rejected() { - let bad_line = |body: &str| { - let e = Lut3d::parse_cube(body).expect_err(body); - assert!(e.starts_with("bad line"), "{e}"); - }; - bad_line(&format!("LUT_3D_SIZE 2\n{}", "-inf inf nan\n".repeat(8))); - bad_line(&format!("LUT_3D_SIZE 2\n{}", "1e39 0 0\n".repeat(8))); - bad_line(&format!("LUT_3D_SIZE 2\n-inf 0 0\n{}", "0 0 0\n".repeat(7))); - bad_line(&format!("LUT_3D_SIZE 2\nnan 0 0\n{}", "0 0 0\n".repeat(8))); - bad_line(&format!("LUT_3D_SIZE 2\ninf 0 0\n{}", "0 0 0\n".repeat(8))); - let ok = cube(|c| c, 2); - assert!(Lut3d::parse_cube(&ok).is_ok()); - assert!(Lut3d::parse_cube(&format!("DOMAIN_MIN nan 0 0\n{ok}")).is_err()); - assert!(Lut3d::parse_cube(&format!("DOMAIN_MAX inf 1 1\n{ok}")).is_err()); - } -} +pub use craft_develop::lut::{Lut3d, get, is_lut_profile, register, unregister}; diff --git a/crates/pipeline/src/nrc_joint.rs b/crates/pipeline/src/nrc_joint.rs index 37a55d07fb..5d89b1d0bb 100644 --- a/crates/pipeline/src/nrc_joint.rs +++ b/crates/pipeline/src/nrc_joint.rs @@ -1,1175 +1,18 @@ -//! Linear colour NR with a fixed, denoised joint guide. Strength controls the spatial scale; -//! noise-normalized guide distances control which neighbours can exchange colour. Both chroma -//! components use the same weights. Symmetric fluxes preserve the grid's channel sums, including -//! at its boundaries; no nonnegative clamp or square-root bias correction is involved. +//! Linear colour NR with a fixed, denoised joint guide, backed by `craft_develop::nrc_joint`. -use lightcraft_color::luminance_2020; -use lightcraft_raster::{Rgb32f, blur::gaussian, resample::Filter}; +use lightcraft_raster::Rgb32f; -use crate::{ - for_rows, - local::{NrcNoise, NrcParams, fit_nonneg_line}, +pub use craft_develop::nrc_joint::{ + JointNoise, NoiseSample, SpeckBrake, noise_from_samples, noise_sample_stride, scale_plan, speck_brake, strength, tolerance, }; -#[derive(Clone, Copy, Debug)] -pub struct JointNoise { - pub model: NrcNoise, - /// Do not extrapolate beyond bands that contain usable noise measurements. - pub ymax: [f32; 3], - pub tolerance: f32, -} - -impl JointNoise { - pub fn var(&self, i: usize, y: f32) -> f32 { - self.model.var(i, y.min(self.ymax[i])) - } -} - -fn yuv(c: [f32; 3]) -> [f32; 3] { - let y = luminance_2020(c); - [y, c[0] - y, c[2] - y] -} - -/// Noise of Y, R-Y and B-Y measured from small high-pass residuals, not the colour variance -/// of a wide smoothing window. The median-square calibration is for Gaussian residuals. -/// Luminance bands with predominantly texture may only lower their weight in the fit: they -/// cannot force a shadow scene's extrapolated highlight noise arbitrarily high. -fn noise_model(img: &Rgb32f) -> JointNoise { - if img.width < 3 || img.height < 3 { - return JointNoise { model: NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }, ymax: [0.0; 3], tolerance: 1.0 }; - } - let mut samples = Vec::new(); - push_samples(img, noise_sample_stride(img.len()), &mut samples); - noise_from_samples(samples) -} - -/// The noise samples of `img` (Y, R-Y, B-Y) every `stride` pixels, in pixel order (see [`noise_model`]). -fn push_samples(img: &Rgb32f, stride: usize, samples: &mut Vec) { - if img.width < 3 || img.height < 3 { - return; - } - for index in (0..img.len()).step_by(stride) { - let (x, y) = (index % img.width, index / img.width); - if x == 0 || y == 0 || x + 1 == img.width || y + 1 == img.height { - continue; - } - let Some(c) = img.data.get(index) else { continue }; - let mut residual = [[0.0f32; 3]; 3]; - let mut brightness = 0.0; - let mut valid = true; - for (scale, delta) in [1usize, 2, 4].into_iter().enumerate() { - // Tiny images use the nearest supported scale rather than extending an edge - // into the noise samples. - let delta = delta.min(x).min(y).min(img.width - x - 1).min(img.height - y - 1); - let neighbours = [index - delta, index + delta, index - delta * img.width, index + delta * img.width]; - let mut m = [0.0f32; 3]; - for n in neighbours { - if let Some(p) = img.data.get(n) { - m = std::array::from_fn(|i| m[i] + 0.25 * p[i]); - } - } - residual[scale] = std::array::from_fn(|i| (c[i] - m[i]).powi(2)); - brightness += m[0] / 3.0; - valid &= c.iter().chain(m.iter()).all(|v| v.is_finite()); - } - if valid { - samples.push((brightness.max(0.0), residual)); - } - } -} - -/// Side of the tiles a frame's noise is measured on (px). -const TILE: usize = 128; -/// Tiles per row and column: many small tiles follow a mostly dark frame's few bright parts better -/// than a few large ones. -const GRID: usize = 12; - -/// The windows of a `full_w × full_h` frame its noise is measured on: the whole frame up to the -/// area of `GRID²` tiles, else `GRID × GRID` tiles spread evenly over it. A windowed render sees -/// only part of the frame; measured on these, every window of it gets the same noise model. +/// Tile windows covering `(full_w, full_h)` for [`noise_of_tiles`]. pub fn tiles(full_w: usize, full_h: usize) -> Vec { - if full_w * full_h <= GRID * GRID * TILE * TILE || full_w < 2 * TILE || full_h < 2 * TILE { - return vec![crate::PixelWindow { x: 0, y: 0, w: full_w, h: full_h }]; - } - let at = |n: usize, k: usize| ((n - TILE) as f64 * (k as f64 + 0.5) / GRID as f64).round() as usize; - (0..GRID * GRID).map(|k| crate::PixelWindow { x: at(full_w, k % GRID), y: at(full_h, k / GRID), w: TILE, h: TILE }).collect() + craft_develop::nrc_joint::tiles(full_w, full_h).into_iter().map(|w| crate::PixelWindow { x: w.x, y: w.y, w: w.w, h: w.h }).collect() } -/// The noise model of `tiles` of a frame (linear RGB at output scale, see [`tiles`]): the same -/// measurement as for a whole image, with the samples of all tiles together. +/// Measure joint noise from pre-extracted pixel windows. pub fn noise_of_tiles(tiles: &[Rgb32f]) -> JointNoise { - let transformed: Vec = tiles.iter().map(|t| t.map(yuv)).collect(); - let stride = noise_sample_stride(transformed.iter().map(Rgb32f::len).sum()); - let mut samples = Vec::new(); - for t in &transformed { - push_samples(t, stride, &mut samples); - } - if samples.is_empty() { - return JointNoise { model: NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }, ymax: [0.0; 3], tolerance: 1.0 }; - } - noise_from_samples(samples) -} - -/// Distance between the noise samples of a `len`-pixel plane (CPU and GPU take the same pixels). -pub fn noise_sample_stride(len: usize) -> usize { - len.div_ceil(crate::local::NRC_SAMPLES).max(1) | 1 -} - -/// One noise sample: the mean brightness of its neighbourhoods and the squared high-pass residual of -/// Y, R−Y, B−Y at spacings 1, 2 and 4. -pub type NoiseSample = (f32, [[f32; 3]; 3]); - -/// The fitted noise model from the samples, in pixel order (see `noise_model`). -pub fn noise_from_samples(samples: Vec) -> JointNoise { - // Moving a slider re-renders the same image: the last fit is reused for identical samples (64-bit - // hash of their bits and count; the samples alone determine the fit). - static LAST: std::sync::Mutex> = std::sync::Mutex::new(None); - let mut hash = 0xcbf2_9ce4_8422_2325u64 ^ samples.len() as u64; - for s in &samples { - for v in std::iter::once(s.0).chain(s.1.iter().flatten().copied()) { - hash = (hash ^ u64::from(v.to_bits())).wrapping_mul(0x0000_0100_0000_01b3).rotate_left(5); - } - } - if let Some((h, noise)) = *LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner) - && h == hash - { - return noise; - } - let noise = fit_noise(samples); - *LAST.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((hash, noise)); - noise -} - -fn fit_noise(samples: Vec) -> JointNoise { - // brightness order, ties in pixel order (as a stable sort): sort compact keys (the bits `total_cmp` - // compares by, then the index), then gather - let mut keys: Vec<(i32, u32)> = samples - .iter() - .enumerate() - .map(|(k, s)| { - let bits = s.0.to_bits() as i32; - (bits ^ (((bits >> 31) as u32) >> 1) as i32, k as u32) - }) - .collect(); - keys.sort_unstable(); - let samples: Vec = keys.iter().filter_map(|&(_, k)| samples.get(k as usize).copied()).collect(); - const BANDS: usize = 16; - let per = samples.len().div_ceil(BANDS).max(32); - let mut pts: [Vec<(f64, f64, f64)>; 3] = std::array::from_fn(|_| Vec::new()); - let mut r: Vec = Vec::with_capacity(per); - for band in samples.chunks(per).filter(|b| b.len() >= 32) { - let y = band.iter().map(|p| p.0 as f64).sum::() / band.len() as f64; - for (i, pts) in pts.iter_mut().enumerate() { - let mut variance = 1e-14f64; - for scale in 0..3 { - r.clear(); - r.extend(band.iter().map(|p| p.1[scale][i])); - let middle = r.len() / 2; - let (_, median, _) = r.select_nth_unstable_by(middle, f32::total_cmp); - // Each kernel has norm squared 1.25. Larger spacings recover noise - // hidden by the positive spatial correlations of demosaiced RGB. - variance = variance.max(*median as f64 / (0.454_936_4 * 1.25)); - } - pts.push((y, variance, band.len() as f64)); - } - } - let mut model = NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }; - let mut ymax = [0.0; 3]; - for (i, pts) in pts.iter().enumerate() { - if pts.is_empty() { - continue; - } - let (a, b, top) = robust_line(pts); - ymax[i] = top; - model.alpha[i] = a as f32; - model.beta[i] = (b as f32).max(1e-14); - } - JointNoise { model, ymax, tolerance: 1.0 } -} - -/// The noise line `v = a·y + b` through the bands `(y, variance, weight)` and the brightest band it -/// rests on. Seeded from the darker half, then all bands with a bounded influence for unexpectedly -/// high residuals (foliage etc.); refit rather than clamp the intercept. -pub(crate) fn robust_line(pts: &[(f64, f64, f64)]) -> (f64, f64, f32) { - let (mut a, mut b) = fit_nonneg_line(&pts[..pts.len().div_ceil(2)]); - let mut ymax = 0.0; - for _ in 0..4 { - // A band's weight fades to 0 between 4 and 5 times the fitted noise instead of dropping at - // 4: a band at the bound must not flip in or out with the last bits of the samples (the - // GPU's differ from the CPU's there), which moved the fit by a few percent. - let weighted: Vec<_> = pts - .iter() - .filter_map(|&(y, v, w)| { - let excess = v / (a * y + b).max(1e-14); - let fade = (5.0 - excess).clamp(0.0, 1.0); - (fade > 0.0).then_some((y, v, w * (2.0 / excess.max(2.0)).powi(4) * fade)) - }) - .collect(); - if !weighted.is_empty() { - (a, b) = fit_nonneg_line(&weighted); - ymax = weighted.iter().map(|p| p.0 as f32).fold(0.0, f32::max); - } - } - (a, b, ymax) -} - -/// Squared distance beyond the expected noise in a difference of two guide samples. A small -/// relative luminance allowance lets a smooth surface exchange colour without crossing a -/// significant luminance or isoluminant colour boundary. The guide is fixed across all scales. -/// (The filter runs `distance_run`, the same operations over planes; this per-pair form is its test reference.) -#[cfg(test)] -fn distance(a: [f32; 3], b: [f32; 3], noise: &JointNoise) -> f32 { - let y = 0.5 * (a[0] + b[0]); - let allowance = (0.025 * y.max(0.0)).powi(2); - let terms: [f32; 3] = std::array::from_fn(|i| { - let v = noise.var(i, y); - let excess = ((a[i] - b[i]).powi(2) - v).max(0.0); - // The 3x3 pilot blur reduces uncorrelated noise to 1/9. Keep a conservative - // allowance for correlations left by demosaicing and grid resampling. - // (A difference within the noise adds exactly 0: no division needed.) - if excess == 0.0 { 0.0 } else { excess / (3.0 * noise.tolerance * v + allowance) } - }); - terms.into_iter().sum::() -} - -/// The guide as three planes (Y, R−Y, B−Y): `distance_run` over them vectorises. -struct Planes { - c: [Vec; 3], - w: usize, -} - -impl Planes { - /// `len` pixels of row `y` from column `from`. - fn run(&self, y: usize, from: usize, len: usize) -> Option<[&[f32]; 3]> { - let start = y.checked_mul(self.w)?.checked_add(from)?; - let end = start.checked_add(len)?; - let [a, b, c] = &self.c; - Some([a.get(start..end)?, b.get(start..end)?, c.get(start..end)?]) - } -} - -/// `distance` of each pair of guide pixels `(a[k], b[k])` into `out[k]`, the same operations in the same -/// order (bit for bit), without branches so the compiler can work on several pixels at once. -fn distance_run(a: [&[f32]; 3], b: [&[f32]; 3], noise: &JointNoise, out: &mut [f32]) { - let ([ay, au, av], [by, bu, bv]) = (a, b); - let (alpha, beta, ymax, tolerance) = (noise.model.alpha, noise.model.beta, noise.ymax, noise.tolerance); - for ((((((o, &ay), &au), &av), &by), &bu), &bv) in out.iter_mut().zip(ay).zip(au).zip(av).zip(by).zip(bu).zip(bv) { - let y = 0.5 * (ay + by); - let allowance = (0.025 * y.max(0.0)).powi(2); - // `JointNoise::var`; an excess of 0 divides to exactly 0, as the branch in `distance` gives - let term = |i: usize, d: f32| { - let v = (alpha[i] * y.min(ymax[i]).max(0.0) + beta[i]).max(1e-14); - let excess = (d.powi(2) - v).max(0.0); - excess / (3.0 * tolerance * v + allowance) - }; - *o = term(0, ay - by) + term(1, au - bu) + term(2, av - bv); - } -} - -/// The exchange weight `exp(−max(distance, path))`; exactly 1 when both are 0 (no `exp` needed). -#[inline] -fn weight(distance: f32, path: f32) -> f32 { - let m = distance.max(path); - if m == 0.0 { 1.0 } else { (-m).exp() } -} - -/// `weight(distance, path)` with the path given as exp(−path): min(exp(−distance), that), and no `exp` -/// for a distance of 0. -#[inline] -fn path_weight(distance: f32, path: f32) -> f32 { - if distance == 0.0 { path } else { (-distance).exp().min(path) } -} - -/// Denoise the pilot along a clearly smoother axis at strong edges. An isotropic blur -/// dilutes a two-pixel isoluminant line before the edge decision even sees it. Weak or -/// ambiguous structure uses the isotropic pilot, so noise alone does not protect itself. -/// Written straight into planes (see `Planes`), one row at a time without branches per pixel. -fn pilot(original: &Rgb32f, noise: &JointNoise) -> Planes { - use rayon::prelude::*; - let blurred = gaussian(original, 0.8); - let (w, h) = (original.width, original.height); - let mut planes = Planes { c: std::array::from_fn(|_| vec![0.0; original.len()]), w }; - let [py, pu, pv] = &mut planes.c; - py.par_chunks_mut(w.max(1)).zip(pu.par_chunks_mut(w.max(1))).zip(pv.par_chunks_mut(w.max(1))).enumerate().for_each_init( - Vec::new, - |out: &mut Vec<[f32; 3]>, (y, ((ry, ru), rv))| { - let Some(blur) = blurred.data.get(y * w..(y + 1) * w) else { return }; - out.clear(); - out.extend_from_slice(blur); - if y > 0 - && y + 1 < h - && let (Some(up), Some(mid), Some(down)) = - (original.data.get((y - 1) * w..y * w), original.data.get(y * w..(y + 1) * w), original.data.get((y + 1) * w..(y + 2) * w)) - { - // columns 1 .. w − 1: the pixel, its left/right (axis 0) and upper/lower (axis 1) neighbours - for (((o, win), &u), &d) in out.iter_mut().skip(1).zip(mid.windows(3)).zip(up.iter().skip(1)).zip(down.iter().skip(1)) { - let &[l, p, r] = win else { continue }; - let var: [f32; 3] = std::array::from_fn(|i| 9.0 * noise.var(i, p[0])); - let axis = |a: [f32; 3], b: [f32; 3]| { - let m: [f32; 3] = std::array::from_fn(|i| (a[i] + p[i] + b[i]) / 3.0); - let t = |i: usize| ((a[i] - m[i]).powi(2) + (p[i] - m[i]).powi(2) + (b[i] - m[i]).powi(2)) / var[i]; - (m, t(0) + t(1) + t(2)) - }; - let (mh, vh) = axis(l, r); - let (mv, vvar) = axis(u, d); - *o = pilot_pick(*o, mh, vh, mv, vvar); - } - } - for (((c, y), u), v) in out.iter().zip(ry.iter_mut()).zip(ru.iter_mut()).zip(rv.iter_mut()) { - (*y, *u, *v) = (c[0], c[1], c[2]); - } - }, - ); - planes -} - -/// The pilot at one pixel from its isotropic blur `o`, the horizontal mean `mh` and noise-normalised -/// variance `vh`, and the vertical ones `mv`, `vvar`: the mean along the clearly smoother axis where -/// the other is more than 4 times as rough (and above 4), the blur where neither is. The choice fades -/// in between 0.8 and 1.25 times that bound instead of switching at it, so a pixel near the bound -/// takes nearly the same pilot when the noise model moves by a hair. -pub(crate) fn pilot_pick(o: [f32; 3], mh: [f32; 3], vh: f32, mv: [f32; 3], vvar: f32) -> [f32; 3] { - let sv = smoothstep(0.8, 1.25, vh / 4.0f32.max(4.0 * vvar)); - let sh = smoothstep(0.8, 1.25, vvar / 4.0f32.max(4.0 * vh)); - if sv >= 1.0 { - mv - } else if sh >= 1.0 { - mh - } else { - std::array::from_fn(|i| o[i] + (mv[i] - o[i]) * sv + (mh[i] - o[i]) * sh) - } -} - -/// The two chroma components `R − Y`, `B − Y`, or a pair of per-axis values (horizontal, vertical). -type Pair = [f32; 2]; -type PairImage = lightcraft_raster::Image; - -fn rgb2(y: f32, uv: Pair) -> [f32; 3] { - let r = y + uv[0]; - let b = y + uv[1]; - [r, (y - 0.2627 * r - 0.0593 * b) / 0.6780, b] -} - -/// One conservative horizontal/vertical diffusion step. Pair weights are symmetric; the -/// guide is never replaced by the filtered result. Long taps also account for the intervening -/// guide edges, so a wide pass cannot jump over a thin differently coloured object. -/// -/// Per pixel: `out = p`, then the lower neighbour's exchange, then the upper one's, in that order -/// (the order the result depends on, bit for bit). -fn diffuse(src: &PairImage, dst: &mut PairImage, links: &PairImage, delta: usize, vertical: bool, rate: f32) { - if vertical { diffuse_v(src, dst, links, delta, rate) } else { diffuse_h(src, dst, links, delta, rate) } -} - -#[inline(always)] -fn exchange(out: &mut Pair, p: Pair, q: Pair, weight: f32) { - out[0] += weight * (q[0] - p[0]); - out[1] += weight * (q[1] - p[1]); -} - -fn diffuse_h(src: &PairImage, dst: &mut PairImage, links: &PairImage, delta: usize, rate: f32) { - let w = src.width; - for_rows(&mut dst.data, w, |y, out| { - let (Some(s), Some(l)) = (src.data.get(y * w..(y + 1) * w), links.data.get(y * w..(y + 1) * w)) else { return }; - for (x, o) in out.iter_mut().enumerate() { - let p = s[x]; - *o = p; - if x >= delta { - exchange(o, p, s[x - delta], rate * l[x - delta][0]); - } - if x + delta < w { - exchange(o, p, s[x + delta], rate * l[x][0]); - } - } - }); -} - -fn diffuse_v(src: &PairImage, dst: &mut PairImage, links: &PairImage, delta: usize, rate: f32) { - let (w, h) = (src.width, src.height); - for_rows(&mut dst.data, w, |y, out| { - let Some(s) = src.data.get(y * w..(y + 1) * w) else { return }; - out.copy_from_slice(s); - if y >= delta - && let (Some(up), Some(lu)) = (src.data.get((y - delta) * w..(y - delta + 1) * w), links.data.get((y - delta) * w..(y - delta + 1) * w)) - { - for (((o, &p), &q), lk) in out.iter_mut().zip(s).zip(up).zip(lu) { - exchange(o, p, q, rate * lk[1]); - } - } - if y + delta < h - && let (Some(down), Some(ld)) = (src.data.get((y + delta) * w..(y + delta + 1) * w), links.data.get(y * w..(y + 1) * w)) - { - for (((o, &p), &q), lk) in out.iter_mut().zip(s).zip(down).zip(ld) { - exchange(o, p, q, rate * lk[1]); - } - } - }); -} - -/// The diffusion scales for a final spatial `sigma` (in grid pixels) on a `w × h` grid: each step's -/// neighbour distance and rate, in order. CPU and GPU run exactly these. -pub fn scale_plan(sigma: f32, w: usize, h: usize) -> Vec<(usize, f32)> { - let mut plan = Vec::new(); - let mut remaining = sigma * sigma; - let mut delta = 1usize; - while remaining > 0.01 && delta <= w.max(h) { - let rate = (remaining / (4.0 * (delta as f32).powi(2))).min(0.25); - plan.push((delta, rate)); - remaining -= 4.0 * rate * (delta as f32).powi(2); - delta = delta.saturating_mul(2); - } - plan -} - -/// Share of the filtered colour at Color `amount` (0..=1): a ramp up to the default 25. -pub fn strength(amount: f32) -> f32 { - (4.0 * amount).clamp(0.0, 1.0) -} - -/// Edge tolerance at Color Detail `detail` (0..=1). -pub fn tolerance(detail: f32) -> f32 { - (1.5 - detail).clamp(0.5, 1.5) -} - -/// The speck brake at Color `amount` (0..=1): the chroma excess (in noise variances of the two chroma -/// components together) from which a pixel starts to count as a colour speck (fully at twice that), and -/// the largest share of its colour that is replaced. Weak at the default 25 (only extreme specks, at most -/// half), stronger up to 100. Below 25 the final blend (`strength`) fades it out with the rest. -pub fn speck_brake(amount: f32) -> SpeckBrake { - let t = ((amount - 0.25) / 0.75).clamp(0.0, 1.0); - SpeckBrake { threshold: 64.0 - 39.0 * t, share: 0.5 + 0.5 * t } -} - -/// See [`speck_brake`]; `share` 0 turns the brake off. -#[derive(Clone, Copy, Debug)] -pub struct SpeckBrake { - pub threshold: f32, - pub share: f32, -} - -impl SpeckBrake { - pub const OFF: SpeckBrake = SpeckBrake { threshold: f32::INFINITY, share: 0.0 }; -} - -/// The median (mean of the middle two) of 8 values, by an optimal 19-comparator sorting network -/// (the GPU kernel uses the same one). -fn median8(v: [f32; 8]) -> f32 { - let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = v; - let cmp = |x: &mut f32, y: &mut f32| { - let (lo, hi) = (x.min(*y), x.max(*y)); - (*x, *y) = (lo, hi); - }; - cmp(&mut a, &mut c); - cmp(&mut b, &mut d); - cmp(&mut e, &mut g); - cmp(&mut f, &mut h); - cmp(&mut a, &mut e); - cmp(&mut b, &mut f); - cmp(&mut c, &mut g); - cmp(&mut d, &mut h); - cmp(&mut a, &mut b); - cmp(&mut c, &mut d); - cmp(&mut e, &mut f); - cmp(&mut g, &mut h); - cmp(&mut c, &mut e); - cmp(&mut d, &mut f); - cmp(&mut b, &mut e); - cmp(&mut d, &mut g); - cmp(&mut b, &mut c); - cmp(&mut d, &mut e); - cmp(&mut f, &mut g); - let _ = (a, b, c, f, g, h); - 0.5 * (d + e) -} - -fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { - let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) -} - -/// How much of a pixel's chroma the speck brake replaces by the median of the ring around it, and that -/// median (Y, R−Y, B−Y), from the pixel `p`, the ring `ring` and the rest of the 5 × 5 border `rest`. A -/// speck stands out in colour far beyond the noise, but not in luminance (a star, a lit point or any real -/// small detail almost always has a luminance step), and it is compact: the colour shift does not reach -/// the border (a line or an edge carries it on). Demosaicing spreads high-ISO specks over 2 × 2 to -/// 3 × 3 pixels, which all lie inside. The noise is taken at the ring's mean luminance (a median of it -/// is only needed for the few pixels past the threshold). -fn speck_share(p: [f32; 3], ring: &[[f32; 3]; 8], rest: impl Iterator, noise: &JointNoise, brake: SpeckBrake) -> (f32, [f32; 3]) { - let y = ring.iter().map(|q| q[0]).sum::() / 8.0; - let (vu, vv) = (noise.var(1, y), noise.var(2, y)); - // The medians lie between the ring's least and largest value, so the farther of the two bounds the - // excess from above (rounding keeps that order): most pixels are decided without the medians. - let reach = |c: usize| { - let (lo, hi) = ring.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), q| (lo.min(q[c]), hi.max(q[c]))); - (p[c] - lo).abs().max((p[c] - hi).abs()) - }; - let (bu, bv) = (reach(1), reach(2)); - if bu * bu / vu + bv * bv / vv <= brake.threshold { - return (0.0, [0.0; 3]); - } - let m = [0.0, median8(ring.map(|q| q[1])), median8(ring.map(|q| q[2]))]; - let (du, dv) = (p[1] - m[1], p[2] - m[2]); - let excess = du * du / vu + dv * dv / vv; - if excess <= brake.threshold { - return (0.0, m); - } - let m = [median8(ring.map(|q| q[0])), m[1], m[2]]; - // luminance: full brake up to half the chroma excess, none from 1.5 times it - let dy = p[0] - m[0]; - let luminance = dy * dy / noise.var(0, y); - let alone = ((1.5 * excess - luminance) / excess).clamp(0.0, 1.0); - if alone <= 0.0 { - return (0.0, m); - } - // compactness: the second largest share of the pixel's colour shift that a border pixel also has (a - // line or an edge through the pixel crosses the border at least twice; one noisy border pixel that - // happens to lean the same way does not protect a speck) - let (_, second) = ring - .iter() - .copied() - .chain(rest) - .map(|q| ((q[1] - m[1]) * du / vu + (q[2] - m[2]) * dv / vv) / excess) - .fold((0.0f32, 0.0f32), |(a, b), s| if s > a { (s, a) } else { (a, b.max(s)) }); - let compact = ((0.8 - second) / 0.3).clamp(0.0, 1.0); - (brake.share * smoothstep(brake.threshold, 2.0 * brake.threshold, excess) * alone * compact, m) -} - -/// Replace the chroma of compact colour specks by that of their surroundings (see `speck_share`), in the -/// transformed image (Y, R−Y, B−Y); luminance is never touched. Runs before the guide is built, so a speck -/// is neither kept by the edge-aware weights nor spread by them. -fn despeck(img: &mut Rgb32f, noise: &JointNoise, brake: SpeckBrake) { - use rayon::prelude::*; - if brake.share <= 0.0 || img.width < 5 || img.height < 5 { - return; - } - let (w, h) = (img.width, img.height); - let source = &*img; - // few pixels change: collect their new chroma per row from the unchanged image, then write them - let changes: Vec> = (2..h - 2) - .into_par_iter() - .map(|y| { - let mut changed = Vec::new(); - let rows: [Option<&[[f32; 3]]>; 5] = std::array::from_fn(|k| source.data.get((y + k - 2) * w..(y + k - 1) * w)); - let [Some(r0), Some(r1), Some(r2), Some(r3), Some(r4)] = rows else { return changed }; - for (x, ((((w0, w1), w2), w3), w4)) in - r0.windows(5).zip(r1.windows(5)).zip(r2.windows(5)).zip(r3.windows(5)).zip(r4.windows(5)).enumerate() - { - let (&[a0, a1, a2, a3, a4], &[b0, _, _, _, b4], &[c0, _, p, _, c4], &[d0, _, _, _, d4], &[e0, e1, e2, e3, e4]) = (w0, w1, w2, w3, w4) - else { - continue; - }; - // the ring: corners and edge centres of the 5 × 5 square, far enough that a speck spread over - // its direct neighbours by demosaicing does not reach them; the rest of the border: with the - // ring, every thin line or edge through the pixel crosses at least one of the 16 at any angle - let ring = [a0, a2, a4, c0, c4, e0, e2, e4]; - let rest = [a1, a3, b0, b4, d0, d4, e1, e3]; - let (k, m) = speck_share(p, &ring, rest.into_iter(), noise, brake); - if k > 0.0 { - changed.push((y * w + x + 2, [p[1] + k * (m[1] - p[1]), p[2] + k * (m[2] - p[2])])); - } - } - changed - }) - .collect(); - for (index, uv) in changes.into_iter().flatten() { - if let Some(o) = img.data.get_mut(index) { - (o[1], o[2]) = (uv[0], uv[1]); - } - } -} - -/// `noise`: the frame's noise model (see [`noise_of_tiles`]); `None` measures it on `img`. -pub(crate) fn denoise(img: &mut Rgb32f, params: &NrcParams, detail: f32, amount: f32, noise: Option<&JointNoise>) { - // Continuous ramp from zero; from the ordinary default Color=25 onward the spatial - // scale controls the extra smoothing. Noise calibration and edge decisions stay fixed. - denoise_with(img, params, 1, detail, strength(amount), speck_brake(amount), noise); -} - -#[cfg(test)] -fn denoise_grid(img: &mut Rgb32f, params: &NrcParams, step: usize, detail: f32, strength: f32, brake: SpeckBrake) { - denoise_with(img, params, step, detail, strength, brake, None); -} - -fn denoise_with(img: &mut Rgb32f, params: &NrcParams, step: usize, detail: f32, strength: f32, brake: SpeckBrake, noise: Option<&JointNoise>) { - if img.is_empty() || strength <= 0.0 { - return; - } - let start = crate::profiling().then(std::time::Instant::now); - // A maximum 2x grid keeps colour boundaries visible even at high strength. The old grid - // grew to 16x with the radius, making the colour loss inseparable from slider strength. - let step = if img.width.is_multiple_of(step) && img.height.is_multiple_of(step) { step } else { 1 }; - let (w, h) = (img.width.div_ceil(step), img.height.div_ceil(step)); - // Transform before resampling; negative linear differences are valid throughout. - let mut original = Rgb32f::new(w, h); - if step == 1 { - // the generic loop below with one sample per pixel, same operations (0 + c, / 1) - for_rows(&mut original.data, w, |y, row| { - for (x, p) in row.iter_mut().enumerate() { - if let Some(&c) = img.data.get(y * w + x) { - let c = yuv(c); - *p = c.map(|v| (0.0f32 + v) / 1.0f32); - } - } - }); - } else { - for_rows(&mut original.data, w, |y, row| { - for (x, p) in row.iter_mut().enumerate() { - let mut count = 0.0f32; - for sy in y * step..((y + 1) * step).min(img.height) { - for sx in x * step..((x + 1) * step).min(img.width) { - if let Some(&c) = img.data.get(sy * img.width + sx) { - let c = yuv(c); - *p = std::array::from_fn(|i| p[i] + c[i]); - count += 1.0; - } - } - } - *p = p.map(|v| v / count.max(1.0)); - } - }); - } - let lap = |what: &str, t: &mut Option| { - if let Some(t0) = t { - eprintln!(" joint {what}: {:.0} ms", t0.elapsed().as_secs_f64() * 1e3); - *t = Some(std::time::Instant::now()); - } - }; - let mut tt = start; - lap("transform", &mut tt); - let mut noise = match noise { - Some(n) => *n, - None => noise_model(&original), - }; - lap("noise model", &mut tt); - noise.tolerance = tolerance(detail); - despeck(&mut original, &noise, brake); - lap("speck brake", &mut tt); - let planes = pilot(&original, &noise); - lap("pilot", &mut tt); - if start.is_some() { - eprintln!(" nr joint: {w}x{h}, Y/R-Y/B-Y alpha {:?} beta {:?}, supported Y {:?}", noise.model.alpha, noise.model.beta, noise.ymax); - } - // Working buffers carry the two chroma components only (Y is restored from the image at the end). - let mut filtered: PairImage = original.map(|p| [p[1], p[2]]); - // the full-resolution reconstruction reads Y from `img`: the transformed copy is no longer needed - let original = (step != 1).then_some(original); - let mut scratch = PairImage::new(w, h); - let mut paths = PairImage::new(w, h); - let mut links = PairImage::new(w, h); - // Direct neighbours: the path over one step is the pair's own distance, and its weight is exp(−distance). - // `paths` holds exp(−path), the largest distance along a path, exponentiated: exp(−max(a, b)) is - // min(exp(−a), exp(−b)) bit for bit (exp is monotonic), so longer paths take minima and a weight with - // a new distance of 0 needs no `exp`; a path of 0 (no pair, at the border) is 1. - // the distances of row `y` to the pixels `offset` to the right and `offset` rows down - let row_distances = |y: usize, offset: usize, dh: &mut Vec, dv: &mut Vec| { - let n = w.saturating_sub(offset); - dh.resize(w, 0.0); - dv.resize(w, 0.0); - if let (Some(a), Some(b), Some(out)) = (planes.run(y, 0, n), planes.run(y, offset, n), dh.get_mut(..n)) { - distance_run(a, b, &noise, out); - } - if y + offset < h - && let (Some(a), Some(b)) = (planes.run(y, 0, w), planes.run(y + offset, 0, w)) - { - distance_run(a, b, &noise, dv); - } - }; - { - use rayon::prelude::*; - paths.data.par_chunks_mut(w).zip(links.data.par_chunks_mut(w)).enumerate().for_each_init( - || (Vec::new(), Vec::new()), - |(dh, dv), (y, (prow, lrow))| { - row_distances(y, 1, dh, dv); - for (x, (((out, link), &d0), &d1)) in prow.iter_mut().zip(lrow.iter_mut()).zip(dh.iter()).zip(dv.iter()).enumerate() { - *link = [0.0; 2]; - *out = [1.0; 2]; - if x + 1 < w { - link[0] = weight(d0, d0); - out[0] = link[0]; - } - if y + 1 < h { - link[1] = weight(d1, d1); - out[1] = link[1]; - } - } - }, - ); - } - lap("links 1", &mut tt); - // Scale is independent of the edge decision. K has no role in deciding whether a leaf - // is noise. Two dyadic sweeps provide broad smoothing with a fixed number of scales. - let sigma = params.passes.last().map_or(0.0, |p| p.sigma / step as f32); - let plan = scale_plan(sigma, w, h); - for (k, &(delta, rate)) in plan.iter().enumerate() { - for _ in 0..2 { - diffuse(&filtered, &mut scratch, &links, delta, false, rate); - std::mem::swap(&mut filtered, &mut scratch); - diffuse(&filtered, &mut scratch, &links, delta, true, rate); - std::mem::swap(&mut filtered, &mut scratch); - } - lap(&format!("scale {delta}"), &mut tt); - let Some(&(next, _)) = plan.get(k + 1) else { break }; - // In one pass: paths of length 2·delta (from the two adjacent delta-length paths, read from - // `paths`, written to `scratch`) and the next scale's pair weights from them. - { - use rayon::prelude::*; - let old = &paths; - scratch.data.par_chunks_mut(w).zip(links.data.par_chunks_mut(w)).enumerate().for_each_init( - || (Vec::new(), Vec::new()), - |(dh, dv), (y, (prow, lrow))| { - row_distances(y, next, dh, dv); - let (Some(here), below) = (old.data.get(y * w..(y + 1) * w), old.data.get((y + delta) * w..(y + delta + 1) * w)) else { return }; - for (x, (((out, link), &d0), &d1)) in prow.iter_mut().zip(lrow.iter_mut()).zip(dh.iter()).zip(dv.iter()).enumerate() { - let Some(&p) = here.get(x) else { continue }; - *out = p; - if x + delta < w - && let Some(q) = here.get(x + delta) - { - out[0] = out[0].min(q[0]); - } - if y + delta < h - && let Some(q) = below.and_then(|b| b.get(x)) - { - out[1] = out[1].min(q[1]); - } - *link = [0.0; 2]; - if x + next < w { - link[0] = path_weight(d0, out[0]); - } - if y + next < h { - link[1] = path_weight(d1, out[1]); - } - } - }, - ); - } - std::mem::swap(&mut paths, &mut scratch); - } - drop(scratch); - drop(paths); - drop(links); - match &original { - None => { - let fw = img.width; - for_rows(&mut img.data, fw, |y, row| { - for (x, p) in row.iter_mut().enumerate() { - let Some(&q) = filtered.data.get(y * w + x) else { continue }; - let result = rgb2(luminance_2020(*p), q); - *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); - } - }); - } - Some(original) => { - // Reconstruct only rows. Keep the fine residual with a shared, noise-subtracted - // Wiener share; a flat noisy patch receives no automatic protection from noisy Y. - let mean = gaussian(original, 1.0); - let corr = gaussian(&original.map(|p| p.map(|v| v * v)), 1.0); - let share = corr.zip_map(&mean, |c, m| { - let snr = (1..3).map(|i| ((c[i] - m[i] * m[i]).max(0.0) / noise.var(i, m[0]) - 1.0).max(0.0)).sum::() * 0.5; - [snr / (snr + 8.0); 3] - }); - let share = gaussian(&share, 0.8); - // Resize one output row at a time using the raster resampler's exact pixel centres. - use lightcraft_raster::resample::weights; - let ux = weights(w, img.width, Filter::Bilinear); - let uy = weights(h, img.height, Filter::Bilinear); - let ow = img.width; - for_rows(&mut img.data, ow, |y, row| { - let Some((y0, wy)) = uy.get(y) else { return }; - for (x, p) in row.iter_mut().enumerate() { - let Some((x0, wx)) = ux.get(x) else { continue }; - let (mut f, mut o, mut a) = ([0.0; 2], [0.0; 3], 0.0); - for (j, &dy) in wy.iter().enumerate() { - for (i, &dx) in wx.iter().enumerate() { - let index = (y0 + j) * w + x0 + i; - if let (Some(q), Some(r), Some(s)) = (filtered.data.get(index), original.data.get(index), share.data.get(index)) { - let weight = dx * dy; - f = std::array::from_fn(|c| f[c] + weight * q[c]); - o = std::array::from_fn(|c| o[c] + weight * r[c]); - a += weight * s[0]; - } - } - } - let c = yuv(*p); - let q = [f[0] + a * (c[1] - o[1]), f[1] + a * (c[2] - o[2])]; - let result = rgb2(c[0], q); - *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); - } - }); - } - } - if let Some(start) = start { - eprintln!(" nr joint: {:.1} ms", start.elapsed().as_secs_f64() * 1e3); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::local::NrcPass; - - fn params(step: usize) -> NrcParams { - NrcParams { off: 0.003, passes: vec![NrcPass { sigma: 4.0, step, k: 64.0, pct: 0.2 }, NrcPass { sigma: 12.0, step, k: 64.0, pct: 0.2 }] } - } - - fn noisy(clean: &Rgb32f, seed: u64, sigma: f32) -> Rgb32f { - let mut result = clean.clone(); - let mut seed = seed; - for p in &mut result.data { - for v in p { - let mut n = 0.0; - for _ in 0..4 { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - n += (seed >> 11) as f32 / (1u64 << 53) as f32 - 0.5; - } - *v += sigma * 1.732 * n; - } - } - result - } - - /// The optimised filter reproduces the reference implementation (8b89526d) bit for bit: same scales, - /// weights, paths and reconstruction, only fewer passes and smaller buffers. - #[test] - fn joint_matches_the_reference_bit_for_bit() { - let mut scene = Rgb32f::new(97, 83); - for (i, p) in scene.data.iter_mut().enumerate() { - let (x, y) = (i % 97, i / 97); - // edges, a thin line, a dark patch and a gradient - *p = if x < 30 { - [0.08, 0.016, 0.02] - } else if x < 32 { - [0.01, 0.05, 0.01] - } else if y < 40 { - [0.0015, 0.004, 0.009] - } else { - [0.02 + 0.001 * x as f32, 0.03, 0.01 + 0.0005 * y as f32] - }; - } - for (w, h) in [(97usize, 83usize), (96, 82), (5, 3), (1, 7)] { - let mut clean = Rgb32f::new(w, h); - for y in 0..h { - for x in 0..w { - clean.data[y * w + x] = scene.data[y * 97 + x]; - } - } - for seed in [0x2545_f491_4f6c_dd1d, 0x9e37_79b9_7f4a_7c15] { - let input = noisy(&clean, seed, 0.004); - for step in [1, 2] { - for (detail, strength, sigma) in [(0.5, 1.0, 12.0), (0.25, 0.6, 4.0), (0.9, 1.0, 27.0)] { - let p = NrcParams { off: 0.003, passes: vec![NrcPass { sigma, step, k: 64.0, pct: 0.2 }] }; - let (mut a, mut b) = (input.clone(), input.clone()); - denoise_grid(&mut a, &p, step, detail, strength, SpeckBrake::OFF); - crate::nrc_joint_reference::denoise_grid(&mut b, &p, step, detail, strength); - for (i, (x, y)) in a.data.iter().zip(&b.data).enumerate() { - for c in 0..3 { - assert!( - x[c].to_bits() == y[c].to_bits(), - "{w}x{h} step {step} sigma {sigma}: pixel {i} channel {c}: {} vs {}", - x[c], - y[c] - ); - } - } - } - } - } - } - } - - /// BENCH (ignored, prints): the optimised filter against the reference on the same 24 MP image, - /// interleaved so both see the same machine load. Median of 3 each. - #[test] - #[ignore] - fn bench_joint_against_reference() { - let (w, h) = (6000usize, 4000usize); - let mut clean = Rgb32f::new(w, h); - for (i, p) in clean.data.iter_mut().enumerate() { - let (x, y) = (i % w, i / w); - *p = if (x / 300 + y / 300) % 2 == 0 { [0.03, 0.02, 0.01] } else { [0.004, 0.006, 0.012] }; - } - let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.004); - let p = NrcParams { off: 0.003, passes: vec![NrcPass { sigma: 27.0, step: 1, k: 64.0, pct: 0.2 }] }; - let (mut new, mut old) = (Vec::new(), Vec::new()); - for _ in 0..3 { - let mut a = input.clone(); - let t = std::time::Instant::now(); - denoise_grid(&mut a, &p, 1, 0.5, 1.0, SpeckBrake::OFF); - new.push(t.elapsed().as_secs_f64()); - let mut b = input.clone(); - let t = std::time::Instant::now(); - crate::nrc_joint_reference::denoise_grid(&mut b, &p, 1, 0.5, 1.0); - old.push(t.elapsed().as_secs_f64()); - } - new.sort_by(f64::total_cmp); - old.sort_by(f64::total_cmp); - println!("joint 24 MP: optimised {:.2} s, reference {:.2} s (medians of {new:.2?} / {old:.2?})", new[1], old[1]); - } - - /// BENCH (ignored, prints): fitting the noise model to 130 000 samples (a 33 MP image's), median of 5. - #[test] - #[ignore] - fn bench_noise_fit() { - let mut seed = 0x2545_f491_4f6c_dd1du64; - let mut rnd = || { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed >> 11) as f32 / (1u64 << 53) as f32 - }; - let samples: Vec = (0..130_000) - .map(|_| { - let y = rnd() * 0.3; - (y, std::array::from_fn(|_| std::array::from_fn(|_| (1e-5 + 1e-4 * y) * rnd() * 2.0))) - }) - .collect(); - let mut times: Vec = (0..5) - .map(|_| { - let s = samples.clone(); - let t = std::time::Instant::now(); - let model = fit_noise(s); - assert!(model.model.beta[0] > 0.0); - t.elapsed().as_secs_f64() * 1e3 - }) - .collect(); - times.sort_by(f64::total_cmp); - println!("noise fit, 130 000 samples: {:.1} ms (of {times:.1?})", times[2]); - } - - /// BENCH (ignored, prints): the speck brake alone against the whole joint filter on one 24 MP image, - /// interleaved. Median of 3 each. - #[test] - #[ignore] - fn bench_speck_brake() { - let (w, h) = (6000usize, 4000usize); - let clean = Rgb32f::from_fn(w, h, |x, y| if (x / 300 + y / 300) % 2 == 0 { [0.03, 0.02, 0.01] } else { [0.004, 0.006, 0.012] }); - let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.004); - let p = NrcParams { off: 0.003, passes: vec![NrcPass { sigma: 27.0, step: 1, k: 64.0, pct: 0.2 }] }; - let transformed = input.map(yuv); - let noise = noise_model(&transformed); - let (mut brake, mut joint) = (Vec::new(), Vec::new()); - for _ in 0..3 { - let mut out = transformed.clone(); - let t = std::time::Instant::now(); - despeck(&mut out, &noise, speck_brake(1.0)); - brake.push(t.elapsed().as_secs_f64()); - let mut a = input.clone(); - let t = std::time::Instant::now(); - denoise_grid(&mut a, &p, 1, 0.5, 1.0, SpeckBrake::OFF); - joint.push(t.elapsed().as_secs_f64()); - } - brake.sort_by(f64::total_cmp); - joint.sort_by(f64::total_cmp); - println!("24 MP: speck brake {:.3} s, joint without it {:.2} s (medians of {brake:.3?} / {joint:.2?})", brake[1], joint[1]); - } - - #[test] - fn joint_keeps_negative_means_luminance_and_reduces_chroma_noise() { - for (w, h) in [(128, 96), (127, 95), (1, 19), (19, 1)] { - let clean = Rgb32f::filled(w, h, [0.006, 0.004, 0.0008]); - for seed in [0x2545_f491_4f6c_dd1d, 0x1234_5678_9abc_def1] { - let input = noisy(&clean, seed, 0.003); - for step in [1, 2] { - let mut output = input.clone(); - denoise_grid(&mut output, ¶ms(step), step, 0.5, 1.0, speck_brake(1.0)); - assert!(output.data.iter().flatten().all(|v| v.is_finite())); - for (a, b) in input.data.iter().zip(&output.data) { - assert!((luminance_2020(*a) - luminance_2020(*b)).abs() < 1e-7); - } - // Thin inputs cannot support a spatial noise estimate; finite/luminance - // checks above still apply, but their sample mean is too noisy for this bound. - if w < 3 || h < 3 { - continue; - } - for c in 0..3 { - let difference = input.data.iter().zip(&output.data).map(|(a, b)| (b[c] - a[c]) as f64).sum::() / input.len() as f64; - assert!(difference.abs() < 2e-6, "step {step}, {w}x{h}, mean error {difference}"); - } - let energy = |im: &Rgb32f| { - im.data - .iter() - .map(|&p| { - let p = yuv(p); - let c = yuv(clean.data[0]); - (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2) - }) - .sum::() - / im.len() as f32 - }; - assert!(energy(&output) < 0.08 * energy(&input)); - assert!(output.data.iter().any(|p| p.iter().any(|&v| v < 0.0)), "negative values were clipped"); - } - } - } - } - - #[test] - fn joint_protects_leaf_and_isoluminant_edges_without_chroma_halos() { - let leaf = [0.02, 0.12, 0.01]; - let black = [0.0005; 3]; - let red = [0.08, 0.0155, 0.02]; - let mut green = [0.012, 0.04, 0.015]; - let gain = luminance_2020(red) / luminance_2020(green); - green = green.map(|v| v * gain); - for (left, right) in [(leaf, black), (red, green)] { - let clean = Rgb32f::from_fn(192, 128, |x, _| if x < 96 { left } else { right }); - for seed in [0x2545_f491_4f6c_dd1d, 0x1234_5678_9abc_def1] { - let input = noisy(&clean, seed, 0.003); - for step in [1, 2] { - let mut output = input.clone(); - denoise_grid(&mut output, ¶ms(step), step, 0.5, 1.0, speck_brake(1.0)); - let step_uv = [yuv(left)[1] - yuv(right)[1], yuv(left)[2] - yuv(right)[2]]; - let length = step_uv.iter().map(|v| v * v).sum::().sqrt(); - for x in [92, 93, 98, 99] { - let mut mean = [0.0; 3]; - for y in 16..112 { - let p = yuv(output.get(x, y)); - mean = std::array::from_fn(|i| mean[i] + p[i] / 96.0); - } - let expected = yuv(if x < 96 { left } else { right }); - let error = ((mean[1] - expected[1]).powi(2) + (mean[2] - expected[2]).powi(2)).sqrt() / length; - assert!(error < 0.08, "step {step}, x {x}, colour error {}%", 100.0 * error); - } - } - } - } - } - - #[test] - fn joint_noise_fit_does_not_treat_bright_texture_as_shot_noise() { - let clean = Rgb32f::from_fn(256, 192, |x, y| { - let l = if x < 192 { 0.003 + x as f32 * 0.00002 } else { 0.15 + if (x + y) % 2 == 0 { 0.08 } else { -0.08 } }; - [l; 3] - }); - let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.002).map(yuv); - let model = noise_model(&input); - for i in 0..3 { - assert!(model.var(i, 0.15) < 5.0 * model.var(i, 0.005), "texture dominated noise fit: {model:?}"); - } - } - - #[test] - fn joint_keeps_a_two_pixel_isoluminant_line() { - let grey = [0.03; 3]; - let mut red = [0.08, 0.0155, 0.02]; - let gain = luminance_2020(grey) / luminance_2020(red); - red = red.map(|v| v * gain); - let clean = Rgb32f::from_fn(192, 128, |x, _| if (94..96).contains(&x) { red } else { grey }); - let mut output = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.006); - denoise_grid(&mut output, ¶ms(1), 1, 0.5, 1.0, speck_brake(1.0)); - let reference = yuv(red); - let mut mean = [0.0; 3]; - for y in 16..112 { - for x in 94..96 { - let p = yuv(output.get(x, y)); - mean = std::array::from_fn(|i| mean[i] + p[i] / 192.0); - } - } - let kept = (mean[1] * reference[1] + mean[2] * reference[2]) / (reference[1].powi(2) + reference[2].powi(2)); - assert!(kept > 0.85, "thin line keeps only {}%", 100.0 * kept); - } - - #[test] - fn joint_estimates_correlated_noise_at_a_matching_scale() { - let clean = Rgb32f::filled(256, 192, [0.03; 3]); - let correlated = gaussian(&noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.012), 0.8).map(yuv); - let model = noise_model(&correlated); - for i in 0..3 { - let mean = correlated.data.iter().map(|p| p[i] as f64).sum::() / correlated.len() as f64; - let variance = correlated.data.iter().map(|p| (p[i] as f64 - mean).powi(2)).sum::() / correlated.len() as f64; - let predicted = model.var(i, 0.03) as f64; - assert!(predicted > 0.6 * variance && predicted < 1.6 * variance, "channel {i}: estimated {predicted}, actual {variance}"); - } - } - - /// The speck brake takes the colour out of a compact, isoluminant 2 × 2 speck (as demosaicing leaves - /// them at high ISO), more at Color 100 than at 25, but leaves a coloured star (a luminance peak) alone. - #[test] - fn noise_line_does_not_jump_when_a_band_crosses_the_outlier_bound() { - // The luminance bands of a 640-px preview of demo scene 0 after luminance NR. Its band at - // 0.593 sat at 4 times the first fit: the CPU's samples put it just above, the GPU's just - // below, and the fits came out 2.6 % apart (CPU and GPU renders then differed by 10 levels). - let mut pts: Vec<(f64, f64, f64)> = [ - (0.009, 5.028e-7), - (0.022, 1.554e-4), - (0.063, 1.459e-4), - (0.147, 9.728e-6), - (0.213, 2.701e-5), - (0.272, 5.077e-6), - (0.315, 3.236e-5), - (0.356, 2.531e-5), - (0.390, 5.329e-6), - (0.420, 4.924e-6), - (0.467, 5.453e-5), - (0.530, 1.823e-5), - (0.593, 0.0), - (0.648, 1.501e-8), - (0.667, 1.898e-8), - (0.996, 3.490e-7), - ] - .map(|(y, v)| (y, v, 5649.0)) - .to_vec(); - let (a, b) = fit_nonneg_line(&pts[..pts.len().div_ceil(2)]); - let bound = 4.0 * (a * 0.593 + b); - let mut fit = |k: f64| { - pts[12].1 = bound * k; - robust_line(&pts) - }; - let (below, above) = (fit(1.0 - 1e-6), fit(1.0 + 1e-6)); - assert!((below.1 / above.1 - 1.0).abs() < 1e-4, "{below:?} vs {above:?}"); - assert!((below.0 - above.0).abs() <= 1e-4 * below.0.abs().max(1e-12), "{below:?} vs {above:?}"); - } - - #[test] - fn speck_brake_removes_compact_colour_specks_but_not_stars() { - let dark = [0.004f32; 3]; - let mut magenta = [0.024, 0.0, 0.024]; - magenta[1] = (luminance_2020(dark) - 0.2627 * magenta[0] - 0.0593 * magenta[2]) / 0.6780; - let star = [0.3, 0.2, 0.1]; - let clean = Rgb32f::from_fn(128, 96, |x, y| match (x, y) { - (40..42, 40..42) => magenta, - (90..92, 40..42) => star, - _ => dark, - }); - let input = noisy(&clean, 0x2545_f491_4f6c_dd1d, 0.001); - // share of the object's chroma (against the background) left in its 2 × 2 pixels - let kept = |out: &Rgb32f, x0: usize, colour: [f32; 3]| { - let (r, b) = (yuv(colour), yuv(dark)); - let reference = [r[1] - b[1], r[2] - b[2]]; - let mut mean = [0.0f32; 2]; - for (x, y) in [(x0, 40), (x0 + 1, 40), (x0, 41), (x0 + 1, 41)] { - let p = yuv(out.get(x, y)); - mean = [mean[0] + 0.25 * (p[1] - b[1]), mean[1] + 0.25 * (p[2] - b[2])]; - } - (mean[0] * reference[0] + mean[1] * reference[1]) / (reference[0].powi(2) + reference[1].powi(2)) - }; - let run = |brake| { - let mut out = input.clone(); - denoise_grid(&mut out, ¶ms(1), 1, 0.5, 1.0, brake); - (kept(&out, 40, magenta), kept(&out, 90, star)) - }; - let (off, star_off) = run(SpeckBrake::OFF); - let (weak, _) = run(speck_brake(0.25)); - let (strong, star_strong) = run(speck_brake(1.0)); - assert!(off > 0.5, "without the brake the speck keeps {off}"); - assert!(weak < 0.8 * off && strong < 0.2, "speck kept: off {off}, at 25 {weak}, at 100 {strong}"); - assert!(strong < weak, "the brake is stronger at 100 ({strong}) than at 25 ({weak})"); - assert!((star_strong - star_off).abs() < 0.02, "star colour {star_off} -> {star_strong}"); - } - - /// `distance_run` (planes, no branches) gives `distance` bit for bit. - #[test] - fn distance_run_matches_distance() { - let clean = Rgb32f::from_fn(64, 3, |x, _| [0.002 * x as f32, 0.01, 0.03 - 0.0004 * x as f32]); - let img = noisy(&clean, 0x9e37_79b9_7f4a_7c15, 0.01).map(yuv); - let mut noise = noise_model(&noisy(&Rgb32f::filled(64, 64, [0.02; 3]), 7, 0.004).map(yuv)); - noise.tolerance = 0.7; - let planes = Planes { c: std::array::from_fn(|i| img.data.iter().map(|p| p[i]).collect()), w: 64 }; - let mut out = vec![0.0; 64]; - distance_run(planes.run(0, 0, 64).unwrap(), planes.run(2, 0, 64).unwrap(), &noise, &mut out); - for (x, d) in out.iter().enumerate() { - assert_eq!(d.to_bits(), distance(img.get(x, 0), img.get(x, 2), &noise).to_bits(), "pixel {x}"); - } - } + let craft_tiles: Vec<_> = tiles.iter().map(crate::bridge::to_craft_rgb32f).collect(); + craft_develop::nrc_joint::noise_of_tiles(&craft_tiles) } diff --git a/crates/pipeline/src/nrc_joint_reference.rs b/crates/pipeline/src/nrc_joint_reference.rs deleted file mode 100644 index 13e2c46b95..0000000000 --- a/crates/pipeline/src/nrc_joint_reference.rs +++ /dev/null @@ -1,352 +0,0 @@ -//! TEST ONLY: the joint colour NR as of 8b89526d, kept as the reference the optimised `nrc_joint` -//! must reproduce bit for bit. Changed since only where `nrc_joint` changed its result on purpose: -//! the noise line's outlier bands fade out (`nrc_joint::robust_line`) and the pilot's axis choice -//! fades in (`nrc_joint::pilot_pick`). -//! -//! Linear colour NR with a fixed, denoised joint guide. Strength controls the spatial scale; -//! noise-normalized guide distances control which neighbours can exchange colour. Both chroma -//! components use the same weights. Symmetric fluxes preserve the grid's channel sums, including -//! at its boundaries; no nonnegative clamp or square-root bias correction is involved. - -use lightcraft_color::luminance_2020; -use lightcraft_raster::{Rgb32f, blur::gaussian, resample::Filter}; - -use crate::{ - for_rows, - local::{NrcNoise, NrcParams}, -}; - -#[derive(Debug)] -struct JointNoise { - model: NrcNoise, - /// Do not extrapolate beyond bands that contain usable noise measurements. - ymax: [f32; 3], - tolerance: f32, -} - -impl JointNoise { - fn var(&self, i: usize, y: f32) -> f32 { - self.model.var(i, y.min(self.ymax[i])) - } -} - -fn yuv(c: [f32; 3]) -> [f32; 3] { - let y = luminance_2020(c); - [y, c[0] - y, c[2] - y] -} - -fn rgb(y: f32, uv: [f32; 3]) -> [f32; 3] { - let r = y + uv[1]; - let b = y + uv[2]; - [r, (y - 0.2627 * r - 0.0593 * b) / 0.6780, b] -} - -/// Noise of Y, R-Y and B-Y measured from small high-pass residuals, not the colour variance -/// of a wide smoothing window. The median-square calibration is for Gaussian residuals. -/// Luminance bands with predominantly texture may only lower their weight in the fit: they -/// cannot force a shadow scene's extrapolated highlight noise arbitrarily high. -fn noise_model(img: &Rgb32f) -> JointNoise { - const BANDS: usize = 16; - let mut samples = Vec::new(); - let stride = img.len().div_ceil(crate::local::NRC_SAMPLES).max(1) | 1; - if img.width < 3 || img.height < 3 { - return JointNoise { model: NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }, ymax: [0.0; 3], tolerance: 1.0 }; - } - for index in (0..img.len()).step_by(stride) { - let (x, y) = (index % img.width, index / img.width); - if x == 0 || y == 0 || x + 1 == img.width || y + 1 == img.height { - continue; - } - let Some(c) = img.data.get(index) else { continue }; - let mut residual = [[0.0f32; 3]; 3]; - let mut brightness = 0.0; - let mut valid = true; - for (scale, delta) in [1usize, 2, 4].into_iter().enumerate() { - // Tiny images use the nearest supported scale rather than extending an edge - // into the noise samples. - let delta = delta.min(x).min(y).min(img.width - x - 1).min(img.height - y - 1); - let neighbours = [index - delta, index + delta, index - delta * img.width, index + delta * img.width]; - let mut m = [0.0f32; 3]; - for n in neighbours { - if let Some(p) = img.data.get(n) { - m = std::array::from_fn(|i| m[i] + 0.25 * p[i]); - } - } - residual[scale] = std::array::from_fn(|i| (c[i] - m[i]).powi(2)); - brightness += m[0] / 3.0; - valid &= c.iter().chain(m.iter()).all(|v| v.is_finite()); - } - if valid { - samples.push((brightness.max(0.0), residual)); - } - } - samples.sort_by(|a, b| a.0.total_cmp(&b.0)); - let per = samples.len().div_ceil(BANDS).max(32); - let mut pts: [Vec<(f64, f64, f64)>; 3] = std::array::from_fn(|_| Vec::new()); - for band in samples.chunks(per).filter(|b| b.len() >= 32) { - let y = band.iter().map(|p| p.0 as f64).sum::() / band.len() as f64; - for (i, pts) in pts.iter_mut().enumerate() { - let mut variance = 1e-14f64; - for scale in 0..3 { - let mut r: Vec = band.iter().map(|p| p.1[scale][i]).collect(); - let middle = r.len() / 2; - let (_, median, _) = r.select_nth_unstable_by(middle, f32::total_cmp); - // Each kernel has norm squared 1.25. Larger spacings recover noise - // hidden by the positive spatial correlations of demosaiced RGB. - variance = variance.max(*median as f64 / (0.454_936_4 * 1.25)); - } - pts.push((y, variance, band.len() as f64)); - } - } - let mut model = NrcNoise { alpha: [0.0; 3], beta: [1e-14; 3] }; - let mut ymax = [0.0; 3]; - for (i, pts) in pts.iter().enumerate() { - if pts.is_empty() { - continue; - } - // Seed from the darker half, then include all bands with a bounded influence for - // unexpectedly high residuals (foliage etc.). Refit rather than clamp the intercept. - let (a, b, top) = crate::nrc_joint::robust_line(pts); - ymax[i] = top; - model.alpha[i] = a as f32; - model.beta[i] = (b as f32).max(1e-14); - } - JointNoise { model, ymax, tolerance: 1.0 } -} - -/// Squared distance beyond the expected noise in a difference of two guide samples. A small -/// relative luminance allowance lets a smooth surface exchange colour without crossing a -/// significant luminance or isoluminant colour boundary. The guide is fixed across all scales. -fn distance(a: [f32; 3], b: [f32; 3], noise: &JointNoise) -> f32 { - let y = 0.5 * (a[0] + b[0]); - let allowance = (0.025 * y.max(0.0)).powi(2); - (0..3) - .map(|i| { - let v = noise.var(i, y); - // The 3x3 pilot blur reduces uncorrelated noise to 1/9. Keep a conservative - // allowance for correlations left by demosaicing and grid resampling. - ((a[i] - b[i]).powi(2) - v).max(0.0) / (3.0 * noise.tolerance * v + allowance) - }) - .sum::() -} - -/// Denoise the pilot along a clearly smoother axis at strong edges. An isotropic blur -/// dilutes a two-pixel isoluminant line before the edge decision even sees it. Weak or -/// ambiguous structure uses the isotropic pilot, so noise alone does not protect itself. -fn pilot(original: &Rgb32f, noise: &JointNoise) -> Rgb32f { - let mut guide = gaussian(original, 0.8); - let (w, h) = (original.width, original.height); - for_rows(&mut guide.data, w, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - if x == 0 || y == 0 || x + 1 == w || y + 1 == h { - continue; - } - let index = y * w + x; - let Some(&p) = original.data.get(index) else { continue }; - let mut means = [[0.0f32; 3]; 2]; - let mut variances = [0.0; 2]; - for (axis, offset) in [1, w].into_iter().enumerate() { - let (Some(&a), Some(&b)) = (original.data.get(index - offset), original.data.get(index + offset)) else { continue }; - means[axis] = std::array::from_fn(|i| (a[i] + p[i] + b[i]) / 3.0); - variances[axis] = (0..3) - .map(|i| { - let m = means[axis][i]; - ((a[i] - m).powi(2) + (p[i] - m).powi(2) + (b[i] - m).powi(2)) / (9.0 * noise.var(i, p[0])) - }) - .sum::(); - } - *out = crate::nrc_joint::pilot_pick(*out, means[0], variances[0], means[1], variances[1]); - } - }); - guide -} - -/// One conservative horizontal/vertical diffusion step. Pair weights are symmetric; the -/// guide is never replaced by the filtered result. Long taps also account for the intervening -/// guide edges, so a wide pass cannot jump over a thin differently coloured object. -fn diffuse(src: &Rgb32f, dst: &mut Rgb32f, links: &Rgb32f, delta: usize, vertical: bool, rate: f32) { - let (w, h) = (src.width, src.height); - for_rows(&mut dst.data, w, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - let index = y * w + x; - let Some(&p) = src.data.get(index) else { continue }; - *out = p; - let coordinate = if vertical { y } else { x }; - let length = if vertical { h } else { w }; - for neighbour in [coordinate.checked_sub(delta), coordinate.checked_add(delta).filter(|&v| v < length)].into_iter().flatten() { - let ni = if vertical { neighbour * w + x } else { y * w + neighbour }; - let start = coordinate.min(neighbour); - let pi = if vertical { start * w + x } else { y * w + start }; - let (Some(&q), Some(link)) = (src.data.get(ni), links.data.get(pi)) else { continue }; - let weight = rate * link[usize::from(vertical)]; - for i in 1..3 { - out[i] += weight * (q[i] - p[i]); - } - } - } - }); -} - -pub(crate) fn denoise_grid(img: &mut Rgb32f, params: &NrcParams, step: usize, detail: f32, strength: f32) { - if img.is_empty() || strength <= 0.0 { - return; - } - let start = crate::profiling().then(std::time::Instant::now); - // A maximum 2x grid keeps colour boundaries visible even at high strength. The old grid - // grew to 16x with the radius, making the colour loss inseparable from slider strength. - let step = if img.width.is_multiple_of(step) && img.height.is_multiple_of(step) { step } else { 1 }; - let (w, h) = (img.width.div_ceil(step), img.height.div_ceil(step)); - // Transform before resampling; negative linear differences are valid throughout. - let mut original = Rgb32f::new(w, h); - for_rows(&mut original.data, w, |y, row| { - for (x, p) in row.iter_mut().enumerate() { - let mut count = 0.0f32; - for sy in y * step..((y + 1) * step).min(img.height) { - for sx in x * step..((x + 1) * step).min(img.width) { - if let Some(&c) = img.data.get(sy * img.width + sx) { - let c = yuv(c); - *p = std::array::from_fn(|i| p[i] + c[i]); - count += 1.0; - } - } - } - *p = p.map(|v| v / count.max(1.0)); - } - }); - let lap = |what: &str, t: &mut Option| { - if let Some(t0) = t { - eprintln!(" joint {what}: {:.0} ms", t0.elapsed().as_secs_f64() * 1e3); - *t = Some(std::time::Instant::now()); - } - }; - let mut tt = start; - lap("transform", &mut tt); - let mut noise = noise_model(&original); - lap("noise model", &mut tt); - noise.tolerance = (1.5 - detail).clamp(0.5, 1.5); - let guide = pilot(&original, &noise); - lap("pilot", &mut tt); - if std::env::var_os("NRV2_DEBUG").is_some() { - eprintln!(" nr joint: {w}x{h}, Y/R-Y/B-Y alpha {:?} beta {:?}, supported Y {:?}", noise.model.alpha, noise.model.beta, noise.ymax); - } - let mut filtered = original.clone(); - let mut scratch = Rgb32f::new(w, h); - let mut paths = Rgb32f::new(w, h); - let mut links = Rgb32f::new(w, h); - for_rows(&mut paths.data, w, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - let index = y * w + x; - let Some(&g) = guide.data.get(index) else { continue }; - if x + 1 < w - && let Some(&b) = guide.data.get(index + 1) - { - out[0] = distance(g, b, &noise); - } - if y + 1 < h - && let Some(&b) = guide.data.get(index + w) - { - out[1] = distance(g, b, &noise); - } - } - }); - // Scale is independent of the edge decision. K has no role in deciding whether a leaf - // is noise. Two dyadic sweeps provide broad smoothing with a fixed number of scales. - let sigma = params.passes.last().map_or(0.0, |p| p.sigma / step as f32); - let mut remaining = sigma * sigma; - let mut delta = 1usize; - while remaining > 0.01 && delta <= w.max(h) { - let rate = (remaining / (4.0 * (delta as f32).powi(2))).min(0.25); - // Each symmetric pair weight is evaluated once per scale and reused by both - // diffusion sweeps and both ends of the pair. - for_rows(&mut links.data, w, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - let index = y * w + x; - let (Some(&g), Some(path)) = (guide.data.get(index), paths.data.get(index)) else { continue }; - *out = [0.0; 3]; - for (axis, offset, valid) in [(0, delta, x + delta < w), (1, delta * w, y + delta < h)] { - if valid && let Some(&other) = guide.data.get(index + offset) { - out[axis] = (-distance(g, other, &noise).max(path[axis])).exp(); - } - } - } - }); - for _ in 0..2 { - diffuse(&filtered, &mut scratch, &links, delta, false, rate); - std::mem::swap(&mut filtered, &mut scratch); - diffuse(&filtered, &mut scratch, &links, delta, true, rate); - std::mem::swap(&mut filtered, &mut scratch); - } - remaining -= 4.0 * rate * (delta as f32).powi(2); - // Maxima over paths of length 2*delta, using the two adjacent delta-length paths. - // Reuse the diffusion scratch so a long tap costs O(1), irrespective of radius. - for_rows(&mut scratch.data, w, |y, row| { - for (x, out) in row.iter_mut().enumerate() { - let index = y * w + x; - let Some(&p) = paths.data.get(index) else { continue }; - *out = p; - if x + delta < w - && let Some(q) = paths.data.get(index + delta) - { - out[0] = out[0].max(q[0]); - } - if y + delta < h - && let Some(q) = paths.data.get(index + delta * w) - { - out[1] = out[1].max(q[1]); - } - } - }); - std::mem::swap(&mut paths, &mut scratch); - lap(&format!("scale {delta}"), &mut tt); - delta = delta.saturating_mul(2); - } - drop(scratch); - drop(paths); - drop(links); - if step == 1 { - for (p, q) in img.data.iter_mut().zip(&filtered.data) { - let result = rgb(luminance_2020(*p), *q); - *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); - } - } else { - // Reconstruct only rows. Keep the fine residual with a shared, noise-subtracted - // Wiener share; a flat noisy patch receives no automatic protection from noisy Y. - let mean = gaussian(&original, 1.0); - let corr = gaussian(&original.map(|p| p.map(|v| v * v)), 1.0); - let share = corr.zip_map(&mean, |c, m| { - let snr = (1..3).map(|i| ((c[i] - m[i] * m[i]).max(0.0) / noise.var(i, m[0]) - 1.0).max(0.0)).sum::() * 0.5; - [snr / (snr + 8.0); 3] - }); - let share = gaussian(&share, 0.8); - // Resize one output row at a time using the raster resampler's exact pixel centres. - use lightcraft_raster::resample::weights; - let ux = weights(w, img.width, Filter::Bilinear); - let uy = weights(h, img.height, Filter::Bilinear); - let ow = img.width; - for_rows(&mut img.data, ow, |y, row| { - let Some((y0, wy)) = uy.get(y) else { return }; - for (x, p) in row.iter_mut().enumerate() { - let Some((x0, wx)) = ux.get(x) else { continue }; - let (mut f, mut o, mut a) = ([0.0; 3], [0.0; 3], 0.0); - for (j, &dy) in wy.iter().enumerate() { - for (i, &dx) in wx.iter().enumerate() { - let index = (y0 + j) * w + x0 + i; - if let (Some(q), Some(r), Some(s)) = (filtered.data.get(index), original.data.get(index), share.data.get(index)) { - let weight = dx * dy; - f = std::array::from_fn(|c| f[c] + weight * q[c]); - o = std::array::from_fn(|c| o[c] + weight * r[c]); - a += weight * s[0]; - } - } - } - let c = yuv(*p); - let q = std::array::from_fn(|i| f[i] + a * (c[i] - o[i])); - let result = rgb(c[0], q); - *p = std::array::from_fn(|i| p[i] + strength * (result[i] - p[i])); - } - }); - } - if let Some(start) = start { - eprintln!(" nr joint: {:.1} ms", start.elapsed().as_secs_f64() * 1e3); - } -} diff --git a/crates/pipeline/src/profiles.rs b/crates/pipeline/src/profiles.rs index c519b2a34b..2131714fdd 100644 --- a/crates/pipeline/src/profiles.rs +++ b/crates/pipeline/src/profiles.rs @@ -1,310 +1,20 @@ -//! Base rendering profiles. A profile is a look applied *underneath* the user's sliders (the sliders -//! stay at their displayed values); `profile.amount` (0–200 %) scales it. All looks are our own. -//! -//! Every look is a set of *deltas* on the user's settings, each multiplied by the amount: slider -//! offsets (contrast, saturation, colour mixer, B&W mix…), colour-grading wheels (added as colour -//! vectors to the user's wheels) and point-curve fades (black/white output levels composed after -//! the user's point curves). The CPU pipeline and the GPU path both render [`effective`] -//! settings, so a profile needs no kernel of its own. No look adds grain. +//! Base rendering profiles, backed by `craft_develop::profiles`. use std::borrow::Cow; -use lightcraft_develop::{DevelopSettings, Treatment, Wheel}; -use lightcraft_geom::Point; +use lightcraft_develop::DevelopSettings; -/// Add a colour-grading wheel (`hue` °, `sat` 0..100, `lum` −100..100) scaled by `k` to `w`, as a -/// colour vector (so a profile's tint combines with the user's instead of replacing it). -fn wheel(w: &mut Wheel, hue: f64, sat: f64, lum: f64, k: f64) { - let (ua, ub) = (w.sat * w.hue.to_radians().cos(), w.sat * w.hue.to_radians().sin()); - let (pa, pb) = (sat * k * hue.to_radians().cos(), sat * k * hue.to_radians().sin()); - let (a, b) = (ua + pa, ub + pb); - let s = a.hypot(b); - if s > 1e-9 { - w.hue = b.atan2(a).to_degrees().rem_euclid(360.0); - } else if w.sat == 0.0 { - w.hue = hue; - } - w.sat = s.clamp(0.0, 100.0); - w.lum = (w.lum + lum * k).clamp(-100.0, 100.0); -} - -/// Fade a point curve: output black level `black` and white level `white` (0..1, moved from the -/// identity by `k`), composed after the user's curve (`y → b + y·(w − b)`). -fn fade(pts: &mut Vec, black: f64, white: f64, k: f64) { - let b = (black * k).clamp(0.0, 0.45); - let w = (1.0 - (1.0 - white) * k).clamp(0.55, 1.0); - if pts.len() < 2 { - *pts = vec![Point::new(0.0, 0.0), Point::new(1.0, 1.0)]; - } - for p in pts.iter_mut() { - p.y = b + p.y.clamp(0.0, 1.0) * (w - b); - } -} +pub use craft_develop::profiles::LOOK_IDS; /// The settings the pipeline actually renders: user settings plus the profile's look. pub fn effective(s: &DevelopSettings) -> Cow<'_, DevelopSettings> { - let k = (s.profile.amount / 100.0).clamp(0.0, 2.0); - let id = s.profile.id.as_str(); - if id == "lc.color" || id.is_empty() || k == 0.0 { - return Cow::Borrowed(s); - } - let mut e = s.clone(); - let add = |v: &mut f64, d: f64| *v = (*v + d * k).clamp(-100.0, 100.0); - match id { - // ---- Basic - "lc.neutral" => { - add(&mut e.light.contrast, -18.0); - add(&mut e.color.saturation, -10.0); - add(&mut e.light.highlights, -10.0); - add(&mut e.light.shadows, 8.0); - } - "lc.vivid" => { - add(&mut e.light.contrast, 16.0); - add(&mut e.color.saturation, 14.0); - add(&mut e.color.vibrance, 14.0); - add(&mut e.light.blacks, -6.0); - } - "lc.landscape" => { - add(&mut e.light.contrast, 10.0); - add(&mut e.color.vibrance, 10.0); - add(&mut e.mixer.green.sat, 14.0); - add(&mut e.mixer.aqua.sat, 10.0); - add(&mut e.mixer.blue.sat, 14.0); - add(&mut e.mixer.blue.lum, -6.0); - add(&mut e.effects.clarity, 6.0); - } - "lc.portrait" => { - add(&mut e.light.contrast, -6.0); - add(&mut e.mixer.orange.sat, -8.0); - add(&mut e.mixer.orange.lum, 6.0); - add(&mut e.mixer.red.sat, -5.0); - add(&mut e.effects.texture, -6.0); - } - "lc.mono" => { - e.treatment = Treatment::Bw; - add(&mut e.light.contrast, 8.0); - } - // ---- Film - "lc.film.warm-print" => { - add(&mut e.light.contrast, 6.0); - add(&mut e.color.saturation, -4.0); - add(&mut e.mixer.orange.lum, 4.0); - fade(&mut e.curve.master, 0.04, 0.97, k); - wheel(&mut e.grading.highlights, 40.0, 18.0, 0.0, k); - wheel(&mut e.grading.shadows, 25.0, 8.0, 0.0, k); - } - "lc.film.cool-fade" => { - add(&mut e.light.contrast, -8.0); - add(&mut e.color.saturation, -10.0); - fade(&mut e.curve.master, 0.07, 0.95, k); - wheel(&mut e.grading.shadows, 210.0, 16.0, 0.0, k); - wheel(&mut e.grading.highlights, 190.0, 6.0, 0.0, k); - } - "lc.film.golden-hour" => { - add(&mut e.color.vibrance, 10.0); - add(&mut e.curve.highlights, -8.0); - add(&mut e.mixer.orange.sat, 8.0); - add(&mut e.mixer.yellow.hue, -6.0); - wheel(&mut e.grading.global, 45.0, 10.0, 0.0, k); - wheel(&mut e.grading.highlights, 35.0, 20.0, 0.0, k); - } - "lc.film.faded-slide" => { - add(&mut e.light.contrast, 14.0); - add(&mut e.color.vibrance, 8.0); - add(&mut e.color.saturation, 6.0); - add(&mut e.curve.shadows, 10.0); - fade(&mut e.curve.blue, 0.06, 1.0, k); - fade(&mut e.curve.red, 0.0, 0.97, k); - } - // ---- Cinematic - "lc.cine.teal-amber" => { - add(&mut e.light.contrast, 10.0); - add(&mut e.mixer.orange.sat, 6.0); - add(&mut e.mixer.green.hue, 20.0); - add(&mut e.mixer.green.sat, -20.0); - add(&mut e.mixer.blue.hue, -8.0); - wheel(&mut e.grading.shadows, 195.0, 30.0, 0.0, k); - wheel(&mut e.grading.highlights, 38.0, 24.0, 0.0, k); - } - "lc.cine.night-blue" => { - add(&mut e.light.contrast, 12.0); - add(&mut e.color.saturation, -12.0); - add(&mut e.curve.darks, -8.0); - wheel(&mut e.grading.shadows, 220.0, 28.0, -4.0, k); - wheel(&mut e.grading.midtones, 215.0, 10.0, 0.0, k); - } - "lc.cine.desert-heat" => { - add(&mut e.light.contrast, 8.0); - add(&mut e.curve.lights, 6.0); - add(&mut e.mixer.blue.sat, -25.0); - add(&mut e.mixer.aqua.sat, -20.0); - wheel(&mut e.grading.global, 32.0, 16.0, 0.0, k); - wheel(&mut e.grading.highlights, 48.0, 12.0, 0.0, k); - } - "lc.cine.neon-dusk" => { - add(&mut e.light.contrast, 10.0); - add(&mut e.color.vibrance, 18.0); - add(&mut e.mixer.magenta.sat, 12.0); - add(&mut e.mixer.purple.sat, 12.0); - wheel(&mut e.grading.shadows, 265.0, 22.0, 0.0, k); - wheel(&mut e.grading.highlights, 330.0, 14.0, 0.0, k); - } - // ---- Muted - "lc.muted.matte-soft" => { - add(&mut e.light.contrast, -12.0); - add(&mut e.color.saturation, -14.0); - add(&mut e.curve.highlights, -6.0); - fade(&mut e.curve.master, 0.08, 0.96, k); - } - "lc.muted.bleached" => { - add(&mut e.light.contrast, 22.0); - add(&mut e.color.saturation, -38.0); - add(&mut e.curve.lights, 6.0); - add(&mut e.effects.clarity, 8.0); - } - "lc.muted.pastel-haze" => { - add(&mut e.light.contrast, -18.0); - add(&mut e.color.saturation, -20.0); - add(&mut e.color.vibrance, 12.0); - fade(&mut e.curve.master, 0.1, 1.0, k); - wheel(&mut e.grading.highlights, 330.0, 6.0, 0.0, k); - wheel(&mut e.grading.shadows, 200.0, 6.0, 0.0, k); - } - "lc.muted.quiet-green" => { - add(&mut e.light.contrast, -4.0); - add(&mut e.color.saturation, -8.0); - add(&mut e.mixer.green.sat, -30.0); - add(&mut e.mixer.green.hue, -10.0); - add(&mut e.mixer.yellow.sat, -18.0); - add(&mut e.mixer.aqua.sat, -15.0); - fade(&mut e.curve.master, 0.04, 1.0, k); - } - // ---- B&W - "lc.bw.mono-rich" => { - e.treatment = Treatment::Bw; - add(&mut e.light.contrast, 18.0); - add(&mut e.curve.darks, -8.0); - add(&mut e.curve.lights, 6.0); - add(&mut e.bw_mix.red, 8.0); - add(&mut e.bw_mix.orange, 10.0); - add(&mut e.bw_mix.blue, -12.0); - } - "lc.bw.red-filter" => { - e.treatment = Treatment::Bw; - add(&mut e.light.contrast, 12.0); - add(&mut e.bw_mix.red, 40.0); - add(&mut e.bw_mix.orange, 30.0); - add(&mut e.bw_mix.yellow, 10.0); - add(&mut e.bw_mix.green, -20.0); - add(&mut e.bw_mix.aqua, -30.0); - add(&mut e.bw_mix.blue, -45.0); - } - "lc.bw.soft" => { - e.treatment = Treatment::Bw; - add(&mut e.light.contrast, -14.0); - add(&mut e.bw_mix.orange, 12.0); - fade(&mut e.curve.master, 0.06, 0.97, k); - } - "lc.bw.sepia" => { - e.treatment = Treatment::Bw; - add(&mut e.light.contrast, 6.0); - fade(&mut e.curve.master, 0.04, 0.98, k); - wheel(&mut e.grading.shadows, 28.0, 18.0, 0.0, k); - wheel(&mut e.grading.highlights, 45.0, 14.0, 0.0, k); - } - _ => return Cow::Borrowed(s), - } - Cow::Owned(e) -} - -/// Ids of the looks [`effective`] implements (besides the identity `lc.color`). -pub const LOOK_IDS: &[&str] = &[ - "lc.neutral", - "lc.vivid", - "lc.landscape", - "lc.portrait", - "lc.mono", - "lc.film.warm-print", - "lc.film.cool-fade", - "lc.film.golden-hour", - "lc.film.faded-slide", - "lc.cine.teal-amber", - "lc.cine.night-blue", - "lc.cine.desert-heat", - "lc.cine.neon-dusk", - "lc.muted.matte-soft", - "lc.muted.bleached", - "lc.muted.pastel-haze", - "lc.muted.quiet-green", - "lc.bw.mono-rich", - "lc.bw.red-filter", - "lc.bw.soft", - "lc.bw.sepia", -]; - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn default_profile_is_borrowed_and_others_change_things() { - let s = DevelopSettings::default(); - assert!(matches!(effective(&s), Cow::Borrowed(_))); - for id in LOOK_IDS { - let mut t = s.clone(); - t.profile.id = (*id).into(); - assert_ne!(*effective(&t), t, "{id}"); - t.profile.amount = 0.0; - assert_eq!(*effective(&t), t, "{id} at 0%"); - } - } - - #[test] - fn looks_scale_with_amount_and_never_add_grain() { - let mut s = DevelopSettings::default(); - s.light.contrast = 5.0; - for id in LOOK_IDS { - s.profile.id = (*id).into(); - let at = |a: f64| { - let mut t = s.clone(); - t.profile.amount = a; - effective(&t).into_owned() - }; - let (half, full, double) = (at(50.0), at(100.0), at(200.0)); - // slider deltas are linear in the amount - let d = |e: &DevelopSettings| e.light.contrast - s.light.contrast; - assert!((d(&full) - 2.0 * d(&half)).abs() < 1e-9, "{id}"); - assert!((d(&double) - 2.0 * d(&full)).abs() < 1e-9, "{id}"); - // wheels and point-curve fades grow with the amount - let lift = |e: &DevelopSettings| e.curve.master.first().map_or(0.0, |p| p.y); - for (a, b) in [(&half, &full), (&full, &double)] { - assert!(a.grading.shadows.sat <= b.grading.shadows.sat + 1e-9, "{id}"); - assert!(a.grading.highlights.sat <= b.grading.highlights.sat + 1e-9, "{id}"); - assert!(lift(a) <= lift(b) + 1e-9, "{id}"); - } - if lift(&full) > 0.0 { - assert!((lift(&full) - 2.0 * lift(&half)).abs() < 1e-9, "{id}"); - } - assert_eq!(full.grain, s.grain, "{id} adds no grain"); - assert_eq!(full.profile, s.profile, "{id}"); - } - } - - #[test] - fn wheels_and_fades_compose_with_user_settings() { - let mut s = DevelopSettings::default(); - s.grading.shadows = Wheel { hue: 195.0, sat: 10.0, lum: 0.0 }; - s.curve.master = vec![Point::new(0.0, 0.0), Point::new(0.5, 0.6), Point::new(1.0, 1.0)]; - s.profile.id = "lc.cine.teal-amber".into(); - let e = effective(&s); - assert!((e.grading.shadows.hue - 195.0).abs() < 1e-6 && (e.grading.shadows.sat - 40.0).abs() < 1e-6, "{:?}", e.grading.shadows); - assert_eq!(e.curve.master, s.curve.master, "no fade in this look: the user's curve stays"); - s.profile.id = "lc.muted.matte-soft".into(); - let e = effective(&s); - assert_eq!(e.curve.master.len(), 3, "user points kept"); - let ys: Vec = e.curve.master.iter().map(|p| p.y).collect(); - for (y, want) in ys.iter().zip([0.08, 0.08 + 0.6 * 0.88, 0.96]) { - assert!((y - want).abs() < 1e-9, "{ys:?}"); + let craft = crate::bridge::to_craft_settings(s); + match craft_develop::profiles::effective(&craft) { + Cow::Borrowed(_) => Cow::Borrowed(s), + Cow::Owned(modified) => { + let mut out = s.clone(); + crate::bridge::apply_craft_profile_fields(&mut out, &modified); + Cow::Owned(out) } } } diff --git a/crates/pipeline/src/tests_light.rs b/crates/pipeline/src/tests_light.rs index dd38bbf046..2de094b404 100644 --- a/crates/pipeline/src/tests_light.rs +++ b/crates/pipeline/src/tests_light.rs @@ -1,11 +1,11 @@ //! Process V4's calibrated Contrast and Blacks (`light_v3`): V1 and V2 render as they //! always did, and the V4 operators behave. -use lightcraft_color::transfer::{linear_to_srgb, srgb_to_linear}; +use lightcraft_color::transfer::linear_to_srgb; use lightcraft_develop::{DevelopSettings, Process, ProcessVersion, controls}; use lightcraft_raster::{Rgb32f, Rgba8}; -use crate::light_v3::{self, FITS, LUT_N, LightOps, Mode, Operator, Reference}; +use crate::light_v3::{self, FITS, LUT_N, LightOps, Mode, Operator}; use crate::light_v3_params as fitted; use crate::{DeepSamples, OutputDepth, PixelWindow, RenderRequest, SourceInfo, StageCache, render, render_cached}; @@ -152,15 +152,15 @@ fn on(process: Process, s: &DevelopSettings) -> DevelopSettings { } /// Every slider and amount the operator checks sweep: Contrast and Blacks with -/// their fits and references. -fn fits() -> [(&'static str, &'static light_v3::Fit, &'static [Reference]); 2] { - [("contrast", &fitted::CONTRAST, fitted::CONTRAST_REFERENCE), ("blacks", &fitted::BLACKS, fitted::BLACKS_REFERENCE)] +/// their fits. +fn fits() -> [(&'static str, &'static light_v3::Fit); 2] { + [("contrast", &fitted::CONTRAST), ("blacks", &fitted::BLACKS)] } #[test] fn the_shipped_fits_unpack_as_the_family_lays_them_out() { assert!(std::ptr::eq(FITS[0], &fitted::CONTRAST) && std::ptr::eq(FITS[1], &fitted::BLACKS)); - for (name, fit, _) in fits() { + for (name, fit) in fits() { let u = fit.unpack().unwrap_or_else(|| panic!("{name} doesn't unpack")); // D(1) = 0, and Contrast's shapes are anchored at black too assert_eq!((u.d_pos[11], u.d_neg[11]), (0.0, 0.0), "{name}"); @@ -221,40 +221,10 @@ fn preview_tables_match_exact_operators_over_combined_amounts() { eprintln!("Preview table maximum encoded error {worst:.6} of an 8-bit level"); } -/// The port against the family's own Python (`tools/light_v3_family.py`, through the generated -/// references): `Family.curve` to the references' 12 digits, and `Family.apply` on pixels to the -/// tables' interpolation. -#[test] -fn the_operators_are_fit_pointwise_family() { - for (name, fit, refs) in fits() { - let u = fit.unpack().unwrap(); - assert!(!refs.is_empty()); - let mut worst = 0.0f64; - for r in refs { - for (v, want) in fitted::REF_V.iter().zip(r.curve) { - let got = u.curve(r.amount, *v); - // (the references are written at 12 significant digits) - assert!((got - want).abs() < 1e-11, "{name} {} at {v}: {got} vs {want}", r.amount); - } - let Some(apply) = r.apply else { continue }; - let op = Operator::new(fit, r.amount).unwrap(); - for (px, want) in fitted::REF_PIX.iter().zip(apply) { - let lin = px.map(|v| srgb_to_linear(v as f32)); - let got = op.apply(lin, &linear_to_srgb).map(linear_to_srgb); - for k in 0..3 { - worst = worst.max((got[k] as f64 - want[k]).abs()); - } - } - } - eprintln!("{name}: worst |apply - Family.apply| {worst:.2e} (encoded)"); - assert!(worst < 1e-3, "{name}: {worst}"); - } -} - /// Each operator is non-decreasing at every integer amount and maps white to white. #[test] fn every_operator_is_monotone_and_keeps_white() { - for (name, fit, _) in fits() { + for (name, fit) in fits() { for a in (-100..=100).filter(|a| *a != 0) { let op = Operator::new(fit, a as f64).unwrap(); assert!(op.lut[0] >= 0.0, "{name} {a}: F(0) = {}", op.lut[0]); @@ -275,7 +245,7 @@ fn every_operator_is_monotone_and_keeps_white() { /// the fit. #[test] fn a_folding_fit_is_flattened_and_others_are_untouched() { - for (name, fit, _) in fits() { + for (name, fit) in fits() { let u = fit.unpack().unwrap(); for a in [-100.0, -50.0, -10.0, 10.0, 50.0, 100.0] { let mut fold = 0.0f64; @@ -423,7 +393,7 @@ fn window_diff(full: &Rgba8, w: &Rgba8, win: PixelWindow) -> u8 { fn hdr_components_follow_the_operators_mode() { let enc = &linear_to_srgb; let lum = |p: [f32; 3]| light_v3::PRO_Y[0] * p[0] + light_v3::PRO_Y[1] * p[1] + light_v3::PRO_Y[2] * p[2]; - for (name, fit, _) in fits() { + for (name, fit) in fits() { for a in [-100.0, -40.0, 40.0, 100.0] { let op = Operator::new(fit, a).unwrap(); for p in [[1.2f32, 0.2, 0.05], [3.0, 1.5, 0.8], [0.4, 1.1, 0.02]] { diff --git a/crates/pipeline/src/visualize.rs b/crates/pipeline/src/visualize.rs index 86d6ade16c..ed35488f3a 100644 --- a/crates/pipeline/src/visualize.rs +++ b/crates/pipeline/src/visualize.rs @@ -313,7 +313,7 @@ pub fn apply(img: &mut Rgba8, o: Overlay, plan: &Plan<'_>, plane: Option<&Plane> Overlay::None | Overlay::HdrRange => {} Overlay::PointColorRange(i) => { if let Some(p) = plan.settings.point_colors.get(i as usize) { - point_color_range(img, &PointK::new(p)); + point_color_range(img, &PointK::new(&crate::bridge::to_craft_point_color(p))); } } Overlay::Spots(t) => spots(img, t, plan.px_per_long), diff --git a/crates/raw/Cargo.toml b/crates/raw/Cargo.toml index 078d76eb97..8a75837bba 100644 --- a/crates/raw/Cargo.toml +++ b/crates/raw/Cargo.toml @@ -11,6 +11,9 @@ workspace = true [dependencies] craft-tiff = { workspace = true } craft-raw = { workspace = true } +craft-develop = { workspace = true } +craft-color = { workspace = true } +craft-color-transform = { workspace = true } lightcraft-meta = { workspace = true } lightcraft-raster = { workspace = true } lightcraft-color = { workspace = true } diff --git a/crates/raw/src/bridge.rs b/crates/raw/src/bridge.rs new file mode 100644 index 0000000000..f4e1ea9827 --- /dev/null +++ b/crates/raw/src/bridge.rs @@ -0,0 +1,82 @@ +//! Adapters between `lightcraft_*` types and `craft_*` types for delegating to `craft_develop::sensor`. + +use craft_color_transform::{Mat3 as CraftMat3, Xy as CraftXy}; +use craft_develop::raster::Rgb32f as CraftRgb32f; +use lightcraft_color::{Mat3, Xy}; +use lightcraft_raster::Rgb32f; + +use crate::{ColorData, RawData, RawImage}; + +pub fn to_craft_xy(xy: Xy) -> CraftXy { + CraftXy { x: xy.x, y: xy.y } +} + +pub fn from_craft_xy(xy: CraftXy) -> Xy { + Xy { x: xy.x, y: xy.y } +} + +pub fn from_craft_mat3(m: CraftMat3) -> Mat3 { + Mat3(m.0) +} + +pub fn to_craft_rgb32f(img: &Rgb32f) -> CraftRgb32f { + CraftRgb32f { width: img.width, height: img.height, data: img.data.clone() } +} + +pub fn from_craft_rgb32f(craft: CraftRgb32f) -> Rgb32f { + Rgb32f { width: craft.width, height: craft.height, data: craft.data } +} + +pub fn take_craft_rgb32f(img: &mut Rgb32f) -> CraftRgb32f { + CraftRgb32f { width: img.width, height: img.height, data: std::mem::take(&mut img.data) } +} + +pub fn put_craft_rgb32f(img: &mut Rgb32f, craft: CraftRgb32f) { + img.width = craft.width; + img.height = craft.height; + img.data = craft.data; +} + +pub fn to_craft_color_data(c: &ColorData) -> craft_raw::ColorData { + craft_raw::ColorData { + illuminant: c.illuminant, + color_matrix: c.color_matrix.map(|m| m.map(|m| m.0)), + forward_matrix: c.forward_matrix.map(|m| m.map(|m| m.0)), + camera_calibration: c.camera_calibration.map(|m| m.map(|m| m.0)), + analog_balance: c.analog_balance, + as_shot_neutral: c.as_shot_neutral, + as_shot_white_xy: c.as_shot_white_xy.map(|xy| [xy.x, xy.y]), + baseline_exposure: c.baseline_exposure, + baseline_sharpness: c.baseline_sharpness, + profile: Default::default(), + kelvin_presets: None, + } +} + +pub fn to_craft_raw_header(raw: &RawImage) -> craft_raw::RawImage { + craft_raw::RawImage { + format: raw.format, + width: raw.width, + height: raw.height, + cpp: raw.cpp, + data: RawData::U16(Vec::new()), + cfa: raw.cfa.clone(), + bits: raw.bits, + black: raw.black.clone(), + white: raw.white.clone(), + active_area: raw.active_area, + crop: raw.crop, + orientation: craft_raw::Orientation::Normal, + color: to_craft_color_data(&raw.color), + wb_multipliers: raw.wb_multipliers, + linearized: raw.linearized, + pixel_aspect: raw.pixel_aspect, + opcodes: raw.opcodes.clone(), + lens_metadata: raw.lens_metadata.clone(), + cinema: Default::default(), + camera: Default::default(), + linearization_table: None, + level_sources: Default::default(), + notices: Default::default(), + } +} diff --git a/crates/raw/src/color.rs b/crates/raw/src/color.rs index 2caafcfde7..23ab1f8118 100644 --- a/crates/raw/src/color.rs +++ b/crates/raw/src/color.rs @@ -1,174 +1,56 @@ -//! DNG colour model (Adobe DNG Specification 1.7, chapter 6 "Mapping Camera Color Space to CIE XYZ Space"). -//! -//! - `ColorMatrix1/2` (XYZ → reference camera) and `CameraCalibration1/2` / `ForwardMatrix1/2` are interpolated -//! between the two calibration illuminants by inverse correlated colour temperature of the white point. -//! - `XYZtoCamera = AnalogBalance · CameraCalibration · ColorMatrix`. -//! - White balance multipliers are the reciprocal of the camera neutral for the chosen white. -//! - Camera → XYZ(D50): through `ForwardMatrix` when present, else the inverse of `XYZtoCamera` followed by -//! Bradford adaptation from the white to D50. -//! - The as-shot white comes from `AsShotWhiteXY`, or `AsShotNeutral` converted to xy by the spec's iteration. -//! -//! Cameras without a colour matrix (non-DNG files until our own calibration DB exists) use a generic -//! "camera RGB ≈ linear sRGB" model and are flagged with `matrix_is_fallback`. +//! DNG colour model (Adobe DNG Specification 1.7, chapter 6), backed by `craft_develop::sensor::color`. -use crate::{ColorData, Mat3, RawImage}; -use lightcraft_color::{D50, D65, REC2020, SRGB, Xy, bradford, cct}; +use lightcraft_color::{Mat3, Xy}; use serde::{Deserialize, Serialize}; -/// Correlated colour temperature (K) of an Exif `LightSource` / DNG `CalibrationIlluminant` code. -pub fn illuminant_temperature(code: u16) -> Option { - Some(match code { - 1 | 4 | 9 => 5500.0, - 2 | 14 => 4150.0, - 3 => 2850.0, - 10 => 6500.0, - 11 => 7500.0, - 12 => 6430.0, - 13 => 5000.0, - 15 => 3450.0, - 16 => 2940.0, - 17 => 2856.0, - 18 => 4874.0, - 19 => 6774.0, - 20 => 5503.0, - 21 => 6504.0, - 22 => 7504.0, - 23 => 5003.0, - 24 => 3200.0, - _ => return None, - }) -} +use crate::{ColorData, RawImage}; -fn lerp(a: &Mat3, b: &Mat3, g: f64) -> Mat3 { - let mut r = [[0.0; 3]; 3]; - for i in 0..3 { - for j in 0..3 { - r[i][j] = g * a.0[i][j] + (1.0 - g) * b.0[i][j]; - } - } - Mat3(r) -} +pub use craft_develop::sensor::color::illuminant_temperature; -/// Weight of calibration 1 for white `xy` (1 = use matrix 1 only). pub fn illuminant_weight(color: &ColorData, white: Xy) -> f64 { - let t = cct::xy_to_temp_tint(white).0; - let (t1, t2) = (illuminant_temperature(color.illuminant[0]).unwrap_or(2856.0), illuminant_temperature(color.illuminant[1]).unwrap_or(6504.0)); - if (t1 - t2).abs() < 1.0 { - return 1.0; - } - let g = (1.0 / t - 1.0 / t2) / (1.0 / t1 - 1.0 / t2); - g.clamp(0.0, 1.0) + craft_develop::sensor::color::illuminant_weight(&crate::bridge::to_craft_color_data(color), crate::bridge::to_craft_xy(white)) } -fn interp(pair: &[Option; 2], g: f64) -> Option { - match pair { - [Some(a), Some(b)] => Some(lerp(a, b, g)), - [Some(a), None] | [None, Some(a)] => Some(*a), - [None, None] => None, - } -} - -/// `AnalogBalance · CameraCalibration` for white `xy`. -fn ab_cc(color: &ColorData, g: f64) -> Mat3 { - let ab = color.analog_balance.map(|a| Mat3::diag(a[0], a[1], a[2])).unwrap_or(Mat3::IDENTITY); - let cc = interp(&color.camera_calibration, g).unwrap_or(Mat3::IDENTITY); - ab.mul(&cc) -} - -/// Whether the file carries a usable colour matrix. pub fn has_matrix(color: &ColorData) -> bool { - color.color_matrix.iter().any(|m| m.is_some()) + craft_develop::sensor::color::has_matrix(&crate::bridge::to_craft_color_data(color)) } -/// `XYZtoCamera` for white `xy` (fallback: XYZ → linear sRGB). pub fn xyz_to_camera(color: &ColorData, white: Xy) -> Mat3 { - let g = illuminant_weight(color, white); - match interp(&color.color_matrix, g) { - Some(cm) => ab_cc(color, g).mul(&cm), - None => SRGB.from_xyz(), - } + crate::bridge::from_craft_mat3(craft_develop::sensor::color::xyz_to_camera( + &crate::bridge::to_craft_color_data(color), + crate::bridge::to_craft_xy(white), + )) } -/// Camera neutral (raw camera values of a neutral surface under white `xy`), normalised to max 1. pub fn camera_neutral(color: &ColorData, white: Xy) -> [f64; 3] { - let n = xyz_to_camera(color, white).apply(white.to_xyz()); - let mx = n.iter().cloned().fold(f64::MIN, f64::max); - if mx > 0.0 { n.map(|v| v / mx) } else { [1.0; 3] } + craft_develop::sensor::color::camera_neutral(&crate::bridge::to_craft_color_data(color), crate::bridge::to_craft_xy(white)) } -/// White-balance multipliers for white `xy` (reciprocal camera neutral, minimum 1). pub fn wb_multipliers(color: &ColorData, white: Xy) -> [f64; 3] { - let n = camera_neutral(color, white); - let m = n.map(|v| if v > 1e-9 { 1.0 / v } else { 1.0 }); - let mn = m.iter().cloned().fold(f64::MAX, f64::min); - m.map(|v| v / mn) + craft_develop::sensor::color::wb_multipliers(&crate::bridge::to_craft_color_data(color), crate::bridge::to_craft_xy(white)) } -/// Convert a camera neutral to a white xy (DNG spec iteration: xy → XYZtoCamera(xy) → xy until stable). pub fn neutral_to_xy(color: &ColorData, neutral: [f64; 3]) -> Xy { - let mut xy = D50; - for _ in 0..50 { - let Some(inv) = xyz_to_camera(color, xy).inverse() else { return xy }; - let xyz = inv.apply(neutral); - let next = Xy::from_xyz(xyz); - if !(next.x.is_finite() && next.y.is_finite()) || next.y <= 0.0 { - return xy; - } - let next = Xy::new(next.x.clamp(0.1, 0.7), next.y.clamp(0.1, 0.7)); - let done = (next.x - xy.x).abs() < 1e-9 && (next.y - xy.y).abs() < 1e-9; - xy = next; - if done { - break; - } - } - xy + crate::bridge::from_craft_xy(craft_develop::sensor::color::neutral_to_xy(&crate::bridge::to_craft_color_data(color), neutral)) } -/// The as-shot white point: `AsShotWhiteXY`, `AsShotNeutral`, vendor multipliers, else D65. pub fn as_shot_white_xy(raw: &RawImage) -> Xy { - as_shot_white(&raw.color, raw.wb_multipliers) + as_shot_white_of(&raw.color, raw.wb_multipliers) } -/// [`as_shot_white_xy`] from a header-only [`crate::RawInfo`]. pub fn as_shot_white_xy_of(info: &crate::RawInfo) -> Xy { - as_shot_white(&info.color, info.wb_multipliers) + as_shot_white_of(&info.color, info.wb_multipliers) } -/// The as-shot white from colour tags and vendor multipliers alone (see [`as_shot_white_xy`]). pub fn as_shot_white_of(c: &ColorData, wb_multipliers: Option<[f32; 3]>) -> Xy { - as_shot_white(c, wb_multipliers) + crate::bridge::from_craft_xy(craft_develop::sensor::color::as_shot_white_of(&crate::bridge::to_craft_color_data(c), wb_multipliers)) } -fn as_shot_white(c: &ColorData, wb_multipliers: Option<[f32; 3]>) -> Xy { - if let Some(xy) = c.as_shot_white_xy { - return xy; - } - if let Some(n) = c.as_shot_neutral { - return neutral_to_xy(c, n); - } - if let Some(m) = wb_multipliers.filter(|m| m.iter().all(|v| *v > 0.0 && v.is_finite())) { - return neutral_to_xy(c, [1.0 / m[0] as f64, 1.0 / m[1] as f64, 1.0 / m[2] as f64]); - } - D65 -} - -/// Camera (raw, not white balanced) → XYZ relative to D50, for scene white `xy`. pub fn camera_to_xyz_d50(color: &ColorData, white: Xy) -> Mat3 { - let g = illuminant_weight(color, white); - if has_matrix(color) - && let Some(fm) = interp(&color.forward_matrix, g) - { - let abcc = ab_cc(color, g); - if let Some(abcc_inv) = abcc.inverse() { - let n = camera_neutral(color, white); - let rn = abcc_inv.apply(n); - if rn.iter().all(|v| *v > 1e-9) { - return fm.mul(&Mat3::diag(1.0 / rn[0], 1.0 / rn[1], 1.0 / rn[2])).mul(&abcc_inv); - } - } - } - let cam_to_xyz = xyz_to_camera(color, white).inverse().unwrap_or(Mat3::IDENTITY); - bradford(white, D50).mul(&cam_to_xyz) + crate::bridge::from_craft_mat3(craft_develop::sensor::color::camera_to_xyz_d50( + &crate::bridge::to_craft_color_data(color), + crate::bridge::to_craft_xy(white), + )) } /// Everything the pipeline needs to go from raw camera RGB to the working space. @@ -184,265 +66,45 @@ pub struct CameraTransform { pub baseline_exposure: f64, } -/// Camera transform for white `wb_xy`: `rec2020 = matrix · (wb ⊙ camera)`. +impl From for CameraTransform { + fn from(t: craft_develop::sensor::color::CameraTransform) -> Self { + Self { + matrix: crate::bridge::from_craft_mat3(t.matrix), + wb: t.wb, + white_xy: crate::bridge::from_craft_xy(t.white_xy), + matrix_is_fallback: t.matrix_is_fallback, + baseline_exposure: t.baseline_exposure, + } + } +} + pub fn camera_transform(raw: &RawImage, wb_xy: Xy) -> CameraTransform { camera_transform_of(&raw.color, wb_xy) } -/// [`camera_transform`] from the colour tags alone. pub fn camera_transform_of(color: &ColorData, wb_xy: Xy) -> CameraTransform { - let fallback = !has_matrix(color); - let wb = wb_multipliers(color, wb_xy); - let to_d50 = camera_to_xyz_d50(color, wb_xy); - let m = REC2020.from_xyz().mul(&bradford(D50, D65)).mul(&to_d50).mul(&Mat3::diag(1.0 / wb[0], 1.0 / wb[1], 1.0 / wb[2])); - let white = m.apply([1.0; 3]); - let k = (white[0] + white[1] + white[2]) / 3.0; - let matrix = if k.abs() > 1e-12 { Mat3(m.0.map(|r| r.map(|v| v / k))) } else { m }; - CameraTransform { matrix, wb: wb.map(|v| v as f32), white_xy: wb_xy, matrix_is_fallback: fallback, baseline_exposure: color.baseline_exposure } + craft_develop::sensor::color::camera_transform_of(&crate::bridge::to_craft_color_data(color), crate::bridge::to_craft_xy(wb_xy)).into() } -/// Linear Rec.2020 → linear Rec.2020 matrix that re-develops pixels developed with the camera -/// transform for white `from` as if developed for white `to`: the camera's own colour model is -/// evaluated at the new white (camera-space white balance, DNG spec ch. 6), as Lightroom does, so -/// a neutral lit by `to` comes out neutral. `None` when the tags have no colour matrix or the -/// transform is singular. pub fn rebalance(color: &ColorData, from: Xy, to: Xy) -> Option { - if !has_matrix(color) { - return None; - } - let (a, b) = (camera_transform_of(color, from), camera_transform_of(color, to)); - let ratio = Mat3::diag(f64::from(b.wb[0] / a.wb[0]), f64::from(b.wb[1] / a.wb[1]), f64::from(b.wb[2] / a.wb[2])); - Some(b.matrix.mul(&ratio).mul(&a.matrix.inverse()?)) + craft_develop::sensor::color::rebalance( + &crate::bridge::to_craft_color_data(color), + crate::bridge::to_craft_xy(from), + crate::bridge::to_craft_xy(to), + ) + .map(crate::bridge::from_craft_mat3) } -/// The white under which `rgb` (linear Rec.2020, developed with the camera transform for white -/// `developed_for`) is a neutral: the white [`rebalance`] must re-develop for to make it neutral -/// (white-balance picker, auto white balance). `None` without a colour matrix, or when `rgb` maps -/// to a non-positive camera value. pub fn neutral_white(color: &ColorData, developed_for: Xy, rgb: [f64; 3]) -> Option { - if !has_matrix(color) { - return None; - } - let a = camera_transform_of(color, developed_for); - let balanced = a.matrix.inverse()?.apply(rgb); - let camera: [f64; 3] = std::array::from_fn(|i| balanced[i] / f64::from(a.wb[i])); - camera.iter().all(|v| v.is_finite() && *v > 0.0).then(|| neutral_to_xy(color, camera)) + craft_develop::sensor::color::neutral_white(&crate::bridge::to_craft_color_data(color), crate::bridge::to_craft_xy(developed_for), rgb) + .map(crate::bridge::from_craft_xy) } -/// `(matrix, multipliers)` with `rec2020 = matrix · (multipliers ⊙ camera)`, linear Rec.2020 D65. pub fn camera_to_rec2020(raw: &RawImage, wb_xy: Xy) -> (Mat3, [f32; 3]) { - let t = camera_transform(raw, wb_xy); - (t.matrix, t.wb) + let (m, wb) = craft_develop::sensor::color::camera_to_rec2020(&crate::bridge::to_craft_raw_header(raw), crate::bridge::to_craft_xy(wb_xy)); + (crate::bridge::from_craft_mat3(m), wb) } -/// Grey-world white balance estimate (multipliers, min 1) from camera RGB, ignoring clipped and very dark pixels. pub fn grey_world(img: &lightcraft_raster::Rgb32f) -> [f32; 3] { - let mut s = [0f64; 3]; - let step = (img.data.len() / 200_000).max(1); - for p in img.data.iter().step_by(step) { - if p.iter().all(|&v| v > 0.02 && v < 0.95) { - for c in 0..3 { - s[c] += p[c] as f64; - } - } - } - if s.iter().any(|&v| v <= 0.0) { - return [1.0; 3]; - } - let m = [s[1] / s[0], 1.0, s[1] / s[2]]; - let mn = m.iter().cloned().fold(f64::MAX, f64::min); - m.map(|v| (v / mn) as f32) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A plausible camera: XYZ → camera matrix (rows sum to something sensible), invertible. - fn cam_a() -> Mat3 { - Mat3([[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]]) - } - fn cam_b() -> Mat3 { - Mat3([[0.7, 0.3, -0.1], [-0.35, 1.3, 0.1], [0.05, -0.2, 1.0]]) - } - - fn color_single(m: Mat3, ill: u16) -> ColorData { - ColorData { illuminant: [ill, 0], color_matrix: [Some(m), None], ..Default::default() } - } - - fn raw_with(color: ColorData) -> RawImage { - RawImage { - format: crate::RawFormat::Dng, - width: 1, - height: 1, - cpp: 1, - data: crate::RawData::U16(vec![0]), - cfa: None, - bits: 16, - black: Default::default(), - white: vec![65535.0], - active_area: crate::Rect::new(0, 0, 1, 1), - crop: crate::Rect::new(0, 0, 1, 1), - orientation: Default::default(), - color, - wb_multipliers: None, - linearized: false, - pixel_aspect: 1.0, - opcodes: Default::default(), - metadata: Default::default(), - lens_metadata: Default::default(), - } - } - - fn close(a: [f64; 3], b: [f64; 3], tol: f64) -> bool { - (0..3).all(|i| (a[i] - b[i]).abs() < tol) - } - - #[test] - fn neutral_maps_to_white_and_primaries_are_recovered() { - let raw = raw_with(color_single(cam_a(), 21)); - let t = camera_transform(&raw, D65); - assert!(!t.matrix_is_fallback); - // a surface with XYZ = Rec.2020 red primary under D65, seen by the camera - let red_xyz = REC2020.to_xyz().apply([1.0, 0.0, 0.0]); - let cam = cam_a().apply(red_xyz); - let wbd = [cam[0] * t.wb[0] as f64, cam[1] * t.wb[1] as f64, cam[2] * t.wb[2] as f64]; - let out = t.matrix.apply(wbd); - let k = out[0]; - assert!(close([out[0] / k, out[1] / k, out[2] / k], [1.0, 0.0, 0.0], 1e-6), "{out:?}"); - // white - let n = cam_a().apply(D65.to_xyz()); - let wbd = [n[0] * t.wb[0] as f64, n[1] * t.wb[1] as f64, n[2] * t.wb[2] as f64]; - let out = t.matrix.apply(wbd); - assert!((out[0] - out[1]).abs() < 1e-6 && (out[1] - out[2]).abs() < 1e-6, "{out:?}"); - assert!(close(t.matrix.apply([1.0; 3]), [1.0; 3], 1e-12)); - assert!(t.wb.iter().cloned().fold(f32::MAX, f32::min) == 1.0); - } - - #[test] - fn dual_illuminant_interpolation() { - let color = ColorData { illuminant: [17, 21], color_matrix: [Some(cam_a()), Some(cam_b())], ..Default::default() }; - assert!((illuminant_weight(&color, cct::temp_tint_to_xy(2856.0, 0.0)) - 1.0).abs() < 0.01); - assert!(illuminant_weight(&color, cct::temp_tint_to_xy(6504.0, 0.0)) < 0.01); - assert_eq!(illuminant_weight(&color, cct::temp_tint_to_xy(10000.0, 0.0)), 0.0); - let mid = cct::temp_tint_to_xy(4000.0, 0.0); - let g = illuminant_weight(&color, mid); - let expect = (1.0 / 4000.0 - 1.0 / 6504.0) / (1.0 / 2856.0 - 1.0 / 6504.0); - assert!((g - expect).abs() < 0.02, "{g} vs {expect}"); - let m = xyz_to_camera(&color, mid); - let l = lerp(&cam_a(), &cam_b(), g); - assert!(close(m.0[0], l.0[0], 1e-12)); - } - - #[test] - fn neutral_xy_roundtrip() { - let color = ColorData { - illuminant: [17, 21], - color_matrix: [Some(cam_a()), Some(cam_b())], - analog_balance: Some([1.0, 1.05, 0.98]), - ..Default::default() - }; - for t in [2600.0, 3200.0, 4500.0, 5500.0, 7000.0, 9000.0] { - for tint in [-10.0, 0.0, 15.0] { - let xy = cct::temp_tint_to_xy(t, tint); - let n = camera_neutral(&color, xy); - let back = neutral_to_xy(&color, n); - assert!((back.x - xy.x).abs() < 1e-6 && (back.y - xy.y).abs() < 1e-6, "{t} {tint}: {back:?} vs {xy:?}"); - } - } - let mut raw = raw_with(color.clone()); - raw.color.as_shot_neutral = Some(camera_neutral(&color, cct::temp_tint_to_xy(3300.0, 5.0))); - let xy = as_shot_white_xy(&raw); - let (t, tint) = cct::xy_to_temp_tint(xy); - assert!((t - 3300.0).abs() < 5.0 && (tint - 5.0).abs() < 0.5, "{t} {tint}"); - raw.color.as_shot_white_xy = Some(D50); - assert_eq!(as_shot_white_xy(&raw), D50); - } - - #[test] - fn forward_matrix_path_agrees_with_color_matrix_path() { - let a = cam_a(); - let n = a.apply(D65.to_xyz()); - let fm = bradford(D65, D50).mul(&a.inverse().unwrap()).mul(&Mat3::diag(n[0], n[1], n[2])); - // DNG forward matrices map (1,1,1) to D50 white (with Y=1): normalise like a real file would - let w = fm.apply([1.0; 3]); - let s = D50.to_xyz()[1] / w[1]; - let fm = Mat3(fm.0.map(|r| r.map(|v| v * s))); - let cm_only = camera_transform(&raw_with(color_single(a, 21)), D65); - let mut with_fm = color_single(a, 21); - with_fm.forward_matrix = [Some(fm), None]; - let fm_t = camera_transform(&raw_with(with_fm), D65); - for i in 0..3 { - assert!(close(cm_only.matrix.0[i], fm_t.matrix.0[i], 1e-9), "{:?} vs {:?}", cm_only.matrix, fm_t.matrix); - } - assert_eq!(cm_only.wb, fm_t.wb); - } - - #[test] - fn camera_calibration_and_analog_balance_are_respected() { - // AB · CC scales channels: the neutral must scale accordingly - let mut c = color_single(cam_a(), 21); - let base = camera_neutral(&c, D65); - c.camera_calibration = [Some(Mat3::diag(1.0, 0.5, 1.0)), None]; - let n = camera_neutral(&c, D65); - assert!((n[1] / n[0] - 0.5 * base[1] / base[0]).abs() < 1e-9); - } - - #[test] - fn fallback_without_matrix() { - let mut raw = raw_with(ColorData::default()); - raw.wb_multipliers = Some([2.0, 1.0, 1.5]); - let xy = as_shot_white_xy(&raw); - let t = camera_transform(&raw, xy); - assert!(t.matrix_is_fallback); - assert!((t.wb[0] / t.wb[1] - 2.0).abs() < 1e-3 && (t.wb[2] / t.wb[1] - 1.5).abs() < 1e-3, "{:?}", t.wb); - let t = camera_transform(&raw, D65); - let expect = SRGB.to_space(&REC2020); - for i in 0..3 { - assert!(close(t.matrix.0[i], expect.0[i], 1e-6)); - } - assert_eq!(camera_to_rec2020(&raw, D65).1, [1.0, 1.0, 1.0]); - } - - #[test] - fn illuminant_codes() { - assert_eq!(illuminant_temperature(21), Some(6504.0)); - assert_eq!(illuminant_temperature(17), Some(2856.0)); - assert_eq!(illuminant_temperature(0), None); - assert_eq!(illuminant_temperature(255), None); - } - - /// Camera-space white balance: re-developing for another white turns a neutral lit by that - /// white neutral (the camera's own matrices, interpolated for the new white, say how); the same - /// white is the identity; without a colour matrix there is nothing to re-evaluate. - #[test] - fn rebalance_redevelops_for_the_new_white() { - let color = ColorData { illuminant: [17, 21], color_matrix: [Some(cam_a()), Some(cam_b())], ..Default::default() }; - let (from, to) = (cct::temp_tint_to_xy(5500.0, 0.0), cct::temp_tint_to_xy(3200.0, 10.0)); - let a = camera_transform_of(&color, from); - // a grey card lit by `to`, as the camera records it, developed for `from`: warm - let n = camera_neutral(&color, to); - let developed = a.matrix.apply(std::array::from_fn(|i| n[i] * a.wb[i] as f64)); - assert!(developed[0] > 1.2 * developed[2], "{developed:?}"); - let out = rebalance(&color, from, to).unwrap().apply(developed); - assert!(close(out.map(|v| v / out[1]), [1.0; 3], 1e-6), "{out:?}"); - let same = rebalance(&color, from, from).unwrap(); - assert!((0..3).all(|r| close(same.0[r], Mat3::IDENTITY.0[r], 1e-9)), "{same:?}"); - assert!(rebalance(&ColorData::default(), from, to).is_none()); - // and back: the developed grey card names the white it was lit by - let white = neutral_white(&color, from, developed).unwrap(); - assert!((white.x - to.x).abs() < 1e-6 && (white.y - to.y).abs() < 1e-6, "{white:?} vs {to:?}"); - assert!(neutral_white(&color, from, [-1.0, 0.5, 0.5]).is_none()); - assert!(neutral_white(&ColorData::default(), from, developed).is_none()); - } - - #[test] - fn grey_world_balances() { - let img = lightcraft_raster::Rgb32f::from_fn(20, 20, |x, _| { - let v = 0.2 + 0.02 * x as f32; - [v * 0.5, v, v * 0.8] - }); - let m = grey_world(&img); - assert!((m[0] - 2.0).abs() < 1e-3 && (m[1] - 1.0).abs() < 1e-6 && (m[2] - 1.25).abs() < 1e-3, "{m:?}"); - } + craft_develop::sensor::color::grey_world(&crate::bridge::to_craft_rgb32f(img)) } diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs index 245586f39a..80d804fdd3 100644 --- a/crates/raw/src/demosaic.rs +++ b/crates/raw/src/demosaic.rs @@ -1,400 +1,17 @@ -//! Demosaicing: CFA mosaic → camera RGB ([`Rgb32f`]), values as normalised (white = 1.0). -//! -//! Methods (all from published descriptions, see the README): -//! - [`Method::Bilinear`] — average of same-colour neighbours (drafts / thumbnails); works for any pattern. -//! - [`Method::Ppg`] — Patterned Pixel Grouping (Chuan-kai Lin): gradient-selected green, colour-difference R/B. -//! - [`Method::Ahd`] — Adaptive Homogeneity-Directed (Hirakawa & Parks, IEEE TIP 2005): horizontal/vertical -//! candidates chosen per pixel by CIELab homogeneity. The quality default for Bayer sensors. -//! - Non-Bayer patterns (X-Trans, …) always use `xtrans::directional`, our own edge-weighted colour-difference -//! interpolation. -//! -//! Every method reproduces a constant-colour mosaic exactly. +//! Demosaicing: CFA mosaic → camera RGB, backed by `craft_develop::sensor::demosaic`. -mod ahd; -mod bilinear; -mod ppg; -mod xtrans; +use crate::{Cfa, Normalized, Rgb32f}; -use crate::{Cfa, Normalized, Rect, Rgb32f}; -use serde::{Deserialize, Serialize}; +pub use craft_develop::sensor::demosaic::Method; -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum Method { - Bilinear, - Ppg, - #[default] - Ahd, -} - -/// Mirror-reflected access to a single-plane mosaic (reflection keeps Bayer parity: −k → k, w−1+k → w−1−k). -#[derive(Clone, Copy)] -pub(crate) struct Mosaic<'a> { - pub w: usize, - pub h: usize, - pub data: &'a [f32], - pub cfa: &'a Cfa, -} - -#[inline] -pub(crate) fn reflect(i: isize, n: usize) -> usize { - if i >= 0 && (i as usize) < n { - return i as usize; - } - let n = n as isize; - if n == 1 { - return 0; - } - let period = 2 * (n - 1); - let mut i = i.rem_euclid(period); - if i >= n { - i = period - i; - } - i as usize -} - -/// `v` clamped between `a` and `b`: `v.clamp(a.min(b), a.max(b))`, except that it returns `v` as is when both -/// bounds are NaN (NaN samples in a float raw), where `f32::clamp` panics. -#[inline] -pub(crate) fn clamp_between(v: f32, a: f32, b: f32) -> f32 { - let (lo, hi) = (a.min(b), a.max(b)); - if lo <= hi { v.clamp(lo, hi) } else { v } -} - -impl Mosaic<'_> { - #[inline] - pub fn get(&self, x: isize, y: isize) -> f32 { - self.data[reflect(y, self.h) * self.w + reflect(x, self.w)] - } - #[inline] - pub fn color(&self, x: isize, y: isize) -> u8 { - self.cfa.color_at(reflect(x, self.w), reflect(y, self.h)) - } -} - -/// Demosaic normalised raw data. `cpp == 3` data is returned as is; monochrome data is replicated to grey. pub fn demosaic(n: &Normalized, method: Method) -> Rgb32f { - let (w, h) = (n.width, n.height); - if w == 0 || h == 0 { - return Rgb32f::new(w, h); - } - match (&n.cfa, n.cpp) { - (_, 3) => Rgb32f { width: w, height: h, data: n.data.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect() }, - // four colours develop from their first three; narrower data (refused by `RawImage::validate`, issue #1511) - // repeats its last sample instead of reading past the pixel - (_, cpp) if cpp != 1 => Rgb32f { - width: w, - height: h, - data: n - .data - .chunks_exact(cpp.max(1)) - .map(|c| { - let s = |i: usize| c.get(i).or(c.last()).copied().unwrap_or(0.0); - [s(0), s(1), s(2)] - }) - .collect(), - }, - (None, _) => Rgb32f { width: w, height: h, data: n.data.iter().map(|&v| [v; 3]).collect() }, - (Some(cfa), _) => { - let m = Mosaic { w, h, data: &n.data, cfa }; - if !cfa.is_bayer() { - return match method { - Method::Bilinear => bilinear::bilinear(&m), - _ => xtrans::directional(&m), - }; - } - if w < 4 || h < 4 { - return bilinear::bilinear(&m); - } - match method { - Method::Bilinear => bilinear::bilinear(&m), - Method::Ppg => ppg::ppg(&m), - Method::Ahd => ahd::ahd(&m), - } - } - } + crate::bridge::from_craft_rgb32f(craft_develop::sensor::demosaic::demosaic(n, method)) } -/// [`demosaic`] with [`Method::Ahd`] of the window `r` alone, for Bayer mosaics (`None` for any other data, or a -/// window not inside the mosaic): the same pixels as demosaicing it all and cropping that to `r`, without -/// demosaicing the rest or copying the window out of it. -pub(crate) fn ahd_window(n: &Normalized, r: Rect) -> Option { - let (w, h) = (n.width, n.height); - let cfa = n.cfa.as_ref()?; - let inside = r.x.checked_add(r.width).is_some_and(|e| e <= w) && r.y.checked_add(r.height).is_some_and(|e| e <= h); - if n.cpp != 1 || !cfa.is_bayer() || w < 4 || h < 4 || n.data.len() != w * h || r.width == 0 || r.height == 0 || !inside { - return None; - } - let m = Mosaic { w, h, data: &n.data, cfa }; - Some(ahd::ahd_window(&m, r.x, r.y, r.width, r.height)) -} - -/// Build a mosaic from an RGB image by sampling each pixel's CFA colour (for tests and synthetic data). pub fn mosaic_from_rgb(img: &Rgb32f, cfa: &Cfa) -> Normalized { - let data = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).map(|(x, y)| img.get(x, y)[cfa.color_at(x, y) as usize]).collect(); - Normalized { width: img.width, height: img.height, cpp: 1, data, cfa: Some(cfa.clone()) } + craft_develop::sensor::demosaic::mosaic_from_rgb(&crate::bridge::to_craft_rgb32f(img), cfa) } -/// Peak signal-to-noise ratio (dB, peak 1.0) between two images over an interior region (`border` pixels excluded). pub fn psnr(a: &Rgb32f, b: &Rgb32f, border: usize) -> f64 { - let mut se = 0.0f64; - let mut n = 0usize; - for y in border..a.height.saturating_sub(border) { - for x in border..a.width.saturating_sub(border) { - let (p, q) = (a.get(x, y), b.get(x, y)); - for c in 0..3 { - se += ((p[c] - q[c]) as f64).powi(2); - n += 1; - } - } - } - if n == 0 || se == 0.0 { - return f64::INFINITY; - } - 10.0 * (1.0 / (se / n as f64)).log10() -} - -#[cfg(test)] -mod tests { - use super::*; - - fn smooth_scene(w: usize, h: usize) -> Rgb32f { - Rgb32f::from_fn(w, h, |x, y| { - let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32); - [0.2 + 0.6 * fx * fy, 0.3 + 0.4 * (fx * 3.0).sin().abs() * 0.5 + 0.2 * fy, 0.1 + 0.5 * (1.0 - fx) * (0.5 + 0.5 * (fy * 5.0).cos())] - }) - } - - /// A photo-like scene: sharp luminance structure (disc, stripes, diagonal edge, fine texture) modulating a - /// smoothly varying colour — edges are mostly luminance edges, as in natural images. - fn edgy_scene(w: usize, h: usize) -> Rgb32f { - Rgb32f::from_fn(w, h, |x, y| { - let (fx, fy) = (x as f32, y as f32); - let d = ((fx - w as f32 * 0.35).powi(2) + (fy - h as f32 * 0.4).powi(2)).sqrt(); - let lum = if d < w as f32 * 0.18 { - 0.85 - } else if x > w * 2 / 3 && (y / 3) % 2 == 0 { - 0.15 - } else if fx + fy * 0.5 > w as f32 * 1.1 { - 0.7 - } else { - 0.35 + 0.1 * ((fx * 0.7).sin() * (fy * 0.9).cos()) - }; - let tint = [0.9 + 0.1 * (fx / w as f32), 0.8, 0.55 + 0.3 * (fy / h as f32)]; - [lum * tint[0], lum * tint[1], lum * tint[2]] - }) - } - - fn run(img: &Rgb32f, cfa: &Cfa, m: Method) -> Rgb32f { - demosaic(&mosaic_from_rgb(img, cfa), m) - } - - #[test] - fn constant_colour_is_exact_for_all_methods_and_phases() { - let img = Rgb32f::filled(17, 13, [0.3, 0.55, 0.8]); - for pat in ["RGGB", "BGGR", "GRBG", "GBRG"] { - let cfa = Cfa::bayer(pat).unwrap(); - for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { - let out = run(&img, &cfa, m); - for p in &out.data { - for c in 0..3 { - assert!((p[c] - img.data[0][c]).abs() < 1e-5, "{pat} {m:?} {p:?}"); - } - } - } - } - let out = run(&Rgb32f::filled(19, 14, [0.3, 0.55, 0.8]), &Cfa::xtrans(), Method::Ahd); - assert!(out.data.iter().all(|p| (p[0] - 0.3).abs() < 1e-5 && (p[1] - 0.55).abs() < 1e-5 && (p[2] - 0.8).abs() < 1e-5)); - } - - /// A window demosaiced alone is the same, bit for bit, as that part of the whole picture: at the edges and - /// corners (where the mosaic is reflected), in the middle, across tile seams, at every CFA phase. - #[test] - fn ahd_window_is_the_crop_of_the_whole() { - let img = edgy_scene(300, 270); - for pat in ["RGGB", "GBRG"] { - let n = mosaic_from_rgb(&img, &Cfa::bayer(pat).unwrap()); - let whole = demosaic(&n, Method::Ahd); - for r in - [Rect::new(0, 0, 300, 270), Rect::new(0, 0, 7, 5), Rect::new(1, 3, 298, 266), Rect::new(121, 130, 140, 9), Rect::new(293, 263, 7, 7)] - { - let part = ahd_window(&n, r).unwrap(); - let want = whole.clone().into_crop(r.x, r.y, r.width, r.height); - assert_eq!((part.width, part.height), (r.width, r.height)); - assert!(part.data.iter().zip(&want.data).all(|(a, b)| a.map(f32::to_bits) == b.map(f32::to_bits)), "{pat} {r:?}"); - } - assert!(ahd_window(&n, Rect::new(1, 0, 300, 270)).is_none(), "a window past the mosaic is refused"); - } - } - - #[test] - fn known_samples_are_preserved() { - let img = edgy_scene(40, 32); - let cfa = Cfa::bayer("GRBG").unwrap(); - for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { - let out = run(&img, &cfa, m); - for y in 0..32 { - for x in 0..40 { - let c = cfa.color_at(x, y) as usize; - assert!((out.get(x, y)[c] - img.get(x, y)[c]).abs() < 1e-6, "{m:?}"); - } - } - } - } - - #[test] - fn psnr_thresholds_and_ranking() { - let smooth = smooth_scene(96, 80); - let edgy = edgy_scene(96, 80); - let cfa = Cfa::bayer("RGGB").unwrap(); - let p = |img: &Rgb32f, m| psnr(img, &run(img, &cfa, m), 4); - let (sb, sp, sa) = (p(&smooth, Method::Bilinear), p(&smooth, Method::Ppg), p(&smooth, Method::Ahd)); - assert!(sb > 38.0 && sp > 38.0 && sa > 38.0, "smooth: bilinear {sb:.1} ppg {sp:.1} ahd {sa:.1}"); - let (eb, ep, ea) = (p(&edgy, Method::Bilinear), p(&edgy, Method::Ppg), p(&edgy, Method::Ahd)); - eprintln!("smooth: bilinear {sb:.1} ppg {sp:.1} ahd {sa:.1}; edgy: bilinear {eb:.1} ppg {ep:.1} ahd {ea:.1}"); - assert!(eb > 20.0, "edgy bilinear {eb:.1}"); - assert!(ep > eb + 6.0, "ppg {ep:.1} vs bilinear {eb:.1}"); - assert!(ea > eb + 6.0, "ahd {ea:.1} vs bilinear {eb:.1}"); - let xt = Cfa::xtrans(); - let xp = psnr(&edgy, &run(&edgy, &xt, Method::Ahd), 6); - let xb = psnr(&edgy, &run(&edgy, &xt, Method::Bilinear), 6); - assert!(xp > 20.0 && xp >= xb - 0.5, "xtrans directional {xp:.1} bilinear {xb:.1}"); - } - - /// Mean anisotropy of a demosaiced picture's fine luminance detail: per pixel, how much more its 3 × 3 high-pass - /// correlates with its horizontal neighbours than with its vertical ones (or the reverse). Noise has none; the - /// short horizontal and vertical strokes of a maze pattern have a lot. - fn anisotropy(img: &Rgb32f) -> f64 { - let (w, h) = (img.width, img.height); - let lum: Vec = img.data.iter().map(|p| 0.25 * p[0] + 0.5 * p[1] + 0.25 * p[2]).collect(); - let mean3 = |x: usize, y: usize| (0..9).map(|k| lum[(y + k / 3 - 1) * w + x + k % 3 - 1]).sum::() / 9.0; - let hp: Vec = - (0..w * h).map(|i| if i % w == 0 || i % w == w - 1 || i < w || i >= w * (h - 1) { 0.0 } else { lum[i] - mean3(i % w, i / w) }).collect(); - let (mut sum, mut n) = (0f64, 0f64); - for y in 2..h - 2 { - for x in 2..w - 2 { - let i = y * w + x; - sum += f64::from((hp[i] * (hp[i - 1] + hp[i + 1] - hp[i - w] - hp[i + w])).abs()); - n += 1.0; - } - } - sum / n - } - - #[test] - fn flat_noise_does_not_turn_into_a_maze() { - // a flat grey patch with sensor-like noise: AHD picked horizontal or vertical candidates per pixel by a - // homogeneity count that noise alone decides, so the picture became short horizontal and vertical strokes - let (w, h) = (192, 160); - let mut seed = 0x2545_f491_4f6c_dd1du64; - let mut noise = || { - // sum of four uniforms ≈ Gaussian, σ ≈ 0.02 - (0..4) - .map(|_| { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed >> 40) as f32 / (1u64 << 24) as f32 - 0.5 - }) - .sum::() - * 0.035 - }; - let cfa = Cfa::bayer("RGGB").unwrap(); - let data = (0..w * h).map(|_| 0.2 + noise()).collect(); - let n = Normalized { width: w, height: h, cpp: 1, data, cfa: Some(cfa) }; - let (ahd, bilinear) = (anisotropy(&demosaic(&n, Method::Ahd)), anisotropy(&demosaic(&n, Method::Bilinear))); - eprintln!("anisotropy: ahd {ahd:.3e}, bilinear {bilinear:.3e}"); - // the hard choice gave about 11 times bilinear's, the blend about 7.5 times - assert!(ahd < 9.0 * bilinear, "ahd {ahd:.3e} bilinear {bilinear:.3e}"); - } - - #[test] - fn tiny_and_degenerate_inputs() { - let cfa = Cfa::bayer("RGGB").unwrap(); - for (w, h) in [(1, 1), (2, 2), (3, 5), (5, 3), (1, 7)] { - let img = Rgb32f::filled(w, h, [0.5; 3]); - for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { - let out = run(&img, &cfa, m); - assert_eq!((out.width, out.height), (w, h)); - assert!(out.data.iter().all(|p| p.iter().all(|v| v.is_finite()))); - } - } - let n = Normalized { width: 2, height: 1, cpp: 1, data: vec![0.2, 0.4], cfa: None }; - assert_eq!(demosaic(&n, Method::Ahd).data, vec![[0.2; 3], [0.4; 3]]); - let n = Normalized { width: 1, height: 1, cpp: 3, data: vec![0.1, 0.2, 0.3], cfa: None }; - assert_eq!(demosaic(&n, Method::Ahd).data, vec![[0.1, 0.2, 0.3]]); - } - - #[test] - fn a_nan_sample_spreads_no_further_than_the_chosen_candidate_takes_it() { - // vertical stripes: the vertical candidate wins outright beside them, and the horizontal one, which reads two - // samples to each side, is the only one that sees a NaN two columns away - let img = Rgb32f::from_fn(32, 24, |x, _| if (x / 2) % 2 == 0 { [0.2, 0.3, 0.25] } else { [0.7, 0.8, 0.6] }); - let cfa = Cfa::bayer("RGGB").unwrap(); - let mut n = mosaic_from_rgb(&img, &cfa); - n.data[12 * 32 + 16] = f32::NAN; - let out = demosaic(&n, Method::Ahd); - let bad = out.data.iter().filter(|p| p.iter().any(|v| !v.is_finite())).count(); - // the pixels that read the NaN sample themselves, as many as the outright pick gave; the blend made it 33 - assert!(bad <= 9, "{bad} pixels not finite"); - } - - #[test] - fn non_finite_samples_do_not_panic() { - // regression: NaN samples (a float DNG) gave AHD and PPG NaN bounds for `f32::clamp`, which panics - let cfa = Cfa::bayer("RGGB").unwrap(); - let mut patchy = mosaic_from_rgb(&edgy_scene(24, 20), &cfa); - for (i, v) in patchy.data.iter_mut().enumerate() { - let (x, y) = (i % 24, i / 24); - if (8..12).contains(&x) && (6..10).contains(&y) { - *v = f32::NAN; - } else if i % 7 == 0 { - *v = if i % 2 == 0 { f32::INFINITY } else { f32::NEG_INFINITY }; - } - } - let all_nan = Normalized { width: 9, height: 7, cpp: 1, data: vec![f32::NAN; 63], cfa: Some(cfa) }; - for n in [&patchy, &all_nan] { - for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { - let out = demosaic(n, m); - assert_eq!((out.width, out.height), (n.width, n.height), "{m:?}"); - } - } - // without NaN bounds it is the `f32::clamp` it replaced, bit for bit (finite results stay identical) - let vals = [f32::NEG_INFINITY, -3e38, -2.5, -0.0, 0.0, 1e-40, 0.5, 1.0, 3e38, f32::INFINITY]; - for v in vals { - for a in vals { - for b in vals { - assert_eq!(clamp_between(v, a, b).to_bits(), v.clamp(a.min(b), a.max(b)).to_bits(), "{v} {a} {b}"); - } - } - } - } - - #[test] - fn reflect_indices() { - assert_eq!(reflect(-1, 5), 1); - assert_eq!(reflect(-2, 5), 2); - assert_eq!(reflect(5, 5), 3); - assert_eq!(reflect(6, 5), 2); - assert_eq!(reflect(3, 1), 0); - assert_eq!(reflect(-7, 2), 1); - } - - #[test] - #[ignore] - fn throughput() { - let (w, h) = (6000, 4000); - let img = smooth_scene(w, h); - let cfa = Cfa::bayer("RGGB").unwrap(); - let n = mosaic_from_rgb(&img, &cfa); - for m in [Method::Bilinear, Method::Ppg, Method::Ahd] { - let t = std::time::Instant::now(); - let _ = demosaic(&n, m); - let s = t.elapsed().as_secs_f64(); - println!("{m:?}: {:.1} MP/s ({:.0} ms for 24 MP)", (w * h) as f64 / 1e6 / s, s * 1e3); - } - let n = mosaic_from_rgb(&img, &Cfa::xtrans()); - let t = std::time::Instant::now(); - let _ = demosaic(&n, Method::Ahd); - println!("X-Trans directional: {:.1} MP/s", (w * h) as f64 / 1e6 / t.elapsed().as_secs_f64()); - } + craft_develop::sensor::demosaic::psnr(&crate::bridge::to_craft_rgb32f(a), &crate::bridge::to_craft_rgb32f(b), border) } diff --git a/crates/raw/src/demosaic/ahd.rs b/crates/raw/src/demosaic/ahd.rs deleted file mode 100644 index 9a1d477e8f..0000000000 --- a/crates/raw/src/demosaic/ahd.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! Adaptive Homogeneity-Directed demosaicing (K. Hirakawa, T. W. Parks, "Adaptive homogeneity-directed -//! demosaicing algorithm", IEEE Trans. Image Processing 14(3), 2005), implemented from the paper: -//! -//! 1. Interpolate green horizontally and vertically (5-tap filter [−¼ ½ ½ ½ −¼] across the missing site, -//! clamped to the two adjacent greens), giving two candidate green planes. -//! 2. Complete each candidate with red/blue by colour-difference (C − G) interpolation. -//! 3. Convert both candidates to CIELab and measure, per pixel, how many of its 4 neighbours lie within the -//! adaptive luminance / chrominance tolerances (ε_L, ε_C from the paper) — the homogeneity. -//! 4. Sum homogeneity over a 3×3 window and pick the more homogeneous candidate. The paper picks one outright; -//! we blend the two by how far apart their sums are (see [`BLEND`]), so a clear edge still takes one candidate. -//! -//! Work is done in overlapping tiles (bounded memory, rayon-parallel), one band of tiles at a time written -//! straight into the output. Each step runs only where the tile's output depends on it: the choice reads the -//! homogeneity 1 pixel around the tile, which reads Lab 2 pixels around, the candidates read the greens 3 -//! pixels around, and those read the mosaic 5 pixels around, inside the `MARGIN`. - -use super::Mosaic; -use crate::Rgb32f; -use rayon::prelude::*; - -const TILE: usize = 128; -const MARGIN: usize = 6; -/// Difference of the two candidates' 3×3 homogeneity sums (each 0–36) from which the more homogeneous one is taken -/// alone; closer sums blend the two linearly, equal sums half and half. In a flat, noisy area noise alone decides -/// which sum is larger, and picking outright turned the noise into short horizontal and vertical strokes (a maze, -/// coloured where white balance is strong). 12 keeps the PSNR of the outright pick on the edge tests. -const BLEND: f32 = 12.0; - -pub(crate) fn ahd(m: &Mosaic) -> Rgb32f { - ahd_window(m, 0, 0, m.w, m.h) -} - -/// The `w × h` pixels at (`x`, `y`) of [`ahd`]'s picture (inside the mosaic), demosaiced alone: every pixel comes -/// from the mosaic around it, so they are the same as when the whole picture is demosaiced and then cropped. -pub(crate) fn ahd_window(m: &Mosaic, x: usize, y: usize, w: usize, h: usize) -> Rgb32f { - let mut out = Rgb32f::new(w, h); - if w == 0 || h == 0 { - return out; - } - // one row of tiles per task, its tiles in parallel too, written straight into the picture - out.data.par_chunks_mut((w * TILE).max(1)).enumerate().for_each(|(ty, band)| { - let (y0, th) = (y + ty * TILE, band.len() / w.max(1)); - let tiles: Vec<(usize, usize, Vec<[f32; 3]>)> = (0..w.div_ceil(TILE)) - .into_par_iter() - .map(|tx| { - let (x0, tw) = (tx * TILE, TILE.min(w - tx * TILE)); - (x0, tw, tile(m, x + x0, y0, tw, th)) - }) - .collect(); - for (x0, tw, px) in tiles { - for (row, src) in band.chunks_exact_mut(w).zip(px.chunks_exact(tw)) { - row[x0..x0 + tw].copy_from_slice(src); - } - } - }); - out -} - -/// Linear camera RGB (treated as sRGB/D65 primaries for the homogeneity metric only) → CIELab. -#[inline] -fn lab(p: [f32; 3]) -> [f32; 3] { - let x = (0.4124 * p[0] + 0.3576 * p[1] + 0.1805 * p[2]) / 0.95047; - let y = 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; - let z = (0.0193 * p[0] + 0.1192 * p[1] + 0.9505 * p[2]) / 1.08883; - #[inline] - fn f(t: f32) -> f32 { - if t > 0.008856 { t.cbrt() } else { 7.787 * t + 16.0 / 116.0 } - } - let (fx, fy, fz) = (f(x), f(y), f(z)); - [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)] -} - -fn tile(m: &Mosaic, x0: usize, y0: usize, tw: usize, th: usize) -> Vec<[f32; 3]> { - let (bw, bh) = (tw + 2 * MARGIN, th + 2 * MARGIN); - let n = bw * bh; - let (ox, oy) = (x0 as isize - MARGIN as isize, y0 as isize - MARGIN as isize); - let mut mos = vec![0f32; n]; - let mut col = vec![0u8; n]; - for (y, (mrow, crow)) in mos.chunks_exact_mut(bw).zip(col.chunks_exact_mut(bw)).enumerate() { - let ry = super::reflect(oy + y as isize, m.h); - if ox >= 0 && ox as usize + bw <= m.w { - // inside the image: the row as it is, and its colours repeating with the pattern - let x0 = ry * m.w + ox as usize; - mrow.copy_from_slice(&m.data[x0..x0 + bw]); - let period: Vec = (0..m.cfa.width).map(|k| m.cfa.color_at(ox as usize + k, ry)).collect(); - for (c, &p) in crow.iter_mut().zip(period.iter().cycle()) { - *c = p; - } - } else { - for x in 0..bw { - mrow[x] = m.get(ox + x as isize, oy + y as isize); - crow[x] = m.color(ox + x as isize, oy + y as isize); - } - } - } - // flat indices of the pixels `d` or more from the buffer's edge, row by row - let inner = |d: usize| (d..bh - d).flat_map(move |y| y * bw + d..y * bw + bw - d); - // 1. directional greens - let mut gh = vec![0f32; n]; - let mut gv = vec![0f32; n]; - for i in inner(MARGIN - 3) { - let c = mos[i]; - if col[i] == 1 { - gh[i] = c; - gv[i] = c; - continue; - } - let (l, r) = (mos[i - 1], mos[i + 1]); - let est = (l + r) * 0.5 + (2.0 * c - mos[i - 2] - mos[i + 2]) * 0.25; - gh[i] = super::clamp_between(est, l, r); - let (u, d) = (mos[i - bw], mos[i + bw]); - let est = (u + d) * 0.5 + (2.0 * c - mos[i - 2 * bw] - mos[i + 2 * bw]) * 0.25; - gv[i] = super::clamp_between(est, u, d); - } - // 2. full candidates, and 3. their Lab - // (`p` with channel `c` set to `v`, in registers: writing channels through an index and reading the pixel - // back for its Lab stalled on store forwarding) - let set = |p: [f32; 3], c: u8, v: f32| [if c == 0 { v } else { p[0] }, if c == 1 { v } else { p[1] }, if c >= 2 { v } else { p[2] }]; - let complete = |g: &[f32]| -> (Vec<[f32; 3]>, Vec<[f32; 3]>) { - let mut rgb = vec![[0f32; 3]; n]; - let mut lab_of = vec![[0f32; 3]; n]; - for i in inner(MARGIN - 2) { - let own = col[i]; - let gvv = g[i]; - let d = |j: usize| mos[j] - g[j]; - let p = if own == 1 { - let p = set([0.0, gvv, 0.0], col[i + 1], gvv + (d(i - 1) + d(i + 1)) * 0.5); - set(p, col[i + bw], gvv + (d(i - bw) + d(i + bw)) * 0.5) - } else { - let p = set([0.0, gvv, 0.0], own, mos[i]); - set(p, 2 - own, gvv + (d(i - bw - 1) + d(i - bw + 1) + d(i + bw - 1) + d(i + bw + 1)) * 0.25) - }; - rgb[i] = p; - lab_of[i] = lab(p); - } - (rgb, lab_of) - }; - let (rh, lh) = complete(&gh); - let (rv, lv) = complete(&gv); - // homogeneity - let dl = |a: &[f32; 3], b: &[f32; 3]| (a[0] - b[0]).abs(); - let dc = |a: &[f32; 3], b: &[f32; 3]| (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2); - let mut hh = vec![0u8; n]; - let mut hv = vec![0u8; n]; - for i in inner(MARGIN - 1) { - // left, right, up, down - let (l, r, u, d) = (i - 1, i + 1, i - bw, i + bw); - let (a, b) = (lh[i], lv[i]); - let dlh = [dl(&a, &lh[l]), dl(&a, &lh[r]), dl(&a, &lh[u]), dl(&a, &lh[d])]; - let dch = [dc(&a, &lh[l]), dc(&a, &lh[r]), dc(&a, &lh[u]), dc(&a, &lh[d])]; - let dlv = [dl(&b, &lv[l]), dl(&b, &lv[r]), dl(&b, &lv[u]), dl(&b, &lv[d])]; - let dcv = [dc(&b, &lv[l]), dc(&b, &lv[r]), dc(&b, &lv[u]), dc(&b, &lv[d])]; - let eps_l = dlh[0].max(dlh[1]).min(dlv[2].max(dlv[3])); - let eps_c = dch[0].max(dch[1]).min(dcv[2].max(dcv[3])); - hh[i] = (0..4).map(|k| u8::from(dlh[k] <= eps_l && dch[k] <= eps_c)).sum(); - hv[i] = (0..4).map(|k| u8::from(dlv[k] <= eps_l && dcv[k] <= eps_c)).sum(); - } - // 4. choose - let mut out = Vec::with_capacity(tw * th); - for i in inner(MARGIN) { - let (mut sh, mut sv) = (0u32, 0u32); - for j in [i - bw - 1, i - bw, i - bw + 1, i - 1, i, i + 1, i + bw - 1, i + bw, i + bw + 1] { - sh += hh[j] as u32; - sv += hv[j] as u32; - } - let wh = (0.5 + (sh as f32 - sv as f32) / (2.0 * BLEND)).clamp(0.0, 1.0); - // a candidate taken alone is copied, and one that isn't finite (beside a float raw's NaN sample) is left out, - // so the other's value doesn't become 0 · NaN - let finite = |p: &[f32; 3]| p.iter().all(|v| v.is_finite()); - out.push(if wh >= 1.0 || !finite(&rv[i]) { - rh[i] - } else if wh <= 0.0 || !finite(&rh[i]) { - rv[i] - } else { - [0, 1, 2].map(|c| rh[i][c] * wh + rv[i][c] * (1.0 - wh)) - }); - } - out -} diff --git a/crates/raw/src/demosaic/bilinear.rs b/crates/raw/src/demosaic/bilinear.rs deleted file mode 100644 index cc61450774..0000000000 --- a/crates/raw/src/demosaic/bilinear.rs +++ /dev/null @@ -1,78 +0,0 @@ -//! Bilinear demosaicing for any CFA pattern: each missing colour is the mean of the same-colour samples in the -//! 3×3 neighbourhood (5×5 when the 3×3 has none, as happens in some non-Bayer layouts). - -use super::Mosaic; -use crate::Rgb32f; -use lightcraft_raster::par_rows; - -/// Offsets (dx, dy) of same-colour neighbours for each pattern position and colour. -pub(crate) fn neighbour_table(m: &Mosaic) -> Vec<[Vec<(isize, isize)>; 3]> { - let cfa = m.cfa; - let mut table = Vec::with_capacity(cfa.width * cfa.height); - for py in 0..cfa.height { - for px in 0..cfa.width { - let mut per: [Vec<(isize, isize)>; 3] = Default::default(); - for (c, list) in per.iter_mut().enumerate() { - for r in [1isize, 2] { - for dy in -r..=r { - for dx in -r..=r { - let (x, y) = (px as isize + dx + 6 * cfa.width as isize, py as isize + dy + 6 * cfa.height as isize); - if cfa.color_at(x as usize, y as usize) as usize == c { - list.push((dx, dy)); - } - } - } - if !list.is_empty() { - break; - } - } - } - table.push(per); - } - } - table -} - -pub(crate) fn bilinear(m: &Mosaic) -> Rgb32f { - let (w, h) = (m.w, m.h); - let table = neighbour_table(m); - let cfa = m.cfa; - let mut out = Rgb32f::new(w, h); - par_rows(&mut out.data, w, |y, row| { - for (x, px) in row.iter_mut().enumerate() { - let own = cfa.color_at(x, y) as usize; - let interior = x >= 2 && y >= 2 && x + 2 < w && y + 2 < h; - let entry = &table[(y % cfa.height) * cfa.width + (x % cfa.width)]; - for c in 0..3 { - if c == own { - px[c] = m.data[y * w + x]; - continue; - } - let (mut s, mut n) = (0.0f32, 0u32); - if interior { - for &(dx, dy) in &entry[c] { - s += m.data[(y as isize + dy) as usize * w + (x as isize + dx) as usize]; - n += 1; - } - } else { - for r in [1isize, 2] { - for dy in -r..=r { - for dx in -r..=r { - let (nx, ny) = (x as isize + dx, y as isize + dy); - if m.color(nx, ny) as usize == c { - s += m.get(nx, ny); - n += 1; - } - } - } - if n > 0 { - break; - } - } - } - px[c] = if n > 0 { s / n as f32 } else { m.data[y * w + x] }; - } - } - }); - out -} diff --git a/crates/raw/src/demosaic/ppg.rs b/crates/raw/src/demosaic/ppg.rs deleted file mode 100644 index 9efd3a8672..0000000000 --- a/crates/raw/src/demosaic/ppg.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! Patterned Pixel Grouping (after Chuan-kai Lin's published description of the method). -//! -//! 1. Green at red/blue sites: four directional gradients (same-colour difference ×2 plus the green difference -//! across the site); the estimate along the flattest direction is the nearer green weighted 3:1 with the far -//! one plus a same-colour Laplacian correction, clamped to the two greens of that direction. -//! 2. Red/blue at green sites: colour-difference (C − G) average of the two same-colour neighbours. -//! 3. Blue at red sites (and red at blue): colour-difference average along the diagonal with the smaller -//! gradient (both diagonals when equal). - -use super::Mosaic; -use crate::Rgb32f; -use lightcraft_raster::par_rows; - -/// Green plane with PPG estimates at non-green sites. -pub(crate) fn green_plane(m: &Mosaic) -> Vec { - let (w, h) = (m.w, m.h); - let mut g = vec![0f32; w * h]; - par_rows(&mut g, w, |y, row| { - let y = y as isize; - for (x, o) in row.iter_mut().enumerate() { - let x = x as isize; - let c = m.get(x, y); - if m.color(x, y) == 1 { - *o = c; - continue; - } - let (gn, gs, gw, ge) = (m.get(x, y - 1), m.get(x, y + 1), m.get(x - 1, y), m.get(x + 1, y)); - let (cn, cs, cw, ce) = (m.get(x, y - 2), m.get(x, y + 2), m.get(x - 2, y), m.get(x + 2, y)); - let dv = (gn - gs).abs(); - let dh = (gw - ge).abs(); - let grads = [(cn - c).abs() * 2.0 + dv, (cs - c).abs() * 2.0 + dv, (cw - c).abs() * 2.0 + dh, (ce - c).abs() * 2.0 + dh]; - let mut best = 0; - for i in 1..4 { - if grads[i] < grads[best] { - best = i; - } - } - let (near, far, cfar) = match best { - 0 => (gn, gs, cn), - 1 => (gs, gn, cs), - 2 => (gw, ge, cw), - _ => (ge, gw, ce), - }; - let est = (near * 3.0 + far + c - cfar) * 0.25; - *o = super::clamp_between(est, near, far); - } - }); - g -} - -pub(crate) fn ppg(m: &Mosaic) -> Rgb32f { - let (w, h) = (m.w, m.h); - let g = green_plane(m); - let gg = |x: isize, y: isize| g[super::reflect(y, h) * w + super::reflect(x, w)]; - let mut out = Rgb32f::new(w, h); - par_rows(&mut out.data, w, |y, row| { - let y = y as isize; - for (x, px) in row.iter_mut().enumerate() { - let x = x as isize; - let own = m.color(x, y) as usize; - let gv = gg(x, y); - px[1] = gv; - if own == 1 { - // horizontal neighbours carry one colour, vertical the other - let ch = m.color(x + 1, y) as usize; - let cv = m.color(x, y + 1) as usize; - let hval = gv + ((m.get(x - 1, y) - gg(x - 1, y)) + (m.get(x + 1, y) - gg(x + 1, y))) * 0.5; - let vval = gv + ((m.get(x, y - 1) - gg(x, y - 1)) + (m.get(x, y + 1) - gg(x, y + 1))) * 0.5; - px[ch] = hval; - px[cv] = vval; - } else { - px[own] = m.get(x, y); - let other = 2 - own; - let d = |dx: isize, dy: isize| m.get(x + dx, y + dy) - gg(x + dx, y + dy); - let ne = (m.get(x + 1, y - 1) - m.get(x - 1, y + 1)).abs() + (gg(x + 1, y - 1) - gv).abs() + (gg(x - 1, y + 1) - gv).abs(); - let nw = (m.get(x - 1, y - 1) - m.get(x + 1, y + 1)).abs() + (gg(x - 1, y - 1) - gv).abs() + (gg(x + 1, y + 1) - gv).abs(); - let diff = if ne < nw { - (d(1, -1) + d(-1, 1)) * 0.5 - } else if nw < ne { - (d(-1, -1) + d(1, 1)) * 0.5 - } else { - (d(1, -1) + d(-1, 1) + d(-1, -1) + d(1, 1)) * 0.25 - }; - px[other] = gv + diff; - } - } - }); - out -} diff --git a/crates/raw/src/demosaic/xtrans.rs b/crates/raw/src/demosaic/xtrans.rs deleted file mode 100644 index 2b50b66c3c..0000000000 --- a/crates/raw/src/demosaic/xtrans.rs +++ /dev/null @@ -1,281 +0,0 @@ -//! Demosaicing for non-Bayer patterns (Fujifilm X-Trans and others): our own edge-weighted colour-difference -//! interpolation. -//! -//! 1. Green at non-green sites: robust weighted mean of the green samples in the 3×3 neighbourhood (5×5 if -//! none), each weighted by `1 / (ε + |g − median|)` so samples across an edge contribute little. -//! 2. Red and blue everywhere: `G(p) + Σ w_q (C(q) − G(q)) / Σ w_q` over same-colour samples `q` in the 5×5 -//! neighbourhood, with `w_q = 1 / (d²(p, q) · (ε + |G(q) − G(p)|))` — spatially close samples on the same -//! side of an edge dominate. - -use super::Mosaic; -use crate::Rgb32f; -use lightcraft_raster::par_rows; - -const EPS: f32 = 1e-3; - -/// Same-colour neighbour offsets for every pattern phase, in scan order (so sums run in the same -/// order as a plain 2-D loop and interior pixels match border pixels bit for bit). -struct Offsets { - pw: usize, - ph: usize, - /// Per phase: green offsets at radius 1, then those at radius 2 (ring order as the loop below). - green: Vec<(Vec<(isize, isize)>, Vec<(isize, isize)>)>, - /// Per phase and colour (0 = red, 1 = blue): 5×5 offsets of that colour. - rb: Vec<[Vec<(isize, isize)>; 2]>, -} - -impl Offsets { - fn new(m: &Mosaic) -> Offsets { - let (pw, ph) = (m.cfa.width.max(1), m.cfa.height.max(1)); - // phases are evaluated far from the borders (pattern coordinates wrap) - let col = |x: isize, y: isize| m.cfa.color_at(x.rem_euclid(pw as isize) as usize, y.rem_euclid(ph as isize) as usize); - let mut green = Vec::new(); - let mut rb = Vec::new(); - for py in 0..ph as isize { - for px in 0..pw as isize { - let ring = |r: isize| { - let mut v = Vec::new(); - for dy in -r..=r { - for dx in -r..=r { - if (dx != 0 || dy != 0) && col(px + dx, py + dy) == 1 { - v.push((dx, dy)); - } - } - } - v - }; - green.push((ring(1), ring(2))); - let of = |c: u8| { - let mut v = Vec::new(); - for dy in -2isize..=2 { - for dx in -2isize..=2 { - if col(px + dx, py + dy) == c { - v.push((dx, dy)); - } - } - } - v - }; - rb.push([of(0), of(2)]); - } - } - Offsets { pw, ph, green, rb } - } - #[inline] - fn phase(&self, x: usize, y: usize) -> usize { - (y % self.ph) * self.pw + x % self.pw - } -} - -/// Robust weighted mean of `vals` around their median. -#[inline] -fn robust_mean(vals: &[f32]) -> f32 { - let mut sorted = [0f32; 24]; - let sorted = &mut sorted[..vals.len()]; - sorted.copy_from_slice(vals); - sorted.sort_unstable_by(|a, b| a.total_cmp(b)); - let med = sorted[sorted.len() / 2]; - let (mut s, mut ws) = (0.0f32, 0.0f32); - for &v in vals { - let wt = 1.0 / (EPS + (v - med).abs()); - s += wt * v; - ws += wt; - } - s / ws -} - -fn green(m: &Mosaic, off: &Offsets) -> Vec { - let (w, h) = (m.w, m.h); - let mut g = vec![0f32; w * h]; - par_rows(&mut g, w, |y, row| { - let interior_y = y >= 2 && y + 2 < h; - let yi = y as isize; - let mut vals: Vec = Vec::with_capacity(24); - for (x, o) in row.iter_mut().enumerate() { - if interior_y && x >= 2 && x + 2 < w { - // fast path: precomputed offsets, no reflection - let ph = off.phase(x, y); - let i = y * w + x; - if m.cfa.color_at(x, y) == 1 { - *o = m.data[i]; - continue; - } - let (r1, r2) = &off.green[ph]; - let ring = if r1.is_empty() { r2 } else { r1 }; - if ring.is_empty() { - *o = m.data[i]; - continue; - } - vals.clear(); - vals.extend(ring.iter().map(|&(dx, dy)| m.data[(i as isize + dy * w as isize + dx) as usize])); - *o = robust_mean(&vals); - continue; - } - let x = x as isize; - if m.color(x, yi) == 1 { - *o = m.get(x, yi); - continue; - } - vals.clear(); - for r in [1isize, 2] { - for dy in -r..=r { - for dx in -r..=r { - if (dx != 0 || dy != 0) && m.color(x + dx, yi + dy) == 1 { - vals.push(m.get(x + dx, yi + dy)); - } - } - } - if !vals.is_empty() { - break; - } - } - if vals.is_empty() { - *o = m.get(x, yi); - continue; - } - *o = robust_mean(&vals); - } - }); - g -} - -pub(crate) fn directional(m: &Mosaic) -> Rgb32f { - let (w, h) = (m.w, m.h); - let off = Offsets::new(m); - let g = green(m, &off); - let gg = |x: isize, y: isize| g[super::reflect(y, h) * w + super::reflect(x, w)]; - let mut out = Rgb32f::new(w, h); - par_rows(&mut out.data, w, |y, row| { - let interior_y = y >= 2 && y + 2 < h; - let yi = y as isize; - for (x, px) in row.iter_mut().enumerate() { - if interior_y && x >= 2 && x + 2 < w { - let i = y * w + x; - let own = m.cfa.color_at(x, y) as usize; - let gp = g[i]; - px[1] = gp; - let lists = &off.rb[off.phase(x, y)]; - for (li, c) in [0usize, 2].into_iter().enumerate() { - if c == own { - px[c] = m.data[i]; - continue; - } - let (mut s, mut ws) = (0.0f32, 0.0f32); - for &(dx, dy) in &lists[li] { - let j = (i as isize + dy * w as isize + dx) as usize; - let gq = g[j]; - let d2 = (dx * dx + dy * dy) as f32; - let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); - s += wt * (m.data[j] - gq); - ws += wt; - } - px[c] = if ws > 0.0 { gp + s / ws } else { gp }; - } - continue; - } - let x = x as isize; - let own = m.color(x, yi) as usize; - let gp = gg(x, yi); - px[1] = gp; - for c in [0usize, 2] { - if c == own { - px[c] = m.get(x, yi); - continue; - } - let (mut s, mut ws) = (0.0f32, 0.0f32); - for dy in -2isize..=2 { - for dx in -2isize..=2 { - if m.color(x + dx, yi + dy) as usize != c { - continue; - } - let gq = gg(x + dx, yi + dy); - let d2 = (dx * dx + dy * dy) as f32; - let wt = 1.0 / (d2 * (EPS + (gq - gp).abs())); - s += wt * (m.get(x + dx, yi + dy) - gq); - ws += wt; - } - } - px[c] = if ws > 0.0 { gp + s / ws } else { gp }; - } - } - }); - out -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::Cfa; - - /// The straightforward per-pixel formulation (reflection at every access): the precomputed - /// interior path must match it bit for bit. - fn reference(m: &Mosaic) -> Rgb32f { - let (w, h) = (m.w, m.h); - let mut g = vec![0f32; w * h]; - for y in 0..h as isize { - for x in 0..w as isize { - let o = &mut g[y as usize * w + x as usize]; - if m.color(x, y) == 1 { - *o = m.get(x, y); - continue; - } - let mut vals = Vec::new(); - for r in [1isize, 2] { - for dy in -r..=r { - for dx in -r..=r { - if (dx != 0 || dy != 0) && m.color(x + dx, y + dy) == 1 { - vals.push(m.get(x + dx, y + dy)); - } - } - } - if !vals.is_empty() { - break; - } - } - *o = if vals.is_empty() { m.get(x, y) } else { robust_mean(&vals) }; - } - } - let gg = |x: isize, y: isize| g[super::super::reflect(y, h) * w + super::super::reflect(x, w)]; - Rgb32f::from_fn(w, h, |x, y| { - let (x, y) = (x as isize, y as isize); - let own = m.color(x, y) as usize; - let gp = gg(x, y); - let mut px = [0f32, gp, 0.0]; - for c in [0usize, 2] { - if c == own { - px[c] = m.get(x, y); - continue; - } - let (mut s, mut ws) = (0.0f32, 0.0f32); - for dy in -2isize..=2 { - for dx in -2isize..=2 { - if m.color(x + dx, y + dy) as usize == c { - let gq = gg(x + dx, y + dy); - let wt = 1.0 / ((dx * dx + dy * dy) as f32 * (EPS + (gq - gp).abs())); - s += wt * (m.get(x + dx, y + dy) - gq); - ws += wt; - } - } - } - px[c] = if ws > 0.0 { gp + s / ws } else { gp }; - } - px - }) - } - - #[test] - fn fast_path_is_bit_exact() { - let cfa = Cfa::xtrans().shifted(1, 2); - let (w, h) = (37, 29); - let mut seed = 12345u32; - let data: Vec = (0..w * h) - .map(|_| { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (seed >> 8) as f32 / (1u32 << 24) as f32 - }) - .collect(); - let m = Mosaic { w, h, data: &data, cfa: &cfa }; - let (a, b) = (directional(&m), reference(&m)); - assert!(a.data.iter().zip(&b.data).all(|(p, q)| p.map(f32::to_bits) == q.map(f32::to_bits))); - } -} diff --git a/crates/raw/src/gaintable.rs b/crates/raw/src/gaintable.rs index 1050577d67..afe743caa1 100644 --- a/crates/raw/src/gaintable.rs +++ b/crates/raw/src/gaintable.rs @@ -1,176 +1,18 @@ -//! DNG `ProfileGainTableMap` (tag 52525, DNG 1.6) and `ProfileGainTableMap2` (tag 52544, DNG 1.7): -//! a coarse grid of 1D gain tables carrying the maker's local tone mapping. Apple ProRAW has one. -//! -//! We read and write the tag (a DNG export keeps it) but don't render it by default: Lightroom -//! Classic renders Apple ProRAW without the map (see [`crate::profile`]), and so do we. The photo's -//! "camera local tone mapping" option renders it ([`GainTableMap::gain`], applied by the pipeline), -//! as the camera itself does. -//! -//! Applying it (DNG 1.7.1, `ProfileGainTableMap` → "Description"): -//! -//! - the four tables around a position are interpolated bilinearly; outside the grid the edge -//! tables are replicated. Positions are relative to the active area at pixel centres; -//! - the table input `clamp((R, G, B, min, max) · weights, 0, 1) ^ gamma` is computed in linear -//! RIMM (ProPhoto) after the baseline exposure; -//! - the gain is the table looked up linearly at `input × MapPointsN` ("multiply the table input -//! value by MapPointsN to compute the floating-point table index"), clamped to the last point, -//! and multiplies R, G and B. Results may exceed 1 and aren't clipped. -//! -//! - The grid has `MapPointsV × MapPointsH` tables of `MapPointsN` gains. Its origin and spacing -//! are relative to the active area (1.0 = the active area's height or width). -//! - The table input is the dot product of (R, G, B, min, max) with the tag's five weights; -//! version 2 then raises it to the tag's `Gamma`. -//! - Version 2 stores gains as u8 or u16 (mapped linearly onto `GainMin..=GainMax`), f16 or f32. -//! It takes precedence over version 1 when both are present. -//! -//! Malformed tags are ignored: a wrong size, zero or huge dimensions, non-finite or negative gains, -//! non-positive spacing, or gamma outside 0.25..=4. -//! -//! Byte order: the tag's fields are TIFF types (LONG, DOUBLE, FLOAT, …), and neither DNG 1.6 nor -//! 1.7.1 gives this tag a byte order of its own, as they do for opcode lists and -//! `OriginalRawFileData` (always big-endian). What applies is the general rule of the DNG 1.6 -//! specification ("DNG Format Overview" → "Byte Order", worded the same in 1.7.1): -//! -//! > DNG readers are required to support either byte order, even for files from a particular -//! > camera model. -//! -//! (, "DNG Specification".) So we read -//! the fields in the file's byte order, and fall back to big-endian for writers that followed the -//! opcode-list convention. A read in the wrong order can't pass for a valid map: one of -//! `MapPointsV` / `MapPointsH` is below 256 (their product is at most [`MAX_TABLES`]), so swapped -//! it is at least 2^24 and the size checks reject it. We write in the file's byte order. +//! DNG `ProfileGainTableMap` (tag 52525, DNG 1.6) and `ProfileGainTableMap2` (tag 52544, DNG 1.7), +//! backed by `craft_develop::sensor::gaintable`. -pub use craft_raw::gaintable::GainTableMap; use serde::{Deserialize, Serialize}; -/// Applying a gain table map (the map, and reading and writing its tag, is `craft-raw`'s). -pub trait GainTableMapApply { - /// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM) - /// colour after the baseline exposure. 1.0 for a map that can't be evaluated. For many pixels, - /// [`Self::evaluator`] once and [`GainEval::gain`] per pixel. - fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32; - /// The map ready to evaluate per pixel, or `None` when it can't be (inconsistent sizes). - fn evaluator(&self) -> Option>; -} +pub use craft_develop::sensor::gaintable::{GainEval, GainTableMapApply}; +pub use craft_raw::gaintable::GainTableMap; -/// Applying the map (see the module docs). Index arithmetic saturates and every lookup is -/// checked: the fields are public and the struct is deserializable, so a hand-built or damaged map -/// must not overflow or panic, whatever it holds. -impl GainTableMapApply for GainTableMap { - /// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM) - /// colour after the baseline exposure. 1.0 for a map that can't be evaluated. For many pixels, - /// [`Self::evaluator`] once and [`GainEval::gain`] per pixel. - fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 { - self.evaluator().map_or(1.0, |e| e.gain(p, x, y)) - } - - /// The map ready to evaluate per pixel, or `None` when it can't be (inconsistent sizes). - fn evaluator(&self) -> Option> { - let n = self.points_n; - let tables = self.points_v.saturating_mul(self.points_h); - if n == 0 || tables == 0 || tables.saturating_mul(n) != self.gains.len() { - return None; - } - let axis = |points: usize, origin: f64, spacing: f64| Axis { - last: points.saturating_sub(1), - origin, - // (a degenerate axis replicates its first table) - inv: if points > 1 && spacing.is_finite() && spacing > 0.0 { 1.0 / spacing } else { 0.0 }, - }; - Some(GainEval { map: self, v: axis(self.points_v, self.origin_v, self.spacing_v), h: axis(self.points_h, self.origin_h, self.spacing_h) }) - } -} - -/// One grid axis, prepared: last table index, origin and inverse spacing (0: one table). -#[derive(Clone, Copy, Debug)] -struct Axis { - last: usize, - origin: f64, - inv: f64, -} - -impl Axis { - /// The cell at relative position `pos`: (first table, second table, weight of the second). - /// Outside the grid the edge table is replicated. - #[inline] - fn cell(self, pos: f64) -> (usize, usize, f32) { - if self.last == 0 || self.inv == 0.0 { - return (0, 0, 0.0); - } - let f = (pos - self.origin) * self.inv; - let f = if f.is_nan() { 0.0 } else { f.clamp(0.0, self.last as f64) }; - // (≥ 0: `as` truncates like `floor`, which isn't inlined on baseline x86-64) - let i0 = (f as usize).min(self.last); - let i1 = i0.saturating_add(1).min(self.last); - (i0, i1, (f - i0 as f64) as f32) - } -} - -/// Grid cell along one axis (see [`Axis::cell`]). -#[cfg(test)] -fn cell(pos: f64, origin: f64, spacing: f64, points: usize) -> (usize, usize, f32) { - let inv = if points > 1 && spacing.is_finite() && spacing > 0.0 { 1.0 / spacing } else { 0.0 }; - Axis { last: points.saturating_sub(1), origin, inv }.cell(pos) -} - -/// A [`GainTableMap`] prepared for evaluating many pixels. -#[derive(Clone, Copy, Debug)] -pub struct GainEval<'a> { - map: &'a GainTableMap, - v: Axis, - h: Axis, -} - -impl GainEval<'_> { - /// [`GainTableMapApply::gain`]. - #[inline] - pub fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 { - let m = self.map; - let (v0, v1, fv) = self.v.cell(y); - let (h0, h1, fh) = self.h.cell(x); - // one fractional index for the four tables (≥ 0, so `as` truncates) - let n = m.points_n; - let last = n - 1; - let idx = (input(m, p) * n as f32).min(last as f32); - let i0 = (idx as usize).min(last); - let i1 = i0.saturating_add(1).min(last); - let t = idx - i0 as f32; - // (v ≤ points_v − 1, h ≤ points_h − 1 and i ≤ n − 1, with points_v·points_h·n = gains.len() - // checked by `evaluator`: none of this overflows, and `get` still guards each read) - let at = |v: usize, h: usize| { - let table = m.gains.get((v * m.points_h + h) * n..).unwrap_or(&[]); - let g0 = table.get(i0).copied().unwrap_or(1.0); - let g1 = table.get(i1).copied().unwrap_or(1.0); - g0 + (g1 - g0) * t - }; - let (a, b, c, d) = (at(v0, h0), at(v0, h1), at(v1, h0), at(v1, h1)); - let top = a + (b - a) * fh; - let bottom = c + (d - c) * fh; - let g = top + (bottom - top) * fv; - if g.is_finite() { g.max(0.0) } else { 1.0 } - } -} - -/// The table input for `p` (linear ProPhoto, after the baseline exposure). -#[inline] -fn input(m: &GainTableMap, p: [f32; 3]) -> f32 { - let w = &m.weights; - let lo = p[0].min(p[1]).min(p[2]); - let hi = p[0].max(p[1]).max(p[2]); - let x = w[0] * p[0] + w[1] * p[1] + w[2] * p[2] + w[3] * lo + w[4] * hi; - let x = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0) }; - if m.gamma == 1.0 { x } else { x.powf(m.gamma) } -} - -/// Where the pixels of a developed source sit in the raw's active area, for [`GainTableMapApply::gain`]. -/// The source is the default crop of the active area (`rect`, relative to the active area), -/// then EXIF-`orientation`ed. Resolution independent. +/// Where the developed picture (the default crop, oriented) sits in the active area. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct SourcePlacement { /// x, y, width, height of the developed crop, relative to the active area. pub rect: [f64; 4], /// The EXIF orientation applied to the developed crop. - pub orientation: lightcraft_geom::Orientation, + pub orientation: crate::Orientation, } impl SourcePlacement { @@ -181,111 +23,3 @@ impl SourcePlacement { (x + u * w, y + v * h) } } - -#[cfg(test)] -mod tests { - use super::*; - - fn map(dims: [usize; 3], spacing: [f64; 2], origin: [f64; 2], weights: [f32; 5], gains: Vec) -> GainTableMap { - let [points_v, points_h, points_n] = dims; - let [spacing_v, spacing_h] = spacing; - let [origin_v, origin_h] = origin; - GainTableMap { points_v, points_h, points_n, spacing_v, spacing_h, origin_v, origin_h, weights, gamma: 1.0, gains } - } - - const LUMA: [f32; 5] = [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0, 0.0, 0.0]; - - #[test] - fn gain_follows_the_table_input_at_input_times_n() { - // one table of 3 points: index = input × 3 (DNG 1.7.1), clamped to the last point - let m = map([1, 1, 3], [1.0, 1.0], [0.0, 0.0], LUMA, vec![1.0, 2.0, 3.0]); - assert_eq!(m.gain([0.0; 3], 0.5, 0.5), 1.0); - assert!((m.gain([1.0 / 3.0; 3], 0.5, 0.5) - 2.0).abs() < 1e-5, "index 1"); - assert!((m.gain([1.0 / 6.0; 3], 0.5, 0.5) - 1.5).abs() < 1e-5, "index 0.5: linear in the table"); - assert!((m.gain([0.9; 3], 0.5, 0.5) - 3.0).abs() < 1e-5, "index 2.7 clamps to the last point"); - // min/max weights and gamma: input = max(R, G, B)², two points - let mut m = map([1, 1, 2], [1.0, 1.0], [0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0], vec![1.0, 3.0]); - m.gamma = 2.0; - // max 0.5 → 0.25 → index 0.5 → ×2 - assert!((m.gain([0.1, 0.5, 0.2], 0.0, 0.0) - 2.0).abs() < 1e-5); - } - - #[test] - fn tables_interpolate_across_the_grid_and_replicate_at_the_edges() { - // 1 × 2 constant tables at x = 0.25 (×1) and x = 0.75 (×3) - let m = map([1, 2, 1], [1.0, 0.5], [0.0, 0.25], LUMA, vec![1.0, 3.0]); - let g = |x: f64| m.gain([0.2; 3], x, 0.5); - assert!((g(0.25) - 1.0).abs() < 1e-5 && (g(0.5) - 2.0).abs() < 1e-5 && (g(0.75) - 3.0).abs() < 1e-5); - assert!((g(0.0) - 1.0).abs() < 1e-5 && (g(1.0) - 3.0).abs() < 1e-5); - assert!((g(-10.0) - 1.0).abs() < 1e-5 && (g(10.0) - 3.0).abs() < 1e-5); - // vertically too: 2 × 1 at y = 0 (×1) and y = 1 (×2) - let m = map([2, 1, 1], [1.0, 1.0], [0.0, 0.0], LUMA, vec![1.0, 2.0]); - assert!((m.gain([0.2; 3], 0.5, 0.25) - 1.25).abs() < 1e-5); - } - - #[test] - fn hand_built_maps_never_panic() { - // review on #273: `(i0 + 1).min(points - 1)` overflowed for points_v = usize::MAX at +inf - let mut m = map([usize::MAX, 1, 1], [1.0, 1.0], [0.0, 0.0], LUMA, vec![2.0]); - assert_eq!(m.gain([0.5; 3], 0.5, f64::INFINITY), 1.0, "inconsistent sizes: no gain"); - for (v, h, n, len) in [(usize::MAX, 1, 1, 1), (1, usize::MAX, usize::MAX, 3), (0, 0, 0, 0), (2, 2, 0, 0), (1, 1, 2, 1)] { - m.points_v = v; - m.points_h = h; - m.points_n = n; - m.gains = vec![2.0; len]; - for spacing in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e-300] { - m.spacing_v = spacing; - m.spacing_h = spacing; - for p in [[0.5; 3], [f32::NAN; 3], [f32::INFINITY, 0.0, -1.0], [1e30; 3]] { - for (x, y) in [(0.5, 0.5), (f64::INFINITY, f64::NEG_INFINITY), (f64::NAN, f64::NAN)] { - assert!(m.gain(p, x, y).is_finite()); - } - } - } - } - // the grid cell itself saturates (the reviewer's case, reached directly) - assert_eq!(cell(f64::INFINITY, 0.0, 1.0, usize::MAX), (usize::MAX - 1, usize::MAX - 1, 0.0)); - assert_eq!(cell(f64::NEG_INFINITY, 0.0, 1.0, usize::MAX).0, 0); - // a consistent map with a huge grid and positions far outside it - let m = map([1, 1, 2], [1e-300, 1e-300], [0.0, 0.0], [f32::MAX; 5], vec![1.0, 4.0]); - assert!(m.gain([1e30; 3], f64::INFINITY, -f64::INFINITY).is_finite()); - } - - #[test] - fn placement_undoes_crop_and_orientation() { - // the source is the right half of the active area, rotated 90° clockwise - let p = SourcePlacement { rect: [0.5, 0.0, 0.5, 1.0], orientation: lightcraft_geom::Orientation::Rotate90 }; - // the oriented source's top-left came from the crop's bottom-left - let (x, y) = p.active(0.0, 0.0); - assert!((x - 0.5).abs() < 1e-12 && (y - 1.0).abs() < 1e-12, "{x} {y}"); - // its top-right came from the crop's top-left - let (x, y) = p.active(1.0, 0.0); - assert!((x - 0.5).abs() < 1e-12 && y.abs() < 1e-12, "{x} {y}"); - let plain = SourcePlacement { rect: [0.0, 0.0, 1.0, 1.0], orientation: lightcraft_geom::Orientation::Normal }; - assert_eq!(plain.active(0.25, 0.75), (0.25, 0.75)); - } -} - -/// `GTM_FILE=photo.dng cargo test --release -p lightcraft-raw gain_throughput -- --ignored --nocapture`: -/// the cost of [`GainEval::gain`] per pixel on a real file's map. -#[cfg(test)] -mod bench { - use super::GainTableMapApply; - #[test] - #[ignore] - fn gain_throughput() { - let Some(path) = std::env::var_os("GTM_FILE") else { return }; - let raw = crate::decode(&std::fs::read(path).unwrap()).unwrap(); - let m = raw.color.profile.gain_table_map.expect("the file has no gain table map"); - let e = m.evaluator().unwrap(); - let n = 3_000_000usize; - let t = std::time::Instant::now(); - let mut acc = 0f32; - for i in 0..n { - let (x, y) = ((i % 2048) as f64 / 2048.0, (i / 2048) as f64 / 1536.0); - let v = ((i * 7919) % 1000) as f32 / 1000.0 * 0.5; - acc += e.gain([v, v * 0.9, v * 0.8], x, y); - } - println!("{}×{}×{} map: {:.1} ns/px ({acc})", m.points_v, m.points_h, m.points_n, t.elapsed().as_secs_f64() * 1e9 / n as f64); - } -} diff --git a/crates/raw/src/highlight.rs b/crates/raw/src/highlight.rs index 40f35dc206..1b75464b1a 100644 --- a/crates/raw/src/highlight.rs +++ b/crates/raw/src/highlight.rs @@ -1,534 +1,32 @@ -//! Clip-aware highlight handling on demosaiced camera RGB (before white balance, white level = 1.0). -//! -//! - [`clip_neutral`]: white-balance-aware clipping so that sensor-clipped areas render neutral instead of -//! magenta/cyan (each channel limited to the smallest white-balanced clip level). -//! - [`reconstruct`] / [`reconstruct_with`]: where only some channels are clipped, rebuild them from the -//! unclipped channels using the chromaticity of reliable unclipped content nearby (bright, away from edges and -//! from the clipped pixels themselves; diffused into the clipped region coarse to fine) unless both the pixel's -//! own channels and the clipped surface's colour just below its clip (the rim) contradict it, and neutral where -//! there is none within reach. Right past the rim, the rim's colour carries on. Fully clipped pixels become -//! neutral at the brightest plausible level; partly clipped ones fade into it on their way from the first channel -//! clipping to the last, pale ones from the start. -//! - [`reconstruct_masked`]: the same for a binned image, whose clipped channels a mask tells (block means with a -//! clipped sample among them). -//! -//! Why the care: the white-balance gains push clipped channels apart (green clips first, red and blue keep -//! rising), so whatever colour the rebuilt pixels carry is hidden at Neutral only by the tone map's roll-off to -//! white. Any darkening (Highlights, negative Exposure or Whites) brings it out. Three things used to leak colour -//! in: the chromaticity of whatever unclipped pixel happened to be nearest (dark foliage, purple and green -//! fringes along branches, pixels demosaiced from clipped neighbours); a colour model that does not render the -//! camera's white-balanced neutral as neutral (a look fitted to the camera's JPEG, a camera profile); and, in a -//! pale partly clipped sky, the colour of another reliable surface (bright foliage) and the sky's own faint -//! colour, which darkening and a camera profile turned teal. +//! Highlight recovery, backed by `craft_develop::sensor::highlight`. -use lightcraft_raster::Rgb32f; -use rayon::prelude::*; +use crate::Rgb32f; + +pub use craft_develop::sensor::highlight::{CLIPPED_B, CLIPPED_G, CLIPPED_R}; -/// Clip every channel of `wb ⊙ img` at `min_c(wb_c) · clip` — i.e. at the lowest channel's clip level after WB — -/// then divide the multipliers back out. `clip` is the sensor clip in normalised units (≈ 1.0). pub fn clip_neutral(img: &mut Rgb32f, wb: [f32; 3], clip: f32) { - let limit = wb.iter().cloned().fold(f32::MAX, f32::min) * clip; - for p in &mut img.data { - for c in 0..3 { - p[c] = (p[c] * wb[c]).min(limit) / wb[c]; - } - } + let mut craft = crate::bridge::take_craft_rgb32f(img); + craft_develop::sensor::highlight::clip_neutral(&mut craft, wb, clip); + crate::bridge::put_craft_rgb32f(img, craft); } -/// Unclipped pixels lend their chromaticity in proportion to how close they come to clipping (their largest -/// channel, relative to the clip level): from nothing below `SOURCE_LO` to fully above `SOURCE_HI`. Dark content -/// (foliage, branches, buildings against a clipped sky) says nothing about the sky's colour. -const SOURCE_LO: f32 = 0.25; -const SOURCE_HI: f32 = 0.6; -/// Sources on a strong edge (a 3 × 3 half-resolution neighbour brighter or darker by this many stops) are -/// left out, fading from `EDGE_LO` to `EDGE_HI`: edge pixels mix two surfaces and carry lens fringes. -const EDGE_LO: f32 = 0.15; -const EDGE_HI: f32 = 0.4; -/// Source cells within this many half-resolution cells of a clipped pixel are left out: their channels were -/// demosaiced partly from clipped samples. (At least 1: the same neighbourhood tells which cells clipped -/// pixels sample.) -const MARGIN: usize = 1; -/// Weight of the coarser estimate against a cell's own sources when the pyramid is pushed back down (in units -/// of source density: a cell half covered by full-weight sources counts 0.5). -const PRIOR: f32 = 0.01; -/// The rebuilt colour fades to neutral where reliable content covers less than `SUPPORT` of the surroundings at -/// every scale up to `REACH` of the long edge (so previews and exports agree), gradually, as the coverage of the -/// widest one falls: a clipped sky between bare branches is better white than the colour of a river far away. -const REACH: f32 = 1.0 / 4.0; -const SUPPORT: f32 = 0.05; -/// An unclipped channel above `FLOOR_LO` of its clip level counts more and more as the clip floor it is about to -/// become (see [`reconstruct_with`]). -const FLOOR_LO: f32 = 0.75; -/// A clipped pixel takes its estimated colour (reliable colour around, or the neutral guess) only as far as it is -/// brighter (or otherwise unlike) the unclipped pixels nearest its clip: the "rim", unclipped pixels above `RIM_LO` -/// of the clip level, weighted towards the clip, the clipped surface's own colour just below it. Up to `NEAR_RIM` -/// stops past the rim (the rim is an average, a little below the clip) it is rebuilt with the rim's colour, and -/// over the next `DEPTH` stops it goes over to the estimate, so a surface runs into clipping without a step -/// whatever its colour and whatever lent the estimate; well past it, or where the rim is another surface (its -/// colour differs; a clipped channel differs by at least as much as it lies above the rim's), the estimate applies. -const RIM_LO: f32 = 0.85; -const NEAR_RIM: f32 = 0.03; -const DEPTH: f32 = 0.2; -/// Reliable colour counts less and less as both the pixel's own channels (see [`contradiction`]) and the rim's -/// colour contradict it, by `AGREE.0` to `AGREE.1` stops: it is another surface's, like bright foliage below a pale -/// sky, whose green would turn the sky teal. (Either alone can be wrong: a pixel's own channels are noisy and -/// can't speak for the channels that clipped, and the rim can be another surface, like a white window frame -/// around a bright view.) -const AGREE: (f32, f32) = (0.15, 0.4); -/// On the way from the first channel clipping to the last, a partly clipped pixel's brightness goes over to the -/// clipped neutral's in the second half, and so does the colour of a strongly coloured one (saturation relative to -/// the white above `PALE.1`). A pale one's colour (below `PALE.0`) goes over from the start: the few per cent of -/// colour left in a pale sky once a channel clipped is as much the estimate's error as the sky's, and darkening -/// shows it. -const PALE: (f32, f32) = (0.2, 0.4); - -#[inline] -fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { - let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) -} - -/// One level of a pyramid, `w × h` cells of `N - 1` values and a weight. Pulled: per cell the weighted sums of -/// the values and the weight, as densities (per pixel of the cell). Pushed: the estimated values, and still the -/// weight. The chromaticity pyramid holds red and blue chromaticity, the rim pyramid white-balanced RGB. -struct Level { - w: usize, - h: usize, - cells: Vec<[f32; N]>, -} - -/// Bilinear sample of a level at the centre of pixel `(x, y)` of a grid `scale` times finer. -#[inline] -fn sample(l: &Level, scale: f32, x: usize, y: usize) -> [f32; N] { - let (cv, cw, ch) = (&l.cells, l.w, l.h); - let fx = ((x as f32 + 0.5) / scale - 0.5).clamp(0.0, cw.saturating_sub(1) as f32); - let fy = ((y as f32 + 0.5) / scale - 0.5).clamp(0.0, ch.saturating_sub(1) as f32); - let (x0, y0) = (fx.floor() as usize, fy.floor() as usize); - let (x1, y1) = ((x0 + 1).min(cw.saturating_sub(1)), (y0 + 1).min(ch.saturating_sub(1))); - let (tx, ty) = (fx - x0 as f32, fy - y0 as f32); - let g = |xx: usize, yy: usize| cv.get(yy * cw + xx).copied().unwrap_or([0.0; N]); - let (a, b, c, d) = (g(x0, y0), g(x1, y0), g(x0, y1), g(x1, y1)); - std::array::from_fn(|k| { - let top = a[k] + (b[k] - a[k]) * tx; - let bot = c[k] + (d[k] - c[k]) * tx; - top + (bot - top) * ty - }) -} - -/// The half-resolution source level of `img`: every `2 × 2` block's source-weighted chromaticity sums, with -/// blocks near clipped pixels or on strong edges left out. Also returns, per cell, whether a clipped pixel lies -/// in its row within [`MARGIN`] cells (the vertical half of that test is left to the readers). -fn sources(img: &Rgb32f, wb: [f32; 3], clip: f32, clipped: &impl Clipped) -> (Level<3>, Vec) { - let (w, h) = (img.width, img.height); - let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); - // per cell: [red sum, blue sum, weight] densities, luminance, whether it holds a clipped pixel - let mut cells = vec![[0f32; 3]; cw * ch]; - let mut lum = vec![0f32; cw * ch]; - let mut near = vec![false; cw * ch]; - cells.par_chunks_mut(cw).zip(lum.par_chunks_mut(cw)).zip(near.par_chunks_mut(cw)).enumerate().for_each(|(y, ((crow, lrow), nrow))| { - let mut touched = vec![false; cw]; - let row = |r: usize| img.data.get(r * w..(r + 1) * w).unwrap_or(&[]); - let (r0, r1) = (row(2 * y), row(2 * y + 1)); - let lo = SOURCE_LO * clip; - for x in 0..cw { - let (mut a, mut sum, mut n, mut hit) = ([0f32; 3], 0f32, 0usize, false); - let span = 2 * x..(2 * x + 2).min(w); - let (i0, i1) = (2 * y * w + 2 * x, (2 * y + 1) * w + 2 * x); - let pixels = r0.get(span.clone()).unwrap_or(&[]).iter().zip(i0..).chain(r1.get(span).unwrap_or(&[]).iter().zip(i1..)); - for (p, i) in pixels { - let q = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]; - let s = q[0].max(0.0) + q[1].max(0.0) + q[2].max(0.0); - sum += s; - n += 1; - let top = p[0].max(p[1]).max(p[2]); - if clipped(i, p).iter().any(|&c| c) { - hit = true; - continue; - } - if top > lo && s > 1e-4 { - let b = smoothstep(SOURCE_LO, SOURCE_HI, top / clip) / s; - a[0] += b * q[0].max(0.0); - a[1] += b * q[2].max(0.0); - a[2] += b * s; - } - } - let k = 1.0 / n.max(1) as f32; - crow[x] = a.map(|v| v * k); - lrow[x] = (sum * k).max(1e-6); - touched[x] = hit; - } - for (x, nr) in nrow.iter_mut().enumerate() { - *nr = touched.get(x.saturating_sub(MARGIN)..=(x + MARGIN).min(cw - 1)).is_some_and(|t| t.iter().any(|&t| t)); - } - }); - // leave out cells near clipped pixels and on strong edges (luminance ratios to the neighbours) - let (lum, near_ref) = (&lum, &near); - let (edge_lo, edge_hi) = (EDGE_LO.exp2(), EDGE_HI.exp2()); - cells.par_chunks_mut(cw).enumerate().for_each(|(y, row)| { - let (ya, yb) = (y.saturating_sub(MARGIN), (y + MARGIN).min(ch - 1)); - let (ea, eb) = (y.saturating_sub(1), (y + 1).min(ch - 1)); - for (x, cell) in row.iter_mut().enumerate() { - if cell[2] <= 0.0 { - continue; - } - if (ya..=yb).any(|yy| near_ref.get(yy * cw + x).copied().unwrap_or(false)) { - *cell = [0.0; 3]; - continue; - } - let l = lum.get(y * cw + x).copied().unwrap_or(1.0); - let (xa, xb) = (x.saturating_sub(1), (x + 1).min(cw - 1)); - let (mut lo, mut hi) = (l, l); - for yy in ea..=eb { - for &v in lum.get(yy * cw + xa..=yy * cw + xb).unwrap_or(&[]) { - lo = lo.min(v); - hi = hi.max(v); - } - } - let keep = 1.0 - smoothstep(edge_lo, edge_hi, (hi / l).max(l / lo)); - *cell = cell.map(|v| v * keep); - } - }); - (Level { w: cw, h: ch, cells }, near) -} - -/// The quarter-resolution rim level of `img`: every `4 × 4` block's white-balanced RGB of its unclipped pixels -/// above [`RIM_LO`] of the clip level, weighted (steeply) towards the clip, as densities. Pixels next to clipped -/// ones (`margin`, by half-resolution cell) are left out, like the colour sources: they were demosaiced partly from -/// clipped samples, and lens fringes along clipped content would pass for its colour. -fn rim(img: &Rgb32f, wb: [f32; 3], clip: f32, clipped: &impl Clipped, margin: &(dyn Fn(usize, usize) -> bool + Sync)) -> Level<4> { - let (w, h) = (img.width, img.height); - let (cw, ch) = (w.div_ceil(4), h.div_ceil(4)); - let mut cells = vec![[0f32; 4]; cw * ch]; - cells.par_chunks_mut(cw).enumerate().for_each(|(y, row)| { - for (x, cell) in row.iter_mut().enumerate() { - let (mut a, mut n) = ([0f32; 4], 0usize); - for sy in 4 * y..(4 * y + 4).min(h) { - for (i, p) in img.data.get(sy * w + 4 * x..sy * w + (4 * x + 4).min(w)).unwrap_or(&[]).iter().enumerate() { - n += 1; - let top = p[0].max(p[1]).max(p[2]) / clip; - if !(RIM_LO..1.0).contains(&top) || margin((4 * x + i) / 2, sy / 2) || clipped(sy * w + 4 * x + i, p).iter().any(|&c| c) { - continue; - } - let k = ((top - RIM_LO) / (1.0 - RIM_LO)).powi(4); - for c in 0..3 { - a[c] += k * p[c] * wb[c]; - } - a[3] += k; - } - } - *cell = a.map(|v| v / n.max(1) as f32); - } - }); - Level { w: cw, h: ch, cells } -} - -/// The next coarser level: each `2 × 2` block's mean densities. -fn pull(l: &Level) -> Level { - let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2)); - let mut cells = vec![[0f32; N]; w * h]; - cells.par_chunks_mut(w).enumerate().for_each(|(y, row)| { - for (x, cell) in row.iter_mut().enumerate() { - let (mut s, mut n) = ([0f32; N], 0usize); - for (sx, sy) in [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)] { - if let Some(c) = (sx < l.w && sy < l.h).then(|| l.cells.get(sy * l.w + sx)).flatten() { - for k in 0..N { - s[k] += c[k]; - } - n += 1; - } - } - *cell = s.map(|v| v / n.max(1) as f32); - } - }); - Level { w, h, cells } -} - -/// The estimated values of the cells of `levels[0]` that `needed` marks (all of them when `None`), and of every -/// cell of the coarser levels: each level's own sources blended with the next coarser estimate. The top level is -/// its own sources' weighted mean (normalised: however sparse they are in a large empty picture, the empty part -/// never pulls the estimate anywhere), and `empty` (at zero weight) when it has none at all. -fn push(levels: &mut [Level], empty: [f32; N], needed: Option<&(dyn Fn(usize, usize) -> bool + Sync)>) { - let estimate = |cell: [f32; N], prior: [f32; N]| -> [f32; N] { - let weight = cell[N - 1]; - let d = weight + PRIOR; - std::array::from_fn(|k| if k + 1 == N { weight } else { (cell[k] + PRIOR * prior[k]) / d }) - }; - let Some(last) = levels.last_mut() else { return }; - last.cells.iter_mut().for_each(|c| { - let weight = c[N - 1]; - *c = if weight > 0.0 { std::array::from_fn(|k| if k + 1 == N { weight } else { c[k] / weight }) } else { empty }; - }); - for i in (0..levels.len().saturating_sub(1)).rev() { - let (fine, coarse) = levels.split_at_mut(i + 1); - let (Some(fine), Some(coarse)) = (fine.last_mut(), coarse.first()) else { continue }; - let w = fine.w; - let needed = needed.filter(|_| i == 0); - fine.cells.par_chunks_mut(w).enumerate().for_each(|(y, row)| { - for (x, cell) in row.iter_mut().enumerate() { - if needed.is_some_and(|f| !f(x, y)) { - continue; - } - *cell = estimate(*cell, sample(coarse, 2.0, x, y)); - } - }); - } -} - -/// How many stops two chromaticities differ by in any channel ratio. -fn unlike(a: [f32; 3], b: [f32; 3]) -> f32 { - let ratio = |i: usize, j: usize| (a[i].max(1e-6) * b[j].max(1e-6)) / (a[j].max(1e-6) * b[i].max(1e-6)); - [(0, 1), (0, 2), (1, 2)].iter().map(|&(i, j)| ratio(i, j).log2().abs()).fold(0.0f32, f32::max) -} - -/// How far channel `c` of a pixel (sensor values `p`, clipped channels `cl`) only bounds its true value from below: -/// fully once clipped, and increasingly from `FLOOR_LO` of the clip on, so that nothing compared with it jumps where -/// it clips. -fn bound(p: [f32; 3], cl: [bool; 3], clip: f32, c: usize) -> f32 { - if cl[c] { 1.0 } else { smoothstep(FLOOR_LO, 1.0, p[c] / clip) } -} - -/// How many stops the channels of a partly clipped pixel (sensor values `p`, white-balanced `q`, clipped channels -/// `cl`) contradict chromaticity `r`: how far the levels they imply spread, where a clipped channel's only bounds the -/// level from below (see [`bound`]). 0 for the pixel's own colour, whatever its level. -fn contradiction(p: [f32; 3], q: [f32; 3], cl: [bool; 3], r: [f32; 3], clip: f32) -> f32 { - let (mut lo, mut hi) = (f32::INFINITY, 0f32); - for c in 0..3 { - let level = q[c] / r[c].max(1e-3); - hi = hi.max(level); - let w = bound(p, cl, clip, c); - if r[c] > 1e-3 && w < 1.0 { - lo = lo.min(level / (1.0 - w)); - } - } - if hi > 0.0 && lo > 0.0 && lo.is_finite() { (hi / lo).log2().max(0.0) } else { 0.0 } -} - -/// The white-balanced colour of a partly clipped pixel (sensor values `p`, white-balanced `q`, clipped channels -/// `cl`) whose colour is estimated at chromaticity `r`: clipped channels rebuilt, unclipped ones kept. `None` -/// when no unclipped channel can tell the level. -fn rebuild(p: [f32; 3], q: [f32; 3], cl: [bool; 3], r: [f32; 3], clip: f32, max_level: f32) -> Option<[f32; 3]> { - // The white-balanced channel sum the unclipped channels imply: their mean, except that a channel about to clip - // counts more and more as the floor it is about to become (continuous with the neighbours where it has). - let (mut sum, mut near_clip, mut k) = (0f32, 0f32, 0usize); - for c in 0..3 { - if !cl[c] && r[c] > 1e-3 { - let s = q[c] / r[c]; - sum += s; - near_clip = near_clip.max(s * smoothstep(FLOOR_LO, 1.0, p[c] / clip)); - k += 1; - } - } - if k == 0 { - return None; - } - // Two clipped channels must not be left at their clip levels: those differ by the white-balance gains (green - // clips first), and the pair would show as magenta or red. They keep the estimate's ratio instead, at the level - // that lifts each to its clip (no channel above the clipped neutral), and so does a channel about to clip (the - // same floor, so nothing jumps where it clips). - let floor = (0..3).filter(|&c| cl[c]).map(|c| q[c] / r[c].max(1e-3)).fold(0.0f32, f32::max); - let top = r[0].max(r[1]).max(r[2]).max(1e-3); - let sum = (sum / k as f32).max(near_clip.max(floor).min(max_level / top)); - Some(std::array::from_fn(|c| if cl[c] { q[c].max(sum * r[c]) } else { q[c] })) -} - -/// Reconstruct partially clipped channels, with a neutral that is neutral in camera RGB. See -/// [`reconstruct_with`]. pub fn reconstruct(img: &mut Rgb32f, wb: [f32; 3], clip: f32) -> usize { - reconstruct_with(img, wb, clip, [1.0; 3]) + let mut craft = crate::bridge::take_craft_rgb32f(img); + let n = craft_develop::sensor::highlight::reconstruct(&mut craft, wb, clip); + crate::bridge::put_craft_rgb32f(img, craft); + n } -/// Reconstruct partially clipped channels. `clip` is the sensor clip level in normalised units (use slightly -/// below 1.0, e.g. 0.99), `wb` the white-balance multipliers that will be applied afterwards, `white` the -/// white-balanced camera RGB that the colour model applied afterwards renders neutral (`[1, 1, 1]` for a model -/// that maps the white-balanced neutral to neutral), scaled to the brightness that `[1, 1, 1]` renders at. -/// Fully clipped pixels become `white` times the brightest plausible level; partly clipped ones take the -/// chromaticity of reliable unclipped content nearby, and that of `white` where there is none. -/// Returns the number of pixels that had at least one clipped channel; the others are left exactly as they were. pub fn reconstruct_with(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3]) -> usize { - rebuild_clipped(img, wb, clip, white, &|_, p| by_value(p, clip)) + let mut craft = crate::bridge::take_craft_rgb32f(img); + let n = craft_develop::sensor::highlight::reconstruct_with(&mut craft, wb, clip, white); + crate::bridge::put_craft_rgb32f(img, craft); + n } -/// Bits of a [`reconstruct_masked`] mask entry: which channels of the pixel had a clipped sample. -pub const CLIPPED_R: u8 = 1; -pub const CLIPPED_G: u8 = 2; -pub const CLIPPED_B: u8 = 4; - -/// [`reconstruct_with`] for a binned image ([`crate::RawImage::develop_binned_masked`]): its values are block -/// means, and `mask` (one entry per pixel, bits [`CLIPPED_R`], [`CLIPPED_G`], [`CLIPPED_B`]) says which colours -/// had a clipped sample in the block. Those channels count as clipped with their mean as the lower bound of their -/// true value, so one clipped specular sample among many unclipped ones neither escapes reconstruction nor -/// (as the block's maximum would) lifts the channel to the clip level, which reads as a coloured speckle (#548). -/// A mask of the wrong length is ignored (clipping is then told by the values alone). pub fn reconstruct_masked(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], mask: &[u8]) -> usize { - if mask.len() != img.data.len() { - return reconstruct_with(img, wb, clip, white); - } - rebuild_clipped(img, wb, clip, white, &|i, p| { - let m = mask.get(i).copied().unwrap_or(0); - let v = by_value(p, clip); - [v[0] || m & CLIPPED_R != 0, v[1] || m & CLIPPED_G != 0, v[2] || m & CLIPPED_B != 0] - }) + let mut craft = crate::bridge::take_craft_rgb32f(img); + let n = craft_develop::sensor::highlight::reconstruct_masked(&mut craft, wb, clip, white, mask); + crate::bridge::put_craft_rgb32f(img, craft); + n } - -/// Which channels of pixel `i` (values `p`) are clipped. -trait Clipped: Fn(usize, &[f32; 3]) -> [bool; 3] + Sync {} -impl [bool; 3] + Sync> Clipped for F {} - -#[inline] -fn by_value(p: &[f32; 3], clip: f32) -> [bool; 3] { - [p[0] >= clip, p[1] >= clip, p[2] >= clip] -} - -/// [`reconstruct_with`], with `clipped` telling the clipped channels. -fn rebuild_clipped(img: &mut Rgb32f, wb: [f32; 3], clip: f32, white: [f32; 3], clipped: &impl Clipped) -> usize { - let (w, h) = (img.width, img.height); - let count = img.data.par_iter().enumerate().filter(|(i, p)| clipped(*i, p).iter().any(|&c| c)).count(); - if count == 0 || w == 0 || h == 0 { - return 0; - } - // a white far from the camera's neutral (or not a number) is a broken colour model: keep the camera's - let plausible = white.iter().all(|v| v.is_finite() && (1.0 / 16.0..=16.0).contains(v)); - let white = if plausible { white } else { [1.0; 3] }; - let total = white[0] + white[1] + white[2]; - let neutral = [white[0] / total, white[1] / total, white[2] / total]; - // A clipped pixel is never a source, so its chromaticity is always the bilinear sample of the - // half-resolution estimate: the pyramid starts there, straight from the image. - let (first, near) = sources(img, wb, clip, clipped); - let mut levels = vec![first]; - while let Some(l) = levels.last().filter(|l| l.w > 1 || l.h > 1) { - let next = pull(l); - levels.push(next); - } - // a clipped pixel samples the cells within one of its own, which are within one of a clipped cell - let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); - let needed = |x: usize, y: usize| (y.saturating_sub(1)..=(y + 1).min(ch - 1)).any(|yy| near.get(yy * cw + x).copied().unwrap_or(false)); - push(&mut levels, [neutral[0], neutral[2], 0.0], Some(&needed)); - // How much reliable content lies around each needed cell: its density at any scale up to [`REACH`] (level - // i's cells span 2^i cells of level 0). Near reliable content some fine level is dense with it; far from it - // only the widest one may still hold a little, and the trust fades with that. Kept in the third entry of the - // level 0 estimates, which clipped pixels sample with their colour. - let reach = REACH * w.max(h) as f32 / 2.0; - let widest = (0..levels.len()).find(|&i| (1u64 << i.min(62)) as f32 >= reach).unwrap_or(levels.len().saturating_sub(1)); - if let Some((first, coarser)) = levels.split_first_mut() { - let support: Vec<(&Level<3>, f32)> = coarser.iter().take(widest).enumerate().map(|(i, l)| (l, (1u64 << (i + 1).min(62)) as f32)).collect(); - let fw = first.w; - first.cells.par_chunks_mut(fw).enumerate().for_each(|(y, row)| { - for (x, cell) in row.iter_mut().enumerate() { - if !needed(x, y) { - continue; - } - let mut t = 0f32; - for &(l, scale) in &support { - t = t.max(smoothstep(0.0, SUPPORT, sample(l, scale, x, y)[2])); - if t >= 1.0 { - break; - } - } - cell[2] = t; - } - }); - } - let Some(field) = levels.first() else { return count }; - // the rim (level 0 of its pyramid holds the estimate), if there is one anywhere at all - let rims = { - let mut levels = vec![rim(img, wb, clip, clipped, &needed)]; - while let Some(l) = levels.last().filter(|l| l.w > 1 || l.h > 1) { - let next = pull(l); - levels.push(next); - } - push(&mut levels, [0.0; 4], None); - Some(levels).filter(|levels| levels.last().is_some_and(|top| top.cells.iter().any(|c| c[3] > 0.0))) - }; - let rim_field = rims.as_ref().and_then(|l| l.first()); - let max_level = wb.iter().cloned().fold(0.0f32, f32::max) * clip; - img.data.par_chunks_mut(w).enumerate().for_each(|(y, row)| { - for (x, px) in row.iter_mut().enumerate() { - let p = *px; - let cl = clipped(y * w + x, &p); - if !cl.iter().any(|&b| b) { - continue; - } - let q = [p[0] * wb[0], p[1] * wb[1], p[2] * wb[2]]; - // rebuilt with the colour of the reliable content around, and with neutral, blended by how much of it - // there is and how well the pixel agrees with it (blending the results, not the colours, keeps the - // estimate consistent with the pixel's own unclipped channels all the way) - let e = sample(field, 2.0, x, y); - let borrowed = [e[0], 1.0 - e[0] - e[1], e[1]]; - let edge = rim_field.map(|rim| sample(rim, 4.0, x, y)); - let mut trust = e[2].clamp(0.0, 1.0); - if trust > 0.0 { - let mut off = contradiction(p, q, cl, borrowed, clip); - if off > AGREE.0 { - off = off.min(edge.map_or(0.0, |edge| { - let s = edge[0] + edge[1] + edge[2]; - if s > 1e-6 { unlike([edge[0] / s, edge[1] / s, edge[2] / s], borrowed) } else { 0.0 } - })); - } - trust *= 1.0 - smoothstep(AGREE.0, AGREE.1, off); - } - // either applies only as far as the pixel lies past the rim nearest its clip (in any channel); nearer, the - // pixel is rebuilt with the rim's colour - let at_rim = edge.and_then(|edge| { - // stops between pixel and rim in each channel; a clipped channel's true value lies at least as far - // above the rim's as its clip, and no further below (see [`bound`]) - let ratio = (0..3) - .map(|c| { - let (a, b) = (q[c].max(1e-12), edge[c].max(1e-12)); - if a >= b { - return a / b; - } - match bound(p, cl, clip, c) { - w if w <= 0.0 => b / a, - w if w >= 1.0 => 1.0, - w => (b / a).powf(1.0 - w), - } - }) - .fold(1.0f32, f32::max); - let past = ratio.log2().min(64.0); - let k = smoothstep(NEAR_RIM, NEAR_RIM + DEPTH, past); - let s = edge[0] + edge[1] + edge[2]; - (k < 1.0 && s > 1e-6).then(|| rebuild(p, q, cl, [edge[0] / s, edge[1] / s, edge[2] / s], clip, max_level)).flatten().map(|a| (a, k)) - }); - let past_rim = |b: [f32; 3]| -> [f32; 3] { - let Some((a, k)) = at_rim else { return b }; - std::array::from_fn(|c| a[c] + (b[c] - a[c]) * k) - }; - let local = (trust > 0.0).then(|| rebuild(p, q, cl, borrowed, clip, max_level)).flatten().map(past_rim); - let plain = (trust < 1.0).then(|| rebuild(p, q, cl, neutral, clip, max_level)).flatten().map(past_rim); - let mut out = match (local, plain) { - (Some(a), Some(b)) => std::array::from_fn(|c| b[c] + (a[c] - b[c]) * trust), - (Some(a), None) | (None, Some(a)) => a, - (None, None) => { - let v = q.iter().cloned().fold(0.0f32, f32::max).max(max_level); - white.map(|c| c * v) - } - }; - // Fade into the fully clipped neutral on the way from the first channel clipping (no change: continuous - // with the unclipped neighbours) to the last one clipping (all of it: continuous with the fully clipped - // ones). The way is measured in stops: how far the rebuilt clipped channels lie above their clip, - // against how far the lowest unclipped channel still lies below its own. - let above = (0..3).filter(|&c| cl[c]).map(|c| (out[c] / q[c].max(1e-9)).max(1.0).log2()).fold(0.0f32, f32::max); - let lowest = (0..3).filter(|&c| !cl[c]).map(|c| p[c]).fold(f32::MAX, f32::min); - let below = (clip / lowest.max(1e-6)).log2().max(0.0); - let way = if above > 0.0 && lowest < clip { above / (above + below) } else { 0.0 }; - // The brightness goes over in the second half of the way, and so does the colour of a strongly coloured - // pixel; a pale one's goes over from the start ([`PALE`]). - let u = [out[0] / white[0], out[1] / white[1], out[2] / white[2]]; - let (lo, hi) = (u[0].min(u[1]).min(u[2]), u[0].max(u[1]).max(u[2])); - let saturation = if hi > 0.0 && hi.is_finite() { 1.0 - lo.max(0.0) / hi } else { 1.0 }; - let start = 0.5 * smoothstep(PALE.0, PALE.1, saturation); - let (t_level, t_colour) = (smoothstep(0.5, 1.0, way), smoothstep(start, start + 0.5, way)); - if t_colour > 0.0 { - let level = (out[0] + out[1] + out[2]) / total; - let full = q.iter().cloned().fold(0.0f32, f32::max).max(max_level); - let v = level + (full - level) * t_level; - out = std::array::from_fn(|c| out[c] + (white[c] * v - out[c]) * t_colour); - } - *px = [out[0] / wb[0], out[1] / wb[1], out[2] / wb[2]]; - } - }); - count -} - -#[cfg(test)] -mod tests; diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index 26c2dde3c3..211933b2d4 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -28,6 +28,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod binned; +mod bridge; pub mod color; mod convert; pub mod dcp; @@ -248,17 +249,7 @@ pub struct RawImage { pub lens_metadata: LensMetadata, } -/// Black-subtracted, white-normalised data covering the active area. -#[derive(Clone, Debug, PartialEq)] -pub struct Normalized { - pub width: usize, - pub height: usize, - pub cpp: usize, - /// Nominal range [0, 1] (values may exceed 1 above white or be negative from noise). - pub data: Vec, - /// CFA anchored at (0, 0) of this buffer. - pub cfa: Option, -} +pub use craft_develop::sensor::Normalized; impl RawImage { /// The description without the samples (what [`probe_info`] returns for the same file). @@ -394,15 +385,6 @@ impl RawImage { /// The result is camera RGB (not white balanced), white level = 1.0, not oriented. pub fn develop(&self, method: Method) -> Result { let n = self.normalized()?; - // with no `OpcodeList3` to apply to the whole picture first, AHD demosaics just the default crop (the same - // pixels, without demosaicing the margin and then copying the crop out of the full picture) - if self.opcodes.list3.is_empty() && method == Method::Ahd { - let c = self.develop_crop(n.width, n.height); - if let Some(rgb) = demosaic::ahd_window(&n, c) { - drop(n); - return Ok(self.stretched(rgb)); - } - } let rgb = demosaic(&n, method); drop(n); Ok(self.finish_demosaiced(rgb)) diff --git a/crates/raw/src/opcodes.rs b/crates/raw/src/opcodes.rs index 7cca133d6c..f9708a7129 100644 --- a/crates/raw/src/opcodes.rs +++ b/crates/raw/src/opcodes.rs @@ -1,332 +1,40 @@ -//! DNG opcode lists (`OpcodeList1/2/3`, DNG 1.7 chapter 7). Opcode lists are always big-endian. -//! -//! Parsed (by `craft-raw`): every opcode (unknown ones are kept as [`Opcode::Unknown`]). Applied: `WarpRectilinear`, -//! `WarpRectilinear2` (opcode 14, DNG 1.6; see [`Opcode::WarpRectilinear2`]), `FixVignetteRadial`, -//! `FixBadPixelsConstant`, `FixBadPixelsList`, `MapTable`, `MapPolynomial`, `GainMap`, `DeltaPerRow/Column`, -//! `ScalePerRow/Column`. `TrimBounds` and `WarpFisheye` are recorded but not applied. -//! -//! Opcodes run in list order, except for the DNG 1.6 skip rule ([`applied_ops`]): a `WarpRectilinear` or -//! `WarpFisheye` that immediately follows an *optional* `WarpRectilinear2` is skipped (the older opcode is the -//! fallback for readers that don't know opcode 14). -//! -//! Value convention: list 1 runs on raw sample values (16-bit scale), lists 2 and 3 on values normalised to -//! [0, 1]; table/polynomial/delta opcodes are defined on the normalised range and are rescaled accordingly. +//! DNG OpcodeList1/2/3 execution, backed by `craft_develop::sensor::opcodes`. +use crate::Rgb32f; + +pub use craft_develop::sensor::opcodes::{apply_list, is_applied}; pub use craft_raw::opcodes::{Area, Opcode, OpcodeLists, WR2_LEN, applied_ops, parse_list, wr2_factor, write_list}; -use crate::{Cfa, Rgb32f}; - -/// Whether [`apply_list`] / [`apply_list3`] implement `op`. -pub fn is_applied(op: &Opcode) -> bool { - !matches!(op, Opcode::Unknown { .. } | Opcode::TrimBounds { .. } | Opcode::WarpFisheye { .. }) -} - -fn area_iter(a: &Area, w: usize, h: usize, cpp: usize) -> impl Iterator + '_ { - let (t, l) = (a.top as usize, a.left as usize); - let (b, r) = ((a.bottom as usize).min(h), (a.right as usize).min(w)); - let (p0, p1) = (a.plane as usize, (a.plane as usize + a.planes.max(1) as usize).min(cpp)); - (t..b.max(t)) - .step_by(a.row_pitch.max(1) as usize) - .flat_map(move |y| (l..r.max(l)).step_by(a.col_pitch.max(1) as usize).flat_map(move |x| (p0..p1.max(p0)).map(move |p| (x, y, p)))) -} - -struct GainMapGrid<'a> { - points: [usize; 2], - spacing: [f64; 2], - origin: [f64; 2], - planes: usize, - gains: &'a [f32], -} - -impl GainMapGrid<'_> { - fn sample_at(&self, position: [f64; 2], plane: usize) -> f32 { - let [pv, ph] = self.points; - let mp = self.planes; - let p = plane.min(mp - 1); - let fy = if self.spacing[0] > 0.0 { ((position[0] - self.origin[0]) / self.spacing[0]).clamp(0.0, (pv - 1) as f64) } else { 0.0 }; - let fx = if self.spacing[1] > 0.0 { ((position[1] - self.origin[1]) / self.spacing[1]).clamp(0.0, (ph - 1) as f64) } else { 0.0 }; - let (y0, x0) = (fy.floor() as usize, fx.floor() as usize); - let (y1, x1) = ((y0 + 1).min(pv - 1), (x0 + 1).min(ph - 1)); - let (ty, tx) = ((fy - y0 as f64) as f32, (fx - x0 as f64) as f32); - let g = |y: usize, x: usize| self.gains[(y * ph + x) * mp + p]; - let top = g(y0, x0) + (g(y0, x1) - g(y0, x0)) * tx; - let bot = g(y1, x0) + (g(y1, x1) - g(y1, x0)) * tx; - top + (bot - top) * ty - } -} - -/// Radius normaliser: distance from the centre to the farthest image corner. -pub(crate) fn max_radius(cx: f64, cy: f64, w: f64, h: f64) -> f64 { - [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)].iter().map(|&(x, y)| (x - cx).hypot(y - cy)).fold(0.0, f64::max).max(1e-9) -} - -/// Most pixels one bad-pixel opcode repairs (the list is 64 MB, `fix_pixels`' set about twice that). Uncapped, a -/// mosaic equal to `FixBadPixelsConstant`'s constant, or one `FixBadPixelsList` rectangle over the image, lists -/// every pixel: tens of GB at [`crate::MAX_SAMPLES`]. Pixels past the cap, in list order, are left as they are. -const MAX_BAD_PIXELS: usize = 1 << 22; - -/// Apply a list to an interleaved `w × h × cpp` buffer. `cfa` (when the data is a mosaic) is used by the -/// bad-pixel opcodes. `scale` is the value of 1.0 in the buffer: 65535 for list 1 (raw 16-bit values), 1 for -/// lists 2 and 3 (normalised values). -/// Whole-image passes one opcode list may cost, all its ops together (a real DNG's list is a -/// handful of gain maps and tables). Ops past it, in list order, are left out: a list repeating a -/// full-image polynomial thousands of times was billions of evaluations on an ordinary raw. +#[cfg(test)] +use crate::Cfa; +#[cfg(test)] const MAX_LIST_PASSES: usize = 32; - -/// Sample visits `op` costs on a `w × h × cpp` buffer (coefficient evaluations for a polynomial). -fn op_cost(op: &Opcode, w: usize, h: usize, cpp: usize) -> usize { - let visits = |a: &Area| { - let rows = (a.bottom as usize).min(h).saturating_sub(a.top as usize).div_ceil(a.row_pitch.max(1) as usize); - let cols = (a.right as usize).min(w).saturating_sub(a.left as usize).div_ceil(a.col_pitch.max(1) as usize); - let planes = (a.plane as usize).saturating_add(a.planes.max(1) as usize).min(cpp).saturating_sub(a.plane as usize); - rows.saturating_mul(cols).saturating_mul(planes) - }; - match op { - Opcode::MapPolynomial { area, coefficients } => visits(area).saturating_mul(coefficients.len().max(1)), - Opcode::MapTable { area, .. } - | Opcode::GainMap { area, .. } - | Opcode::DeltaPerRow { area, .. } - | Opcode::DeltaPerColumn { area, .. } - | Opcode::ScalePerRow { area, .. } - | Opcode::ScalePerColumn { area, .. } => visits(area), - // `apply_list` does nothing for these, so they spend none of the budget - Opcode::Unknown { .. } - | Opcode::TrimBounds { .. } - | Opcode::WarpFisheye { .. } - | Opcode::WarpRectilinear { .. } - | Opcode::WarpRectilinear2 { .. } => 0, - _ => w.saturating_mul(h).saturating_mul(cpp), - } -} - -pub fn apply_list(list: &[Opcode], buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, scale: f32) { - let mut budget = w.saturating_mul(h).saturating_mul(cpp).max(1).saturating_mul(MAX_LIST_PASSES); - for op in list { - let cost = op_cost(op, w, h, cpp); - if cost > budget { - continue; - } - budget -= cost; - match op { - Opcode::MapTable { area, table } => { - let n = table.len(); - for (x, y, p) in area_iter(area, w, h, cpp) { - let v = &mut buf[(y * w + x) * cpp + p]; - let idx = ((*v / scale * 65535.0).round().max(0.0) as usize).min(n - 1); - *v = table[idx] as f32 / 65535.0 * scale; - } - } - Opcode::MapPolynomial { area, coefficients } => { - for (x, y, p) in area_iter(area, w, h, cpp) { - let v = &mut buf[(y * w + x) * cpp + p]; - let t = (*v / scale) as f64; - let r = coefficients.iter().rev().fold(0.0, |acc, &c| acc * t + c); - *v = r as f32 * scale; - } - } - Opcode::GainMap { area, points_v, points_h, spacing, origin, map_planes, gains } => { - let grid = GainMapGrid { - points: [*points_v as usize, *points_h as usize], - spacing: *spacing, - origin: *origin, - planes: *map_planes as usize, - gains, - }; - for (x, y, p) in area_iter(area, w, h, cpp) { - let rv = y as f64 / h as f64; - let rh = x as f64 / w as f64; - let g = grid.sample_at([rv, rh], p - area.plane as usize); - buf[(y * w + x) * cpp + p] *= g; - } - } - Opcode::DeltaPerRow { area, deltas } | Opcode::DeltaPerColumn { area, deltas } => { - let per_row = matches!(op, Opcode::DeltaPerRow { .. }); - for (x, y, p) in area_iter(area, w, h, cpp) { - let i = - if per_row { (y - area.top as usize) / area.row_pitch as usize } else { (x - area.left as usize) / area.col_pitch as usize }; - if let Some(d) = deltas.get(i) { - buf[(y * w + x) * cpp + p] += d * scale; - } - } - } - Opcode::ScalePerRow { area, scales } | Opcode::ScalePerColumn { area, scales } => { - let per_row = matches!(op, Opcode::ScalePerRow { .. }); - for (x, y, p) in area_iter(area, w, h, cpp) { - let i = - if per_row { (y - area.top as usize) / area.row_pitch as usize } else { (x - area.left as usize) / area.col_pitch as usize }; - if let Some(s) = scales.get(i) { - buf[(y * w + x) * cpp + p] *= s; - } - } - } - Opcode::FixVignetteRadial { k, center } => { - let (cx, cy) = (center[0] * w as f64, center[1] * h as f64); - let m = max_radius(cx, cy, w as f64, h as f64); - for y in 0..h { - for x in 0..w { - let r2 = ((x as f64 + 0.5 - cx).powi(2) + (y as f64 + 0.5 - cy).powi(2)) / (m * m); - let g = 1.0 + r2 * (k[0] + r2 * (k[1] + r2 * (k[2] + r2 * (k[3] + r2 * k[4])))); - for p in 0..cpp { - buf[(y * w + x) * cpp + p] *= g as f32; - } - } - } - } - Opcode::FixBadPixelsConstant { constant, .. } => { - let c = (*constant as f64 / 65535.0 * scale as f64) as f32; - let bad: Vec<(usize, usize)> = - (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| cpp == 1 && buf[y * w + x] == c).take(MAX_BAD_PIXELS).collect(); - fix_pixels(buf, w, h, cpp, cfa, &bad); - } - Opcode::FixBadPixelsList { points, rects, .. } => { - let mut bad: Vec<(usize, usize)> = - points.iter().map(|&(r, c)| (c as usize, r as usize)).filter(|&(x, y)| x < w && y < h).take(MAX_BAD_PIXELS).collect(); - 'rects: for r in rects { - let [t, l, b, rr] = r.map(|v| v as usize); - for y in t..b.min(h) { - for x in l..rr.min(w) { - if bad.len() >= MAX_BAD_PIXELS { - break 'rects; - } - bad.push((x, y)); - } - } - } - fix_pixels(buf, w, h, cpp, cfa, &bad); - } - _ => {} - } - } -} - -/// Replace listed pixels with the mean of the nearest same-colour neighbours that are not themselves bad. -fn fix_pixels(buf: &mut [f32], w: usize, h: usize, cpp: usize, cfa: Option<&Cfa>, bad: &[(usize, usize)]) { - if bad.is_empty() { - return; - } - let mut is_bad = std::collections::HashSet::with_capacity(bad.len()); - for &b in bad { - is_bad.insert(b); - } - let step: isize = match cfa { - Some(c) if c.width == 2 && c.height == 2 => 2, - Some(c) => c.width.max(c.height) as isize, - None => 1, - }; - for &(x, y) in bad { - for p in 0..cpp { - let mut sum = 0.0; - let mut n = 0; - for (dx, dy) in [(-step, 0), (step, 0), (0, -step), (0, step), (-step, -step), (step, step), (-step, step), (step, -step)] { - let (nx, ny) = (x as isize + dx, y as isize + dy); - if nx < 0 || ny < 0 || nx >= w as isize || ny >= h as isize || is_bad.contains(&(nx as usize, ny as usize)) { - continue; - } - sum += buf[(ny as usize * w + nx as usize) * cpp + p]; - n += 1; - } - if n > 0 { - buf[(y * w + x) * cpp + p] = sum / n as f32; - } - } - } -} - -/// Most full-image passes of one `OpcodeList3`: every warp record is a full-image allocation and resample -/// pass and every bad-pixel record a full flatten-and-rebuild, and a hostile record may repeat either -/// thousands of times. Real DNGs carry at most a couple; passes past the cap are skipped. +#[cfg(test)] const MAX_LIST3_PASSES: usize = 8; -/// Apply `OpcodeList3` (on the demosaiced RGB image, values normalised to [0, 1]). +#[cfg(test)] +pub(crate) fn max_radius(cx: f64, cy: f64, w: f64, h: f64) -> f64 { + let corners = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)]; + corners.iter().map(|&(x, y)| (x - cx).hypot(y - cy)).fold(0.0f64, f64::max).max(1e-9) +} + pub fn apply_list3(list: &[Opcode], img: &mut Rgb32f) { - if list.is_empty() { - return; - } - let (w, h) = (img.width, img.height); - let mut passes = 0usize; - for op in applied_ops(list) { - match op { - Opcode::WarpRectilinear { planes, center } => { - if passes < MAX_LIST3_PASSES { - passes += 1; - *img = warp_rectilinear(img, planes, *center); - } - } - Opcode::WarpRectilinear2 { planes, center, reciprocal, .. } => { - if passes < MAX_LIST3_PASSES { - passes += 1; - *img = warp_rectilinear2(img, planes, *center, *reciprocal); - } - } - Opcode::WarpFisheye { .. } | Opcode::TrimBounds { .. } | Opcode::Unknown { .. } => {} - other => { - if passes >= MAX_LIST3_PASSES { - continue; - } - passes += 1; - let mut flat: Vec = img.data.iter().flat_map(|p| *p).collect(); - apply_list(std::slice::from_ref(other), &mut flat, w, h, 3, None, 1.0); - for (d, c) in img.data.iter_mut().zip(flat.as_chunks::<3>().0) { - *d = [c[0], c[1], c[2]]; - } - } - } - } + let mut craft = crate::bridge::take_craft_rgb32f(img); + craft_develop::sensor::opcodes::apply_list3(list, &mut craft); + crate::bridge::put_craft_rgb32f(img, craft); } -/// DNG `WarpRectilinear`: for each output pixel, the source position is the radial + tangential model around the -/// optical centre, with coordinates normalised by the distance to the farthest corner. pub fn warp_rectilinear(img: &Rgb32f, planes: &[[f64; 6]], center: [f64; 2]) -> Rgb32f { - let (w, h) = (img.width, img.height); - let (cx, cy) = (center[0] * (w as f64 - 1.0), center[1] * (h as f64 - 1.0)); - let m = max_radius(cx, cy, w as f64 - 1.0, h as f64 - 1.0); - let mut out = Rgb32f::new(w, h); - let coef = |p: usize| planes[p.min(planes.len() - 1)]; - lightcraft_raster::par_rows(&mut out.data, w, |y, row| { - for (x, px) in row.iter_mut().enumerate() { - for (c, v) in px.iter_mut().enumerate() { - let [kr0, kr1, kr2, kr3, kt0, kt1] = coef(c); - let dx = (x as f64 - cx) / m; - let dy = (y as f64 - cy) / m; - let r2 = dx * dx + dy * dy; - let f = kr0 + r2 * (kr1 + r2 * (kr2 + r2 * kr3)); - let sx = dx * f + kt0 * 2.0 * dx * dy + kt1 * (r2 + 2.0 * dx * dx); - let sy = dy * f + kt1 * 2.0 * dx * dy + kt0 * (r2 + 2.0 * dy * dy); - let (fx, fy) = (cx + m * sx, cy + m * sy); - *v = img.sample_bilinear(fx as f32 + 0.5, fy as f32 + 0.5)[c]; - } - } - }); - out + crate::bridge::from_craft_rgb32f(craft_develop::sensor::opcodes::warp_rectilinear(&crate::bridge::to_craft_rgb32f(img), planes, center)) } -/// DNG 1.6 `WarpRectilinear2`: the `WarpRectilinear` geometry (centre and normalisation as there), with the radial -/// factor of [`wr2_factor`] in place of the even polynomial in `r²`. A pixel whose factor is not finite stays put. pub fn warp_rectilinear2(img: &Rgb32f, planes: &[[f64; WR2_LEN]], center: [f64; 2], reciprocal: bool) -> Rgb32f { - let (w, h) = (img.width, img.height); - let Some(last) = planes.len().checked_sub(1) else { return img.clone() }; - let mut out = Rgb32f::new(w, h); - let (cx, cy) = (center[0] * (w as f64 - 1.0), center[1] * (h as f64 - 1.0)); - let m = max_radius(cx, cy, w as f64 - 1.0, h as f64 - 1.0); - lightcraft_raster::par_rows(&mut out.data, w, |y, row| { - for (x, px) in row.iter_mut().enumerate() { - for (c, v) in px.iter_mut().enumerate() { - let Some(k) = planes.get(c.min(last)) else { continue }; - let dx = (x as f64 - cx) / m; - let dy = (y as f64 - cy) / m; - let r2 = dx * dx + dy * dy; - let (sx, sy) = match wr2_factor(k, reciprocal, r2.sqrt()) { - Some(f) => { - (dx * f + k[15] * 2.0 * dx * dy + k[16] * (r2 + 2.0 * dx * dx), dy * f + k[16] * 2.0 * dx * dy + k[15] * (r2 + 2.0 * dy * dy)) - } - None => (dx, dy), - }; - let (fx, fy) = (cx + m * sx, cy + m * sy); - *v = img.sample_bilinear(fx as f32 + 0.5, fy as f32 + 0.5)[c]; - } - } - }); - out + crate::bridge::from_craft_rgb32f(craft_develop::sensor::opcodes::warp_rectilinear2( + &crate::bridge::to_craft_rgb32f(img), + planes, + center, + reciprocal, + )) } #[cfg(test)]