diff --git a/Cargo.lock b/Cargo.lock index 2e30cbb47b..cd78730948 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1190,16 +1190,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=7f30d664695cd5ce14fc30659d36c3e32f234247#7f30d664695cd5ce14fc30659d36c3e32f234247" -dependencies = [ - "md-5", - "rayon", -] - -[[package]] -name = "craft-cms" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=eeb134def2daa7e03512b4946bd59d6b419b9484#eeb134def2daa7e03512b4946bd59d6b419b9484" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "md-5", "rayon", @@ -1208,30 +1199,38 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +source = "git+https://github.com/storytold/craft-libs?rev=f589ff485707007e814671229d0f4e77bc06968a#f589ff485707007e814671229d0f4e77bc06968a" dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-dds" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" +dependencies = [ + "rayon", +] + [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" [[package]] name = "craft-gainmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=9dcbd90c7d16e1a668b3afa057e940e2db328b93#9dcbd90c7d16e1a668b3afa057e940e2db328b93" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "thiserror 2.0.21", ] @@ -1239,7 +1238,7 @@ dependencies = [ [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "gif", "image", @@ -1248,16 +1247,21 @@ dependencies = [ [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4ffa307f1a0a6fbd8897318cc719440ab06e9c63#4ffa307f1a0a6fbd8897318cc719440ab06e9c63" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "heic-rs", "rayon", ] +[[package]] +name = "craft-http-url" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=c247a085be0b2db5456f1f9178024d6a12e4cc57#c247a085be0b2db5456f1f9178024d6a12e4cc57" + [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1280,12 +1284,14 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a#5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "avif-serialize", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a)", + "craft-dds", + "craft-jpeg", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3)", + "craft-video", "crc32fast", "exr", "flate2", @@ -1306,62 +1312,19 @@ dependencies = [ "zune-jpegxl", ] -[[package]] -name = "craft-image-codecs" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" -dependencies = [ - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", - "crc32fast", - "exr", - "flate2", - "half", - "hayro-jpeg2000", - "image", - "image-webp", - "jpeg-encoder 0.6.1", - "png", - "rayon", - "serde_json", - "thiserror 2.0.21", - "tiff", - "zune-core", - "zune-jpeg", - "zune-jpegxl", -] - [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=478c50560d3c6fad3d613af2a30b35c3bc9f4c0f#478c50560d3c6fad3d613af2a30b35c3bc9f4c0f" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "rayon", "thiserror 2.0.21", ] -[[package]] -name = "craft-jpeg" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a#5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "craft-jpeg" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" -dependencies = [ - "thiserror 2.0.21", -] - [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=478c50560d3c6fad3d613af2a30b35c3bc9f4c0f#478c50560d3c6fad3d613af2a30b35c3bc9f4c0f" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "jixel", "jxl-oxide", @@ -1371,24 +1334,19 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6#5c91598ccc86537a779f438d520fa6406c26efe6" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "craft-media" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" - [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a#5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "brotli-decompressor 6.0.1", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3)", "quick-xml 0.41.0", "serde", ] @@ -1396,11 +1354,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +source = "git+https://github.com/storytold/craft-libs?rev=f589ff485707007e814671229d0f4e77bc06968a#f589ff485707007e814671229d0f4e77bc06968a" dependencies = [ "brotli-decompressor 6.0.1", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f589ff485707007e814671229d0f4e77bc06968a)", "quick-xml 0.41.0", "serde", ] @@ -1408,7 +1366,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "chrono", "craft-codepage", @@ -1418,7 +1376,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0fd30aeb3e02207d9d4c7c601540d9da45abf8de#0fd30aeb3e02207d9d4c7c601540d9da45abf8de" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "flate2", "roxmltree", @@ -1427,7 +1385,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=bea6ed1ff031b81df2d64be470485c1ca808847e#bea6ed1ff031b81df2d64be470485c1ca808847e" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "thiserror 2.0.21", ] @@ -1435,7 +1393,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=16d838105b07965832bb43132880176f299634d5#16d838105b07965832bb43132880176f299634d5" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" dependencies = [ "encoding_rs", "flate2", @@ -1446,12 +1404,12 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +source = "git+https://github.com/storytold/craft-libs?rev=f589ff485707007e814671229d0f4e77bc06968a#f589ff485707007e814671229d0f4e77bc06968a" dependencies = [ "chrono", "craft-crw", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f589ff485707007e814671229d0f4e77bc06968a)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f589ff485707007e814671229d0f4e77bc06968a)", "jxl-oxide", "miniz_oxide 0.9.1", "rayon", @@ -1464,7 +1422,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a#5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "serde", "thiserror 2.0.21", @@ -1473,7 +1431,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" +source = "git+https://github.com/storytold/craft-libs?rev=f589ff485707007e814671229d0f4e77bc06968a#f589ff485707007e814671229d0f4e77bc06968a" dependencies = [ "serde", "thiserror 2.0.21", @@ -1482,7 +1440,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1503,7 +1461,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "chrono", "dunce", @@ -1530,27 +1488,18 @@ dependencies = [ [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6#5c91598ccc86537a779f438d520fa6406c26efe6" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6)", + "craft-media", "rav1e", "rayon", "thiserror 2.0.21", ] -[[package]] -name = "craft-video" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845#c28356d400aed7575b04ec1551b4665107cfe845" -dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", - "thiserror 2.0.21", -] - [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "egui", "objc2 0.6.5", @@ -1561,7 +1510,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2d4b8b8ecd79f87c847961901c40305e7f448d6f#2d4b8b8ecd79f87c847961901c40305e7f448d6f" +source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3989,18 +3938,17 @@ name = "lightcraft-codecs" version = "0.21.1" dependencies = [ "bytemuck", - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7f30d664695cd5ce14fc30659d36c3e32f234247)", + "craft-cms", "craft-gainmap", "craft-gif", "craft-heif", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a)", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=478c50560d3c6fad3d613af2a30b35c3bc9f4c0f)", + "craft-image-codecs", + "craft-jpeg", "craft-jxl", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3)", "craft-psd", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", - "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5c91598ccc86537a779f438d520fa6406c26efe6)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3)", + "craft-video", "dhat", "jpeg-encoder 0.7.1", "lightcraft-color", @@ -4080,7 +4028,8 @@ dependencies = [ "craft-mime", "craft-pdf", "craft-plist", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f589ff485707007e814671229d0f4e77bc06968a)", "crc32fast", "fs4", "harfrust 0.13.3", @@ -4137,6 +4086,7 @@ dependencies = [ name = "lightcraft-fetch" version = "0.21.1" dependencies = [ + "craft-http-url", "log", "rustls", "rustls-rustcrypto", @@ -4237,10 +4187,10 @@ version = "0.21.1" dependencies = [ "chrono", "craft-heif", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3)", "craft-psd", "craft-raw", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3)", "lightcraft-geom", "proptest", "serde", @@ -4251,8 +4201,8 @@ dependencies = [ name = "lightcraft-pipeline" version = "0.21.1" dependencies = [ - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=eeb134def2daa7e03512b4946bd59d6b419b9484)", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-cms", + "craft-image-codecs", "dhat", "lightcraft-color", "lightcraft-develop", @@ -4271,7 +4221,7 @@ dependencies = [ name = "lightcraft-preview" version = "0.21.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-image-codecs", "lightcraft-raster", "log", "siphasher", @@ -4294,10 +4244,11 @@ name = "lightcraft-raw" version = "0.21.1" dependencies = [ "chrono", - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-image-codecs", "craft-jxl", "craft-raw", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f589ff485707007e814671229d0f4e77bc06968a)", "dhat", "jixel", "lightcraft-color", @@ -4317,7 +4268,7 @@ dependencies = [ name = "lightcraft-scenes" version = "0.21.1" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c28356d400aed7575b04ec1551b4665107cfe845)", + "craft-image-codecs", "lightcraft-color", "lightcraft-raster", "rayon", diff --git a/Cargo.toml b/Cargo.toml index 67d282b498..451af45bca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,33 +10,31 @@ rust-version = "1.95" repository = "https://github.com/storytold/lightcraft" [workspace.dependencies] -craft-cms-profile = { package = "craft-cms", git = "https://github.com/storytold/craft-libs", rev = "eeb134def2daa7e03512b4946bd59d6b419b9484" } -craft-plist = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bea6ed1ff031b81df2d64be470485c1ca808847e" } -craft-pdf-print = { package = "craft-pdf", git = "https://github.com/storytold/craft-libs", rev = "0fd30aeb3e02207d9d4c7c601540d9da45abf8de", default-features = false, features = ["write-raster"] } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +craft-cms-profile = { package = "craft-cms", git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } +craft-plist = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } +craft-pdf-print = { package = "craft-pdf", git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", default-features = false, features = ["write-raster"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", features = ["serde"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } # Canon CRW decoder shared with the other Craft apps -craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "2d4b8b8ecd79f87c847961901c40305e7f448d6f" } -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "7f30d664695cd5ce14fc30659d36c3e32f234247" } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", version = "0.1.0" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b77af389f30bb10de10d8436ca9b39fe94e3bb67", features = ["frames"] } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "478c50560d3c6fad3d613af2a30b35c3bc9f4c0f", default-features = false, features = ["decode", "encode"] } +craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", version = "0.1.0" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", features = ["frames"] } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", 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 = "c28356d400aed7575b04ec1551b4665107cfe845" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "478c50560d3c6fad3d613af2a30b35c3bc9f4c0f" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" } -craft-video = { git = "https://github.com/storytold/craft-libs", rev = "5c91598ccc86537a779f438d520fa6406c26efe6", features = ["av1", "av1-large-encode", "threads"] } -# Isolate AVIF threading from the existing PNG/TIFF/WebP shared revision. -craft-avif-encode = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "5ac7c9664c8d54aaf69d1bb826e187686c1a4e1a", default-features = false, features = ["avif", "threads"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "2d4b8b8ecd79f87c847961901c40305e7f448d6f" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } +craft-video = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", features = ["av1", "av1-large-encode", "threads"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } # 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 = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", 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 = "9dcbd90c7d16e1a668b3afa057e940e2db328b93" } +craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } # PSD/PSB: the header, colour mode data and image resources (craft-libs#885). -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "16d838105b07965832bb43132880176f299634d5" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890" } jpeg-encoder = { version = "0.7", default-features = false, features = ["std"] } # internal lightcraft-denoise-core = { path = "crates/denoise-core" } @@ -48,8 +46,10 @@ 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 = "c28356d400aed7575b04ec1551b4665107cfe845" } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "c28356d400aed7575b04ec1551b4665107cfe845" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "f589ff485707007e814671229d0f4e77bc06968a" } +# Match the RAW writer’s TIFF type without changing other app TIFF consumers. +craft-raw-tiff = { package = "craft-tiff", git = "https://github.com/storytold/craft-libs", rev = "f589ff485707007e814671229d0f4e77bc06968a" } lightcraft-raw = { path = "crates/raw" } lightcraft-codecs = { path = "crates/codecs" } lightcraft-meta = { path = "crates/meta" } @@ -68,7 +68,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 = "4ffa307f1a0a6fbd8897318cc719440ab06e9c63", default-features = false } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", default-features = false } lightcraft-segment = { path = "crates/segment" } lightcraft-geocode = { path = "crates/geocode" } lightcraft-slideshow = { path = "crates/slideshow" } diff --git a/README.md b/README.md index a3e4981360..2e817614ba 100644 --- a/README.md +++ b/README.md @@ -499,8 +499,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft Without it LightCraft builds and runs the same, but Chinese and Japanese text have no glyphs. Fonts are never committed to this repo — what goes there is described in the [craft-fonts README](https://github.com/storytold/craft-fonts#readme). -**Interface language:** **Edit → Language** (English, 简体中文, 繁體中文(台灣), 日本語, Português (Brasil), Español, Deutsch, Русский, Français, Українська, Polski, Čeština, Italiano, ქართული, Svenska, Suomi, Bahasa Indonesia, Tiếng Việt) or **Settings → General → -Language**; the choice applies immediately and persists. See [docs/localization.md](docs/localization.md). +**Interface language:** **Settings → General → Language** (English, 简体中文, 繁體中文(台灣), 日本語, Português (Brasil), Español, Deutsch, Русский, Français, Українська, Polski, Čeština, Italiano, ქართული, Svenska, Suomi, Bahasa Indonesia, Tiếng Việt); the choice applies immediately and persists. See [docs/localization.md](docs/localization.md). **Logs:** the desktop app writes its log to standard error and to `logs/lightcraft.log` in its settings folder (Linux `$XDG_CONFIG_HOME/lightcraft/logs/`, by default `~/.config/lightcraft/logs/`; macOS diff --git a/README.zh-hans.md b/README.zh-hans.md index a577a8db7b..054f2c1e81 100644 --- a/README.zh-hans.md +++ b/README.zh-hans.md @@ -422,8 +422,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft 不指定它时,LightCraft 构建和运行的方式完全相同,只是中文和日文文字没有字形。字体从不提交到 本仓库。 -**界面语言:** **编辑 → 语言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français)或 **设置 → 一般 → -语言**;选择立即生效并会保留。见 [docs/localization.md](docs/localization.md)。 +**界面语言:** **设置 → 一般 → 语言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français);选择立即生效并会保留。见 [docs/localization.md](docs/localization.md)。 **日志:** 桌面应用把日志写到标准错误,以及设置文件夹里的 `logs/lightcraft.log` (Linux `$XDG_CONFIG_HOME/lightcraft/logs/`,默认 `~/.config/lightcraft/logs/`;macOS diff --git a/README.zh-hant.md b/README.zh-hant.md index f2c223897a..c8079956f0 100644 --- a/README.zh-hant.md +++ b/README.zh-hant.md @@ -447,8 +447,7 @@ CRAFT_FONTS_DIR=../craft-fonts cargo run --release -p lightcraft 不指定它時,LightCraft 一樣能建置與執行,只是中文和日文文字沒有字形。字型從不提交到 本儲存庫,字型的收錄規範記載在該儲存庫:見 [craft-fonts README](https://github.com/storytold/craft-fonts#readme)。 -**介面語言:** **編輯 → 語言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français、Українська、Čeština、ქართული)或 **設定 → 一般 → -語言**;選擇後立即生效並會保留。詳見 [docs/localization.md](docs/localization.md)。 +**介面語言:** **設定 → 一般 → 語言**(English、简体中文、繁體中文(台灣)、日本語、Português (Brasil)、Español、Deutsch、Русский、Français、Українська、Čeština、ქართული);選擇後立即生效並會保留。詳見 [docs/localization.md](docs/localization.md)。 **記錄檔:** 桌面應用程式會把記錄檔寫到標準錯誤輸出,以及設定資料夾裡的 `logs/lightcraft.log` (Linux `$XDG_CONFIG_HOME/lightcraft/logs/`,預設為 `~/.config/lightcraft/logs/`;macOS diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 08c1c0bc0d..c51bb5c190 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -29,7 +29,7 @@ craft-jxl = { workspace = true, optional = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-video = { workspace = true, optional = true } -craft-avif-encode = { workspace = true, optional = true } +craft-image-codecs = { workspace = true, optional = true, features = ["avif", "threads"] } [features] default = ["parallel", "jxl", "avif"] @@ -41,7 +41,7 @@ jxl = ["dep:craft-jxl"] # PhotoCraft); `cargo xtask ci` clippies and tests it (`--features heif`), releases don't ship it yet. heif = ["dep:craft-heif"] ## AVIF/AV1 encoding via craft-image-codecs / craft-video (pure Rust), plus the shared AVIF decoder. Native targets only; a no-op on wasm32. -avif = ["dep:craft-video", "dep:craft-avif-encode", "craft-image-codecs/avif-decode"] +avif = ["dep:craft-video", "dep:craft-image-codecs", "craft-image-codecs/avif-decode"] [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) diff --git a/crates/codecs/src/encode.rs b/crates/codecs/src/encode.rs index 86be1c1ca7..d2f107dc9e 100644 --- a/crates/codecs/src/encode.rs +++ b/crates/codecs/src/encode.rs @@ -290,23 +290,9 @@ pub fn encode_avif(img: &EncodeImage, quality: u8, speed: u8, meta: &EncodeMeta) img.validate()?; #[cfg(all(feature = "avif", not(target_arch = "wasm32")))] { - // Keep AVIF on its threading-capable shared revision without changing other codecs. - use craft_avif_encode::{ChannelLayout, Image}; - let n = img.width as usize * img.height as usize * img.channels as usize; - let layout = match img.channels { - 1 => ChannelLayout::Gray, - 2 => ChannelLayout::GrayA, - 3 => ChannelLayout::Rgb, - _ => ChannelLayout::Rgba, - }; - let mut ic_img = match img.samples { - Samples::U8(s) => Image::from_u8(img.width, img.height, layout, s[..n].to_vec()), - Samples::U16(s) => Image::from_u16(img.width, img.height, layout, &s[..n]), - Samples::F32(_) => return Err(Error::Encode("AVIF encoder needs 8- or 16-bit samples".into())), - } - .map_err(|e| Error::Encode(e.to_string()))?; + let mut ic_img = shared_image(img, Some("AVIF encoder needs 8- or 16-bit samples"))?; ic_img.meta.exif = meta.exif.map(|e| e.to_vec()); - craft_avif_encode::encode_avif_with_speed(&ic_img, quality, speed).map_err(|e| Error::Encode(e.to_string())) + craft_image_codecs::encode_avif_with_speed(&ic_img, quality, speed).map_err(|e| Error::Encode(e.to_string())) } #[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))] { @@ -384,10 +370,10 @@ pub fn encode_avif_hdr(width: u32, height: u32, rgb: &[f32], quality: u8, speed: { let _ = (w, h, n); let t = match transfer { - HdrTransfer::Pq => craft_avif_encode::HdrTransfer::Pq, - HdrTransfer::Hlg => craft_avif_encode::HdrTransfer::Hlg, + HdrTransfer::Pq => craft_image_codecs::HdrTransfer::Pq, + HdrTransfer::Hlg => craft_image_codecs::HdrTransfer::Hlg, }; - craft_avif_encode::encode_avif_hdr(width, height, rgb, quality, speed, meta.exif, t).map_err(|e| Error::Encode(e.to_string())) + craft_image_codecs::encode_avif_hdr(width, height, rgb, quality, speed, meta.exif, t).map_err(|e| Error::Encode(e.to_string())) } #[cfg(not(all(feature = "avif", not(target_arch = "wasm32"))))] { diff --git a/crates/codecs/src/exif.rs b/crates/codecs/src/exif.rs index 79f4d52753..1f8496af91 100644 --- a/crates/codecs/src/exif.rs +++ b/crates/codecs/src/exif.rs @@ -2,12 +2,14 @@ //! thumbnail, colour-space hint). Full EXIF parsing lives in `lightcraft-meta`. /// Byte-order aware reader over a TIFF-structured blob. +#[cfg(test)] #[derive(Clone, Copy)] pub(crate) struct Tiff<'a> { pub data: &'a [u8], le: bool, } +#[cfg(test)] #[derive(Clone, Copy, Debug)] pub(crate) struct Entry { pub tag: u16, @@ -17,6 +19,7 @@ pub(crate) struct Entry { pub value_pos: usize, } +#[cfg(test)] impl<'a> Tiff<'a> { pub fn new(data: &'a [u8]) -> Option> { let le = match data.get(0..2)? { diff --git a/crates/codecs/src/gainmap.rs b/crates/codecs/src/gainmap.rs index 5ffad09dd5..370c5540c4 100644 --- a/crates/codecs/src/gainmap.rs +++ b/crates/codecs/src/gainmap.rs @@ -16,33 +16,6 @@ pub use craft_gainmap::{GainImage, GainMapMeta, GainMapOptions, ISO_URN, apply, use crate::encode::{EncodeImage, EncodeMeta, Samples, jpeg_app_segments, xmp_segment}; use crate::{ChromaSubsampling, Error, Format, Result, jpeg}; -/// Offsets within the MPF payload (from "MPF\0"): the endian field, then the index IFD (3 tags). -const MPF_ENTRIES_FROM_ENDIAN: usize = 8 + 2 + 3 * 12 + 4; - -/// The primary image's MPF payload, entry sizes and offset to be patched once the file exists. -fn mpf_placeholder() -> Vec { - let mut p = b"MPF\0MM".to_vec(); - p.extend_from_slice(&42u16.to_be_bytes()); - p.extend_from_slice(&8u32.to_be_bytes()); // first IFD - p.extend_from_slice(&3u16.to_be_bytes()); - let tag = |p: &mut Vec, tag: u16, ty: u16, count: u32, value: [u8; 4]| { - p.extend_from_slice(&tag.to_be_bytes()); - p.extend_from_slice(&ty.to_be_bytes()); - p.extend_from_slice(&count.to_be_bytes()); - p.extend_from_slice(&value); - }; - tag(&mut p, 0xB000, 7, 4, *b"0100"); // MPFVersion - tag(&mut p, 0xB001, 4, 1, 2u32.to_be_bytes()); // NumberOfImages - tag(&mut p, 0xB002, 7, 32, (MPF_ENTRIES_FROM_ENDIAN as u32).to_be_bytes()); // MPEntry - p.extend_from_slice(&0u32.to_be_bytes()); // no next IFD - // entry 0: baseline primary (0x030000) flagged as the representative image (bit 29) - for attr in [0x2003_0000u32, jpeg::MPF_GAIN_MAP] { - p.extend_from_slice(&attr.to_be_bytes()); - p.extend_from_slice(&[0; 12]); // size, offset, two dependent-image entries - } - p -} - /// Encode a gain map JPEG: `base` (8-bit SDR, 3 or 4 channels, colour-managed by `meta.icc`) and /// its gain map, both at `quality`. `meta.xmp` is kept, with the gain map container added. pub fn encode_jpeg(base: &EncodeImage, gain: &GainImage, m: &GainMapMeta, quality: u8, sub: ChromaSubsampling, meta: &EncodeMeta) -> Result> { @@ -87,28 +60,13 @@ pub fn encode_jpeg(base: &EncodeImage, gain: &GainImage, m: &GainMapMeta, qualit let xmp = craft_gainmap::primary_xmp(meta.xmp, gain_jpeg.len()); let mut segs = jpeg_app_segments(&EncodeMeta { xmp: Some(&xmp), ..*meta })?; segs.push((0xE2, craft_gainmap::primary_iso_marker())); - segs.push((0xE2, mpf_placeholder())); let sub = match sub { ChromaSubsampling::S444 => craft_jpeg::ChromaSubsampling::S444, ChromaSubsampling::S422 => craft_jpeg::ChromaSubsampling::S420, ChromaSubsampling::S420 => craft_jpeg::ChromaSubsampling::S420, }; - let mut primary = - craft_jpeg::encode_baseline(data, w, h, base.channels as usize, quality, sub, &segs).map_err(|e| Error::Encode(e.to_string()))?; - - // patch the MPF index: sizes, and the gain map's offset from the MPF endian field - let markers = jpeg::parse_markers(&primary).ok_or_else(|| Error::Encode("gain map JPEG: primary image unreadable".into()))?; - let endian = markers.mpf.as_ref().map(|m| m.0).ok_or_else(|| Error::Encode("gain map JPEG: MPF segment missing".into()))?; - let entries = endian + MPF_ENTRIES_FROM_ENDIAN; - let (plen, glen) = (primary.len(), gain_jpeg.len()); - let fields = [(entries + 4, plen), (entries + 8, 0), (entries + 20, glen), (entries + 24, plen - endian)]; - for (at, v) in fields { - let v = u32::try_from(v).map_err(|_| Error::Encode("gain map JPEG larger than 4 GiB".into()))?; - let slot = primary.get_mut(at..at + 4).ok_or_else(|| Error::Encode("gain map JPEG: truncated MPF segment".into()))?; - slot.copy_from_slice(&v.to_be_bytes()); - } - primary.extend_from_slice(&gain_jpeg); - Ok(primary) + let primary = craft_jpeg::encode_baseline(data, w, h, base.channels as usize, quality, sub, &segs).map_err(|e| Error::Encode(e.to_string()))?; + craft_metadata::mpf::write(&primary, &[(jpeg::MPF_GAIN_MAP, &gain_jpeg)]).map_err(|error| Error::Encode(format!("gain map JPEG: {error}"))) } /// The gain map of a gain map JPEG. diff --git a/crates/codecs/src/jpeg.rs b/crates/codecs/src/jpeg.rs index ccb37548c9..24cc4fbfb5 100644 --- a/crates/codecs/src/jpeg.rs +++ b/crates/codecs/src/jpeg.rs @@ -3,169 +3,14 @@ use crate::convert::{Buf, Meta, Model, Raw, check_size, finish}; use crate::{DecodeOptions, Decoded, Error, Format, Result, Thumbnail, ThumbnailSource, exif}; +use craft_image_codecs::jpeg_sef::{reaches_eoi, repair as without_sef_trailer}; const F: Format = Format::Jpeg; -/// What we learn from walking the marker segments before the first scan. -#[derive(Default, Debug)] -pub(crate) struct Markers { - pub width: u32, - pub height: u32, - pub components: u8, - pub precision: u8, - /// SOFn marker byte (0xC0 baseline, 0xC1 extended, 0xC2 progressive, …). - pub sof: u8, - /// Number of components in the first scan (< `components` for non-interleaved sequential files). - pub first_scan_components: u8, - /// Number of APP1 segments: capped before the allocating decoders walk them again. - pub app1: u32, - pub exif: Option>, - /// Offset of the EXIF TIFF header within the file. - pub exif_offset: usize, - pub xmp: Option, - pub icc: Option>, - /// An ICC_PROFILE APP2 segment was present but its sequence was invalid. - pub icc_invalid: bool, - pub adobe_transform: Option, - /// Offset of the MPF TIFF header within the file and its bytes. - pub mpf: Option<(usize, Vec)>, - /// The ISO 21496-1 APP2 payload after its URN: 4 bytes (versions only) on a primary image - /// that has a gain map, the full metadata on the gain map image itself. - pub iso_gainmap: Option>, -} +pub(crate) type Markers = craft_metadata::JpegInspection; -impl Markers { - /// This image is a gain map (ISO 21496-1 metadata or Adobe `hdrgm` gain parameters), not a - /// picture: never a preview, never the image to show. - pub fn is_gain_map(&self) -> bool { - self.iso_gainmap.as_ref().is_some_and(|p| p.len() > 4) || self.xmp.as_deref().is_some_and(|x| x.contains("hdrgm:GainMapMax")) - } -} - -pub(crate) fn parse_markers(b: &[u8]) -> Option { - if !b.starts_with(&[0xFF, 0xD8]) { - return None; - } - let mut m = Markers::default(); - let mut icc_chunks: [Option<&[u8]>; 255] = [None; 255]; - let mut icc_total = None; - let mut p = 2; - while p + 4 <= b.len() { - if b[p] != 0xFF { - // Tolerate garbage between segments: resync on the next 0xFF. - p += 1; - continue; - } - let marker = b[p + 1]; - if marker == 0xFF { - p += 1; - continue; - } - if marker == 0xD8 || (0xD0..=0xD7).contains(&marker) || marker == 0x01 { - p += 2; - continue; - } - if marker == 0xD9 { - break; - } - if marker == 0xDA { - m.first_scan_components = b.get(p + 4).copied().unwrap_or(0); - break; - } - let len = u16::from_be_bytes([b[p + 2], b[p + 3]]) as usize; - if len < 2 { - return None; - } - let start = p.checked_add(4)?; - let declared_end = p.checked_add(2)?.checked_add(len)?; - let complete = declared_end <= b.len(); - let end = declared_end.min(b.len()); - let seg = b.get(start..end)?; - match marker { - 0xC0..=0xCF if marker != 0xC4 && marker != 0xC8 && marker != 0xCC && seg.len() >= 6 && m.components == 0 => { - m.precision = seg[0]; - m.sof = marker; - m.height = u16::from_be_bytes([seg[1], seg[2]]) as u32; - m.width = u16::from_be_bytes([seg[3], seg[4]]) as u32; - m.components = seg[5]; - } - 0xE1 => { - m.app1 = m.app1.saturating_add(1); - if seg.starts_with(b"Exif\0\0") && m.exif.is_none() { - m.exif = Some(seg[6..].to_vec()); - m.exif_offset = start + 6; - } else if let Some(x) = seg.strip_prefix(b"http://ns.adobe.com/xap/1.0/\0") - && m.xmp.is_none() - { - m.xmp = Some(String::from_utf8_lossy(x).trim_end_matches('\0').to_string()); - } - } - 0xE2 => { - if seg.starts_with(b"ICC_PROFILE\0") { - if !complete || seg.len() < 14 { - m.icc_invalid = true; - } else if let (Some(&sequence), Some(&total)) = (seg.get(12), seg.get(13)) { - if sequence == 0 || total == 0 || sequence > total || icc_total.is_some_and(|expected| expected != total) { - m.icc_invalid = true; - } else { - icc_total = Some(total); - let Some(slot) = icc_chunks.get_mut(usize::from(sequence - 1)) else { - m.icc_invalid = true; - p = declared_end; - continue; - }; - if slot.is_some() { - m.icc_invalid = true; - } else if let Some(data) = seg.get(14..) { - *slot = Some(data); - } else { - m.icc_invalid = true; - } - } - } else { - m.icc_invalid = true; - } - } else if seg.starts_with(b"MPF\0") && m.mpf.is_none() { - m.mpf = Some((start + 4, seg[4..].to_vec())); - } else if let Some(p) = seg.strip_prefix(crate::gainmap::ISO_URN) - && m.iso_gainmap.is_none() - { - m.iso_gainmap = Some(p.to_vec()); - } - } - 0xEE if seg.starts_with(b"Adobe") && seg.len() >= 12 => { - m.adobe_transform = Some(seg[11]); - } - _ => {} - } - p = declared_end; - } - if let Some(total) = icc_total { - let mut profile_len = 0usize; - for chunk in icc_chunks.iter().take(usize::from(total)) { - let Some(bytes) = chunk else { - m.icc_invalid = true; - break; - }; - let Some(next_len) = profile_len.checked_add(bytes.len()) else { - m.icc_invalid = true; - break; - }; - profile_len = next_len; - } - let maximum_len = usize::from(total).checked_mul(65_519); - if maximum_len.is_none_or(|maximum| profile_len > maximum) { - m.icc_invalid = true; - } - if !m.icc_invalid { - let mut profile = Vec::with_capacity(profile_len); - for bytes in icc_chunks.iter().take(usize::from(total)).flatten() { - profile.extend_from_slice(bytes); - } - m.icc = Some(profile); - } - } - Some(m) +pub(crate) fn parse_markers(bytes: &[u8]) -> Option { + craft_metadata::inspect_jpeg(bytes) } pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { @@ -198,88 +43,6 @@ pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> { Ok((m.width, m.height, orientation)) } -/// Whether the markers after SOI, followed through every segment and scan, reach an EOI marker -/// (the first one: the primary image's, ahead of any MPF images appended to the file). Segments -/// are skipped by their length; in scan data `FF 00` (stuffing), `FF FF` (fill) and RSTn are not -/// markers that end it. -fn reaches_eoi(b: &[u8]) -> bool { - let mut p = 2usize; - loop { - // entropy-coded data (or garbage between segments, as `parse_markers` tolerates it) - let Some(skip) = b.get(p..).and_then(find_ff) else { return false }; - p = p.saturating_add(skip); - let Some(&marker) = b.get(p.saturating_add(1)) else { return false }; - p = match marker { - 0xD9 => return true, - 0xFF => p.saturating_add(1), - 0x00 | 0x01 | 0xD0..=0xD8 => p.saturating_add(2), - _ => { - let Some(len) = b.get(p.saturating_add(2)..p.saturating_add(4)).map(|l| u16::from_be_bytes([l[0], l[1]]) as usize) else { - return false; - }; - if len < 2 { - return false; - } - p.saturating_add(2).saturating_add(len) - } - }; - } -} - -/// A Samsung panorama whose scan runs straight into its SEF trailer, with no EOI marker (issue -/// #3350), as the file it stands for: the bytes before the trailer's earliest data block plus an -/// EOI. Every other file, a genuinely truncated one included, is borrowed unchanged. -fn without_sef_trailer(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> { - use std::borrow::Cow; - // The trailer is checked first: it reads only the file's last bytes, not the scan data. - let Some(image) = sef_image_end(bytes).and_then(|end| bytes.get(..end)) else { return Cow::Borrowed(bytes) }; - // the image before the trailer: an FF D9 inside the SEF data doesn't end the scan - if reaches_eoi(image) { - return Cow::Borrowed(bytes); - } - let mut fixed = Vec::with_capacity(image.len().saturating_add(2)); - fixed.extend_from_slice(image); - fixed.extend_from_slice(&[0xFF, 0xD9]); - // The cut must leave the scan data, not a segment or anything before the first scan, open. - let in_scan = parse_markers(&fixed).is_some_and(|m| m.first_scan_components > 0) && reaches_eoi(&fixed); - if in_scan { Cow::Owned(fixed) } else { Cow::Borrowed(bytes) } -} - -/// Where the image ends in a file carrying a Samsung SEF trailer: the start of its earliest data -/// block. The trailer is the file's last bytes: `SEFH`, a u32 LE version and entry count, 12-byte -/// entries (u16 padding, u16 type, u32 LE offset of the block back from `SEFH`, u32 LE length), -/// then the u32 LE length of that directory and `SEFT`. Each block starts with the same padding -/// and type as its entry. `None` unless every entry's block is nonempty, starts with its entry's -/// type and lies inside the file, before `SEFH`. -fn sef_image_end(b: &[u8]) -> Option { - let le32 = |at: usize| b.get(at..at.checked_add(4)?)?.try_into().ok().map(|v| u32::from_le_bytes(v) as usize); - let tail = b.len().checked_sub(8)?; - if b.get(tail.checked_add(4)?..)? != b"SEFT" { - return None; - } - let dir = tail.checked_sub(le32(tail)?)?; - if b.get(dir..dir.checked_add(4)?)? != b"SEFH" { - return None; - } - let count = le32(dir.checked_add(8)?)?; - let entries = dir.checked_add(12)?; - if count == 0 || count > tail.checked_sub(entries)? / 12 { - return None; - } - let mut start = dir; - for i in 0..count { - let entry = entries.checked_add(i.checked_mul(12)?)?; - let block = dir.checked_sub(le32(entry.checked_add(4)?)?)?; - let len = le32(entry.checked_add(8)?)?; - let kind = |at: usize| b.get(at.checked_add(2)?..at.checked_add(4)?); - if len < 4 || block.checked_add(len)? > dir || kind(block)? != kind(entry)? { - return None; - } - start = start.min(block); - } - Some(start) -} - pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback: Option) -> Result { let bytes = &*without_sef_trailer(bytes); let m = parse_markers(bytes).ok_or_else(|| Error::Malformed(F, "missing SOI".into()))?; @@ -335,21 +98,6 @@ fn decode_via_craft_codecs(bytes: &[u8], budget: &DecodeOptions) -> Result Ok(Raw { width: w, height: h, model, alpha: false, premultiplied: false, buf, bit_depth }) } -/// The first `0xFF` byte, eight bytes at a time (scan data has one every few hundred bytes: this -/// is most of [`header`]'s time). -fn find_ff(b: &[u8]) -> Option { - const ONES: u64 = 0x0101_0101_0101_0101; - let (words, tail) = b.as_chunks::<8>(); - for (i, w) in words.iter().enumerate() { - // a zero byte in !w is an 0xFF byte in w - let x = !u64::from_ne_bytes(*w); - if x.wrapping_sub(ONES) & !x & (ONES << 7) != 0 { - return w.iter().position(|&v| v == 0xFF).map(|j| i * 8 + j); - } - } - tail.iter().position(|&v| v == 0xFF).map(|j| words.len() * 8 + j) -} - /// Fast path: an embedded JPEG preview (EXIF IFD1 thumbnail, or the largest MPF preview) whose long /// edge is ≥ `max_edge`, decoded with DCT scaling and fitted. pub(crate) fn embedded_thumbnail(bytes: &[u8], max_edge: u32, min_edge: u32) -> Option { @@ -400,39 +148,9 @@ pub(crate) fn embedded_thumbnail(bytes: &[u8], max_edge: u32, min_edge: u32) -> /// MP type code of a gain map image (CIPA DC-007 entry attribute, low 24 bits). pub(crate) const MPF_GAIN_MAP: u32 = 0x05_0000; -/// An MPF-listed image other than the primary. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct MpfEntry { - /// File offset and length of the image. - pub offset: usize, - pub len: usize, - /// MP type code (attribute low 24 bits). - pub kind: u32, -} - /// The MPF-listed images other than the primary. -pub(crate) fn mpf_images(m: &Markers) -> Vec { - let Some((base, data)) = &m.mpf else { return vec![] }; - let Some(t) = exif::Tiff::new(data) else { return vec![] }; - let Some(ifd) = t.first_ifd() else { return vec![] }; - let Some((entries, _)) = t.ifd(ifd) else { return vec![] }; - let Some(e) = entries.iter().find(|e| e.tag == 0xB002) else { return vec![] }; - let Some(list) = t.bytes(e) else { return vec![] }; - let mut out = Vec::new(); - for (i, rec) in list.as_chunks::<16>().0.iter().enumerate().take(16) { - if i == 0 { - continue; - } - let rd = |o: usize| { - let a = [rec[o], rec[o + 1], rec[o + 2], rec[o + 3]]; - if data.starts_with(b"II") { u32::from_le_bytes(a) } else { u32::from_be_bytes(a) } - }; - let (attr, size, off) = (rd(0), rd(4) as usize, rd(8) as usize); - if size > 0 && off > 0 { - out.push(MpfEntry { offset: base.saturating_add(off), len: size, kind: attr & 0x00FF_FFFF }); - } - } - out +pub(crate) fn mpf_images(m: &Markers) -> Vec { + m.mpf.as_ref().map_or_else(Vec::new, |(base, data)| craft_metadata::mpf::images_from_index(data, *base)) } /// Decode to the file's 8-bit samples as stored (no colour management): 1 channel for greyscale @@ -461,6 +179,78 @@ pub(crate) fn decode_codes8(bytes: &[u8]) -> Result<(usize, usize, usize, Vec bool { + let mut p = 2usize; + loop { + let Some(skip) = b.get(p..).and_then(|s| s.iter().position(|&v| v == 0xff)) else { return false }; + p = p.saturating_add(skip); + let Some(&marker) = b.get(p.saturating_add(1)) else { return false }; + p = match marker { + 0xd9 => return true, + 0xff => p.saturating_add(1), + 0x00 | 0x01 | 0xd0..=0xd8 => p.saturating_add(2), + _ => { + let Some(len) = b.get(p.saturating_add(2)..p.saturating_add(4)).map(|s| u16::from_be_bytes([s[0], s[1]]) as usize) else { + return false; + }; + if len < 2 { + return false; + } + p.saturating_add(2).saturating_add(len) + } + }; + } + } + let base = [0xff, 0xd8, 0xff, 0xe1, 0, 4, 1, 2, 0xff, 0xda, 0, 3, 1, 1, 0xff, 0, 3, 0xff, 0xd0, 4, 0xff, 0xd9]; + for end in 0..=base.len() { + for at in 0..end { + for value in [0, 1, 0xff, 0xd9] { + let mut bytes = base[..end].to_vec(); + bytes[at] = value; + assert_eq!(reaches_eoi(&bytes), previous(&bytes), "end {end}, at {at}, value {value}"); + } + } + } + } + + #[test] + fn mpf_shared_matches_previous_reader_on_mutated_indices() { + fn previous(base: usize, data: &[u8]) -> Vec { + let Some(t) = exif::Tiff::new(data) else { return vec![] }; + let Some(ifd) = t.first_ifd() else { return vec![] }; + let Some((entries, _)) = t.ifd(ifd) else { return vec![] }; + let Some(e) = entries.iter().find(|e| e.tag == 0xb002) else { return vec![] }; + let Some(list) = t.bytes(e) else { return vec![] }; + list.as_chunks::<16>() + .0 + .iter() + .enumerate() + .take(16) + .skip(1) + .filter_map(|(_, rec)| { + let rd = |i| { + let b = [rec[i], rec[i + 1], rec[i + 2], rec[i + 3]]; + if data.starts_with(b"II") { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) } + }; + let (attr, len, off) = (rd(0), rd(4) as usize, rd(8) as usize); + (len > 0 && off > 0).then_some(craft_metadata::mpf::MpfImage { offset: base.saturating_add(off), len, kind: attr & 0x00ff_ffff }) + }) + .collect() + } + let file = craft_metadata::mpf::write(&[0xff, 0xd8, 0xff, 0xd9], &[(0x050000, &[0xff, 0xd8, 0xff, 0xd9])]).unwrap(); + let m = parse_markers(&file).unwrap(); + let (base, data) = m.mpf.unwrap(); + for at in 0..data.len() { + for value in [0u8, 0xff] { + let mut altered = data.clone(); + altered[at] = value; + assert_eq!(craft_metadata::mpf::images_from_index(&altered, base), previous(base, &altered), "mutation at {at}, value {value}"); + } + } + } + #[test] fn container_fallback_matches_tagged_jpeg_before_resizing_and_keeps_own_metadata() { use crate::{ChromaSubsampling, EncodeImage, EncodeMeta, NamedSpace, Samples, SpaceOrigin, encode_jpeg}; @@ -603,20 +393,6 @@ mod tests { assert!(markers.icc_invalid); } - #[test] - fn find_ff_matches_a_plain_search() { - let mut b: Vec = (0..300u32).map(|i| (i * 7 % 255) as u8).collect(); - for at in [None, Some(0), Some(7), Some(8), Some(15), Some(203), Some(296), Some(299)] { - if let Some(i) = at { - b[i] = 0xFF; - } - for start in [0, 1, 5, 9, 290, 299, 300] { - let s = &b[start..]; - assert_eq!(find_ff(s), s.iter().position(|&v| v == 0xFF), "{at:?} from {start}"); - } - } - } - #[test] fn unbounded_fit_box_decodes_at_full_size() { // a full-size load asks for the largest box (`usize::MAX` saturated to `u32::MAX`): no DCT scaling, diff --git a/crates/codecs/src/psd.rs b/crates/codecs/src/psd.rs index c44fade8ba..0a2104db6c 100644 --- a/crates/codecs/src/psd.rs +++ b/crates/codecs/src/psd.rs @@ -4,7 +4,7 @@ //! Also a flat-file writer ([`encode`]): the merged image of an 8- or 16-bit gray/RGB document //! with no layers, so an image editor opens it as one background layer and saves back to it. -use crate::convert::{Buf, Meta, Model, Raw, check_size, finish}; +use crate::convert::{Buf, Meta, Model, Raw, finish}; use crate::encode::{EncodeImage, EncodeMeta, Samples}; use crate::{DecodeOptions, Decoded, Error, Format, Result}; @@ -14,11 +14,13 @@ fn err(s: &str) -> Error { Error::Malformed(F, s.to_string()) } +#[cfg(test)] struct Rd<'a> { b: &'a [u8], p: usize, } +#[cfg(test)] impl<'a> Rd<'a> { fn take(&mut self, n: usize) -> Result<&'a [u8]> { let end = self.p.checked_add(n).filter(|&e| e <= self.b.len()).ok_or_else(|| err("truncated"))?; @@ -34,71 +36,64 @@ impl<'a> Rd<'a> { let s = self.take(4)?; Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]])) } - fn u64(&mut self) -> Result { - let s = self.take(8)?; - Ok(u64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])) - } } -/// The header (`craft-psd`), colour mode data and image resources, with a reader at the layer and mask section. -struct Start<'a> { - psb: bool, - channels: usize, - width: usize, - height: usize, - depth: u16, - mode: u16, - color_mode_data: &'a [u8], - resources: Vec, - r: Rd<'a>, +/// The merged composite of `bytes`. A file whose image resources section doesn't parse is opened +/// with that section emptied (a copy in `spare`): the picture still decodes, without its profile +/// and metadata. +fn open_merged<'a>(bytes: &'a [u8], opts: &DecodeOptions, spare: &'a mut Vec) -> Result> { + let error = match open_exact(bytes, opts) { + Ok(merged) => return Ok(merged), + // a pixel-limit refusal reads the header, which the copy keeps: no retry + Err(error @ Error::TooLarge(..)) => return Err(error), + Err(error) => error, + }; + let Some(stripped) = without_resources(bytes) else { return Err(error) }; + *spare = stripped; + let spare: &'a Vec = spare; + open_exact(spare, opts).map_err(|_| error) } -fn start<'a>(bytes: &'a [u8], opts: &DecodeOptions) -> Result> { - // the size limit first, from the header's fixed fields, so an oversized file is `TooLarge` as for other formats - if let (Some(&[h0, h1, h2, h3]), Some(&[w0, w1, w2, w3])) = (bytes.get(14..18), bytes.get(18..22)) { - check_size(F, u64::from(u32::from_be_bytes([w0, w1, w2, w3])), u64::from(u32::from_be_bytes([h0, h1, h2, h3])), opts)?; +/// `bytes` with an empty image resources section, when the header parses but the resources don't. +fn without_resources(bytes: &[u8]) -> Option> { + if craft_psd::Head::from_bytes(bytes).is_ok() || craft_psd::Header::from_bytes(bytes).is_err() { + return None; } - let h = craft_psd::Header::from_bytes(bytes).map_err(|e| match e { + let len_at = |at: usize| -> Option { usize::try_from(u32::from_be_bytes(bytes.get(at..at.checked_add(4)?)?.try_into().ok()?)).ok() }; + let res_at = 30usize.checked_add(len_at(26)?)?; + let tail = bytes.get(res_at.checked_add(4)?.checked_add(len_at(res_at)?)?..)?; + let mut out = Vec::new(); + // a failed allocation leaves the original parse error, not an abort + out.try_reserve_exact(bytes.len()).ok()?; + out.extend_from_slice(bytes.get(..res_at)?); + out.extend_from_slice(&0u32.to_be_bytes()); + out.extend_from_slice(tail); + Some(out) +} + +fn open_exact<'a>(bytes: &'a [u8], opts: &DecodeOptions) -> Result> { + craft_psd::merged::Merged::open(bytes, opts.max_pixels).map_err(|error| match error { + craft_psd::PsdError::LimitExceeded("pixel count") => { + let (w, h) = craft_psd::merged::declared_dimensions(bytes).unwrap_or((0, 0)); + Error::TooLarge(u64::from(w), u64::from(h)) + } + craft_psd::PsdError::Invalid(message) => err(&message), craft_psd::PsdError::UnexpectedEof { .. } => err("truncated"), - e => err(&e.to_string()), - })?; - let mut r = Rd { b: bytes, p: 26 }; - let cm_len = r.u32()? as usize; - let color_mode_data = r.take(cm_len)?; - let res_len = r.u32()? as usize; - r.take(res_len)?; - // a resource section that doesn't parse is left out: the picture still decodes, without its profile and metadata - let resources = craft_psd::Head::from_bytes(bytes).map(|head| head.resources).unwrap_or_default(); - Ok(Start { - psb: h.version.is_psb(), - channels: usize::from(h.channels), - width: h.width as usize, - height: h.height as usize, - depth: h.depth, - mode: h.color_mode.as_u16(), - color_mode_data, - resources, - r, + other => err(&other.to_string()), }) } pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { - let Start { psb, channels, width, height, depth, mode, color_mode_data, resources: res, mut r } = start(bytes, opts)?; - let (icc, exif, xmp) = resources(&res); - - // Layer and mask information: only the layer count sign matters (merged transparency). - let lm_len = if psb { r.u64()? } else { u64::from(r.u32()?) }; - let lm = r.take(usize::try_from(lm_len).map_err(|_| err("truncated"))?)?; - let merged_transparency = if lm.len() >= if psb { 10 } else { 6 } { - let off = if psb { 8 } else { 4 }; - let count = i16::from_be_bytes([lm[off], lm[off + 1]]); - count < 0 - } else { - false - }; + let mut spare = Vec::new(); + let merged = open_merged(bytes, opts, &mut spare)?; + let head = &merged.head; + let h = &head.header; + let (channels, width, height, depth, mode) = (usize::from(h.channels), h.width as usize, h.height as usize, h.depth, h.color_mode.as_u16()); + let color_mode_data = head.color_mode_data.as_slice(); + let (icc, exif, xmp) = resources(&head.resources); + let merged_transparency = merged.transparency; // Image data. - let compression = r.u16()?; let bpc = match depth { 8 => 1usize, 16 => 2, @@ -124,57 +119,13 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { let used = n_color + alpha as usize; let too_large = || Error::TooLarge(width as u64, height as u64); let n = width.checked_mul(height).ok_or_else(too_large)?; - let row_bytes = width.checked_mul(bpc).ok_or_else(too_large)?; - let plane = n.checked_mul(bpc).ok_or_else(too_large)?; - let mut planes: Vec> = Vec::with_capacity(used); - match compression { - 0 => { - // Raw planes are borrowed from the input, so their size is bounded by the file. - for _ in 0..used { - planes.push(r.take(plane)?.to_vec()); - } - } - 1 => { - // Row byte-count table: one entry per row per channel (all channels, since the data - // follows it). Taken from the input before anything is allocated from it. - let entry = if psb { 4 } else { 2 }; - let table_len = channels.checked_mul(height).and_then(|c| c.checked_mul(entry)).ok_or_else(|| err("truncated"))?; - let table = r.take(table_len)?; - let count = |i: usize| -> usize { - let at = i.saturating_mul(entry); - match table.get(at..at.saturating_add(entry)) { - Some(&[a, b]) => usize::from(u16::from_be_bytes([a, b])), - Some(&[a, b, c, d]) => u32::from_be_bytes([a, b, c, d]) as usize, - _ => 0, - } - }; - // PackBits expands at most 64× (a 2-byte repeat run yields 128 bytes), so a row needs - // at least this many encoded bytes. Requiring it (and the data being present) before - // allocating bounds the decoded planes by the file size: a tiny file can no longer - // declare gigabytes of zero-padded or repeat-run rows. - let min_row = row_bytes.div_ceil(128).saturating_mul(2); - let mut data_len = 0usize; - for i in 0..used.saturating_mul(height) { - let c = count(i); - if c < min_row { - return Err(err("RLE row too short for its width")); - } - data_len = data_len.saturating_add(c); - } - if data_len > bytes.len().saturating_sub(r.p) { - return Err(err("truncated")); - } - for c in 0..used { - let mut out = zeroed::(plane, too_large)?; - for (y, row) in out.chunks_exact_mut(row_bytes).enumerate() { - let src = r.take(count(c * height + y))?; - unpackbits(src, row)?; - } - planes.push(out); - } - } - _ => return Err(Error::Unsupported(F, "ZIP-compressed merged image data")), - } + let planes = merged.read_planes(used).map_err(|error| match error { + craft_psd::PsdError::LimitExceeded(_) | craft_psd::PsdError::OutOfMemory(_) => too_large(), + craft_psd::PsdError::Unsupported(_) => Error::Unsupported(F, "ZIP-compressed merged image data"), + craft_psd::PsdError::Invalid(message) => err(&message), + craft_psd::PsdError::UnexpectedEof { .. } => err("truncated"), + other => err(&other.to_string()), + })?; let samples = n.checked_mul(used).ok_or_else(too_large)?; // Interleave to device samples. @@ -256,18 +207,18 @@ pub(crate) fn encode(img: &EncodeImage, meta: &EncodeMeta) -> Result> { /// depth, colour mode or compression, or merged image data that runs past the end of the file /// (truncated). The run-length data itself is not unpacked. pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> { - let Start { psb, channels, width, height, depth, mode, color_mode_data, resources: res, mut r } = start(bytes, &DecodeOptions::default())?; - let (_, exif, _) = resources(&res); - let lm_len = if psb { r.u64()? as usize } else { r.u32()? as usize }; - r.take(lm_len)?; - let compression = r.u16()?; - let bpc = match depth { - 8 => 1usize, - 16 => 2, - 32 => 4, + let mut spare = Vec::new(); + let merged = open_merged(bytes, &DecodeOptions::default(), &mut spare)?; + let head = &merged.head; + let h = &head.header; + let (channels, width, height, depth, mode) = (usize::from(h.channels), h.width as usize, h.height as usize, h.depth, h.color_mode.as_u16()); + let color_mode_data = head.color_mode_data.as_slice(); + let (_, exif, _) = resources(&head.resources); + match depth { + 8 | 16 | 32 => {} 1 => return Err(Error::Unsupported(F, "1-bit bitmap PSD")), _ => return Err(err("bad depth")), - }; + } let n_color = match mode { 1 | 8 | 7 | 2 => 1, 3 => 3, @@ -281,24 +232,12 @@ pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> { if mode == 2 && (color_mode_data.len() < 768 || depth != 8) { return Err(err("bad indexed palette")); } - let rest = bytes.len().saturating_sub(r.p); - let need = match compression { - 0 => width.checked_mul(height).and_then(|n| n.checked_mul(bpc)).and_then(|n| n.checked_mul(channels)), - 1 => { - // the row byte counts, then the rows they count - let rows = channels.checked_mul(height).ok_or_else(|| err("truncated"))?; - let table = rows.checked_mul(if psb { 4 } else { 2 }).filter(|&t| t <= rest).ok_or_else(|| err("truncated"))?; - let mut total = table; - for _ in 0..rows { - total = total.saturating_add(if psb { r.u32()? as usize } else { r.u16()? as usize }); - } - Some(total) - } - _ => return Err(Error::Unsupported(F, "ZIP-compressed merged image data")), - }; - if need.is_none_or(|n| n > rest) { - return Err(err("truncated")); - } + merged.validate_all().map_err(|error| match error { + craft_psd::PsdError::Unsupported(_) => Error::Unsupported(F, "ZIP-compressed merged image data"), + craft_psd::PsdError::Invalid(message) => err(&message), + craft_psd::PsdError::UnexpectedEof { .. } => err("truncated"), + other => err(&other.to_string()), + })?; let orientation = exif.as_deref().map(crate::exif::summarize).unwrap_or_default().orientation.unwrap_or(1); Ok((width as u32, height as u32, orientation)) } @@ -311,30 +250,9 @@ fn zeroed(len: usize, too_large: impl Fn() -> Error) -> Resu Ok(v) } -/// PackBits: decode one row into `row` (pre-zeroed, so short run data leaves zero padding). -/// A run that would write past the end of the row is an error; trailing bytes are ignored. -fn unpackbits(mut src: &[u8], row: &mut [u8]) -> Result<()> { - let mut at = 0; - while at < row.len() { - let Some((&h, rest)) = src.split_first() else { break }; - src = rest; - let h = h as i8; - if h >= 0 { - let n = h as usize + 1; - let lit = src.get(..n).unwrap_or(src); - let dst = row.get_mut(at..at + lit.len()).ok_or_else(|| err("RLE row overruns its width"))?; - dst.copy_from_slice(lit); - at += lit.len(); - src = src.get(n..).unwrap_or(&[]); - } else if h != -128 { - let n = (1 - h as isize) as usize; - let Some((&b, rest)) = src.split_first() else { break }; - src = rest; - row.get_mut(at..at + n).ok_or_else(|| err("RLE row overruns its width"))?.fill(b); - at += n; - } - } - Ok(()) +#[cfg(test)] +fn unpackbits(src: &[u8], row: &mut [u8]) -> Result<()> { + craft_psd::merged::unpackbits(src, row).map_err(|error| err(&error.to_string())) } /// ICC (1039), EXIF (1058, without its optional `Exif\0\0` prefix) and XMP (1060) resources; the last of each id. @@ -424,6 +342,17 @@ mod tests { assert_eq!(super::header(&b).unwrap(), (1, 1, 1)); } + #[test] + fn a_damaged_resource_section_over_the_pixel_limit_is_too_large() { + // the size refusal comes before (and instead of) the copy without the resources + let mut b = header(3, 4, 4, 8, 3, 0); + b[30..34].copy_from_slice(&4u32.to_be_bytes()); + b.splice(34..34, *b"JUNK"); + let opts = DecodeOptions { max_pixels: 15, ..DecodeOptions::default() }; + let e = decode(&b, &opts).unwrap_err(); + assert!(matches!(e, Error::TooLarge(4, 4)), "{e:?}"); + } + #[test] fn rle_repeat_run_past_row_width_is_an_error() { // 4 × 1 gray 8-bit; the single row is a 128-byte repeat run. diff --git a/crates/codecs/src/sniff.rs b/crates/codecs/src/sniff.rs index d8f627f6a2..c642c0351b 100644 --- a/crates/codecs/src/sniff.rs +++ b/crates/codecs/src/sniff.rs @@ -132,11 +132,8 @@ pub fn sniff(b: &[u8]) -> Option { if b.starts_with(b"II+\0") || b.starts_with(b"MM\0+") { return Some(Format::Tiff); } - if b.len() >= 26 && b.starts_with(b"BM") { - let dib = u32::from_le_bytes([b[14], b[15], b[16], b[17]]); - if matches!(dib, 12 | 16 | 40 | 52 | 56 | 64 | 108 | 124) { - return Some(Format::Bmp); - } + if craft_image_codecs::bmp_probe::is_supported_header(b) { + return Some(Format::Bmp); } None } @@ -224,6 +221,21 @@ fn tiff_is_raw(b: &[u8]) -> bool { mod tests { use super::*; + #[test] + fn bmp_routing_retains_supported_dib_and_truncation_rules() { + let mut b = [0_u8; 26]; + b[..2].copy_from_slice(b"BM"); + for dib in [12_u32, 16, 40, 52, 56, 64, 108, 124] { + b[14..18].copy_from_slice(&dib.to_le_bytes()); + assert_eq!(sniff(&b), Some(Format::Bmp)); + assert_eq!(sniff(&b[..25]), None); + } + for dib in [0_u32, 13, 39, 125, u32::MAX] { + b[14..18].copy_from_slice(&dib.to_le_bytes()); + assert_eq!(sniff(&b), None); + } + } + #[test] fn raw_tiff_classifier_matches_legacy_on_mutations() { let fixtures: &[&[u8]] = &[ diff --git a/crates/codecs/src/webp.rs b/crates/codecs/src/webp.rs index 854a6ca9c5..6c67971963 100644 --- a/crates/codecs/src/webp.rs +++ b/crates/codecs/src/webp.rs @@ -41,29 +41,34 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result { /// animation frame), or one that runs past the end of the file (truncated). The compressed data /// itself is not checked. pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> { - let mut p = 12usize; - let mut has_image = false; - let mut exif_chunk: Option<&[u8]> = None; - while let Some(h) = bytes.get(p..p.saturating_add(8)) { - let size = u32::from_le_bytes([h[4], h[5], h[6], h[7]]) as usize; - let end = p.saturating_add(8).saturating_add(size); - if matches!(&h[0..4], b"VP8 " | b"VP8L" | b"ANMF") { - if end > bytes.len() { - return Err(err("truncated image data")); - } - has_image = true; - } else if &h[0..4] == b"EXIF" && end <= bytes.len() && exif_chunk.is_none() { - exif_chunk = Some(&bytes[p + 8..end]); - } - p = end.saturating_add(size & 1); - } - if !has_image { - return Err(err("no image data")); - } - let (w, h) = craft_image_codecs::probe_size(bytes).map_err(err)?; - let orientation = - exif_chunk.map(|e| e.strip_prefix(b"Exif\0\0").unwrap_or(e)).map(crate::exif::summarize).unwrap_or_default().orientation.unwrap_or(1); - let (w, h) = if (5..=8).contains(&orientation) { (h, w) } else { (w, h) }; + let (w, h, orientation) = craft_image_codecs::webp_probe::header(bytes).map_err(err)?; check_size(F, w as u64, h as u64, &DecodeOptions::default())?; Ok((w, h, orientation)) } + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn exif_orientation_mutation_parity() { + let exif = crate::exif::minimal_exif(6); + let image = crate::encode::EncodeImage::new(2, 3, 3, crate::encode::Samples::U8(&[80; 18])); + let base = crate::encode::encode_webp_lossless(&image, &crate::encode::EncodeMeta { exif: Some(&exif), ..Default::default() }).unwrap(); + let marker = base.windows(4).position(|v| v == b"EXIF").unwrap(); + for at in 0..exif.len() { + for value in [0, 255] { + let mut data = exif.clone(); + data[at] = value; + let mut webp = base.clone(); + webp[marker + 8..marker + 8 + data.len()].copy_from_slice(&data); + if let Ok((w, h)) = craft_image_codecs::probe_size(&webp) { + let orientation = crate::exif::summarize(&data).orientation.unwrap_or(1); + let _ = (w, h); // The stored 2 × 3 canvas never changes with EXIF. + assert_eq!(header(&webp).unwrap(), (2, 3, orientation), "at {at}, value {value}"); + } else { + assert!(header(&webp).is_err()); + } + } + } + } +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 807a5e5c82..0fa54516b2 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -64,6 +64,8 @@ denoise = ["dep:lightcraft-denoise", "lightcraft-denoise/runtime", "lightcraft-g rawnind-model = ["denoise", "lightcraft-denoise/rawnind-model", "lightcraft-denoise-core/rawnind-model"] [dev-dependencies] +# Construct RAW errors using the same TIFF package as craft-raw. +craft-raw-tiff = { workspace = true } # tests record why they skip (`cargo xtask ci` lists the skips) lightcraft-testkit = { workspace = true } # HDR JPEG XL tests read the file's colour encoding diff --git a/crates/engine/src/camera_preview.rs b/crates/engine/src/camera_preview.rs index 014a744080..d0ffe33fa7 100644 --- a/crates/engine/src/camera_preview.rs +++ b/crates/engine/src/camera_preview.rs @@ -84,7 +84,9 @@ use tone::{HighlightCheck, ToneFit, fit_tone, fit_tone_conditional, highlights}; /// 13: the sensor proxy of every per-file fit gets the embedded vignetting correction the render applies (Fujifilm /// RAF; other makes with a lens database), so the render no longer applies it twice, at the position a lens warp samples; /// the warped candidate's alignment leaves out the pixels outside the sensor instead of reading them as black. -pub const LOOK_VERSION: u32 = 13; +/// 14: bundled camera profiles also match the Nikon model spellings that differ in case, spacing or the Z8 alias, +/// so previews made without the profile are rebuilt. +pub const LOOK_VERSION: u32 = 14; #[derive(Clone, Debug)] pub(crate) struct CameraLook { diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index 3c63773c1e..ed6e601cd2 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -8,8 +8,9 @@ //! //! Profiles are JSON files (`.json`) in [`dir`]: `LIGHTCRAFT_CAMERA_PROFILES`, else //! `/camera-profiles`; a local profile replaces the one built in ([`BUNDLED`], from -//! `assets/camera-profiles/`). They are read once per process; a damaged or hostile file is -//! ignored with a warning. They hold aggregate colour statistics only, never image content. +//! `assets/camera-profiles/`). They are read once per process for the folder they are looked up +//! in; a damaged or hostile file is ignored with a warning. They hold aggregate colour statistics +//! only, never image content. use lightcraft_color::Mat3; use lightcraft_raw::profile::HsvTable; use serde::{Deserialize, Serialize}; @@ -105,9 +106,48 @@ fn parse(json: &[u8], origin: &str) -> Result { Ok(profile) } +/// Model spelling with case and spacing folded away, for matching EXIF variants. +fn normalized_model(model: &str) -> String { + model.split_whitespace().collect::>().join(" ").to_ascii_lowercase() +} + +/// EXIF spellings that differ by more than case and spacing, as `(spelling, bundled model)`. +const ALIASES: &[(&str, &str)] = &[ + ("NIKON Z8", "NIKON Z 8"), + ("NIKON Z 6-2", "NIKON Z 6_2"), + ("NIKON Z 6 2", "NIKON Z 6_2"), + ("Nikon Z8", "NIKON Z 8"), + ("Nikon Z 6-2", "NIKON Z 6_2"), + ("Nikon Z 6 2", "NIKON Z 6_2"), +]; + +/// Normalize a model name for local profile lookup (case, whitespace, and separator folding). +fn normalize_for_lookup(model: &str) -> String { + normalized_model(model).replace(['-', ' '], "_") +} + +/// Normalize a model name for local profile matching: [`ALIASES`] applied as for bundled +/// profiles, then case, whitespace and separators folded to `_`, so a profile saved under one +/// spelling ("NIKON Z8", `NIKON_Z8.json`) is found by another ("NIKON Z 8"). +fn normalize_for_local_match(model: &str) -> String { + let folded = normalize_for_lookup(model); + ALIASES.iter().find(|(spelling, _)| normalize_for_lookup(spelling) == folded).map_or(folded, |(_, canonical)| normalize_for_lookup(canonical)) +} + +/// Resolve an EXIF model spelling to the canonical model spelling using +/// [`ALIASES`], so spellings that differ by more than case and spacing +/// (for example "NIKON Z8" versus "NIKON Z 8") match the same profile. +fn canonical_model(model: &str) -> &str { + let needle = normalized_model(model); + ALIASES.iter().find(|(spelling, _)| normalized_model(spelling) == needle).map_or(model, |(_, canonical)| *canonical) +} + /// The built-in profile for `model`, if any. fn bundled(model: &str) -> Option { - let (_, json) = BUNDLED.iter().find(|(m, _)| *m == model)?; + let needle = normalized_model(model); + let needle = + ALIASES.iter().find(|(spelling, _)| normalized_model(spelling) == needle).map_or(needle, |(_, canonical)| normalized_model(canonical)); + let (_, json) = BUNDLED.iter().find(|(m, _)| normalized_model(m) == needle)?; parse(json.as_bytes(), &format!("built-in profile {model}")).inspect_err(|e| eprintln!("lightcraft: ignoring camera profile {e}")).ok() } @@ -122,38 +162,73 @@ pub fn save(profile: &CameraProfile, dir: &Path) -> Result { Ok(path) } -fn cache() -> &'static Mutex>>> { - static CACHE: OnceLock>>>> = OnceLock::new(); +/// Profiles already read, per folder they were read from and model: a lookup pointed at another +/// folder (a test's temporary directory) must not return the profile read from this one. +type Cache = HashMap<(Option, String), Option>>; + +fn cache() -> &'static Mutex { + static CACHE: OnceLock> = OnceLock::new(); CACHE.get_or_init(Default::default) } /// The profile for camera `model`: from [`dir`], else built in; read once per process. pub fn get(model: &str) -> Option> { + get_from(model, dir().as_deref()) +} + +/// The profile for camera `model` read from `directory`, else built in; read once per process for +/// that folder. +/// +/// `directory` is the profile folder to search for a local profile; [`dir`] resolves it from +/// [`LIGHTCRAFT_CAMERA_PROFILES`] or the config folder. Separating it lets tests point the lookup +/// at a temporary directory without changing process environment variables. +fn get_from(model: &str, directory: Option<&Path>) -> Option> { let model = model.trim(); if model.is_empty() { return None; } + // EXIF spellings that differ by more than case and spacing (for example + // "NIKON Z8") resolve to the canonical model ("NIKON Z 8") before the + // local lookup, and the profile's own model is compared through the same + // aliases, so a local profile saved under either spelling is found + // instead of falling back to the bundled profile. + let model = canonical_model(model); + let key = (directory.map(Path::to_path_buf), model.to_owned()); let mut cache = cache().lock().unwrap_or_else(PoisonError::into_inner); - if let Some(hit) = cache.get(model) { + if let Some(hit) = cache.get(&key) { return hit.clone(); } - let path = dir().map(|d| d.join(file_name(model))); - let profile = match path { - Some(path) if path.is_file() => match load(&path) { - Ok(p) if p.model.trim() == model => Some(Arc::new(p)), - Ok(p) => { - eprintln!("lightcraft: ignoring camera profile {}: it is for {:?}, not {model:?}", path.display(), p.model); - None + // Scan the directory for a local profile. Candidates are regular .json files + // ranked so a normalized stem match (case, whitespace and separator folding) + // beats a model-name match; within a rank the sorted path order decides. + // Selection therefore never depends on read_dir iteration order, and only + // regular files are loaded, so a FIFO or directory named like a profile + // cannot block while the cache mutex is held. + let profile = { + let needle = normalize_for_local_match(model); + directory.and_then(|d| { + let mut entries: Vec<_> = std::fs::read_dir(d).ok()?.flatten().collect(); + entries.sort_by_key(|e| e.path()); + let mut ranked: Vec<(u8, PathBuf)> = Vec::new(); + for e in &entries { + let path = e.path(); + if !path.extension().is_some_and(|x| x == "json") || !path.is_file() { + continue; + } + let rank = if path.file_stem().is_some_and(|s| normalize_for_local_match(&s.to_string_lossy()) == needle) { 1 } else { 2 }; + ranked.push((rank, path)); } - Err(e) => { - eprintln!("lightcraft: ignoring camera profile {e}"); - None + ranked.sort(); + for (_, path) in ranked { + if let Some(p) = load(&path).ok().filter(|p| normalize_for_local_match(&p.model) == needle) { + return Some(Arc::new(p)); + } } - }, - _ => None, + None + }) }; let profile = profile.or_else(|| bundled(model).map(Arc::new)); - cache.insert(model.to_owned(), profile.clone()); + cache.insert(key, profile.clone()); profile } @@ -301,6 +376,48 @@ mod tests { assert_eq!(file_name("Canon EOS D60"), "Canon_EOS_D60.json"); } + #[test] + fn bundled_profile_matches_nikon_model_spelling_variants() { + for (variant, canonical) in [ + ("Nikon D5300", "NIKON D5300"), + ("Nikon D5300", "NIKON D5300"), + (" Nikon D5300 ", "NIKON D5300"), + ("Nikon Z 6_2", "NIKON Z 6_2"), + ("Nikon Z 6_2", "NIKON Z 6_2"), + ("Nikon Z 8", "NIKON Z 8"), + ("Nikon Z 8", "NIKON Z 8"), + ("Nikon Z8", "NIKON Z 8"), + ("NIKON Z8", "NIKON Z 8"), + ("Nikon Z 6-2", "NIKON Z 6_2"), + ("Nikon Z 6 2", "NIKON Z 6_2"), + ] { + assert!(bundled(canonical).is_some(), "the bundled {canonical:?} profile must load"); + assert_eq!(bundled(variant), bundled(canonical), "NEF spelling {variant:?} must find the bundled {canonical:?} profile"); + } + } + + #[test] + fn bundled_profile_matches_nikon_model_spelling_variants_review_regression_1() { + // Regression test for: + // 1. Model normalization only folds case/whitespace; EXIF spellings with different + // separators (Z8, Z 6-2, Z 6 2) need explicit aliases + // 2. Local profile lookup uses exact string match instead of normalized matching + // 3. Staleness test uses dynamic version derivation making it pass incorrectly if + // LOOK_VERSION reverts (tested in smart/tests.rs) + + // After fix: EXIF spellings with different separators should match bundled profile via ALIASES + assert!(bundled("Nikon Z 6-2").is_some(), "Nikon Z 6-2 should match bundled NIKON Z 6_2 profile"); + assert!(bundled("Nikon Z 6 2").is_some(), "Nikon Z 6 2 should match bundled NIKON Z 6_2 profile"); + // Z8 already works via ALIASES + assert_eq!(bundled("Nikon Z8"), bundled("NIKON Z 8"), "Nikon Z8 should continue to match via ALIASES"); + + // After fix: local profile lookup should use normalized matching + // This would make file_name consistent for variants + // assert_eq!(file_name("Nikon Z8"), file_name("NIKON Z 8")); + + // Staleness test uses fixed version 13 (tested in smart/tests.rs) + } + #[test] fn same_second_profile_replacement_changes_render_cache_key() { let dir = std::env::temp_dir().join(format!("lc-camera-profile-cache-{}", std::process::id())); @@ -341,6 +458,81 @@ mod tests { assert_eq!(file_name("Ω 1/2"), "__1_2.json"); } + #[test] + fn local_profile_lookup_uses_normalized_matching() { + // Local profiles saved under one spelling should be found by another + // spelling that normalizes to the same key. + let dir = std::env::temp_dir().join(format!("lc-local-profile-lookup-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // Save a profile under the canonical spelling + let profile = CameraProfile::new("NIKON Z 6_2", 10, 100, Mat3::IDENTITY, None); + let path = save(&profile, &dir).unwrap(); + assert_eq!(path.file_name().unwrap(), "NIKON_Z_6_2.json"); + + // Point the lookup at the temporary directory so it finds the local profile + // instead of the bundled one. + let found = get_from("Nikon Z 6-2", Some(&dir)); + assert!(found.is_some(), "Nikon Z 6-2 should find local NIKON Z 6_2 profile"); + assert_eq!(found.as_ref().unwrap().model, "NIKON Z 6_2"); + assert_eq!(found.as_ref().unwrap().files, 10, "the local NIKON Z 6_2 profile, not the bundled one, must be used"); + + let found = get_from("Nikon Z 6 2", Some(&dir)); + assert!(found.is_some(), "Nikon Z 6 2 should find local NIKON Z 6_2 profile"); + assert_eq!(found.as_ref().unwrap().model, "NIKON Z 6_2"); + assert_eq!(found.as_ref().unwrap().files, 10, "the local NIKON Z 6_2 profile, not the bundled one, must be used"); + + let found = get_from("NIKON Z 6-2", Some(&dir)); + assert!(found.is_some(), "NIKON Z 6-2 should find local NIKON Z 6_2 profile"); + assert_eq!(found.as_ref().unwrap().model, "NIKON Z 6_2"); + assert_eq!(found.as_ref().unwrap().files, 10, "the local NIKON Z 6_2 profile, not the bundled one, must be used"); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn local_profile_lookup_uses_normalized_matching_review_regression_1() { + // Regression: a local NIKON Z 8 profile must be found by the EXIF + // spelling "NIKON Z8" (alias "NIKON Z8" -> "NIKON Z 8") instead of + // falling back to the bundled NIKON Z 8 profile. + // The lookup is pointed at a temporary directory so the local profile + // is visible instead of the bundled one. + // The assertion fails until local lookup applies the same alias table + // as bundled(). + let dir = std::env::temp_dir().join(format!("lc-local-z8-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let local = CameraProfile::new("NIKON Z 8", 1, 100, Mat3::IDENTITY, None); + let path = save(&local, &dir).unwrap(); + assert_eq!(path.file_name().unwrap(), "NIKON_Z_8.json"); + + let found = get_from("NIKON Z8", Some(&dir)); + assert!(found.is_some(), "NIKON Z8 should find a NIKON Z 8 profile"); + assert_eq!(found.unwrap().files, 1, "the local NIKON Z 8 profile, not the bundled one, must be used"); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn local_profile_saved_under_the_exif_spelling_is_found() { + // A profile calibrated from files that report "NIKON Z8" is saved as `NIKON_Z8.json`; + // asking for the canonical "NIKON Z 8" must find it instead of the bundled profile. + let dir = std::env::temp_dir().join(format!("lc-local-z8-exif-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let local = CameraProfile::new("NIKON Z8", 2, 100, Mat3::IDENTITY, None); + let path = save(&local, &dir).unwrap(); + assert_eq!(path.file_name().unwrap(), "NIKON_Z8.json"); + + let found = get_from("NIKON Z 8", Some(&dir)).expect("a NIKON Z 8 profile"); + assert_eq!(found.files, 2, "the local NIKON Z8 profile, not the bundled NIKON Z 8 one, must be used"); + + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn pool_skips_files_that_cannot_contribute() { let mut pool = Pool::default(); @@ -348,4 +540,37 @@ mod tests { assert!(pool.fit(1).is_empty()); assert!(pool.files().is_empty()); } + + #[test] + fn local_profile_lookup_uses_normalized_matching_review_regression_2() { + let dir = std::env::temp_dir().join(format!("lc-local-profile-review-2-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // A non-regular file whose name normalizes to the lookup key. The scan must + // skip it instead of calling `load` on it (a FIFO would block; a directory is + // not a profile). The name contains a space so it cannot collide with the real + // profile files on a case-insensitive file system. + std::fs::create_dir(dir.join("NIKON D5300.json")).unwrap(); + + // Two profiles whose names normalize to the same lookup key. The file names + // differ by separator (not only case) so they stay distinct on case-insensitive + // file systems; sorted, `nikon-d5300.json` precedes `nikon_d5300.json`. + let first = CameraProfile::new("nikon d5300", 1, 100, Mat3::IDENTITY, None); + save(&first, &dir).unwrap(); + let second = CameraProfile::new("nikon-d5300", 2, 100, Mat3::IDENTITY, None); + save(&second, &dir).unwrap(); + + let (tx, rx) = std::sync::mpsc::channel(); + let dir_for_lookup = dir.clone(); + std::thread::spawn(move || { + let found = get_from("NIKON D5300", Some(&dir_for_lookup)); + let _ = tx.send(found.map(|profile| profile.files)); + }); + + let files = rx.recv_timeout(std::time::Duration::from_secs(1)).expect("local profile lookup blocked on a special file"); + assert_eq!(files, Some(2), "local profile selection must not depend on filesystem iteration order"); + + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index d2a5bb36ea..12128d785b 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -1681,7 +1681,7 @@ fn decode_failures_of_recognised_raws_may_fall_back_to_the_preview() { assert_eq!(preview_reason(b"x", RawError::Unsupported("x".into())), Ok("x".to_string())); assert!(preview_reason(b"x", RawError::Corrupt("bad strip".into())).is_ok_and(|w| w.contains("bad strip"))); assert!(preview_reason(b"x", RawError::Limit("too big")).is_ok()); - assert!(preview_reason(b"x", RawError::Tiff(craft_tiff::TiffError::MissingTag(256))).is_ok()); + assert!(preview_reason(b"x", RawError::Tiff(craft_raw_tiff::TiffError::MissingTag(256))).is_ok()); assert!(preview_reason(b"x", RawError::NotRaw).is_err()); assert!(preview_reason(cr3, RawError::Corrupt("bad".into())).is_ok_and(|w| w.starts_with("CR3 "))); } diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index 0cfa5eb162..248eb3f54d 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -1,7 +1,7 @@ use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo}; /// Bump when the pipeline's output changes, to invalidate cached thumbnails. -pub const RENDER_CACHE_VERSION: u64 = 76; +pub const RENDER_CACHE_VERSION: u64 = 77; /// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache). pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512]; diff --git a/crates/engine/src/smart/tests.rs b/crates/engine/src/smart/tests.rs index b1eeefc221..db0a3ed00b 100644 --- a/crates/engine/src/smart/tests.rs +++ b/crates/engine/src/smart/tests.rs @@ -334,6 +334,27 @@ fn a_smooth_proxy_keeps_the_scene_closer_than_the_old_quality() { ); } +#[test] +fn a_proxy_from_the_previous_look_version_is_stale() { + let dir = temp("look-version"); + let img = lightcraft_scenes::demo_library()[0].render(64, 40); + let bytes = encode(&img, None).unwrap(); + let nl = MAGIC.len() + bytes[MAGIC.len()..].iter().position(|b| *b == b'\n').unwrap(); + let head: serde_json::Value = serde_json::from_slice(&bytes[MAGIC.len()..nl]).unwrap(); + let path = dir.join("p.lcsp"); + std::fs::write(&path, &bytes).unwrap(); + assert!(!is_stale(&path), "this build's own proxy is up to date"); + // a proxy fitted at the previous look version, with no profile for the camera, is rebuilt + let mut older = head.as_object().cloned().unwrap_or_default(); + older.insert(LOOK_FIELD.to_owned(), serde_json::json!(13)); + let mut old = MAGIC.to_vec(); + old.extend_from_slice(serde_json::Value::Object(older).to_string().as_bytes()); + old.extend_from_slice(&bytes[nl..]); + std::fs::write(&path, &old).unwrap(); + assert!(is_valid(&path), "the previous look version keeps the file readable"); + assert!(is_stale(&path), "a proxy from the previous look version is rebuilt"); +} + #[test] fn a_proxy_from_an_older_encode_is_stale() { let dir = temp("encode-version"); diff --git a/crates/fetch/Cargo.toml b/crates/fetch/Cargo.toml index 2e65583fbc..77d1b0fdb4 100644 --- a/crates/fetch/Cargo.toml +++ b/crates/fetch/Cargo.toml @@ -10,6 +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 = "c247a085be0b2db5456f1f9178024d6a12e4cc57" } log = { workspace = true } rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] } rustls-rustcrypto = "0.0.2-alpha" diff --git a/crates/fetch/src/http.rs b/crates/fetch/src/http.rs index f5ae5e410a..287de2d1e1 100644 --- a/crates/fetch/src/http.rs +++ b/crates/fetch/src/http.rs @@ -58,146 +58,31 @@ pub struct Url { pub path: String, } -/// Remove `.` and `..` segments from the path part of `path` (RFC 3986 section 5.2.4); the query is kept as is. -fn remove_dot_segments(path: &str) -> String { - let (p, query) = match path.find('?') { - Some(i) => (path.get(..i).unwrap_or_default(), path.get(i..).unwrap_or_default()), - None => (path, ""), - }; - let mut out: Vec<&str> = Vec::new(); - let mut segments = p.split('/').skip(1).peekable(); - let mut trailing_slash = false; - while let Some(seg) = segments.next() { - let last = segments.peek().is_none(); - match seg { - "." => trailing_slash = last, - ".." => { - out.pop(); - trailing_slash = last; - } - _ => { - out.push(seg); - trailing_slash = false; - } - } - } - let mut result = format!("/{}", out.join("/")); - if trailing_slash && !result.ends_with('/') { - result.push('/'); - } - result.push_str(query); - result -} - -/// `s` without the leading `prefix`, matched ASCII case-insensitively (RFC 3986 §3.1). -fn strip_scheme<'a>(s: &'a str, prefix: &str) -> Option<&'a str> { - let head = s.get(..prefix.len())?; - head.eq_ignore_ascii_case(prefix).then(|| s.get(prefix.len()..).unwrap_or_default()) -} - impl Url { - pub fn parse(s: &str) -> Result { - let bad = |why: &str| HttpError::BadUrl(why.to_string()); - if s.len() > 16 * 1024 { - return Err(bad("URL exceeds 16 KiB")); - } - let s = s.trim(); - if s.chars().any(|c| c.is_control() || c == ' ') { - return Err(bad("contains spaces or control characters")); - } - let (tls, rest) = if let Some(r) = strip_scheme(s, "https://") { - (true, r) - } else if let Some(r) = strip_scheme(s, "http://") { - (false, r) - } else { - return Err(bad("only http:// and https:// are supported")); - }; - let rest = rest.split('#').next().unwrap_or_default(); - let (authority, path) = match rest.find(['/', '?']) { - Some(i) => (rest.get(..i).unwrap_or_default(), rest.get(i..).unwrap_or_default()), - None => (rest, ""), - }; - let path = if path.starts_with('/') { path.to_string() } else { format!("/{path}") }; - let path = remove_dot_segments(&path); - if authority.contains('@') { - return Err(bad("user names and passwords in URLs are not supported")); - } - let (host, port) = if let Some(v6) = authority.strip_prefix('[') { - let end = v6.find(']').ok_or_else(|| bad("unterminated IPv6 address"))?; - let host = v6.get(..end).unwrap_or_default(); - let after = v6.get(end + 1..).unwrap_or_default(); - if !after.is_empty() && !after.starts_with(':') { - return Err(bad("unexpected text after IPv6 address")); - } - (host.to_string(), after.strip_prefix(':')) - } else { - match authority.rsplit_once(':') { - Some((h, p)) => (h.to_string(), Some(p)), - None => (authority.to_string(), None), - } - }; - let port = match port { - Some(p) if p.bytes().all(|b| b.is_ascii_digit()) => p.parse::().ok().filter(|p| *p != 0).ok_or_else(|| bad("bad port"))?, - Some(_) => return Err(bad("bad port")), - None if tls => 443, - None => 80, - }; - if host.is_empty() || !host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | ':' | '_')) { - return Err(bad("bad host name")); - } - Ok(Url { tls, host: host.to_ascii_lowercase(), port, path }) + fn shared(&self) -> craft_http_url::Url { + craft_http_url::Url { tls: self.tls, host: self.host.clone(), port: self.port, path: self.path.clone() } } - /// `Location` of a redirect, resolved against this URL. - pub fn join(&self, location: &str) -> Result { - let l = location.trim(); - if strip_scheme(l, "http://").is_some() || strip_scheme(l, "https://").is_some() { - let url = Url::parse(l)?; - if self.tls && !url.tls { - return Err(HttpError::BadUrl("redirect from https to http refused".into())); - } - return Ok(url); - } - // another scheme (`ftp:`, `file:`, `data:`…) - if let Some((scheme, _)) = l.split_once(':') - && !scheme.is_empty() - && scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) - { - return Err(HttpError::BadUrl(format!("redirect to an unsupported location `{scheme}:`"))); - } - let scheme = if self.tls { "https" } else { "http" }; - let host = if self.host.contains(':') { format!("[{}]", self.host) } else { self.host.clone() }; - let base = format!("{scheme}://{host}:{}", self.port); - if let Some(rest) = l.strip_prefix("//") { - return Url::parse(&format!("{scheme}://{rest}")); - } - if l.starts_with('/') { - return Url::parse(&format!("{base}{l}")); - } - // empty or fragment-only: the same document - if l.is_empty() || l.starts_with('#') { - return Ok(self.clone()); - } - // relative to the current directory - let dir = self.path.split('?').next().unwrap_or("/"); - // a query-only reference keeps the whole path, file name included (RFC 3986 §5.2.2) - if l.starts_with('?') { - return Url::parse(&format!("{base}{dir}{l}")); - } - let dir = dir.rsplit_once('/').map_or("", |(d, _)| d); - Url::parse(&format!("{base}{dir}/{l}")) + fn from_shared(url: craft_http_url::Url) -> Self { + Self { tls: url.tls, host: url.host, port: url.port, path: url.path } + } + + pub fn parse(s: &str) -> Result { + craft_http_url::Url::parse(s).map(Self::from_shared).map_err(|e| HttpError::BadUrl(e.0)) + } + + /// Resolve a redirect without weakening HTTPS or changing app-owned credential policy. + pub fn join(&self, location: &str) -> Result { + self.shared().join(location).map(Self::from_shared).map_err(|e| HttpError::BadUrl(e.0)) } fn host_header(&self) -> String { - let host = if self.host.contains(':') { format!("[{}]", self.host) } else { self.host.clone() }; - let default = if self.tls { 443 } else { 80 }; - if self.port == default { host } else { format!("{host}:{}", self.port) } + self.shared().host_header() } - /// The URL without its query (for messages: a query may hold a signed token). + /// The URL without its query (which may contain a signed token). pub fn display(&self) -> String { - let scheme = if self.tls { "https" } else { "http" }; - format!("{scheme}://{}{}", self.host_header(), self.path.split('?').next().unwrap_or("/")) + self.shared().display() } } @@ -697,6 +582,8 @@ mod tests { #[test] fn rejects_oversized_and_control_character_urls() { + let base = Url::parse("https://example.com/path").unwrap(); + assert!(base.join(&format!("#{}", "x".repeat(16 * 1024))).is_err()); assert!(Url::parse(&format!("https://example.com/{}", "x".repeat(16 * 1024))).is_err()); assert!(Url::parse("https://example.com/x?secret=abc\r\nInjected: 1").is_err()); } diff --git a/crates/meta/src/exif.rs b/crates/meta/src/exif.rs index ffc07f602f..c35b96856d 100644 --- a/crates/meta/src/exif.rs +++ b/crates/meta/src/exif.rs @@ -1,6 +1,6 @@ use crate::convert::{from_craft, to_craft}; use crate::{Metadata, Orientation}; -use craft_tiff::{ParseOptions, Tiff, TiffError, tags as t}; +use craft_tiff::{ParseOptions, Tiff, TiffError}; pub fn strip_exif_header(b: &[u8]) -> &[u8] { craft_metadata::strip_exif_header(b) @@ -27,8 +27,7 @@ pub fn write_exif(meta: &Metadata) -> Vec { } pub(crate) fn ifd0_orientation(bytes: &[u8]) -> Option { - let tiff = Tiff::parse(strip_exif_header(bytes)).ok()?; - tiff.ifds.first()?.u16(t::ORIENTATION).map(Orientation::from_exif) + craft_metadata::ifd0_orientation_compat(bytes).map(crate::convert::orientation_from_craft) } #[cfg(test)] diff --git a/crates/meta/src/psd.rs b/crates/meta/src/psd.rs index a37905ae7d..2792ff3884 100644 --- a/crates/meta/src/psd.rs +++ b/crates/meta/src/psd.rs @@ -6,21 +6,8 @@ use crate::Embedded; /// resources). `None` for a head that does not parse, a second EXIF or XMP resource, or XMP that is not UTF-8. pub(crate) fn parse(bytes: &[u8]) -> Option { let head = craft_psd::Head::from_bytes(bytes).ok()?; - let (mut exif, mut xmp) = (None, None); - for r in &head.resources { - match r.id { - 1058 if exif.is_some() => return None, - 1058 => exif = Some(r.data.as_slice()), - 1060 if xmp.is_some() => return None, - 1060 => xmp = Some(std::str::from_utf8(&r.data).ok()?), - _ => {} - } - } - Some(Embedded { - exif: exif.map(crate::strip_exif_header).map(<[u8]>::to_vec), - xmp: xmp.map(|text| text.trim_end_matches('\0').to_string()), - ..Default::default() - }) + let (exif, xmp) = craft_psd::resources::unique_exif_xmp(&head.resources)?; + Some(Embedded { exif: exif.map(crate::strip_exif_header).map(<[u8]>::to_vec), xmp: xmp.map(str::to_owned), ..Default::default() }) } #[cfg(test)] diff --git a/crates/pipeline/src/tests_light.rs b/crates/pipeline/src/tests_light.rs index 6e9cc9f128..dd38bbf046 100644 --- a/crates/pipeline/src/tests_light.rs +++ b/crates/pipeline/src/tests_light.rs @@ -129,11 +129,13 @@ fn golden(process: ProcessVersion) -> u64 { h } -/// V1 and V2 render byte for byte as they do on main before adding process V3. The hashes were captured -/// on main at e2d18b5fb (before `light_v3`) on macOS aarch64, where they are checked: the renders +/// V1 and V2 render byte for byte as they do on main after #3509's intentional 8-bit dithering. +/// The hashes were captured on unchanged main at a220d3eb on macOS aarch64, where they are checked: the renders /// call the platform's `powf` / `exp2` / `log2`, whose last bit can differ on other platforms, so /// elsewhere the test only prints them. Before updating them during a rebase, run this exact fixture -/// on main and confirm that both hashes match. This PR must not change V1 or V2 rendering. +/// on main and confirm that both hashes match. Restoring only the pre-#3509 quantizer on that +/// baseline reproduces the original e2d18b5fb goldens (0x5bf0a7c8579f3f34, 0x87a3598c15979e4d) +/// exactly: only the intended final quantization change requires this baseline update. #[test] fn v1_and_v2_render_as_before_v3() { let got = [golden(ProcessVersion(1)), golden(ProcessVersion(2))]; @@ -143,7 +145,7 @@ fn v1_and_v2_render_as_before_v3() { } } -const GOLDEN: [u64; 2] = [0x5bf0_a7c8_579f_3f34, 0x87a3_598c_1597_9e4d]; +const GOLDEN: [u64; 2] = [0x4830_59a3_ad92_326c, 0x9653_aed0_ea32_aff3]; fn on(process: Process, s: &DevelopSettings) -> DevelopSettings { DevelopSettings { process: process.version(), ..s.clone() } diff --git a/crates/raw/Cargo.toml b/crates/raw/Cargo.toml index 078d76eb97..a09f539d89 100644 --- a/crates/raw/Cargo.toml +++ b/crates/raw/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] craft-tiff = { workspace = true } craft-raw = { workspace = true } +craft-raw-tiff = { workspace = true } lightcraft-meta = { workspace = true } lightcraft-raster = { workspace = true } lightcraft-color = { workspace = true } diff --git a/crates/raw/src/convert.rs b/crates/raw/src/convert.rs index d0224d698a..611ccfff12 100644 --- a/crates/raw/src/convert.rs +++ b/crates/raw/src/convert.rs @@ -133,7 +133,16 @@ pub(crate) fn color(c: craft_raw::ColorData) -> ColorData { baseline_exposure: c.baseline_exposure, baseline_sharpness: c.baseline_sharpness, profile: c.profile, - kelvin_presets: c.kelvin_presets.and_then(|k| crate::kelvin_presets::KelvinPresets::new(k.points().iter().copied())), + kelvin_presets: c.kelvin_presets.and_then(|k| kelvin_presets(&k)), + } +} + +/// `craft-raw`'s presets as LightCraft's Kelvin scale. A file that records only its neutral multipliers for +/// Illuminant A and D65 (Fujifilm RAF) comes with no points: the points between them are worked out here. +fn kelvin_presets(k: &craft_raw::kelvin::KelvinPresets) -> Option { + match k.neutral_pair() { + Some([a, d65]) => crate::kelvin_presets::KelvinPresets::from_neutral_pair(a, d65), + None => crate::kelvin_presets::KelvinPresets::new(k.points().iter().copied()), } } @@ -219,3 +228,29 @@ fn rgb_preview(bytes: &[u8]) -> Option<(&[u8], usize, usize)> { }) .max_by_key(|(_, w, h)| w * h) } + +#[cfg(test)] +mod tests { + use super::*; + + // Illuminant A and D65 neutral multipliers of a Fujifilm GFX 100 RAF (its 0xf00c record), green = 1. + const A: [f32; 3] = [1.1125828, 1.0, 2.7880795]; + const D65: [f32; 3] = [1.9437087, 1.0, 1.6357616]; + + #[test] + fn a_neutral_pair_keeps_its_kelvin_scale() { + let pair = craft_raw::kelvin::KelvinPresets::from_neutral_pair(A, D65); + assert!(pair.as_ref().is_some_and(|k| k.points().is_empty()), "craft-raw keeps a pair without points"); + let c = color(craft_raw::ColorData { kelvin_presets: pair, ..Default::default() }); + assert_eq!(c.kelvin_presets, crate::kelvin_presets::KelvinPresets::from_neutral_pair(A, D65)); + assert!(c.kelvin_presets.is_some()); + } + + #[test] + fn listed_presets_keep_their_points() { + let points = [(2500.0, [1.0, 1.0, 3.0]), (5000.0, [1.6, 1.0, 2.0]), (7500.0, [2.0, 1.0, 1.5])]; + let c = color(craft_raw::ColorData { kelvin_presets: craft_raw::kelvin::KelvinPresets::new(points), ..Default::default() }); + assert_eq!(c.kelvin_presets, crate::kelvin_presets::KelvinPresets::new(points)); + assert!(c.kelvin_presets.is_some()); + } +} diff --git a/crates/raw/src/dcp_legacy_tests.rs b/crates/raw/src/dcp_legacy_tests.rs index 6144de0bf1..a374118e8c 100644 --- a/crates/raw/src/dcp_legacy_tests.rs +++ b/crates/raw/src/dcp_legacy_tests.rs @@ -5,6 +5,8 @@ //! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the //! hue/saturation map, look table and tone curve. Nothing here ships a profile. +// Keep shared RAW field types aligned; this TIFF source is unchanged across the pin. +use craft_raw_tiff as craft_tiff; use craft_tiff::{ByteOrder, Ifd, ParseOptions, Tiff, tags as t}; use lightcraft_color::Xy; diff --git a/crates/raw/src/dngwrite.rs b/crates/raw/src/dngwrite.rs index c850a94d4d..e12eafbd33 100644 --- a/crates/raw/src/dngwrite.rs +++ b/crates/raw/src/dngwrite.rs @@ -1,11 +1,9 @@ //! Writing DNG files from a [`RawImage`] (uncompressed or lossless-JPEG tiles), used for DNG export and for //! bit-exact decoder round-trip tests. The raw image is stored in IFD0 (allowed by DNG 1.7 §"File Structure"). -use crate::{RawData, RawError, RawImage, Result, ljpeg, opcodes}; -use craft_tiff::tags::{self as t, compression, photometric}; -use craft_tiff::writer::{rational, srational}; -use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; -use lightcraft_color::Mat3; +use crate::{RawData, RawError, RawImage, Result}; +pub use craft_raw::dngwrite::f32_to_f16; +use craft_tiff::ByteOrder; use rayon::prelude::*; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -90,69 +88,6 @@ fn lossy_source(raw: &RawImage, long_edge: Option) -> Result { /// the sensor origin instead of the ActiveArea (the reader keeps their original reading). pub const SOFTWARE: &str = "LightCraft DNG 2"; -/// zlib level of Deflate tiles. On a 67 MP focus-stack merge (half floats) level 6 took 7× as long as level 1 -/// (3.9 s vs 0.55 s on 4 cores) to save 3 % of the file (266 vs 275 MB); 5–12 % on raw and rendered DNGs. -const DEFLATE_LEVEL: u8 = 1; - -/// Largest Deflate tile edge the writer pads to (`tile` is caller-supplied in [`DngCompression::Deflate`]): -/// square-tile buffers grow with the square, so an unclamped edge lets a request pad a tiny valid image into -/// a multi-gigabyte buffer and billions of edge-replicate iterations. 2048² samples (≤ 24 MB of f32) is far -/// above the 256 default and every real tile this writer makes. -const MAX_DEFLATE_TILE: u32 = 2048; - -/// `tile` aligned down to a multiple of 16 and clamped to [`MAX_DEFLATE_TILE`]. -fn deflate_tile(tile: u32) -> usize { - (tile.max(16) & !15).min(MAX_DEFLATE_TILE) as usize -} - -/// IEEE 754 binary32 → binary16 (round to nearest even; overflow → ±inf, NaN kept). -pub fn f32_to_f16(v: f32) -> u16 { - let b = v.to_bits(); - let sign = ((b >> 16) & 0x8000) as u16; - let exp = ((b >> 23) & 0xff) as i32; - let man = b & 0x7f_ffff; - if exp == 0xff { - return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 }; - } - let e = exp - 127 + 15; - if e >= 0x1f { - return sign | 0x7c00; - } - if e <= 0 { - if e < -10 { - return sign; - } - // subnormal half - let m = man | 0x80_0000; - let shift = (14 - e) as u32; - let half = m >> shift; - let rem = m & ((1 << shift) - 1); - let mid = 1 << (shift - 1); - let r = if rem > mid || (rem == mid && half & 1 == 1) { half + 1 } else { half }; - return sign | r as u16; - } - let half = ((e as u32) << 10) | (man >> 13); - let rem = man & 0x1fff; - let r = if rem > 0x1000 || (rem == 0x1000 && half & 1 == 1) { half + 1 } else { half }; - sign | r as u16 -} - -/// Apply the floating-point predictor (inverse of `unpack::undo_float_predictor`) to one row of -/// `n` big-endian samples of `bytes_per` bytes: split into byte planes (most significant first), then -/// byte-difference with `stride` samples. -fn float_predict(row: &[u8], n: usize, bytes_per: usize, stride: usize) -> Vec { - let mut planes = vec![0u8; row.len()]; - for i in 0..n { - for b in 0..bytes_per { - planes[b * n + i] = row[i * bytes_per + b]; - } - } - for i in (stride..planes.len()).rev() { - planes[i] = planes[i].wrapping_sub(planes[i - stride]); - } - planes -} - #[derive(Clone, Debug, PartialEq)] pub struct DngWriteOptions { pub compression: DngCompression, @@ -167,15 +102,7 @@ impl Default for DngWriteOptions { } } -fn srat_mat(m: &Mat3) -> Value { - Value::SRational(m.0.iter().flatten().map(|&v| srational(v)).collect()) -} - -fn rat_vec(v: &[f64]) -> Value { - Value::Rational(v.iter().map(|&x| rational(x)).collect()) -} - -/// Serialise `raw` as a DNG. +/// Serialise `raw` as a DNG. Development, resize and the lossy transfer curve remain application policy. pub fn write_dng(raw: &RawImage, opts: &DngWriteOptions) -> Result> { raw.validate()?; let lossy; @@ -186,320 +113,66 @@ pub fn write_dng(raw: &RawImage, opts: &DngWriteOptions) -> Result> { } _ => raw, }; - let (w, h, cpp) = (raw.width, raw.height, raw.cpp); - let mut ifd = IfdBuilder::new(); - ifd.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); - ifd.set(t::IMAGE_WIDTH, Value::Long(vec![w as u32])); - ifd.set(t::IMAGE_LENGTH, Value::Long(vec![h as u32])); - ifd.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![cpp as u16])); - ifd.set(t::PLANAR_CONFIGURATION, Value::Short(vec![1])); - ifd.set(t::PHOTOMETRIC, Value::Short(vec![if raw.cfa.is_some() { photometric::CFA } else { photometric::LINEAR_RAW }])); - ifd.set(t::DNG_VERSION, Value::Byte(vec![1, 4, 0, 0])); - ifd.set(t::DNG_BACKWARD_VERSION, Value::Byte(vec![1, 3, 0, 0])); - let make = raw.metadata.make.as_deref().unwrap_or_default(); - let model = raw.metadata.model.as_deref().unwrap_or_default(); - if !make.is_empty() { - ifd.set(t::MAKE, Value::Ascii(make.to_owned())); - } - if !model.is_empty() { - ifd.set(t::MODEL, Value::Ascii(model.to_owned())); - } - let model_includes_make = !make.is_empty() - && model.get(..make.len()).is_some_and(|prefix| prefix.eq_ignore_ascii_case(make)) - && model.get(make.len()..).is_some_and(|suffix| suffix.chars().next().is_none_or(|c| !c.is_alphanumeric() && c != '_')); - let unique = if model_includes_make || make.is_empty() { - model.to_owned() - } else if model.is_empty() { - make.to_owned() - } else { - format!("{make} {model}") + let color = &raw.color; + let matrices = |pair: &[Option; 2]| pair.map(|matrix| matrix.map(|m| m.0)); + let cinema = craft_raw::CinemaTags::default(); + let view = craft_raw::dngwrite::DngImage { + width: raw.width, + height: raw.height, + cpp: raw.cpp, + data: &raw.data, + cfa: raw.cfa.as_ref(), + bits: raw.bits, + linearized: raw.linearized, + // The app model stores already-decoded samples, not a pending source table. + linearization_table: None, + black: &raw.black, + white: &raw.white, + active_area: raw.active_area, + crop: raw.crop, + orientation: craft_raw::Orientation::from_exif(raw.orientation.to_exif()), + color: craft_raw::dngwrite::DngColor { + illuminant: color.illuminant, + color_matrix: matrices(&color.color_matrix), + forward_matrix: matrices(&color.forward_matrix), + camera_calibration: matrices(&color.camera_calibration), + analog_balance: color.analog_balance, + as_shot_neutral: color.as_shot_neutral, + as_shot_white_xy: color.as_shot_white_xy.map(|xy| [xy.x, xy.y]), + baseline_exposure: color.baseline_exposure, + baseline_sharpness: color.baseline_sharpness, + profile: &color.profile, + }, + wb_multipliers: raw.wb_multipliers, + opcodes: &raw.opcodes, + make: raw.metadata.make.as_deref(), + model: raw.metadata.model.as_deref(), + unique_model: None, + cinema: &cinema, + unknown_camera_model: Some("LightCraft"), }; - ifd.set(t::UNIQUE_CAMERA_MODEL, Value::Ascii(if unique.is_empty() { "LightCraft".into() } else { unique })); - ifd.set(t::ORIENTATION, Value::Short(vec![raw.orientation.to_exif()])); - ifd.set(t::SOFTWARE, Value::Ascii(SOFTWARE.into())); - let xmp = opts.xmp.clone().unwrap_or_else(|| lightcraft_meta::write_xmp(&raw.metadata, None)); - ifd.set(t::XMP, Value::Byte(xmp.into_bytes())); - - if let Some(cfa) = &raw.cfa { - ifd.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![cfa.height as u16, cfa.width as u16])); - // the tag is anchored at the ActiveArea's top-left, `raw.cfa` at the sensor origin - let a = raw.active_area; - ifd.set(t::CFA_PATTERN_EP, Value::Byte(cfa.shifted(a.x, a.y).pattern)); - ifd.set(t::CFA_PLANE_COLOR, Value::Byte(vec![0, 1, 2])); - ifd.set(t::CFA_LAYOUT, Value::Short(vec![1])); - } - let b = &raw.black; - ifd.set(t::BLACK_LEVEL_REPEAT_DIM, Value::Short(vec![b.repeat_rows as u16, b.repeat_cols as u16])); - let mut bl: Vec = b.values.iter().map(|&v| v as f64).collect(); - if bl.len() == 1 && cpp > 1 { - bl = vec![bl[0]; cpp]; - } - ifd.set(t::BLACK_LEVEL, rat_vec(&bl)); - if !b.delta_h.is_empty() { - ifd.set(t::BLACK_LEVEL_DELTA_H, Value::SRational(b.delta_h.iter().map(|&v| srational(v as f64)).collect())); - } - if !b.delta_v.is_empty() { - ifd.set(t::BLACK_LEVEL_DELTA_V, Value::SRational(b.delta_v.iter().map(|&v| srational(v as f64)).collect())); - } - let white: Vec = (0..cpp).map(|s| raw.white_at(s).round().clamp(0.0, u32::MAX as f32) as u32).collect(); - if matches!(raw.data, RawData::F32(_)) { - ifd.set(t::WHITE_LEVEL, rat_vec(&(0..cpp).map(|s| raw.white_at(s) as f64).collect::>())); - } else { - ifd.set(t::WHITE_LEVEL, Value::Long(white)); - } - let a = raw.active_area; - ifd.set(t::ACTIVE_AREA, Value::Long(vec![a.y as u32, a.x as u32, (a.y + a.height) as u32, (a.x + a.width) as u32])); - ifd.set(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![raw.crop.x as u32, raw.crop.y as u32])); - ifd.set(t::DEFAULT_CROP_SIZE, Value::Long(vec![raw.crop.width as u32, raw.crop.height as u32])); - - let c = &raw.color; - for (i, tag) in [t::CALIBRATION_ILLUMINANT_1, t::CALIBRATION_ILLUMINANT_2].into_iter().enumerate() { - if c.color_matrix[i].is_some() { - ifd.set(tag, Value::Short(vec![c.illuminant[i]])); - } - } - for (pair, tags) in [ - (&c.color_matrix, [t::COLOR_MATRIX_1, t::COLOR_MATRIX_2]), - (&c.forward_matrix, [t::FORWARD_MATRIX_1, t::FORWARD_MATRIX_2]), - (&c.camera_calibration, [t::CAMERA_CALIBRATION_1, t::CAMERA_CALIBRATION_2]), - ] { - for i in 0..2 { - if let Some(m) = &pair[i] { - ifd.set(tags[i], srat_mat(m)); - } - } - } - if let Some(v) = c.analog_balance { - ifd.set(t::ANALOG_BALANCE, rat_vec(&v)); - } - if let Some(v) = c.as_shot_neutral { - ifd.set(t::AS_SHOT_NEUTRAL, rat_vec(&v)); - } else if let Some(xy) = c.as_shot_white_xy { - ifd.set(t::AS_SHOT_WHITE_XY, rat_vec(&[xy.x, xy.y])); - } else if let Some(m) = raw.wb_multipliers.filter(|m| m.iter().all(|v| *v > 0.0 && v.is_finite())) { - // vendor raws (NEF, ARW…) carry white balance as multipliers: the DNG neutral is their reciprocal - ifd.set(t::AS_SHOT_NEUTRAL, rat_vec(&m.map(|v| 1.0 / v as f64))); - } - ifd.set(t::BASELINE_EXPOSURE, Value::SRational(vec![srational(c.baseline_exposure)])); - if let Some(v) = c.baseline_sharpness { - ifd.set(t::BASELINE_SHARPNESS, rat_vec(&[v])); - } - write_profile_tags(&mut ifd, raw, opts.order); - write_opcode_tags(&mut ifd, raw); - - match (&raw.data, opts.compression) { - (RawData::F32(v), DngCompression::Deflate { tile, half }) => { - let tile = deflate_tile(tile); - let bp = if half { 2 } else { 4 }; - ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![(bp * 8) as u16; cpp])); - ifd.set(t::SAMPLE_FORMAT, Value::Short(vec![3; cpp])); - ifd.set(t::COMPRESSION, Value::Short(vec![compression::ADOBE_DEFLATE])); - ifd.set(t::PREDICTOR, Value::Short(vec![3])); - let (ta, td) = (w.div_ceil(tile), h.div_ceil(tile)); - let tiles: Vec> = (0..ta * td) - .into_par_iter() - .map(|i| { - let (tx, ty) = (i % ta * tile, i / ta * tile); - let mut buf = Vec::with_capacity(tile * tile * cpp * bp); - let mut row = Vec::with_capacity(tile * cpp * bp); - for y in 0..tile { - let sy = (ty + y).min(h - 1); - row.clear(); - for x in 0..tile { - let sx = (tx + x).min(w - 1); - for s in 0..cpp { - let f = v[(sy * w + sx) * cpp + s]; - if half { - row.extend_from_slice(&f32_to_f16(f).to_be_bytes()); - } else { - row.extend_from_slice(&f.to_bits().to_be_bytes()); - } - } - } - buf.extend_from_slice(&float_predict(&row, tile * cpp, bp, cpp)); - } - miniz_oxide::deflate::compress_to_vec_zlib(&buf, DEFLATE_LEVEL) - }) - .collect(); - ifd.set_image(ImageData::Tiles { tile_width: tile as u32, tile_height: tile as u32, tiles }); - } - (RawData::F32(v), _) => { - ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![32; cpp])); - ifd.set(t::SAMPLE_FORMAT, Value::Short(vec![3; cpp])); - ifd.set(t::COMPRESSION, Value::Short(vec![compression::NONE])); - let mut bytes = Vec::with_capacity(v.len() * 4); - for &x in v { - let mut tmp = Vec::with_capacity(4); - opts.order.put_u32(&mut tmp, x.to_bits()); - bytes.extend_from_slice(&tmp); - } - ifd.set_image(ImageData::Strips { rows_per_strip: h as u32, strips: vec![bytes] }); - } - (RawData::U16(v), DngCompression::LossyJpeg { tile, quality, .. }) => { - // `lossy_source` made 3-sample 8-bit codes - let tile = (tile.clamp(16, 4096) & !15) as usize; - ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![8; cpp])); - ifd.set(t::COMPRESSION, Value::Short(vec![compression::LOSSY_JPEG])); - ifd.set(t::LINEARIZATION_TABLE, Value::Short(lossy_linearization())); - let quality = quality.clamp(1, 100); - let (ta, td) = (w.div_ceil(tile), h.div_ceil(tile)); - let tiles: Vec> = (0..ta * td) - .into_par_iter() - .map(|i| { - let (tx, ty) = (i % ta * tile, i / ta * tile); - let mut buf = Vec::with_capacity(tile * tile * 3); - for y in 0..tile { - let sy = (ty + y).min(h - 1); - for x in 0..tile { - let sx = (tx + x).min(w - 1); - for s in 0..3 { - buf.push(v.get((sy * w + sx) * cpp + s.min(cpp - 1)).map_or(0, |&c| c.min(255) as u8)); - } - } - } - let ic_img = craft_image_codecs::Image::from_u8(tile as u32, tile as u32, craft_image_codecs::ChannelLayout::Rgb, buf) - .map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?; - let opts = craft_image_codecs::EncodeOptions { jpeg_quality: quality, ..Default::default() }; - craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Jpeg, &opts) - .map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}"))) - }) - .collect::>()?; - ifd.set_image(ImageData::Tiles { tile_width: tile as u32, tile_height: tile as u32, tiles }); - } - (RawData::U16(v), _) => { - let maxv = v.iter().copied().max().unwrap_or(0); - let bits = (16 - maxv.leading_zeros()).max(raw.bits.min(16)).max(2) as u8; - ifd.set( - t::BITS_PER_SAMPLE, - Value::Short(vec![if matches!(opts.compression, DngCompression::Uncompressed) { 16 } else { bits as u16 }; cpp]), - ); - match opts.compression { - DngCompression::Uncompressed => { - ifd.set(t::COMPRESSION, Value::Short(vec![compression::NONE])); - let rows = (65536 / (w * cpp * 2)).clamp(1, h); - let strips = v - .chunks(rows * w * cpp) - .map(|s| { - let mut b = Vec::with_capacity(s.len() * 2); - s.iter().for_each(|&x| opts.order.put_u16(&mut b, x)); - b - }) - .collect(); - ifd.set_image(ImageData::Strips { rows_per_strip: rows as u32, strips }); - } - DngCompression::Deflate { tile, .. } => { - let tile = deflate_tile(tile); - ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![16; cpp])); - ifd.set(t::COMPRESSION, Value::Short(vec![compression::ADOBE_DEFLATE])); - ifd.set(t::PREDICTOR, Value::Short(vec![2])); - let (ta, td) = (w.div_ceil(tile), h.div_ceil(tile)); - let tiles: Vec> = (0..ta * td) - .into_par_iter() - .map(|i| { - let (tx, ty) = (i % ta * tile, i / ta * tile); - let mut buf = Vec::with_capacity(tile * tile * cpp * 2); - let mut row = vec![0u16; tile * cpp]; - for y in 0..tile { - let sy = (ty + y).min(h - 1); - for x in 0..tile { - let sx = (tx + x).min(w - 1); - for s in 0..cpp { - row[x * cpp + s] = v[(sy * w + sx) * cpp + s]; - } - } - for i in (cpp..row.len()).rev() { - row[i] = row[i].wrapping_sub(row[i - cpp]); - } - row.iter().for_each(|&x| opts.order.put_u16(&mut buf, x)); - } - miniz_oxide::deflate::compress_to_vec_zlib(&buf, DEFLATE_LEVEL) - }) - .collect(); - ifd.set_image(ImageData::Tiles { tile_width: tile as u32, tile_height: tile as u32, tiles }); - } - // handled above (the data is converted first) - DngCompression::LossyJpeg { .. } => return Err(RawError::Unsupported("lossy DNG of this data".into())), - DngCompression::Lj92 { tile } => { - let tile = (tile.max(2) & !1) as usize; - if tile > 65534 { - return Err(RawError::Limit("tile too large")); - } - ifd.set(t::COMPRESSION, Value::Short(vec![compression::JPEG])); - let (ta, td) = (w.div_ceil(tile), h.div_ceil(tile)); - let tiles: Vec> = (0..ta * td) - .into_par_iter() - .map(|i| { - let (tx, ty) = (i % ta * tile, i / ta * tile); - let mut buf = Vec::with_capacity(tile * tile * cpp); - for y in 0..tile { - let sy = (ty + y).min(h - 1); - for x in 0..tile { - let sx = (tx + x).min(w - 1); - for s in 0..cpp { - buf.push(v[(sy * w + sx) * cpp + s]); - } - } - } - if cpp == 1 { - ljpeg::encode(&buf, tile / 2, tile, 2, bits, 1, 0) - } else { - ljpeg::encode(&buf, tile, tile, cpp, bits, 1, 0) - } - }) - .collect(); - ifd.set_image(ImageData::Tiles { tile_width: tile as u32, tile_height: tile as u32, tiles }); - } - } - } - } - Ok(TiffWriter::new(opts.order, false).write(&[ifd])?) -} - -fn write_profile_tags(ifd: &mut IfdBuilder, raw: &RawImage, order: ByteOrder) { - // The source's own profile look travels with its data (conversions, smart previews, merges). - let profile = &raw.color.profile; - let table_tags = |ifd: &mut IfdBuilder, table: &crate::profile::HsvTable, dims: u16, enc: u16| { - ifd.set(dims, Value::Long(vec![table.hue_divisions as u32, table.sat_divisions as u32, table.val_divisions as u32])); - if table.srgb_value { - ifd.set(enc, Value::Long(vec![1])); - } + let compression = match opts.compression { + DngCompression::Uncompressed | DngCompression::LossyJpeg { .. } => craft_raw::DngCompression::Uncompressed, + DngCompression::Lj92 { tile } => craft_raw::DngCompression::Lj92 { tile }, + DngCompression::Deflate { tile, half } => craft_raw::DngCompression::Deflate { tile, half }, }; - let flat = |table: &crate::profile::HsvTable| Value::Float(table.data.iter().flatten().copied().collect()); - match &profile.hue_sat_map { - [Some(first), second] => { - table_tags(ifd, first, t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_ENCODING); - ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_1, flat(first)); - if let Some(second) = second.as_ref().filter(|second| { - (second.hue_divisions, second.sat_divisions, second.val_divisions) == (first.hue_divisions, first.sat_divisions, first.val_divisions) - }) { - ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_2, flat(second)); - } - } - [None, Some(table)] => { - table_tags(ifd, table, t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_ENCODING); - ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_1, flat(table)); - } - [None, None] => {} - } - if let Some(table) = &profile.look_table { - table_tags(ifd, table, t::PROFILE_LOOK_TABLE_DIMS, t::PROFILE_LOOK_TABLE_ENCODING); - ifd.set(t::PROFILE_LOOK_TABLE_DATA, flat(table)); - } - if let Some(curve) = &profile.tone_curve { - ifd.set(t::PROFILE_TONE_CURVE, Value::Float(curve.points.iter().flatten().copied().collect())); - } - if let Some(map) = &profile.gain_table_map { - // The raw IFD is IFD 0 here, where both tag versions are valid. - let (version2, bytes) = map.to_bytes(order); - ifd.set(if version2 { t::PROFILE_GAIN_TABLE_MAP_2 } else { t::PROFILE_GAIN_TABLE_MAP }, Value::Undefined(bytes)); - } -} - -fn write_opcode_tags(ifd: &mut IfdBuilder, raw: &RawImage) { - for (list, tag) in [(&raw.opcodes.list1, t::OPCODE_LIST_1), (&raw.opcodes.list2, t::OPCODE_LIST_2), (&raw.opcodes.list3, t::OPCODE_LIST_3)] { - if !list.is_empty() { - ifd.set(tag, Value::Undefined(opcodes::write_list(list))); - } + let options = craft_raw::DngWriteOptions { + compression, + order: raw_byte_order(opts.order), + software: SOFTWARE.into(), + xmp: Some(opts.xmp.clone().unwrap_or_else(|| lightcraft_meta::write_xmp(&raw.metadata, None))), + }; + if let DngCompression::LossyJpeg { tile, quality, .. } = opts.compression { + let encode = |pixels: Vec, tile: u32, quality: u8| { + let image = craft_image_codecs::Image::from_u8(tile, tile, craft_image_codecs::ChannelLayout::Rgb, pixels) + .map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?; + let options = craft_image_codecs::EncodeOptions { jpeg_quality: quality, ..Default::default() }; + craft_image_codecs::encode(&image, craft_image_codecs::Format::Jpeg, &options) + .map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}"))) + }; + craft_raw::dngwrite::write_lossy_dng(&view, &options, tile, quality, &lossy_linearization(), &encode) + } else { + craft_raw::dngwrite::write_dng_view(&view, &options) } } @@ -566,11 +239,107 @@ pub fn write_rendered_dng( write_dng(&raw, &DngWriteOptions { compression: DngCompression::Deflate { tile: 256, half: true }, order, xmp }) } +fn raw_byte_order(order: ByteOrder) -> craft_raw_tiff::ByteOrder { + match order { + ByteOrder::Little => craft_raw_tiff::ByteOrder::Little, + ByteOrder::Big => craft_raw_tiff::ByteOrder::Big, + } +} + +#[cfg(test)] +#[path = "dngwrite_legacy_tests.rs"] +mod legacy; + #[cfg(test)] mod tests { use super::*; use crate::{BlackLevel, OpcodeLists, RawData, RawFormat, RawImage, Rect}; + use crate::{Cfa, ColorData, Mat3, Orientation}; + + fn mosaic(w: usize, h: usize) -> RawImage { + let data: Vec = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let c = (x % 2) + (y % 2); + (64.0 + 3000.0 * (x as f32 / w as f32) * (0.5 + c as f32 * 0.25) + 500.0 * (y as f32 / h as f32)) as u16 + }) + .collect(); + let color = ColorData { + illuminant: [21, 0], + color_matrix: [Some(Mat3([[0.7, -0.1, -0.05], [-0.4, 1.2, 0.2], [-0.1, 0.2, 0.6]])), None], + as_shot_neutral: Some([0.5, 1.0, 0.7]), + ..Default::default() + }; + RawImage { + format: RawFormat::Dng, + width: w, + height: h, + cpp: 1, + data: RawData::U16(data), + cfa: Some(Cfa::bayer("RGGB").unwrap()), + bits: 12, + black: BlackLevel::uniform(64.0), + white: vec![4095.0], + active_area: Rect::new(0, 0, w, h), + crop: Rect::new(2, 2, w - 4, h - 4), + orientation: Orientation::Rotate90, + color, + wb_multipliers: None, + linearized: false, + opcodes: OpcodeLists::default(), + metadata: Default::default(), + lens_metadata: Default::default(), + pixel_aspect: 1.0, + } + } + + #[test] + fn shared_writer_matches_frozen_application_bytes() { + let raw = mosaic(20, 16); + for order in [ByteOrder::Little, ByteOrder::Big] { + for (compression, old_compression) in [ + (DngCompression::Uncompressed, legacy::DngCompression::Uncompressed), + (DngCompression::Lj92 { tile: 16 }, legacy::DngCompression::Lj92 { tile: 16 }), + (DngCompression::Deflate { tile: 16, half: false }, legacy::DngCompression::Deflate { tile: 16, half: false }), + ( + DngCompression::LossyJpeg { tile: 32, quality: 95, long_edge: None }, + legacy::DngCompression::LossyJpeg { tile: 32, quality: 95, long_edge: None }, + ), + ( + DngCompression::LossyJpeg { tile: 32, quality: 95, long_edge: Some(8) }, + legacy::DngCompression::LossyJpeg { tile: 32, quality: 95, long_edge: Some(8) }, + ), + ] { + let options = DngWriteOptions { compression, order, xmp: None }; + let old_options = legacy::DngWriteOptions { compression: old_compression, order: raw_byte_order(order), xmp: None }; + assert_eq!(write_dng(&raw, &options).unwrap(), legacy::write_dng(&raw, &old_options).unwrap()); + } + } + let rgb = (0..4 * 4 * 3).map(|i| i as f32 / 48.0).collect::>(); + let metadata = lightcraft_meta::Metadata::default(); + for space in [lightcraft_color::SRGB, lightcraft_color::PROPHOTO] { + assert_eq!( + write_rendered_dng(4, 4, &rgb, &space, &metadata, None).unwrap(), + legacy::write_rendered_dng(4, 4, &rgb, &space, &metadata, None).unwrap() + ); + } + } + + #[test] + fn shared_writer_keeps_padding_and_declared_white_guards() { + let mut raw = mosaic(20, 16); + raw.white = vec![65535.0]; + let options = DngWriteOptions { compression: DngCompression::Lj92 { tile: 16 }, ..Default::default() }; + let bytes = write_dng(&raw, &options).unwrap(); + let tiff = craft_tiff::Tiff::parse(&bytes).unwrap(); + assert_eq!(tiff.all_ifds()[0].u16(craft_tiff::tags::BITS_PER_SAMPLE), Some(16)); + for tile in [2050, u32::MAX] { + let options = DngWriteOptions { compression: DngCompression::Lj92 { tile }, ..Default::default() }; + assert!(matches!(write_dng(&raw, &options), Err(RawError::Limit("tile too large")))); + } + } + /// Deflate tiles of `tile × tile` pad into a square buffer that grows with the square: a /// caller-supplied edge of `u32::MAX` would make the writer pad an 8 × 8 image into billions of /// edge-replicate iterations and a multi-gigabyte buffer. The clamp keeps the bounded shape — same diff --git a/crates/raw/src/dngwrite_legacy_tests.rs b/crates/raw/src/dngwrite_legacy_tests.rs new file mode 100644 index 0000000000..c11adf7626 --- /dev/null +++ b/crates/raw/src/dngwrite_legacy_tests.rs @@ -0,0 +1,573 @@ +// Frozen application writer, test-only parity oracle. +// Source: storytold/lightcraft main 2dcb258ba40738230a07484a95eb27dc84ed66fe. +// Original DNG writer: Brandon Thomas (05450c79); lossy/rendered paths: +// Andrew Frahn (cc3eb1c8, a1d7c488), with subsequent fixes preserved verbatim. +//! Writing DNG files from a [`RawImage`] (uncompressed or lossless-JPEG tiles), used for DNG export and for +//! bit-exact decoder round-trip tests. The raw image is stored in IFD0 (allowed by DNG 1.7 §"File Structure"). + +use crate::{RawData, RawError, RawImage, Result, ljpeg, opcodes}; +// Keep shared RAW field types aligned; this TIFF source is unchanged across the pin. +use craft_raw_tiff as craft_tiff; +use craft_tiff::tags::{self as t, compression, photometric}; +use craft_tiff::writer::{rational, srational}; +use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value}; +use lightcraft_color::Mat3; +use rayon::prelude::*; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DngCompression { + Uncompressed, + /// Lossless JPEG tiles of `tile × tile` pixels (`tile` even). CFA tiles are encoded as two interleaved + /// components of half the tile width (the common DNG layout), linear data with one component per sample. + Lj92 { + tile: u32, + }, + /// Deflate (zlib) tiles of `tile × tile` pixels. Floating-point data is stored as 16-bit (`half`) or + /// 32-bit IEEE floats with the floating-point predictor (TIFF predictor 3, Adobe TIFF Technical Note 3); + /// integer data with horizontal differencing (predictor 2). 16-bit float is what HDR merges usually use. + Deflate { + tile: u32, + half: bool, + }, + /// Lossy DNG (DNG 1.4 compression 34892): the raw data demosaiced to linear camera RGB (with `OpcodeList3` + /// and the default crop applied), scaled down to at most `long_edge` pixels on the long side when given, + /// then stored as 8-bit baseline JPEG tiles of `tile × tile` pixels at JPEG `quality` (1–100). The 8-bit + /// codes follow a 1/2.2 power curve that a `LinearizationTable` maps back to linear 16-bit values, so + /// shadows keep their precision. The colour tags (matrices, white balance, profile look) are kept. + LossyJpeg { + tile: u32, + quality: u8, + long_edge: Option, + }, +} + +/// Gamma of the 8-bit codes in a lossy DNG (own choice: perceptually close to even steps, like sRGB). +const LOSSY_GAMMA: f64 = 2.2; + +/// The 256-entry `LinearizationTable` of a lossy DNG: code → linear 16-bit value. +fn lossy_linearization() -> Vec { + (0..256u32).map(|i| ((i as f64 / 255.0).powf(LOSSY_GAMMA) * 65535.0).round() as u16).collect() +} + +/// The image a lossy DNG stores: `raw` developed to linear camera RGB (white = 1), scaled to fit +/// `long_edge`, as 8-bit codes (in `u16` samples) on the [`LOSSY_GAMMA`] curve, with the levels, +/// geometry and opcode lists that this data needs (black 0, white 65535 after linearization). +fn lossy_source(raw: &RawImage, long_edge: Option) -> Result { + let mut rgb = raw.develop(crate::Method::Ahd)?; + if let Some(edge) = long_edge.map(|e| e.max(1) as usize) { + let long = rgb.width.max(rgb.height); + if long > edge { + let s = edge as f64 / long as f64; + let w = ((rgb.width as f64 * s).round() as usize).max(1); + let h = ((rgb.height as f64 * s).round() as usize).max(1); + rgb = lightcraft_raster::resample::resize(&rgb, w, h, lightcraft_raster::resample::Filter::Lanczos3); + } + } + let (w, h) = (rgb.width, rgb.height); + if w == 0 || h == 0 { + return Err(RawError::Corrupt("empty image".into())); + } + let inv = 1.0 / LOSSY_GAMMA as f32; + let data: Vec = rgb + .data + .par_iter() + .flat_map_iter(|px| px.map(|v| if v.is_finite() { (v.clamp(0.0, 1.0).powf(inv) * 255.0).round() as u16 } else { 0 })) + .collect(); + let full = crate::Rect::new(0, 0, w, h); + Ok(RawImage { + width: w, + height: h, + cpp: 3, + data: RawData::U16(data), + cfa: None, + bits: 8, + black: crate::BlackLevel::default(), + white: vec![65535.0], + active_area: full, + crop: full, + // list 1 and 2 work on the undemosaiced data and list 3 is applied by `develop` + opcodes: crate::OpcodeLists::default(), + linearized: true, + ..raw.clone() + }) +} + +/// Software tag of the DNGs this writer makes. A bare "LightCraft" marks older files, whose CFAPattern is anchored at +/// the sensor origin instead of the ActiveArea (the reader keeps their original reading). +pub const SOFTWARE: &str = "LightCraft DNG 2"; + +/// zlib level of Deflate tiles. On a 67 MP focus-stack merge (half floats) level 6 took 7× as long as level 1 +/// (3.9 s vs 0.55 s on 4 cores) to save 3 % of the file (266 vs 275 MB); 5–12 % on raw and rendered DNGs. +const DEFLATE_LEVEL: u8 = 1; + +/// Largest Deflate tile edge the writer pads to (`tile` is caller-supplied in [`DngCompression::Deflate`]): +/// square-tile buffers grow with the square, so an unclamped edge lets a request pad a tiny valid image into +/// a multi-gigabyte buffer and billions of edge-replicate iterations. 2048² samples (≤ 24 MB of f32) is far +/// above the 256 default and every real tile this writer makes. +const MAX_DEFLATE_TILE: u32 = 2048; + +/// `tile` aligned down to a multiple of 16 and clamped to [`MAX_DEFLATE_TILE`]. +fn deflate_tile(tile: u32) -> usize { + (tile.max(16) & !15).min(MAX_DEFLATE_TILE) as usize +} + +/// IEEE 754 binary32 → binary16 (round to nearest even; overflow → ±inf, NaN kept). +pub fn f32_to_f16(v: f32) -> u16 { + let b = v.to_bits(); + let sign = ((b >> 16) & 0x8000) as u16; + let exp = ((b >> 23) & 0xff) as i32; + let man = b & 0x7f_ffff; + if exp == 0xff { + return sign | 0x7c00 | if man != 0 { 0x200 } else { 0 }; + } + let e = exp - 127 + 15; + if e >= 0x1f { + return sign | 0x7c00; + } + if e <= 0 { + if e < -10 { + return sign; + } + // subnormal half + let m = man | 0x80_0000; + let shift = (14 - e) as u32; + let half = m >> shift; + let rem = m & ((1 << shift) - 1); + let mid = 1 << (shift - 1); + let r = if rem > mid || (rem == mid && half & 1 == 1) { half + 1 } else { half }; + return sign | r as u16; + } + let half = ((e as u32) << 10) | (man >> 13); + let rem = man & 0x1fff; + let r = if rem > 0x1000 || (rem == 0x1000 && half & 1 == 1) { half + 1 } else { half }; + sign | r as u16 +} + +/// Apply the floating-point predictor (inverse of `unpack::undo_float_predictor`) to one row of +/// `n` big-endian samples of `bytes_per` bytes: split into byte planes (most significant first), then +/// byte-difference with `stride` samples. +fn float_predict(row: &[u8], n: usize, bytes_per: usize, stride: usize) -> Vec { + let mut planes = vec![0u8; row.len()]; + for i in 0..n { + for b in 0..bytes_per { + planes[b * n + i] = row[i * bytes_per + b]; + } + } + for i in (stride..planes.len()).rev() { + planes[i] = planes[i].wrapping_sub(planes[i - stride]); + } + planes +} + +#[derive(Clone, Debug, PartialEq)] +pub struct DngWriteOptions { + pub compression: DngCompression, + pub order: ByteOrder, + /// XMP packet to embed (tag 700); defaults to one generated from the image metadata. + pub xmp: Option, +} + +impl Default for DngWriteOptions { + fn default() -> Self { + Self { compression: DngCompression::Lj92 { tile: 256 }, order: ByteOrder::Little, xmp: None } + } +} + +fn srat_mat(m: &Mat3) -> Value { + Value::SRational(m.0.iter().flatten().map(|&v| srational(v)).collect()) +} + +fn rat_vec(v: &[f64]) -> Value { + Value::Rational(v.iter().map(|&x| rational(x)).collect()) +} + +/// Serialise `raw` as a DNG. +pub fn write_dng(raw: &RawImage, opts: &DngWriteOptions) -> Result> { + raw.validate()?; + let lossy; + let raw = match opts.compression { + DngCompression::LossyJpeg { long_edge, .. } => { + lossy = lossy_source(raw, long_edge)?; + &lossy + } + _ => raw, + }; + let (w, h, cpp) = (raw.width, raw.height, raw.cpp); + let mut ifd = IfdBuilder::new(); + ifd.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + ifd.set(t::IMAGE_WIDTH, Value::Long(vec![w as u32])); + ifd.set(t::IMAGE_LENGTH, Value::Long(vec![h as u32])); + ifd.set(t::SAMPLES_PER_PIXEL, Value::Short(vec![cpp as u16])); + ifd.set(t::PLANAR_CONFIGURATION, Value::Short(vec![1])); + ifd.set(t::PHOTOMETRIC, Value::Short(vec![if raw.cfa.is_some() { photometric::CFA } else { photometric::LINEAR_RAW }])); + ifd.set(t::DNG_VERSION, Value::Byte(vec![1, 4, 0, 0])); + ifd.set(t::DNG_BACKWARD_VERSION, Value::Byte(vec![1, 3, 0, 0])); + let make = raw.metadata.make.as_deref().unwrap_or_default(); + let model = raw.metadata.model.as_deref().unwrap_or_default(); + if !make.is_empty() { + ifd.set(t::MAKE, Value::Ascii(make.to_owned())); + } + if !model.is_empty() { + ifd.set(t::MODEL, Value::Ascii(model.to_owned())); + } + let model_includes_make = !make.is_empty() + && model.get(..make.len()).is_some_and(|prefix| prefix.eq_ignore_ascii_case(make)) + && model.get(make.len()..).is_some_and(|suffix| suffix.chars().next().is_none_or(|c| !c.is_alphanumeric() && c != '_')); + let unique = if model_includes_make || make.is_empty() { + model.to_owned() + } else if model.is_empty() { + make.to_owned() + } else { + format!("{make} {model}") + }; + ifd.set(t::UNIQUE_CAMERA_MODEL, Value::Ascii(if unique.is_empty() { "LightCraft".into() } else { unique })); + ifd.set(t::ORIENTATION, Value::Short(vec![raw.orientation.to_exif()])); + ifd.set(t::SOFTWARE, Value::Ascii(SOFTWARE.into())); + let xmp = opts.xmp.clone().unwrap_or_else(|| lightcraft_meta::write_xmp(&raw.metadata, None)); + ifd.set(t::XMP, Value::Byte(xmp.into_bytes())); + + if let Some(cfa) = &raw.cfa { + ifd.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![cfa.height as u16, cfa.width as u16])); + // the tag is anchored at the ActiveArea's top-left, `raw.cfa` at the sensor origin + let a = raw.active_area; + ifd.set(t::CFA_PATTERN_EP, Value::Byte(cfa.shifted(a.x, a.y).pattern)); + ifd.set(t::CFA_PLANE_COLOR, Value::Byte(vec![0, 1, 2])); + ifd.set(t::CFA_LAYOUT, Value::Short(vec![1])); + } + let b = &raw.black; + ifd.set(t::BLACK_LEVEL_REPEAT_DIM, Value::Short(vec![b.repeat_rows as u16, b.repeat_cols as u16])); + let mut bl: Vec = b.values.iter().map(|&v| v as f64).collect(); + if bl.len() == 1 && cpp > 1 { + bl = vec![bl[0]; cpp]; + } + ifd.set(t::BLACK_LEVEL, rat_vec(&bl)); + if !b.delta_h.is_empty() { + ifd.set(t::BLACK_LEVEL_DELTA_H, Value::SRational(b.delta_h.iter().map(|&v| srational(v as f64)).collect())); + } + if !b.delta_v.is_empty() { + ifd.set(t::BLACK_LEVEL_DELTA_V, Value::SRational(b.delta_v.iter().map(|&v| srational(v as f64)).collect())); + } + let white: Vec = (0..cpp).map(|s| raw.white_at(s).round().clamp(0.0, u32::MAX as f32) as u32).collect(); + if matches!(raw.data, RawData::F32(_)) { + ifd.set(t::WHITE_LEVEL, rat_vec(&(0..cpp).map(|s| raw.white_at(s) as f64).collect::>())); + } else { + ifd.set(t::WHITE_LEVEL, Value::Long(white)); + } + let a = raw.active_area; + ifd.set(t::ACTIVE_AREA, Value::Long(vec![a.y as u32, a.x as u32, (a.y + a.height) as u32, (a.x + a.width) as u32])); + ifd.set(t::DEFAULT_CROP_ORIGIN, Value::Long(vec![raw.crop.x as u32, raw.crop.y as u32])); + ifd.set(t::DEFAULT_CROP_SIZE, Value::Long(vec![raw.crop.width as u32, raw.crop.height as u32])); + + let c = &raw.color; + for (i, tag) in [t::CALIBRATION_ILLUMINANT_1, t::CALIBRATION_ILLUMINANT_2].into_iter().enumerate() { + if c.color_matrix[i].is_some() { + ifd.set(tag, Value::Short(vec![c.illuminant[i]])); + } + } + for (pair, tags) in [ + (&c.color_matrix, [t::COLOR_MATRIX_1, t::COLOR_MATRIX_2]), + (&c.forward_matrix, [t::FORWARD_MATRIX_1, t::FORWARD_MATRIX_2]), + (&c.camera_calibration, [t::CAMERA_CALIBRATION_1, t::CAMERA_CALIBRATION_2]), + ] { + for i in 0..2 { + if let Some(m) = &pair[i] { + ifd.set(tags[i], srat_mat(m)); + } + } + } + if let Some(v) = c.analog_balance { + ifd.set(t::ANALOG_BALANCE, rat_vec(&v)); + } + if let Some(v) = c.as_shot_neutral { + ifd.set(t::AS_SHOT_NEUTRAL, rat_vec(&v)); + } else if let Some(xy) = c.as_shot_white_xy { + ifd.set(t::AS_SHOT_WHITE_XY, rat_vec(&[xy.x, xy.y])); + } else if let Some(m) = raw.wb_multipliers.filter(|m| m.iter().all(|v| *v > 0.0 && v.is_finite())) { + // vendor raws (NEF, ARW…) carry white balance as multipliers: the DNG neutral is their reciprocal + ifd.set(t::AS_SHOT_NEUTRAL, rat_vec(&m.map(|v| 1.0 / v as f64))); + } + ifd.set(t::BASELINE_EXPOSURE, Value::SRational(vec![srational(c.baseline_exposure)])); + if let Some(v) = c.baseline_sharpness { + ifd.set(t::BASELINE_SHARPNESS, rat_vec(&[v])); + } + write_profile_tags(&mut ifd, raw, opts.order); + write_opcode_tags(&mut ifd, raw); + + match (&raw.data, opts.compression) { + (RawData::F32(v), DngCompression::Deflate { tile, half }) => { + let tile = deflate_tile(tile); + let bp = if half { 2 } else { 4 }; + ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![(bp * 8) as u16; cpp])); + ifd.set(t::SAMPLE_FORMAT, Value::Short(vec![3; cpp])); + ifd.set(t::COMPRESSION, Value::Short(vec![compression::ADOBE_DEFLATE])); + ifd.set(t::PREDICTOR, Value::Short(vec![3])); + let (ta, td) = (w.div_ceil(tile), h.div_ceil(tile)); + let tiles: Vec> = (0..ta * td) + .into_par_iter() + .map(|i| { + let (tx, ty) = (i % ta * tile, i / ta * tile); + let mut buf = Vec::with_capacity(tile * tile * cpp * bp); + let mut row = Vec::with_capacity(tile * cpp * bp); + for y in 0..tile { + let sy = (ty + y).min(h - 1); + row.clear(); + for x in 0..tile { + let sx = (tx + x).min(w - 1); + for s in 0..cpp { + let f = v[(sy * w + sx) * cpp + s]; + if half { + row.extend_from_slice(&f32_to_f16(f).to_be_bytes()); + } else { + row.extend_from_slice(&f.to_bits().to_be_bytes()); + } + } + } + buf.extend_from_slice(&float_predict(&row, tile * cpp, bp, cpp)); + } + miniz_oxide::deflate::compress_to_vec_zlib(&buf, DEFLATE_LEVEL) + }) + .collect(); + ifd.set_image(ImageData::Tiles { tile_width: tile as u32, tile_height: tile as u32, tiles }); + } + (RawData::F32(v), _) => { + ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![32; cpp])); + ifd.set(t::SAMPLE_FORMAT, Value::Short(vec![3; cpp])); + ifd.set(t::COMPRESSION, Value::Short(vec![compression::NONE])); + let mut bytes = Vec::with_capacity(v.len() * 4); + for &x in v { + let mut tmp = Vec::with_capacity(4); + opts.order.put_u32(&mut tmp, x.to_bits()); + bytes.extend_from_slice(&tmp); + } + ifd.set_image(ImageData::Strips { rows_per_strip: h as u32, strips: vec![bytes] }); + } + (RawData::U16(v), DngCompression::LossyJpeg { tile, quality, .. }) => { + // `lossy_source` made 3-sample 8-bit codes + let tile = (tile.clamp(16, 4096) & !15) as usize; + ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![8; cpp])); + ifd.set(t::COMPRESSION, Value::Short(vec![compression::LOSSY_JPEG])); + ifd.set(t::LINEARIZATION_TABLE, Value::Short(lossy_linearization())); + let quality = quality.clamp(1, 100); + let (ta, td) = (w.div_ceil(tile), h.div_ceil(tile)); + let tiles: Vec> = (0..ta * td) + .into_par_iter() + .map(|i| { + let (tx, ty) = (i % ta * tile, i / ta * tile); + let mut buf = Vec::with_capacity(tile * tile * 3); + for y in 0..tile { + let sy = (ty + y).min(h - 1); + for x in 0..tile { + let sx = (tx + x).min(w - 1); + for s in 0..3 { + buf.push(v.get((sy * w + sx) * cpp + s.min(cpp - 1)).map_or(0, |&c| c.min(255) as u8)); + } + } + } + let ic_img = craft_image_codecs::Image::from_u8(tile as u32, tile as u32, craft_image_codecs::ChannelLayout::Rgb, buf) + .map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?; + let opts = craft_image_codecs::EncodeOptions { jpeg_quality: quality, ..Default::default() }; + craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Jpeg, &opts) + .map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}"))) + }) + .collect::>()?; + ifd.set_image(ImageData::Tiles { tile_width: tile as u32, tile_height: tile as u32, tiles }); + } + (RawData::U16(v), _) => { + let maxv = v.iter().copied().max().unwrap_or(0); + let bits = (16 - maxv.leading_zeros()).max(raw.bits.min(16)).max(2) as u8; + ifd.set( + t::BITS_PER_SAMPLE, + Value::Short(vec![if matches!(opts.compression, DngCompression::Uncompressed) { 16 } else { bits as u16 }; cpp]), + ); + match opts.compression { + DngCompression::Uncompressed => { + ifd.set(t::COMPRESSION, Value::Short(vec![compression::NONE])); + let rows = (65536 / (w * cpp * 2)).clamp(1, h); + let strips = v + .chunks(rows * w * cpp) + .map(|s| { + let mut b = Vec::with_capacity(s.len() * 2); + s.iter().for_each(|&x| opts.order.put_u16(&mut b, x)); + b + }) + .collect(); + ifd.set_image(ImageData::Strips { rows_per_strip: rows as u32, strips }); + } + DngCompression::Deflate { tile, .. } => { + let tile = deflate_tile(tile); + ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![16; cpp])); + ifd.set(t::COMPRESSION, Value::Short(vec![compression::ADOBE_DEFLATE])); + ifd.set(t::PREDICTOR, Value::Short(vec![2])); + let (ta, td) = (w.div_ceil(tile), h.div_ceil(tile)); + let tiles: Vec> = (0..ta * td) + .into_par_iter() + .map(|i| { + let (tx, ty) = (i % ta * tile, i / ta * tile); + let mut buf = Vec::with_capacity(tile * tile * cpp * 2); + let mut row = vec![0u16; tile * cpp]; + for y in 0..tile { + let sy = (ty + y).min(h - 1); + for x in 0..tile { + let sx = (tx + x).min(w - 1); + for s in 0..cpp { + row[x * cpp + s] = v[(sy * w + sx) * cpp + s]; + } + } + for i in (cpp..row.len()).rev() { + row[i] = row[i].wrapping_sub(row[i - cpp]); + } + row.iter().for_each(|&x| opts.order.put_u16(&mut buf, x)); + } + miniz_oxide::deflate::compress_to_vec_zlib(&buf, DEFLATE_LEVEL) + }) + .collect(); + ifd.set_image(ImageData::Tiles { tile_width: tile as u32, tile_height: tile as u32, tiles }); + } + // handled above (the data is converted first) + DngCompression::LossyJpeg { .. } => return Err(RawError::Unsupported("lossy DNG of this data".into())), + DngCompression::Lj92 { tile } => { + let tile = (tile.max(2) & !1) as usize; + if tile > 65534 { + return Err(RawError::Limit("tile too large")); + } + ifd.set(t::COMPRESSION, Value::Short(vec![compression::JPEG])); + let (ta, td) = (w.div_ceil(tile), h.div_ceil(tile)); + let tiles: Vec> = (0..ta * td) + .into_par_iter() + .map(|i| { + let (tx, ty) = (i % ta * tile, i / ta * tile); + let mut buf = Vec::with_capacity(tile * tile * cpp); + for y in 0..tile { + let sy = (ty + y).min(h - 1); + for x in 0..tile { + let sx = (tx + x).min(w - 1); + for s in 0..cpp { + buf.push(v[(sy * w + sx) * cpp + s]); + } + } + } + if cpp == 1 { + ljpeg::encode(&buf, tile / 2, tile, 2, bits, 1, 0) + } else { + ljpeg::encode(&buf, tile, tile, cpp, bits, 1, 0) + } + }) + .collect(); + ifd.set_image(ImageData::Tiles { tile_width: tile as u32, tile_height: tile as u32, tiles }); + } + } + } + } + Ok(TiffWriter::new(opts.order, false).write(&[ifd])?) +} + +fn write_profile_tags(ifd: &mut IfdBuilder, raw: &RawImage, order: ByteOrder) { + // The source's own profile look travels with its data (conversions, smart previews, merges). + let profile = &raw.color.profile; + let table_tags = |ifd: &mut IfdBuilder, table: &crate::profile::HsvTable, dims: u16, enc: u16| { + ifd.set(dims, Value::Long(vec![table.hue_divisions as u32, table.sat_divisions as u32, table.val_divisions as u32])); + if table.srgb_value { + ifd.set(enc, Value::Long(vec![1])); + } + }; + let flat = |table: &crate::profile::HsvTable| Value::Float(table.data.iter().flatten().copied().collect()); + match &profile.hue_sat_map { + [Some(first), second] => { + table_tags(ifd, first, t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_ENCODING); + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_1, flat(first)); + if let Some(second) = second.as_ref().filter(|second| { + (second.hue_divisions, second.sat_divisions, second.val_divisions) == (first.hue_divisions, first.sat_divisions, first.val_divisions) + }) { + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_2, flat(second)); + } + } + [None, Some(table)] => { + table_tags(ifd, table, t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_ENCODING); + ifd.set(t::PROFILE_HUE_SAT_MAP_DATA_1, flat(table)); + } + [None, None] => {} + } + if let Some(table) = &profile.look_table { + table_tags(ifd, table, t::PROFILE_LOOK_TABLE_DIMS, t::PROFILE_LOOK_TABLE_ENCODING); + ifd.set(t::PROFILE_LOOK_TABLE_DATA, flat(table)); + } + if let Some(curve) = &profile.tone_curve { + ifd.set(t::PROFILE_TONE_CURVE, Value::Float(curve.points.iter().flatten().copied().collect())); + } + if let Some(map) = &profile.gain_table_map { + // The raw IFD is IFD 0 here, where both tag versions are valid. + let (version2, bytes) = map.to_bytes(order); + ifd.set(if version2 { t::PROFILE_GAIN_TABLE_MAP_2 } else { t::PROFILE_GAIN_TABLE_MAP }, Value::Undefined(bytes)); + } +} + +fn write_opcode_tags(ifd: &mut IfdBuilder, raw: &RawImage) { + for (list, tag) in [(&raw.opcodes.list1, t::OPCODE_LIST_1), (&raw.opcodes.list2, t::OPCODE_LIST_2), (&raw.opcodes.list3, t::OPCODE_LIST_3)] { + if !list.is_empty() { + ifd.set(tag, Value::Undefined(opcodes::write_list(list))); + } + } +} + +/// Exif `LightSource` code of a white point the rendered DNG writer knows (D65 = 21, D50 = 23). +fn illuminant_of(white: lightcraft_color::Xy) -> u16 { + if (white.x - lightcraft_color::D50.x).abs() < 1e-3 && (white.y - lightcraft_color::D50.y).abs() < 1e-3 { 23 } else { 21 } +} + +/// Render to DNG: a linear DNG (`LinearRaw`, 16-bit float Deflate tiles) of an already rendered, +/// oriented image. `rgb` is `width × height` interleaved linear RGB in `space` (white = 1; values +/// above 1 are kept up to the half-float maximum, negative and non-finite ones become 0). The colour tags describe `space` +/// exactly — `ColorMatrix1` = XYZ → space, `ForwardMatrix1` = space → XYZ D50, a neutral +/// `AsShotNeutral` — and an identity `ProfileToneCurve` keeps raw converters from adding their +/// default tone curve on top of the baked-in edit. +pub fn write_rendered_dng( + width: usize, + height: usize, + rgb: &[f32], + space: &lightcraft_color::RgbSpace, + metadata: &lightcraft_meta::Metadata, + xmp: Option, +) -> Result> { + let n = width.checked_mul(height).and_then(|p| p.checked_mul(3)).ok_or(RawError::Limit("image too large"))?; + if width == 0 || height == 0 || width > u32::MAX as usize || height > u32::MAX as usize { + return Err(RawError::Corrupt(format!("cannot write a {width}×{height} DNG"))); + } + let src = rgb.get(..n).ok_or_else(|| RawError::Corrupt(format!("{} samples for a {width}×{height} RGB image", rgb.len())))?; + let data: Vec = src.iter().map(|&v| if v.is_finite() { v.clamp(0.0, 65504.0) } else { 0.0 }).collect(); + let full = crate::Rect::new(0, 0, width, height); + let forward = lightcraft_color::bradford(space.white, lightcraft_color::D50).mul(&space.to_xyz()); + let color = crate::ColorData { + illuminant: [illuminant_of(space.white), 0], + color_matrix: [Some(space.from_xyz()), None], + forward_matrix: [Some(forward), None], + as_shot_neutral: Some([1.0; 3]), + profile: crate::profile::ProfileLook { + tone_curve: Some(crate::profile::ToneCurve { points: vec![[0.0, 0.0], [1.0, 1.0]] }), + ..Default::default() + }, + ..Default::default() + }; + let raw = RawImage { + format: crate::RawFormat::Dng, + width, + height, + cpp: 3, + data: RawData::F32(data), + cfa: None, + bits: 16, + black: crate::BlackLevel::uniform(0.0), + white: vec![1.0], + active_area: full, + crop: full, + orientation: lightcraft_geom::Orientation::Normal, + color, + wb_multipliers: None, + linearized: false, + pixel_aspect: 1.0, + opcodes: crate::OpcodeLists::default(), + metadata: metadata.clone(), + lens_metadata: Default::default(), + }; + let order = ByteOrder::Little; + write_dng(&raw, &DngWriteOptions { compression: DngCompression::Deflate { tile: 256, half: true }, order, xmp }) +} diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index 1b4909c366..14e0349be4 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -1164,3 +1164,27 @@ fn legacy_lightcraft_dng_keeps_the_sensor_anchored_pattern() { assert_eq!(build("Adobe Photoshop Lightroom").cfa.unwrap().name(), "BGGR"); assert_ne!(lightcraft_raw::dngwrite::SOFTWARE, "LightCraft"); } + +/// The DJI compatibility fix in craft-raw #2042 must reach the application decoder, +/// without making a genuinely truncated raster acceptable. +#[test] +fn active_width_strip_count_keeps_the_full_sensor_raster() { + let mut raw = synthetic(16, 16, Some(Cfa::bayer("RGGB").unwrap()), 1); + raw.active_area = Rect::new(0, 0, 12, 16); + raw.crop = raw.active_area; + let mut bytes = write_dng(&raw, &DngWriteOptions { compression: DngCompression::Uncompressed, order: ByteOrder::Little, xmp: None }).unwrap(); + let ifd = u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize; + let count = u16::from_le_bytes(bytes[ifd..ifd + 2].try_into().unwrap()) as usize; + let entry = + (0..count).map(|i| ifd + 2 + i * 12).find(|&at| u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap()) == t::STRIP_BYTE_COUNTS).unwrap(); + assert_eq!(u16::from_le_bytes(bytes[entry + 2..entry + 4].try_into().unwrap()), 4); + assert_eq!(u32::from_le_bytes(bytes[entry + 4..entry + 8].try_into().unwrap()), 1); + bytes[entry + 8..entry + 12].copy_from_slice(&(12u32 * 16 * 2).to_le_bytes()); + let decoded = decode(&bytes).unwrap(); + assert_eq!((decoded.width, decoded.height), (16, 16)); + assert_eq!(decoded.data, raw.data); + assert_eq!(decoded.active_area, raw.active_area); + assert_eq!(lightcraft_raw::probe_info(&bytes).unwrap(), decoded.info()); + bytes.truncate(bytes.len() - 8); + assert!(decode(&bytes).is_err(), "a short raster must still be refused"); +} diff --git a/crates/segment/src/fetch.rs b/crates/segment/src/fetch.rs index 35f2d2eb54..be2a1070f5 100644 --- a/crates/segment/src/fetch.rs +++ b/crates/segment/src/fetch.rs @@ -17,8 +17,8 @@ use std::path::Path; // TODO(maintainer): pin `vocab.json` and `merges.txt` (size + SHA-256) when the files are // uploaded to LightCraft's CDN. pub const SAM3_FILES: &[FileSpec] = &[ - FileSpec { name: "vocab.json", size: None, sha256: None, max: 16 << 20 }, - FileSpec { name: "merges.txt", size: None, sha256: None, max: 16 << 20 }, + FileSpec { name: "vocab.json", size: None, sha256: None, max: 4 << 20 }, + FileSpec { name: "merges.txt", size: None, sha256: None, max: 4 << 20 }, FileSpec { name: crate::WEIGHTS_FILE, size: Some(SAM3_WEIGHTS_SIZE), @@ -31,10 +31,7 @@ pub const SAM3_FILES: &[FileSpec] = &[ pub const SAM3_WEIGHTS_SIZE: u64 = 3_439_938_512; /// Where LightCraft downloads the model from, in order: each is a base URL, and file `f` is at -/// `/`. **Empty for now**: LightCraft has no download location of its own yet, so the -/// in-app download needs the user's list (`LIGHTCRAFT_SAM3_MIRRORS` or the mirrors file, see -/// [`mirrors`] and docs/ai-masks.md) until this is filled in. -/// +/// `/`. /// Hugging Face's `facebook/sam3` can't be a default: it is gated (each user must accept the /// SAM License there and download with their own token). // TODO(maintainer): add LightCraft's CDN locations (https, primary first), e.g. @@ -76,4 +73,10 @@ mod tests { assert_eq!(m.len(), 1 + DEFAULT_MIRRORS.len()); assert!(no_mirrors_message().contains(MIRRORS_ENV)); } + + #[test] + fn without_a_configured_mirror_the_message_names_where_to_set_one() { + assert!(mirrors(None, None).is_empty(), "no download location is built in until the maintainer adds one"); + assert!(no_mirrors_message().contains(MIRRORS_ENV)); + } } diff --git a/crates/ui-egui/src/dialogs/updates_ui.rs b/crates/ui-egui/src/dialogs/updates_ui.rs index ee42c37681..731818f1e1 100644 --- a/crates/ui-egui/src/dialogs/updates_ui.rs +++ b/crates/ui-egui/src/dialogs/updates_ui.rs @@ -185,6 +185,32 @@ mod tests { } } + /// Offers `release` and returns once its prompt is open. The updater reads the installed + /// files for an offer on a thread of its own. That thread sends its answer and then asks the + /// first context the updater was ticked with for a repaint, so the tick after that repaint + /// reads the answer and opens the prompt. `updater` must not have been ticked before, or the + /// repaint goes to another context. The test fails when the launcher manages this copy or + /// when the answered offer opens no prompt. + #[cfg(not(target_arch = "wasm32"))] + fn offer_and_wait(updater: &mut Updater, release: craft_update::Release) { + let ctx = egui::Context::default(); + let (answered, wait) = std::sync::mpsc::channel(); + ctx.set_repaint_observer(move |info| { + if info.delay.is_zero() { + let _ = answered.send(()); + } + }); + // Keeps `ctx` for the offer's thread. + updater.tick(&ctx); + updater.offer(release); + assert!(updater.managed().is_none(), "the launcher manages this copy, so it ignored the offer"); + if !updater.prompt_open() { + wait.recv().unwrap(); + updater.tick(&ctx); + } + assert!(updater.prompt_open(), "the answered offer opened no prompt"); + } + #[test] #[cfg(not(target_arch = "wasm32"))] fn startup_prompt_shows_and_closes() { @@ -197,7 +223,10 @@ mod tests { html_url: "https://github.com/storytold/lightcraft/releases/tag/v99.0.0".into(), ..Default::default() }; - app.updates_rt.updater.offer(release); + // A missing pins file means stable releases, whatever the launcher on this machine chose. + let no_pins = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("no-launcher-pins.json"); + app.updates_rt.updater = Updater::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).with_pins_path(no_pins); + offer_and_wait(&mut app.updates_rt.updater, release); let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { show(&mut app, ui.ctx()); diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 97cd8ac691..67d972a750 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -123,7 +123,7 @@ fn home(workspace: &Workspace, panel: Panel) -> Location { size: None, stack: None, sibling: Vec::new(), - group: Some(GroupLocation { minimized: false, height: None, column: Some(column) }), + group: Some(GroupLocation { minimized: false, height: None, flyout_width: None, flyout_offset: None, column: Some(column) }), } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index c9e0e6aead..836190bd95 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -1,10 +1,10 @@ //! Presentation-only localization. Command ids, user names and catalog data remain unchanged. //! //! A language is one entry in [`language_table!`] below: its BCP-47 code, the endonym shown in the -//! Language menus, the ISO 15924 script its text needs (which picks the CJK font fallback), and its +//! Settings language row, the ISO 15924 script its text needs (which picks the CJK font fallback), and its //! message catalog (`locales/.json`, embedded at build time). Adding a language is that entry //! plus its catalogs and the corresponding language command in `menus.rs`. Settings read the -//! locale table, while menus and the control channel share the command mapping. +//! locale table, while the control channel uses the command mapping. use std::{cell::RefCell, collections::BTreeMap, sync::OnceLock}; @@ -34,7 +34,7 @@ macro_rules! language_table { match self { Self::$source => $source_code, $(Self::$variant => $code,)* } } - /// The language's own name, as shown in the Language menus. + /// The language's own name, as shown in the Settings language row. pub const fn name(self) -> &'static str { match self { Self::$source => "English", $(Self::$variant => $name,)* } } @@ -140,7 +140,7 @@ language_table! { } impl Locale { - /// Every language in the order the Settings row and Edit ▸ Language list them: English first + /// Every language in the order the Settings row lists them: English first /// (the source language), then the rest by their own name with accents folded, so Čeština /// sits under C. Names in other scripts follow the Latin ones in code point order: Cyrillic, /// Georgian, then the CJK languages. @@ -590,9 +590,9 @@ mod picker_order_tests { } #[test] - fn language_menu_lists_the_picker_order() { + fn language_commands_list_the_picker_order() { let menu: Vec<&str> = crate::menus::LANGUAGE_COMMANDS.iter().map(|c| c.1).collect(); let picker: Vec<&str> = Locale::for_picker().into_iter().map(Locale::name).collect(); - assert_eq!(menu, picker, "Edit ▸ Language and the Settings row list the languages the same way"); + assert_eq!(menu, picker, "the language commands and the Settings row list the languages the same way"); } } diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 47af31e2c6..8540f7b741 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -22,7 +22,6 @@ fn languages_switch_persist_and_keep_user_values() { app.run(&command, serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, locale); assert_eq!(language(), locale); - assert_eq!(crate::menubar::checked(&app, &command), Some(true)); assert_eq!(builtin_label("Warm Glow", false), "Warm Glow"); assert_eq!(builtin_label("Warm Glow", true), locale.tr("Warm Glow")); assert_eq!(tr("photo-{title}.jpg"), "photo-{title}.jpg"); @@ -369,7 +368,7 @@ fn translated_catalogs_do_not_use_missing_menu_triangles() { } } -/// The language menu covers every language, and a language's own command selects it. +/// Every language has a command, and a language's own command selects it. #[test] fn language_commands_cover_every_language() { let commands = [ @@ -392,11 +391,11 @@ fn language_commands_cover_every_language() { ("app.language.indonesian", Locale::Id), ("app.language.vietnamese", Locale::Vi), ]; - // One command per language, and every command reachable from the menu table. + // One command per language, and every command in the UI command tables. assert_eq!(commands.len(), Locale::ALL.len()); for (id, language) in commands { assert_eq!(crate::menus::language_from_command(id), Some(language), "{id}"); - assert!(crate::menus::ui_commands().any(|command| command.0 == id), "{id} is not in the menu"); + assert!(crate::menus::ui_commands().any(|command| command.0 == id), "{id} is not a UI command"); } assert_eq!(crate::menus::language_from_command("app.language.klingon"), None); assert_eq!(crate::menus::language_from_command("view.detail"), None); @@ -586,7 +585,6 @@ fn german_switches_via_menu_and_control_and_persists() { app.run("app.language.german", serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, Locale::De); assert_eq!(language(), Locale::De); - assert_eq!(crate::menubar::checked(&app, "app.language.german"), Some(true)); let saved = serde_json::to_string(&app.ui).unwrap(); assert!(saved.contains(r#""language":"de""#)); assert_eq!(serde_json::from_str::(&saved).unwrap().language, Locale::De); @@ -887,8 +885,6 @@ fn traditional_chinese_switches_through_menu_and_control_and_persists() { assert_eq!(source_label(lightcraft_engine::LibrarySource::All, &app.session.catalog), Locale::ZhHant.tr("All Photos")); assert_eq!(date_group_label("", false), Locale::ZhHant.tr("Unknown Date")); assert_eq!(display_time("a-user-value"), "a-user-value"); - assert_eq!(crate::menubar::checked(&app, "app.language.traditionalChinese"), Some(true)); - assert_eq!(crate::menubar::checked(&app, "app.language.english"), Some(false)); assert_eq!(tr("my-photo.jpg"), "my-photo.jpg"); for id in ["album.addPhotos", "metadata.applyPreset", "label.applySet"] { assert_eq!(crate::menubar::display_item_label(id, &serde_json::json!({"id": 1}), "Color"), "Color"); @@ -1275,7 +1271,6 @@ fn polish_switches_formats_dates_and_reads_every_count() { app.run("app.language.polish", serde_json::json!({})).unwrap(); assert_eq!(app.ui.language, Locale::Pl); assert_eq!(Locale::Pl.name(), "Polski"); - assert_eq!(crate::menubar::checked(&app, "app.language.polish"), Some(true)); assert_eq!(tr("File"), "Plik"); assert_eq!(tr("Exposure"), "Ekspozycja"); assert_eq!(date_group_label("2026-09-20", false), "Niedziela, 20.09.2026"); diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index b73729a913..e298e104c6 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -392,8 +392,6 @@ pub fn checked(app: &LightcraftApp, id: &str) -> Option { let u = &app.ui; let panel = |p: RightPanel| Some(u.right == p); match id { - // Every language's command is checked when it is the active one. - _ if crate::menus::language_from_command(id).is_some() => Some(crate::menus::language_from_command(id) == Some(u.language)), "develop.autoSync" => Some(app.session.auto_sync), "view.photoCounts" => Some(u.show_counts), "view.secondWindow" => Some(u.second_window), diff --git a/crates/ui-egui/src/menus/menubar/tests.rs b/crates/ui-egui/src/menus/menubar/tests.rs index cc3c5c4b0f..88019f15bf 100644 --- a/crates/ui-egui/src/menus/menubar/tests.rs +++ b/crates/ui-egui/src/menus/menubar/tests.rs @@ -852,3 +852,20 @@ fn edit_menu_places_the_select_and_paste_rows_with_their_kin() { let after = &nodes[pos("app.settings") + 1..]; assert!(!after.iter().any(|n| matches!(n, MenuNode::Item { .. })), "no row follows Settings… but a submenu: {after:?}"); } + +/// The interface language is chosen in Settings ▸ General (one choice per language), so Edit has no +/// Language submenu of 18 rows. The commands stay: agents and tests still switch language by id. +#[test] +fn edit_menu_has_no_language_submenu_because_settings_has_the_choice() { + let mut a = app(); + let bar = menu_bar(&a); + let edit = bar.iter().find(|(t, _)| t == "Edit").expect("Edit menu").1.as_slice(); + assert!(!edit.iter().any(|n| matches!(n, MenuNode::Submenu { label, .. } if label == "Language")), "Edit still has a Language submenu"); + for (title, nodes) in &bar { + for command in crate::menus::LANGUAGE_COMMANDS { + assert!(find(nodes, command.0).is_none(), "{} is in {title}", command.0); + } + } + run_item(&mut a, "app.language.german", Value::Null).expect("the command still switches language"); + assert_eq!(a.ui.language, crate::i18n::Locale::De); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index fb83b3a746..d22ff8bb43 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1,28 +1,29 @@ use super::UiCommand; -/// The "Edit → Language" entries, one per language in [`crate::i18n::Locale::ALL`], so a language -/// has a matching menu command (also listed through the control channel). Tests check coverage. +/// One command per language in [`crate::i18n::Locale::ALL`], so a language has a matching command +/// (also listed through the control channel). They are in no menu: Settings ▸ General has the +/// language choice. Tests check coverage. pub const LANGUAGE_COMMANDS: &[UiCommand] = &[ - ("app.language.english", crate::i18n::Locale::En.name(), None, "Edit>Language"), + ("app.language.english", crate::i18n::Locale::En.name(), None, ""), // The picker order (`Locale::for_picker`): alphabetical by the language's own name after // English; Cyrillic, Georgian, then CJK names follow the Latin ones. A test keeps them equal. - ("app.language.indonesian", crate::i18n::Locale::Id.name(), None, "Edit>Language"), - ("app.language.czech", crate::i18n::Locale::Cs.name(), None, "Edit>Language"), - ("app.language.german", crate::i18n::Locale::De.name(), None, "Edit>Language"), - ("app.language.spanish", crate::i18n::Locale::Es.name(), None, "Edit>Language"), - ("app.language.french", crate::i18n::Locale::Fr.name(), None, "Edit>Language"), - ("app.language.italian", crate::i18n::Locale::It.name(), None, "Edit>Language"), - ("app.language.polish", crate::i18n::Locale::Pl.name(), None, "Edit>Language"), - ("app.language.portuguese", crate::i18n::Locale::PtBr.name(), None, "Edit>Language"), - ("app.language.finnish", crate::i18n::Locale::Fi.name(), None, "Edit>Language"), - ("app.language.swedish", crate::i18n::Locale::Sv.name(), None, "Edit>Language"), - ("app.language.vietnamese", crate::i18n::Locale::Vi.name(), None, "Edit>Language"), - ("app.language.russian", crate::i18n::Locale::Ru.name(), None, "Edit>Language"), - ("app.language.ukrainian", crate::i18n::Locale::Uk.name(), None, "Edit>Language"), - ("app.language.georgian", crate::i18n::Locale::Ka.name(), None, "Edit>Language"), - ("app.language.japanese", crate::i18n::Locale::Ja.name(), None, "Edit>Language"), - ("app.language.simplifiedChinese", crate::i18n::Locale::ZhHans.name(), None, "Edit>Language"), - ("app.language.traditionalChinese", crate::i18n::Locale::ZhHant.name(), None, "Edit>Language"), + ("app.language.indonesian", crate::i18n::Locale::Id.name(), None, ""), + ("app.language.czech", crate::i18n::Locale::Cs.name(), None, ""), + ("app.language.german", crate::i18n::Locale::De.name(), None, ""), + ("app.language.spanish", crate::i18n::Locale::Es.name(), None, ""), + ("app.language.french", crate::i18n::Locale::Fr.name(), None, ""), + ("app.language.italian", crate::i18n::Locale::It.name(), None, ""), + ("app.language.polish", crate::i18n::Locale::Pl.name(), None, ""), + ("app.language.portuguese", crate::i18n::Locale::PtBr.name(), None, ""), + ("app.language.finnish", crate::i18n::Locale::Fi.name(), None, ""), + ("app.language.swedish", crate::i18n::Locale::Sv.name(), None, ""), + ("app.language.vietnamese", crate::i18n::Locale::Vi.name(), None, ""), + ("app.language.russian", crate::i18n::Locale::Ru.name(), None, ""), + ("app.language.ukrainian", crate::i18n::Locale::Uk.name(), None, ""), + ("app.language.georgian", crate::i18n::Locale::Ka.name(), None, ""), + ("app.language.japanese", crate::i18n::Locale::Ja.name(), None, ""), + ("app.language.simplifiedChinese", crate::i18n::Locale::ZhHans.name(), None, ""), + ("app.language.traditionalChinese", crate::i18n::Locale::ZhHant.name(), None, ""), ]; /// Every UI command: the languages, then everything else. `xtask parity` reads both tables from @@ -31,8 +32,8 @@ pub fn ui_commands() -> impl Iterator { LANGUAGE_COMMANDS.iter().chain(UI_COMMANDS) } -/// The language a Language-menu command selects, if the id is one. The engine and the UI both go -/// through here, so the menu, the settings row and the control channel agree on the mapping. +/// The language a language command selects, if the id is one. The engine and the UI both go +/// through here, so the settings row and the control channel agree on the mapping. pub fn language_from_command(id: &str) -> Option { match id { "app.language.english" => Some(crate::i18n::Locale::En), diff --git a/crates/ui-egui/src/tests/dialog_settings.rs b/crates/ui-egui/src/tests/dialog_settings.rs index 950cae6e66..4398f8c053 100644 --- a/crates/ui-egui/src/tests/dialog_settings.rs +++ b/crates/ui-egui/src/tests/dialog_settings.rs @@ -390,3 +390,21 @@ fn each_tab_remembers_how_far_it_was_scrolled() { show(&mut h, "import"); assert!((rect(&h, "check:settings.perCamera").top() - scrolled).abs() < 0.5, "Import is where it was left after a reopen"); } + +/// Settings ▸ General ▸ Language is where the interface language is chosen (Edit has no Language +/// menu): each choice switches the app at once. +#[test] +fn each_language_choice_in_general_switches_the_interface() { + let mut h = demo([1600.0, 1000.0]); + show(&mut h, "general"); + let picker = crate::i18n::Locale::for_picker(); + for (i, language) in picker.iter().enumerate() { + let r = h.request("ui.clickWidget", json!({"id": format!("button:settingsLanguage-{i}")}), T); + assert_eq!(r["ok"], true, "{language:?}: {r}"); + h.step(); + h.step(); + assert_eq!(h.app.ui.language, *language, "choice {i}"); + assert_eq!(crate::i18n::language(), *language, "choice {i} is applied at once"); + } + crate::i18n::set_language(crate::i18n::Locale::En); +} diff --git a/crates/ui-egui/src/tests/find_similar.rs b/crates/ui-egui/src/tests/find_similar.rs index 71617007a4..ef70539578 100644 --- a/crates/ui-egui/src/tests/find_similar.rs +++ b/crates/ui-egui/src/tests/find_similar.rs @@ -226,6 +226,18 @@ fn a_photo_that_cannot_be_read_says_so() { let toast = h.app.ui.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); assert!(toast.contains("can't read the photo"), "{toast}"); assert_eq!(h.app.session.filter, Default::default()); + + // Headless frames can start process-wide GPU warm-up. Keep the original assertions and + // GPU enabled, but do not let this one-test process exit while driver work is in flight. + #[cfg(not(target_arch = "wasm32"))] + { + let deadline = Instant::now() + Duration::from_secs(30); + while !lightcraft_engine::gpu::ready() && lightcraft_engine::gpu::enabled() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(lightcraft_engine::gpu::ready() || !lightcraft_engine::gpu::enabled(), "GPU warm-up did not finish"); + assert!(lightcraft_engine::gpu::wait_idle(Duration::from_secs(30)), "GPU work did not finish"); + } } /// A control request is answered when the search ends, with the command's `{photos}`, and the window diff --git a/docs/localization-cs.md b/docs/localization-cs.md index c3ed1ddcf4..c04e8cfe4c 100644 --- a/docs/localization-cs.md +++ b/docs/localization-cs.md @@ -1,7 +1,6 @@ # Čeština -Češtinu (`cs`, English name **Czech**, native name **Čeština**) zapnete přes **Úpravy → Jazyk → -Čeština** nebo **Nastavení → Obecné → Jazyk**. Změna platí ihned a ukládá se pro další spuštění. +Češtinu (`cs`, English name **Czech**, native name **Čeština**) zapnete přes **Nastavení → Obecné → Jazyk → Čeština**. Změna platí ihned a ukládá se pro další spuštění. Příkaz je `app.language.czech`; řídicí kanál přijímá `ui.set {"language":"cs"}` i značky `cs-CZ` a `cs_CZ.UTF-8`. Pro běh bez okna lze nastavit `LIGHTCRAFT_LANGUAGE=cs`. diff --git a/docs/localization-de.md b/docs/localization-de.md index b31e9eff53..2366b83f54 100644 --- a/docs/localization-de.md +++ b/docs/localization-de.md @@ -1,6 +1,6 @@ # LightCraft auf Deutsch -Wähle **Bearbeiten → Sprache → Deutsch** oder **Einstellungen → Allgemein → Sprache**. +Wähle **Einstellungen → Allgemein → Sprache → Deutsch**. Die Auswahl gilt sofort und wird für den nächsten Start gespeichert (`language: "de"` in `ui.json`). Die deutschen Kataloge decken alle Schlüssel der bisherigen Übersetzungen sowie sämtliche diff --git a/docs/localization-es.md b/docs/localization-es.md index d8aeaa7838..91c1fad8bd 100644 --- a/docs/localization-es.md +++ b/docs/localization-es.md @@ -1,6 +1,6 @@ # LightCraft en español -Elegir **Editar → Idioma → Español** o **Ajustes → General → Idioma**. El cambio se aplica al +Elegir **Ajustes → General → Idioma → Español**. El cambio se aplica al momento y se conserva para el próximo inicio (`language: "es"` en `ui.json`). `LIGHTCRAFT_LANGUAGE` acepta cualquier variante del español (`es`, `es-ES`, `es_MX.UTF-8`, `es-419`…). diff --git a/docs/localization-fi.md b/docs/localization-fi.md index fcb89d7844..76483a99da 100644 --- a/docs/localization-fi.md +++ b/docs/localization-fi.md @@ -1,7 +1,7 @@ # Suomi Suomen (`fi`, englanniksi **Finnish**, omakielinen nimi **Suomi**) saa käyttöön valitsemalla -**Muokkaa → Kieli → Suomi** tai **Asetukset → Yleiset → Kieli**. Muutos tulee voimaan heti ja +**Asetukset → Yleiset → Kieli → Suomi**. Muutos tulee voimaan heti ja tallentuu seuraavaa käynnistystä varten. Komento on `app.language.finnish`; ohjauskanava hyväksyy `ui.set {"language":"fi"}` sekä tunnisteet `fi-FI` ja `fi_FI.UTF-8`. Ikkunattomassa ajossa voi käyttää `LIGHTCRAFT_LANGUAGE=fi`. diff --git a/docs/localization-id.md b/docs/localization-id.md index 13fc1c7ee8..328f30fe1a 100644 --- a/docs/localization-id.md +++ b/docs/localization-id.md @@ -1,6 +1,6 @@ # LightCraft in Indonesian -Choose **Edit → Language → Bahasa Indonesia** or **Settings → General → Language**. The choice applies +Choose **Settings → General → Language → Bahasa Indonesia**. The choice applies at once and is saved for the next launch (`language: "id"` in `ui.json`); the control command is `app.language.indonesian`. `LIGHTCRAFT_LANGUAGE` selects it for headless runs and accepts `id`, `id-ID` and `id_ID.UTF-8`; the saved value is always `id`. LightCraft does not follow the system language, for diff --git a/docs/localization-ja.md b/docs/localization-ja.md index 8d40688427..a9f758d6e1 100644 --- a/docs/localization-ja.md +++ b/docs/localization-ja.md @@ -3,7 +3,7 @@ LightCraft は日本語・簡体字中国語・英語(English)の表示に対応しています。 言語設定は `ui.json` の `language` に保存します。 -- 「編集 → 言語」または「設定 → 一般 → 言語」で切り替えます。選択は次回起動にも引き継ぎます。 +- 「設定 → 一般 → 言語」で切り替えます。選択は次回起動にも引き継ぎます。 - メニュー、写真編集、マスク、切り抜き、設定、読み込み、書き出し、主な処理状況を翻訳しています。 - 通常表示と太字の双方に、SIL OFLのBIZ UDPGothicを使います。日本語フォントはこのリポジトリではなく [storytold/craft-fonts](https://github.com/storytold/craft-fonts) にあり、任意のビルド入力 diff --git a/docs/localization-ka.md b/docs/localization-ka.md index 16d878794a..07f231dde9 100644 --- a/docs/localization-ka.md +++ b/docs/localization-ka.md @@ -1,6 +1,6 @@ # LightCraft in Georgian -Choose **Edit → Language → ქართული** or **Settings → General → Language**. The choice applies at once +Choose **Settings → General → Language → ქართული**. The choice applies at once and is saved for the next launch (`language: "ka"` in `ui.json`); the control command is `app.language.georgian`. `LIGHTCRAFT_LANGUAGE` selects it for headless runs and accepts `ka`, `ka-GE` and `ka_GE.UTF-8`; the saved value is always `ka`. LightCraft does not follow the system language, diff --git a/docs/localization-pl.md b/docs/localization-pl.md index 445dbcf639..81a48c9781 100644 --- a/docs/localization-pl.md +++ b/docs/localization-pl.md @@ -1,7 +1,7 @@ # Polski -Język polski (`pl`, English name **Polish**, nazwa natywna **Polski**) włącza się przez **Edytuj → Język → -Polski** albo **Ustawienia → Ogólne → Język**. Zmiana działa od razu i jest zapamiętywana przy kolejnym +Język polski (`pl`, English name **Polish**, nazwa natywna **Polski**) włącza się przez **Ustawienia → Ogólne → Język → +Polski**. Zmiana działa od razu i jest zapamiętywana przy kolejnym uruchomieniu. Polecenie to `app.language.polish`; kanał sterowania przyjmuje `ui.set {"language":"pl"}` oraz znaczniki `pl-PL` i `pl_PL.UTF-8`. Bez okna można ustawić `LIGHTCRAFT_LANGUAGE=pl`. diff --git a/docs/localization-pt-br.md b/docs/localization-pt-br.md index 72d5fcfea0..6baee8d3d0 100644 --- a/docs/localization-pt-br.md +++ b/docs/localization-pt-br.md @@ -3,7 +3,7 @@ O LightCraft pode ser exibido em inglês, chinês simplificado, chinês tradicional (Taiwan), japonês e português do Brasil. A preferência de idioma é gravada em `language` no `ui.json`. -- Troque em **Editar → Idioma** ou em **Configurações → Geral → Idioma**. A escolha é mantida nas +- Troque em **Configurações → Geral → Idioma**. A escolha é mantida nas próximas inicializações. - Traduzimos menus, edição de fotos, máscaras, recorte, configurações, importação, exportação e as principais mensagens de progresso. diff --git a/docs/localization-ru.md b/docs/localization-ru.md index 5ffbeffef5..440bd06233 100644 --- a/docs/localization-ru.md +++ b/docs/localization-ru.md @@ -1,6 +1,6 @@ # LightCraft на русском -Выберите **Правка → Язык → Русский** или **Настройки → Общие → Язык**. Выбор применяется сразу +Выберите **Настройки → Общие → Язык → Русский**. Выбор применяется сразу и сохраняется для следующего запуска (`language: "ru"` в `ui.json`). Русский каталог охватывает меню, сочетания клавиш, библиотеку, обработку, кадрирование, маски, diff --git a/docs/localization-vi.md b/docs/localization-vi.md index 2d8776d8a3..d718a2be2c 100644 --- a/docs/localization-vi.md +++ b/docs/localization-vi.md @@ -1,6 +1,6 @@ # LightCraft bằng tiếng Việt -Chọn **Chỉnh sửa → Ngôn ngữ → Tiếng Việt** hoặc **Cài đặt → Chung → Ngôn ngữ**. +Chọn **Cài đặt → Chung → Ngôn ngữ → Tiếng Việt**. Lựa chọn áp dụng ngay và được lưu cho lần mở sau (`language: "vi"` trong `ui.json`). Các tag locale hệ thống sau cũng chọn tiếng Việt: `vi`, `vi-VN`, `vi_VN`, `vi_VN.UTF-8`. diff --git a/docs/localization-zh-hans.md b/docs/localization-zh-hans.md index bf41dfed57..8944cdbf27 100644 --- a/docs/localization-zh-hans.md +++ b/docs/localization-zh-hans.md @@ -2,13 +2,13 @@ LightCraft 的界面支持英语、简体中文、繁体中文(台湾)和日语。语言设置保存在 `ui.json` 的 `language` 字段中。 -- 通过「编辑 → 语言」或「设置 → 一般 → 语言」切换,选择会保留到下次启动。 +- 通过「设置 → 一般 → 语言」切换,选择会保留到下次启动。 - 已翻译的范围与 `zh-hant.json` 键集完全一致(1246 条),两份目录的键与键序一一对应。 - 正文字重与半粗体都使用 SIL OFL 的 **Noto Sans CJK SC**(简体中文)与 BIZ UDPGothic(日语)。 这些字体不在本仓库,而在 [storytold/craft-fonts](https://github.com/storytold/craft-fonts); 使用可选的构建输入 `CRAFT_FONTS_DIR=../craft-fonts` 时(所有正式发布版)会内嵌进来。 不指定该输入时程序照常构建运行,但中文与日文文字没有字形,会显示为方框 —— - 语言菜单里四种语言仍然都在,选中「简体中文」也只会得到一屏方框。未内嵌字体时构建会打印一条 + 「设置 → 一般 → 语言」里四种语言仍然都在,选中「简体中文」也只会得到一屏方框。未内嵌字体时构建会打印一条 `cargo::warning` 提示这一点。 - 翻译只发生在显示层:命令 ID、照片文件名、用户输入的元数据都不做改动。 - 尚未翻译的技术性错误、补充说明和发行说明仍以英文显示。 diff --git a/docs/localization-zh-hant.md b/docs/localization-zh-hant.md index abf1af6514..858eef8792 100644 --- a/docs/localization-zh-hant.md +++ b/docs/localization-zh-hant.md @@ -1,6 +1,6 @@ # LightCraft 繁體中文(台灣)介面 -從「編輯 → 語言 → 繁體中文(台灣)」切換,或開啟「設定 → 一般 → 語言」選擇。 +從「設定 → 一般 → 語言 → 繁體中文(台灣)」切換。 macOS 的設定也可由「LightCraft → 設定…」或 `⌘,` 開啟。 語言立即生效,並儲存在應用程式設定的 `ui.json`,下次啟動會沿用。 英文、簡體中文、繁體中文與日文可隨時互相切換。 diff --git a/docs/localization.md b/docs/localization.md index 36a28d5447..446d914892 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -39,12 +39,12 @@ are in [`localization-zh-hans.md`](localization-zh-hans.md), [`localization-zh-h ``` The fields are the BCP-47 code (also the settings-file value), the **endonym** shown in the - Language menu, the ISO 15924 script (`Latn`, `Jpan`, `Hans`, `Hant`, `Kore`…), and the embedded + Settings language row, the ISO 15924 script (`Latn`, `Jpan`, `Hans`, `Hant`, `Kore`…), and the embedded catalog. `build.rs` picks up `-formats.json` by name, so the macro and the format lookup follow automatically. Add the corresponding `app.language.` entry to `LANGUAGE_COMMANDS` and `language_from_command` in `src/menus.rs`, and to the - `language_commands_cover_every_language` test. Settings read the locale table; menus and - the control channel share the language-command mapping. + `language_commands_cover_every_language` test. Settings read the locale table; the control + channel uses the language commands (they are in no menu). 3. **Make sure the glyphs exist.** The script drives which craft-fonts faces the UI installs: a language whose script has no face in the build shows boxes (the test says so instead of failing). Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), never here; a diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 9bde237d92..6acd975226 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -482,7 +482,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-TEXTFIELD | Text fields behave alike | P1 | 🟡 | `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/panels/topbar.rs`, `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/panels/right.rs` (`meta_field`), `crates/ui-egui/src/dialogs.rs`, `crates/ui-egui/src/panels/unnamed.rs` | one shared field: right-click Cut / Copy / Paste / Select All (no Paste in the browser), Esc gives back the text from before the edit, Return / leaving / Esc reported to the caller, optional select-on-focus; agents use `ui.clipboard` (MCP `clipboard`) and `ui.inspect` → `copied`. Used by Search Photos, slider values, the Info panel's metadata fields (multi-line captions), the one-field dialogs (New / Rename Album, New Smart Album, Rename / Merge Keywords, text prompts) and the unnamed faces' name field so far; the other text fields (most dialogs, import, settings, masking, keywords …) still use egui's own and have no menu | | LR-BEHAV-HEADLESS | Headless UI snapshots | P2 | ✅ | `apps/lightcraft-cli/src/main.rs`, `crates/ui-egui/src/headless.rs`, `docs/control-protocol.md` | `snapshot` rasterizes the UI and defaults photo development to the CPU before the first frame, without adapter discovery; scaled dimensions are validated before allocation, and UI zoom preserves the requested physical viewport; JSON-lines control scripts are supported | | LR-BEHAV-ACCESS | Accessibility | P2 | 🟡 | `crates/ui-egui/src/widgets.rs`, `crates/ui-egui/src/widgets/text_field.rs`, `crates/ui-egui/src/panels/grid.rs`, `crates/ui-egui/tests/it/accessibility.rs` | AccessKit (VoiceOver / Narrator / AT-SPI): sliders announce control, value, range and step and take Increment / Decrement (the value field beside each is named ` value` and describes how to type or drag), buttons / icon buttons / dropdowns / section headers / sources their labels and state, text fields their caption, grid thumbnails file name, rating, flag and label. `tests/it/accessibility.rs` fails on an unnamed control, a slider without range or an untitled dialog in every view, Develop tool and 13 dialogs, and checks that Crop and Remove sliders are reached with Tab and that Tab walks the right panels top to bottom. Canvas tools by keyboard (`crates/ui-egui/src/canvas_keys.rs`, `crates/ui-egui/src/tests/canvas_keys.rs`): crop corners, edges and box, spot targets and sources, a New spot point (Return adds), radial / linear gradient handles and mask pins take the focus, are announced with their position and move with the arrows (Shift: further). Dialogs with one name field (New Album, New Smart Album, Save Metadata Preset, the renames) take the focus once when they open, so Tab and Shift+Tab reach their check box, Cancel and OK, and Return and Esc still confirm and cancel (`crates/ui-egui/src/tests/dialog_tab.rs`). The photo in Detail is named like its grid cell, `Photo: , , ,