pipeline, raw, inpaint: delegate extracted #587 modules to craft-develop (#4656)

* pipeline, raw, inpaint: delegate extracted #587 modules to craft-develop

* raw: fix craft_raw ColorData/RawImage bridge and opcode test imports

* raw: remove unused to_craft_mat3 in bridge

* pipeline: fix craft-develop bridge, Cargo.toml, Planes Clone, and light_v3 tests

* pipeline: remove unused is_bw, from_craft_mat3, and srgb_to_linear

* raw, pipeline: preserve lightcraft_geom::Orientation in SourcePlacement

* pipeline: use camera-space wb_matrix_for in white_balance and scene_linear_pre

* pipeline: forward masks and LocalAdjustments in to_craft_settings

* pipeline: fill remaining LocalAdjustments fields in bridge
This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-22 16:57:48 -05:00
1 parent bbb529f64b
commit f3aa598c69
36 files changed
+902 -9507

No files matched your search

Generated
+43 -35
View File
@@ -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",
+31 -28
View File
@@ -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" }
+1 -1
View File
@@ -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"
+1
View File
@@ -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 }
+2 -57
View File
@@ -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<bool> = (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};
-207
View File
@@ -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<f32> = 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::<f32>() / 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<f32> + Sync + Send) -> Vec<f32> {
#[cfg(not(target_arch = "wasm32"))]
let planes: Vec<Vec<f32>> = 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<Vec<f32>> = (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<f32> {
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<f32> = (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<bool> {
(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<f32> = (0..w * h).map(|i| 0.2 + 0.005 * (i % w) as f32 + 0.003 * (i / w) as f32).collect();
let mut v: Vec<f32> = 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}");
}
}
-587
View File
@@ -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<f32>,
hole: Vec<bool>,
}
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<u32> {
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<f32>,
hole: &'a [bool],
/// Valid source centres: the whole patch is inside the grid and contains no hole pixel.
valid: Vec<bool>,
valid_list: Vec<(i32, i32)>,
/// Target centres (patch overlaps the hole), row-major.
targets: Vec<bool>,
/// 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<f32> = 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<f32>)> {
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<Vec<(usize, Vec<f32>)>> = 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<Vec<(usize, Vec<f32>)>> = (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<Vec<f32>> {
// 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<Option<Vec<f32>>, 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<f32>)> = 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<f32> {
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<bool> {
(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<f32> = (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<f32> = 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}");
}
}
+4
View File
@@ -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 }
+31 -281
View File
@@ -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<f64> {
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<craft_color_transform::Xy>> =
(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))
}
+395
View File
@@ -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<CraftPoint> {
pts.iter().map(|p| CraftPoint::new(p.x, p.y)).collect()
}
fn from_craft_points(pts: &[CraftPoint]) -> Vec<lightcraft_geom::Point> {
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);
}
+16 -442
View File
@@ -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<PointK>,
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))
}
File diff suppressed because it is too large. Load diff
+16 -222
View File
@@ -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 }
}
}
+2 -7
View File
@@ -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<bool> = std::sync::OnceLock::new();
+24 -413
View File
@@ -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<Unpacked> {
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<Operator> {
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<Operator>,
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<LightOps> {
if !applies(s, info) {
return None;
}
let l = &s.light;
let ops: Vec<Operator> = 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<LinearOperator>),
}
impl PreviewOps {
pub(crate) fn new(exact: &LightOps, encode: &impl Fn(f32) -> f32) -> Option<Self> {
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]]>,
}
+2 -314
View File
@@ -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::*;
File diff suppressed because it is too large. Load diff
+28 -33
View File
@@ -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);
}
+2 -142
View File
@@ -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<String>,
}
impl Lut3d {
/// Parse a `.cube` file.
pub fn parse_cube(text: &str) -> Result<Lut3d, String> {
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<HashMap<String, Arc<Lut3d>>> {
static R: OnceLock<RwLock<HashMap<String, Arc<Lut3d>>>> = 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<Arc<Lut3d>> {
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::<Vec<_>>().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::<Vec<_>>().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};
File diff suppressed because it is too large. Load diff
-352
View File
@@ -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::<f64>() / 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<f32> = 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::<f32>()
}
/// 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::<f32>();
}
*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<std::time::Instant>| {
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::<f32>() * 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);
}
}
+10 -300
View File
@@ -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<Point>, 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<f64> = 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)
}
}
}
+9 -39
View File
@@ -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]] {
+1 -1
View File
@@ -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),
+3
View File
@@ -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 }
+82
View File
@@ -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(),
}
}
+44 -382
View File
@@ -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<f64> {
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<Mat3>; 2], g: f64) -> Option<Mat3> {
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<craft_develop::sensor::color::CameraTransform> 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<Mat3> {
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<Xy> {
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))
}
+6 -389
View File
@@ -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<Rgb32f> {
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<f32> = 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::<f32>() / 9.0;
let hp: Vec<f32> =
(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::<f32>()
* 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)
}
-179
View File
@@ -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<u8> = (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
}
-78
View File
@@ -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
}
-89
View File
@@ -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<f32> {
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
}
-281
View File
@@ -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<f32> {
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<f32> = 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<f32> = (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)));
}
}
+6 -272
View File
@@ -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.
//!
//! (<https://helpx.adobe.com/camera-raw/digital-negative.html>, "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<GainEval<'_>>;
}
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<GainEval<'_>> {
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<f32>) -> 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);
}
}
+19 -521
View File
@@ -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<const N: usize> {
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<const N: usize>(l: &Level<N>, 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<bool>) {
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<const N: usize>(l: &Level<N>) -> Level<N> {
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<const N: usize>(levels: &mut [Level<N>], 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<F: Fn(usize, &[f32; 3]) -> [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;
+2 -20
View File
@@ -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<f32>,
/// CFA anchored at (0, 0) of this buffer.
pub cfa: Option<Cfa>,
}
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<Rgb32f> {
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))
+24 -316
View File
@@ -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<Item = (usize, usize, usize)> + '_ {
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<f32> = 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)]