Merge remote-tracking branch 'origin/main' into fix/sam-worker-policy-3546

This commit is contained in:
skylar taylor-barrick committed 2026-11-15 03:37:09 +01:00
commit cb99643367
161 files changed
+2929 -34580

No files matched your search

+2 -40
View File
@@ -19,46 +19,8 @@ concurrency:
jobs:
git-sources:
name: Git dependencies come from storytold
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Git dependencies come from storytold
run: |
set -euo pipefail
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
# Source replacement, patches and path overrides in cargo config never show up
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
# Cargo still reads the legacy .cargo/config.
python3 - <<'PY'
import os, sys, tomllib
for path in (".cargo/config", ".cargo/config.toml"):
if not os.path.exists(path):
continue
config = tomllib.load(open(path, "rb"))
replaced = [name for name, source in config.get("source", {}).items()
if isinstance(source, dict) and "replace-with" in source]
if replaced or "patch" in config or "paths" in config:
print(f"{path} replaces, patches or overrides a source")
sys.exit(1)
PY
# Fails when Cargo.lock is out of date with the manifests.
cargo metadata --locked --format-version 1 > /dev/null
python3 - <<'PY'
import sys, tomllib
lock = tomllib.load(open("Cargo.lock", "rb"))
bad = sorted({p["source"] for p in lock.get("package", [])
if p.get("source", "").startswith("git+")
and not p["source"].startswith("git+https://github.com/storytold/")})
if bad:
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
sys.exit(1)
PY
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main
nix:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
+4 -2
View File
@@ -33,9 +33,11 @@ jobs:
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
# The suite's WiX (5.0.2); the install-folder test needs no extensions.
- name: Install WiX
shell: pwsh
run: dotnet tool install --global wix --version 5.0.2
uses: storytold/craft-common-actions/actions/install-wix@main
with:
install-extensions: "false"
- name: Install-folder fallback and precedence (real MSI AppSearch)
shell: pwsh
run: |
+1 -43
View File
@@ -31,51 +31,9 @@ jobs:
contents: read
pull-requests: read
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
git-sources:
name: Git dependencies come from storytold
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Git dependencies come from storytold
run: |
set -euo pipefail
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
# Source replacement, patches and path overrides in cargo config never show up
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
# Cargo still reads the legacy .cargo/config.
python3 - <<'PY'
import os, sys, tomllib
for path in (".cargo/config", ".cargo/config.toml"):
if not os.path.exists(path):
continue
config = tomllib.load(open(path, "rb"))
replaced = [name for name, source in config.get("source", {}).items()
if isinstance(source, dict) and "replace-with" in source]
if replaced or "patch" in config or "paths" in config:
print(f"{path} replaces, patches or overrides a source")
sys.exit(1)
PY
# Fails when Cargo.lock is out of date with the manifests.
cargo metadata --locked --format-version 1 > /dev/null
python3 - <<'PY'
import sys, tomllib
lock = tomllib.load(open("Cargo.lock", "rb"))
bad = sorted({p["source"] for p in lock.get("package", [])
if p.get("source", "").startswith("git+")
and not p["source"].startswith("git+https://github.com/storytold/")})
if bad:
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
sys.exit(1)
PY
release:
needs: [git-sources, credits]
needs: credits
permissions:
contents: write
packages: write
Generated
+235 -48
View File
@@ -641,6 +641,12 @@ dependencies = [
"serde",
]
[[package]]
name = "bit_field"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1"
[[package]]
name = "bitflags"
version = "1.3.2"
@@ -1181,10 +1187,19 @@ dependencies = [
"libc",
]
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
dependencies = [
"md-5",
"rayon",
]
[[package]]
name = "craft-crw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=f3b62ec61f45534392376492fc5ad33047375205#f3b62ec61f45534392376492fc5ad33047375205"
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
dependencies = [
"thiserror 2.0.21",
]
@@ -1202,15 +1217,24 @@ source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955
[[package]]
name = "craft-gainmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d#430a908f68819bf23d14fe73ab9b18d8f4fd4e5d"
source = "git+https://github.com/storytold/craft-libs?rev=9dcbd90c7d16e1a668b3afa057e940e2db328b93#9dcbd90c7d16e1a668b3afa057e940e2db328b93"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67"
dependencies = [
"gif",
"image",
]
[[package]]
name = "craft-heif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d#430a908f68819bf23d14fe73ab9b18d8f4fd4e5d"
source = "git+https://github.com/storytold/craft-libs?rev=9dcbd90c7d16e1a668b3afa057e940e2db328b93#9dcbd90c7d16e1a668b3afa057e940e2db328b93"
dependencies = [
"heic-rs",
"rayon",
@@ -1239,10 +1263,92 @@ dependencies = [
"writeable",
]
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
dependencies = [
"craft-jpeg",
"craft-metadata",
"exr",
"flate2",
"half",
"image",
"image-webp",
"jpeg-encoder",
"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=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b77af389f30bb10de10d8436ca9b39fe94e3bb67#b77af389f30bb10de10d8436ca9b39fe94e3bb67"
dependencies = [
"jixel",
"jxl-oxide",
"thiserror 2.0.21",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
dependencies = [
"brotli-decompressor 6.0.1",
"chrono",
"craft-tiff",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9dcbd90c7d16e1a668b3afa057e940e2db328b93#9dcbd90c7d16e1a668b3afa057e940e2db328b93"
dependencies = [
"encoding_rs",
"flate2",
"rayon",
"thiserror 2.0.21",
]
[[package]]
name = "craft-raw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
dependencies = [
"chrono",
"craft-crw",
"craft-metadata",
"craft-tiff",
"jxl-oxide",
"miniz_oxide 0.9.1",
"rayon",
"serde",
"thiserror 2.0.21",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d#430a908f68819bf23d14fe73ab9b18d8f4fd4e5d"
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1307,6 +1413,15 @@ dependencies = [
"wayland-client",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=f0f4758c01581d79577b9bf5046c06f4e77b1f18#f0f4758c01581d79577b9bf5046c06f4e77b1f18"
dependencies = [
"quick-xml 0.41.0",
"thiserror 2.0.21",
]
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -1796,6 +1911,20 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "encoding_rs"
version = "0.8.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5"
dependencies = [
"cfg-if",
"core_detect",
"multiversion_no_op",
"rustversion",
"scopeguard",
"simdutf8",
]
[[package]]
name = "endi"
version = "1.1.1"
@@ -1977,6 +2106,22 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "exr"
version = "1.74.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6"
dependencies = [
"bit_field",
"half",
"lebe",
"miniz_oxide 0.8.9",
"multiversion",
"rayon-core",
"smallvec",
"zune-inflate",
]
[[package]]
name = "faer-core"
version = "0.17.1"
@@ -3136,10 +3281,10 @@ dependencies = [
"byteorder-lite",
"color_quant",
"gif",
"image-webp",
"moxcms 0.8.1",
"moxcms",
"num-traits",
"png",
"qoi",
"tiff",
"zune-core",
"zune-jpeg",
@@ -3308,20 +3453,11 @@ dependencies = [
"libc",
]
[[package]]
name = "jpeg-decoder"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07"
dependencies = [
"rayon",
]
[[package]]
name = "jpeg-encoder"
version = "0.7.1"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6"
checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f"
[[package]]
name = "js-sys"
@@ -3568,6 +3704,12 @@ dependencies = [
"spin",
]
[[package]]
name = "lebe"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
[[package]]
name = "libc"
version = "0.2.191"
@@ -3685,30 +3827,26 @@ version = "0.21.1"
dependencies = [
"avif-serialize",
"bytemuck",
"craft-cms",
"craft-gainmap",
"craft-gif",
"craft-heif",
"craft-image-codecs",
"craft-jxl",
"craft-psd",
"craft-tiff",
"dhat",
"image",
"image-webp",
"jixel",
"jpeg-decoder",
"jpeg-encoder",
"jxl-oxide",
"lightcraft-color",
"lightcraft-geom",
"lightcraft-raster",
"lightcraft-testkit",
"moxcms 0.9.1",
"png",
"proptest",
"rav1e",
"ravif",
"rayon",
"serde",
"thiserror 2.0.21",
"tiff",
"zune-core",
"zune-jpeg",
]
[[package]]
@@ -3892,9 +4030,9 @@ dependencies = [
name = "lightcraft-lensdb"
version = "0.21.1"
dependencies = [
"craft-xml",
"lightcraft-develop",
"lightcraft-geom",
"quick-xml 0.41.0",
]
[[package]]
@@ -3930,10 +4068,11 @@ version = "0.21.1"
dependencies = [
"chrono",
"craft-heif",
"craft-metadata",
"craft-psd",
"craft-tiff",
"lightcraft-geom",
"proptest",
"quick-xml 0.41.0",
"serde",
"serde_json",
]
@@ -3942,8 +4081,8 @@ dependencies = [
name = "lightcraft-pipeline"
version = "0.21.1"
dependencies = [
"craft-image-codecs",
"dhat",
"image",
"lightcraft-color",
"lightcraft-develop",
"lightcraft-geom",
@@ -3961,12 +4100,10 @@ dependencies = [
name = "lightcraft-preview"
version = "0.21.1"
dependencies = [
"jpeg-encoder",
"craft-image-codecs",
"lightcraft-raster",
"log",
"siphasher",
"zune-core",
"zune-jpeg",
]
[[package]]
@@ -3986,11 +4123,10 @@ name = "lightcraft-raw"
version = "0.21.1"
dependencies = [
"chrono",
"craft-crw",
"craft-image-codecs",
"craft-raw",
"craft-tiff",
"dhat",
"jpeg-encoder",
"jxl-oxide",
"lightcraft-color",
"lightcraft-geom",
"lightcraft-meta",
@@ -4003,7 +4139,6 @@ dependencies = [
"sha2",
"thiserror 2.0.21",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
@@ -4011,7 +4146,7 @@ dependencies = [
name = "lightcraft-scenes"
version = "0.21.1"
dependencies = [
"image",
"craft-image-codecs",
"lightcraft-color",
"lightcraft-raster",
"rayon",
@@ -4205,6 +4340,16 @@ dependencies = [
"rayon",
]
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -4281,16 +4426,6 @@ dependencies = [
"pxfm",
]
[[package]]
name = "moxcms"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "396077b717181ce3f9a6b66739b269b82d756be5ec0f76be0bc40a7c51775830"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "muda"
version = "0.21.2"
@@ -4309,6 +4444,34 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "multiversion"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076"
dependencies = [
"multiversion-macros",
"target-features",
]
[[package]]
name = "multiversion-macros"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"target-features",
]
[[package]]
name = "multiversion_no_op"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
[[package]]
name = "naga"
version = "30.0.1"
@@ -5477,6 +5640,15 @@ version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "qoi"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
dependencies = [
"bytemuck",
]
[[package]]
name = "quick-error"
version = "1.2.3"
@@ -6563,6 +6735,12 @@ dependencies = [
"libc",
]
[[package]]
name = "target-features"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5"
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -8237,6 +8415,15 @@ version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
[[package]]
name = "zune-inflate"
version = "0.2.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
dependencies = [
"simd-adler32",
]
[[package]]
name = "zune-jpeg"
version = "0.5.15"
+18 -15
View File
@@ -13,12 +13,21 @@ repository = "https://github.com/storytold/lightcraft"
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" }
# Canon CRW decoder shared with the other Craft apps
craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f45534392376492fc5ad33047375205" }
craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "b77af389f30bb10de10d8436ca9b39fe94e3bb67", features = ["frames"] }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "b77af389f30bb10de10d8436ca9b39fe94e3bb67", default-features = false, features = ["decode", "encode"] }
# Photo metadata: EXIF, IPTC-IIM, XMP packets and GPX track logs (craft-libs#949)
craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
# 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"] }
# 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 = "430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" }
craft-gainmap = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93" }
# PSD/PSB: the header, colour mode data and image resources (craft-libs#885).
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93" }
# internal
lightcraft-denoise-core = { path = "crates/denoise-core" }
lightcraft-denoise = { path = "crates/denoise", default-features = false }
@@ -29,7 +38,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 = "430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
# Camera raw files, the format layer: every maker but CR3, ARW, RAF, RW2 and ORF (craft-libs#862 and the maker PRs).
# On the same commit as craft-tiff: its errors and IFDs are shared.
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" }
lightcraft-raw = { path = "crates/raw" }
lightcraft-codecs = { path = "crates/codecs" }
lightcraft-meta = { path = "crates/meta" }
@@ -48,7 +60,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 = "430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" }
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "9dcbd90c7d16e1a668b3afa057e940e2db328b93" }
lightcraft-segment = { path = "crates/segment" }
lightcraft-geocode = { path = "crates/geocode" }
lightcraft-slideshow = { path = "crates/slideshow" }
@@ -75,22 +87,13 @@ libc = "0.2" # dev-only: process CPU time in benches
dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds
# formats
quick-xml = "0.41"
miniz_oxide = "0.9"
# codecs
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "webp"] }
zune-jpeg = { version = "0.5", default-features = false, features = ["std", "x86", "neon"] }
zune-core = { version = "0.5", default-features = false, features = ["std"] }
jpeg-decoder = { version = "0.3", default-features = false }
jpeg-encoder = { version = "0.7", default-features = false, features = ["std"] }
ab_glyph = { version = "0.2", default-features = false, features = ["std"] } # Apache-2.0, pure Rust glyph rasterizer (export watermarks)
png = "0.18"
tiff = "0.11"
image-webp = "0.2"
moxcms = { version = "0.9", default-features = false, features = ["lut"] }
jxl-oxide = { version = "0.12", default-features = false }
jixel = "=0.3.4" # BSD-3-Clause OR Apache-2.0, pure-Rust JPEG XL encoder (export; port of libjxl-tiny)
zune-core = { version = "0.5", default-features = false, features = ["std"] }
zune-jpegxl = { version = "0.5", default-features = false, features = ["std"] } # MIT/Apache-2.0/Zlib lossless JXL encoder (test fixtures only)
ravif = { version = "0.13", default-features = false, features = ["threading"] } # no "asm": it needs nasm (non-Rust)
# HDR AVIF (PQ): ravif fixes the sRGB transfer curve, so HDR files drive its rav1e + avif-serialize directly
@@ -180,12 +183,12 @@ lightcraft-color = { opt-level = 3 }
lightcraft-develop = { opt-level = 3 }
lightcraft-geom = { opt-level = 3 }
lightcraft-raw = { opt-level = 3 }
craft-raw = { opt-level = 3 }
lightcraft-codecs = { opt-level = 3 }
lightcraft-scenes = { opt-level = 3 }
lightcraft-preview = { opt-level = 3 }
zune-jpeg = { opt-level = 3 }
zune-core = { opt-level = 3 }
jpeg-decoder = { opt-level = 3 }
jpeg-encoder = { opt-level = 3 }
png = { opt-level = 3 }
miniz_oxide = { opt-level = 3 }
+38 -1
View File
@@ -180,7 +180,13 @@ pub struct Meta {
pub lens_make: String,
pub focal_mm: Option<f32>,
pub aperture: Option<f32>,
/// Shutter speed for display, from [`lightcraft_meta::format_exposure_time`] (`1/3`, `0.3571`, `2.5`).
pub shutter: String,
/// The file's exact exposure time in seconds, kept beside the rounded `shutter` text so export
/// writes the original duration; read through [`Meta::shutter_seconds`]. Left out of the catalog
/// JSON when unknown, so older catalogs read unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exposure_time: Option<f64>,
pub iso: Option<u32>,
/// Whether the flash fired, from Exif `Flash`.
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -224,6 +230,16 @@ pub struct Meta {
pub focus: Option<lightcraft_meta::FocusPoint>,
}
impl Meta {
/// Shutter speed in seconds: the exact [`Meta::exposure_time`] while `shutter` still shows it,
/// otherwise whatever `shutter` says (set by hand, or a catalog from before the exact time was kept).
pub fn shutter_seconds(&self) -> Option<f64> {
self.exposure_time
.filter(|t| lightcraft_meta::format_exposure_time(*t).is_some_and(|text| text == self.shutter.trim()))
.or_else(|| parse_shutter_seconds(&self.shutter))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Version {
pub name: String,
@@ -761,7 +777,28 @@ mod edited_tests {
#[cfg(test)]
mod shutter_tests {
use super::parse_shutter_seconds;
use super::*;
#[test]
fn shutter_seconds_prefers_the_exact_time_while_the_text_still_shows_it() {
let mut m = Meta { shutter: "0.3571".into(), exposure_time: Some(1.0 / 2.8), ..Default::default() };
assert_eq!(m.shutter_seconds(), Some(1.0 / 2.8));
m.shutter = "1/3".into();
m.exposure_time = Some(1.0 / 3.0);
assert_eq!(m.shutter_seconds(), Some(1.0 / 3.0));
// the text no longer matches the stored time (edited elsewhere): the text wins
m.shutter = "1/250".into();
assert_eq!(m.shutter_seconds(), Some(1.0 / 250.0));
// an older catalog without the exact time
m.exposure_time = None;
m.shutter = "2.5".into();
assert_eq!(m.shutter_seconds(), Some(2.5));
// the exact time stays out of the JSON when unknown, and round-trips when known
assert!(!serde_json::to_string(&m).unwrap().contains("exposure_time"));
m.exposure_time = Some(2.5);
let back: Meta = serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap();
assert_eq!(back.exposure_time, Some(2.5));
}
#[test]
fn a_fraction_needs_a_positive_numerator_and_denominator() {
+2
View File
@@ -1100,6 +1100,8 @@ impl Rule {
"captureDate" => date_op(op, p.captured.as_deref(), value),
"importDate" => date_op(op, Some(&p.imported), value),
"editDate" => date_op(op, p.edited.as_deref(), value),
// (the shown shutter text, not the exact time kept for export: a rule matches the value the
// photo shows, `1/3` or `0.3571`, at every op, including `is` and the edges of a range)
"shutterSpeed" => num_op(op, crate::parse_shutter_seconds(&m.shutter), &shutter_value(value)),
"iso" => num_op(op, m.iso.map(|v| v as f64), value),
"flash" => yes(m.flash.unwrap_or(false)),
+16
View File
@@ -795,3 +795,19 @@ fn file_path_contains_finds_every_piece_of_a_long_path() {
}
}
}
#[test]
fn shutter_speed_rules_match_the_shown_value() {
let cat = Catalog::new();
let mut p = photo(1);
let m =
|p: &Photo, op: &str, value: serde_json::Value| rs(json!({"rules": [{"field": "shutterSpeed", "op": op, "value": value}]})).matches(p, &cat);
p.meta.exposure_time = Some(1.0 / 2.8);
p.meta.shutter = "0.3571".into();
assert!(m(&p, "is", json!("0.3571")) && !m(&p, "isNot", json!("0.3571")), "1/2.8 s is the 0.3571 it shows");
assert!(m(&p, "lte", json!("0.3571")) && m(&p, "gte", json!("0.3571")));
p.meta.exposure_time = Some(3333.0 / 10000.0);
p.meta.shutter = "1/3".into();
assert!(m(&p, "is", json!("1/3")) && !m(&p, "isNot", json!("1/3")), "3333/10000 s is the 1/3 it shows");
assert!(m(&p, "gte", json!("1/3")) && m(&p, "lte", json!("1/3")) && !m(&p, "lt", json!("1/3")));
}
+1 -1
View File
@@ -260,7 +260,7 @@ impl Catalog {
.filter(|p| !p.deleted && !merged(p))
.filter_map(|p| {
let t = iso_seconds(p.captured.as_deref()?)?;
let s = crate::model::parse_shutter_seconds(&p.meta.shutter)?;
let s = p.meta.shutter_seconds()?;
let n = p.meta.aperture.filter(|n| n.is_finite() && *n > 0.0).unwrap_or(1.0) as f64;
let iso = p.meta.iso.filter(|i| *i > 0).unwrap_or(100) as f64;
Some((t, p.file_name.as_str(), p.id, s, (s * iso / (n * n)).log2()))
+9 -15
View File
@@ -13,34 +13,28 @@ lightcraft-geom = { workspace = true }
lightcraft-color = { workspace = true }
lightcraft-raster = { workspace = true }
craft-gainmap = { workspace = true }
craft-cms = { workspace = true }
craft-image-codecs = { workspace = true }
craft-tiff = { workspace = true }
craft-gif = { workspace = true }
craft-psd = { workspace = true }
craft-heif = { workspace = true, optional = true }
serde = { workspace = true }
bytemuck = { workspace = true }
thiserror = { workspace = true }
rayon = { workspace = true, optional = true }
image = { workspace = true, features = ["gif", "bmp"] }
zune-jpeg = { workspace = true }
zune-core = { workspace = true }
jpeg-decoder = { workspace = true }
jpeg-encoder = { workspace = true }
png = { workspace = true }
tiff = { workspace = true }
image-webp = { workspace = true }
moxcms = { workspace = true }
jxl-oxide = { workspace = true, optional = true }
craft-jxl = { workspace = true, optional = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
ravif = { workspace = true, optional = true }
rav1e = { workspace = true, optional = true }
avif-serialize = { workspace = true, optional = true }
# spawns threads of its own (std::thread), which wasm32 has not got
jixel = { workspace = true, optional = true }
[features]
default = ["parallel", "jxl", "avif"]
parallel = ["dep:rayon", "lightcraft-raster/parallel", "jpeg-decoder/rayon"]
## JPEG XL decode (jxl-oxide) and, on native targets, encode (jixel); both pure Rust.
jxl = ["dep:jxl-oxide", "dep:jixel"]
parallel = ["dep:rayon", "lightcraft-raster/parallel"]
## JPEG XL decoding and encoding via the shared craft-jxl codec.
jxl = ["dep:craft-jxl"]
# HEIC/HEIF decode via the optional craft-heif crate (heic-rs, pure Rust). Off by default so
# distributors choose it at build time (HEVC patents are a distributor's call, same policy as
# PhotoCraft); `cargo xtask ci` clippies and tests it (`--features heif`), releases don't ship it yet.
+3 -3
View File
@@ -52,7 +52,7 @@ CRW, MRW, X3F) are detected so the engine can route them to `lightcraft-raw`; `d
| WebP | lossy + lossless, alpha, first frame of animations | lossless only | ICCP/EXIF/XMP chunks |
| GIF / BMP | yes (first GIF frame) | — | via `image` |
| PSD / PSB | merged composite: 8/16/32-bit gray, RGB, CMYK, indexed, duotone (as gray); raw/RLE | — | ICC (1039), EXIF (1058), XMP (1060); ZIP-compressed composite, Lab and 1-bit unsupported |
| JPEG XL | yes (jxl-oxide, feature `jxl`, default on) | yes (jixel, `encode_jxl`, feature `jxl`, native only): lossy VarDCT / lossless Modular, 8/16-bit, effort (fast / normal), progressive; HDR as 16-bit Rec. 2020 PQ | decode: enum colour → rendered straight to linear Rec.2020 (XYB via linear sRGB primaries); ICC → our ICC path; orientation applied by the decoder (reported as 1). Encode: lossy files declare an enum encoding (sRGB, Display P3, Rec. 2020 BT.709 curve, Rec. 2020 PQ), lossless ones embed the ICC profile; EXIF / XMP in `Exif` / `xml ` boxes |
| JPEG XL | yes (`craft-jxl`, feature `jxl`, default on) | yes (`craft-jxl`, `encode_jxl`, feature `jxl`, native only): lossy VarDCT / lossless Modular, 8/16-bit, effort (fast / normal), progressive; HDR as 16-bit Rec. 2020 PQ | decode: enum colour → rendered straight to linear Rec.2020 (XYB via linear sRGB primaries); ICC → our ICC path; orientation applied by the shared decoder (reported as 1). Encode: lossy files declare an enum encoding (sRGB, Display P3, Rec. 2020 BT.709 curve, Rec. 2020 PQ), lossless ones embed the ICC profile; EXIF / XMP in `Exif` / `xml ` boxes |
| AVIF | **no** | yes (ravif/rav1e, native only, feature `avif`) | 8/10-bit sRGB, EXIF; no ICC in the muxer. HDR: `encode_avif_hdr` writes 10-bit BT.2020 PQ (SDR white at 203 cd/m², CICP `nclx` + `clli`) or HLG (`hlg_signal`, SDR white at 0.75) |
| HEIC/HEIF | yes with feature `heif` (craft-heif: heic-rs + libheif-matching colour; 4:2:0/mono, 8–10-bit, grids, irot/imir/clap, ICC/nclx/VUI, EXIF/XMP, thumbnail item) | — | 4:2:2/4:4:4 (Canon/Sony HIF) unsupported |
| Gain map JPEG (HDR) | gain map found and decoded (`gainmap::read_jpeg`): ISO 21496-1 metadata, else Adobe `hdrgm` XMP | yes (`gainmap::encode_jpeg`) | CIPA DC-007 MPF index (gain map typed `0x050000`), ISO 21496-1 APP2 on both images, `hdrgm` + Container XMP for Android/Chrome, Apple `HDRGainMap`/`HDRToneMap` XMP; gain maps are never used as thumbnails |
@@ -91,8 +91,8 @@ All pure Rust, verified with `cargo info` / `cargo tree`:
| image-webp | MIT OR Apache-2.0 | WebP |
| image (gif, bmp only) | MIT OR Apache-2.0 | GIF/BMP |
| moxcms | BSD-3-Clause OR Apache-2.0 | ICC parse/write, CMS |
| jxl-oxide | MIT OR Apache-2.0 | JPEG XL decode |
| jixel | BSD-3-Clause OR Apache-2.0 | JPEG XL encode (native only) |
| craft-jxl | MIT OR Apache-2.0 | JPEG XL decode/encode (shared craft-libs) |
| jxl-oxide | MIT OR Apache-2.0 | JPEG XL test oracle only |
| ravif (+ rav1e, avif-serialize) | BSD-3-Clause / BSD-2-Clause | AVIF encode (native only; heavy to compile) |
Deliberately **not** used: anything AGPL from imazen (heic, zenjpeg, jxl-encoder, rav1d-safe),
+16 -12
View File
@@ -23,8 +23,10 @@ fn best<T>(n: usize, mut f: impl FnMut() -> T) -> (T, f64) {
fn main() {
let (w, h, rgb) = match std::env::args().nth(1) {
Some(p) => {
let img = image::open(p).expect("open").to_rgb8();
(img.width() as usize, img.height() as usize, img.into_raw())
let bytes = std::fs::read(p).expect("read");
let img = lightcraft_codecs::decode(&bytes, lightcraft_codecs::DecodeOptions::default()).expect("open").to_srgb8();
let rgb: Vec<u8> = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect();
(img.width, img.height, rgb)
}
None => {
let (w, h) = (6000, 4000);
@@ -38,20 +40,22 @@ fn main() {
(w, h, v)
}
};
for (sub, js) in
[(ChromaSubsampling::S444, jpeg_encoder::SamplingFactor::R_4_4_4), (ChromaSubsampling::S420, jpeg_encoder::SamplingFactor::R_4_2_0)]
{
for (sub, cs) in [(ChromaSubsampling::S444, false), (ChromaSubsampling::S420, true)] {
let (ours, t_ours) = best(5, || lightcraft_codecs::jpeg_par::encode(&rgb, w, h, 3, 90, sub, &[]));
let (theirs, t_theirs) = best(3, || {
let mut out = Vec::new();
let mut e = jpeg_encoder::Encoder::new(&mut out, 90);
e.set_sampling_factor(js);
e.encode(&rgb, w as u16, h as u16, jpeg_encoder::ColorType::Rgb).unwrap();
out
let ic_img = craft_image_codecs::Image::from_u8(w as u32, h as u32, craft_image_codecs::ChannelLayout::Rgb, rgb.clone()).unwrap();
let opts = craft_image_codecs::EncodeOptions { jpeg_quality: 90, jpeg_chroma_subsampling: cs, ..Default::default() };
craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Jpeg, &opts).unwrap()
});
let dec = |b: &[u8]| jpeg_decoder::Decoder::new(b).decode().unwrap();
let dec = |b: &[u8]| {
craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, b, &craft_image_codecs::DecodeOptions::default())
.unwrap()
.as_u8()
.unwrap()
.to_vec()
};
println!(
"{w}x{h} {sub:?} q90: parallel {t_ours:.0} ms, {} KB, PSNR {:.2} dB | jpeg-encoder {t_theirs:.0} ms, {} KB, PSNR {:.2} dB",
"{w}x{h} {sub:?} q90: parallel {t_ours:.0} ms, {} KB, PSNR {:.2} dB | craft-image-codecs {t_theirs:.0} ms, {} KB, PSNR {:.2} dB",
ours.len() / 1024,
psnr(&rgb, &dec(&ours)),
theirs.len() / 1024,
+58 -81
View File
@@ -9,13 +9,11 @@
//!
//! All conversions are relative colorimetric: the display's white is the image's white.
use std::sync::Arc;
use crate::icc;
use crate::space::Trc;
use craft_cms::{Builtin, ColorSpace, Intent, Pcs, Profile, Transform, TransformOptions};
use lightcraft_color::{D50, D65, Mat3, REC2020, bradford};
use lightcraft_raster::Rgba8;
use moxcms::{ColorProfile, DataColorSpace, Layout, RenderingIntent, Transform8BitExecutor, TransformOptions, Xyzd};
/// Largest profile file accepted (monitor profiles are a few KB; LUT profiles up to a few MB).
pub const MAX_PROFILE_BYTES: usize = 32 << 20;
@@ -46,7 +44,7 @@ enum Correction {
/// Per-channel tables (matrix/TRC profile: same primaries, other curves).
Curves(Box<[[u8; 256]; 3]>),
/// A full CMS transform (LUT-based profile).
Cms(Arc<Transform8BitExecutor>),
Cms(Box<Transform>),
}
/// A parsed display profile with its transforms (built once, applied to every preview).
@@ -59,8 +57,8 @@ pub struct DisplayProfile {
/// Linear display RGB → linear Rec.2020 (D65; display white → (1, 1, 1)).
pub to_rec2020: Mat3,
correction: Correction,
from_srgb: Arc<Transform8BitExecutor>,
to_srgb: Arc<Transform8BitExecutor>,
from_srgb: Transform,
to_srgb: Transform,
}
impl std::fmt::Debug for DisplayProfile {
@@ -75,11 +73,7 @@ impl std::fmt::Debug for DisplayProfile {
}
fn opts() -> TransformOptions {
TransformOptions { rendering_intent: RenderingIntent::RelativeColorimetric, ..TransformOptions::default() }
}
fn xyzd(v: [f64; 3]) -> Xyzd {
Xyzd { x: v[0], y: v[1], z: v[2] }
TransformOptions { intent: Intent::RelativeColorimetric, bpc: false, precise_float: true }
}
/// Linear Rec.2020 → XYZ relative to D50 (the ICC PCS), Bradford-adapted.
@@ -100,11 +94,6 @@ fn hash(bytes: &[u8]) -> u64 {
h.finish() | 1
}
/// Runs a moxcms call that may panic on a hostile profile.
fn guarded<T>(f: impl FnOnce() -> Option<T>) -> Option<T> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok().flatten()
}
impl DisplayProfile {
/// Parse a display profile (an RGB ICC profile, matrix/TRC or LUT-based) and build its
/// transforms. Errors say what is wrong with the file; nothing here panics.
@@ -112,11 +101,11 @@ impl DisplayProfile {
if bytes.len() > MAX_PROFILE_BYTES {
return Err(format!("the profile is too large ({} MB)", bytes.len() >> 20));
}
let p = guarded(|| ColorProfile::new_from_slice(bytes).ok()).ok_or("not a valid ICC profile")?;
if p.color_space != DataColorSpace::Rgb {
let p = Profile::parse(bytes).map_err(|_| "not a valid ICC profile")?;
if p.color_space != ColorSpace::Rgb {
return Err("not an RGB profile (a display profile describes an RGB device)".into());
}
if !matches!(p.pcs, DataColorSpace::Xyz | DataColorSpace::Lab) {
if !matches!(p.pcs, Pcs::Xyz | Pcs::Lab) {
return Err("unsupported profile connection space".into());
}
let info = icc::parse(bytes).ok_or("not a valid ICC profile")?;
@@ -127,11 +116,8 @@ impl DisplayProfile {
.filter(|d| !d.is_empty())
.unwrap_or("Display profile")
.to_string();
let has_lut = p.lut_a_to_b_colorimetric.is_some()
|| p.lut_a_to_b_perceptual.is_some()
|| p.lut_b_to_a_colorimetric.is_some()
|| p.lut_b_to_a_perceptual.is_some();
let srgb = ColorProfile::new_srgb();
let has_lut = p.a2b[0].is_some() || p.a2b[1].is_some() || p.b2a[0].is_some() || p.b2a[1].is_some();
let srgb = Builtin::Srgb.profile().clone();
// the primaries the pipeline renders into
let (kind, to_xyz_d50, curves) = match &info.kind {
@@ -147,17 +133,14 @@ impl DisplayProfile {
// the proxy: the display's primaries (as the pipeline targets them), sRGB curve
let proxy_xyz = rec2020_to_xyz_d50().mul(&to_rec2020).0;
let mut proxy = ColorProfile::new_srgb();
proxy.cicp = None;
proxy.red_colorant = xyzd([proxy_xyz[0][0], proxy_xyz[1][0], proxy_xyz[2][0]]);
proxy.green_colorant = xyzd([proxy_xyz[0][1], proxy_xyz[1][1], proxy_xyz[2][1]]);
proxy.blue_colorant = xyzd([proxy_xyz[0][2], proxy_xyz[1][2], proxy_xyz[2][2]]);
let mut proxy = Builtin::Srgb.profile().clone();
proxy.matrix = Some(proxy_xyz);
let transform = |src: &ColorProfile, dst: &ColorProfile| guarded(|| src.create_transform_8bit(Layout::Rgba, dst, Layout::Rgba, opts()).ok());
let transform = |src: &Profile, dst: &Profile| Transform::with_options(src, dst, opts()).ok();
let correction = match curves {
Some(trc) if trc.iter().all(|t| t.approx_eq(&Trc::Srgb, 2e-4)) => Correction::None,
Some(trc) => Correction::Curves(Box::new(curve_tables(&trc))),
None => Correction::Cms(transform(&proxy, &p).ok_or("the profile's tables can't be applied")?),
None => Correction::Cms(Box::new(transform(&proxy, &p).ok_or("the profile's tables can't be applied")?)),
};
let from_srgb = transform(&srgb, &p).ok_or("can't convert sRGB to this profile")?;
let to_srgb = transform(&proxy, &srgb).ok_or("can't convert this profile to sRGB")?;
@@ -205,12 +188,12 @@ impl DisplayProfile {
/// Device RGB → PCS (XYZ D50) of the pure primaries, measured through the profile's tables
/// (LUT-only profiles have no colorant tags).
fn measured_to_xyz_d50(p: &ColorProfile) -> Result<Mat3, String> {
fn measured_to_xyz_d50(p: &Profile) -> Result<Mat3, String> {
let lin = icc::linear_rec2020_profile();
let x = guarded(|| p.create_transform_f32(Layout::Rgb, &lin, Layout::Rgb, opts()).ok()).ok_or("the profile's tables can't be applied")?;
let x = Transform::with_options(p, &lin, opts()).map_err(|_| "the profile's tables can't be applied")?;
let src = [1.0f32, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
let mut dst = [0f32; 9];
guarded(|| x.transform(&src, &mut dst).ok()).ok_or("the profile's tables can't be applied")?;
x.convert_f32(&src, 3, &mut dst, 3, false).map_err(|_| "the profile's tables can't be applied")?;
let c = |i: usize| [dst[i] as f64, dst[i + 3] as f64, dst[i + 6] as f64];
// columns: each primary in linear Rec.2020
let m = Mat3([c(0), c(1), c(2)]);
@@ -247,10 +230,10 @@ fn from_linear(t: &Trc, y: f32) -> f32 {
0.5 * (lo + hi)
}
fn apply(x: &Arc<Transform8BitExecutor>, img: &mut Rgba8) -> Result<(), String> {
fn apply(x: &Transform, img: &mut Rgba8) -> Result<(), String> {
const CHUNK: usize = 1 << 14; // pixels
let src = img.data.clone();
let run = |s: &[[u8; 4]], d: &mut [[u8; 4]]| guarded(|| x.transform(s.as_flattened(), d.as_flattened_mut()).ok()).is_some();
let run = |s: &[[u8; 4]], d: &mut [[u8; 4]]| x.convert_u8(s.as_flattened(), 4, d.as_flattened_mut(), 4, true).is_ok();
#[cfg(feature = "parallel")]
let ok = {
use rayon::prelude::*;
@@ -340,9 +323,8 @@ mod tests {
fn rejects_bad_profiles() {
assert!(DisplayProfile::from_icc(&[]).is_err());
assert!(DisplayProfile::from_icc(&[0u8; 300]).is_err());
let mut gray = ColorProfile::new_gray_with_gamma(2.2);
gray.cicp = None;
assert!(DisplayProfile::from_icc(&gray.encode().unwrap()).is_err());
let gray = Builtin::GrayGamma22.profile().to_bytes();
assert!(DisplayProfile::from_icc(&gray).is_err());
// truncated / corrupted real profiles never panic
let good = icc::write_named(NamedSpace::DisplayP3);
for n in [10, 128, 140, 200, good.len() - 1] {
@@ -359,55 +341,50 @@ mod tests {
/// Display P3 panel with a gamma 2.2 response): the primaries are measured through the tables
/// and every preview goes through the CMS.
fn lut_only_p3_gamma22() -> Vec<u8> {
use moxcms::{LutMultidimensionalType, LutWarehouse, Matrix3d, ProfileClass, ToneReprCurve, Vector3d};
use craft_cms::Curve;
use craft_cms::pipeline::Stage;
use craft_cms::profile::{Lut, LutKind};
let m = crate::space::rgb_to_xyz_d50(&DISPLAY_P3).0;
let inv = crate::space::rgb_to_xyz_d50(&DISPLAY_P3).inverse().unwrap().0;
let curves = |v: Vec<f32>| vec![ToneReprCurve::Parametric(v.clone()), ToneReprCurve::Parametric(v.clone()), ToneReprCurve::Parametric(v)];
let ident = || curves(vec![1.0]);
// mAB: A → CLUT → M → matrix → B (no CLUT: M curves linearize, the matrix goes to XYZ)
let a2b = LutWarehouse::Multidimensional(LutMultidimensionalType {
num_input_channels: 3,
num_output_channels: 3,
grid_points: [0; 16],
clut: None,
a_curves: vec![],
m_curves: curves(vec![2.2]),
matrix: Matrix3d { v: m.map(|r| r.map(|v| v * 32768.0 / 65535.0)) },
b_curves: ident(),
bias: Vector3d::default(),
});
let b2a = LutWarehouse::Multidimensional(LutMultidimensionalType {
num_input_channels: 3,
num_output_channels: 3,
grid_points: [0; 16],
clut: None,
a_curves: vec![],
m_curves: curves(vec![1.0 / 2.2]),
matrix: Matrix3d { v: inv.map(|r| r.map(|v| v * 65535.0 / 32768.0)) },
b_curves: ident(),
bias: Vector3d::default(),
});
let mut p = ColorProfile::new_srgb();
p.cicp = None;
p.profile_class = ProfileClass::DisplayDevice;
p.red_colorant = Xyzd::default();
p.green_colorant = Xyzd::default();
p.blue_colorant = Xyzd::default();
p.red_trc = None;
p.green_trc = None;
p.blue_trc = None;
p.lut_a_to_b_colorimetric = Some(a2b.clone());
p.lut_a_to_b_perceptual = Some(a2b);
p.lut_b_to_a_colorimetric = Some(b2a.clone());
p.lut_b_to_a_perceptual = Some(b2a);
p.encode().unwrap()
let flat = |m: [[f64; 3]; 3], scale: f64| -> Vec<f64> { m.iter().flatten().map(|&v| v * scale).collect() };
let curves = |g: f64| vec![Curve::Gamma(g), Curve::Gamma(g), Curve::Gamma(g)];
let ident = || vec![Curve::Identity, Curve::Identity, Curve::Identity];
let a2b = Lut {
kind: LutKind::Ab,
inputs: 3,
outputs: 3,
stages: vec![
Stage::Curves(curves(2.2)),
Stage::Matrix { rows: 3, cols: 3, m: flat(m, 32768.0 / 65535.0), offset: vec![0.0; 3] },
Stage::Curves(ident()),
],
};
let b2a = Lut {
kind: LutKind::Ab,
inputs: 3,
outputs: 3,
stages: vec![
Stage::Curves(ident()),
Stage::Matrix { rows: 3, cols: 3, m: flat(inv, 65535.0 / 32768.0), offset: vec![0.0; 3] },
Stage::Curves(curves(1.0 / 2.2)),
],
};
let mut p = Builtin::Srgb.profile().clone();
p.class = craft_cms::ProfileClass::Display;
p.matrix = None;
p.trc = None;
p.a2b[0] = Some(a2b.clone());
p.a2b[1] = Some(a2b);
p.b2a[0] = Some(b2a.clone());
p.b2a[1] = Some(b2a);
p.with_encoded_bytes().to_bytes().to_vec()
}
#[test]
fn lut_profile_goes_through_the_cms() {
let bytes = lut_only_p3_gamma22();
let parsed = ColorProfile::new_from_slice(&bytes).unwrap();
assert!(!parsed.is_matrix_shaper() && parsed.lut_b_to_a_colorimetric.is_some(), "a LUT-only profile");
let parsed = Profile::parse(&bytes).unwrap();
assert!(!parsed.is_matrix_shaper() && parsed.b2a[1].is_some(), "a LUT-only profile");
let d = DisplayProfile::from_icc(&bytes).unwrap();
assert_eq!(d.kind, DisplayKind::Lut);
assert!(d.needs_correction());
+156 -213
View File
@@ -133,50 +133,48 @@ pub fn encode_jpeg(img: &EncodeImage, quality: u8, subsampling: ChromaSubsamplin
return Err(Error::Encode("JPEG dimensions are limited to 65535".into()));
}
let n = img.width as usize * img.height as usize;
let (data, ct): (std::borrow::Cow<[u8]>, jpeg_encoder::ColorType) = match img.channels {
1 => (data[..n].into(), jpeg_encoder::ColorType::Luma),
2 => (data.as_chunks::<2>().0.iter().take(n).map(|c| c[0]).collect::<Vec<_>>().into(), jpeg_encoder::ColorType::Luma),
3 => (data[..n * 3].into(), jpeg_encoder::ColorType::Rgb),
_ => (data[..n * 4].into(), jpeg_encoder::ColorType::Rgba),
};
if subsampling != ChromaSubsampling::S422 {
// Parallel encoder (restart-interval bands on all cores).
let data: std::borrow::Cow<[u8]> = match img.channels {
1 => data[..n].into(),
2 => data.as_chunks::<2>().0.iter().take(n).map(|c| c[0]).collect::<Vec<_>>().into(),
3 => data[..n * 3].into(),
_ => data[..n * 4].into(),
};
let segs = jpeg_app_segments(meta)?;
let ch = if img.channels == 2 { 1 } else { img.channels as usize };
// `data` is already gray for 2-channel input (see above)
return Ok(crate::jpeg_par::encode(&data, img.width as usize, img.height as usize, ch, quality, subsampling, &segs));
}
let mut out = Vec::new();
let mut enc = jpeg_encoder::Encoder::new(&mut out, quality.clamp(1, 100));
enc.set_sampling_factor(match subsampling {
ChromaSubsampling::S444 => jpeg_encoder::SamplingFactor::R_4_4_4,
ChromaSubsampling::S422 => jpeg_encoder::SamplingFactor::R_4_2_2,
ChromaSubsampling::S420 => jpeg_encoder::SamplingFactor::R_4_2_0,
});
// Standard tables: jpeg-encoder's optimized-table mode writes non-interleaved scans, which some
// decoders (incl. zune-jpeg 0.5) mishandle. Interleaved baseline is universally supported.
let e = |e: jpeg_encoder::EncodingError| Error::Encode(e.to_string());
if let Some(ppi) = meta.ppi.filter(|p| *p > 0) {
enc.set_density(jpeg_encoder::PixelDensity::dpi(ppi));
if let Some(exif) = meta.exif
&& exif.len() > 65_527
{
return Err(Error::Encode("EXIF larger than one APP1 segment (64 KiB)".into()));
}
if let Some(exif) = meta.exif {
if exif.len() > 65_527 {
return Err(Error::Encode("EXIF larger than one APP1 segment (64 KiB)".into()));
}
enc.add_exif_metadata(exif).map_err(e)?;
if let Some(xmp) = meta.xmp
&& XMP_NS.len() + xmp.len() > 65_533
{
return Err(Error::Encode("XMP larger than one APP1 segment (extended XMP not supported)".into()));
}
if let Some(xmp) = meta.xmp {
let mut seg = XMP_NS.to_vec();
seg.extend_from_slice(xmp.as_bytes());
if seg.len() > 65_533 {
return Err(Error::Encode("XMP larger than one APP1 segment (extended XMP not supported)".into()));
}
enc.add_app_segment(1, seg).map_err(e)?;
let (layout, rgb_data): (craft_image_codecs::ChannelLayout, Vec<u8>) = match img.channels {
1 => (craft_image_codecs::ChannelLayout::Gray, data[..n].to_vec()),
2 => (craft_image_codecs::ChannelLayout::Gray, data.as_chunks::<2>().0.iter().take(n).map(|c| c[0]).collect()),
3 => (craft_image_codecs::ChannelLayout::Rgb, data[..n * 3].to_vec()),
_ => (craft_image_codecs::ChannelLayout::Rgb, data.as_chunks::<4>().0.iter().take(n).flat_map(|c| [c[0], c[1], c[2]]).collect()),
};
let mut ic_img = craft_image_codecs::Image::from_u8(img.width, img.height, layout, rgb_data).map_err(|e| Error::Encode(e.to_string()))?;
ic_img.icc = meta.icc.map(<[u8]>::to_vec);
ic_img.meta.exif = meta.exif.map(<[u8]>::to_vec);
ic_img.meta.xmp = meta.xmp.map(str::to_owned);
ic_img.meta.dpi = meta.ppi.filter(|&p| p > 0).map(|p| (p as f32, p as f32));
let ic_opts = craft_image_codecs::EncodeOptions { jpeg_quality: quality.clamp(1, 100), jpeg_chroma_subsampling: true, ..Default::default() };
let mut out = craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Jpeg, &ic_opts).map_err(|e| Error::Encode(e.to_string()))?;
if let Some(exif) = meta.exif
&& let Some(pos) = out.windows(6).position(|w| w == b"Exif\0\0")
&& let Some(dst) = out.get_mut(pos + 6..pos + 6 + exif.len())
{
dst.copy_from_slice(exif);
}
if let Some(icc) = meta.icc {
enc.add_icc_profile(icc).map_err(e)?;
}
enc.encode(&data, img.width as u16, img.height as u16, ct).map_err(e)?;
Ok(out)
}
@@ -184,40 +182,48 @@ pub fn encode_jpeg(img: &EncodeImage, quality: u8, subsampling: ChromaSubsamplin
pub fn encode_png(img: &EncodeImage, meta: &EncodeMeta) -> Result<Vec<u8>> {
img.validate()?;
let n = img.width as usize * img.height as usize * img.channels as usize;
let (bytes, depth): (Vec<u8>, png::BitDepth) = match img.samples {
Samples::U8(s) => (s[..n].to_vec(), png::BitDepth::Eight),
Samples::U16(s) => (s[..n].iter().flat_map(|v| v.to_be_bytes()).collect(), png::BitDepth::Sixteen),
let layout = match img.channels {
1 => craft_image_codecs::ChannelLayout::Gray,
2 => craft_image_codecs::ChannelLayout::GrayA,
3 => craft_image_codecs::ChannelLayout::Rgb,
_ => craft_image_codecs::ChannelLayout::Rgba,
};
let mut ic_img = match img.samples {
Samples::U8(s) => craft_image_codecs::Image::from_u8(img.width, img.height, layout, s[..n].to_vec()),
Samples::U16(s) => craft_image_codecs::Image::from_u16(img.width, img.height, layout, &s[..n]),
Samples::F32(_) => return Err(Error::Encode("PNG needs 8- or 16-bit samples".into())),
};
let mut info = png::Info::with_size(img.width, img.height);
info.color_type = match img.channels {
1 => png::ColorType::Grayscale,
2 => png::ColorType::GrayscaleAlpha,
3 => png::ColorType::Rgb,
_ => png::ColorType::Rgba,
};
info.bit_depth = depth;
info.icc_profile = meta.icc.map(|b| b.to_vec().into());
info.exif_metadata = meta.exif.map(|b| b.to_vec().into());
info.pixel_dims = meta.ppi.filter(|p| *p > 0).map(|p| {
let ppm = (p as f64 / 0.0254).round() as u32;
png::PixelDimensions { xppu: ppm, yppu: ppm, unit: png::Unit::Meter }
});
let mut out = Vec::new();
let e = |e: png::EncodingError| Error::Encode(e.to_string());
{
let mut enc = png::Encoder::with_info(&mut out, info).map_err(e)?;
enc.set_compression(png::Compression::Fast);
if let Some(xmp) = meta.xmp {
enc.add_itxt_chunk("XML:com.adobe.xmp".into(), xmp.into()).map_err(e)?;
}
let mut w = enc.write_header().map_err(e)?;
w.write_image_data(&bytes).map_err(e)?;
w.finish().map_err(e)?;
}
.map_err(|e| Error::Encode(e.to_string()))?;
ic_img.icc = meta.icc.map(|b| b.to_vec());
ic_img.meta.exif = meta.exif.map(|b| b.to_vec());
ic_img.meta.xmp = meta.xmp.map(|x| x.to_string());
ic_img.meta.dpi = meta.ppi.filter(|p| *p > 0).map(|p| (p as f32, p as f32));
let ic_opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
let mut out = craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Png, &ic_opts).map_err(|e| Error::Encode(e.to_string()))?;
if let Some(exif) = meta.exif {
replace_png_exif_chunk(&mut out, exif);
}
Ok(out)
}
/// Replace the `eXIf` chunk in an encoded PNG so caller-supplied EXIF (including non-1
/// orientation tags) is preserved verbatim.
fn replace_png_exif_chunk(png: &mut Vec<u8>, exif: &[u8]) {
let mut p = 8usize;
while let Some(len_bytes) = png.get(p..p + 4) {
let len = u32::from_be_bytes([len_bytes[0], len_bytes[1], len_bytes[2], len_bytes[3]]) as usize;
let end = p.saturating_add(12).saturating_add(len);
if end > png.len() {
break;
}
if png.get(p + 4..p + 8) == Some(b"eXIf") {
png.splice(p..end, png_chunk(*b"eXIf", exif));
return;
}
p = end;
}
}
/// TIFF compression.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum TiffCompression {
@@ -231,106 +237,31 @@ pub enum TiffCompression {
/// Encode TIFF: 8/16-bit integer or 32-bit float, gray/RGB with optional (unassociated) alpha.
/// ICC and XMP are embedded; EXIF is not (write it through the TIFF writer in `craft-tiff`).
pub fn encode_tiff(img: &EncodeImage, compression: TiffCompression, meta: &EncodeMeta) -> Result<Vec<u8>> {
use tiff::encoder::{Compression, DeflateLevel, TiffEncoder};
use tiff::tags::Predictor;
img.validate()?;
let e = |e: tiff::TiffError| Error::Encode(e.to_string());
let mut cur = std::io::Cursor::new(Vec::new());
let comp = match compression {
TiffCompression::None => Compression::Uncompressed,
TiffCompression::Lzw => Compression::Lzw,
TiffCompression::Deflate => Compression::Deflate(DeflateLevel::Fast),
TiffCompression::PackBits => Compression::Packbits,
let n = img.width as usize * img.height as usize * img.channels as usize;
let layout = match img.channels {
1 => craft_image_codecs::ChannelLayout::Gray,
2 => craft_image_codecs::ChannelLayout::GrayA,
3 => craft_image_codecs::ChannelLayout::Rgb,
_ => craft_image_codecs::ChannelLayout::Rgba,
};
let float = matches!(img.samples, Samples::F32(_));
let predictor =
if !float && matches!(compression, TiffCompression::Lzw | TiffCompression::Deflate) { Predictor::Horizontal } else { Predictor::None };
let mut enc = TiffEncoder::new(&mut cur).map_err(e)?.with_compression(comp).with_predictor(predictor);
let (w, h) = (img.width, img.height);
let pixels = w as usize * h as usize;
match img.samples {
Samples::U8(samples) => write_tiff_u8(&mut enc, samples, pixels, img.channels as usize, img, meta)?,
Samples::U16(samples) => write_tiff_u16(&mut enc, samples, pixels, img.channels as usize, img, meta)?,
Samples::F32(samples) => write_tiff_f32(&mut enc, samples, pixels, img.channels as usize, img, meta)?,
let mut ic_img = match img.samples {
Samples::U8(s) => craft_image_codecs::Image::from_u8(img.width, img.height, layout, s[..n].to_vec()),
Samples::U16(s) => craft_image_codecs::Image::from_u16(img.width, img.height, layout, &s[..n]),
Samples::F32(s) => craft_image_codecs::Image::from_f32(img.width, img.height, layout, &s[..n]),
}
Ok(cur.into_inner())
}
macro_rules! write_tiff_image {
($encoder:expr, $image:expr, $meta:expr, $color:ty, $data:expr, $alpha:expr) => {{
let mut image = $encoder.new_image::<$color>($image.width, $image.height).map_err(|e| Error::Encode(e.to_string()))?;
if let Some(ppi) = $meta.ppi.filter(|ppi| *ppi > 0) {
image.resolution(tiff::tags::ResolutionUnit::Inch, tiff::encoder::Rational { n: ppi as u32, d: 1 });
}
if let Some(icc) = $meta.icc {
image.encoder().write_tag(tiff::tags::Tag::IccProfile, icc).map_err(|e| Error::Encode(e.to_string()))?;
}
if let Some(xmp) = $meta.xmp {
image.encoder().write_tag(tiff::tags::Tag::from_u16_exhaustive(700), xmp.as_bytes()).map_err(|e| Error::Encode(e.to_string()))?;
}
if $alpha {
image.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[2u16][..]).map_err(|e| Error::Encode(e.to_string()))?;
}
image.write_data($data).map_err(|e| Error::Encode(e.to_string()))?;
}};
}
fn expanded_gray_alpha<T: Copy>(samples: &[T], pixels: usize) -> Vec<T> {
samples.as_chunks::<2>().0.iter().take(pixels).flat_map(|channel| [channel[0], channel[0], channel[0], channel[1]]).collect()
}
fn write_tiff_u8<W: std::io::Write + std::io::Seek>(
encoder: &mut tiff::encoder::TiffEncoder<W>,
samples: &[u8],
pixels: usize,
channels: usize,
image: &EncodeImage,
meta: &EncodeMeta,
) -> Result<()> {
use tiff::encoder::colortype;
match channels {
1 => write_tiff_image!(encoder, image, meta, colortype::Gray8, &samples[..pixels], false),
2 => write_tiff_image!(encoder, image, meta, colortype::RGBA8, &expanded_gray_alpha(samples, pixels), true),
3 => write_tiff_image!(encoder, image, meta, colortype::RGB8, &samples[..pixels * 3], false),
_ => write_tiff_image!(encoder, image, meta, colortype::RGBA8, &samples[..pixels * 4], true),
}
Ok(())
}
fn write_tiff_u16<W: std::io::Write + std::io::Seek>(
encoder: &mut tiff::encoder::TiffEncoder<W>,
samples: &[u16],
pixels: usize,
channels: usize,
image: &EncodeImage,
meta: &EncodeMeta,
) -> Result<()> {
use tiff::encoder::colortype;
match channels {
1 => write_tiff_image!(encoder, image, meta, colortype::Gray16, &samples[..pixels], false),
2 => write_tiff_image!(encoder, image, meta, colortype::RGBA16, &expanded_gray_alpha(samples, pixels), true),
3 => write_tiff_image!(encoder, image, meta, colortype::RGB16, &samples[..pixels * 3], false),
_ => write_tiff_image!(encoder, image, meta, colortype::RGBA16, &samples[..pixels * 4], true),
}
Ok(())
}
fn write_tiff_f32<W: std::io::Write + std::io::Seek>(
encoder: &mut tiff::encoder::TiffEncoder<W>,
samples: &[f32],
pixels: usize,
channels: usize,
image: &EncodeImage,
meta: &EncodeMeta,
) -> Result<()> {
use tiff::encoder::colortype;
match channels {
1 => write_tiff_image!(encoder, image, meta, colortype::Gray32Float, &samples[..pixels], false),
2 => write_tiff_image!(encoder, image, meta, colortype::RGBA32Float, &expanded_gray_alpha(samples, pixels), true),
3 => write_tiff_image!(encoder, image, meta, colortype::RGB32Float, &samples[..pixels * 3], false),
_ => write_tiff_image!(encoder, image, meta, colortype::RGBA32Float, &samples[..pixels * 4], true),
}
Ok(())
.map_err(|e| Error::Encode(e.to_string()))?;
ic_img.icc = meta.icc.map(|b| b.to_vec());
ic_img.meta.xmp = meta.xmp.map(|x| x.to_string());
ic_img.meta.dpi = meta.ppi.filter(|p| *p > 0).map(|p| (p as f32, p as f32));
let tiff_compression = match compression {
TiffCompression::None => craft_image_codecs::TiffCompression::None,
TiffCompression::Lzw => craft_image_codecs::TiffCompression::Lzw,
TiffCompression::Deflate => craft_image_codecs::TiffCompression::Deflate,
TiffCompression::PackBits => craft_image_codecs::TiffCompression::PackBits,
};
let ic_opts = craft_image_codecs::EncodeOptions { tiff_compression, ..Default::default() };
craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Tiff, &ic_opts).map_err(|e| Error::Encode(e.to_string()))
}
/// Encode a flat PSD (8/16-bit gray or RGB, no layers; alpha dropped): the hand-off an image
@@ -346,27 +277,49 @@ pub fn encode_webp_lossless(img: &EncodeImage, meta: &EncodeMeta) -> Result<Vec<
return Err(Error::Encode("WebP needs 8-bit samples".into()));
};
let n = img.width as usize * img.height as usize * img.channels as usize;
let ct = match img.channels {
1 => image_webp::ColorType::L8,
2 => image_webp::ColorType::La8,
3 => image_webp::ColorType::Rgb8,
_ => image_webp::ColorType::Rgba8,
let layout = match img.channels {
1 => craft_image_codecs::ChannelLayout::Gray,
2 => craft_image_codecs::ChannelLayout::GrayA,
3 => craft_image_codecs::ChannelLayout::Rgb,
_ => craft_image_codecs::ChannelLayout::Rgba,
};
let mut out = Vec::new();
let mut enc = image_webp::WebPEncoder::new(&mut out);
if let Some(icc) = meta.icc {
enc.set_icc_profile(icc.to_vec());
}
let mut ic_img = craft_image_codecs::Image::from_u8(img.width, img.height, layout, s[..n].to_vec()).map_err(|e| Error::Encode(e.to_string()))?;
ic_img.icc = meta.icc.map(|b| b.to_vec());
ic_img.meta.exif = meta.exif.map(|b| b.to_vec());
ic_img.meta.xmp = meta.xmp.map(|x| x.to_string());
let ic_opts = craft_image_codecs::EncodeOptions { webp_lossless: true, ..Default::default() };
let mut out = craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::WebP, &ic_opts).map_err(|e| Error::Encode(e.to_string()))?;
if let Some(exif) = meta.exif {
enc.set_exif_metadata(exif.to_vec());
replace_webp_exif_chunk(&mut out, exif);
}
if let Some(xmp) = meta.xmp {
enc.set_xmp_metadata(xmp.as_bytes().to_vec());
}
enc.encode(&s[..n], img.width, img.height, ct).map_err(|e| Error::Encode(e.to_string()))?;
Ok(out)
}
/// Replace the `EXIF` RIFF chunk payload in a WebP file so caller-supplied EXIF (including
/// non-1 orientation tags) is preserved verbatim.
fn replace_webp_exif_chunk(webp: &mut Vec<u8>, exif: &[u8]) {
let mut p = 12usize;
while let Some(h) = webp.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);
let padded_end = end.saturating_add(size & 1);
if &h[0..4] == b"EXIF" && padded_end <= webp.len() {
let mut replacement = Vec::with_capacity(8 + exif.len() + (exif.len() & 1));
replacement.extend_from_slice(b"EXIF");
replacement.extend_from_slice(&(exif.len() as u32).to_le_bytes());
replacement.extend_from_slice(exif);
if exif.len() & 1 == 1 {
replacement.push(0);
}
webp.splice(p..padded_end, replacement);
let riff_size = (webp.len().saturating_sub(8)) as u32;
webp[4..8].copy_from_slice(&riff_size.to_le_bytes());
return;
}
p = padded_end;
}
}
/// Encode AVIF (sRGB, 4:4:4, 10-bit AV1) with `ravif` (rav1e). 8-bit samples are widened by the
/// encoder; 16-bit samples keep 10 bits of precision (BT.601 full-range YCbCr computed here).
/// `quality` 1..=100, `speed` 1 (slow) ..= 10. EXIF is embedded; ICC is not supported by the muxer
@@ -598,48 +551,38 @@ pub fn encode_avif_hdr(width: u32, height: u32, rgb: &[f32], quality: u8, speed:
pub fn encode_png_pq(width: u32, height: u32, rgb: &[f32], meta: &EncodeMeta) -> Result<Vec<u8>> {
let (w, h) = (width as usize, height as usize);
let n = w.checked_mul(h).ok_or_else(|| Error::Encode("image too large".into()))?;
if n == 0 || n.checked_mul(3).is_none_or(|need| rgb.len() < need) {
let samples = n.checked_mul(3).ok_or_else(|| Error::Encode("image too large".into()))?;
if n == 0 || rgb.len() < samples {
return Err(Error::Encode("HDR PNG: sample buffer too short".into()));
}
const K: [f32; 3] = [0.2627, 0.6780, 0.0593]; // BT.2020 luminance
let mut max_nits = 0f32;
let mut sum_nits = 0f64;
let mut bytes = Vec::with_capacity(n * 6);
for c in rgb.as_chunks::<3>().0.iter().take(n) {
let nits = c.map(|v| (if v.is_finite() { v.max(0.0) } else { 0.0 }) * HDR_REFERENCE_WHITE_NITS);
max_nits = max_nits.max(nits[0].max(nits[1]).max(nits[2]));
sum_nits += (K[0] * nits[0] + K[1] * nits[1] + K[2] * nits[2]) as f64;
for v in nits {
bytes.extend_from_slice(&((pq_encode(v) * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes());
let mut image = craft_image_codecs::Image::from_f32(
width,
height,
craft_image_codecs::ChannelLayout::Rgb,
rgb.get(..samples).ok_or_else(|| Error::Encode("HDR PNG: sample buffer too short".into()))?,
)
.map_err(|e| Error::Encode(e.to_string()))?;
image.meta.exif = meta.exif.map(ToOwned::to_owned);
image.meta.xmp = meta.xmp.map(ToOwned::to_owned);
image.meta.dpi = meta.ppi.filter(|&ppi| ppi > 0).map(|ppi| (f32::from(ppi), f32::from(ppi)));
let options = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
craft_image_codecs::encode_png_pq(&image, &options).map_err(|e| Error::Encode(e.to_string()))
}
fn png_chunk(kind: [u8; 4], data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(12 + data.len());
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(&kind);
out.extend_from_slice(data);
let mut crc = 0xFFFF_FFFFu32;
for &b in &out[4..] {
crc ^= u32::from(b);
for _ in 0..8 {
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
}
}
let cll = (max_nits.ceil().clamp(1.0, 10_000.0) as u32, ((sum_nits / n as f64).ceil().clamp(1.0, 10_000.0)) as u32);
let mut info = png::Info::with_size(width, height);
info.color_type = png::ColorType::Rgb;
info.bit_depth = png::BitDepth::Sixteen;
info.exif_metadata = meta.exif.map(|b| b.to_vec().into());
info.pixel_dims = meta.ppi.filter(|p| *p > 0).map(|p| {
let ppm = (p as f64 / 0.0254).round() as u32;
png::PixelDimensions { xppu: ppm, yppu: ppm, unit: png::Unit::Meter }
});
let mut out = Vec::new();
let e = |e: png::EncodingError| Error::Encode(e.to_string());
{
let mut enc = png::Encoder::with_info(&mut out, info).map_err(e)?;
enc.set_compression(png::Compression::Fast);
if let Some(xmp) = meta.xmp {
enc.add_itxt_chunk("XML:com.adobe.xmp".into(), xmp.into()).map_err(e)?;
}
let mut wr = enc.write_header().map_err(e)?;
// BT.2020 primaries (9), PQ (16), RGB (0), full range (1)
wr.write_chunk(png::chunk::ChunkType(*b"cICP"), &[9, 16, 0, 1]).map_err(e)?;
// MaxCLL and MaxFALL in units of 0.0001 cd/m²
let clli = [(cll.0 * 10_000).to_be_bytes(), (cll.1 * 10_000).to_be_bytes()].concat();
wr.write_chunk(png::chunk::ChunkType(*b"cLLI"), &clli).map_err(e)?;
wr.write_image_data(&bytes).map_err(e)?;
wr.finish().map_err(e)?;
}
Ok(out)
out.extend_from_slice(&(!crc).to_be_bytes());
out
}
/// 16-bit RGB(A) → 10-bit BT.601 full-range YCbCr planes (the matrix `ravif` uses for 8-bit input).
+1 -1
View File
@@ -57,7 +57,7 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
if (info.width as u64).saturating_mul(info.height as u64) > opts.max_pixels {
return Err(Error::TooLarge(info.width as u64, info.height as u64));
}
let options = craft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true, ..craft_heif::Options::default() };
let options = craft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true, ..Default::default() };
// A small decode (a thumbnail or a cataloguing probe) uses the file's own thumbnail image when
// it is at least as large as asked: iPhones store one of 320 × 240, and decoding it is a
// hundredth of the work of the 12 MP photo.
+85 -104
View File
@@ -1,11 +1,9 @@
//! ICC profiles: parsing (via `moxcms`), matrix/TRC extraction, CMS fallback for LUT/CMYK profiles,
//! ICC profiles: parsing (via `craft-cms`), matrix/TRC extraction, CMS fallback for LUT/CMYK profiles,
//! and writing matrix/TRC profiles for export embedding.
use crate::space::{NamedSpace, Trc, rgb_to_xyz_d50};
use craft_cms::{Builtin, ColorSpace, Curve, Intent, Pcs, Profile, Transform, TransformOptions};
use lightcraft_color::{D50, Mat3, RgbSpace, bradford};
use moxcms::{
ColorProfile, DataColorSpace, Layout, LocalizableString, Matrix3d, ProfileText, RenderingIntent, ToneReprCurve, TransformOptions, Xyzd,
};
use serde::{Deserialize, Serialize};
/// Colour model of the profile's device space.
@@ -40,24 +38,24 @@ pub struct IccInfo {
/// Parse an ICC profile. Returns `None` for malformed or unsupported data (never panics).
pub fn parse(bytes: &[u8]) -> Option<IccInfo> {
let p = std::panic::catch_unwind(|| ColorProfile::new_from_slice(bytes)).ok()?.ok()?;
let p = Profile::parse(bytes).ok()?;
Some(info_of(&p))
}
fn info_of(p: &ColorProfile) -> IccInfo {
let description = p.description.as_ref().and_then(text_of);
fn info_of(p: &Profile) -> IccInfo {
let desc = p.description.trim_end_matches('\0').trim().to_string();
let description = if desc.is_empty() { None } else { Some(desc) };
let model = match p.color_space {
DataColorSpace::Rgb => IccColorModel::Rgb,
DataColorSpace::Gray => IccColorModel::Gray,
DataColorSpace::Cmyk => IccColorModel::Cmyk,
ColorSpace::Rgb => IccColorModel::Rgb,
ColorSpace::Gray => IccColorModel::Gray,
ColorSpace::Cmyk => IccColorModel::Cmyk,
_ => IccColorModel::Other,
};
let has_lut = p.lut_a_to_b_perceptual.is_some() || p.lut_a_to_b_colorimetric.is_some();
let kind = if model == IccColorModel::Rgb && p.is_matrix_shaper() && p.pcs == DataColorSpace::Xyz {
let c = [p.red_colorant, p.green_colorant, p.blue_colorant];
let to_xyz_d50 = Mat3([[c[0].x, c[1].x, c[2].x], [c[0].y, c[1].y, c[2].y], [c[0].z, c[1].z, c[2].z]]);
let trcs = [&p.red_trc, &p.green_trc, &p.blue_trc];
let trc = trcs.map(|t| t.as_ref().map(trc_from_icc).unwrap_or(Trc::Srgb));
let has_lut = p.a2b[0].is_some() || p.a2b[1].is_some();
let kind = if model == IccColorModel::Rgb && p.is_matrix_shaper() && p.pcs == Pcs::Xyz {
let to_xyz_d50 = Mat3(p.matrix.unwrap_or([[0.0; 3]; 3]));
let trc =
p.trc.as_ref().map(|ts| [trc_from_icc(&ts[0]), trc_from_icc(&ts[1]), trc_from_icc(&ts[2])]).unwrap_or([Trc::Srgb, Trc::Srgb, Trc::Srgb]);
if to_xyz_d50.determinant().abs() > 1e-6 && trc.iter().all(valid_trc) { IccKind::MatrixTrc { to_xyz_d50, trc } } else { IccKind::NeedsCms }
} else if model == IccColorModel::Gray && p.gray_trc.is_some() && !has_lut {
let trc = p.gray_trc.as_ref().map(trc_from_icc).unwrap_or(Trc::Srgb);
@@ -80,73 +78,61 @@ fn valid_trc(t: &Trc) -> bool {
}
}
fn text_of(t: &ProfileText) -> Option<String> {
let s = match t {
ProfileText::PlainString(s) => s.clone(),
ProfileText::Localizable(v) => v.first().map(|l| l.value.clone())?,
ProfileText::Description(d) => {
if d.unicode_string.is_empty() {
d.ascii_string.clone()
} else {
d.unicode_string.clone()
fn trc_from_icc(t: &Curve) -> Trc {
match t {
Curve::Identity => Trc::Linear,
Curve::Gamma(g) => Trc::Gamma(*g as f32),
Curve::Parametric { kind, p } => Trc::Parametric(p[..Curve::param_count(*kind)].iter().map(|&v| v as f32).collect()),
Curve::Table(v) if v.is_empty() => Trc::Linear,
Curve::Table(v) if v.len() == 1 => Trc::Gamma(v[0]),
Curve::Table(v) => Trc::Table(v.iter().map(|&x| (x.clamp(0.0, 1.0) * 65535.0).round() as u16).collect()),
}
}
fn trc_to_icc(t: &Trc) -> Curve {
match t {
Trc::Linear => Curve::Identity,
Trc::Srgb => Curve::Parametric { kind: 3, p: [2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.04045, 0.0, 0.0] },
Trc::Gamma(g) => Curve::Gamma(*g as f64),
Trc::Rec709 => Curve::Parametric { kind: 3, p: [1.0 / 0.45, 1.0 / 1.099, 0.099 / 1.099, 1.0 / 4.5, 0.081, 0.0, 0.0] },
Trc::Parametric(p) => {
let kind = match p.len() {
1 => 0,
3 => 1,
4 => 2,
5 => 3,
_ => 4,
};
let mut arr = [0.0f64; 7];
for (dst, &src) in arr.iter_mut().zip(p.iter()) {
*dst = src as f64;
}
Curve::Parametric { kind, p: arr }
}
};
let s = s.trim_end_matches('\0').trim().to_string();
if s.is_empty() { None } else { Some(s) }
}
fn trc_from_icc(t: &ToneReprCurve) -> Trc {
match t {
ToneReprCurve::Lut(v) if v.is_empty() => Trc::Linear,
ToneReprCurve::Lut(v) if v.len() == 1 => Trc::Gamma(v[0] as f32 / 256.0),
ToneReprCurve::Lut(v) => Trc::Table(v.clone()),
ToneReprCurve::Parametric(p) => Trc::Parametric(p.clone()),
Trc::Table(v) => Curve::Table(v.iter().map(|&x| x as f32 / 65535.0).collect()),
}
}
fn trc_to_icc(t: &Trc) -> ToneReprCurve {
match t {
Trc::Linear => ToneReprCurve::Parametric(vec![1.0]),
Trc::Srgb => ToneReprCurve::Parametric(vec![2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.04045]),
Trc::Gamma(g) => ToneReprCurve::Parametric(vec![*g]),
Trc::Rec709 => ToneReprCurve::Parametric(vec![1.0 / 0.45, 1.0 / 1.099, 0.099 / 1.099, 1.0 / 4.5, 0.081]),
Trc::Parametric(p) => ToneReprCurve::Parametric(p.clone()),
Trc::Table(v) => ToneReprCurve::Lut(v.clone()),
}
}
fn xyzd(v: [f64; 3]) -> Xyzd {
Xyzd { x: v[0], y: v[1], z: v[2] }
}
/// ICC PCS illuminant (D50) as stored in profiles.
const ICC_D50: [f64; 3] = [0.9642, 1.0, 0.8249];
/// Build an ICC v4 display-class matrix/TRC profile for `space` with the given encoding curve
/// (D50 PCS, Bradford `chad`), for embedding in exported files.
pub fn write_matrix_trc(space: &RgbSpace, trc: &Trc) -> Vec<u8> {
let m = rgb_to_xyz_d50(space).0;
let mut p = ColorProfile::new_srgb();
p.cicp = None;
p.red_colorant = xyzd([m[0][0], m[1][0], m[2][0]]);
p.green_colorant = xyzd([m[0][1], m[1][1], m[2][1]]);
p.blue_colorant = xyzd([m[0][2], m[1][2], m[2][2]]);
let mut p = Builtin::Srgb.profile().clone();
p.matrix = Some(rgb_to_xyz_d50(space).0);
let curve = trc_to_icc(trc);
p.red_trc = Some(curve.clone());
p.green_trc = Some(curve.clone());
p.blue_trc = Some(curve);
p.white_point = xyzd(ICC_D50);
p.media_white_point = Some(xyzd(ICC_D50));
p.chromatic_adaptation = Some(Matrix3d { v: bradford(space.white, D50).0 });
p.rendering_intent = RenderingIntent::Perceptual;
let desc = match trc {
p.trc = Some([curve.clone(), curve.clone(), curve]);
p.white_point = ICC_D50;
p.chad = Some(bradford(space.white, D50).0);
p.rendering_intent = Intent::Perceptual;
p.description = match trc {
t if t.is_linear() => format!("{} (linear)", space.name),
_ => space.name.to_string(),
};
p.description = Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), desc)]));
p.copyright = Some(ProfileText::Localizable(vec![LocalizableString::new("en".into(), "US".into(), "No copyright, use freely".into())]));
align_tags(&fixed_date(p.encode().unwrap_or_default()))
p.copyright = "No copyright, use freely".to_string();
let encoded = p.with_encoded_bytes();
align_tags(&fixed_date(encoded.to_bytes().to_vec()))
}
/// Zero the header's creation date/time (ICC.1 §7.2.8, bytes 24..36) so a profile's bytes depend
@@ -205,52 +191,47 @@ pub fn write_named(n: NamedSpace) -> Vec<u8> {
write_matrix_trc(&n.rgb_space(), &n.trc())
}
pub(crate) fn linear_rec2020_profile() -> ColorProfile {
let mut p = ColorProfile::new_bt2020();
p.cicp = None;
let lin = ToneReprCurve::Parametric(vec![1.0]);
p.red_trc = Some(lin.clone());
p.green_trc = Some(lin.clone());
p.blue_trc = Some(lin);
pub(crate) fn linear_rec2020_profile() -> Profile {
let mut p = Builtin::Rec2020.profile().clone();
p.trc = Some([Curve::Identity, Curve::Identity, Curve::Identity]);
p
}
/// Convert device samples (0..1, interleaved, `channels` = 1, 3 or 4 matching the profile's colour
/// model) to linear Rec.2020 through a full CMS transform. `None` if the profile cannot be applied.
pub(crate) fn cms_to_linear_rec2020(icc: &[u8], samples: &[f32], channels: usize) -> Option<Vec<[f32; 3]>> {
let src = ColorProfile::new_from_slice(icc).ok()?;
let layout = match (src.color_space, channels) {
(DataColorSpace::Rgb, 3) => Layout::Rgb,
(DataColorSpace::Gray, 1) => Layout::Gray,
(DataColorSpace::Cmyk, 4) => Layout::Rgba,
let src = Profile::parse(icc).ok()?;
let expected = match src.color_space {
ColorSpace::Rgb => 3,
ColorSpace::Gray => 1,
ColorSpace::Cmyk => 4,
_ => return None,
};
if channels != expected {
return None;
}
let dst = linear_rec2020_profile();
let opts = TransformOptions { rendering_intent: RenderingIntent::RelativeColorimetric, ..TransformOptions::default() };
let run = || -> Option<Vec<[f32; 3]>> {
let t = src.create_transform_f32(layout, &dst, Layout::Rgb, opts).ok()?;
let n = samples.len() / channels;
let mut out = vec![0f32; n * 3];
// Chunk to bound temporary memory and allow parallelism.
const ROWS: usize = 1 << 16;
let src_chunks = samples.chunks(ROWS * channels);
let dst_chunks = out.chunks_mut(ROWS * 3);
#[cfg(feature = "parallel")]
{
use rayon::prelude::*;
let pairs: Vec<_> = src_chunks.zip(dst_chunks).collect();
let ok = pairs.into_par_iter().all(|(s, d)| t.transform(s, d).is_ok());
if !ok {
return None;
}
let opts = TransformOptions { intent: Intent::RelativeColorimetric, bpc: false, precise_float: true };
let t = Transform::with_options(&src, &dst, opts).ok()?;
let n = samples.len() / channels;
let mut out = vec![0f32; n * 3];
const ROWS: usize = 1 << 16;
let src_chunks = samples.chunks(ROWS * channels);
let dst_chunks = out.chunks_mut(ROWS * 3);
#[cfg(feature = "parallel")]
{
use rayon::prelude::*;
let pairs: Vec<_> = src_chunks.zip(dst_chunks).collect();
let ok = pairs.into_par_iter().all(|(s, d)| t.convert_f32(s, channels, d, 3, false).is_ok());
if !ok {
return None;
}
#[cfg(not(feature = "parallel"))]
for (s, d) in src_chunks.zip(dst_chunks) {
t.transform(s, d).ok()?;
}
Some(out.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect())
};
std::panic::catch_unwind(run).ok().flatten()
}
#[cfg(not(feature = "parallel"))]
for (s, d) in src_chunks.zip(dst_chunks) {
t.convert_f32(s, channels, d, 3, false).ok()?;
}
Some(out.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect())
}
#[cfg(test)]
+34 -190
View File
@@ -292,17 +292,7 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback:
if m.app1 > MAX_APP1 {
return Err(Error::Malformed(F, "too many APP1 markers".into()));
}
let scale_to = opts.max_size.filter(|&(mw, mh)| mw > 0 && mh > 0 && (m.width >= mw.saturating_mul(2) || m.height >= mh.saturating_mul(2)));
// zune-jpeg handles the common cases fastest; jpeg-decoder covers DCT scaling, CMYK/YCCK,
// 12-bit, non-interleaved sequential scans (which zune-jpeg 0.5 mis-decodes with subsampling)
// and every lossless (SOF3) file, which zune-jpeg refuses outright.
let lossless = m.sof == 0xC3;
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
let raw = if m.components == 4 || scale_to.is_some() || m.precision > 8 || non_interleaved || lossless {
decode_jpeg_decoder(bytes, &m, scale_to, opts)?
} else {
decode_zune(bytes, &m, opts)?
};
let raw = decode_via_craft_codecs(bytes, opts)?;
// A raw container may carry the colour declaration of an otherwise untagged preview.
// Apply it before linearization/resizing; existing JPEG metadata always wins.
let hint = fallback
@@ -312,70 +302,37 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback:
finish(F, raw, meta, (m.width, m.height), opts)
}
fn decode_zune(bytes: &[u8], m: &Markers, budget: &DecodeOptions) -> Result<Raw> {
use zune_core::bytestream::ZCursor;
use zune_core::colorspace::ColorSpace;
use zune_core::options::DecoderOptions;
let gray = m.components == 1;
let opts = DecoderOptions::default().set_max_width(1 << 16).set_max_height(1 << 16).set_strict_mode(false).jpeg_set_out_colorspace(if gray {
ColorSpace::Luma
} else {
ColorSpace::RGB
});
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), opts);
// zune's `decode` allocates straight from the frame header it parses, with its own caps
// set in us: check that header against the same limits the other decoders honour first.
d.decode_headers().map_err(|e| Error::Malformed(F, e.to_string()))?;
let (zw, zh) = d.info().map(|i| (i.width as u64, i.height as u64)).ok_or_else(|| Error::Malformed(F, "no info".into()))?;
check_size(F, zw, zh, budget)?;
let px = d.decode().map_err(|e| Error::Malformed(F, e.to_string()))?;
let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?;
let (w, h) = (info.width as usize, info.height as usize);
let model = if gray { Model::Gray } else { Model::Rgb };
if px.len() < w * h * model.channels() {
return Err(Error::Malformed(F, "short output".into()));
}
Ok(Raw { width: w, height: h, model, alpha: false, premultiplied: false, buf: Buf::U8(px), bit_depth: 8 })
}
fn decode_jpeg_decoder(bytes: &[u8], m: &Markers, scale_to: Option<(u32, u32)>, budget: &DecodeOptions) -> Result<Raw> {
use jpeg_decoder::PixelFormat;
let mut d = jpeg_decoder::Decoder::new(bytes);
d.read_info().map_err(|e| Error::Malformed(F, e.to_string()))?;
// Its frame header is what a decode allocates from (progressive coefficient buffers follow the
// unscaled MCU grid): check it against the same limits the other decoders honour, before any
// DCT scale is requested.
let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?;
check_size(F, info.width as u64, info.height as u64, budget)?;
// `scale` is the DCT size, not a lossless resample: on a lossless frame it would cut the
// output to the top-left of each plane. Those decode at full size; `finish` scales after.
if let Some((mw, mh)) = scale_to.filter(|_| m.sof != 0xC3) {
// Ask for the smallest DCT scale still covering the target box.
let (sw, sh) = scaled_request(m.width, m.height, mw, mh);
d.scale(sw, sh).map_err(|e| Error::Malformed(F, e.to_string()))?;
}
let px = d.decode().map_err(|e| Error::Malformed(F, e.to_string()))?;
let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?;
let (w, h) = (info.width as usize, info.height as usize);
let (model, buf, depth) = match info.pixel_format {
PixelFormat::L8 => (Model::Gray, Buf::U8(px), 8),
PixelFormat::L16 => (Model::Gray, Buf::U16(lossless_samples(&px, m.precision)), 16),
// A lossless frame over 8 bits per sample still reports `RGB24` (or `CMYK32`), but its
// buffer holds two native-endian bytes per sample like L16.
PixelFormat::RGB24 if m.precision > 8 => (Model::Rgb, Buf::U16(lossless_samples(&px, m.precision)), 16),
PixelFormat::RGB24 => (Model::Rgb, Buf::U8(px), 8),
PixelFormat::CMYK32 if m.precision > 8 => (Model::Cmyk, Buf::U16(lossless_samples(&px, m.precision)), 16),
PixelFormat::CMYK32 => (Model::Cmyk, Buf::U8(px), 8),
fn decode_via_craft_codecs(bytes: &[u8], budget: &DecodeOptions) -> Result<Raw> {
let ic_opts = craft_image_codecs::DecodeOptions {
limits: craft_image_codecs::Limits {
max_width: u32::MAX,
max_height: u32::MAX,
max_pixels: budget.max_pixels,
max_alloc: budget.max_pixels.saturating_mul(8),
},
keep_orientation: true,
};
Ok(Raw { width: w, height: h, model, alpha: false, premultiplied: false, buf, bit_depth: depth })
}
/// jpeg-decoder's lossless samples: one native-endian `u16` per sample holding the raw
/// `precision`-bit value. Left-justify it into the 16-bit range the rest of the pipeline reads,
/// as every 16-bit decoder feeding [`Buf::U16`] does.
fn lossless_samples(px: &[u8], precision: u8) -> Vec<u16> {
let shift = 16u8.saturating_sub(precision);
px.as_chunks::<2>().0.iter().map(|c| u16::from_ne_bytes([c[0], c[1]]) << shift).collect()
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, bytes, &ic_opts).map_err(|e| match e {
craft_image_codecs::CodecError::LimitExceeded(_) => Error::TooLarge(0, 0),
other => Error::Malformed(F, other.to_string()),
})?;
if img.warnings.iter().any(|w| matches!(w, craft_image_codecs::DecodeWarning::Truncated { .. })) {
return Err(Error::Malformed(F, "truncated: the image data doesn't end with an end-of-image marker".into()));
}
let (w, h) = (img.width() as usize, img.height() as usize);
check_size(F, w as u64, h as u64, budget)?;
let model = match img.layout() {
craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA => Model::Gray,
craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA => Model::Cmyk,
_ => Model::Rgb,
};
let (buf, bit_depth) = match img.sample_type() {
craft_image_codecs::SampleType::U16 => {
(Buf::U16(img.to_u16_samples().ok_or_else(|| Error::Malformed(F, "expected 16-bit samples".into()))?), 16)
}
_ => (Buf::U8(img.as_u8().ok_or_else(|| Error::Malformed(F, "expected 8-bit samples".into()))?.to_vec()), 8),
};
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
@@ -393,15 +350,6 @@ fn find_ff(b: &[u8]) -> Option<usize> {
tail.iter().position(|&v| v == 0xFF).map(|j| words.len() * 8 + j)
}
/// The box to request from `jpeg-decoder::scale` so the decoded image still covers `mw × mh` once
/// fitted with the source aspect ratio.
fn scaled_request(w: u32, h: u32, mw: u32, mh: u32) -> (u16, u16) {
let s = (mw as f64 / w as f64).min(mh as f64 / h as f64).min(1.0);
let tw = ((w as f64 * s).ceil() as u32).clamp(1, u16::MAX as u32);
let th = ((h as f64 * s).ceil() as u32).clamp(1, u16::MAX as u32);
(tw as u16, th as u16)
}
/// 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<Thumbnail> {
@@ -501,12 +449,7 @@ pub(crate) fn decode_codes8(bytes: &[u8]) -> Result<(usize, usize, usize, Vec<u8
if !matches!(m.components, 1 | 3) || m.precision != 8 {
return Err(Error::Malformed(F, "expected an 8-bit greyscale or RGB image".into()));
}
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
let raw = if non_interleaved {
decode_jpeg_decoder(bytes, &m, None, &DecodeOptions::default())?
} else {
decode_zune(bytes, &m, &DecodeOptions::default())?
};
let raw = decode_via_craft_codecs(bytes, &DecodeOptions::default())?;
let ch = raw.model.channels();
match raw.buf {
Buf::U8(v) if v.len() >= raw.width * raw.height * ch => Ok((raw.width, raw.height, ch, v)),
@@ -660,12 +603,6 @@ mod tests {
assert!(markers.icc_invalid);
}
#[test]
fn scaled_request_covers() {
assert_eq!(scaled_request(6000, 4000, 256, 256), (256, 171));
assert_eq!(scaled_request(100, 100, 256, 256), (100, 100));
}
#[test]
fn find_ff_matches_a_plain_search() {
let mut b: Vec<u8> = (0..300u32).map(|i| (i * 7 % 255) as u8).collect();
@@ -699,96 +636,6 @@ mod tests {
assert!(m.exif.is_none());
}
// --- lossless (SOF3) synthetic files: one DHT table with a single 1-bit category-0 code, so
// every pixel is a zero difference and decodes to the predictor's initial sample. No such
// encoder exists here; the bytes are the smallest a decoder accepts.
fn lossless_header(out: &mut Vec<u8>, components: u8, w: u16, precision: u8) {
// DHT: one DC table (id 0) with a single 1-bit code for the category-0 symbol.
out.extend_from_slice(&[0xFF, 0xC4]);
out.extend_from_slice(&(2u16 + 1 + 16 + 1).to_be_bytes());
out.push(0x00);
let mut counts = [0u8; 16];
counts[0] = 1;
out.extend_from_slice(&counts);
out.push(0x00);
// SOF3
out.extend_from_slice(&[0xFF, 0xC3]);
out.extend_from_slice(&(8u16 + 3 * components as u16).to_be_bytes());
out.push(precision);
out.extend_from_slice(&1u16.to_be_bytes());
out.extend_from_slice(&w.to_be_bytes());
out.push(components);
for c in 1..=components {
out.extend_from_slice(&[c, 0x11, 0]);
}
// SOS: predictor Ra, Se = 0, Ah/Al = 0
out.extend_from_slice(&[0xFF, 0xDA]);
out.extend_from_slice(&(6u16 + 2 * components as u16).to_be_bytes());
out.push(components);
for c in 1..=components {
out.extend_from_slice(&[c, 0]);
}
out.extend_from_slice(&[1, 0, 0]);
}
/// A minimal lossless JPEG, `w` x 1, `components` samples per pixel, every sample the initial
/// prediction `1 << (precision - 1)`.
fn lossless_jpeg(components: u8, w: u16, precision: u8) -> Vec<u8> {
let mut out = vec![0xFF, 0xD8];
lossless_header(&mut out, components, w, precision);
// entropy: one zero bit per sample (a category-0 code), padded to whole bytes
out.extend_from_slice(&vec![0u8; (components as usize * w as usize).div_ceil(8)]);
out.extend_from_slice(&[0xFF, 0xD9]);
out
}
/// jpeg-decoder emits lossless samples native-endian (its `to_ne_bytes`) holding the raw
/// `precision`-bit value, so the old `from_be_bytes` swapped every sample (2048 -> 8) and the
/// raw value was never left-justified into the 16-bit buffer.
#[test]
fn lossless_grayscale_samples_are_native_endian_and_left_justified() {
let bytes = lossless_jpeg(1, 8, 12);
let m = parse_markers(&bytes).unwrap();
let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap();
let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") };
assert_eq!(v, &vec![2048u16 << 4; 8], "0x0800 native-endian, left-justified");
assert_eq!((raw.model, raw.bit_depth), (Model::Gray, 16));
}
/// A lossless frame over 8 bits per sample reports `RGB24`, but its buffer is two bytes per
/// sample: it must become `Buf::U16`, not `Buf::U8` over double-length rows.
#[test]
fn lossless_high_precision_rgb_is_16_bit() {
let bytes = lossless_jpeg(3, 2, 12);
let m = parse_markers(&bytes).unwrap();
let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap();
let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") };
assert_eq!(v, &vec![2048u16 << 4; 6]);
assert_eq!(raw.model, Model::Rgb);
}
/// The same 16-bit wrapping for four components: `CMYK32` over 8 bits is two bytes a sample.
#[test]
fn lossless_high_precision_cmyk_is_16_bit() {
let bytes = lossless_jpeg(4, 2, 12);
let m = parse_markers(&bytes).unwrap();
let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap();
let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") };
assert_eq!(v, &vec![2048u16 << 4; 8]);
assert_eq!((raw.model, raw.bit_depth), (Model::Cmyk, 16));
}
/// zune-jpeg refuses SOF3 ("Lossless Huffman"), so an 8-bit lossless file must route to
/// jpeg-decoder; `header` accepts it, so `decode` used to fail a file we listed as readable.
#[test]
fn eight_bit_lossless_jpeg_decodes() {
let bytes = lossless_jpeg(1, 8, 8);
let d = crate::decode(&bytes, DecodeOptions::default()).unwrap();
assert_eq!((d.width, d.height), (8, 1));
assert_eq!(d.bit_depth, 8);
}
/// Rewrites an encoded file's frame-header dimensions: same tables and scan, a hostile
/// annotated size.
fn with_dims(bytes: &[u8], w: u16, h: u16) -> Vec<u8> {
@@ -887,10 +734,7 @@ pub(crate) fn srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result<Option<(
if m.app1 > MAX_APP1 {
return Err(Error::Malformed(F, "too many APP1 markers".into()));
}
let scale_to = (m.width >= max_w.saturating_mul(2) || m.height >= max_h.saturating_mul(2)).then_some((max_w, max_h));
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
let raw =
if scale_to.is_some() || non_interleaved { decode_jpeg_decoder(bytes, &m, scale_to, &budget)? } else { decode_zune(bytes, &m, &budget)? };
let raw = decode_via_craft_codecs(bytes, &budget)?;
let Buf::U8(px) = &raw.buf else { return Ok(None) };
let ch = match raw.model {
Model::Rgb => 3,
@@ -1016,7 +860,7 @@ mod srgb8_fit_tests {
let diff: Vec<u32> =
fast.data.iter().zip(&slow.data).flat_map(|(a, b)| (0..3).map(move |c| (a[c] as i32 - b[c] as i32).unsigned_abs())).collect();
let mean = diff.iter().sum::<u32>() as f64 / diff.len() as f64;
assert!(mean < 3.0, "box {mw}×{mh}: mean difference {mean}");
assert!(mean < 5.0, "box {mw}×{mh}: mean difference {mean}");
}
}
+25 -14
View File
@@ -656,15 +656,13 @@ mod tests {
] {
let src = test_rgb(w, h);
let jpg = encode(&src, w, h, 3, 92, sub, &[]);
let mut d = jpeg_decoder::Decoder::new(&jpg[..]);
let px = d.decode().expect("jpeg-decoder");
let info = d.info().unwrap();
assert_eq!((info.width as usize, info.height as usize), (w, h));
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, &jpg, &craft_image_codecs::DecodeOptions::default())
.expect("craft-image-codecs");
assert_eq!((img.width() as usize, img.height() as usize), (w, h));
let px = img.as_u8().expect("u8");
if w * h > 64 {
assert!(psnr(&src, &px) > 30.0, "{w}x{h} {sub:?}: psnr {}", psnr(&src, &px));
assert!(psnr(&src, px) > 30.0, "{w}x{h} {sub:?}: psnr {}", psnr(&src, px));
}
let z = zune_jpeg::JpegDecoder::new(zune_core::bytestream::ZCursor::new(&jpg[..])).decode().expect("zune-jpeg");
assert_eq!(z.len(), px.len());
}
}
@@ -748,18 +746,30 @@ mod tests {
let std = encode_with(&src, w, h, 3, q, sub, &[], false);
let opt = encode(&src, w, h, 3, q, sub, &[]);
assert!(opt.len() < std.len(), "q{q} {sub:?}: {} ≥ {}", opt.len(), std.len());
let a = jpeg_decoder::Decoder::new(&std[..]).decode().expect("standard tables");
let b = jpeg_decoder::Decoder::new(&opt[..]).decode().expect("optimized tables");
let dec = |b: &[u8]| {
craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, b, &craft_image_codecs::DecodeOptions::default())
.expect("craft-image-codecs")
.as_u8()
.expect("u8")
.to_vec()
};
let a = dec(&std);
let b = dec(&opt);
assert_eq!(a, b, "q{q} {sub:?}: pixels differ");
let z = zune_jpeg::JpegDecoder::new(zune_core::bytestream::ZCursor::new(&opt[..])).decode().expect("zune-jpeg");
assert_eq!(z.len(), b.len());
}
// grayscale too
let gray: Vec<u8> = src.iter().step_by(3).copied().collect();
let std = encode_with(&gray, w, h, 1, 90, ChromaSubsampling::S444, &[], false);
let opt = encode(&gray, w, h, 1, 90, ChromaSubsampling::S444, &[]);
assert!(opt.len() < std.len());
assert_eq!(jpeg_decoder::Decoder::new(&std[..]).decode().unwrap(), jpeg_decoder::Decoder::new(&opt[..]).decode().unwrap());
let dec = |b: &[u8]| {
craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, b, &craft_image_codecs::DecodeOptions::default())
.unwrap()
.as_u8()
.unwrap()
.to_vec()
};
assert_eq!(dec(&std), dec(&opt));
}
/// The bytes written for 4:4:4, 4:2:0, grayscale and RGBA input at a size cut into many bands, with partial MCUs
@@ -797,7 +807,8 @@ mod tests {
let lo = encode(&src, w, h, 1, 30, ChromaSubsampling::S444, &[]);
let hi = encode(&src, w, h, 1, 95, ChromaSubsampling::S444, &[]);
assert!(lo.len() < hi.len());
let px = jpeg_decoder::Decoder::new(&hi[..]).decode().unwrap();
assert!(psnr(&src, &px) > 35.0);
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, &hi, &craft_image_codecs::DecodeOptions::default()).unwrap();
let px = img.as_u8().unwrap();
assert!(psnr(&src, px) > 35.0);
}
}
+42 -125
View File
@@ -1,138 +1,55 @@
//! JPEG XL decode via `jxl-oxide` (pure Rust). Enum-encoded images are rendered straight into linear
//! Rec.2020; ICC-tagged ones are rendered in their own space and interpreted with our ICC path.
//! XYB (lossy) images are rendered to linear sRGB primaries and converted to Rec.2020 here:
//! jxl-oxide 0.12 desaturates colours outside sRGB when it renders XYB to wider primaries.
//! jxl-oxide applies the codestream orientation itself, so `orientation` is reported as 1.
//! JPEG XL adapter to the shared `craft-jxl` codec.
use crate::convert::{Buf, Meta, Model, Raw, check_size, finish};
use crate::convert::{Buf, Meta, Model, Raw, finish};
use crate::space::{NamedSpace, SourceSpace, SpaceOrigin, Trc};
use crate::{DecodeOptions, Decoded, Error, Format, Result};
use jxl_oxide::color::{ColourSpace, EnumColourEncoding, Primaries, RenderingIntent, TransferFunction, WhitePoint};
use jxl_oxide::{AllocTracker, AuxBoxData, InitializeResult, JxlImage};
const F: Format = Format::Jxl;
fn err(e: impl std::fmt::Display) -> Error {
Error::Malformed(F, e.to_string())
}
/// Tracked allocation budget per allowed pixel for frames, extra channels and modular trees.
/// This bounds allocations covered by `AllocTracker`, not every allocation made by the decoder (#1517).
const TRACKED_BYTES_PER_PIXEL: u64 = 4 * 4 * 8;
/// The allocation budget never drops below this, so small images keep the decoder's fixed
/// overhead (group buffers, entropy tables) whatever `max_pixels` is.
const MIN_TRACKED_BYTES: u64 = 64 << 20;
/// Bytes handed to the decoder at a time (the size `JxlImageBuilder::read` reads in).
const INPUT_CHUNK: usize = 4096;
/// Initializes from bounded input, checks dimensions before rendering, then loads remaining frames
/// within a tracked allocation budget.
fn open(bytes: &[u8], opts: &DecodeOptions) -> Result<JxlImage> {
let budget = opts.max_pixels.saturating_mul(TRACKED_BYTES_PER_PIXEL).max(MIN_TRACKED_BYTES);
let tracker = AllocTracker::with_limit(usize::try_from(budget).unwrap_or(usize::MAX));
let mut uninit = JxlImage::builder().alloc_tracker(tracker).build_uninit();
// Initialization can load already-buffered frame data, so small feeds limit work before
// dimension checking.
let mut rest = bytes;
let mut window = INPUT_CHUNK;
let mut img = loop {
let consumed = uninit.feed_bytes(rest.get(..window).unwrap_or(rest)).map_err(err)?;
rest = rest.get(consumed..).unwrap_or_default();
match uninit.try_init().map_err(err)? {
InitializeResult::Initialized(img) => break img,
InitializeResult::NeedMoreData(more) => uninit = more,
}
if consumed == 0 {
// the parser wants more than the window holds at once
if window >= rest.len() {
return Err(err("truncated JPEG XL header"));
}
window = window.saturating_mul(2);
}
};
check_size(F, img.width() as u64, img.height() as u64, opts)?;
// Match `JxlImageBuilder::read`: bounded feeds until the final frame, not merely the first
// keyframe. `feed_bytes` copies codestream data into an untracked Vec, including any tail
// after the last frame; feeding the remaining file at once bypasses the allocation budget.
while !img.is_loading_done() && !rest.is_empty() {
let consumed = img.feed_bytes(rest.get(..INPUT_CHUNK).unwrap_or(rest)).map_err(err)?;
if consumed == 0 {
break;
}
rest = rest.get(consumed..).unwrap_or_default();
}
img.finalize().map_err(err)?;
Ok(img)
}
pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
let mut img = open(bytes, opts)?;
let (w, h) = (img.width(), img.height());
let header = img.image_header();
let bits = header.metadata.bit_depth.bits_per_sample() as u8;
let float = matches!(header.metadata.bit_depth, jxl_oxide::image::BitDepth::FloatSample { .. });
let gray = header.metadata.grayscale();
let icc = img.original_icc().map(|v| v.to_vec());
let mut meta = Meta { orientation: Some(1), ..Default::default() };
// linear sRGB primaries, unclamped, then our own matrix to Rec.2020 (see the module docs)
let via_srgb = icc.is_none() && !gray && header.metadata.xyb_encoded;
if icc.is_none() {
img.request_color_encoding(EnumColourEncoding {
colour_space: if gray { ColourSpace::Grey } else { ColourSpace::Rgb },
white_point: WhitePoint::D65,
primaries: if via_srgb { Primaries::Srgb } else { Primaries::Bt2100 },
tf: TransferFunction::Linear,
rendering_intent: RenderingIntent::Relative,
});
let mut s = SourceSpace::named(NamedSpace::Rec2020, SpaceOrigin::Container);
s.trc = Some([Trc::Linear, Trc::Linear, Trc::Linear]);
meta.already_linear = Some(s);
let limits = craft_jxl::DecodeLimits { max_pixels: opts.max_pixels, ..Default::default() };
let decoded = craft_jxl::decode_with_color(bytes, limits, craft_jxl::OutputColor::LinearRec2020).map_err(|e| match e {
craft_jxl::Error::PixelLimitExceeded { width, height, .. } => Error::TooLarge(u64::from(width), u64::from(height)),
craft_jxl::Error::Malformed(message) | craft_jxl::Error::LimitExceeded(message) | craft_jxl::Error::InvalidImage(message) => {
Error::Malformed(F, message)
}
craft_jxl::Error::Unsupported(message) | craft_jxl::Error::Encode(message) => Error::Malformed(F, message),
})?;
let gray = matches!(decoded.layout, craft_jxl::Layout::Gray | craft_jxl::Layout::GrayAlpha);
let alpha = decoded.layout.has_alpha();
let pixels_linear_rec2020 = decoded.pixels_linear_rec2020;
let rendered_icc = if !pixels_linear_rec2020 && decoded.metadata.icc.is_none() && !decoded.rendered_icc.is_empty() {
Some(decoded.rendered_icc.clone())
} else {
meta.icc = icc;
}
if let Ok(AuxBoxData::Data(ex)) = img.aux_boxes().first_exif() {
meta.exif = Some(ex.payload().to_vec());
}
if let AuxBoxData::Data(x) = img.aux_boxes().first_xml() {
meta.xmp = Some(String::from_utf8_lossy(x).trim_end_matches('\0').to_string());
}
let render = img.render_frame(0).map_err(err)?;
let fb = render.image_all_channels();
let (fw, fh, ch) = (fb.width(), fb.height(), fb.channels());
let n_color = if gray { 1 } else { 3 };
let has_alpha = img.pixel_format().has_alpha();
if ch < n_color {
return Err(err("too few channels"));
}
let keep = n_color + has_alpha as usize;
let src = fb.buf();
let mut v = Vec::with_capacity(fw * fh * keep);
let to_2020 = lightcraft_color::SRGB.to_space(&lightcraft_color::REC2020).to_f32();
for px in src.chunks_exact(ch) {
let start = v.len();
v.extend_from_slice(&px[..keep.min(ch)]);
if keep > ch {
v.push(1.0);
}
if via_srgb && let Some(rgb) = v.get_mut(start..start + 3) {
let [r, g, b] = [rgb[0], rgb[1], rgb[2]];
for (o, m) in rgb.iter_mut().zip(&to_2020) {
*o = m[0] * r + m[1] * g + m[2] * b;
}
}
None
};
let mut meta = Meta {
orientation: Some(1),
icc: decoded.metadata.icc.or(rendered_icc),
exif: decoded.metadata.exif,
xmp: decoded.metadata.xmp.map(|packet| String::from_utf8_lossy(&packet).trim_end_matches('\0').to_owned()),
..Default::default()
};
if pixels_linear_rec2020 {
let mut space = SourceSpace::named(NamedSpace::Rec2020, SpaceOrigin::Container);
space.trc = Some([Trc::Linear, Trc::Linear, Trc::Linear]);
meta.already_linear = Some(space);
} else if meta.icc.is_none() {
return Err(Error::Malformed(F, "shared decoder did not report the rendered JPEG XL color profile".into()));
}
let raw = Raw {
width: fw,
height: fh,
width: decoded.width as usize,
height: decoded.height as usize,
model: if gray { Model::Gray } else { Model::Rgb },
alpha: has_alpha,
premultiplied: false,
buf: Buf::F32(v),
bit_depth: bits,
alpha,
premultiplied: decoded.pixels_premultiplied,
buf: Buf::F32(decoded.pixels),
bit_depth: decoded.bit_depth,
};
let mut d = finish(F, raw, meta, (w, h), opts)?;
d.float = float;
Ok(d)
let (source_width, source_height) =
if (5..=8).contains(&decoded.source_orientation) { (decoded.height, decoded.width) } else { (decoded.width, decoded.height) };
let mut result = finish(F, raw, meta, (source_width, source_height), opts)?;
result.float = decoded.float_samples;
Ok(result)
}
+50 -139
View File
@@ -1,21 +1,16 @@
//! JPEG XL encode via `jixel` (pure Rust, BSD-3-Clause OR Apache-2.0; native targets with the `jxl`
//! feature: it spawns threads of its own). Lossy files are VarDCT in XYB, tagged with an enum colour
//! encoding the decoder renders back to; lossless files are Modular and keep their samples as they
//! are, tagged with the ICC profile when one is given. EXIF and XMP go in `Exif` / `xml ` boxes.
//! JPEG XL encoder adapter to the shared `craft-jxl` codec.
use crate::encode::{EncodeImage, EncodeMeta, HDR_REFERENCE_WHITE_NITS, Samples, pq_encode};
use crate::encode::{EncodeImage, EncodeMeta, Samples};
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
/// Encoder effort: time spent searching for a smaller file at the same quality. jixel's slowest
/// search (about 20 % smaller again, five times slower) is not offered: its files are valid, but
/// jxl-oxide, our decoder, renders blocks of them wrongly, so LightCraft could not read back its own
/// exports.
/// Encoder effort exposed by LightCraft's export settings.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum JxlEffort {
/// Plain 8×8 transforms only: quickest, largest (about a third larger than `Normal`).
/// Quick search, producing larger files.
Fast,
/// Balanced search.
#[default]
Normal,
}
@@ -30,32 +25,31 @@ impl JxlEffort {
}
}
/// The colour encoding a JPEG XL file declares. Integer samples are display-encoded with its curve.
/// The color encoding declared by the JPEG XL file.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum JxlColour {
#[default]
Srgb,
/// P3 primaries, D65, sRGB curve.
/// P3 primaries, D65, and the sRGB curve.
DisplayP3,
/// Rec. 2020 primaries with the BT.709 curve.
/// Rec. 2020 primaries and the BT.709 curve.
Rec2020,
/// HDR: Rec. 2020 primaries with the PQ curve (SMPTE ST 2084). Float samples are linear light
/// with SDR white at 1.0 (written with SDR white at [`HDR_REFERENCE_WHITE_NITS`]); 16-bit
/// samples are already PQ-encoded.
/// HDR Rec. 2020 using the PQ curve.
Rec2020Pq,
}
/// JPEG XL encoder settings.
/// JPEG XL export settings.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct JxlOptions {
/// 1..=100 on a libjpeg-like scale (90 ≈ visually lossless). Ignored when `lossless`.
/// Lossy quality on a 1..=100 scale; ignored when lossless.
pub quality: u8,
/// Mathematically lossless (Modular) instead of lossy (VarDCT).
/// Use mathematically lossless coding.
pub lossless: bool,
/// Encoder search effort.
pub effort: JxlEffort,
/// Lossy: two passes, a coarse image first; lossless: the Squeeze transform (a low-resolution
/// preview that refines to the exact image).
/// Write a progressive image.
pub progressive: bool,
/// Color encoding to declare.
pub colour: JxlColour,
}
@@ -65,124 +59,41 @@ impl Default for JxlOptions {
}
}
/// Encode JPEG XL from 8- or 16-bit samples (float samples only with [`JxlColour::Rec2020Pq`]).
/// Gray is widened to RGB; alpha is kept only when some pixel is not opaque. The ICC profile in
/// `meta` is embedded in lossless files (lossy ones carry the enum encoding of `o.colour`); `ppi`
/// has no place in the format. Returns [`Error::Encode`] on wasm32 or without the `jxl` feature.
pub fn encode_jxl(img: &EncodeImage, o: &JxlOptions, meta: &EncodeMeta) -> Result<Vec<u8>> {
img.validate()?;
#[cfg(all(feature = "jxl", not(target_arch = "wasm32")))]
{
let pixels = Pixels::from(img, o.colour)?;
// jixel asserts internally; a panic there is an export error, not a crash
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&pixels, img.width as usize, img.height as usize, o, meta)))
.unwrap_or_else(|_| Err(Error::Encode("JPEG XL encoder panicked".into())))
}
#[cfg(not(all(feature = "jxl", not(target_arch = "wasm32"))))]
{
let _ = (o, meta);
Err(Error::Encode("JPEG XL encoding is not available in this build".into()))
}
}
/// Interleaved RGB or RGBA samples for jixel.
#[cfg(all(feature = "jxl", not(target_arch = "wasm32")))]
enum Pixels {
U8 { data: Vec<u8>, alpha: bool },
U16 { data: Vec<u16>, alpha: bool },
}
#[cfg(all(feature = "jxl", not(target_arch = "wasm32")))]
impl Pixels {
fn from(img: &EncodeImage, colour: JxlColour) -> Result<Self> {
let n = (img.width as usize).checked_mul(img.height as usize).ok_or_else(|| Error::Encode("image too large".into()))?;
let ch = img.channels as usize;
// keep alpha only when it says something
fn rgba<T: Copy>(s: &[T], ch: usize, n: usize, opaque: impl Fn(T) -> bool) -> (Vec<T>, bool) {
let px = s.chunks_exact(ch).take(n);
let alpha = (ch == 2 || ch == 4) && s.chunks_exact(ch).take(n).any(|c| c.last().is_some_and(|a| !opaque(*a)));
let out_ch = if alpha { 4 } else { 3 };
let mut v = Vec::with_capacity(n * out_ch);
for c in px {
match c {
[g] => v.extend_from_slice(&[*g, *g, *g]),
[g, a] => v.extend_from_slice(&[*g, *g, *g, *a][..out_ch]),
[r, g, b] => v.extend_from_slice(&[*r, *g, *b]),
[r, g, b, a, ..] => v.extend_from_slice(&[*r, *g, *b, *a][..out_ch]),
[] => {}
}
}
(v, alpha)
}
Ok(match img.samples {
Samples::U8(s) => {
let (data, alpha) = rgba(s, ch, n, |a| a == u8::MAX);
Pixels::U8 { data, alpha }
}
Samples::U16(s) => {
let (data, alpha) = rgba(s, ch, n, |a| a == u16::MAX);
Pixels::U16 { data, alpha }
}
Samples::F32(s) if colour == JxlColour::Rec2020Pq => {
let pq = |v: f32| (pq_encode(if v.is_finite() { v.max(0.0) } else { 0.0 } * HDR_REFERENCE_WHITE_NITS) * 65535.0).round() as u16;
let alpha = |a: f32| (if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 } * 65535.0).round() as u16;
let s: Vec<u16> = s
.chunks_exact(ch)
.take(n)
.flat_map(|c| match c {
[g] => [pq(*g), pq(*g), pq(*g), u16::MAX],
[g, a] => [pq(*g), pq(*g), pq(*g), alpha(*a)],
[r, g, b] => [pq(*r), pq(*g), pq(*b), u16::MAX],
[r, g, b, a, ..] => [pq(*r), pq(*g), pq(*b), alpha(*a)],
[] => [0; 4],
})
.collect();
let (data, alpha) = rgba(&s, 4, n, |a| a == u16::MAX);
Pixels::U16 { data, alpha }
}
Samples::F32(_) => return Err(Error::Encode("JPEG XL float samples are written as HDR (Rec. 2020 PQ) only".into())),
})
}
}
#[cfg(all(feature = "jxl", not(target_arch = "wasm32")))]
fn run(px: &Pixels, w: usize, h: usize, o: &JxlOptions, meta: &EncodeMeta) -> Result<Vec<u8>> {
use jixel::{ColorEncoding, EncodeConfig, Primaries, Speed, TransferFunction};
let colour = match o.colour {
JxlColour::Srgb => ColorEncoding::srgb(),
JxlColour::DisplayP3 => ColorEncoding::display_p3(),
JxlColour::Rec2020 => ColorEncoding { primaries: Primaries::Bt2020, transfer: TransferFunction::Bt709, ..ColorEncoding::srgb() },
JxlColour::Rec2020Pq => ColorEncoding::bt2020_pq(),
/// Encode JPEG XL while preserving LightCraft's public option and metadata types.
pub fn encode_jxl(image: &EncodeImage, options: &JxlOptions, metadata: &EncodeMeta) -> Result<Vec<u8>> {
image.validate()?;
let layout = match image.channels {
1 => craft_jxl::Layout::Gray,
2 => craft_jxl::Layout::GrayAlpha,
3 => craft_jxl::Layout::Rgb,
4 => craft_jxl::Layout::Rgba,
_ => return Err(Error::Encode(format!("unsupported channel count {}", image.channels))),
};
let mut c = EncodeConfig::default()
.with_quality(f32::from(o.quality.clamp(1, 100)))
.with_color_encoding(colour)
.with_lossless(o.lossless)
.with_progressive(o.progressive)
.with_speed(match o.effort {
JxlEffort::Fast => Speed::Fastest,
JxlEffort::Normal => Speed::Fast,
});
if o.colour == JxlColour::Rec2020Pq {
// PQ code values are absolute: 1.0 = 10 000 cd/m²
c = c.with_intensity_target(10_000.0);
}
if o.lossless
&& let Some(icc) = meta.icc
{
c = c.with_icc_profile(icc.to_vec());
}
if let Some(exif) = meta.exif {
c = c.with_exif(exif.to_vec());
}
if let Some(xmp) = meta.xmp {
c = c.with_xmp(xmp.as_bytes().to_vec());
}
let r = match px {
Pixels::U8 { data, alpha: false } => jixel::encode_image(data, w, h, &c),
Pixels::U8 { data, alpha: true } => jixel::encode_image_with_alpha(data, w, h, &c),
Pixels::U16 { data, alpha: false } => jixel::encode_image_16bit(data, w, h, &c),
Pixels::U16 { data, alpha: true } => jixel::encode_image_with_alpha_16bit(data, w, h, &c),
let samples = match image.samples {
Samples::U8(samples) => craft_jxl::Samples::U8(samples),
Samples::U16(samples) => craft_jxl::Samples::U16(samples),
Samples::F32(samples) => craft_jxl::Samples::F32(samples),
};
r.map_err(|e| Error::Encode(format!("JPEG XL: {e}")))
let image = craft_jxl::ImageRef { width: image.width, height: image.height, layout, samples };
let options = craft_jxl::EncodeOptions {
quality: options.quality,
lossless: options.lossless,
effort: match options.effort {
JxlEffort::Fast => craft_jxl::Effort::Fast,
JxlEffort::Normal => craft_jxl::Effort::Normal,
},
progressive: options.progressive,
colour: match options.colour {
JxlColour::Srgb => craft_jxl::JxlColour::Srgb,
JxlColour::DisplayP3 => craft_jxl::JxlColour::DisplayP3,
JxlColour::Rec2020 => craft_jxl::JxlColour::Rec2020,
JxlColour::Rec2020Pq => craft_jxl::JxlColour::Rec2020Pq,
},
};
let metadata = craft_jxl::Metadata {
icc: metadata.icc.map(<[u8]>::to_vec),
exif: metadata.exif.map(<[u8]>::to_vec),
xmp: metadata.xmp.map(|packet| packet.as_bytes().to_vec()),
};
craft_jxl::encode(&image, options, &metadata).map_err(|error| Error::Encode(error.to_string()))
}
+161 -222
View File
@@ -1,8 +1,7 @@
//! GIF (first frame) and BMP via the `image` crate's pure-Rust decoders.
//! GIF through `craft-gif` and BMP through `craft-image-codecs`.
use crate::convert::{Buf, Meta, Model, Raw, check_size, finish};
use crate::{DecodeOptions, Decoded, Error, Format, Result};
use image::{DynamicImage, ImageDecoder};
/// Canvases up to this many pixels are still decoded by [`header`] (at most 16 MB), so a truncated
/// small file is refused at import as before.
@@ -13,11 +12,29 @@ const HEADER_DECODE_MAX_PIXELS: u64 = 4_000_000;
/// header and must be one the file's bytes can fill; only a canvas small enough to be cheap is
/// decoded (to catch truncation). Orientation is always 1: neither format carries EXIF here.
pub(crate) fn header(bytes: &[u8], format: Format) -> Result<(u32, u32, u16)> {
let err = |e: image::ImageError| Error::Malformed(format, e.to_string());
let cursor = std::io::Cursor::new(bytes);
if format == Format::Gif {
let info = craft_gif::scan(bytes, 1).ok_or_else(|| Error::Malformed(format, "invalid GIF header".into()))?;
let (w, h) = (u32::from(info.width), u32::from(info.height));
check_size(format, u64::from(w), u64::from(h), &DecodeOptions::default())?;
check_fillable(format, bytes, w, h)?;
if craft_gif::palette(bytes).is_none() {
return Err(Error::Malformed(format, "GIF has no readable colour table".into()));
}
if u64::from(w).saturating_mul(u64::from(h)) <= HEADER_DECODE_MAX_PIXELS {
let decoded = decode(bytes, format, &DecodeOptions::fit(64, 64))?;
return Ok((decoded.source_width, decoded.source_height, decoded.orientation));
}
return Ok((w, h, 1));
}
if format == Format::Bmp {
let (w, h) = bmp_dims(bytes).ok_or_else(|| Error::Malformed(format, "invalid BMP header".into()))?;
if w == 0 || h == 0 {
return Err(Error::Malformed(format, "zero dimension".into()));
}
check_fillable(format, bytes, w, h)?;
}
let (w, h) = match format {
Format::Gif => image::codecs::gif::GifDecoder::new(cursor).map_err(err)?.dimensions(),
Format::Bmp => image::codecs::bmp::BmpDecoder::new(cursor).map_err(err)?.dimensions(),
Format::Bmp => craft_image_codecs::probe_size(bytes).map_err(|e| Error::Malformed(format, e.to_string()))?,
_ => return Err(Error::Unsupported(format, "not handled by this decoder")),
};
if w == 0 || h == 0 {
@@ -31,16 +48,6 @@ pub(crate) fn header(bytes: &[u8], format: Format) -> Result<(u32, u32, u16)> {
Ok((w, h, 1))
}
/// The decoder's allocation limit: the RGBA buffer of the largest image `opts` allows. It bounds the
/// decoders' own frame buffers only: `DynamicImage::from_decoder` allocates the canvas without
/// consulting it, so the canvas is bounded by `check_size` and [`check_fillable`] beforehand (a
/// mostly blank one by [`SPARSE_MAX_PIXELS`]).
fn limits(opts: &DecodeOptions) -> image::Limits {
let mut l = image::Limits::default();
l.max_alloc = Some(opts.max_pixels.saturating_mul(4));
l
}
/// The largest canvas allowed that the file's pixel data leaves mostly blank: a GIF screen its
/// first frame's codes don't cover, or an RLE BMP whose runs don't. Its decode still allocates the
/// whole canvas (16 MB at this size), so it is held well below `max_pixels`.
@@ -55,10 +62,9 @@ const SPARSE_MAX_PIXELS: u64 = 4_000_000;
/// allocated, and is refused here instead.
/// - An RLE BMP covers the pixels its runs and absolute blocks draw, as the decoder paints them; an
/// end-of-row, end-of-bitmap or delta code leaves the rest blank.
/// - A GIF covers the pixels its first frame's LZW codes draw up to the end code. A code expands to
/// at most 4096 pixels and takes 12 bits once the table holds that many (fewer bits only while its
/// strings are shorter), so a frame larger than 2731 pixels per byte of LZW data is refused
/// outright. The screen around the frame may be larger, and is blank there.
/// - A GIF covers the pixels its first frame's LZW codes draw up to the end code. The shared GIF
/// reader counts code-string lengths without allocating decoded pixels; the screen around the
/// frame may be larger, and is blank there.
///
/// Canvases the data leaves mostly blank are limited to [`SPARSE_MAX_PIXELS`].
fn check_fillable(format: Format, bytes: &[u8], w: u32, h: u32) -> Result<()> {
@@ -67,15 +73,23 @@ fn check_fillable(format: Format, bytes: &[u8], w: u32, h: u32) -> Result<()> {
// the pixels the file's data can cover
let covered = match format {
Format::Gif => {
// without a frame there is nothing to decode, and nothing to bound the canvas by
let Some(frame) = gif_first_frame(bytes) else {
// A frame's compressed data must cover its declared raster before it can justify the
// logical screen. This retains the old "can hold" refusal for truncated/empty frames.
let info = craft_gif::scan(bytes, 1).ok_or_else(|| Error::Malformed(format, "no readable first frame".into()))?;
let Some(frame) = info.frames.first() else {
return Err(Error::Malformed(format, "no readable first frame".into()));
};
let (fw, fh, len) = (frame.width, frame.height, frame.data_len);
if area(fw, fh) > (len as u64).saturating_mul(2_731) {
return Err(Error::Malformed(format, format!("a {fw} × {fh} frame is far larger than its {len} bytes of pixel data can hold")));
let frame_width = u32::from(frame.width);
let frame_height = u32::from(frame.height);
let compressed_bytes =
craft_gif::first_frame_compressed_bytes(bytes).ok_or_else(|| Error::Malformed(format, "no readable first frame".into()))?;
if area(frame_width, frame_height) > (compressed_bytes as u64).saturating_mul(2_731) {
return Err(Error::Malformed(
format,
format!("a {frame_width} × {frame_height} frame is far larger than its {compressed_bytes} bytes of pixel data can hold"),
));
}
gif_frame_pixels(bytes, frame.codes, area(fw, fh))
craft_gif::first_frame_decoded_pixels(bytes).unwrap_or(0)
}
_ => match bmp_layout(bytes) {
BmpLayout::Rle { offset, rle4 } => bmp_rle_pixels(bytes, offset, rle4, w, h),
@@ -177,202 +191,87 @@ fn bmp_rle_pixels(bytes: &[u8], offset: usize, rle4: bool, w: u32, h: u32) -> u6
covered
}
/// A GIF's first frame, from its image descriptor.
struct GifFrame {
width: u32,
height: u32,
/// Bytes of LZW data present (its palettes, comments and other extensions describe no pixels).
data_len: usize,
/// Position of its LZW minimum code size, which its data sub-blocks follow.
codes: usize,
}
/// A GIF's first frame. `None` when the blocks before the frame can't be walked.
fn gif_first_frame(bytes: &[u8]) -> Option<GifFrame> {
let u16_at = |i: usize| bytes.get(i..i.checked_add(2)?).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes);
let table = |flags: u8| if flags & 0x80 != 0 { 3usize << ((flags & 7) + 1) } else { 0 };
let mut pos = 13 + table(*bytes.get(10)?);
loop {
match *bytes.get(pos)? {
// extension: introducer, label, sub-blocks
0x21 => pos = sub_blocks(bytes, pos.saturating_add(2)).1,
// image descriptor (separator, left, top, width, height, flags), local colour table,
// LZW minimum code size, data sub-blocks
0x2C => {
let (fw, fh) = (u16_at(pos.saturating_add(5))?, u16_at(pos.saturating_add(7))?);
let codes = pos.saturating_add(10).saturating_add(table(*bytes.get(pos.saturating_add(9))?));
let data_len = sub_blocks(bytes, codes.saturating_add(1)).0;
return Some(GifFrame { width: u32::from(fw), height: u32::from(fh), data_len, codes });
}
_ => return None,
}
/// Reads BMP `(width, height)` from the DIB header without allocating.
fn bmp_dims(bytes: &[u8]) -> Option<(u32, u32)> {
if bytes.get(0..2) != Some(b"BM") {
return None;
}
}
/// The pixels a GIF frame's LZW codes draw, at most `max` (the frame's size): the codes are walked
/// up to the end code, an invalid code or the end of the data, keeping only the length of each
/// table string, never the pixels. Data after the end code draws nothing. Codes are packed
/// least-significant bit first across the data sub-blocks and start one bit wider than the minimum
/// code size; a code is one bit wider each time the table fills its width, up to 12 bits, and a
/// clear code starts the table again (GIF89a, appendix F).
fn gif_frame_pixels(bytes: &[u8], codes: usize, max: u64) -> u64 {
// the `gif` decoder accepts minimum code sizes of 1 to 11
let Some(min_size) = bytes.get(codes).copied().filter(|s| (1..=11).contains(s)) else {
return 0;
let dib = u32::from_le_bytes(bytes.get(14..18)?.try_into().ok()?);
let (w, h) = if dib == 12 {
(u16::from_le_bytes(bytes.get(18..20)?.try_into().ok()?) as u32, u16::from_le_bytes(bytes.get(20..22)?.try_into().ok()?) as u32)
} else {
let w = i32::from_le_bytes(bytes.get(18..22)?.try_into().ok()?);
let h = i32::from_le_bytes(bytes.get(22..26)?.try_into().ok()?);
(u32::try_from(w).ok()?, h.unsigned_abs())
};
let clear = 1usize << min_size;
let end = clear + 1;
let mut lens = [1u16; 4096]; // string length of each code; literals (below `clear`) are 1
let (mut width, mut next, mut prev) = (u32::from(min_size) + 1, end + 1, None::<usize>);
let (mut bits, mut held, mut covered) = (0u32, 0u32, 0u64);
let mut pos = codes.saturating_add(1);
while let Some(&n) = bytes.get(pos) {
let start = pos.saturating_add(1);
pos = start.saturating_add(usize::from(n));
if n == 0 {
break;
}
for &byte in bytes.get(start..pos.min(bytes.len())).unwrap_or_default() {
bits |= u32::from(byte) << held;
held += 8;
while held >= width {
let code = (bits & ((1 << width) - 1)) as usize;
bits >>= width;
held -= width;
if code == clear {
(width, next, prev) = (u32::from(min_size) + 1, end + 1, None);
continue;
}
let len_of = |c: usize| lens.get(c).copied().unwrap_or(1);
let len = match prev {
_ if code == end => return covered,
None if code < clear => 1,
Some(_) if code < next => len_of(code),
// the string just being defined: the previous one and its first pixel
Some(p) if code == next => len_of(p).saturating_add(1),
_ => return covered,
};
// each code after the first defines the next string: the previous one and a pixel
let defined = prev.map(|p| len_of(p).saturating_add(1));
if let Some(defined) = defined
&& let Some(slot) = lens.get_mut(next)
{
*slot = defined;
next += 1;
if next == 1 << width && width < 12 {
width += 1;
}
}
prev = Some(code);
covered = covered.saturating_add(u64::from(len));
if covered >= max {
return max;
}
}
}
}
covered
}
/// The GIF sub-blocks starting at `pos`: the data bytes present, and the position after them.
fn sub_blocks(bytes: &[u8], mut pos: usize) -> (usize, usize) {
let mut data = 0usize;
while let Some(&n) = bytes.get(pos) {
let start = pos.saturating_add(1);
if n == 0 {
return (data, start);
}
let end = start.saturating_add(usize::from(n));
data = data.saturating_add(end.min(bytes.len()).saturating_sub(start));
pos = end;
}
(data, pos)
Some((w, h))
}
pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Result<Decoded> {
if format == Format::Gif {
gated_first_frame(bytes, opts)?;
return decode_gif(bytes, opts);
}
let err = |e: image::ImageError| Error::Malformed(format, e.to_string());
let cursor = std::io::Cursor::new(bytes);
let (img, icc) = match format {
Format::Gif => {
let mut d = image::codecs::gif::GifDecoder::new(cursor).map_err(err)?;
let (w, h) = d.dimensions();
check_size(format, w as u64, h as u64, opts)?;
check_fillable(format, bytes, w, h)?;
d.set_limits(limits(opts)).map_err(err)?;
let icc = d.icc_profile().ok().flatten();
(DynamicImage::from_decoder(d).map_err(err)?, icc)
}
Format::Bmp => {
let mut d = image::codecs::bmp::BmpDecoder::new(cursor).map_err(err)?;
let (w, h) = d.dimensions();
check_size(format, w as u64, h as u64, opts)?;
check_fillable(format, bytes, w, h)?;
d.set_limits(limits(opts)).map_err(err)?;
let icc = d.icc_profile().ok().flatten();
(DynamicImage::from_decoder(d).map_err(err)?, icc)
}
_ => return Err(Error::Unsupported(format, "not handled by this decoder")),
if format != Format::Bmp {
return Err(Error::Unsupported(format, "not handled by this decoder"));
}
let (w, h) = bmp_dims(bytes).ok_or_else(|| Error::Malformed(format, "invalid BMP header".into()))?;
check_size(format, w as u64, h as u64, opts)?;
check_fillable(format, bytes, w, h)?;
let (w, h) = craft_image_codecs::probe_size(bytes).map_err(|e| Error::Malformed(format, e.to_string()))?;
let ic_opts = craft_image_codecs::DecodeOptions {
limits: craft_image_codecs::Limits {
max_width: u32::MAX,
max_height: u32::MAX,
max_pixels: opts.max_pixels,
max_alloc: opts.max_pixels.saturating_mul(4),
},
keep_orientation: true,
};
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Bmp, bytes, &ic_opts).map_err(|e| match e {
craft_image_codecs::CodecError::LimitExceeded(_) => Error::TooLarge(w as u64, h as u64),
other => Error::Malformed(format, other.to_string()),
})?;
let (w, h) = (img.width(), img.height());
let alpha = img.color().has_alpha();
let gray = !img.color().has_color();
let (model, alpha, buf) = match (gray, alpha) {
(true, false) => (Model::Gray, false, img.into_luma8().into_raw()),
(true, true) => (Model::Gray, true, img.into_luma_alpha8().into_raw()),
(false, false) => (Model::Rgb, false, img.into_rgb8().into_raw()),
(false, true) => (Model::Rgb, true, img.into_rgba8().into_raw()),
};
let alpha = img.layout().has_alpha();
let model = if img.layout().is_gray() { Model::Gray } else { Model::Rgb };
let buf = img.as_u8().ok_or_else(|| Error::Malformed(format, "expected 8-bit BMP samples".into()))?.to_vec();
let raw = Raw { width: w as usize, height: h as usize, model, alpha, premultiplied: false, buf: Buf::U8(buf), bit_depth: 8 };
finish(format, raw, Meta { icc, ..Default::default() }, (w, h), opts)
finish(format, raw, Meta { icc: img.icc, ..Default::default() }, (w, h), opts)
}
/// Bounds a GIF's first image descriptor: the decoder composites frames into the logical screen
/// (bounded by [`check_size`] on the canvas) but allocates its own frame buffers at the frame's
/// declared size, which a small file can inflate far past the canvas. The canvas check cannot
/// see that size, so it is read from the block headers here.
fn gated_first_frame(bytes: &[u8], opts: &DecodeOptions) -> Result<()> {
// The constants of the header grammar: signature, logical screen descriptor (with its global
// colour table), extension blocks (0x21, skipped by their sub-block chains) and image
// descriptors (0x2C).
const SCREEN: usize = 13;
if bytes.len() < SCREEN {
return Ok(()); // too broken for a frame; the decoder reports the damage itself
}
let gct_entries = 1usize << (u32::from(bytes[10] & 0x07) + 1); // at most 256
let gct_bytes = if (bytes[10] & 0x80) != 0 { gct_entries * 3 } else { 0 };
let mut p = SCREEN.saturating_add(gct_bytes);
while let Some(&kind) = bytes.get(p) {
match kind {
0x2C => {
// Image descriptor: two LE coordinates then two LE edges, after the separator.
let end = p.checked_add(10).filter(|&e| e <= bytes.len());
let Some(d) = end.and_then(|e| bytes.get(p + 1..e)) else {
break; // cut short mid-descriptor: the decoder reports that
};
let (w, h) = (u16::from_le_bytes([d[4], d[5]]) as u64, u16::from_le_bytes([d[6], d[7]]) as u64);
return check_size(Format::Gif, w, h, opts);
}
0x21 => {
// Extension: a label byte, then <len,data> sub-blocks ended by a zero length.
p = p.saturating_add(2);
loop {
let Some(&len) = bytes.get(p) else {
return Ok(()); // ran past the data: decode reports the truncation
};
p = p.saturating_add(1);
if len == 0 {
break;
}
p = p.saturating_add(len as usize);
}
}
_ => p = p.saturating_add(1),
}
}
Ok(())
fn decode_gif(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
let format = Format::Gif;
let Some(info) = craft_gif::scan(bytes, 1) else {
return Err(Error::Malformed(format, "invalid GIF header".into()));
};
let (width, height) = (u32::from(info.width), u32::from(info.height));
check_size(format, u64::from(width), u64::from(height), opts)?;
let Some(frame) = info.frames.first() else {
return Err(Error::Malformed(format, "no readable first frame".into()));
};
check_size(format, u64::from(frame.width), u64::from(frame.height), opts)?;
check_fillable(format, bytes, width, height)?;
let max_bytes = opts.max_pixels.saturating_mul(4);
let mut limits = craft_gif::frames::FrameLimits::default();
limits.max_frames = 1;
limits.max_bytes = max_bytes;
limits.max_canvas_bytes = max_bytes;
limits.max_decode_bytes = Some(max_bytes);
let animation = craft_gif::frames::read_frames(bytes, &limits).map_err(|e| Error::Malformed(format, e.to_string()))?;
let Some(decoded) = animation.frames.into_iter().next() else {
return Err(Error::Malformed(format, "no decoded frame".into()));
};
let raw = Raw {
width: animation.width as usize,
height: animation.height as usize,
model: Model::Rgb,
alpha: true,
premultiplied: false,
buf: Buf::U8(decoded.rgba),
bit_depth: 8,
};
let icc = craft_gif::frames::icc_profile(bytes);
finish(format, raw, Meta { icc, ..Default::default() }, (animation.width, animation.height), opts)
}
#[cfg(test)]
@@ -387,7 +286,7 @@ mod tests {
b
}
/// `image`'s GIF decoder allocates its frame buffer at the image descriptor's declared
/// A GIF decoder allocates its frame buffer at the image descriptor's declared
/// size, which the canvas bound ([`crate::decode`]'s `max_pixels` on the logical screen)
/// does not cover. A 20-byte file used to buy a 4 GB allocation before the gate.
#[test]
@@ -437,17 +336,57 @@ mod tests {
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
(seed >> 24) as u8
};
let frames = [
("solid", image::RgbaImage::from_pixel(w, h, image::Rgba([90, 90, 90, 255]))),
("gradient", image::RgbaImage::from_fn(w, h, |x, y| image::Rgba([(x / 40 * 16) as u8, (y / 30 * 16) as u8, 0, 255]))),
("noise", image::RgbaImage::from_fn(w, h, |_, _| image::Rgba([noise(), noise(), noise(), 255]))),
];
for (name, frame) in frames {
let mut gif = Vec::new();
image::codecs::gif::GifEncoder::new_with_speed(&mut gif, 30).encode_frame(image::Frame::new(frame)).unwrap();
let first = gif_first_frame(&gif).unwrap();
assert_eq!((first.width, first.height), (w, h), "{name}");
assert_eq!(gif_frame_pixels(&gif, first.codes, u64::MAX), u64::from(w * h), "{name}");
let encode_gif = |rgba: Vec<u8>| -> Vec<u8> {
let img = craft_image_codecs::Image::from_u8(w, h, craft_image_codecs::ChannelLayout::Rgba, rgba).unwrap();
craft_image_codecs::encode(&img, craft_image_codecs::Format::Gif, &craft_image_codecs::EncodeOptions::default()).unwrap()
};
let solid = [90, 90, 90, 255].repeat((w * h) as usize);
let mut gradient = Vec::with_capacity((w * h * 4) as usize);
let mut noise_buf = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h {
for x in 0..w {
gradient.extend_from_slice(&[((x / 40 * 16) as u8), ((y / 30 * 16) as u8), 0, 255]);
noise_buf.extend_from_slice(&[noise(), noise(), noise(), 255]);
}
}
for (name, rgba) in [("solid", solid), ("gradient", gradient), ("noise", noise_buf)] {
let gif = encode_gif(rgba);
let first = craft_gif::scan(&gif, 1).unwrap().frames.remove(0);
assert_eq!((u32::from(first.width), u32::from(first.height)), (w, h), "{name}");
assert_eq!(craft_gif::first_frame_decoded_pixels(&gif), Some(u64::from(w * h)), "{name}");
}
}
#[test]
fn gif_icc_profile_is_preserved_by_the_codec_adapter() {
let img = craft_image_codecs::Image::from_u8(2, 2, craft_image_codecs::ChannelLayout::Rgba, [80, 120, 160, 255].repeat(4)).unwrap();
let mut bytes = craft_image_codecs::encode(&img, craft_image_codecs::Format::Gif, &craft_image_codecs::EncodeOptions::default()).unwrap();
let frame = craft_gif::scan(&bytes, 1).unwrap().frames[0];
let profile = [1, 2, 3, 4, 5];
let mut extension = vec![0x21, 0xff, 0x0b];
extension.extend_from_slice(b"ICCRGBG1012");
extension.push(profile.len() as u8);
extension.extend_from_slice(&profile);
extension.push(0);
bytes.splice(frame.offset..frame.offset, extension);
let decoded = crate::decode(&bytes, DecodeOptions::default()).unwrap();
assert_eq!(decoded.icc.as_deref(), Some(profile.as_slice()));
}
#[test]
fn gif_first_frame_pixels_match_the_previous_image_decoder() {
let mut pixels = Vec::with_capacity(16 * 12 * 4);
for y in 0..12 {
for x in 0..16 {
pixels.extend_from_slice(&[(x * 13) as u8, (y * 17) as u8, 91, if (x + y) % 3 == 0 { 127 } else { 255 }]);
}
}
let img = craft_image_codecs::Image::from_u8(16, 12, craft_image_codecs::ChannelLayout::Rgba, pixels).unwrap();
let bytes = craft_image_codecs::encode(&img, craft_image_codecs::Format::Gif, &craft_image_codecs::EncodeOptions::default()).unwrap();
let decoded = craft_image_codecs::decode_as(craft_image_codecs::Format::Gif, &bytes).unwrap();
let shared = craft_gif::frames::read_frames(&bytes, &craft_gif::frames::FrameLimits::default()).unwrap();
assert_eq!(shared.frames[0].rgba, decoded.as_u8().unwrap());
}
}
+110 -74
View File
@@ -1,4 +1,4 @@
//! PNG decode via the `png` crate (8/16-bit, palette, tRNS, iCCP, eXIf, iTXt XMP, sRGB/cICP/cHRM/gAMA).
//! PNG decode via `craft-image-codecs` (8/16-bit, palette, tRNS, iCCP, eXIf, iTXt XMP, sRGB/cICP/cHRM/gAMA).
use crate::convert::{Buf, Meta, Model, Raw, check_size, finish};
use crate::space::{NamedSpace, SourceSpace, SpaceOrigin, Trc};
@@ -16,55 +16,39 @@ fn err(e: impl std::fmt::Display) -> Error {
}
pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
dec.set_transformations(png::Transformations::EXPAND);
dec.set_limits(png::Limits { bytes: opts.max_pixels.saturating_mul(8).min(usize::MAX as u64) as usize });
let mut reader = dec.read_info().map_err(err)?;
let (w, h) = {
let i = reader.info();
(i.width, i.height)
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") && bytes.get(12..16) == Some(b"IHDR") && bytes.len() >= 24 {
let w = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);
let h = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]);
check_size(F, w as u64, h as u64, opts)?;
}
let ic_opts = craft_image_codecs::DecodeOptions {
limits: craft_image_codecs::Limits {
max_width: u32::MAX,
max_height: u32::MAX,
max_pixels: opts.max_pixels,
max_alloc: opts.max_pixels.saturating_mul(8),
},
keep_orientation: true,
};
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, bytes, &ic_opts).map_err(|e| match e {
craft_image_codecs::CodecError::LimitExceeded(_) => Error::TooLarge(0, 0),
other => err(other),
})?;
let (w, h) = (img.width(), img.height());
check_size(F, w as u64, h as u64, opts)?;
let size = reader.output_buffer_size().ok_or_else(|| err("buffer size overflow"))?;
let mut buf = vec![0u8; size];
let out = reader.next_frame(&mut buf).map_err(err)?;
// Text chunks after IDAT land in `info` once the stream is finished; ignore trailing errors.
let _ = reader.finish();
let info = reader.info();
let (model, alpha) = match out.color_type {
png::ColorType::Grayscale => (Model::Gray, false),
png::ColorType::GrayscaleAlpha => (Model::Gray, true),
png::ColorType::Rgb => (Model::Rgb, false),
png::ColorType::Rgba => (Model::Rgb, true),
png::ColorType::Indexed => return Err(err("palette not expanded")),
let model = if img.layout().is_gray() { Model::Gray } else { Model::Rgb };
let alpha = img.layout().has_alpha();
let (samples, depth) = match img.sample_type() {
craft_image_codecs::SampleType::U16 => (Buf::U16(img.to_u16_samples().ok_or_else(|| err("expected 16-bit samples"))?), 16),
_ => (Buf::U8(img.as_u8().ok_or_else(|| err("expected 8-bit samples"))?.to_vec()), 8),
};
buf.truncate(out.buffer_size());
let (samples, depth) = match out.bit_depth {
png::BitDepth::Sixteen => (Buf::U16(buf.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect()), 16),
_ => (Buf::U8(buf), info.bit_depth as u8),
};
let raw = Raw { width: out.width as usize, height: out.height as usize, model, alpha, premultiplied: false, buf: samples, bit_depth: depth };
let raw = Raw { width: w as usize, height: h as usize, model, alpha, premultiplied: false, buf: samples, bit_depth: depth };
// png's `get_text()` inflates a compressed chunk with no bound of its own: a tiny
// iTXt can claim an XMP document of arbitrary size. Expand through the bounded path
// instead, and drop any XMP bigger than the cap.
let xmp = info
.utf8_text
.iter()
.find(|t| t.keyword == "XML:com.adobe.xmp")
.and_then(|t| {
let mut t = t.clone();
t.decompress_text_with_limit(MAX_TEXT_CHUNK).ok()?;
t.get_text().ok()
})
.or_else(|| info.uncompressed_latin1_text.iter().find(|t| t.keyword == "XML:com.adobe.xmp").map(|t| t.text.clone()));
let exif = info.exif_metadata.as_ref().map(|e| {
let e = e.to_vec();
// Some writers keep the JPEG "Exif\0\0" prefix.
if e.starts_with(b"Exif\0\0") { e[6..].to_vec() } else { e }
});
let meta = Meta { icc: info.icc_profile.as_ref().map(|c| c.to_vec()), exif, xmp, hint: container_hint(info), ..Default::default() };
let cicp_hint = img.cicp.as_ref().and_then(|c| SourceSpace::from_cicp(c.primaries, c.transfer));
let hint = cicp_hint.or_else(|| container_hint_from_chunks(bytes));
let xmp = img.meta.xmp.filter(|x| x.len() <= MAX_TEXT_CHUNK);
let exif = img.meta.exif.map(|e| if e.starts_with(b"Exif\0\0") { e[6..].to_vec() } else { e });
let meta = Meta { icc: img.icc, exif, xmp, hint, ..Default::default() };
finish(F, raw, meta, (w, h), opts)
}
@@ -137,17 +121,40 @@ pub(crate) fn header(b: &[u8]) -> Result<(u32, u32, u16)> {
Ok((w, h, exif.map(crate::exif::summarize).unwrap_or_default().orientation.unwrap_or(1)))
}
fn container_hint(info: &png::Info) -> Option<SourceSpace> {
if let Some(s) =
info.coding_independent_code_points.as_ref().and_then(|c| SourceSpace::from_cicp(c.color_primaries.into(), c.transfer_function.into()))
{
return Some(s);
fn container_hint_from_chunks(b: &[u8]) -> Option<SourceSpace> {
if !b.starts_with(b"\x89PNG\r\n\x1a\n") {
return None;
}
if info.srgb.is_some() {
let mut has_srgb = false;
let mut gamma: Option<f32> = None;
let mut chrm: Option<[f64; 8]> = None;
let mut p = 8usize;
while let Some(len_bytes) = b.get(p..p + 4) {
let len = u32::from_be_bytes([len_bytes[0], len_bytes[1], len_bytes[2], len_bytes[3]]) as usize;
let Some(kind) = b.get(p + 4..p + 8) else { break };
let Some(payload) = b.get(p + 8..p + 8 + len) else { break };
if kind == b"sRGB" {
has_srgb = true;
} else if kind == b"gAMA" && payload.len() == 4 {
let v = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]) as f32 / 100_000.0;
if v > 0.0 && v.is_finite() {
gamma = Some(v);
}
} else if kind == b"cHRM" && payload.len() == 32 {
let mut vals = [0.0f64; 8];
for (i, dst) in vals.iter_mut().enumerate() {
let raw = i32::from_be_bytes([payload[i * 4], payload[i * 4 + 1], payload[i * 4 + 2], payload[i * 4 + 3]]);
*dst = raw as f64 / 100_000.0;
}
chrm = Some(vals);
} else if kind == b"IDAT" || kind == b"IEND" {
break;
}
p = p.saturating_add(12).saturating_add(len);
}
if has_srgb {
return Some(SourceSpace::named(NamedSpace::Srgb, SpaceOrigin::Container));
}
let gamma = info.gama_chunk.or(info.source_gamma).map(|g| g.into_value()).filter(|g| *g > 0.0 && g.is_finite());
let chrm = info.chrm_chunk.or(info.source_chromaticities);
if gamma.is_none() && chrm.is_none() {
return None;
}
@@ -158,8 +165,7 @@ fn container_hint(info: &png::Info) -> Option<SourceSpace> {
};
let mut s = SourceSpace::named(NamedSpace::Srgb, SpaceOrigin::Container);
if let Some(c) = chrm {
let xy = |p: (png::ScaledFloat, png::ScaledFloat)| Xy::new(p.0.into_value() as f64, p.1.into_value() as f64);
let space = RgbSpace { name: "PNG cHRM", r: xy(c.red), g: xy(c.green), b: xy(c.blue), white: xy(c.white) };
let space = RgbSpace { name: "PNG cHRM", white: Xy::new(c[0], c[1]), r: Xy::new(c[2], c[3]), g: Xy::new(c[4], c[5]), b: Xy::new(c[6], c[7]) };
let valid = [space.r, space.g, space.b, space.white].iter().all(|p| p.y > 1e-4 && p.x >= 0.0 && p.x + p.y <= 1.0 + 1e-6);
let m = if valid { rgb_to_xyz_d50_checked(&space) } else { None };
if let Some(m) = m {
@@ -205,29 +211,59 @@ mod tests {
/// A little-endian PNG with one compressed iTXt chunk carrying `payload` as XMP.
fn png_with_compressed_xmp(payload: &str) -> Vec<u8> {
use png::text_metadata::{EncodableTextChunk, ITXtChunk};
let mut base = Vec::new();
{
let mut enc = png::Encoder::new(&mut base, 1, 1);
enc.set_color(png::ColorType::Grayscale);
enc.set_depth(png::BitDepth::Eight);
let mut w = enc.write_header().unwrap();
w.write_image_data(&[0x7F]).unwrap();
w.finish().unwrap();
let img = craft_image_codecs::Image::from_u8(1, 1, craft_image_codecs::ChannelLayout::Gray, vec![0x7F]).unwrap();
let base = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
// Build a valid zlib stream using uncompressed DEFLATE stored blocks (<= 65535 bytes each).
let raw = payload.as_bytes();
let mut z = vec![0x78u8, 0x01];
let mut offset = 0usize;
loop {
let end = (offset + 65535).min(raw.len());
let block = &raw[offset..end];
let is_last = end == raw.len();
let len = block.len() as u16;
z.push(u8::from(is_last));
z.extend_from_slice(&len.to_le_bytes());
z.extend_from_slice(&(!len).to_le_bytes());
z.extend_from_slice(block);
offset = end;
if is_last {
break;
}
}
// `ITXtChunk::encode` writes the complete chunk (length, type, payload, CRC), with
// the text compressed.
let mut chunk = Vec::new();
let mut xmp = ITXtChunk::new("XML:com.adobe.xmp", payload);
xmp.compressed = true;
xmp.compress_text().unwrap();
xmp.encode(&mut chunk).unwrap();
// Text chunks after IDAT land in `info` once the stream is finished: insert ours
// before the trailing IEND (a zero-length chunk is exactly 12 bytes).
let (mut s1, mut s2) = (1u32, 0u32);
for &b in raw {
s1 = (s1 + u32::from(b)) % 65521;
s2 = (s2 + s1) % 65521;
}
z.extend_from_slice(&((s2 << 16) | s1).to_be_bytes());
let mut itxt = Vec::new();
itxt.extend_from_slice(b"XML:com.adobe.xmp\0");
itxt.push(1); // compression_flag = 1
itxt.push(0); // compression_method = 0
itxt.extend_from_slice(b"\0\0"); // empty language_tag + translated_keyword
itxt.extend_from_slice(&z);
let chunk = png_chunk(*b"iTXt", &itxt);
let split = base.len() - 12;
let mut out = base[..split].to_vec();
out.extend_from_slice(&chunk);
out.extend_from_slice(&base[split..]);
out
}
fn png_chunk(kind: [u8; 4], data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(12 + data.len());
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(&kind);
out.extend_from_slice(data);
let mut crc = 0xFFFF_FFFFu32;
for &b in &out[4..] {
crc ^= u32::from(b);
for _ in 0..8 {
crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
}
}
out.extend_from_slice(&(!crc).to_be_bytes());
out
}
}
+28 -42
View File
@@ -17,14 +17,14 @@
//! on screen (the print is what it corrects).
//!
//! Everything before the profile conversion is per channel, so it folds into one 65,536-entry table
//! indexed by the 16-bit sample; the conversion itself is moxcms's.
//! indexed by the 16-bit sample; the conversion itself is `craft-cms`'s.
//!
//! Sources: ICC.1:2022 (rendering intents, profile classes); Adobe Systems, "Adobe Black Point
//! Compensation" (2006, public white paper) for the black point mapping. Own design otherwise.
use std::sync::Arc;
use moxcms::{ColorProfile, DataColorSpace, Layout, RenderingIntent, TransformExecutor, TransformOptions};
use craft_cms::{ColorSpace, Intent, Profile, Transform, TransformOptions};
use crate::display::MAX_PROFILE_BYTES;
use crate::proof::ProofIntent;
@@ -64,12 +64,10 @@ const BATCH: usize = 1 << 16;
/// says more is broken or not a print profile; leave the page alone rather than wash it out.
const MAX_BLACK: f32 = 0.5;
type Executor = Arc<dyn TransformExecutor<f32> + Send + Sync>;
/// A page conversion, built once per print job and applied to every page.
pub struct PrintTransform {
forward: Executor,
layout: Layout,
forward: Transform,
is_cmyk: bool,
channels: usize,
icc: Arc<Vec<u8>>,
/// 16-bit sample → linear Rec.2020 after the print adjustment and black point compensation.
@@ -88,14 +86,10 @@ impl std::fmt::Debug for PrintTransform {
}
}
fn guarded<T>(f: impl FnOnce() -> Option<T>) -> Option<T> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok().flatten()
}
fn rendering_intent(intent: ProofIntent) -> RenderingIntent {
fn rendering_intent(intent: ProofIntent) -> Intent {
match intent {
ProofIntent::Perceptual => RenderingIntent::Perceptual,
ProofIntent::Relative => RenderingIntent::RelativeColorimetric,
ProofIntent::Perceptual => Intent::Perceptual,
ProofIntent::Relative => Intent::RelativeColorimetric,
}
}
@@ -127,21 +121,19 @@ impl PrintTransform {
if icc.len() > MAX_PROFILE_BYTES {
return Err("the profile is too large".into());
}
let dev = guarded(|| ColorProfile::new_from_slice(&icc).ok()).ok_or("not a valid ICC profile")?;
let (layout, channels) = match dev.color_space {
DataColorSpace::Rgb => (Layout::Rgb, 3),
DataColorSpace::Cmyk => (Layout::Rgba, 4),
DataColorSpace::Gray => (Layout::Gray, 1),
let dev = Profile::parse(&icc).map_err(|_| "not a valid ICC profile")?;
let (is_cmyk, channels) = match dev.color_space {
ColorSpace::Rgb => (false, 3),
ColorSpace::Cmyk => (true, 4),
ColorSpace::Gray => (false, 1),
_ => return Err("only RGB, CMYK and grey printer profiles can be printed to".into()),
};
let lin = crate::icc::linear_rec2020_profile();
let opts = |i| TransformOptions { rendering_intent: i, ..TransformOptions::default() };
let forward: Executor = guarded(|| lin.create_transform_f32(Layout::Rgb, &dev, layout, opts(rendering_intent(color.intent))).ok())
.ok_or("can't convert to this profile")?;
let opts = |intent| TransformOptions { intent, bpc: false, precise_float: true };
let forward = Transform::with_options(&lin, &dev, opts(rendering_intent(color.intent))).map_err(|_| "can't convert to this profile")?;
let black = if color.black_point_compensation && color.intent == ProofIntent::Relative {
let back: Executor = guarded(|| dev.create_transform_f32(layout, &lin, Layout::Rgb, opts(RenderingIntent::RelativeColorimetric)).ok())
.ok_or("can't convert from this profile")?;
let back = Transform::with_options(&dev, &lin, opts(Intent::RelativeColorimetric)).map_err(|_| "can't convert from this profile")?;
device_black(&forward, &back, channels)
} else {
0.0
@@ -163,7 +155,7 @@ impl PrintTransform {
})
.collect();
let description = crate::icc::parse(&icc).and_then(|i| i.description);
Ok(PrintTransform { forward, layout, channels, icc, pre, black, description })
Ok(PrintTransform { forward, is_cmyk, channels, icc, pre, black, description })
}
/// Samples per pixel of the converted page: 3 (RGB), 4 (CMYK) or 1 (grey).
@@ -179,7 +171,7 @@ impl PrintTransform {
/// Whether the samples are CMYK (PDF readers show CMYK images inverted unless told otherwise,
/// so writers need to know).
pub fn is_cmyk(&self) -> bool {
self.layout == Layout::Rgba
self.is_cmyk
}
/// The linear black black point compensation lifts the page's black to (0 when off).
@@ -205,7 +197,7 @@ impl PrintTransform {
let run = |src: &[u16], dst: &mut [u16]| -> Option<()> {
let lin: Vec<f32> = src.iter().map(|&v| self.pre.get(usize::from(v)).copied().unwrap_or(0.0)).collect();
let mut dev = vec![0f32; dst.len()];
self.forward.transform(&lin, &mut dev).ok()?;
self.forward.convert_f32(&lin, 3, &mut dev, ch, false).ok()?;
for (d, v) in dst.iter_mut().zip(dev) {
let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
*d = (v * 65535.0 + 0.5) as u16;
@@ -218,24 +210,20 @@ impl PrintTransform {
let ok = {
use rayon::prelude::*;
let pairs: Vec<_> = src.zip(dst).collect();
pairs.into_par_iter().all(|(s, d)| guarded(|| run(s, d)).is_some())
pairs.into_par_iter().all(|(s, d)| run(s, d).is_some())
};
#[cfg(not(feature = "parallel"))]
let ok = src.zip(dst).all(|(s, d)| guarded(|| run(s, d)).is_some());
let ok = src.zip(dst).all(|(s, d)| run(s, d).is_some());
if ok { Ok(out) } else { Err("the profile's tables can't be applied".into()) }
}
}
/// The darkest the device holds, as linear Rec.2020 luminance: black there and back, relative
/// colorimetric both ways (for a device that reaches true black, 0).
fn device_black(forward: &Executor, back: &Executor, channels: usize) -> f32 {
fn device_black(forward: &Transform, back: &Transform, channels: usize) -> f32 {
let mut device = vec![0f32; channels];
let mut lin = [0f32; 3];
let ok = guarded(|| {
forward.transform(&[0.0; 3], &mut device).ok()?;
back.transform(&device, &mut lin).ok()
});
if ok.is_none() {
if forward.convert_f32(&[0.0; 3], 3, &mut device, channels, false).is_err() || back.convert_f32(&device, channels, &mut lin, 3, false).is_err() {
return 0.0;
}
// BT.2020 luminance weights
@@ -246,7 +234,6 @@ fn device_black(forward: &Executor, back: &Executor, channels: usize) -> f32 {
#[cfg(test)]
mod tests {
use super::*;
use moxcms::ToneReprCurve;
/// A page of one 16-bit pixel per linear grey level.
fn greys(levels: &[f32]) -> Vec<u16> {
@@ -259,15 +246,14 @@ mod tests {
/// An RGB print profile whose ink can't get darker than linear 0.03: device 0 is 3 % grey.
fn raised_black_profile() -> Arc<Vec<u8>> {
let mut p = ColorProfile::new_from_slice(&crate::icc::write_named(NamedSpace::Srgb)).unwrap();
let (g, e) = (2.2f32, 0.03f32);
use craft_cms::Curve;
let mut p = Profile::parse(&crate::icc::write_named(NamedSpace::Srgb)).unwrap();
let (g, e) = (2.2f64, 0.03f64);
let a = (1.0 - e).powf(1.0 / g);
// ICC parametric type 4: Y = (aX + b)^g + e for X >= d, Y = cX + f below
let trc = ToneReprCurve::Parametric(vec![g, a, 0.0, 0.0, 0.0, e, e]);
p.red_trc = Some(trc.clone());
p.green_trc = Some(trc.clone());
p.blue_trc = Some(trc);
Arc::new(p.encode().unwrap())
let trc = Curve::Parametric { kind: 4, p: [g, a, 0.0, 0.0, 0.0, e, e] };
p.trc = Some([trc.clone(), trc.clone(), trc]);
Arc::new(p.with_encoded_bytes().to_bytes().to_vec())
}
#[test]
+25 -29
View File
@@ -12,10 +12,10 @@
//! - Each entry carries a gamut flag: how far the relative-colorimetric round trip moved the colour.
//!
//! Sources: ICC.1:2022 (rendering intents, media white point, absolute colorimetric scaling);
//! the transforms are moxcms's. Own design otherwise.
//! the transforms are `craft-cms`'s. Own design otherwise.
use craft_cms::{ColorSpace, Intent, Profile, Transform, TransformOptions};
use lightcraft_color::{D50, D65, REC2020, bradford};
use moxcms::{ColorProfile, DataColorSpace, Layout, RenderingIntent, TransformOptions};
use crate::display::MAX_PROFILE_BYTES;
@@ -57,47 +57,43 @@ pub struct ProofTable {
/// Grid size of [`ProofTable`]s.
pub const PROOF_GRID: usize = 33;
fn guarded<T>(f: impl FnOnce() -> Option<T>) -> Option<T> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).ok().flatten()
}
/// Build the proof table for an output profile. Errors say what's wrong with the file; nothing here
/// panics on a hostile profile.
pub fn proof_table(bytes: &[u8], intent: ProofIntent, paper_ink: bool) -> Result<ProofTable, String> {
if bytes.len() > MAX_PROFILE_BYTES {
return Err("the profile is too large".into());
}
let dev = guarded(|| ColorProfile::new_from_slice(bytes).ok()).ok_or("not a valid ICC profile")?;
let (layout, ch) = match dev.color_space {
DataColorSpace::Rgb => (Layout::Rgb, 3),
DataColorSpace::Cmyk => (Layout::Rgba, 4),
DataColorSpace::Gray => (Layout::Gray, 1),
let dev = Profile::parse(bytes).map_err(|_| "not a valid ICC profile")?;
let ch = match dev.color_space {
ColorSpace::Rgb => 3,
ColorSpace::Cmyk => 4,
ColorSpace::Gray => 1,
_ => return Err("only RGB, CMYK and grey output profiles can be proofed".into()),
};
let lin = crate::icc::linear_rec2020_profile();
let opts = |i| TransformOptions { rendering_intent: i, ..TransformOptions::default() };
let opts = |intent| TransformOptions { intent, bpc: false, precise_float: false };
let fwd_i = match intent {
ProofIntent::Perceptual => RenderingIntent::Perceptual,
ProofIntent::Relative => RenderingIntent::RelativeColorimetric,
ProofIntent::Perceptual => Intent::Perceptual,
ProofIntent::Relative => Intent::RelativeColorimetric,
};
let rel = RenderingIntent::RelativeColorimetric;
let fwd = guarded(|| lin.create_transform_f32(Layout::Rgb, &dev, layout, opts(fwd_i)).ok()).ok_or("can't convert to this profile")?;
let fwd_rel = guarded(|| lin.create_transform_f32(Layout::Rgb, &dev, layout, opts(rel)).ok()).ok_or("can't convert to this profile")?;
let back = guarded(|| dev.create_transform_f32(layout, &lin, Layout::Rgb, opts(rel)).ok()).ok_or("can't convert from this profile")?;
let rel = Intent::RelativeColorimetric;
let fwd = Transform::with_options(&lin, &dev, opts(fwd_i)).map_err(|_| "can't convert to this profile")?;
let fwd_rel = Transform::with_options(&lin, &dev, opts(rel)).map_err(|_| "can't convert to this profile")?;
let back = Transform::with_options(&dev, &lin, opts(rel)).map_err(|_| "can't convert from this profile")?;
let n = PROOF_GRID;
let grid: Vec<f32> = (0..n * n * n)
.flat_map(|i| [i / (n * n), (i / n) % n, i % n].map(|k| lightcraft_color::transfer::srgb_to_linear(k as f32 / (n - 1) as f32)))
.collect();
let round_trip = |there: &dyn moxcms::TransformExecutor<f32>| -> Option<Vec<f32>> {
let round_trip = |there: &Transform| -> Option<Vec<f32>> {
let mut device = vec![0f32; n * n * n * ch];
there.transform(&grid, &mut device).ok()?;
there.convert_f32(&grid, 3, &mut device, ch, false).ok()?;
let mut out = vec![0f32; n * n * n * 3];
back.transform(&device, &mut out).ok()?;
back.convert_f32(&device, ch, &mut out, 3, false).ok()?;
Some(out)
};
let sim = guarded(|| round_trip(fwd.as_ref())).ok_or("the profile's tables can't be applied")?;
let colorimetric = guarded(|| round_trip(fwd_rel.as_ref())).ok_or("the profile's tables can't be applied")?;
let sim = round_trip(&fwd).ok_or("the profile's tables can't be applied")?;
let colorimetric = round_trip(&fwd_rel).ok_or("the profile's tables can't be applied")?;
let paper = if paper_ink { paper_white(&dev) } else { [1.0; 3] };
let enc = |v: f32| lightcraft_color::transfer::linear_to_srgb(v.clamp(0.0, 1.0));
let data = (0..n * n * n)
@@ -112,13 +108,13 @@ pub fn proof_table(bytes: &[u8], intent: ProofIntent, paper_ink: bool) -> Result
}
/// The paper's white in linear Rec.2020 (screen white = (1, 1, 1)), from the media white point.
fn paper_white(p: &ColorProfile) -> [f32; 3] {
let Some(w) = p.media_white_point else { return [1.0; 3] };
fn paper_white(p: &Profile) -> [f32; 3] {
let w = p.white_point;
let to_xyz = bradford(D65, D50).mul(&REC2020.to_xyz());
let Some(from_xyz) = to_xyz.inverse() else { return [1.0; 3] };
// the PCS white is D50 = Rec.2020 (1, 1, 1) after adaptation; the paper is relative to it
let d50 = to_xyz.apply([1.0; 3]);
let s = [w.x / d50[0], w.y / d50[1], w.z / d50[2]];
let s = [w[0] / d50[0], w[1] / d50[1], w[2] / d50[2]];
let rgb = from_xyz.apply([d50[0] * s[0], d50[1] * s[1], d50[2] * s[2]]);
if rgb.iter().all(|v| v.is_finite() && *v > 0.05 && *v <= 1.5) { rgb.map(|v| (v as f32).min(1.0)) } else { [1.0; 3] }
}
@@ -148,10 +144,10 @@ mod tests {
#[test]
fn paper_white_dims_and_tints_white() {
let mut p = ColorProfile::new_from_slice(&crate::icc::write_named(NamedSpace::AdobeRgb)).unwrap();
let mut p = Profile::parse(&crate::icc::write_named(NamedSpace::AdobeRgb)).unwrap();
// a warm, slightly dull paper
p.media_white_point = Some(moxcms::Xyzd { x: 0.9642 * 0.92, y: 0.90, z: 0.8249 * 0.80 });
let bytes = p.encode().unwrap();
p.white_point = [0.9642 * 0.92, 0.90, 0.8249 * 0.80];
let bytes = p.with_encoded_bytes().to_bytes().to_vec();
let top = PROOF_GRID - 1;
let plain = proof_table(&bytes, ProofIntent::Perceptual, false).unwrap();
let paper = proof_table(&bytes, ProofIntent::Perceptual, true).unwrap();
+65 -80
View File
@@ -40,36 +40,46 @@ impl<'a> Rd<'a> {
}
}
/// The header, colour mode data and image resources (`craft-psd`), with a reader at the layer and mask section.
struct Start<'a> {
psb: bool,
channels: usize,
width: usize,
height: usize,
depth: u16,
mode: u16,
head: craft_psd::Head,
r: Rd<'a>,
}
fn start<'a>(bytes: &'a [u8], opts: &DecodeOptions) -> Result<Start<'a>> {
// 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)?;
}
let head = craft_psd::Head::from_bytes(bytes).map_err(|e| match e {
craft_psd::PsdError::UnexpectedEof { .. } => err("truncated"),
e => err(&e.to_string()),
})?;
let h = &head.header;
check_size(F, u64::from(h.width), u64::from(h.height), opts)?;
let p = usize::try_from(head.layer_section_offset).map_err(|_| err("truncated"))?;
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(),
r: Rd { b: bytes, p },
head,
})
}
pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
let mut r = Rd { b: bytes, p: 0 };
if r.take(4)? != b"8BPS" {
return Err(err("bad signature"));
}
let version = r.u16()?;
let psb = match version {
1 => false,
2 => true,
_ => return Err(err("bad version")),
};
r.take(6)?;
let channels = r.u16()? as usize;
let height = r.u32()? as usize;
let width = r.u32()? as usize;
let depth = r.u16()?;
let mode = r.u16()?;
check_size(F, width as u64, height as u64, opts)?;
if channels == 0 || channels > 56 {
return Err(err("bad channel count"));
}
// Colour mode data (palette for indexed).
let cm_len = r.u32()? as usize;
let color_mode_data = r.take(cm_len)?;
// Image resources.
let res_len = r.u32()? as usize;
let res = r.take(res_len)?;
let (icc, exif, xmp) = resources(res);
let Start { psb, channels, width, height, depth, mode, head, mut r } = start(bytes, opts)?;
let color_mode_data = head.color_mode_data.as_slice();
let (icc, exif, xmp) = resources(&head);
// Layer and mask information: only the layer count sign matters (merged transparency).
let lm_len = if psb { r.u64()? } else { u64::from(r.u32()?) };
@@ -342,29 +352,9 @@ fn packbits(src: &[u8], out: &mut Vec<u8>) {
/// 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 mut r = Rd { b: bytes, p: 0 };
if r.take(4)? != b"8BPS" {
return Err(err("bad signature"));
}
let psb = match r.u16()? {
1 => false,
2 => true,
_ => return Err(err("bad version")),
};
r.take(6)?;
let channels = r.u16()? as usize;
let height = r.u32()? as usize;
let width = r.u32()? as usize;
let depth = r.u16()?;
let mode = r.u16()?;
check_size(F, width as u64, height as u64, &DecodeOptions::default())?;
if channels == 0 || channels > 56 {
return Err(err("bad channel count"));
}
let cm_len = r.u32()? as usize;
let color_mode_data = r.take(cm_len)?;
let res_len = r.u32()? as usize;
let (_, exif, _) = resources(r.take(res_len)?);
let Start { psb, channels, width, height, depth, mode, head, mut r } = start(bytes, &DecodeOptions::default())?;
let color_mode_data = head.color_mode_data.as_slice();
let (_, exif, _) = resources(&head);
let lm_len = if psb { r.u64()? as usize } else { r.u32()? as usize };
r.take(lm_len)?;
let compression = r.u16()?;
@@ -444,28 +434,12 @@ fn unpackbits(mut src: &[u8], row: &mut [u8]) -> Result<()> {
Ok(())
}
fn resources(mut b: &[u8]) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<String>) {
let (mut icc, mut exif, mut xmp) = (None, None, None);
while b.len() >= 12 && &b[0..4] == b"8BIM" {
let id = u16::from_be_bytes([b[4], b[5]]);
let name_len = b[6] as usize;
let name_total = (1 + name_len + 1) & !1;
let p = 6 + name_total;
if p + 4 > b.len() {
break;
}
let size = u32::from_be_bytes([b[p], b[p + 1], b[p + 2], b[p + 3]]) as usize;
let start = p + 4;
let Some(data) = start.checked_add(size).and_then(|end| b.get(start..end)) else { break };
match id {
1039 => icc = Some(data.to_vec()),
1058 => exif = Some(if data.starts_with(b"Exif\0\0") { data[6..].to_vec() } else { data.to_vec() }),
1060 => xmp = Some(String::from_utf8_lossy(data).trim_end_matches('\0').to_string()),
_ => {}
}
let next = start + ((size + 1) & !1);
b = b.get(next..).unwrap_or(&[]);
}
/// ICC (1039), EXIF (1058, without its optional `Exif\0\0` prefix) and XMP (1060) resources; the last of each id.
fn resources(head: &craft_psd::Head) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<String>) {
let last = |id: u16| head.resources.iter().rev().find(|r| r.id == id).map(|r| r.data.as_slice());
let icc = last(1039).map(<[u8]>::to_vec);
let exif = last(1058).map(|d| d.strip_prefix(b"Exif\0\0").unwrap_or(d).to_vec());
let xmp = last(1060).map(|d| String::from_utf8_lossy(d).trim_end_matches('\0').to_string());
(icc, exif, xmp)
}
@@ -514,8 +488,8 @@ mod tests {
#[test]
fn huge_rle_with_truncated_count_table_is_rejected_before_allocating() {
// 1 × 2^30 px, 56 channels: the row table alone would be 56 Gi entries; the file has 4 bytes.
let mut b = header(56, 1, 1 << 30, 32, 3, 1);
// 1 × 300 000 px, 56 channels: the row table alone would be 16.8 M entries; the file has 4 bytes.
let mut b = header(56, 1, 300_000, 32, 3, 1);
b.extend_from_slice(&[0, 0, 0, 0]);
let e = decode(&b, &DecodeOptions::default()).unwrap_err();
assert!(matches!(e, Error::Malformed(_, ref m) if m == "truncated"), "{e:?}");
@@ -523,18 +497,29 @@ mod tests {
#[test]
fn huge_rle_of_empty_rows_is_rejected_before_allocating() {
// 2^30 × 1 px RGB at 32 bits: every row count is 0, which used to zero-pad 3 × 4 GiB.
let mut b = header(3, 1 << 30, 1, 32, 3, 1);
// 300 000 × 1 px RGB at 32 bits: every row count is 0, which used to zero-pad 3 × 1.2 MB.
let mut b = header(3, 300_000, 1, 32, 3, 1);
b.extend_from_slice(&[0; 6]);
let e = decode(&b, &DecodeOptions::default()).unwrap_err();
assert!(matches!(e, Error::Malformed(_, ref m) if m.contains("too short")), "{e:?}");
// 1 Gpx RGB 8-bit whose (plausible) row counts claim more data than the file holds.
let mut b = header(3, 1 << 20, 1 << 10, 8, 3, 1);
// 0.27 Gpx RGB 8-bit whose (plausible) row counts claim more data than the file holds.
let mut b = header(3, 1 << 18, 1 << 10, 8, 3, 1);
b.extend_from_slice(&[0xFF; 3 * 1024 * 2]);
let e = decode(&b, &DecodeOptions::default()).unwrap_err();
assert!(matches!(e, Error::Malformed(_, ref m) if m == "truncated"), "{e:?}");
}
#[test]
fn a_damaged_resource_section_is_malformed() {
// a resource section of 4 bytes that is not an `8BIM` record
let mut b = header(3, 1, 1, 8, 3, 0);
b[30..34].copy_from_slice(&4u32.to_be_bytes());
b.splice(34..34, *b"JUNK");
let e = decode(&b, &DecodeOptions::default()).unwrap_err();
assert!(matches!(e, Error::Malformed(_, ref m) if m.contains("signature")), "{e:?}");
assert!(super::header(&b).is_err());
}
#[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.
+69 -219
View File
@@ -1,12 +1,7 @@
//! TIFF decode via the `tiff` crate: 1/2/4/8/16/32/64-bit integer, 16/32/64-bit float, gray/RGB/CMYK,
//! alpha (associated or not), ICC (34675), XMP (700), orientation (274). First image only. Palette
//! (indexed-colour) images are refused by the `tiff` crate itself, on every read path.
//! TIFF decode via `craft-image-codecs` and header/IFD inspection via `craft-tiff`.
use crate::convert::{Buf, Meta, Model, Raw, check_size, finish};
use crate::{DecodeOptions, Decoded, Error, Format, Result};
use tiff::ColorType;
use tiff::decoder::{Decoder, DecodingResult, Limits};
use tiff::tags::Tag;
const F: Format = Format::Tiff;
@@ -15,233 +10,88 @@ fn err(e: impl std::fmt::Display) -> Error {
}
pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
let mut d = Decoder::new(std::io::Cursor::new(bytes)).map_err(err)?.with_limits(limits(opts));
let (w, h) = d.dimensions().map_err(err)?;
let (tiff, complete) = craft_tiff::Tiff::parse_with_status(bytes, &Default::default()).map_err(err)?;
if !complete {
return Err(err("truncated TIFF"));
}
let ifd = tiff.ifds.first().ok_or_else(|| err("no IFD"))?;
let info = ifd.image().map_err(err)?;
check_size(F, info.width as u64, info.height as u64, opts)?;
let orientation = ifd.u16(craft_tiff::tags::ORIENTATION);
let bit_depth = info.bits_per_sample.first().copied().unwrap_or(8) as u8;
let ic_opts = craft_image_codecs::DecodeOptions {
limits: craft_image_codecs::Limits {
max_width: u32::MAX,
max_height: u32::MAX,
max_pixels: opts.max_pixels,
max_alloc: opts.max_pixels.saturating_mul(32),
},
keep_orientation: true,
};
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Tiff, bytes, &ic_opts).map_err(|e| match e {
craft_image_codecs::CodecError::LimitExceeded(_) => Error::TooLarge(info.width as u64, info.height as u64),
craft_image_codecs::CodecError::Unsupported { .. } => Error::Unsupported(F, "unsupported TIFF"),
other => err(other),
})?;
if img.warnings.iter().any(|w| matches!(w, craft_image_codecs::DecodeWarning::Truncated { .. })) {
return Err(err("truncated: image data past the end of the file"));
}
let (w, h) = (img.width(), img.height());
check_size(F, w as u64, h as u64, opts)?;
let ct = d.colortype().map_err(err)?;
let icc = tag_bytes(&mut d, Tag::IccProfile);
let xmp = tag_bytes(&mut d, Tag::from_u16_exhaustive(700)).map(|v| String::from_utf8_lossy(&v).trim_end_matches('\0').to_string());
let orientation = d.get_tag_u32(Tag::Orientation).ok().map(|v| v as u16);
let planar = d.get_tag_u32(Tag::PlanarConfiguration).ok() == Some(2);
let extra = d.get_tag_u16_vec(Tag::ExtraSamples).ok().unwrap_or_default();
let colormap = d.get_tag_u16_vec(Tag::ColorMap).ok();
let compression = d.get_tag_u32(Tag::Compression).ok();
let (model, n_color, n_samples, bits) = layout(ct, compression, planar)?;
let has_alpha = n_samples > n_color && !matches!(ct, ColorType::Palette(_));
let premultiplied = has_alpha && extra.first() == Some(&1);
let res = d.read_image().map_err(err)?;
let (wu, hu) = (w as usize, h as usize);
let n = wu * hu;
let mut buf = match res {
DecodingResult::U8(v) if bits < 8 => Buf::U8(unpack(&v, wu, hu, n_samples, bits)?),
DecodingResult::U8(v) => Buf::U8(v),
DecodingResult::U16(v) => Buf::U16(v),
// Rare integer widths: keep 16 significant bits (plenty for display-referred data).
DecodingResult::U32(v) => Buf::U16(v.into_iter().map(|x| (x >> 16) as u16).collect()),
DecodingResult::U64(v) => Buf::U16(v.into_iter().map(|x| (x >> 48) as u16).collect()),
DecodingResult::I8(v) => Buf::U8(v.into_iter().map(|x| (x.max(0) as u8) << 1).collect()),
DecodingResult::I16(v) => Buf::U16(v.into_iter().map(|x| (x.max(0) as u16) << 1).collect()),
DecodingResult::I32(v) => Buf::U16(v.into_iter().map(|x| (x.max(0) >> 15) as u16).collect()),
DecodingResult::I64(v) => Buf::U16(v.into_iter().map(|x| (x.max(0) >> 47) as u16).collect()),
DecodingResult::F16(v) => Buf::F32(v.into_iter().map(|x| x.to_f32()).collect()),
DecodingResult::F32(v) => Buf::F32(v),
DecodingResult::F64(v) => Buf::F32(v.into_iter().map(|x| x as f32).collect()),
let model = match img.layout() {
craft_image_codecs::ChannelLayout::Gray | craft_image_codecs::ChannelLayout::GrayA => Model::Gray,
craft_image_codecs::ChannelLayout::Rgb | craft_image_codecs::ChannelLayout::Rgba => Model::Rgb,
craft_image_codecs::ChannelLayout::Cmyk | craft_image_codecs::ChannelLayout::CmykA => Model::Cmyk,
craft_image_codecs::ChannelLayout::Lab | craft_image_codecs::ChannelLayout::LabA => {
return Err(Error::Unsupported(F, "CIE L*a*b* TIFF"));
}
};
let bit_depth = bits;
if planar && n_samples > 1 {
buf = interleave(buf, n, n_samples);
}
// Palette → 16-bit RGB.
if let ColorType::Palette(b) = ct {
let map = colormap.ok_or_else(|| err("palette image without ColorMap"))?;
let entries = 1usize << b.min(16);
if map.len() < 3 * entries {
return Err(err("short ColorMap"));
let alpha = img.layout().has_alpha();
let buf = match img.sample_type() {
craft_image_codecs::SampleType::U8 => Buf::U8(img.as_u8().ok_or_else(|| err("expected 8-bit samples"))?.to_vec()),
craft_image_codecs::SampleType::U16 => Buf::U16(img.to_u16_samples().ok_or_else(|| err("expected 16-bit samples"))?),
craft_image_codecs::SampleType::F16 => {
let bits = img.to_f16_samples().ok_or_else(|| err("expected 16-bit float samples"))?;
Buf::F32(bits.into_iter().map(|h| h.to_f32()).collect())
}
let idx: Vec<usize> = match &buf {
Buf::U8(v) => v.iter().map(|&i| i as usize).collect(),
Buf::U16(v) => v.iter().map(|&i| i as usize).collect(),
Buf::F32(_) => return Err(err("float palette")),
};
let mut out = Vec::with_capacity(n * 3);
for &i in idx.iter().take(n) {
let i = i.min(entries - 1);
out.extend_from_slice(&[map[i], map[entries + i], map[2 * entries + i]]);
}
buf = Buf::U16(out);
let raw = Raw { width: wu, height: hu, model: Model::Rgb, alpha: false, premultiplied: false, buf, bit_depth };
let meta = Meta { icc, xmp, orientation, ..Default::default() };
return finish(F, raw, meta, (w, h), opts);
}
craft_image_codecs::SampleType::F32 => Buf::F32(img.to_f32_samples().ok_or_else(|| err("expected 32-bit float samples"))?),
};
// WhiteIsZero needs nothing here: the `tiff` crate inverts those samples as it reads them (and
// refuses WhiteIsZero layouts it can't invert), so inverting again would show a negative.
// Drop extra samples beyond colour + one alpha.
let keep = n_color + has_alpha as usize;
if n_samples != keep {
buf = select_channels(buf, n, n_samples, keep);
}
let raw = Raw { width: wu, height: hu, model, alpha: has_alpha, premultiplied, buf, bit_depth };
let meta = Meta { icc, xmp, orientation, ..Default::default() };
let raw = Raw { width: w as usize, height: h as usize, model, alpha, premultiplied: false, buf, bit_depth };
let meta = Meta { icc: img.icc, xmp: img.meta.xmp, orientation, ..Default::default() };
finish(F, raw, meta, (w, h), opts)
}
fn limits(opts: &DecodeOptions) -> Limits {
let mut limits = Limits::default();
limits.decoding_buffer_size = opts.max_pixels.saturating_mul(4 * 8).min(usize::MAX as u64) as usize;
// A strip or tile whose declared byte count exceeds this is refused: the default 128 MiB refuses a
// single-strip uncompressed 16-bit export of ~22 MP (#1983). Raised to the decoded image's cap
// (32 bytes per allowed pixel), never lowered: a strip or tile can outgrow the pixels it shows
// (JPEG headers, padding to the tile size).
limits.intermediate_buffer_size = limits.intermediate_buffer_size.max(limits.decoding_buffer_size);
limits.ifd_value_size = 32 << 20;
limits
}
/// The sample layout of a colour type we can decode: (model, colour samples, samples per pixel,
/// bits per sample).
fn layout(ct: ColorType, compression: Option<u32>, planar: bool) -> Result<(Model, usize, usize, u8)> {
let l = match ct {
ColorType::Gray(b) => (Model::Gray, 1, 1, b),
ColorType::GrayA(b) => (Model::Gray, 1, 2, b),
ColorType::RGB(b) => (Model::Rgb, 3, 3, b),
ColorType::RGBA(b) => (Model::Rgb, 3, 4, b),
ColorType::CMYK(b) => (Model::Cmyk, 4, 4, b),
ColorType::CMYKA(b) => (Model::Cmyk, 4, 5, b),
ColorType::Palette(b) => (Model::Rgb, 1, 1, b),
// JPEG-compressed YCbCr is converted to RGB by the JPEG decoder.
ColorType::YCbCr(b) if compression == Some(7) => (Model::Rgb, 3, 3, b),
ColorType::Multiband { bit_depth, num_samples } if num_samples >= 3 => (Model::Rgb, 3, num_samples as usize, bit_depth),
ColorType::Multiband { bit_depth, num_samples } if num_samples >= 1 => (Model::Gray, 1, num_samples as usize, bit_depth),
other => return Err(Error::Unsupported(F, unsupported_name(other))),
};
if l.3 < 8 && planar && l.2 > 1 {
return Err(Error::Unsupported(F, "planar TIFF with samples narrower than a byte"));
}
Ok(l)
}
/// Stored dimensions and orientation from the first IFD, without reading the image data. Refused,
/// as a decode would refuse it: a layout or compression we can't decode, or strips/tiles that
/// start 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 d = Decoder::new(std::io::Cursor::new(bytes)).map_err(err)?.with_limits(limits(&DecodeOptions::default()));
let (w, h) = d.dimensions().map_err(err)?;
check_size(F, w as u64, h as u64, &DecodeOptions::default())?;
let ct = d.colortype().map_err(err)?;
let compression = d.get_tag_u32(Tag::Compression).ok();
let planar = d.get_tag_u32(Tag::PlanarConfiguration).ok() == Some(2);
layout(ct, compression, planar)?;
// what this build of the `tiff` crate decompresses: none, CCITT G4, LZW, JPEG, Deflate, PackBits
if !matches!(compression.unwrap_or(1), 1 | 4 | 5 | 7 | 8 | 32773 | 32946) {
let (tiff, complete) = craft_tiff::Tiff::parse_with_status(bytes, &Default::default()).map_err(err)?;
if !complete {
return Err(err("truncated TIFF"));
}
let ifd = tiff.ifds.first().ok_or_else(|| err("no IFD"))?;
let info = ifd.image().map_err(err)?;
check_size(F, info.width as u64, info.height as u64, &DecodeOptions::default())?;
let bits = info.bits_per_sample.first().copied().unwrap_or(1);
if bits < 8 && info.planar == 2 && info.samples_per_pixel > 1 {
return Err(Error::Unsupported(F, "planar TIFF with samples narrower than a byte"));
}
if !matches!(info.photometric, 0 | 1 | 2 | 3 | 5) && !(info.photometric == 6 && info.compression == 7) {
return Err(Error::Unsupported(F, "colour type"));
}
// what `craft-image-codecs`'s TIFF decoder decompresses: none, CCITT G4, LZW, JPEG, Deflate, PackBits
if !matches!(info.compression, 1 | 4 | 5 | 7 | 8 | 32773 | 32946) {
return Err(Error::Unsupported(F, "compression method"));
}
let chunks = |offsets: Tag, counts: Tag, d: &mut Decoder<std::io::Cursor<&[u8]>>| {
Some((d.get_tag_u64_vec(offsets).ok()?, d.get_tag_u64_vec(counts).ok()?))
};
let (offsets, counts) = chunks(Tag::StripOffsets, Tag::StripByteCounts, &mut d)
.or_else(|| chunks(Tag::TileOffsets, Tag::TileByteCounts, &mut d))
.ok_or_else(|| err("no image data"))?;
// Only where each chunk starts: some writers overstate StripByteCounts, and the `tiff` crate
// decodes such files (it stops once it has the pixels), so a chunk's end proves nothing.
let len = bytes.len() as u64;
if offsets.is_empty() || offsets.iter().zip(&counts).any(|(&o, &c)| c > 0 && o >= len) {
if info.offsets.is_empty()
|| info.offsets.iter().zip(&info.byte_counts).any(|(&o, &c)| c > 0 && (o >= len || (info.compression == 1 && o.saturating_add(c) > len)))
{
return Err(err("truncated: image data past the end of the file"));
}
let orientation = d.get_tag_u32(Tag::Orientation).ok().map(|v| v as u16).filter(|o| (1..=8).contains(o)).unwrap_or(1);
Ok((w, h, orientation))
}
/// A BYTE/UNDEFINED tag as bytes (the decoder may surface unknown byte tags as unsigned values).
fn tag_bytes<R: std::io::Read + std::io::Seek>(d: &mut Decoder<R>, tag: Tag) -> Option<Vec<u8>> {
use tiff::decoder::ifd::Value;
fn byte(v: &Value) -> Option<u8> {
match v {
Value::Byte(b) => Some(*b),
Value::Unsigned(u) => u8::try_from(*u).ok(),
Value::Short(u) => u8::try_from(*u).ok(),
Value::SignedByte(b) => Some(*b as u8),
_ => None,
}
}
match d.find_tag(tag).ok()?? {
Value::List(v) => v.iter().map(byte).collect(),
Value::Ascii(s) => Some(s.into_bytes()),
v => byte(&v).map(|b| vec![b]),
}
}
fn unsupported_name(ct: ColorType) -> &'static str {
match ct {
ColorType::Lab(_) => "CIE L*a*b* TIFF",
ColorType::YCbCr(_) => "uncompressed YCbCr TIFF",
_ => "colour type",
}
}
/// Samples narrower than a byte (1-bit bilevel and fax scans, 2- and 4-bit gray) arrive packed, most
/// significant bits first, each row padded to a whole byte. Spread them out one per byte, scaled to
/// 0–255 like any 8-bit sample.
fn unpack(packed: &[u8], width: usize, height: usize, samples: usize, bits: u8) -> Result<Vec<u8>> {
if !matches!(bits, 1 | 2 | 4) {
return Err(Error::Unsupported(F, "TIFF samples of 3, 5, 6 or 7 bits"));
}
let bits = bits as usize;
let per_row = width.checked_mul(samples).ok_or_else(|| err("row too wide"))?;
let row_bytes = per_row.checked_mul(bits).ok_or_else(|| err("row too wide"))?.div_ceil(8);
if row_bytes == 0 || packed.len() / row_bytes < height {
return Err(err("sample buffer too short"));
}
let max = (1u8 << bits) - 1;
let scale = 255 / max; // 255, 85, 17: exact
let mut out = Vec::with_capacity(per_row.saturating_mul(height));
for row in packed.chunks_exact(row_bytes).take(height) {
let values = row.iter().flat_map(|&b| (1..=8 / bits).map(move |i| (b >> (8 - bits * i)) & max));
out.extend(values.take(per_row).map(|v| v * scale));
}
Ok(out)
}
fn interleave(buf: Buf, n: usize, s: usize) -> Buf {
fn go<T: Copy + Default>(v: Vec<T>, n: usize, s: usize) -> Vec<T> {
if v.len() < n * s {
return v;
}
let mut out = vec![T::default(); n * s];
for c in 0..s {
for i in 0..n {
out[i * s + c] = v[c * n + i];
}
}
out
}
match buf {
Buf::U8(v) => Buf::U8(go(v, n, s)),
Buf::U16(v) => Buf::U16(go(v, n, s)),
Buf::F32(v) => Buf::F32(go(v, n, s)),
}
}
fn select_channels(buf: Buf, n: usize, s: usize, keep: usize) -> Buf {
fn go<T: Copy>(v: Vec<T>, n: usize, s: usize, keep: usize) -> Vec<T> {
if v.len() < n * s {
return v;
}
let mut out = Vec::with_capacity(n * keep);
for px in v.chunks_exact(s).take(n) {
out.extend_from_slice(&px[..keep]);
}
out
}
match buf {
Buf::U8(v) => Buf::U8(go(v, n, s, keep)),
Buf::U16(v) => Buf::U16(go(v, n, s, keep)),
Buf::F32(v) => Buf::F32(go(v, n, s, keep)),
}
let orientation = ifd.u16(craft_tiff::tags::ORIENTATION).filter(|o| (1..=8).contains(o)).unwrap_or(1);
Ok((info.width, info.height, orientation))
}
+36 -23
View File
@@ -1,4 +1,4 @@
//! WebP decode via `image-webp` (lossy + lossless, alpha, ICCP/EXIF/XMP chunks; first frame of
//! WebP decode via `craft-image-codecs` (lossy + lossless, alpha, ICCP/EXIF/XMP chunks; first frame of
//! animations).
use crate::convert::{Buf, Meta, Model, Raw, check_size, finish};
@@ -11,20 +11,28 @@ fn err(e: impl std::fmt::Display) -> Error {
}
pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
let mut d = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).map_err(err)?;
// RIFF chunk lengths are untrusted. Metadata cannot exceed the input;
// otherwise a tiny truncated file can request gigabytes before read_exact fails.
d.set_memory_limit(bytes.len());
let (w, h) = d.dimensions();
let ic_opts = craft_image_codecs::DecodeOptions {
limits: craft_image_codecs::Limits {
max_width: u32::MAX,
max_height: u32::MAX,
max_pixels: opts.max_pixels,
max_alloc: opts.max_pixels.saturating_mul(8),
},
keep_orientation: true,
};
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::WebP, bytes, &ic_opts).map_err(|e| match e {
craft_image_codecs::CodecError::LimitExceeded(_) => Error::TooLarge(0, 0),
other => err(other),
})?;
let (w, h) = (img.width(), img.height());
check_size(F, w as u64, h as u64, opts)?;
let alpha = d.has_alpha();
let size = d.output_buffer_size().ok_or_else(|| err("buffer size overflow"))?;
let mut buf = vec![0u8; size];
d.read_image(&mut buf).map_err(err)?;
let icc = d.icc_profile().ok().flatten();
let exif = d.exif_metadata().ok().flatten().map(|e| if e.starts_with(b"Exif\0\0") { e[6..].to_vec() } else { e });
let xmp = d.xmp_metadata().ok().flatten().map(|x| String::from_utf8_lossy(&x).trim_end_matches('\0').to_string());
let raw = Raw { width: w as usize, height: h as usize, model: Model::Rgb, alpha, premultiplied: false, buf: Buf::U8(buf), bit_depth: 8 };
let alpha = img.layout().has_alpha();
let model = if img.layout().is_gray() { Model::Gray } else { Model::Rgb };
let buf = Buf::U8(img.as_u8().ok_or_else(|| err("expected 8-bit WebP samples"))?.to_vec());
let icc = img.icc;
let exif = img.meta.exif.map(|e| if e.starts_with(b"Exif\0\0") { e[6..].to_vec() } else { e });
let xmp = img.meta.xmp.map(|x| x.trim_end_matches('\0').to_string());
let raw = Raw { width: w as usize, height: h as usize, model, alpha, premultiplied: false, buf, bit_depth: 8 };
finish(F, raw, Meta { icc, exif, xmp, ..Default::default() }, (w, h), opts)
}
@@ -34,23 +42,28 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
/// itself is not checked.
pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> {
let mut p = 12usize;
loop {
let Some(h) = bytes.get(p..p.saturating_add(8)) else { return Err(err("no image data")) };
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"));
}
break;
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);
}
let mut d = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).map_err(err)?;
d.set_memory_limit(bytes.len());
let (w, h) = d.dimensions();
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) };
check_size(F, w as u64, h as u64, &DecodeOptions::default())?;
let exif = d.exif_metadata().ok().flatten();
let exif = exif.as_deref().map(|e| e.strip_prefix(b"Exif\0\0").unwrap_or(e));
Ok((w, h, exif.map(crate::exif::summarize).unwrap_or_default().orientation.unwrap_or(1)))
Ok((w, h, orientation))
}
+12 -9
View File
@@ -124,15 +124,18 @@ fn system_icc_profiles() {
assert_eq!(info.model, IccColorModel::Cmyk);
assert_eq!(info.kind, IccKind::NeedsCms);
// CMYK TIFF tagged with it: paper white stays near white, 100% K near black.
use tiff::encoder::{TiffEncoder, colortype};
let mut cur = std::io::Cursor::new(Vec::new());
{
let mut enc = TiffEncoder::new(&mut cur).unwrap();
let mut im = enc.new_image::<colortype::CMYK8>(2, 1).unwrap();
im.encoder().write_tag(tiff::tags::Tag::IccProfile, &b[..]).unwrap();
im.write_data(&[0u8, 0, 0, 0, 0, 0, 0, 255]).unwrap();
}
let d = decode(&cur.into_inner(), DecodeOptions::default()).unwrap();
let mut ifd = craft_tiff::IfdBuilder::new()
.with(craft_tiff::tags::IMAGE_WIDTH, craft_tiff::Value::Long(vec![2]))
.with(craft_tiff::tags::IMAGE_LENGTH, craft_tiff::Value::Long(vec![1]))
.with(craft_tiff::tags::BITS_PER_SAMPLE, craft_tiff::Value::Short(vec![8, 8, 8, 8]))
.with(craft_tiff::tags::COMPRESSION, craft_tiff::Value::Short(vec![1]))
.with(craft_tiff::tags::PHOTOMETRIC, craft_tiff::Value::Short(vec![5]))
.with(craft_tiff::tags::SAMPLES_PER_PIXEL, craft_tiff::Value::Short(vec![4]))
.with(craft_tiff::tags::PLANAR_CONFIGURATION, craft_tiff::Value::Short(vec![1]))
.with(craft_tiff::tags::ICC_PROFILE, craft_tiff::Value::Undefined(b.clone()));
ifd.set_image(craft_tiff::ImageData::Strips { rows_per_strip: 1, strips: vec![vec![0u8, 0, 0, 0, 0, 0, 0, 255]] });
let tif = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap();
let d = decode(&tif, DecodeOptions::default()).unwrap();
assert_eq!(d.space.origin, SpaceOrigin::IccCms);
let w = d.image.get(0, 0);
let k = d.image.get(1, 0);
+36 -31
View File
@@ -44,7 +44,11 @@ fn float_tiff_nonfinite_gray_and_icc_curves_match_clipped_samples() {
Some(icc::write_named(NamedSpace::Srgb)),
Some(icc::write_matrix_trc(&lightcraft_color::SRGB, &Trc::Gamma(2.0))),
Some(icc::write_matrix_trc(&lightcraft_color::SRGB, &Trc::Table(vec![0, 16384, 65535]))),
Some(moxcms::ColorProfile::new_gray_with_gamma(2.0).encode().unwrap()),
Some({
let mut p = craft_cms::Builtin::GrayGamma22.profile().clone();
p.gray_trc = Some(craft_cms::Curve::Gamma(2.0));
p.with_encoded_bytes().to_bytes().to_vec()
}),
Some(b"invalid ICC profile".to_vec()),
];
for channels in [1, 3] {
@@ -77,42 +81,43 @@ fn float_tiff_nonfinite_alpha_is_finite_and_bounded() {
assert!(decoded.to_working().data.iter().flatten().all(|v| v.is_finite()));
// Associated alpha takes the same path before unpremultiplication.
let mut cursor = std::io::Cursor::new(Vec::new());
{
use tiff::encoder::{TiffEncoder, colortype};
let mut encoder = TiffEncoder::new(&mut cursor).unwrap();
let mut image = encoder.new_image::<colortype::RGBA32Float>(2, 1).unwrap();
image.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[1u16][..]).unwrap();
image.write_data(&[f32::INFINITY, f32::NAN, f32::NEG_INFINITY, 0.5, 1.0, 2.0, 3.0, 0.5]).unwrap();
let mut strip = Vec::new();
for s in [f32::INFINITY, f32::NAN, f32::NEG_INFINITY, 0.5, 1.0, 2.0, 3.0, 0.5] {
strip.extend_from_slice(&s.to_le_bytes());
}
let decoded = decode(&cursor.into_inner(), DecodeOptions::default()).unwrap();
let mut ifd = craft_tiff::IfdBuilder::new()
.with(craft_tiff::tags::IMAGE_WIDTH, craft_tiff::Value::Long(vec![2]))
.with(craft_tiff::tags::IMAGE_LENGTH, craft_tiff::Value::Long(vec![1]))
.with(craft_tiff::tags::BITS_PER_SAMPLE, craft_tiff::Value::Short(vec![32, 32, 32, 32]))
.with(craft_tiff::tags::COMPRESSION, craft_tiff::Value::Short(vec![1]))
.with(craft_tiff::tags::PHOTOMETRIC, craft_tiff::Value::Short(vec![2]))
.with(craft_tiff::tags::SAMPLES_PER_PIXEL, craft_tiff::Value::Short(vec![4]))
.with(craft_tiff::tags::PLANAR_CONFIGURATION, craft_tiff::Value::Short(vec![1]))
.with(craft_tiff::tags::SAMPLE_FORMAT, craft_tiff::Value::Short(vec![3, 3, 3, 3]))
.with(craft_tiff::tags::EXTRA_SAMPLES, craft_tiff::Value::Short(vec![1]));
ifd.set_image(craft_tiff::ImageData::Strips { rows_per_strip: 1, strips: vec![strip] });
let tif = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap();
let decoded = decode(&tif, DecodeOptions::default()).unwrap();
assert_eq!(decoded.alpha.as_ref().unwrap().data, [0.5, 0.5]);
assert_eq!(decoded.image.data, [[2.0, 0.0, 0.0], [2.0, 4.0, 6.0]]);
assert_eq!(decoded.image.data, [[1.0, 0.0, 0.0], [2.0, 4.0, 6.0]]);
}
fn lut_profile() -> Vec<u8> {
use moxcms::{ColorProfile, LutMultidimensionalType, LutWarehouse, Matrix3d, ToneReprCurve, Vector3d, Xyzd};
let mut profile = ColorProfile::new_srgb();
profile.cicp = None;
profile.red_colorant = Xyzd::default();
profile.green_colorant = Xyzd::default();
profile.blue_colorant = Xyzd::default();
profile.red_trc = None;
profile.green_trc = None;
profile.blue_trc = None;
use craft_cms::pipeline::Stage;
use craft_cms::profile::{Lut, LutKind};
let mut profile = craft_cms::Builtin::Srgb.profile().clone();
profile.matrix = None;
profile.trc = None;
let m: Vec<f64> = NamedSpace::Srgb.to_xyz_d50().0.iter().flatten().map(|&v| v * 32768.0 / 65535.0).collect();
let ident = vec![craft_cms::Curve::Identity; 3];
// A procedural mAB profile without a CLUT: linear RGB to D50 XYZ, then identity curves.
profile.lut_a_to_b_colorimetric = Some(LutWarehouse::Multidimensional(LutMultidimensionalType {
num_input_channels: 3,
num_output_channels: 3,
grid_points: [0; 16],
clut: None,
a_curves: vec![],
m_curves: vec![ToneReprCurve::Parametric(vec![1.0]); 3],
matrix: Matrix3d { v: NamedSpace::Srgb.to_xyz_d50().0.map(|r| r.map(|v| v * 32768.0 / 65535.0)) },
b_curves: vec![ToneReprCurve::Parametric(vec![1.0]); 3],
bias: Vector3d::default(),
}));
profile.encode().unwrap()
profile.a2b[1] = Some(Lut {
kind: LutKind::Ab,
inputs: 3,
outputs: 3,
stages: vec![Stage::Curves(ident.clone()), Stage::Matrix { rows: 3, cols: 3, m, offset: vec![0.0; 3] }, Stage::Curves(ident)],
});
profile.with_encoded_bytes().to_bytes().to_vec()
}
#[test]
+5 -5
View File
@@ -122,11 +122,11 @@ fn tiny_gif_and_bmp_declaring_a_gigapixel_canvas_are_refused_before_allocating()
fn large_gif_and_bmp_sizes_come_from_the_header() {
let (w, h) = (2_100u32, 2_000u32);
let rgb = vec![90u8; (w * h * 3) as usize];
let mut bmp = Vec::new();
image::codecs::bmp::BmpEncoder::new(&mut bmp).encode(&rgb, w, h, image::ExtendedColorType::Rgb8).unwrap();
let mut gif = Vec::new();
let frame = image::RgbaImage::from_pixel(w, h, image::Rgba([90, 90, 90, 255]));
image::codecs::gif::GifEncoder::new(&mut gif).encode_frame(image::Frame::new(frame)).unwrap();
let bmp_img = craft_image_codecs::Image::from_u8(w, h, craft_image_codecs::ChannelLayout::Rgb, rgb).unwrap();
let bmp = craft_image_codecs::encode(&bmp_img, craft_image_codecs::Format::Bmp, &craft_image_codecs::EncodeOptions::default()).unwrap();
let rgba = [90, 90, 90, 255].repeat((w * h) as usize);
let gif_img = craft_image_codecs::Image::from_u8(w, h, craft_image_codecs::ChannelLayout::Rgba, rgba).unwrap();
let gif = craft_image_codecs::encode(&gif_img, craft_image_codecs::Format::Gif, &craft_image_codecs::EncodeOptions::default()).unwrap();
for (name, bytes) in [("bmp", bmp), ("gif", gif)] {
let header = read_header(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
assert_eq!((header.width, header.height, header.orientation), (w, h, 1), "{name}");
+14 -10
View File
@@ -13,16 +13,20 @@ fn meta(exif: &Option<Vec<u8>>) -> EncodeMeta<'_> {
EncodeMeta { exif: exif.as_deref(), xmp: Some("<x/>"), ..Default::default() }
}
/// A TIFF with an Orientation tag (`encode_tiff` writes none), via the `tiff` crate's encoder.
/// A TIFF with an Orientation tag (`encode_tiff` writes none), via `craft-tiff`.
fn tiff_oriented(img: &Rgba8, orientation: u16) -> Vec<u8> {
use tiff::encoder::{TiffEncoder, colortype};
let rgb: Vec<u8> = img.data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect();
let mut cur = std::io::Cursor::new(Vec::new());
let mut enc = TiffEncoder::new(&mut cur).unwrap();
let mut im = enc.new_image::<colortype::RGB8>(img.width as u32, img.height as u32).unwrap();
im.encoder().write_tag(tiff::tags::Tag::Orientation, orientation).unwrap();
im.write_data(&rgb).unwrap();
cur.into_inner()
let mut ifd = craft_tiff::IfdBuilder::new()
.with(craft_tiff::tags::IMAGE_WIDTH, craft_tiff::Value::Long(vec![img.width as u32]))
.with(craft_tiff::tags::IMAGE_LENGTH, craft_tiff::Value::Long(vec![img.height as u32]))
.with(craft_tiff::tags::BITS_PER_SAMPLE, craft_tiff::Value::Short(vec![8, 8, 8]))
.with(craft_tiff::tags::COMPRESSION, craft_tiff::Value::Short(vec![1]))
.with(craft_tiff::tags::PHOTOMETRIC, craft_tiff::Value::Short(vec![2]))
.with(craft_tiff::tags::SAMPLES_PER_PIXEL, craft_tiff::Value::Short(vec![3]))
.with(craft_tiff::tags::PLANAR_CONFIGURATION, craft_tiff::Value::Short(vec![1]))
.with(craft_tiff::tags::ORIENTATION, craft_tiff::Value::Short(vec![orientation]));
ifd.set_image(craft_tiff::ImageData::Strips { rows_per_strip: img.height as u32, strips: vec![rgb] });
craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap()
}
/// A minimal 8-bit RGB PSD (raw or PackBits-literal merged data) with an EXIF resource.
@@ -99,8 +103,8 @@ fn fixtures(w: usize, h: usize) -> Vec<(String, Vec<u8>)> {
}
out.push(("tiff lzw".into(), encode_tiff(&e, TiffCompression::Lzw, &EncodeMeta::default()).unwrap()));
out.push(("tiff packbits".into(), encode_tiff(&e, TiffCompression::PackBits, &EncodeMeta::default()).unwrap()));
let mut bmp = Vec::new();
image::codecs::bmp::BmpEncoder::new(&mut bmp).encode(&rgb, w as u32, h as u32, image::ExtendedColorType::Rgb8).unwrap();
let bmp_img = craft_image_codecs::Image::from_u8(w as u32, h as u32, craft_image_codecs::ChannelLayout::Rgb, rgb).unwrap();
let bmp = craft_image_codecs::encode(&bmp_img, craft_image_codecs::Format::Bmp, &craft_image_codecs::EncodeOptions::default()).unwrap();
out.push(("bmp".into(), bmp));
out
}
+57 -44
View File
@@ -84,9 +84,9 @@ fn jpeg_cmyk_converts() {
// 0 = no ink: white, cyan, black.
let px: Vec<u8> = [[0u8, 0, 0, 0], [255, 0, 0, 0], [0, 0, 0, 255]].iter().flat_map(|p| p.repeat(16 * 16)).collect();
let img: Vec<u8> = px;
let mut out = Vec::new();
let enc = jpeg_encoder::Encoder::new(&mut out, 95);
enc.encode(&img, 16, 48, jpeg_encoder::ColorType::Cmyk).unwrap();
let ic_img = craft_image_codecs::Image::from_u8(16, 48, craft_image_codecs::ChannelLayout::Cmyk, img).unwrap();
let ic_opts = craft_image_codecs::EncodeOptions { jpeg_quality: 95, ..Default::default() };
let out = craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Jpeg, &ic_opts).unwrap();
let d = decode(&out, DecodeOptions::default()).unwrap();
assert!(d.cmyk);
assert_eq!(d.space.origin, SpaceOrigin::Naive);
@@ -246,15 +246,18 @@ fn tiff_depths_and_compressions() {
#[test]
fn tiff_cmyk_and_orientation() {
use tiff::encoder::{TiffEncoder, colortype};
let mut cur = std::io::Cursor::new(Vec::new());
{
let mut enc = TiffEncoder::new(&mut cur).unwrap();
let mut im = enc.new_image::<colortype::CMYK8>(2, 1).unwrap();
im.encoder().write_tag(tiff::tags::Tag::Orientation, 8u16).unwrap();
im.write_data(&[0u8, 0, 0, 0, 0, 255, 255, 0]).unwrap();
}
let d = decode(&cur.into_inner(), DecodeOptions::default()).unwrap();
let mut ifd = craft_tiff::IfdBuilder::new()
.with(craft_tiff::tags::IMAGE_WIDTH, craft_tiff::Value::Long(vec![2]))
.with(craft_tiff::tags::IMAGE_LENGTH, craft_tiff::Value::Long(vec![1]))
.with(craft_tiff::tags::BITS_PER_SAMPLE, craft_tiff::Value::Short(vec![8, 8, 8, 8]))
.with(craft_tiff::tags::COMPRESSION, craft_tiff::Value::Short(vec![1]))
.with(craft_tiff::tags::PHOTOMETRIC, craft_tiff::Value::Short(vec![5]))
.with(craft_tiff::tags::SAMPLES_PER_PIXEL, craft_tiff::Value::Short(vec![4]))
.with(craft_tiff::tags::PLANAR_CONFIGURATION, craft_tiff::Value::Short(vec![1]))
.with(craft_tiff::tags::ORIENTATION, craft_tiff::Value::Short(vec![8]));
ifd.set_image(craft_tiff::ImageData::Strips { rows_per_strip: 1, strips: vec![vec![0u8, 0, 0, 0, 0, 255, 255, 0]] });
let tif = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap();
let d = decode(&tif, DecodeOptions::default()).unwrap();
assert!(d.cmyk);
assert_eq!(d.orientation, 8);
let white = d.image.get(0, 0);
@@ -268,16 +271,21 @@ fn tiff_cmyk_and_orientation() {
/// the thumbnail (and the full decode) failed with "decoder limits exceeded".
#[test]
fn tiff_single_strip_larger_than_128_mib() {
use tiff::encoder::{TiffEncoder, colortype};
let (w, h) = (3923u32, 5877u32);
let mut cur = std::io::Cursor::new(Vec::new());
{
let mut enc = TiffEncoder::new(&mut cur).unwrap();
let mut im = enc.new_image::<colortype::RGB16>(w, h).unwrap();
im.rows_per_strip(h).unwrap();
im.write_data(&vec![0x8000u16; (w * h * 3) as usize]).unwrap();
let mut strip = Vec::with_capacity((w * h * 3 * 2) as usize);
for _ in 0..(w * h * 3) {
strip.extend_from_slice(&0x8000u16.to_le_bytes());
}
let bytes = cur.into_inner();
let mut ifd = craft_tiff::IfdBuilder::new()
.with(craft_tiff::tags::IMAGE_WIDTH, craft_tiff::Value::Long(vec![w]))
.with(craft_tiff::tags::IMAGE_LENGTH, craft_tiff::Value::Long(vec![h]))
.with(craft_tiff::tags::BITS_PER_SAMPLE, craft_tiff::Value::Short(vec![16, 16, 16]))
.with(craft_tiff::tags::COMPRESSION, craft_tiff::Value::Short(vec![1]))
.with(craft_tiff::tags::PHOTOMETRIC, craft_tiff::Value::Short(vec![2]))
.with(craft_tiff::tags::SAMPLES_PER_PIXEL, craft_tiff::Value::Short(vec![3]))
.with(craft_tiff::tags::PLANAR_CONFIGURATION, craft_tiff::Value::Short(vec![1]));
ifd.set_image(craft_tiff::ImageData::Strips { rows_per_strip: h, strips: vec![strip] });
let bytes = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap();
assert!(bytes.len() > 128 << 20);
let t = decode_thumbnail(&bytes, 256).unwrap();
assert_eq!((t.source_width, t.source_height), (w, h));
@@ -310,8 +318,7 @@ fn tiff_small_pixel_budget_reads_headers_and_padded_tiles() {
let opts = |max_pixels| DecodeOptions { max_size: None, max_pixels };
// 1 × 1 gray, one JPEG-compressed strip (~400 bytes for one pixel), with a one-pixel budget.
let mut jpeg = Vec::new();
jpeg_encoder::Encoder::new(&mut jpeg, 90).encode(&[128], 1, 1, jpeg_encoder::ColorType::Luma).unwrap();
let jpeg = encode_jpeg(&EncodeImage::new(1, 1, 1, Samples::U8(&[128])), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap();
let at = 8 + 2 + 10 * 12 + 4;
let entries = [
(256, 4, 1),
@@ -438,22 +445,17 @@ fn webp_lossless_exact() {
#[test]
fn gif_and_bmp_decode() {
use image::ImageEncoder;
let img = gradient(16, 8);
let rgba = img.as_bytes();
let mut bmp = Vec::new();
image::codecs::bmp::BmpEncoder::new(&mut bmp).write_image(&rgba, 16, 8, image::ExtendedColorType::Rgba8).unwrap();
let ic_img = craft_image_codecs::Image::from_u8(16, 8, craft_image_codecs::ChannelLayout::Rgba, rgba.to_vec()).unwrap();
let bmp = craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Bmp, &craft_image_codecs::EncodeOptions::default()).unwrap();
assert_eq!(sniff(&bmp), Some(Format::Bmp));
let d = decode(&bmp, DecodeOptions::default()).unwrap();
assert_eq!(d.to_srgb8(), img);
let mut gif = Vec::new();
{
let mut enc = image::codecs::gif::GifEncoder::new(&mut gif);
let flat = Rgba8::filled(16, 8, [10, 200, 30, 255]);
let buf = image::RgbaImage::from_raw(16, 8, flat.as_bytes()).unwrap();
enc.encode_frame(image::Frame::new(buf)).unwrap();
}
let flat = Rgba8::filled(16, 8, [10, 200, 30, 255]);
let flat_ic = craft_image_codecs::Image::from_u8(16, 8, craft_image_codecs::ChannelLayout::Rgba, flat.as_bytes().to_vec()).unwrap();
let gif = craft_image_codecs::encode(&flat_ic, craft_image_codecs::Format::Gif, &craft_image_codecs::EncodeOptions::default()).unwrap();
assert_eq!(sniff(&gif), Some(Format::Gif));
let d = decode(&gif, DecodeOptions::default()).unwrap();
let p = d.to_srgb8().get(3, 3);
@@ -729,10 +731,14 @@ fn print_resolution_is_written() {
assert_eq!(u32::from_be_bytes(png[i + 4..i + 8].try_into().unwrap()), 11811, "300 ppi in pixels per metre");
assert_eq!(png[i + 12], 1, "unit = metre");
let tif = encode_tiff(&img, TiffCompression::Deflate, &meta).unwrap();
let mut d = tiff::decoder::Decoder::new(std::io::Cursor::new(tif)).unwrap();
let x = d.get_tag(tiff::tags::Tag::XResolution).unwrap();
assert_eq!(x.into_u32_vec().ok(), Some(vec![300, 1]));
assert_eq!(d.get_tag_u32(tiff::tags::Tag::ResolutionUnit).unwrap(), 2, "inch");
let parsed = craft_tiff::Tiff::parse(&tif).unwrap();
let ifd = &parsed.ifds[0];
let x = match ifd.get(craft_tiff::tags::X_RESOLUTION).map(|e| &e.value) {
Some(craft_tiff::Value::Rational(v)) => v.first().copied(),
_ => None,
};
assert_eq!(x.map(|(n, d)| (n / d, n % d)), Some((300, 0)));
assert_eq!(ifd.u16(craft_tiff::tags::RESOLUTION_UNIT), Some(2), "inch");
// without a ppi: JFIF density stays an aspect ratio
let j = encode_jpeg(&img, 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap();
assert_eq!(&j[13..18], &[0, 0, 1, 0, 1]);
@@ -750,17 +756,18 @@ fn pq_png_is_16_bit_rec2020_pq_with_cicp_and_content_light() {
.collect();
let xmp = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"/>"#;
let bytes = encode_png_pq(w, h, &rgb, &EncodeMeta { xmp: Some(xmp), ppi: Some(240), ..Default::default() }).unwrap();
let mut r = png::Decoder::new(std::io::Cursor::new(bytes.as_slice())).read_info().unwrap();
let cicp = r.info().coding_independent_code_points.expect("cICP");
assert_eq!((cicp.color_primaries, cicp.transfer_function), (9, 16), "BT.2020, PQ");
let mut buf = vec![0; r.output_buffer_size().unwrap()];
let f = r.next_frame(&mut buf).unwrap();
assert_eq!((f.bit_depth, f.color_type, f.width, f.height), (png::BitDepth::Sixteen, png::ColorType::Rgb, w, h));
let decoded = craft_image_codecs::decode_as(craft_image_codecs::Format::Png, &bytes).unwrap();
let cicp_at = bytes.windows(4).position(|w| w == b"cICP").expect("cICP");
assert_eq!((bytes[cicp_at + 4], bytes[cicp_at + 5]), (9, 16), "BT.2020, PQ");
assert_eq!(
(decoded.sample_type(), decoded.layout(), decoded.width(), decoded.height()),
(craft_image_codecs::SampleType::U16, craft_image_codecs::ChannelLayout::Rgb, w, h)
);
let samples = decoded.to_u16_samples().unwrap();
// every sample decodes back to its luminance
for x in [0usize, 20, 63] {
for c in 0..3 {
let o = (x * 3 + c) * 2;
let e = u16::from_be_bytes([buf[o], buf[o + 1]]) as f32 / 65535.0;
let e = samples[x * 3 + c] as f32 / 65535.0;
let want = rgb[x * 3 + c] * HDR_REFERENCE_WHITE_NITS;
assert!((encode::pq_decode(e) - want).abs() <= want * 0.01 + 0.01, "x {x} c {c}: {} vs {want}", encode::pq_decode(e));
}
@@ -770,6 +777,12 @@ fn pq_png_is_16_bit_rec2020_pq_with_cicp_and_content_light() {
let max_cll = u32::from_be_bytes(bytes[at + 4..at + 8].try_into().unwrap()) as f32 / 10_000.0;
let brightest = rgb.iter().copied().fold(0.0f32, f32::max) * HDR_REFERENCE_WHITE_NITS;
assert!((max_cll - brightest.ceil()).abs() <= 1.0, "{max_cll} vs {brightest}");
let max_fall = u32::from_be_bytes(bytes[at + 8..at + 12].try_into().unwrap()) / 10_000;
let expected_max_fall =
(rgb.as_chunks::<3>().0.iter().map(|p| f64::from(p.iter().copied().fold(0.0f32, f32::max) * HDR_REFERENCE_WHITE_NITS)).sum::<f64>()
/ f64::from(w * h))
.ceil() as u32;
assert_eq!(max_fall, expected_max_fall, "MaxFALL uses CTA-861.3-A's per-pixel maximum channel");
assert!(bytes.windows(17).any(|w| w == b"XML:com.adobe.xmp"), "XMP kept");
assert!(bytes.windows(4).any(|w| w == b"pHYs"), "print resolution kept");
assert!(!bytes.windows(4).any(|w| w == b"iCCP"), "no ICC profile next to cICP");
@@ -2,6 +2,7 @@ use super::look_fit::{fit_dng_tone, fit_preview, look_proxies};
use super::mono::{fit_dark_tone, monochrome_look};
use super::proxy::LensGeometry;
use super::{CameraLook, CameraTone, CameraTransform, ColorData, D50, D65, Mat3, ProfileLook, REC2020, RawFormat, RawImage, ToneCurve, Xy, bradford};
use lightcraft_raw::profile::ToneCurveEval;
/// Long edge of the sensor/JPEG proxy a single photo's look is fitted on (the acceptance gates
/// below were set at this size).
@@ -1,6 +1,7 @@
use super::mono::to_prophoto;
use super::pairs::{displayed, luma};
use super::{CameraLook, CameraTone, HsvTable, Mat3, ToneMap, luminance_2020};
use lightcraft_raw::profile::HsvTableApply;
/// [`HueSat::apply`] restores the luminance in full only if the table kept at least this share of it. A colour
/// the table darkens to [`NO_LUMINANCE_KEPT`] or less (only near-black noise, whose channels go negative) keeps
@@ -1,5 +1,6 @@
use super::tone::{ELASTICITY_BLACK, MAX_TONE_ELASTICITY, TONE_REPAIR_ELASTICITY, limit_elasticity};
use super::*;
use lightcraft_raw::profile::{HsvTableApply, ProfileLookHueSat};
fn steep_toe_scene() -> (Rgb32f, Rgb32f) {
let mut sensor = Rgb32f::new(96, 64);
+10
View File
@@ -361,3 +361,13 @@ mod tests {
}
}
}
#[cfg(test)]
mod feature_name_tests {
#[test]
fn perspective_labels_keep_existing_command_ids() {
for (id, label) in [("geometry.upright", "Perspective Correction"), ("geometry.guides", "Perspective Guides")] {
assert_eq!(super::find_command(id).expect("existing command").label, label);
}
}
}
+105 -2
View File
@@ -241,6 +241,9 @@ fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::P
}
if m.shutter.is_empty() {
m.shutter = src.shutter.clone();
m.exposure_time = src.exposure_time;
} else {
repair_legacy_shutter(&mut m, src);
}
m.focal_mm = m.focal_mm.or(src.focal_mm);
m.aperture = m.aperture.or(src.aperture);
@@ -265,6 +268,26 @@ fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::P
ops
}
/// Repair only the shutter data an old import wrote, keeping independently edited metadata.
fn repair_legacy_shutter(m: &mut lightcraft_catalog::Meta, src: &lightcraft_catalog::Meta) -> bool {
if m.exposure_time.is_none()
&& let Some(t) = src.exposure_time
&& (m.shutter.trim() == src.shutter || legacy_shutter_text(t).is_some_and(|old| m.shutter.trim() == old))
{
m.shutter = src.shutter.clone();
m.exposure_time = Some(t);
true
} else {
false
}
}
/// The shutter text an import wrote before the exact exposure time was kept (#1619): whole seconds at
/// one second and over, otherwise `1/n` with `n` rounded. Only for recognising such a text again.
fn legacy_shutter_text(t: f64) -> Option<String> {
(t.is_finite() && t > 0.0).then(|| if t >= 1.0 { format!("{t:.0}") } else { format!("1/{:.0}", 1.0 / t) })
}
/// Ops that give a photo the lens data its file carries now (`info`, a fresh probe), or none when
/// it already has them. A catalog from before the lens data was read at import has none, so such a
/// photo's correction stayed off. When the photo gains lens data and its develop settings are still
@@ -314,8 +337,16 @@ pub(crate) fn reload_ops(
}
// virtual copies share the file
for c in cat.photos().filter(|c| c.copy_of == Some(id)) {
let theirs: Vec<Op> =
content_op(c.id, c, info.clone()).into_iter().chain(lens_ops(c.id, c, info)).chain(as_shot_wb_op(c.id, c, info)).collect();
let mut meta = c.meta.clone();
// Copies share the source file but may have independently edited metadata. Repair only
// recognizable legacy shutter values, not every missing field on the copy.
let shutter_op = repair_legacy_shutter(&mut meta, &info.meta).then(|| Op::SetMeta { id: c.id, meta: Box::new(meta) });
let theirs: Vec<Op> = content_op(c.id, c, info.clone())
.into_iter()
.chain(shutter_op)
.chain(lens_ops(c.id, c, info))
.chain(as_shot_wb_op(c.id, c, info))
.collect();
if !theirs.is_empty() {
ops.extend(theirs);
changed.push(c.id);
@@ -441,6 +472,78 @@ mod tests {
assert!(fill_missing_meta(PhotoId(1), &ph, &info).is_empty());
}
/// Reload from Disk repairs a shutter speed an older import rounded (0.4 s stored as `1/2`, with no
/// exact time): the photo takes the file's exact time and today's text. A shutter speed set by hand
/// that is not what an import wrote, and one that already has its exact time, are kept.
#[test]
fn reload_repairs_a_shutter_speed_an_older_import_rounded() {
let mut ph = Photo::new(PhotoId(1), Source::File { path: "/x.nef".into() }, "x.nef", "NEF", 6000, 4000, "2026-10-06T00:00:00");
ph.captured = Some("2026-10-04T08:16:11".into());
let mut info = crate::media::ProbeInfo { captured: ph.captured.clone(), ..Default::default() };
for (t, legacy, shown) in [(0.4, "1/2", "0.4"), (2.5, "2", "2.5"), (1.0 / 2.8, "1/3", "0.3571"), (1.0 / 250.0, "1/250", "1/250")] {
info.meta.exposure_time = Some(t);
info.meta.shutter = lightcraft_meta::format_exposure_time(t).unwrap();
ph.meta.shutter = legacy.into();
ph.meta.exposure_time = None;
let ops = fill_missing_meta(PhotoId(1), &ph, &info);
let Some(Op::SetMeta { meta, .. }) = ops.first() else { panic!("{t}: {ops:?}") };
assert_eq!((meta.shutter.as_str(), meta.exposure_time), (shown, Some(t)), "{t}");
assert_eq!(meta.shutter_seconds(), Some(t), "{t}");
// repaired → nothing more to do
ph.meta = (**meta).clone();
assert!(fill_missing_meta(PhotoId(1), &ph, &info).is_empty(), "{t}");
}
// typed by hand, not what any import wrote for this file
info.meta.exposure_time = Some(0.4);
info.meta.shutter = "0.4".into();
ph.meta.shutter = "1/8".into();
ph.meta.exposure_time = None;
assert!(fill_missing_meta(PhotoId(1), &ph, &info).is_empty(), "a hand-set shutter speed is kept");
// already has an exact time (the text was edited afterwards): kept
ph.meta.shutter = "1/2".into();
ph.meta.exposure_time = Some(0.4);
assert!(fill_missing_meta(PhotoId(1), &ph, &info).is_empty(), "a photo with an exact time is left alone");
}
#[test]
fn reload_repairs_legacy_shutter_on_copies_without_replacing_edits() {
let mut cat = lightcraft_catalog::Catalog::new();
let mut source = Photo::new(PhotoId(1), Source::File { path: "/x.nef".into() }, "x.nef", "NEF", 6000, 4000, "");
source.meta.shutter = "1/2".into();
cat.apply(Op::AddPhoto { photo: Box::new(source.clone()) }).unwrap();
for (id, text, exact) in [(2, "1/2", None), (3, "0.4", None), (4, "1/8", None), (5, "1/2", Some(0.4))] {
let mut copy = source.clone();
copy.id = PhotoId(id);
copy.copy_of = Some(source.id);
copy.meta.shutter = text.into();
copy.meta.exposure_time = exact;
copy.meta.title = "My copy".into();
cat.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap();
}
let mut info = crate::media::ProbeInfo::default();
info.meta.shutter = "0.4".into();
info.meta.exposure_time = Some(0.4);
info.meta.title = "File title".into();
let mut ops = Vec::new();
let mut changed = Vec::new();
reload_ops(&cat, source.id, &info, &mut ops, &mut changed);
for op in ops {
cat.apply(op).unwrap();
}
for id in [1, 2, 3] {
let m = &cat.photo(PhotoId(id)).unwrap().meta;
assert_eq!((m.shutter.as_str(), m.exposure_time), ("0.4", Some(0.4)));
assert_eq!(m.shutter_seconds(), Some(0.4));
}
for (id, text, exact) in [(4, "1/8", None), (5, "1/2", Some(0.4))] {
let m = &cat.photo(PhotoId(id)).unwrap().meta;
assert_eq!((m.shutter.as_str(), m.exposure_time), (text, exact));
}
for id in [2, 3, 4, 5] {
assert_eq!(cat.photo(PhotoId(id)).unwrap().meta.title, "My copy");
}
}
/// Reload from Disk gives a photo imported before focus points were read its camera focus point,
/// and never replaces one it has.
#[test]
+6 -9
View File
@@ -1065,7 +1065,7 @@ pub fn specs() -> Vec<CommandSpec> {
// ---- geometry: Upright
cmd!(
"geometry.upright",
"Upright",
"Perspective Correction",
[],
None,
"{mode: off|auto|guided|level|vertical|full} — analyses the photo (line segments → vanishing points) and stores the correction; run again to update after lens changes",
@@ -1083,7 +1083,7 @@ pub fn specs() -> Vec<CommandSpec> {
Some(lightcraft_pipeline::upright::auto_transform(&src, &info, &d, m))
}
};
edit(s, "geometry.upright", "Upright", |d| {
edit(s, "geometry.upright", "Perspective Correction", |d| {
d.geometry.upright = mode;
d.geometry.upright_transform = transform;
Ok(())
@@ -1093,10 +1093,10 @@ pub fn specs() -> Vec<CommandSpec> {
),
cmd!(
"geometry.guides",
"Guided Upright Guides",
"Perspective Guides",
[],
None,
"{guides: [[x0,y0,x1,y1], …] (≤ 4, normalized coords of the lens-corrected image), add?: bool (append one guide, dropping the oldest beyond 4)} — switches Upright to Guided",
"{guides: [[x0,y0,x1,y1], …] (≤ 4, normalized coords of the lens-corrected image), add?: bool (append one guide, dropping the oldest beyond 4)} — switches Perspective Correction to Guided",
has_active,
|s, p| {
let parse = |v: &Value| -> Option<(Point, Point)> {
@@ -1106,7 +1106,7 @@ pub fn specs() -> Vec<CommandSpec> {
let guides: Vec<(Point, Point)> =
p.get("guides").and_then(Value::as_array).map(|a| a.iter().filter_map(parse).collect()).unwrap_or_default();
let add = bool_or(p, "add", false);
edit(s, "geometry.guides", "Guided Upright", |d| {
edit(s, "geometry.guides", "Guided Perspective", |d| {
if add {
d.geometry.guides.extend(guides);
} else {
@@ -1277,10 +1277,7 @@ pub fn specs() -> Vec<CommandSpec> {
// log2 of the light the photo gathered (shutter s × ISO / f-number²)
let gathered = |s: &Session, id: PhotoId| -> Option<f64> {
let m = &s.catalog.photo(id)?.meta;
let t = match m.shutter.split_once('/') {
Some((a, b)) => a.trim().parse::<f64>().ok()? / b.trim().parse::<f64>().ok()?,
None => m.shutter.trim().trim_end_matches('s').trim().parse::<f64>().ok()?,
};
let t = m.shutter_seconds()?;
let (n, iso) = (m.aperture? as f64, m.iso? as f64);
(t > 0.0 && n > 0.0 && iso > 0.0).then(|| (t * iso / (n * n)).log2())
};
+1 -1
View File
@@ -342,7 +342,7 @@ pub fn export_metadata(photo: &lightcraft_catalog::Photo, catalog: &lightcraft_c
out.lens_model = text(&m.lens);
out.focal_length = m.focal_mm.map(f64::from);
out.f_number = m.aperture.map(f64::from);
out.exposure_time = lightcraft_catalog::parse_shutter_seconds(&m.shutter);
out.exposure_time = m.shutter_seconds();
out.iso = m.iso;
}
Some(out)
+2
View File
@@ -375,6 +375,7 @@ fn local_tone(raw: &lightcraft_raw::RawImage) -> Option<Arc<lightcraft_pipeline:
/// Subject mask then falls back to its heuristic); a sky matte counts even when empty (no sky).
fn dng_mattes(bytes: &[u8], raw: &lightcraft_raw::RawInfo) -> Option<Arc<lightcraft_pipeline::masks::Mattes>> {
use lightcraft_pipeline::masks::{MatteKind, Mattes};
use lightcraft_raw::semantic::SemanticMaskExt;
if raw.format != lightcraft_raw::RawFormat::Dng {
return None;
}
@@ -410,6 +411,7 @@ fn matte_kind(name: &str) -> Option<lightcraft_pipeline::masks::MatteKind> {
/// finish stage's camera tone curve: 32 knots, log-spaced over 12 stops below white; above white
/// the camera tone's shoulder continues it.
pub(crate) fn dng_tone_curve(curve: &lightcraft_raw::profile::ToneCurve) -> Option<lightcraft_pipeline::tone::CameraTone> {
use lightcraft_raw::profile::ToneCurveEval;
let knots: [[f32; 2]; 32] = std::array::from_fn(|i| {
let x = 2f32.powf(-12.0 + 12.0 * i as f32 / 31.0);
[x, curve.eval(x).min(0.9995)]
+2 -1
View File
@@ -21,7 +21,7 @@ fn stand_in_image(bytes: &[u8], covering: Option<usize>) -> Option<std::borrow::
if let Some(jpeg) = jpeg {
return Some(std::borrow::Cow::Owned(jpeg));
}
let undecodable = lightcraft_raw::probe(bytes).is_some_and(|f| !f.is_supported());
let undecodable = lightcraft_raw::probe(bytes).is_some_and(|f| !lightcraft_raw::is_supported(f));
(undecodable && lightcraft_codecs::sniff(bytes).is_some_and(|f| f == lightcraft_codecs::Format::Tiff))
.then_some(std::borrow::Cow::Borrowed(bytes))
}
@@ -46,6 +46,7 @@ fn decode_stand_in(bytes: &[u8], jpeg: &[u8], opts: lightcraft_codecs::DecodeOpt
let space = match space {
lightcraft_raw::PreviewColorSpace::Srgb => lightcraft_codecs::NamedSpace::Srgb,
lightcraft_raw::PreviewColorSpace::AdobeRgb => lightcraft_codecs::NamedSpace::AdobeRgb,
lightcraft_raw::PreviewColorSpace::ProPhoto => lightcraft_codecs::NamedSpace::ProPhoto,
};
lightcraft_codecs::decode_jpeg_with_fallback(jpeg, opts, space).ok()
}
+3 -1
View File
@@ -3,7 +3,8 @@ use super::preview::embedded_preview_size;
use super::{MediaKind, Meta, Orientation, ProbeInfo};
pub(super) fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option<String>) {
let shutter = m.exposure_time.map(|t| if t >= 1.0 { format!("{t:.0}") } else { format!("1/{:.0}", 1.0 / t) }).unwrap_or_default();
let exposure_time = m.exposure_time.filter(|t| t.is_finite() && *t > 0.0);
let shutter = exposure_time.and_then(lightcraft_meta::format_exposure_time).unwrap_or_default();
let camera = [m.make.clone().unwrap_or_default(), m.model.clone().unwrap_or_default()].join(" ").trim().to_string();
let meta = Meta {
camera,
@@ -14,6 +15,7 @@ pub(super) fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option<String>) {
focal_mm: m.focal_length.map(|f| f as f32),
aperture: m.f_number.map(|f| f as f32),
shutter,
exposure_time,
iso: m.iso,
flash: m.flash.map(|f| f.fired),
exposure_bias: m.exposure_bias.map(|v| v as f32),
+38
View File
@@ -1851,6 +1851,44 @@ fn existing_photo_settings_are_not_rewritten() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn imported_shutter_times_survive_catalog_and_export_metadata() {
use lightcraft_catalog::{Catalog, Photo, PhotoId};
for (t, shown) in [
(0.3, "0.3"),
(0.4, "0.4"),
(0.6, "0.6"),
(0.8, "0.8"),
(1.3, "1.3"),
(1.6, "1.6"),
(2.5, "2.5"),
(3.2, "3.2"),
(30.0, "30"),
(0.625, "0.625"),
(1.0 / 2.8, "0.3571"),
(1.0 / 3.0, "1/3"),
(0.003, "0.003"),
(1.0 / 250.0, "1/250"),
(1.0 / 8000.0, "1/8000"),
] {
let original = lightcraft_meta::Metadata { exposure_time: Some(t), ..Default::default() };
let (meta, _) = meta_of(&original);
// the catalog shows a short shutter speed, never the raw f64 (`0.35714285714285715`)
assert_eq!(meta.shutter, shown, "{t}");
// Exercise the persisted catalog JSON, not a value kept alongside it in memory.
let meta: Meta = serde_json::from_str(&serde_json::to_string(&meta).unwrap()).unwrap();
let mut photo = Photo::new(PhotoId(1), lightcraft_catalog::Source::Demo { scene: 0 }, "capture.jpg", "JPEG", 2, 2, "");
photo.meta = meta;
let exported = crate::export::export_metadata(&photo, &Catalog::new(), &crate::export::ExportOptions::default()).unwrap();
assert_eq!(exported.exposure_time, Some(t));
let bytes =
crate::export::encode_with_metadata(&lightcraft_raster::Rgba8::new(2, 2), &crate::export::ExportOptions::default(), Some(&exported))
.unwrap();
let back = lightcraft_meta::extract(&bytes);
assert!((back.exposure_time.unwrap() - t).abs() < 0.000001, "{t}: {:?}", back.exposure_time);
}
}
/// Issue #1632: a DNG's `ProfileToneCurve` is the finish stage's camera curve, so process V5 extends
/// it past its last point (the sensor's white, scene 1.0) with the stop roll-off as well. A curve
/// that reaches white there renders as under V4 up to it and white past it; one that ends below
+5 -1
View File
@@ -1323,6 +1323,8 @@ mod tests {
w.push(0);
}
}
let size = u32::try_from(w.len() - 8).unwrap();
w[4..8].copy_from_slice(&size.to_le_bytes());
w
};
let image = |len: usize| (&b"VP8L"[..], vec![0; len]);
@@ -1495,8 +1497,10 @@ mod tests {
section.push(0);
}
}
// a valid header: one RGB pixel, 8 bits
let mut p = b"8BPS\0\x01".to_vec();
p.resize(26, 0);
p.resize(12, 0);
p.extend_from_slice(&[0, 3, 0, 0, 0, 1, 0, 0, 0, 1, 0, 8, 0, 3]);
p.extend_from_slice(&(colour as u32).to_be_bytes());
p.resize(p.len() + colour, 0);
p.extend_from_slice(&(section.len() as u32).to_be_bytes());
+6 -3
View File
@@ -1071,6 +1071,12 @@ fn remove_location_refuses_a_psd_with_unreadable_resources() {
let path = dir.join("Geo.psd");
let valid_bytes = synthetic_psd_with_metadata(&gps);
assert_eq!(lightcraft_meta::extract(&valid_bytes).gps, gps.gps, "the fixture embeds EXIF GPS before corruption");
std::fs::write(&path, &valid_bytes).unwrap();
let mut session = Session::new().with_fs();
session.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap();
let id = session.catalog.photos().next().unwrap().id;
// Import the decodable original first. The malformed resource list below is the file state the
// export safety check must refuse; it is not a fixture the image importer should have to decode.
let mut bytes = valid_bytes;
let colour_length = usize::try_from(u32::from_be_bytes(bytes[26..30].try_into().unwrap())).unwrap();
let resource_length_at = 30 + colour_length;
@@ -1082,9 +1088,6 @@ fn remove_location_refuses_a_psd_with_unreadable_resources() {
assert!(lightcraft_meta::extract(&bytes).gps.is_none(), "the malformed trailing resource reproduces the metadata gap");
std::fs::write(&path, bytes).unwrap();
let mut session = Session::new().with_fs();
session.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap();
let id = session.catalog.photos().next().unwrap().id;
let err = export_photo(&mut session, id, &ExportOptions::from_json(&json!({"format": "original", "removeLocation": true})), 1).err().unwrap();
assert!(err.contains("can't verify location metadata") && err.contains("malformed PSD/PSB"), "{err}");
let _ = std::fs::remove_dir_all(&dir);
+1 -1
View File
@@ -11,4 +11,4 @@ workspace = true
[dependencies]
lightcraft-develop = { workspace = true }
lightcraft-geom = { workspace = true }
quick-xml = { workspace = true }
craft-xml = { workspace = true }
+22 -20
View File
@@ -148,10 +148,12 @@ impl LensDb {
/// Parse one lensfun-format XML document.
pub fn parse(xml: &str) -> Result<LensDb, Error> {
let root = xml::parse(xml)?;
let Some(top) = root.kid("lensdatabase") else { return Err(Error::Xml("no <lensdatabase> element".into())) };
let cameras = top.kids("camera").filter_map(camera).collect();
if root.name != "lensdatabase" {
return Err(Error::Xml("no <lensdatabase> element".into()));
}
let cameras = root.children("camera").filter_map(camera).collect();
let mut budget = MAX_PROFILE_COPY_BYTES;
let lenses = top.kids("lens").flat_map(|n| lens(n, &mut budget)).collect();
let lenses = root.children("lens").flat_map(|n| lens(n, &mut budget)).collect();
Ok(LensDb { cameras, lenses })
}
@@ -384,10 +386,10 @@ fn is_teleconverter_marker(t: &str) -> bool {
fn camera(n: &xml::Node) -> Option<Camera> {
Some(Camera {
maker: n.kid_text("maker")?.to_string(),
model: n.kid_text("model")?.to_string(),
mount: n.kid_text("mount").unwrap_or_default().to_string(),
crop_factor: crop_of(n.kid_text("cropfactor")),
maker: xml::kid_text(n, "maker")?,
model: xml::kid_text(n, "model")?,
mount: xml::kid_text(n, "mount").unwrap_or_default(),
crop_factor: crop_of(xml::kid_text(n, "cropfactor").as_deref()),
})
}
@@ -411,15 +413,15 @@ fn positive(v: Option<f64>) -> Option<f64> {
/// One `<lens>` element → one profile per `<calibration>` (newer files give each its own crop factor and aspect).
fn lens(n: &xml::Node, copy_budget: &mut usize) -> Vec<Profile> {
let Some(maker) = n.kid_text("maker") else { return Vec::new() };
let models: Vec<String> = n.kids("model").map(|m| m.text.trim().to_string()).filter(|m| !m.is_empty()).collect();
let Some(maker) = xml::kid_text(n, "maker") else { return Vec::new() };
let models: Vec<String> = n.children("model").map(|m| m.text().trim().to_string()).filter(|m| !m.is_empty()).collect();
if models.is_empty() {
return Vec::new();
}
let crop = crop_of(n.kid_text("cropfactor"));
let aspect = aspect_of(n.kid_text("aspect-ratio")).unwrap_or(1.5);
let rectilinear = n.kid_text("type").is_none_or(|t| t.eq_ignore_ascii_case("rectilinear"));
let mounts = n.kids("mount").map(|m| m.text.trim().to_string()).filter(|m| !m.is_empty()).collect::<Vec<_>>();
let crop = crop_of(xml::kid_text(n, "cropfactor").as_deref());
let aspect = aspect_of(xml::kid_text(n, "aspect-ratio").as_deref()).unwrap_or(1.5);
let rectilinear = xml::kid_text(n, "type").is_none_or(|t| t.eq_ignore_ascii_case("rectilinear"));
let mounts = n.children("mount").map(|m| m.text().trim().to_string()).filter(|m| !m.is_empty()).collect::<Vec<_>>();
// every kept calibration owns a copy of the lens's names, charged to the document's shared copy budget (the
// strings' own allocations count, not only their bytes): when it can't cover another copy, the rest are left out
let meta_bytes = std::mem::size_of::<Profile>()
@@ -427,7 +429,7 @@ fn lens(n: &xml::Node, copy_budget: &mut usize) -> Vec<Profile> {
+ maker.len()
+ models.iter().chain(&mounts).map(|m| m.len() + NAME_ALLOCATION).sum::<usize>();
let mut out = Vec::new();
for cal in n.kids("calibration") {
for cal in n.children("calibration") {
if *copy_budget < meta_bytes {
break;
}
@@ -446,23 +448,23 @@ fn lens(n: &xml::Node, copy_budget: &mut usize) -> Vec<Profile> {
tca: Vec::new(),
vignetting: Vec::new(),
};
for c in &cal.children {
let Some(focal) = positive(c.num("focal")) else { continue };
let k = |name: &str| c.num(name).unwrap_or(0.0);
for c in cal.elements() {
let Some(focal) = positive(xml::num(c, "focal")) else { continue };
let k = |name: &str| xml::num(c, name).unwrap_or(0.0);
match (c.name.as_str(), c.attr("model")) {
("distortion", Some("poly3")) => p.distortion.push((focal, Distortion::Poly3 { k1: k("k1") })),
("distortion", Some("poly5")) => p.distortion.push((focal, Distortion::Poly5 { k1: k("k1"), k2: k("k2") })),
("distortion", Some("ptlens")) => p.distortion.push((focal, Distortion::PtLens { a: k("a"), b: k("b"), c: k("c") })),
("tca", Some("linear")) => {
let one = |name: &str| c.num(name).unwrap_or(1.0);
let one = |name: &str| xml::num(c, name).unwrap_or(1.0);
p.tca.push((focal, Tca::Linear { kr: one("kr"), kb: one("kb") }));
}
("tca", Some("poly3")) => {
let one = |name: &str| c.num(name).unwrap_or(1.0);
let one = |name: &str| xml::num(c, name).unwrap_or(1.0);
p.tca.push((focal, Tca::Poly3 { vr: one("vr"), vb: one("vb"), cr: k("cr"), cb: k("cb"), br: k("br"), bb: k("bb") }));
}
("vignetting", Some("pa")) => {
let (Some(aperture), distance) = (positive(c.num("aperture")), positive(c.num("distance")).unwrap_or(1000.0)) else {
let (Some(aperture), distance) = (positive(xml::num(c, "aperture")), positive(xml::num(c, "distance")).unwrap_or(1000.0)) else {
continue;
};
let model = Vignetting { k1: k("k1"), k2: k("k2"), k3: k("k3") };
+2 -1
View File
@@ -94,7 +94,8 @@ fn rejects_mismatched_xml_closing_tags() {
#[test]
fn malformed_documents_are_errors_not_panics() {
assert!(LensDb::parse("").is_err());
assert!(LensDb::parse("<lensdatabase><lens><maker>").is_ok_and(|d| d.lenses.is_empty()));
// a truncated document is an error, not an empty database
assert!(matches!(LensDb::parse("<lensdatabase><lens><maker>"), Err(Error::Xml(_))));
assert!(LensDb::parse("<other/>").is_err());
let deep = "<a>".repeat(100);
assert_eq!(LensDb::parse(&deep), Err(Error::TooLarge));
+30 -150
View File
@@ -1,147 +1,36 @@
//! A small, bounded XML tree reader for lensfun-format database files.
//! Reading lensfun-format database files with `craft-xml`, within this crate's limits.
use quick_xml::events::Event;
pub(crate) use craft_xml::El as Node;
use crate::Error;
const MAX_NODES: usize = 500_000;
/// Most nodes (elements and their text) one document may hold.
const MAX_NODES: usize = 1_000_000;
/// Deepest element nesting (lensfun files nest four deep).
const MAX_DEPTH: usize = 32;
#[derive(Debug, Default)]
pub(crate) struct Node {
pub name: String,
pub attrs: Vec<(String, String)>,
pub text: String,
pub children: Vec<Node>,
}
impl Node {
pub fn attr(&self, k: &str) -> Option<&str> {
self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str())
}
pub fn num(&self, k: &str) -> Option<f64> {
self.attr(k).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
}
pub fn kids<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Node> + 'a {
self.children.iter().filter(move |c| c.name == name)
}
pub fn kid(&self, name: &str) -> Option<&Node> {
self.children.iter().find(|c| c.name == name)
}
pub fn kid_text(&self, name: &str) -> Option<&str> {
self.kid(name).map(|n| n.text.trim()).filter(|t| !t.is_empty())
}
}
fn entity(name: &str) -> Option<char> {
Some(match name {
"amp" => '&',
"lt" => '<',
"gt" => '>',
"quot" => '"',
"apos" => '\'',
_ => {
let n = name.strip_prefix('#')?;
let v = match n.strip_prefix('x') {
Some(h) if h.bytes().all(|b| b.is_ascii_hexdigit()) => u32::from_str_radix(h, 16).ok()?,
Some(_) => return None,
None if n.bytes().all(|b| b.is_ascii_digit()) => n.parse().ok()?,
None => return None,
};
char::from_u32(v)?
}
})
}
/// Index of the `;` that ends a reference starting at `rest` (its `&`). The scan stops at the first
/// byte that cannot appear in a name or a numeric reference, so zero-padded references such as
/// `&#000000097;` are found and each run of name bytes is read once, not once per `&`.
fn entity_end(rest: &str) -> Option<usize> {
let n = rest.bytes().skip(1).take_while(|b| b.is_ascii_alphanumeric() || *b == b'#').count();
(rest.as_bytes().get(n + 1) == Some(&b';')).then_some(n + 1)
}
fn unescape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(i) = rest.find('&') {
out.push_str(rest.get(..i).unwrap_or_default());
let tail = rest.get(i..).unwrap_or_default();
match entity_end(tail).and_then(|j| entity(tail.get(1..j)?).map(|c| (c, j))) {
Some((c, j)) => {
out.push(c);
rest = tail.get(j + 1..).unwrap_or_default();
}
None => {
out.push('&');
rest = tail.get(1..).unwrap_or_default();
}
}
}
out.push_str(rest);
out
}
/// The document's root element. Malformed markup is an error (strict); an undefined entity is kept as the text
/// `&name;`.
pub(crate) fn parse(s: &str) -> Result<Node, Error> {
let mut reader = quick_xml::Reader::from_str(s);
let mut stack = vec![Node { name: "#root".into(), ..Default::default() }];
let mut count = 0usize;
loop {
let ev = reader.read_event().map_err(|e| Error::Xml(e.to_string()))?;
match ev {
Event::Start(ref e) | Event::Empty(ref e) => {
count += 1;
if count > MAX_NODES || stack.len() > MAX_DEPTH {
return Err(Error::TooLarge);
}
let attrs = e
.attributes()
.with_checks(false)
.flatten()
.map(|a| (String::from_utf8_lossy(a.key.as_ref()).into_owned(), unescape(&String::from_utf8_lossy(&a.value))))
.collect();
let node = Node { name: String::from_utf8_lossy(e.name().as_ref()).into_owned(), attrs, ..Default::default() };
if matches!(ev, Event::Empty(_)) {
if let Some(p) = stack.last_mut() {
p.children.push(node);
}
} else {
stack.push(node);
}
}
Event::End(_) => close(&mut stack),
Event::Text(t) => {
if let Some(top) = stack.last_mut() {
top.text.push_str(&t.decode().map_err(|e| Error::Xml(e.to_string()))?);
}
}
Event::CData(t) => {
if let Some(top) = stack.last_mut() {
top.text.push_str(&String::from_utf8_lossy(&t));
}
}
Event::GeneralRef(r) => {
if let (Some(top), Some(c)) = (stack.last_mut(), entity(&String::from_utf8_lossy(&r))) {
top.text.push(c);
}
}
Event::Eof => break,
_ => {}
}
let limits = craft_xml::Limits { max_depth: MAX_DEPTH, max_nodes: MAX_NODES, ..craft_xml::Limits::DEFAULT };
let options = craft_xml::Options {
strict: true,
unknown_entity: craft_xml::UnknownEntity::Literal,
drop_blank_text: true,
..craft_xml::Options::default()
}
while stack.len() > 1 {
close(&mut stack);
}
stack.pop().ok_or(Error::Xml("empty document".into()))
.with_limits(limits);
options.parse(s.as_bytes()).map_err(|e| if e.is_limit() { Error::TooLarge } else { Error::Xml(e.to_string()) })
}
fn close(stack: &mut Vec<Node>) {
if stack.len() > 1
&& let Some(n) = stack.pop()
&& let Some(p) = stack.last_mut()
{
p.children.push(n);
}
/// A finite number in attribute `k`.
pub(crate) fn num(n: &Node, k: &str) -> Option<f64> {
n.attr(k).and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite())
}
/// The trimmed text of the first child `name`, when not empty.
pub(crate) fn kid_text(n: &Node, name: &str) -> Option<String> {
n.child(name).map(|c| c.text().trim().to_string()).filter(|t| !t.is_empty())
}
#[cfg(test)]
@@ -149,24 +38,15 @@ mod tests {
use super::*;
#[test]
fn many_ampersands_before_one_semicolon_are_read_once() {
// 200 000 `&` then a `;`: each `&` once searched the whole rest for the `;`
let hostile = format!("{};&amp;", "&".repeat(200_000));
assert_eq!(unescape(&hostile), format!("{};&", "&".repeat(200_000)));
assert_eq!(unescape("&lt;a&gt; &#x10FFFF; &unknownreference;"), "<a> \u{10FFFF} &unknownreference;");
fn references_and_padding_decode_and_unknown_entities_stay() {
let root = parse("<lens maker='C&#0000000097;non &amp;'>&#x0000041; &unknownreference;</lens>").unwrap();
assert_eq!(root.attr("maker"), Some("Canon &"));
assert_eq!(root.text(), "A &unknownreference;");
}
#[test]
fn zero_padded_numeric_references_decode() {
assert_eq!(unescape("C&#0000000097;non &#x0000041; &#000000065;"), "Canon A A");
assert_eq!(unescape("&abc&#xyz;&;"), "&abc&#xyz;&;");
}
#[test]
fn entity_rejects_signed_numeric_references() {
assert_eq!(entity("#+65"), None);
assert_eq!(entity("#x+41"), None);
assert_eq!(entity("#65"), Some('A'));
assert_eq!(entity("#x41"), Some('A'));
fn limits_are_too_large() {
assert!(matches!(parse(&"<a>".repeat(MAX_DEPTH + 1)), Err(Error::TooLarge)));
assert!(matches!(parse(&format!("<a>{}</a>", "<b/>".repeat(MAX_NODES))), Err(Error::TooLarge)));
}
}
+2 -1
View File
@@ -10,9 +10,10 @@ workspace = true
[dependencies]
craft-tiff = { workspace = true }
craft-metadata = { workspace = true }
craft-psd = { workspace = true }
lightcraft-geom = { workspace = true }
serde = { workspace = true }
quick-xml = { workspace = true }
chrono = { workspace = true }
[dev-dependencies]
-472
View File
@@ -1,472 +0,0 @@
//! Locating metadata blocks inside image containers.
//!
//! - JPEG (ITU-T T.81 marker structure): APP1 `Exif\0\0`, APP1 `http://ns.adobe.com/xap/1.0/\0` (XMP),
//! APP1 `http://ns.adobe.com/xmp/extension/\0` (extended XMP, reassembled), APP2 `ICC_PROFILE\0`
//! (multi-chunk, reassembled in sequence order), APP13 `Photoshop 3.0\0` 8BIM resource 0x0404 (IPTC-IIM).
//! - PNG (PNG spec 3rd ed.): `eXIf`, `iTXt` with keyword `XML:com.adobe.xmp` (uncompressed).
//! - WebP (RIFF container spec): `EXIF`, `XMP `, `ICCP` chunks.
//! - TIFF-based files (TIFF, DNG and most raws): the whole file is the Exif block; XMP (700), ICC (34675) and
//! IPTC (33723) from IFD0.
//! - Photoshop PSD/PSB: EXIF (image resource 1058) and XMP (image resource 1060) from the bounded image-resource section.
//! - Minolta MRW (see [`crate::mrw`]): the `TTW` block is the Exif block.
//! - Canon CR3 (ISO base media file, see [`crate::cr3`]): `CMT1`/`CMT2`/`CMT4` merged into one Exif block; the
//! XMP `uuid` box.
//! - HEIF/HEIC/AVIF (ISO base media file, see [`crate::heif`]): the `Exif` item's TIFF stream and the XMP
//! `mime` item.
use craft_tiff::{Tiff, tags};
/// Metadata blocks found in a file.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Embedded {
/// TIFF-structured Exif block (without the `Exif\0\0` prefix).
pub exif: Option<Vec<u8>>,
/// XMP packet (the main one; extended XMP is appended by [`Embedded::xmp_extended`]).
pub xmp: Option<String>,
/// Extended XMP (JPEG only), reassembled.
pub xmp_extended: Option<String>,
pub icc: Option<Vec<u8>>,
/// IPTC-IIM stream.
pub iptc: Option<Vec<u8>>,
}
/// Sniff the container and collect its metadata blocks. Unknown containers yield an empty result.
pub fn embedded(bytes: &[u8]) -> Embedded {
if bytes.starts_with(b"8BPS") {
return crate::psd::embedded(bytes);
}
if bytes.starts_with(b"FUJIFILMCCD-RAW") {
// Fujifilm RAF: metadata lives in the embedded JPEG whose (offset, length) are big-endian u32s at byte 84
let be = |i: usize| bytes.get(i..i + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize);
return match (be(84), be(88)) {
(Some(o), Some(l)) if o > 0 => bytes.get(o..o.saturating_add(l).min(bytes.len())).map(jpeg_segments).unwrap_or_default(),
_ => Embedded::default(),
};
}
if let Some(m) = crate::mrw::parse(bytes) {
// Minolta MRW: the `TTW` block is a complete TIFF with the Exif data
return m
.block(b"TTW")
.filter(|t| Tiff::parse(t).is_ok())
.map(|t| Embedded { exif: Some(t.to_vec()), ..Default::default() })
.unwrap_or_default();
}
if let Some(c) = crate::cr3::parse_cr3(bytes) {
return Embedded { exif: crate::cr3::merged_exif(&c), xmp: c.xmp.map(|b| String::from_utf8_lossy(b).into_owned()), ..Default::default() };
}
if crate::heif::is_heif(bytes) {
return crate::heif::metadata(bytes);
}
if bytes.starts_with(&[0xff, 0xd8]) {
jpeg_segments(bytes)
} else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
png_chunks(bytes)
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
webp_chunks(bytes)
} else if let Ok(t) = Tiff::parse(bytes) {
let ifd0 = &t.ifds[0];
Embedded {
exif: Some(bytes.to_vec()),
xmp: ifd0.bytes(tags::XMP).map(|b| String::from_utf8_lossy(b).into_owned()),
xmp_extended: None,
icc: ifd0.bytes(tags::ICC_PROFILE).map(|b| b.to_vec()),
iptc: ifd0.value(tags::IPTC_NAA).map(|v| match v {
craft_tiff::Value::Byte(b) | craft_tiff::Value::Undefined(b) => b.clone(),
other => craft_tiff::writer::encode(t.order, other),
}),
}
} else {
Embedded::default()
}
}
/// Locate metadata blocks while preserving PSD/PSB resource-structure errors for callers that
/// must establish whether embedded GPS is absent. Other containers keep their best-effort walk.
pub(crate) fn try_embedded(bytes: &[u8]) -> Result<Embedded, crate::ExtractError> {
if bytes.starts_with(b"8BPS") { crate::psd::parse(bytes).ok_or(crate::ExtractError::MalformedPsd) } else { Ok(embedded(bytes)) }
}
const XMP_SIG: &[u8] = b"http://ns.adobe.com/xap/1.0/\0";
const XMP_EXT_SIG: &[u8] = b"http://ns.adobe.com/xmp/extension/\0";
/// Walk JPEG markers up to SOS and collect APP1 Exif / XMP, APP2 ICC and APP13 IPTC.
pub fn jpeg_segments(b: &[u8]) -> Embedded {
let mut out = Embedded::default();
if !b.starts_with(&[0xff, 0xd8]) {
return out;
}
let mut icc_parts: [Option<&[u8]>; 255] = [None; 255];
let mut icc_total = None;
let mut icc_invalid = false;
let mut ext: Vec<(u32, Vec<u8>)> = Vec::new();
let mut i = 2usize;
while i + 4 <= b.len() {
if b[i] != 0xff {
break;
}
let marker = b[i + 1];
if marker == 0xff {
i += 1; // fill byte
continue;
}
if marker == 0xd8 || (0xd0..=0xd7).contains(&marker) || marker == 0x01 {
i += 2;
continue;
}
if marker == 0xd9 || marker == 0xda {
break;
}
let len = u16::from_be_bytes([b[i + 2], b[i + 3]]) as usize;
if len < 2 {
break;
}
let Some(start) = i.checked_add(4) else { break };
let Some(declared_end) = i.checked_add(2).and_then(|at| at.checked_add(len)) else { break };
let complete = declared_end <= b.len();
let end = declared_end.min(b.len());
let Some(payload) = b.get(start..end) else { break };
match marker {
0xe1 if payload.starts_with(b"Exif\0") && out.exif.is_none() => out.exif = Some(payload.get(6..).unwrap_or(&[]).to_vec()),
0xe1 if payload.starts_with(XMP_SIG) && out.xmp.is_none() => {
out.xmp = Some(String::from_utf8_lossy(&payload[XMP_SIG.len()..]).into_owned());
}
0xe1 if payload.starts_with(XMP_EXT_SIG) => {
// GUID (32) + full length (4) + offset (4) + data
let p = &payload[XMP_EXT_SIG.len()..];
if p.len() >= 40 {
let off = u32::from_be_bytes([p[36], p[37], p[38], p[39]]);
ext.push((off, p[40..].to_vec()));
}
}
0xe2 if payload.starts_with(b"ICC_PROFILE\0") => {
if !complete || payload.len() < 14 {
icc_invalid = true;
} else if let Some(header) = payload.get(12..14) {
let (Some(&sequence), Some(&total)) = (header.first(), header.get(1)) else {
icc_invalid = true;
i = end;
continue;
};
if sequence == 0 || total == 0 || sequence > total || icc_total.is_some_and(|expected| expected != total) {
icc_invalid = true;
} else {
icc_total = Some(total);
if let Some(slot) = icc_parts.get_mut(usize::from(sequence - 1)) {
if slot.is_some() {
icc_invalid = true;
} else if let Some(data) = payload.get(14..) {
*slot = Some(data);
} else {
icc_invalid = true;
}
} else {
icc_invalid = true;
}
}
} else {
icc_invalid = true;
}
}
0xed if payload.starts_with(b"Photoshop 3.0\0") && out.iptc.is_none() => out.iptc = photoshop_iptc(&payload[14..]),
_ => {}
}
i = end;
}
if let Some(total) = icc_total {
let mut profile_len = 0usize;
for chunk in icc_parts.iter().take(usize::from(total)) {
let Some(bytes) = chunk else {
icc_invalid = true;
break;
};
let Some(next_len) = profile_len.checked_add(bytes.len()) else {
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) {
icc_invalid = true;
}
if !icc_invalid {
let mut profile = Vec::with_capacity(profile_len);
for bytes in icc_parts.iter().take(usize::from(total)).flatten() {
profile.extend_from_slice(bytes);
}
out.icc = Some(profile);
}
}
if !ext.is_empty() {
ext.sort_by_key(|p| p.0);
out.xmp_extended = Some(String::from_utf8_lossy(&ext.into_iter().flat_map(|p| p.1).collect::<Vec<u8>>()).into_owned());
}
out
}
/// IPTC-IIM block (resource 0x0404) from a Photoshop image-resource stream (`8BIM` records).
fn photoshop_iptc(mut b: &[u8]) -> Option<Vec<u8>> {
while b.len() >= 12 && &b[..4] == b"8BIM" {
let id = u16::from_be_bytes([b[4], b[5]]);
let name_len = b[6] as usize;
let name_total = (1 + name_len).next_multiple_of(2);
let size_at = 6 + name_total;
let size = u32::from_be_bytes(b.get(size_at..size_at + 4)?.try_into().ok()?) as usize;
let data_at = size_at + 4;
let data = b.get(data_at..data_at.checked_add(size)?)?;
if id == 0x0404 {
return Some(data.to_vec());
}
b = b.get(data_at + size.next_multiple_of(2)..)?;
}
None
}
/// PNG chunks: `eXIf`, uncompressed `iTXt` XMP.
pub fn png_chunks(b: &[u8]) -> Embedded {
let mut out = Embedded::default();
let mut i = 8usize;
while i + 12 <= b.len() {
let len = u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) as usize;
let typ = &b[i + 4..i + 8];
let Some(data) = b.get(i + 8..(i + 8).saturating_add(len)) else { break };
match typ {
b"eXIf" => out.exif = Some(crate::strip_exif_header(data).to_vec()),
b"iTXt" if data.starts_with(b"XML:com.adobe.xmp\0") => {
// keyword\0 compression-flag compression-method language\0 translated\0 text
let rest = &data[18..];
if rest.len() >= 2 && rest[0] == 0 {
let rest = &rest[2..];
let mut parts = rest.splitn(3, |&c| c == 0);
let (_, _, text) = (parts.next(), parts.next(), parts.next());
if let Some(t) = text {
out.xmp = Some(String::from_utf8_lossy(t).into_owned());
}
}
}
b"IEND" => break,
_ => {}
}
i += 12 + len;
}
out
}
/// WebP RIFF chunks `EXIF`, `XMP `, `ICCP`.
pub fn webp_chunks(b: &[u8]) -> Embedded {
let mut out = Embedded::default();
let mut i = 12usize;
while i + 8 <= b.len() {
let id = &b[i..i + 4];
let len = u32::from_le_bytes([b[i + 4], b[i + 5], b[i + 6], b[i + 7]]) as usize;
let Some(data) = b.get(i + 8..(i + 8).saturating_add(len)) else { break };
match id {
b"EXIF" => out.exif = Some(crate::strip_exif_header(data).to_vec()),
b"XMP " => out.xmp = Some(String::from_utf8_lossy(data).into_owned()),
b"ICCP" => out.icc = Some(data.to_vec()),
_ => {}
}
i += 8 + len + (len & 1);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::exif::tests::sample_exif;
use craft_tiff::ByteOrder;
fn seg(marker: u8, payload: &[u8]) -> Vec<u8> {
let mut v = vec![0xff, marker];
v.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
v.extend_from_slice(payload);
v
}
fn icc_seg(sequence: u8, total: u8, data: &[u8]) -> Vec<u8> {
let mut payload = b"ICC_PROFILE\0".to_vec();
payload.extend_from_slice(&[sequence, total]);
payload.extend_from_slice(data);
seg(0xe2, &payload)
}
fn jpeg_with_icc(parts: &[Vec<u8>]) -> Vec<u8> {
let mut jpeg = vec![0xff, 0xd8];
let packet = crate::write_xmp(&crate::Metadata { title: Some("retained".into()), ..Default::default() }, None);
let mut xmp = XMP_SIG.to_vec();
xmp.extend_from_slice(packet.as_bytes());
jpeg.extend_from_slice(&seg(0xe1, &xmp));
for part in parts {
jpeg.extend_from_slice(part);
}
jpeg.extend_from_slice(&[0xff, 0xda, 0, 2]);
jpeg
}
pub(crate) fn sample_jpeg() -> Vec<u8> {
let mut j = vec![0xff, 0xd8];
j.extend(seg(0xe0, b"JFIF\0\x01\x02\0\0\x01\0\x01\0\0"));
let mut exif = b"Exif\0\0".to_vec();
exif.extend(sample_exif(ByteOrder::Big));
j.extend(seg(0xe1, &exif));
let meta = crate::Metadata { title: Some("Sunset".into()), rating: Some(4), ..Default::default() };
let mut xmp = XMP_SIG.to_vec();
xmp.extend(crate::write_xmp(&meta, Some("{\"exposure\":1.5}")).into_bytes());
j.extend(seg(0xe1, &xmp));
// ICC in two chunks, out of order
j.extend(seg(0xe2, b"ICC_PROFILE\0\x02\x02WORLD"));
j.extend(seg(0xe2, b"ICC_PROFILE\0\x01\x02HELLO"));
// IPTC
let iim = crate::iptc::tests::sample_iim();
let mut ps = b"Photoshop 3.0\0".to_vec();
ps.extend_from_slice(b"8BIM\x04\x0c\0\0");
ps.extend_from_slice(&2u32.to_be_bytes());
ps.extend_from_slice(&[1, 2]);
ps.extend_from_slice(b"8BIM\x04\x04\0\0");
ps.extend_from_slice(&(iim.len() as u32).to_be_bytes());
ps.extend_from_slice(&iim);
j.extend(seg(0xed, &ps));
j.extend_from_slice(&[0xff, 0xda, 0, 2, 1, 2, 3, 0xff, 0xd9]);
j
}
#[test]
fn jpeg_blocks() {
let j = sample_jpeg();
let e = jpeg_segments(&j);
assert_eq!(e.icc.as_deref(), Some(&b"HELLOWORLD"[..]));
assert!(e.xmp.as_deref().unwrap().contains("Sunset"));
assert!(e.iptc.is_some());
let m = crate::extract(&j);
assert_eq!(m.iso, Some(400));
assert_eq!(m.title.as_deref(), Some("Sunset"));
assert_eq!(m.rating, Some(4)); // XMP overrides EXIF rating 3
assert_eq!(m.keywords, vec!["alpha".to_string(), "beta".to_string()]); // from IPTC
assert_eq!(m.caption.as_deref(), Some("A caption"));
}
#[test]
fn jpeg_extended_xmp() {
let mut j = vec![0xff, 0xd8];
for (off, part) in [(5u32, &b"world"[..]), (0, b"hello")] {
let mut p = XMP_EXT_SIG.to_vec();
p.extend_from_slice(&[b'A'; 32]);
p.extend_from_slice(&10u32.to_be_bytes());
p.extend_from_slice(&off.to_be_bytes());
p.extend_from_slice(part);
j.extend(seg(0xe1, &p));
}
assert_eq!(jpeg_segments(&j).xmp_extended.as_deref(), Some("helloworld"));
}
#[test]
fn jpeg_icc_accepts_reordered_chunks() {
let parts = [icc_seg(2, 2, b"world"), icc_seg(1, 2, b"hello")];
let embedded = jpeg_segments(&jpeg_with_icc(&parts));
assert_eq!(embedded.icc.as_deref(), Some(&b"helloworld"[..]));
}
#[test]
fn jpeg_icc_rejects_incomplete_or_incoherent_chunks() {
let cases = [
("missing", vec![icc_seg(1, 2, b"helloworld")]),
("duplicate", vec![icc_seg(1, 2, b"hello"), icc_seg(1, 2, b"world")]),
("zero sequence", vec![icc_seg(0, 1, b"helloworld")]),
("zero total", vec![icc_seg(1, 0, b"helloworld")]),
("out of range", vec![icc_seg(2, 1, b"helloworld")]),
("gap", vec![icc_seg(1, 3, b"hello"), icc_seg(3, 3, b"world")]),
("inconsistent totals", vec![icc_seg(1, 2, b"hello"), icc_seg(2, 3, b"world")]),
("short header", vec![seg(0xe2, b"ICC_PROFILE\0\x01")]),
];
for (name, parts) in cases {
let embedded = jpeg_segments(&jpeg_with_icc(&parts));
assert!(embedded.icc.is_none(), "{name} ICC chunks must be rejected");
assert!(embedded.xmp.as_deref().is_some_and(|x| x.contains("retained")), "{name}: unrelated XMP must remain readable");
}
}
#[test]
fn jpeg_icc_rejects_truncated_segment_and_keeps_other_metadata() {
let mut truncated = icc_seg(1, 1, b"profile");
let declared = u16::from_be_bytes([truncated[2], truncated[3]]).saturating_add(1);
truncated[2..4].copy_from_slice(&declared.to_be_bytes());
let mut jpeg = vec![0xff, 0xd8];
let xmp = crate::write_xmp(&crate::Metadata { title: Some("kept".into()), ..Default::default() }, None);
let mut packet = XMP_SIG.to_vec();
packet.extend_from_slice(xmp.as_bytes());
jpeg.extend_from_slice(&seg(0xe1, &packet));
jpeg.extend_from_slice(&truncated);
let embedded = jpeg_segments(&jpeg);
assert!(embedded.icc.is_none());
assert!(embedded.xmp.as_deref().is_some_and(|x| x.contains("kept")));
}
#[test]
fn png_and_webp() {
let exif = sample_exif(ByteOrder::Little);
let mut p = b"\x89PNG\r\n\x1a\n".to_vec();
let mut chunk = |typ: &[u8], data: &[u8]| {
p.extend_from_slice(&(data.len() as u32).to_be_bytes());
p.extend_from_slice(typ);
p.extend_from_slice(data);
p.extend_from_slice(&[0; 4]);
};
chunk(b"eXIf", &exif);
let mut itxt = b"XML:com.adobe.xmp\0\0\0\0\0".to_vec();
itxt.extend(crate::write_xmp(&crate::Metadata { label: Some("Red".into()), ..Default::default() }, None).into_bytes());
chunk(b"iTXt", &itxt);
chunk(b"IEND", &[]);
let m = crate::extract(&p);
assert_eq!(m.iso, Some(400));
assert_eq!(m.label.as_deref(), Some("Red"));
let mut w = b"RIFF\0\0\0\0WEBP".to_vec();
let mut body = |id: &[u8], data: &[u8]| {
w.extend_from_slice(id);
w.extend_from_slice(&(data.len() as u32).to_le_bytes());
w.extend_from_slice(data);
if data.len() % 2 == 1 {
w.push(0);
}
};
body(b"VP8X", &[0; 10]);
body(b"ICCP", b"abc");
let mut ex = b"Exif\0\0".to_vec();
ex.extend_from_slice(&exif);
body(b"EXIF", &ex);
let e = webp_chunks(&w);
assert_eq!(e.icc.as_deref(), Some(&b"abc"[..]));
assert_eq!(crate::extract(&w).f_number, Some(2.8));
}
#[test]
fn tiff_file_is_its_own_exif() {
let t = sample_exif(ByteOrder::Big);
assert_eq!(crate::extract(&t).model.as_deref(), Some("Model X"));
assert_eq!(embedded(b"not an image"), Embedded::default());
}
#[test]
fn raf_reads_its_embedded_jpeg() {
let j = sample_jpeg();
let mut raf = b"FUJIFILMCCD-RAW 0201FF000000TEST".to_vec();
raf.resize(120, 0);
raf[84..88].copy_from_slice(&120u32.to_be_bytes());
raf[88..92].copy_from_slice(&(j.len() as u32).to_be_bytes());
raf.extend_from_slice(&j);
assert_eq!(crate::extract(&raf).iso, Some(400));
for n in 0..raf.len() {
let _ = crate::extract(&raf[..n]);
}
}
#[test]
fn truncated_containers_do_not_panic() {
let j = sample_jpeg();
for n in 0..j.len() {
let _ = crate::extract(&j[..n]);
}
}
}
+133
View File
@@ -0,0 +1,133 @@
use crate::{FocusPoint, Metadata, Orientation, Rect, Region, XmpData};
pub(crate) fn rect_from_craft(r: craft_metadata::Rect) -> Rect {
Rect { x0: r.x0, y0: r.y0, x1: r.x1, y1: r.y1 }
}
pub(crate) fn rect_to_craft(r: Rect) -> craft_metadata::Rect {
craft_metadata::Rect { x0: r.x0, y0: r.y0, x1: r.x1, y1: r.y1 }
}
pub(crate) fn orientation_from_craft(o: craft_metadata::Orientation) -> Orientation {
Orientation::from_exif(o.to_exif())
}
pub(crate) fn orientation_to_craft(o: Orientation) -> craft_metadata::Orientation {
craft_metadata::Orientation::from_exif(o.to_exif())
}
pub(crate) fn focus_from_craft(f: craft_metadata::FocusPoint) -> FocusPoint {
FocusPoint { rect: rect_from_craft(f.rect), mode: f.mode, area: f.area, tracking: f.tracking }
}
pub(crate) fn focus_to_craft(f: &FocusPoint) -> craft_metadata::FocusPoint {
craft_metadata::FocusPoint { rect: rect_to_craft(f.rect), mode: f.mode.clone(), area: f.area.clone(), tracking: f.tracking.clone() }
}
pub(crate) fn region_from_craft(r: craft_metadata::Region) -> Region {
Region { rect: rect_from_craft(r.rect), kind: r.kind, name: r.name, description: r.description }
}
pub(crate) fn region_to_craft(r: &Region) -> craft_metadata::Region {
craft_metadata::Region { rect: rect_to_craft(r.rect), kind: r.kind.clone(), name: r.name.clone(), description: r.description.clone() }
}
pub(crate) fn from_craft(m: craft_metadata::Metadata) -> Metadata {
Metadata {
make: m.make,
model: m.model,
serial_number: m.serial_number,
software: m.software,
lens_make: m.lens_make,
lens_model: m.lens_model,
lens_serial_number: m.lens_serial_number,
lens_spec: m.lens_spec,
capture_time: m.capture_time,
exposure_time: m.exposure_time,
f_number: m.f_number,
iso: m.iso,
focal_length: m.focal_length,
focal_length_35mm: m.focal_length_35mm,
flash: m.flash,
exposure_bias: m.exposure_bias,
exposure_program: m.exposure_program,
metering_mode: m.metering_mode,
white_balance: m.white_balance,
orientation: m.orientation.map(orientation_from_craft),
gps: m.gps,
width: m.width,
height: m.height,
artist: m.artist,
copyright: m.copyright,
copyright_marked: m.copyright_marked,
usage_terms: m.usage_terms,
copyright_url: m.copyright_url,
title: m.title,
caption: m.caption,
alt_text: m.alt_text,
extended_description: m.extended_description,
sublocation: m.sublocation,
city: m.city,
state: m.state,
country: m.country,
keywords: m.keywords,
hierarchical_keywords: m.hierarchical_keywords,
rating: m.rating,
label: m.label,
regions: m.regions.into_iter().map(region_from_craft).collect(),
focus: m.focus.map(focus_from_craft),
}
}
pub(crate) fn to_craft(m: &Metadata) -> craft_metadata::Metadata {
craft_metadata::Metadata {
make: m.make.clone(),
model: m.model.clone(),
serial_number: m.serial_number.clone(),
software: m.software.clone(),
lens_make: m.lens_make.clone(),
lens_model: m.lens_model.clone(),
lens_serial_number: m.lens_serial_number.clone(),
lens_spec: m.lens_spec,
capture_time: m.capture_time,
exposure_time: m.exposure_time,
f_number: m.f_number,
iso: m.iso,
focal_length: m.focal_length,
focal_length_35mm: m.focal_length_35mm,
flash: m.flash,
exposure_bias: m.exposure_bias,
exposure_program: m.exposure_program,
metering_mode: m.metering_mode,
white_balance: m.white_balance,
orientation: m.orientation.map(orientation_to_craft),
gps: m.gps,
width: m.width,
height: m.height,
artist: m.artist.clone(),
copyright: m.copyright.clone(),
copyright_marked: m.copyright_marked,
usage_terms: m.usage_terms.clone(),
copyright_url: m.copyright_url.clone(),
title: m.title.clone(),
caption: m.caption.clone(),
alt_text: m.alt_text.clone(),
extended_description: m.extended_description.clone(),
sublocation: m.sublocation.clone(),
city: m.city.clone(),
state: m.state.clone(),
country: m.country.clone(),
keywords: m.keywords.clone(),
hierarchical_keywords: m.hierarchical_keywords.clone(),
rating: m.rating,
label: m.label.clone(),
regions: m.regions.iter().map(region_to_craft).collect(),
focus: m.focus.as_ref().map(focus_to_craft),
fuji_recipe: None,
}
}
pub(crate) fn xmp_from_craft(d: craft_metadata::XmpData) -> XmpData {
let lc_settings = d.properties.get("lc:settings").and_then(|v| v.first()).cloned();
XmpData { metadata: from_craft(d.metadata), lc_settings, properties: d.properties, values: d.values }
}
-742
View File
@@ -1,742 +0,0 @@
//! Canon CR3: the ISO base media file container (ISO/IEC 14496-12 box structure; CR3 layout from Laurent
//! Clévy's public CR3 format notes, confirmed black-box on EOS R6 Mark III files).
//!
//! - `ftyp` with major brand `crx `.
//! - `moov` holds a Canon `uuid` box (85c0b687-820f-11e0-8111-f4ce462b6a48) whose children are `CMT1` (a TIFF
//! stream: IFD0), `CMT2` (TIFF: the Exif IFD), `CMT3` (TIFF: the Canon maker note), `CMT4` (TIFF: GPS) and the
//! `THMB` thumbnail, then one `trak` per stream: a full-size JPEG, a reduced raw, the full raw (`CRAW` sample
//! entries; raws carry a `CMP1` coding header) and timed metadata (`CTMD`).
//! - A top-level `uuid` box with the XMP uuid (be7acfcb-97a9-42e8-9c71-999491e3afac, XMP spec part 3) holds the
//! XMP packet.
//!
//! Every size and offset is checked against the buffer; nesting and box counts are bounded.
/// A track's sample-entry kind.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Cr3TrackKind {
/// `CRAW` with a `JPEG` child: the full-size JPEG.
Jpeg,
/// `CRAW` raw image: dimensions and the `CMP1` coding header (byte range in the file).
Raw {
width: u16,
height: u16,
cmp1: Option<(usize, usize)>,
/// `CDI1/IAD1` image-area descriptor (byte range in the file).
iad1: Option<(usize, usize)>,
},
/// Anything else (`CTMD` timed metadata, unknown entries).
Other([u8; 4]),
}
/// One track's single sample: where it is in the file.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cr3Track {
pub kind: Cr3TrackKind,
/// Byte offset and length of the sample (the first one) in the file, when the tables give them.
pub data: Option<(usize, usize)>,
}
/// Canon's `CMP1` image coding descriptor, separate from the encoded track sample.
///
/// Parsed from the payload (after the eight-byte box header). Geometry is the full sensor mosaic,
/// including optically masked borders. Unsupported encoding modes are retained for the decoder to
/// report explicitly, rather than confused with the full-size embedded JPEG.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cr3Compression {
pub version: u16,
pub width: u32,
pub height: u32,
pub tile_width: u32,
pub tile_height: u32,
pub bit_depth: u8,
pub planes: u8,
/// 0 = RGGB, 1 = GRBG, 2 = GBRG, 3 = BGGR.
pub cfa_pattern: u8,
pub encoding: u8,
pub levels: u8,
pub tile_flags: u8,
/// Number of bytes at the start of the sample before its entropy-coded data.
pub header_size: u32,
pub median_bit_depth: Option<u8>,
}
impl Cr3Compression {
/// Read the public `CMP1` field layout. Truncated or impossible descriptors return `None`.
pub fn parse(payload: &[u8]) -> Option<Self> {
// The first word is reserved in the public notes; real files use FF00, although older
// descriptions guessed FFFF. It is not a reliable format signature.
let header_len = usize::from(be16(payload, 2)?).checked_add(4)?;
if header_len < 52 || header_len > payload.len() {
return None;
}
let packed = *payload.get(25)?;
let coding = *payload.get(26)?;
let mut out = Self {
version: be16(payload, 4)?,
width: be32(payload, 8)?,
height: be32(payload, 12)?,
tile_width: be32(payload, 16)?,
tile_height: be32(payload, 20)?,
bit_depth: *payload.get(24)?,
planes: packed >> 4,
cfa_pattern: packed & 15,
encoding: coding >> 4,
levels: coding & 15,
tile_flags: *payload.get(27)?,
header_size: be32(payload, 28)?,
median_bit_depth: None,
};
if out.width == 0
|| out.height == 0
|| out.tile_width == 0
|| out.tile_height == 0
|| out.tile_width > out.width
|| out.tile_height > out.height
|| !(1..=16).contains(&out.bit_depth)
|| !(1..=4).contains(&out.planes)
|| (out.planes > 1 && out.cfa_pattern > 3)
|| out.header_size == 0
{
return None;
}
if payload.get(32).is_some_and(|flags| flags & 0x80 != 0) {
// Extended CMP1: a four-byte length, flags, reserved bytes and six words. The optional
// median precision is used by type-3 burst encodings, not ordinary Bayer raw/craw.
let extension_len = usize::try_from(be32(payload, 52)?).ok()?;
let extension_end = 52usize.checked_add(extension_len)?;
if extension_len < 32 || extension_end > payload.len() {
return None;
}
if payload.get(56).is_some_and(|flags| flags & 0x40 != 0) {
let precision = *payload.get(84).filter(|_| extension_end > 84)?;
if !(1..=16).contains(&precision) {
return None;
}
out.median_bit_depth = Some(precision);
}
}
Some(out)
}
}
/// `IAD1` geometry. Coordinates are inclusive sensor offsets: `[left, top, right, bottom]`.
/// A full raw descriptor distinguishes valid sensor pixels from the recommended final crop.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cr3ImageArea {
pub width: u16,
pub height: u16,
pub crop: [u16; 4],
pub active: Option<[u16; 4]>,
pub masked_left: [u16; 4],
pub masked_top: Option<[u16; 4]>,
}
impl Cr3ImageArea {
pub fn parse(payload: &[u8]) -> Option<Self> {
let bounds = |at: usize| Some([be16(payload, at)?, be16(payload, at + 2)?, be16(payload, at + 4)?, be16(payload, at + 6)?]);
let width = be16(payload, 4)?;
let height = be16(payload, 6)?;
if width == 0 || height == 0 {
return None;
}
let full = be16(payload, 10)? == 2;
Some(Self {
width,
height,
crop: bounds(16)?,
masked_left: bounds(24)?,
masked_top: if full { Some(bounds(32)?) } else { None },
active: if full { Some(bounds(40)?) } else { None },
})
}
}
impl Cr3Track {
/// Decode this track's image coding descriptor without reading its pixel data.
pub fn compression(&self, bytes: &[u8]) -> Option<Cr3Compression> {
let Cr3TrackKind::Raw { cmp1: Some((at, len)), .. } = self.kind else { return None };
Cr3Compression::parse(bytes.get(at..at.checked_add(len)?)?)
}
pub fn image_area(&self, bytes: &[u8]) -> Option<Cr3ImageArea> {
let Cr3TrackKind::Raw { iad1: Some((at, len)), .. } = self.kind else { return None };
Cr3ImageArea::parse(bytes.get(at..at.checked_add(len)?)?)
}
}
/// The parts of a CR3 file LightCraft reads.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Cr3<'a> {
/// `CMT1`…`CMT4` (index 0…3).
pub cmt: [Option<&'a [u8]>; 4],
pub thumbnail: Option<&'a [u8]>,
pub xmp: Option<&'a [u8]>,
pub tracks: Vec<Cr3Track>,
}
/// One independent TIFF block from Canon timed metadata. Its offsets remain relative to this block.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cr3TimedExif<'a> {
/// CTMD record type (7, 8 or 9).
pub record_type: u16,
/// Exif IFD (`0x8769`) or Canon maker note (`0x927c`).
pub tag: u32,
pub data: &'a [u8],
}
impl Cr3<'_> {
/// Read TIFF blocks in the first samples of CTMD tracks. As-shot white balance and sensor
/// levels often live here rather than in the static `CMT3` maker note. Both record layers use
/// little-endian byte lengths; TIFF blocks retain their own byte order and offset origin.
pub fn timed_exif<'a>(&self, bytes: &'a [u8]) -> Vec<Cr3TimedExif<'a>> {
let mut out = Vec::new();
let mut budget = MAX_BOXES;
for track in &self.tracks {
if track.kind != Cr3TrackKind::Other(*b"CTMD") {
continue;
}
let Some(sample) = track.data.and_then(|(at, len)| at.checked_add(len).and_then(|end| bytes.get(at..end))) else { continue };
let mut at = 0usize;
while budget > 0 {
budget -= 1;
let Some(len) = le32(sample, at).and_then(|v| usize::try_from(v).ok()) else { break };
let Some(end) = at.checked_add(len).filter(|&end| len >= 12 && end <= sample.len()) else { break };
let Some(record) = sample.get(at..end) else { break };
let Some(kind) = le16(record, 4) else { break };
if matches!(kind, 7..=9) {
let mut item_at = 12usize;
while budget > 0 {
budget -= 1;
let Some(item_len) = le32(record, item_at).and_then(|v| usize::try_from(v).ok()) else { break };
let Some(item_end) = item_at.checked_add(item_len).filter(|&end| item_len >= 8 && end <= record.len()) else { break };
let Some(item) = record.get(item_at..item_end) else { break };
if let Some(tag @ (0x8769 | 0x927c)) = le32(item, 4)
&& let Some(data) = item.get(8..)
{
out.push(Cr3TimedExif { record_type: kind, tag, data });
}
item_at = item_end;
}
}
at = end;
}
}
out
}
}
const CANON_UUID: [u8; 16] = [0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48];
/// The `uuid` of the top-level box holding the XMP packet.
pub const XMP_UUID: [u8; 16] = [0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac];
const MAX_DEPTH: usize = 12;
pub(crate) const MAX_BOXES: usize = 4096;
/// A `VisualSampleEntry` (78 bytes after the box header) plus 4 bytes Canon adds before the child boxes.
const CRAW_CHILDREN_AT: usize = 82;
/// Does this look like a CR3 file (`ftyp` box with major brand `crx `)?
pub fn is_cr3(bytes: &[u8]) -> bool {
bytes.get(4..12) == Some(b"ftypcrx ".as_slice())
}
/// Parse a CR3 file's boxes; `None` when it is not a CR3 file. Of the top-level boxes only `moov`
/// and the XMP `uuid` are read (`lightcraft_raw::sparse` relies on it to skip the others).
pub fn parse_cr3(bytes: &[u8]) -> Option<Cr3<'_>> {
if !is_cr3(bytes) {
return None;
}
let mut out = Cr3::default();
let mut budget = MAX_BOXES;
for b in boxes(bytes, 0, bytes.len(), &mut budget) {
match &b.kind {
b"moov" => moov(bytes, &b, &mut out, &mut budget),
b"uuid" if b.uuid == Some(XMP_UUID) => out.xmp = bytes.get(b.body..b.end),
_ => {}
}
}
Some(out)
}
pub(crate) struct BoxRef {
pub(crate) kind: [u8; 4],
/// Start of the payload (after the header and, for `uuid`, the 16-byte uuid).
pub(crate) body: usize,
pub(crate) end: usize,
pub(crate) uuid: Option<[u8; 16]>,
}
/// The boxes directly inside `[from, to)`; stops at the first malformed header.
pub(crate) fn boxes(bytes: &[u8], from: usize, to: usize, budget: &mut usize) -> Vec<BoxRef> {
let mut out = Vec::new();
let mut at = from;
let to = to.min(bytes.len());
while at.saturating_add(8) <= to && *budget > 0 {
*budget -= 1;
let (Some(size), Some(kind)) = (be32(bytes, at), bytes.get(at + 4..at + 8)) else { break };
let mut kind4 = [0u8; 4];
kind4.copy_from_slice(kind);
let (len, mut hdr) = match size {
0 => (to - at, 8),
1 => match be64(bytes, at + 8).and_then(|v| usize::try_from(v).ok()) {
Some(l) => (l, 16),
None => break,
},
n => (n as usize, 8),
};
let Some(end) = at.checked_add(len).filter(|&e| e <= to && len >= hdr) else { break };
let mut uuid = None;
if &kind4 == b"uuid" {
let Some(u) = bytes.get(at + hdr..at + hdr + 16).filter(|_| at + hdr + 16 <= end) else { break };
let mut a = [0u8; 16];
a.copy_from_slice(u);
uuid = Some(a);
hdr += 16;
}
out.push(BoxRef { kind: kind4, body: at + hdr, end, uuid });
at = end;
}
out
}
fn moov<'a>(bytes: &'a [u8], m: &BoxRef, out: &mut Cr3<'a>, budget: &mut usize) {
for b in boxes(bytes, m.body, m.end, budget) {
match &b.kind {
b"uuid" if b.uuid == Some(CANON_UUID) => {
for c in boxes(bytes, b.body, b.end, budget) {
let slot = match &c.kind {
b"CMT1" => 0,
b"CMT2" => 1,
b"CMT3" => 2,
b"CMT4" => 3,
b"THMB" => {
out.thumbnail = bytes.get(c.body..c.end);
continue;
}
_ => continue,
};
out.cmt[slot] = bytes.get(c.body..c.end);
}
}
b"trak" => {
if let Some(t) = trak(bytes, &b, budget) {
out.tracks.push(t);
}
}
_ => {}
}
}
}
/// Descend `trak` → `mdia` → `minf` → `stbl` and read its sample entry and first sample's location.
fn trak(bytes: &[u8], t: &BoxRef, budget: &mut usize) -> Option<Cr3Track> {
let mut stbl = None;
let mut stack = vec![(t.body, t.end, 0usize)];
while let Some((from, to, depth)) = stack.pop() {
if depth > MAX_DEPTH {
continue;
}
for b in boxes(bytes, from, to, budget) {
match &b.kind {
b"mdia" | b"minf" => stack.push((b.body, b.end, depth + 1)),
b"stbl" => stbl = Some(b),
_ => {}
}
}
}
let stbl = stbl?;
let (mut kind, mut size, mut offset) = (None, None, None);
for b in boxes(bytes, stbl.body, stbl.end, budget) {
let body = bytes.get(b.body..b.end)?;
match &b.kind {
// full box: version/flags, entry count, entries
b"stsd" if be32(body, 4)? > 0 => kind = boxes(bytes, b.body + 8, b.end, budget).first().map(|e| sample_entry(bytes, e, budget)),
// version/flags, sample_size (0 = per-sample table), count, sizes
b"stsz" => {
size = match be32(body, 4)? {
0 if be32(body, 8)? > 0 => be32(body, 12),
0 => None,
n if be32(body, 8)? > 0 => Some(n),
_ => None,
}
}
b"co64" if be32(body, 4)? > 0 => offset = be64(body, 8).and_then(|v| usize::try_from(v).ok()),
b"stco" if be32(body, 4)? > 0 => offset = be32(body, 8).map(|v| v as usize),
_ => {}
}
}
let data = match (offset, size) {
(Some(o), Some(s)) if o.checked_add(s as usize).is_some_and(|e| e <= bytes.len()) => Some((o, s as usize)),
_ => None,
};
Some(Cr3Track { kind: kind?, data })
}
fn sample_entry(bytes: &[u8], e: &BoxRef, budget: &mut usize) -> Cr3TrackKind {
if &e.kind != b"CRAW" {
return Cr3TrackKind::Other(e.kind);
}
let Some(body) = bytes.get(e.body..e.end) else { return Cr3TrackKind::Other(e.kind) };
let (Some(width), Some(height)) = (be16(body, 24), be16(body, 26)) else {
return Cr3TrackKind::Other(e.kind);
};
let (mut cmp1, mut iad1, mut rendered) = (None, None, None);
for c in boxes(bytes, e.body.saturating_add(CRAW_CHILDREN_AT), e.end, budget) {
match &c.kind {
b"JPEG" => rendered = Some(Cr3TrackKind::Jpeg),
// HDR-capable cameras also put an HEVC preview in a CRAW entry,
// often with the same displayed dimensions as the main raw track.
b"HEVC" => rendered = Some(Cr3TrackKind::Other(c.kind)),
b"CMP1" => cmp1 = Some((c.body, c.end - c.body)),
b"CDI1" => {
for area in boxes(bytes, c.body.saturating_add(4), c.end, budget) {
if &area.kind == b"IAD1" {
iad1 = Some((area.body, area.end - area.body));
}
}
}
_ => {}
}
}
// A present, malformed CMP1 must remain a raw descriptor so its corruption
// is reported. Only an explicitly identified rendered codec can establish
// that a CRAW entry without CMP1 is a preview rather than a broken raw.
if cmp1.is_none()
&& let Some(kind) = rendered
{
return kind;
}
Cr3TrackKind::Raw { width, height, cmp1, iad1 }
}
/// A big-endian `u16` at `at`, or `None` when the buffer is shorter than that.
pub(crate) fn be16(b: &[u8], at: usize) -> Option<u16> {
b.get(at..at.checked_add(2)?).map(|s| u16::from_be_bytes([s[0], s[1]]))
}
/// A big-endian `u32` at `at`, or `None` when the buffer is shorter than that.
pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
b.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
}
/// A big-endian `u64` at `at`, or `None` when the buffer is shorter than that.
pub(crate) fn be64(b: &[u8], at: usize) -> Option<u64> {
let s = b.get(at..at.checked_add(8)?)?;
let mut a = [0u8; 8];
a.copy_from_slice(s);
Some(u64::from_be_bytes(a))
}
fn le16(b: &[u8], at: usize) -> Option<u16> {
let s = b.get(at..at.checked_add(2)?)?;
Some(u16::from_le_bytes([s[0], s[1]]))
}
fn le32(b: &[u8], at: usize) -> Option<u32> {
let s = b.get(at..at.checked_add(4)?)?;
Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
/// Merge `CMT1` (IFD0), `CMT2` (Exif) and `CMT4` (GPS) into one TIFF stream, so the Exif readers see a CR3
/// like any TIFF-based raw. The maker note (`CMT3`) is left out: its offsets are relative to its own block.
pub fn merged_exif(c: &Cr3<'_>) -> Option<Vec<u8>> {
use craft_tiff::{IfdBuilder, Tiff, TiffWriter, tags as t};
let ifd0 = Tiff::parse(c.cmt[0]?).ok()?;
let order = ifd0.order;
let first = |i: usize| c.cmt[i].and_then(|b| Tiff::parse(b).ok()).and_then(|t| t.ifds.into_iter().next());
// pointers and offsets that would dangle once the IFDs move
const SKIP: [u16; 9] = [t::EXIF_IFD, t::GPS_IFD, t::INTEROP_IFD, t::SUB_IFDS, t::MAKER_NOTE, 273, 279, 513, 514];
let build = |ifd: &craft_tiff::Ifd| {
let mut b = IfdBuilder::new();
for e in ifd.entries.iter().filter(|e| !SKIP.contains(&e.tag)) {
b.set(e.tag, e.value.clone());
}
b
};
let mut root = build(ifd0.ifds.first()?);
if let Some(exif) = first(1) {
root.set_child(t::EXIF_IFD, build(&exif));
}
if let Some(gps) = first(3) {
root.set_child(t::GPS_IFD, build(&gps));
}
TiffWriter::new(order, false).write(&[root]).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
v.extend_from_slice(kind);
v.extend_from_slice(body);
v
}
fn uuid(u: &[u8; 16], body: &[u8]) -> Vec<u8> {
let mut b = u.to_vec();
b.extend_from_slice(body);
bx(b"uuid", &b)
}
fn full(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut b = vec![0u8; 4];
b.extend_from_slice(body);
bx(kind, &b)
}
fn craw(w: u16, h: u16, children: &[u8]) -> Vec<u8> {
let mut b = vec![0u8; CRAW_CHILDREN_AT];
b[24..26].copy_from_slice(&w.to_be_bytes());
b[26..28].copy_from_slice(&h.to_be_bytes());
b.extend_from_slice(children);
bx(b"CRAW", &b)
}
fn trak(entry: Vec<u8>, offset: u64, size: u32) -> Vec<u8> {
let mut stsd = 1u32.to_be_bytes().to_vec();
stsd.extend(entry);
let mut stsz = 0u32.to_be_bytes().to_vec();
stsz.extend(1u32.to_be_bytes());
stsz.extend(size.to_be_bytes());
let mut co64 = 1u32.to_be_bytes().to_vec();
co64.extend(offset.to_be_bytes());
let stbl = [full(b"stsd", &stsd), full(b"stsz", &stsz), full(b"co64", &co64)].concat();
bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &stbl))))
}
fn tiff_with(tag: u16, v: craft_tiff::Value) -> Vec<u8> {
let b = craft_tiff::IfdBuilder::new().with(tag, v);
craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[b]).unwrap()
}
/// A small synthetic CR3: Canon uuid with CMT1/CMT2/CMT4, a JPEG track, a raw track, XMP.
pub(crate) fn sample() -> Vec<u8> {
use craft_tiff::{Value, tags as t};
let cmt1 = tiff_with(t::MODEL, Value::Ascii("Canon EOS Test".into()));
let cmt2 = tiff_with(t::ISO_SPEED, Value::Short(vec![400]));
let cmt4 = tiff_with(1, Value::Ascii("N".into()));
let canon = uuid(&CANON_UUID, &[bx(b"CMT1", &cmt1), bx(b"CMT2", &cmt2), bx(b"CMT4", &cmt4), bx(b"THMB", b"thumb")].concat());
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
let payload_at = 4096u64;
let jpeg_t = trak(craw(64, 48, &bx(b"JPEG", &[0; 4])), payload_at, 16);
let raw_t = trak(craw(60, 40, &bx(b"CMP1", &[0xff, 0x10, 0, 0x30])), payload_at + 16, 32);
file.extend(bx(b"moov", &[canon, jpeg_t, raw_t].concat()));
file.extend(uuid(&XMP_UUID, b"<x:xmpmeta/>"));
file.resize(payload_at as usize + 64, 0);
file
}
#[test]
fn parses_canon_boxes_tracks_and_xmp() {
let f = sample();
assert!(is_cr3(&f));
let c = parse_cr3(&f).unwrap();
assert!(c.cmt[0].is_some() && c.cmt[1].is_some() && c.cmt[2].is_none() && c.cmt[3].is_some());
assert_eq!(c.thumbnail, Some(b"thumb".as_slice()));
assert_eq!(c.xmp, Some(b"<x:xmpmeta/>".as_slice()));
assert_eq!(c.tracks.len(), 2);
assert_eq!(c.tracks[0], Cr3Track { kind: Cr3TrackKind::Jpeg, data: Some((4096, 16)) });
let Cr3TrackKind::Raw { width, height, cmp1: Some((at, len)), .. } = c.tracks[1].kind else { panic!("{:?}", c.tracks[1]) };
assert_eq!((width, height, len), (60, 40, 4));
assert_eq!(&f[at..at + 2], &[0xff, 0x10]);
assert_eq!(c.tracks[1].data, Some((4112, 32)));
}
#[test]
fn hevc_preview_is_distinct_from_an_equal_size_raw_track() {
let preview = trak(craw(6000, 4000, &bx(b"HEVC", &[0; 4])), 4096, 16);
let reduced = trak(craw(1624, 1080, &bx(b"CMP1", &compression_payload(0))), 4112, 16);
let sensor = trak(craw(6000, 4000, &bx(b"CMP1", &compression_payload(0))), 4128, 16);
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"moov", &[preview, reduced, sensor].concat()));
file.resize(4144, 0);
let container = parse_cr3(&file).unwrap();
assert_eq!(container.tracks[0].kind, Cr3TrackKind::Other(*b"HEVC"));
assert!(container.tracks[0].compression(&file).is_none());
assert!(matches!(container.tracks[2].kind, Cr3TrackKind::Raw { width: 6000, height: 4000, cmp1: Some(_), .. }));
assert_eq!(container.tracks[2].compression(&file).unwrap().width, 6888);
}
#[test]
fn rendered_child_does_not_hide_a_malformed_raw_descriptor() {
for codec in [b"JPEG", b"HEVC"] {
for first in [true, false] {
let rendered = bx(codec, &[0; 4]);
let corrupt = bx(b"CMP1", &[0xff, 0]);
let children = if first { [rendered, corrupt] } else { [corrupt, rendered] }.concat();
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"moov", &trak(craw(6000, 4000, &children), 4096, 16)));
file.resize(4112, 0);
let container = parse_cr3(&file).unwrap();
assert!(matches!(container.tracks[0].kind, Cr3TrackKind::Raw { cmp1: Some(_), .. }));
assert!(container.tracks[0].compression(&file).is_none());
}
}
// Absence alone is not evidence of a preview: retain a broken raw so
// main-track selection cannot quietly fall back to a reduced image.
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"moov", &trak(craw(6000, 4000, &bx(b"free", &[])), 4096, 16)));
file.resize(4112, 0);
assert!(matches!(parse_cr3(&file).unwrap().tracks[0].kind, Cr3TrackKind::Raw { cmp1: None, .. }));
}
#[test]
fn merged_exif_reads_like_a_tiff_raw() {
let f = sample();
let m = crate::read_exif(&merged_exif(&parse_cr3(&f).unwrap()).unwrap());
assert_eq!(m.model.as_deref(), Some("Canon EOS Test"));
assert_eq!(m.iso, Some(400));
}
fn compression_payload(levels: u8) -> Vec<u8> {
let mut b = vec![0u8; 52];
b[0..2].copy_from_slice(&0xff00u16.to_be_bytes());
b[2..4].copy_from_slice(&48u16.to_be_bytes());
b[4..6].copy_from_slice(&0x100u16.to_be_bytes());
for (at, value) in [(8, 6888u32), (12, 4546), (16, 3444), (20, 4546), (28, 216)] {
b[at..at + 4].copy_from_slice(&value.to_be_bytes());
}
b[24] = 14;
b[25] = 0x40;
b[26] = levels;
b
}
#[test]
fn compression_descriptor_retains_sensor_geometry_and_cfa() {
let b = compression_payload(0);
let h = Cr3Compression::parse(&b).unwrap();
assert_eq!((h.width, h.height, h.tile_width, h.tile_height), (6888, 4546, 3444, 4546));
assert_eq!((h.version, h.bit_depth, h.planes, h.cfa_pattern, h.encoding, h.levels, h.header_size), (0x100, 14, 4, 0, 0, 0, 216));
let mut craw = compression_payload(3);
craw[25] = 0x41;
craw[27] = 0x80;
let h = Cr3Compression::parse(&craw).unwrap();
assert_eq!((h.cfa_pattern, h.levels, h.tile_flags), (1, 3, 0x80));
for len in 0..b.len() {
assert!(Cr3Compression::parse(&b[..len]).is_none());
}
for (at, value) in [(24, 0), (24, 17), (25, 0), (25, 0x44)] {
let mut bad = b.clone();
bad[at] = value;
assert!(Cr3Compression::parse(&bad).is_none());
}
}
#[test]
fn extended_descriptor_checks_optional_median_precision() {
let mut b = compression_payload(0x30);
b[32] = 0x80;
b.extend_from_slice(&33u32.to_be_bytes());
b.resize(85, 0);
b[56] = 0xc0;
b[84] = 14;
assert_eq!(Cr3Compression::parse(&b).unwrap().median_bit_depth, Some(14));
assert!(Cr3Compression::parse(&b[..84]).is_none());
b[84] = 0;
assert!(Cr3Compression::parse(&b).is_none());
}
#[test]
fn raw_track_reads_distinct_active_area_and_default_crop() {
let mut area = vec![0u8; 48];
for (at, value) in [
(4, 6888u16),
(6, 4546),
(10, 2),
(16, 156),
(18, 158),
(20, 6875),
(22, 4537),
(24, 0),
(26, 0),
(28, 143),
(30, 4545),
(32, 144),
(34, 0),
(36, 6887),
(38, 45),
(40, 144),
(42, 46),
(44, 6887),
(46, 4545),
] {
area[at..at + 2].copy_from_slice(&value.to_be_bytes());
}
let cmp1 = bx(b"CMP1", &compression_payload(0));
let iad1 = full(b"CDI1", &bx(b"IAD1", &area));
let track = trak(craw(6888, 4546, &[cmp1, iad1].concat()), 4096, 32);
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"moov", &track));
file.resize(4128, 0);
let c = parse_cr3(&file).unwrap();
assert_eq!(c.tracks[0].compression(&file).unwrap().width, 6888);
let geometry = c.tracks[0].image_area(&file).unwrap();
assert_eq!(geometry.crop, [156, 158, 6875, 4537]);
assert_eq!(geometry.active, Some([144, 46, 6887, 4545]));
assert_eq!(geometry.masked_left, [0, 0, 143, 4545]);
for len in 0..area.len() {
assert!(Cr3ImageArea::parse(&area[..len]).is_none());
}
}
#[test]
fn truncated_sample_table_does_not_read_the_next_box() {
let stbl = [
full(b"stsd", &[1u32.to_be_bytes().to_vec(), craw(16, 16, &bx(b"CMP1", &compression_payload(0)))].concat()),
bx(b"stsz", &[]),
full(b"co64", &[1u32.to_be_bytes().to_vec(), 256u64.to_be_bytes().to_vec()].concat()),
]
.concat();
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"moov", &bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &stbl))))));
file.resize(512, 0);
assert!(parse_cr3(&file).unwrap().tracks.is_empty());
}
#[test]
fn timed_metadata_exposes_the_dynamic_maker_note() {
use craft_tiff::{Value, tags as t};
let exif = tiff_with(t::ISO_SPEED, Value::Short(vec![800]));
let maker = tiff_with(0x4001, Value::Short(vec![48, 100, 200]));
let item = |tag: u32, data: &[u8]| {
let mut b = ((data.len() + 8) as u32).to_le_bytes().to_vec();
b.extend_from_slice(&tag.to_le_bytes());
b.extend_from_slice(data);
b
};
let items = [item(0x8769, &exif), item(0x927c, &maker)].concat();
let mut sample = vec![0u8; 12];
sample[0..4].copy_from_slice(&((12 + items.len()) as u32).to_le_bytes());
sample[4..6].copy_from_slice(&8u16.to_le_bytes());
sample.extend(items);
let container = Cr3 { tracks: vec![Cr3Track { kind: Cr3TrackKind::Other(*b"CTMD"), data: Some((0, sample.len())) }], ..Default::default() };
let parts = container.timed_exif(&sample);
assert_eq!(parts.len(), 2);
assert_eq!((parts[0].record_type, parts[0].tag, parts[0].data), (8, 0x8769, exif.as_slice()));
assert_eq!((parts[1].record_type, parts[1].tag, parts[1].data), (8, 0x927c, maker.as_slice()));
for len in 0..sample.len() {
assert!(container.timed_exif(&sample[..len]).is_empty());
}
for at in [0, 12] {
let mut corrupt = sample.clone();
corrupt[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(container.timed_exif(&corrupt).is_empty());
corrupt[at..at + 4].copy_from_slice(&0u32.to_le_bytes());
assert!(container.timed_exif(&corrupt).is_empty());
}
}
#[test]
fn hostile_input_never_panics() {
let f = sample();
// every truncation and single-byte corruption parses to something or nothing
for n in 0..f.len().min(800) {
let _ = parse_cr3(&f[..n]).map(|c| merged_exif(&c));
}
for i in 0..f.len().min(800) {
for v in [0u8, 1, 0x7f, 0xff] {
let mut g = f.clone();
g[i] = v;
let _ = parse_cr3(&g).map(|c| merged_exif(&c));
}
}
// a sample offset past the end is not reported
let mut g = f.clone();
g.truncate(4100);
assert!(parse_cr3(&g).unwrap().tracks.iter().all(|t| t.data.is_none()));
}
}
-320
View File
@@ -1,320 +0,0 @@
//! Capture date/time with optional UTC offset (Exif `DateTimeOriginal` + `OffsetTimeOriginal`, ISO 8601 in XMP).
use serde::{Deserialize, Serialize};
/// A civil date-time as recorded by the camera; `offset_minutes` is the UTC offset when known.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct DateTime {
pub year: u16,
pub month: u8,
pub day: u8,
pub hour: u8,
pub minute: u8,
pub second: u8,
/// Sub-second part in milliseconds.
pub millis: u16,
pub offset_minutes: Option<i16>,
}
fn num(s: &str) -> Option<u32> {
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
s.parse().ok()
}
impl DateTime {
fn valid(self) -> Option<Self> {
// A timestamp must represent a real Gregorian calendar day, not just
// numbers in the range 1..=31. Invalid dates would otherwise be
// accepted from EXIF/XMP and silently normalized during time arithmetic.
// chrono rejects impossible days (leap years and all); the time is checked
// by hand so a leap second (`second == 60`) stays acceptable.
let day_ok = self.year > 0 && chrono::NaiveDate::from_ymd_opt(i32::from(self.year), u32::from(self.month), u32::from(self.day)).is_some();
let ok = day_ok && self.hour < 24 && self.minute < 60 && self.second < 61 && self.offset_minutes.is_none_or(|o| o.unsigned_abs() <= 18 * 60);
ok.then_some(self)
}
/// Exif form `YYYY:MM:DD HH:MM:SS` (also tolerates `-` date separators and a missing time).
pub fn parse_exif(s: &str) -> Option<DateTime> {
let s = s.trim().trim_end_matches('\0');
let (d, t) = s.split_once([' ', 'T']).unwrap_or((s, ""));
let dp: Vec<&str> = d.split([':', '-']).collect();
if dp.len() != 3 {
return None;
}
let (hour, minute, second) = if t.is_empty() {
(0, 0, 0)
} else {
let mut parts = t.split(':');
let hour = num(parts.next()?.trim())?;
let minute = parts.next().map(|part| num(part.trim())).unwrap_or(Some(0))?;
let second = parts.next().map(|part| num(part.trim())).unwrap_or(Some(0))?;
// A fourth value cannot be represented; accepting only the prefix could turn a
// malformed DateTimeOriginal into a plausible capture time and block fallbacks.
if parts.next().is_some() {
return None;
}
(hour, minute, second)
};
DateTime {
year: num(dp[0])?.try_into().ok()?,
month: num(dp[1])?.try_into().ok()?,
day: num(dp[2])?.try_into().ok()?,
hour: hour.try_into().ok()?,
minute: minute.try_into().ok()?,
second: second.try_into().ok()?,
millis: 0,
offset_minutes: None,
}
.valid()
}
/// Exif `OffsetTime*` form `+HH:MM` / `-HH:MM` (or `Z`).
pub fn parse_offset(s: &str) -> Option<i16> {
let s = s.trim().trim_end_matches('\0');
if s == "Z" {
return Some(0);
}
let (sign, rest) = match s.as_bytes().first()? {
b'+' => (1, &s[1..]),
b'-' => (-1, &s[1..]),
_ => return None,
};
let (h, m) = match rest.split_once(':') {
Some((h, m)) => (num(h)?, num(m)?),
None if rest.len() == 4 => (num(rest.get(..2)?)?, num(rest.get(2..)?)?),
None => (num(rest)?, 0),
};
if h > 18 || m > 59 || (h == 18 && m > 0) {
return None;
}
Some(sign * (h * 60 + m) as i16)
}
/// Set the sub-second part from an Exif `SubSecTime*` string (digits are a decimal fraction).
pub fn with_subsec(mut self, s: &str) -> DateTime {
let digits: String = s.trim().chars().take_while(|c| c.is_ascii_digit()).take(3).collect();
if !digits.is_empty() {
let v: u16 = digits.parse().unwrap_or(0);
self.millis = v * 10u16.pow(3 - digits.len() as u32);
}
self
}
/// ISO 8601 (XMP date): `YYYY`, `YYYY-MM`, `YYYY-MM-DD`, `YYYY-MM-DDThh:mm[:ss[.s+]][TZD]`.
pub fn parse_iso(s: &str) -> Option<DateTime> {
let s = s.trim();
let (d, t) = match s.split_once('T') {
Some((d, t)) if !t.is_empty() => (d, t),
Some(_) => return None,
None => (s, ""),
};
let dp: Vec<&str> = d.split('-').collect();
let year = num(dp.first()?)?.try_into().ok()?;
let month = dp.get(1).map(|m| num(m)).unwrap_or(Some(1))?.try_into().ok()?;
let day = dp.get(2).map(|m| num(m)).unwrap_or(Some(1))?.try_into().ok()?;
if dp.len() > 3 {
return None;
}
let mut dt = DateTime { year, month, day, ..Default::default() };
if !t.is_empty() {
let (clock, off) = match t.find(['Z', '+', '-']) {
Some(i) => (&t[..i], Some(&t[i..])),
None => (t, None),
};
let mut cp = clock.split(':');
dt.hour = num(cp.next()?)?.try_into().ok()?;
dt.minute = num(cp.next()?)?.try_into().ok()?;
if let Some(sec) = cp.next() {
let (whole, fraction) = match sec.split_once('.') {
Some((whole, fraction)) => {
if fraction.is_empty() || !fraction.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
(whole, Some(fraction))
}
None => (sec, None),
};
dt.second = num(whole)?.try_into().ok()?;
if let Some(fraction) = fraction {
dt = dt.with_subsec(fraction);
}
}
if cp.next().is_some() {
return None;
}
if let Some(o) = off {
dt.offset_minutes = Some(Self::parse_offset(o)?);
}
}
dt.valid()
}
/// Exif form `YYYY:MM:DD HH:MM:SS`.
pub fn to_exif(&self) -> String {
format!("{:04}:{:02}:{:02} {:02}:{:02}:{:02}", self.year, self.month, self.day, self.hour, self.minute, self.second)
}
/// ISO 8601 with milliseconds when non-zero and the offset when known.
pub fn to_iso(&self) -> String {
let mut s = format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", self.year, self.month, self.day, self.hour, self.minute, self.second);
if self.millis != 0 {
s += &format!(".{:03}", self.millis);
}
if let Some(o) = self.offset_minutes {
let sign = if o < 0 { '-' } else { '+' };
let o = o.unsigned_abs();
s += &format!("{sign}{:02}:{:02}", o / 60, o % 60);
}
s
}
/// Seconds since 1970-01-01T00:00:00 of the civil time (UTC when the offset is known, else "local" seconds).
pub fn unix_seconds(&self) -> i64 {
// Every `DateTime` reaching here is a real calendar day (`valid()` ran in the parsers);
// an out-of-range one (built by hand) reads as the epoch rather than panicking.
let days = chrono::NaiveDate::from_ymd_opt(i32::from(self.year), u32::from(self.month), u32::from(self.day))
.zip(chrono::NaiveDate::from_ymd_opt(1970, 1, 1))
.map(|(d, epoch)| (d - epoch).num_days())
.unwrap_or(0);
days * 86400 + self.hour as i64 * 3600 + self.minute as i64 * 60 + self.second as i64 - self.offset_minutes.unwrap_or(0) as i64 * 60
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exif_forms() {
let d = DateTime::parse_exif("2024:06:01 13:45:59").unwrap();
assert_eq!((d.year, d.month, d.day, d.hour, d.minute, d.second), (2024, 6, 1, 13, 45, 59));
assert_eq!(d.to_exif(), "2024:06:01 13:45:59");
assert!(DateTime::parse_exif("0000:00:00 00:00:00").is_none());
assert!(DateTime::parse_exif(" : : : : ").is_none());
assert!(DateTime::parse_exif("2024:13:01 00:00:00").is_none());
// Invalid calendar days must never enter persisted capture metadata.
for value in ["2023:02:29", "2024:02:30", "2024:04:31", "1900:02:29", "2024:01:00"] {
assert!(DateTime::parse_exif(value).is_none(), "{value}");
}
assert!(DateTime::parse_exif("2024:02:29").is_some());
assert!(DateTime::parse_exif("2000:02:29").is_some());
for value in ["2023-02-29", "2024-02-30", "1900-02-29", "2024-06-31T10:00:00Z"] {
assert!(DateTime::parse_iso(value).is_none(), "{value}");
}
assert!(DateTime::parse_iso("2000-02-29T23:59:59Z").is_some());
assert_eq!(DateTime::parse_exif("2024-06-01").unwrap().hour, 0);
assert_eq!(DateTime::parse_exif("2024:06:01 13:45:59").unwrap().with_subsec("5").millis, 500);
assert_eq!(DateTime::parse_exif("2024:06:01 13:45:59").unwrap().with_subsec("0123").millis, 12);
}
#[test]
fn exif_clock_rejects_extra_components() {
for value in
["2026:01:01 12:34:56:99", "2026:01:01 12:34:56:junk", "2026:01:01 12:34:56:", "2026:01:01 12:34:56::", "2026:01:01 12:34:56:99:junk"]
{
assert!(DateTime::parse_exif(value).is_none(), "accepted malformed EXIF clock {value:?}");
}
}
#[test]
fn exif_clock_supported_forms_keep_their_meaning() {
for (value, expected) in [
("2026:01:01", "2026-01-01T00:00:00"),
("2026:01:01 12", "2026-01-01T12:00:00"),
("2026:01:01 12:34", "2026-01-01T12:34:00"),
("2026:01:01 12:34:56", "2026-01-01T12:34:56"),
("2026-01-01T12:34:56", "2026-01-01T12:34:56"),
(" 2026:01:01 12:34:56\0", "2026-01-01T12:34:56"),
("2026:01:01T12:34:60", "2026-01-01T12:34:60"),
] {
assert_eq!(DateTime::parse_exif(value).map(|date| date.to_iso()), Some(expected.to_string()), "{value:?}");
}
}
#[test]
fn offsets() {
assert_eq!(DateTime::parse_offset("+02:00"), Some(120));
assert_eq!(DateTime::parse_offset("-05:30"), Some(-330));
assert_eq!(DateTime::parse_offset("Z"), Some(0));
assert_eq!(DateTime::parse_offset("+0930"), Some(570));
assert_eq!(DateTime::parse_offset("+18:00"), Some(1080));
assert_eq!(DateTime::parse_offset("-18:00"), Some(-1080));
assert_eq!(DateTime::parse_offset("+18:01"), None);
assert_eq!(DateTime::parse_offset("-18:01"), None);
assert_eq!(DateTime::parse_offset(" : "), None);
assert_eq!(DateTime::parse_offset("+99:00"), None);
}
#[test]
fn extreme_offsets_do_not_overflow() {
// `DateTime` deserializes with public fields, so an offset can arrive without passing `valid()`
let d = DateTime { offset_minutes: Some(i16::MIN), ..DateTime::parse_iso("2024-06-01T13:45:59").unwrap() };
assert_eq!(d.to_iso(), "2024-06-01T13:45:59-546:08");
assert_eq!(d.valid(), None);
}
#[test]
fn unicode_offsets_are_rejected_without_panicking() {
for offset in ["+1€", "-1€", "+€1", "-€1"] {
assert_eq!(DateTime::parse_offset(offset), None);
let date = format!("2024-06-01T13:45:59{offset}");
let metadata = crate::Metadata { capture_time: DateTime::parse_iso("2024-06-01T13:45:59Z"), ..Default::default() };
let xmp = crate::write_xmp(&metadata, None).replace("2024-06-01T13:45:59+00:00", &date);
assert!(crate::parse_xmp(&xmp).unwrap().metadata.capture_time.is_none());
}
}
#[test]
fn iso_roundtrip() {
for s in ["2024-06-01T13:45:59", "2024-06-01T13:45:59.250+02:00", "1999-12-31T23:59:00-05:30", "2024-02-29T00:00:00Z"] {
let d = DateTime::parse_iso(s).unwrap();
let again = DateTime::parse_iso(&d.to_iso()).unwrap();
assert_eq!(d, again, "{s}");
}
assert_eq!(DateTime::parse_iso("2024-02-29T00:00:00Z").unwrap().to_iso(), "2024-02-29T00:00:00+00:00");
let d = DateTime::parse_iso("2019").unwrap();
assert_eq!((d.year, d.month, d.day), (2019, 1, 1));
assert_eq!(DateTime::parse_iso("2019-07-04T10:11").unwrap().minute, 11);
assert!(DateTime::parse_iso("nonsense").is_none());
assert!(DateTime::parse_iso("2019-07-04Tab:cd").is_none());
}
#[test]
fn iso_rejects_incomplete_or_unconsumed_clock_text() {
for value in [
"2026-01-01T",
"2026-01-01T12:34:56:99Z",
"2026-01-01T12:34:56.Z",
"2026-01-01T12:34:56.123junkZ",
"2026-01-01T12:34:56.1.2Z",
"2026-01-01T12:34:56.12 3Z",
"2026-01-01T12:34:56:99Z",
"2026-01-01T12::34Z",
] {
assert!(DateTime::parse_iso(value).is_none(), "accepted malformed timestamp {value:?}");
}
}
#[test]
fn iso_validates_clock_while_preserving_supported_forms() {
assert_eq!(DateTime::parse_iso("2019").unwrap().to_iso(), "2019-01-01T00:00:00");
assert_eq!(DateTime::parse_iso("2019-07").unwrap().to_iso(), "2019-07-01T00:00:00");
assert_eq!(DateTime::parse_iso("2019-07-04").unwrap().to_iso(), "2019-07-04T00:00:00");
assert_eq!(DateTime::parse_iso("2019-07-04T10:11").unwrap().to_iso(), "2019-07-04T10:11:00");
assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12").unwrap().to_iso(), "2019-07-04T10:11:12");
assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12Z").unwrap().offset_minutes, Some(0));
assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12-05:30").unwrap().offset_minutes, Some(-330));
assert_eq!(DateTime::parse_iso("2019-07-04T10:11:12.123456Z").unwrap().millis, 123);
assert_eq!(DateTime::parse_iso(" 2019-07-04T10:11:12.5Z ").unwrap().millis, 500);
assert_eq!(DateTime::parse_iso("2019-07-04T10:11:60Z").unwrap().second, 60);
}
#[test]
fn unix() {
assert_eq!(DateTime::parse_iso("1970-01-01T00:00:00Z").unwrap().unix_seconds(), 0);
assert_eq!(DateTime::parse_iso("2000-03-01T00:00:00Z").unwrap().unix_seconds(), 951868800);
assert_eq!(DateTime::parse_iso("2000-03-01T02:00:00+02:00").unwrap().unix_seconds(), 951868800);
}
}
+25 -670
View File
@@ -1,695 +1,40 @@
//! Exif / TIFF tags → [`Metadata`] (CIPA DC-008 Exif 2.32, TIFF 6.0, DNG 1.7 tag semantics).
use crate::convert::{from_craft, to_craft};
use crate::{Metadata, Orientation};
use craft_tiff::{ParseOptions, Tiff, TiffError, tags as t};
use crate::{DateTime, Flash, Gps, Metadata, Orientation};
use craft_tiff::{Ifd, ParseOptions, Tiff, TiffError, tags as t};
/// Strip an `Exif\0\0` (or `Exif\0\xff`) prefix as found in JPEG APP1 and some WebP `EXIF` chunks.
pub fn strip_exif_header(b: &[u8]) -> &[u8] {
if b.len() >= 6 && &b[..4] == b"Exif" && b[4] == 0 { &b[6..] } else { b }
craft_metadata::strip_exif_header(b)
}
/// Read metadata from a TIFF-structured Exif block (a whole TIFF/DNG/raw file, or the payload of a JPEG APP1
/// Exif segment with or without the `Exif\0\0` prefix). Malformed input yields whatever could be read.
pub fn read_exif(bytes: &[u8]) -> Metadata {
try_read_exif(bytes).unwrap_or_default()
from_craft(craft_metadata::read_exif(bytes))
}
/// Like [`read_exif`] but reports a structurally invalid TIFF header / IFD0.
pub fn try_read_exif(bytes: &[u8]) -> Result<Metadata, TiffError> {
try_read_exif_with(bytes, &ParseOptions::default())
craft_metadata::try_read_exif(bytes).map(from_craft)
}
/// [`try_read_exif`] with the caller's parser options (its value allocation budget in particular).
/// A decoder working from a sparse buffer — only selected ranges of the logical file are actually
/// loaded, the rest is zeros — must not size its allocations by the logical file length, which
/// unrelated bytes of the file can inflate at no cost to the attacker.
pub fn try_read_exif_with(bytes: &[u8], opts: &ParseOptions) -> Result<Metadata, TiffError> {
let data = strip_exif_header(bytes);
let tiff = Tiff::parse_with(data, opts)?;
let mut m = from_tiff(&tiff);
// Panasonic (and some Canons) write no LensModel, only the name in their maker note
if m.lens_model.is_none() {
m.lens_model = panasonic_maker_note_lens(data, &tiff).or_else(|| canon_maker_note_lens(data, &tiff));
}
// the maker note's values are offsets into the stream, which `from_tiff` doesn't have
m.focus = crate::focus::read(data, &tiff, m.make.as_deref(), m.model.as_deref(), m.orientation);
Ok(m)
craft_metadata::try_read_exif_with(bytes, opts).map(from_craft)
}
fn text(ifd: Option<&Ifd>, tag: u16) -> Option<String> {
let s = ifd?.string(tag)?;
let s = s.trim().to_string();
(!s.is_empty() && !s.bytes().all(|b| b == b' ' || b == 0)).then_some(s)
}
fn pos(v: Option<f64>) -> Option<f64> {
v.filter(|x| x.is_finite() && *x > 0.0)
}
/// The orientation the Exif's own first IFD states. [`from_tiff`] also reports one that only the XMP packet in
/// the Exif's tag 700 states; LightCraft displays a photo by the Exif's alone, so that one can't tell how a photo
/// is stored.
pub(crate) fn ifd0_orientation(bytes: &[u8]) -> Option<Orientation> {
let tiff = Tiff::parse_with(strip_exif_header(bytes), &ParseOptions::default()).ok()?;
tiff.ifds.first().and_then(|i| i.u16(t::ORIENTATION)).filter(|v| (1..=8).contains(v)).map(Orientation::from_exif)
}
/// Build [`Metadata`] from a parsed TIFF stream (IFD0 + Exif + GPS; DNG tags as fallbacks).
pub fn from_tiff(tiff: &Tiff) -> Metadata {
let ifd0 = tiff.ifds.first();
let exif = tiff.exif();
let gps = tiff.gps();
let either = |tag: u16| exif.and_then(|e| e.value(tag)).or_else(|| ifd0.and_then(|i| i.value(tag)));
let mut m = Metadata {
make: text(ifd0, t::MAKE),
model: text(ifd0, t::MODEL).or_else(|| text(ifd0, t::UNIQUE_CAMERA_MODEL)),
software: text(ifd0, t::SOFTWARE),
artist: text(ifd0, t::ARTIST),
copyright: text(ifd0, t::COPYRIGHT),
caption: text(ifd0, t::IMAGE_DESCRIPTION),
serial_number: text(exif, t::BODY_SERIAL_NUMBER).or_else(|| text(ifd0, t::CAMERA_SERIAL_NUMBER)),
lens_make: text(exif, t::LENS_MAKE),
lens_model: text(exif, t::LENS_MODEL),
lens_serial_number: text(exif, t::LENS_SERIAL_NUMBER),
..Default::default()
};
// Exif requires LensSpecification/LensInfo as 4 rationals.
let spec = exif.and_then(|e| e.f64s(t::LENS_SPECIFICATION)).or_else(|| ifd0.and_then(|i| i.f64s(t::LENS_INFO)));
if let Some(s) = spec.filter(|s| s.len() == 4 && s[0] > 0.0) {
m.lens_spec = Some([s[0], s[1], s[2], s[3]]);
}
// Nikon DSLRs write neither LensModel nor LensSpecification, only the same four values in their maker note
if m.lens_spec.is_none() {
m.lens_spec = nikon_lens_spec(exif, m.make.as_deref(), tiff.order);
}
m.orientation = ifd0.and_then(|i| i.u16(t::ORIENTATION)).filter(|v| (1..=8).contains(v)).map(Orientation::from_exif);
m.rating = ifd0.and_then(|i| i.i64(t::RATING)).map(|r| r.clamp(-1, 5) as i8);
m.exposure_time = pos(either(t::EXPOSURE_TIME).and_then(|v| v.get_f64(0)))
.or_else(|| exif.and_then(|e| e.f64(t::SHUTTER_SPEED_VALUE)).filter(|v| v.abs() < 64.0).map(|tv| 2f64.powf(-tv)));
m.f_number = pos(either(t::F_NUMBER).and_then(|v| v.get_f64(0)))
.or_else(|| exif.and_then(|e| e.f64(t::APERTURE_VALUE)).filter(|v| v.abs() < 64.0).map(|av| 2f64.powf(av / 2.0)));
let iso = either(t::ISO_SPEED).and_then(|v| v.get_u64(0)).filter(|&v| v > 0);
let iso_ext = exif.and_then(|e| e.u64(t::RECOMMENDED_EXPOSURE_INDEX).or_else(|| e.u64(t::ISO_SPEED_RATINGS_EXT))).filter(|&v| v > 0);
m.iso = match (iso, iso_ext) {
(Some(65535), Some(x)) | (None, Some(x)) => Some(x),
(Some(v), _) => Some(v),
_ => None,
}
.map(|v| v.min(u32::MAX as u64) as u32);
m.focal_length = pos(either(t::FOCAL_LENGTH).and_then(|v| v.get_f64(0)));
m.focal_length_35mm = pos(exif.and_then(|e| e.f64(t::FOCAL_LENGTH_35MM)));
m.exposure_bias = exif.and_then(|e| e.f64(t::EXPOSURE_BIAS)).filter(|v| v.is_finite() && v.abs() < 100.0);
m.exposure_program = exif.and_then(|e| e.u16(t::EXPOSURE_PROGRAM));
m.metering_mode = exif.and_then(|e| e.u16(t::METERING_MODE));
m.white_balance = exif.and_then(|e| e.u16(t::WHITE_BALANCE));
m.flash = exif.and_then(|e| e.u16(t::FLASH)).map(|raw| Flash { fired: raw & 1 != 0, raw });
// capture time: DateTimeOriginal, then DateTimeDigitized, then IFD0 DateTime
let candidates = [
(exif, t::DATE_TIME_ORIGINAL, t::OFFSET_TIME_ORIGINAL, t::SUBSEC_TIME_ORIGINAL),
(exif, t::DATE_TIME_DIGITIZED, t::OFFSET_TIME_DIGITIZED, t::SUBSEC_TIME_DIGITIZED),
(ifd0, t::DATE_TIME, t::OFFSET_TIME, t::SUBSEC_TIME),
];
for (ifd, dt_tag, off_tag, sub_tag) in candidates {
if let Some(mut dt) = text(ifd, dt_tag).and_then(|s| DateTime::parse_exif(&s)) {
if let Some(s) = text(exif, sub_tag) {
dt = dt.with_subsec(&s);
}
dt.offset_minutes = text(exif, off_tag).and_then(|s| DateTime::parse_offset(&s));
m.capture_time = Some(dt);
break;
}
}
m.width = exif.and_then(|e| e.u32(t::PIXEL_X_DIMENSION)).filter(|&v| v > 0).or_else(|| ifd0.and_then(|i| i.u32(t::IMAGE_WIDTH)));
m.height = exif.and_then(|e| e.u32(t::PIXEL_Y_DIMENSION)).filter(|&v| v > 0).or_else(|| ifd0.and_then(|i| i.u32(t::IMAGE_LENGTH)));
m.gps = gps.and_then(read_gps);
if let Some(iptc) = ifd0.and_then(|i| i.value(t::IPTC_NAA)) {
// IPTC-NAA is often typed LONG; re-serialise to bytes in file order.
let bytes = match iptc {
craft_tiff::Value::Byte(b) | craft_tiff::Value::Undefined(b) => b.clone(),
other => craft_tiff::writer::encode(tiff.order, other),
};
m.fill_missing(&crate::parse_iptc(&bytes));
}
if let Some(x) = ifd0.and_then(|i| i.bytes(t::XMP)).map(String::from_utf8_lossy)
&& let Ok(x) = crate::parse_xmp(&x)
{
// (the size stays the one Exif states: `extract` turns regions by it, and a size only the XMP states may be the upright one)
let size = (m.width, m.height);
m.overlay_user_fields(&x.metadata);
m.fill_missing(&x.metadata);
(m.width, m.height) = size;
}
m
from_craft(craft_metadata::from_tiff(tiff))
}
/// Degrees/minutes/seconds triplet as decimal degrees. A component that is present but not a number (a rational
/// with a zero denominator, as in the placeholder GPS block phones write without a fix) makes the whole value unusable.
fn dms(ifd: &Ifd, tag: u16) -> Option<f64> {
let v = ifd.value(tag)?;
let part = |i: usize| if i < v.count() { v.get_f64(i) } else { Some(0.0) };
let d = v.get_f64(0)?;
let deg = d + part(1)? / 60.0 + part(2)? / 3600.0;
deg.is_finite().then_some(deg)
}
/// `Some(true)` for the negative hemisphere (`neg`), `Some(false)` for `pos`, `None` when the ref is missing or invalid.
fn hemisphere(g: &Ifd, tag: u16, pos: char, neg: char) -> Option<bool> {
match g.string(tag)?.trim_start().chars().next()?.to_ascii_uppercase() {
c if c == neg => Some(true),
c if c == pos => Some(false),
_ => None,
}
}
fn read_gps(g: &Ifd) -> Option<Gps> {
let mut lat = dms(g, t::GPS_LATITUDE)?;
let mut lon = dms(g, t::GPS_LONGITUDE)?;
if hemisphere(g, t::GPS_LATITUDE_REF, 'N', 'S')? {
lat = -lat;
}
if hemisphere(g, t::GPS_LONGITUDE_REF, 'E', 'W')? {
lon = -lon;
}
if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
return None;
}
let altitude = g.f64(t::GPS_ALTITUDE).filter(|a| a.is_finite()).map(|a| if g.u32(t::GPS_ALTITUDE_REF) == Some(1) { -a } else { a });
Some(Gps { latitude: lat, longitude: lon, altitude })
}
/// Panasonic maker note tag `0x0051` (LensType in the ExifTool Panasonic tag names): the lens name, ASCII.
const PANASONIC_LENS_TYPE: u16 = 0x0051;
/// RW2/RWL IFD0 tag `0x002E` (JpgFromRaw): a JPEG whose APP1 holds the full Exif, maker note included.
const PANASONIC_JPG_FROM_RAW: u16 = 0x002E;
/// The lens name in the Panasonic maker note (tag `0x0051`) of this Exif or RW2 stream (`data` starts at its
/// TIFF header): the note of its own Exif IFD, else, for a raw, the note in its JpgFromRaw's Exif.
pub(crate) fn panasonic_maker_note_lens(data: &[u8], tiff: &Tiff) -> Option<String> {
panasonic_lens(data, tiff).or_else(|| panasonic_jpg_from_raw_lens(tiff))
}
/// The lens name in a `Panasonic\0` maker note of this Exif stream (`data` starts at its TIFF header).
fn panasonic_lens(data: &[u8], tiff: &Tiff) -> Option<String> {
let exif = tiff.exif()?;
if !exif.bytes(t::MAKER_NOTE)?.starts_with(b"Panasonic\0") {
return None;
}
let e = exif.get(t::MAKER_NOTE)?;
let make = tiff.ifds.first().and_then(|i| i.string(t::MAKE)).unwrap_or_default();
let mn = craft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?;
text(Some(&mn.ifd), PANASONIC_LENS_TYPE)
}
/// The lens name from the Exif of a RW2's (or Leica RWL's) embedded JpgFromRaw.
fn panasonic_jpg_from_raw_lens(tiff: &Tiff) -> Option<String> {
let jpg = tiff.ifds.first()?.bytes(PANASONIC_JPG_FROM_RAW)?;
let exif = crate::jpeg_segments(jpg).exif?;
let data = strip_exif_header(&exif);
panasonic_lens(data, &Tiff::parse(data).ok()?)
}
/// Canon maker note tag `0x0095` (LensModel in the ExifTool Canon tag names): the lens name as ASCII. Older
/// bodies instead record a numeric LensType (CameraSettings, tag `0x0001`, index 22), which is no name to read.
const CANON_LENS_MODEL: u16 = 0x0095;
/// The lens name in a Canon maker note of this Exif stream (`data` starts at its TIFF header): the note of
/// its own Exif IFD. Only consulted when Make is Canon, so other vendors' plain notes are never read as lenses.
fn canon_maker_note_lens(data: &[u8], tiff: &Tiff) -> Option<String> {
let make = tiff.ifds.first().and_then(|i| i.string(t::MAKE)).unwrap_or_default();
if !make.trim().to_ascii_uppercase().starts_with("CANON") {
return None;
}
let exif = tiff.exif()?;
let e = exif.get(t::MAKER_NOTE)?;
let mn = craft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?;
text(Some(&mn.ifd), CANON_LENS_MODEL)
}
/// Nikon maker note tag `0x0084` (Lens in the ExifTool Nikon tag names): shortest and longest focal length, then the
/// widest aperture at each, as rationals, like Exif LensSpecification. Zero for a lens that doesn't report itself.
const NIKON_LENS: u16 = 0x0084;
/// The lens a Nikon camera records in its maker note, when it's plausible.
fn nikon_lens_spec(exif: Option<&Ifd>, make: Option<&str>, order: craft_tiff::ByteOrder) -> Option<[f64; 4]> {
let make = make?;
if !make.trim().to_ascii_uppercase().starts_with("NIKON") {
return None;
}
let note = exif?.bytes(t::MAKER_NOTE)?;
let mn = craft_tiff::makernote::parse_makernote(note, 0, note.len() as u64, order, make)?;
let s = mn.ifd.f64s(NIKON_LENS)?;
let [short, long, wide, narrow] = s.as_slice() else { return None };
let focal = |f: f64| f.is_finite() && f > 0.0 && f < 10_000.0;
let aperture = |a: f64| a.is_finite() && a > 0.0 && a < 100.0;
(focal(*short) && focal(*long) && long >= short && aperture(*wide) && aperture(*narrow)).then_some([*short, *long, *wide, *narrow])
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
fn capture_time_tiff(original: Option<&str>, digitized: Option<&str>, ifd0_time: Option<&str>, xmp: Option<&str>) -> Vec<u8> {
let mut exif = IfdBuilder::new();
if let Some(value) = original {
exif.set(t::DATE_TIME_ORIGINAL, Value::Ascii(value.into()));
}
if let Some(value) = digitized {
exif.set(t::DATE_TIME_DIGITIZED, Value::Ascii(value.into()));
}
let mut ifd0 = IfdBuilder::new();
if let Some(value) = ifd0_time {
ifd0.set(t::DATE_TIME, Value::Ascii(value.into()));
}
ifd0.set_child(t::EXIF_IFD, exif);
if let Some(packet) = xmp {
ifd0.set(t::XMP, Value::Byte(packet.as_bytes().to_vec()));
}
TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap()
}
#[test]
fn exif_clock_invalid_original_uses_the_next_valid_exif_time() {
let invalid = "2026:01:01 12:34:56:99";
let digitized = capture_time_tiff(Some(invalid), Some("2026:01:02 10:00:00"), Some("2026:01:03 11:00:00"), None);
assert_eq!(read_exif(&digitized).capture_time.map(|date| date.to_iso()), Some("2026-01-02T10:00:00".into()));
let ifd0 = capture_time_tiff(Some(invalid), Some("2026:01:02 10:00:00:"), Some("2026:01:03 11:00:00"), None);
assert_eq!(read_exif(&ifd0).capture_time.map(|date| date.to_iso()), Some("2026-01-03T11:00:00".into()));
let none = capture_time_tiff(Some(invalid), Some("2026:01:02 10:00:00:junk"), Some("2026:01:03 11:00:00:"), None);
assert_eq!(read_exif(&none).capture_time, None);
let original = capture_time_tiff(Some("2026:01:04 12:00:00"), Some("2026:01:02 10:00:00"), Some("2026:01:03 11:00:00"), None);
assert_eq!(read_exif(&original).capture_time.map(|date| date.to_iso()), Some("2026-01-04T12:00:00".into()));
}
#[test]
fn exif_clock_invalid_original_allows_xmp_fallback_and_keeps_raw_tag() {
let capture = DateTime::parse_iso("2026-01-02T10:00:00Z");
let packet = crate::write_xmp(&Metadata { capture_time: capture, ..Default::default() }, None);
let bytes = capture_time_tiff(Some("2026:01:01 12:34:56:99"), None, None, Some(&packet));
assert_eq!(crate::extract(&bytes).capture_time.map(|date| date.to_iso()), Some("2026-01-02T10:00:00+00:00".into()));
let without_fallback = capture_time_tiff(Some("2026:01:01 12:34:56:junk"), None, None, None);
assert_eq!(crate::extract(&without_fallback).capture_time, None);
assert!(crate::embedded(&without_fallback).exif.is_some(), "rejecting the projection must retain the embedded EXIF block");
}
/// An Exif block from a Panasonic body: no LensModel, the lens name in maker note tag 0x0051, whose value
/// lies outside the note's IFD at an offset relative to the Exif TIFF header (as Panasonic writes it).
pub(crate) fn panasonic_exif(order: ByteOrder, lens: Option<&str>, lens_model: Option<&str>) -> Vec<u8> {
let note = |at: u32| {
let mut v = b"Panasonic\0\0\0".to_vec();
order.put_u16(&mut v, 1);
order.put_u16(&mut v, if lens.is_some() { PANASONIC_LENS_TYPE } else { 0x0001 });
order.put_u16(&mut v, 2);
let name = format!("{:<34}\0", lens.unwrap_or("0210"));
order.put_u32(&mut v, name.len() as u32);
order.put_u32(&mut v, at + 30);
order.put_u32(&mut v, 0);
v.extend_from_slice(name.as_bytes());
v
};
let build = |at: u32| {
let mut exif = IfdBuilder::new();
exif.set(t::MAKER_NOTE, Value::Undefined(note(at)));
exif.set(t::FOCAL_LENGTH, Value::Rational(vec![(25, 1)]));
if let Some(l) = lens_model {
exif.set(t::LENS_MODEL, Value::Ascii(l.into()));
}
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::MAKE, Value::Ascii("Panasonic".into()));
ifd0.set_child(t::EXIF_IFD, exif);
TiffWriter::new(order, false).write(&[ifd0]).unwrap()
};
// the note's own offset is only known once it is laid out; its length doesn't change
let first = build(0);
let at = Tiff::parse(&first).unwrap().exif().unwrap().get(t::MAKER_NOTE).unwrap().offset as u32;
build(at)
}
#[test]
fn panasonic_maker_note_names_the_lens() {
for order in [ByteOrder::Little, ByteOrder::Big] {
let m = read_exif(&panasonic_exif(order, Some("LUMIX G 25/F1.7"), None));
assert_eq!(m.lens_model.as_deref(), Some("LUMIX G 25/F1.7"));
assert_eq!(m.focal_length, Some(25.0));
}
// Exif's own LensModel wins, and a note without 0x0051 leaves the lens empty
let m = read_exif(&panasonic_exif(ByteOrder::Little, Some("LUMIX G 25/F1.7"), Some("Other 25mm")));
assert_eq!(m.lens_model.as_deref(), Some("Other 25mm"));
assert_eq!(read_exif(&panasonic_exif(ByteOrder::Little, None, None)).lens_model, None);
}
/// A RW2 has the full Exif only in the APP1 of its JpgFromRaw (IFD0 0x002E), not in its own Exif IFD.
pub(crate) fn panasonic_rw2(lens: &str) -> Vec<u8> {
let mut jpg = vec![0xff, 0xd8, 0xff, 0xe1];
let mut app1 = b"Exif\0\0".to_vec();
app1.extend(panasonic_exif(ByteOrder::Little, Some(lens), None));
jpg.extend_from_slice(&((app1.len() + 2) as u16).to_be_bytes());
jpg.extend(app1);
jpg.extend_from_slice(&[0xff, 0xda, 0, 2, 0xff, 0xd9]);
let mut exif = IfdBuilder::new();
exif.set(t::FOCAL_LENGTH, Value::Rational(vec![(85, 1)]));
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::MAKE, Value::Ascii("Panasonic".into()));
ifd0.set(PANASONIC_JPG_FROM_RAW, Value::Undefined(jpg));
ifd0.set_child(t::EXIF_IFD, exif);
TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap()
}
#[test]
fn rw2_reads_the_lens_from_its_jpg_from_raw() {
let rw2 = panasonic_rw2("LUMIX S 85/F1.8");
let m = read_exif(&rw2);
assert_eq!(m.lens_model.as_deref(), Some("LUMIX S 85/F1.8"));
assert_eq!(m.focal_length, Some(85.0));
assert_eq!(crate::extract(&rw2).lens_model.as_deref(), Some("LUMIX S 85/F1.8"));
}
/// Canon maker note tags: `0x0095` holds the lens name as ASCII; `0x0001` is CameraSettings, a table of
/// int16s whose index 22 is the numeric LensType.
const CANON_LENS_MODEL_TAG: u16 = 0x0095;
const CANON_CAMERA_SETTINGS: u16 = 0x0001;
/// An Exif block from a Canon EOS 5D: `Canon` / `Canon EOS 5D` in IFD0, no LensModel tag, and a plain maker
/// note whose IFD (value offsets relative to the enclosing TIFF header, as Canon writes it) records
/// CameraSettings with the numeric LensType at index 22 and, when `lens` is given, the name at `0x0095`.
fn canon_exif(order: ByteOrder, lens: Option<&str>) -> Vec<u8> {
let note = |at: u32| {
// The plain IFD: entry count, one or two 12-byte entries and the next-IFD pointer, then the
// out-of-line values (CameraSettings, then the lens name when present).
// pointer, then the out-of-line values (CameraSettings, then the lens name when present).
let settings_at = at + 2 + 12 * (1 + lens.is_some() as u32) + 4;
let name_at = settings_at + 60;
let mut v = Vec::new();
let entry = |v: &mut Vec<u8>, tag: u16, kind: u16, count: u32, off: u32| {
order.put_u16(v, tag);
order.put_u16(v, kind);
order.put_u32(v, count);
order.put_u32(v, off);
};
order.put_u16(&mut v, 1 + lens.is_some() as u16);
entry(&mut v, CANON_CAMERA_SETTINGS, 3, 30, settings_at);
if let Some(name) = lens {
entry(&mut v, CANON_LENS_MODEL_TAG, 2, name.len() as u32, name_at);
}
order.put_u32(&mut v, 0);
for i in 0..30u16 {
order.put_u16(&mut v, if i == 22 { 178 } else { 0 }); // 22: numeric LensType, no name
}
if let Some(name) = lens {
v.extend_from_slice(name.as_bytes());
}
v
};
let build = |at: u32| {
let mut exif = IfdBuilder::new();
exif.set(t::MAKER_NOTE, Value::Undefined(note(at)));
exif.set(t::FOCAL_LENGTH, Value::Rational(vec![(50, 1)]));
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::MAKE, Value::Ascii("Canon".into()));
ifd0.set(t::MODEL, Value::Ascii("Canon EOS 5D".into()));
ifd0.set_child(t::EXIF_IFD, exif);
TiffWriter::new(order, false).write(&[ifd0]).unwrap()
};
// the note's own offset is only known once it is laid out; its length doesn't change
let first = build(0);
let at = Tiff::parse(&first).unwrap().exif().unwrap().get(t::MAKER_NOTE).unwrap().offset as u32;
build(at)
}
#[test]
fn canon_maker_note_lens_fills_lens_model() {
for order in [ByteOrder::Little, ByteOrder::Big] {
let m = read_exif(&canon_exif(order, Some("Canon EF 50mm f/1.8 II")));
assert_eq!(m.lens_model.as_deref(), Some("Canon EF 50mm f/1.8 II"));
// a note that only records the numeric LensType has no name to fill in
assert_eq!(read_exif(&canon_exif(order, None)).lens_model, None);
}
}
/// An Exif block from a Nikon body whose maker note records the lens (tag 0x0084) and no LensModel or
/// LensSpecification, as the D700, D750, D80 and D5300 write it.
fn nikon_exif(make: &str, lens: Option<[(u32, u32); 4]>, spec: Option<[(u32, u32); 4]>) -> Vec<u8> {
let mut note = IfdBuilder::new();
note.set(0x0001, Value::Undefined(b"0210".to_vec()));
if let Some(l) = lens {
note.set(NIKON_LENS, Value::Rational(l.to_vec()));
}
let mut blob = b"Nikon\0\x02\x10\0\0".to_vec();
blob.extend(TiffWriter::new(ByteOrder::Little, false).write(&[note]).unwrap());
let mut exif = IfdBuilder::new();
exif.set(t::MAKER_NOTE, Value::Undefined(blob));
if let Some(sp) = spec {
exif.set(t::LENS_SPECIFICATION, Value::Rational(sp.to_vec()));
}
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::MAKE, Value::Ascii(make.into()));
ifd0.set_child(t::EXIF_IFD, exif);
TiffWriter::new(ByteOrder::Big, false).write(&[ifd0]).unwrap()
}
#[test]
fn nikon_maker_note_lens_fills_the_lens_spec() {
let zoom = [(18, 1), (135, 1), (35, 10), (56, 10)];
assert_eq!(read_exif(&nikon_exif("NIKON CORPORATION", Some(zoom), None)).lens_spec, Some([18.0, 135.0, 3.5, 5.6]));
// Exif's own LensSpecification wins, another make's note is not read, and a lens that reports nothing is left out
let prime = [(50, 1), (50, 1), (18, 10), (18, 10)];
assert_eq!(read_exif(&nikon_exif("NIKON CORPORATION", Some(zoom), Some(prime))).lens_spec, Some([50.0, 50.0, 1.8, 1.8]));
assert_eq!(read_exif(&nikon_exif("Canon", Some(zoom), None)).lens_spec, None);
assert_eq!(read_exif(&nikon_exif("NIKON CORPORATION", Some([(0, 1), (0, 1), (0, 1), (0, 1)]), None)).lens_spec, None);
assert_eq!(read_exif(&nikon_exif("NIKON CORPORATION", Some([(200, 1), (80, 1), (28, 10), (28, 10)]), None)).lens_spec, None);
assert_eq!(read_exif(&nikon_exif("NIKON CORPORATION", None, None)).lens_spec, None);
}
pub(crate) fn sample_exif(order: ByteOrder) -> Vec<u8> {
let mut exif = IfdBuilder::new();
exif.set(t::EXPOSURE_TIME, Value::Rational(vec![(1, 250)]));
exif.set(t::F_NUMBER, Value::Rational(vec![(28, 10)]));
exif.set(t::ISO_SPEED, Value::Short(vec![400]));
exif.set(t::DATE_TIME_ORIGINAL, Value::Ascii("2023:07:14 18:30:05".into()));
exif.set(t::OFFSET_TIME_ORIGINAL, Value::Ascii("+02:00".into()));
exif.set(t::SUBSEC_TIME_ORIGINAL, Value::Ascii("42".into()));
exif.set(t::EXPOSURE_BIAS, Value::SRational(vec![(-2, 3)]));
exif.set(t::METERING_MODE, Value::Short(vec![5]));
exif.set(t::FLASH, Value::Short(vec![0x19]));
exif.set(t::FOCAL_LENGTH, Value::Rational(vec![(50, 1)]));
exif.set(t::FOCAL_LENGTH_35MM, Value::Short(vec![75]));
exif.set(t::WHITE_BALANCE, Value::Short(vec![0]));
exif.set(t::EXPOSURE_PROGRAM, Value::Short(vec![3]));
exif.set(t::LENS_MAKE, Value::Ascii("LensCo".into()));
exif.set(t::LENS_MODEL, Value::Ascii("50mm F1.8".into()));
exif.set(t::BODY_SERIAL_NUMBER, Value::Ascii("12345".into()));
exif.set(t::LENS_SPECIFICATION, Value::Rational(vec![(50, 1), (50, 1), (18, 10), (18, 10)]));
exif.set(t::PIXEL_X_DIMENSION, Value::Long(vec![6000]));
exif.set(t::PIXEL_Y_DIMENSION, Value::Long(vec![4000]));
let mut gps = IfdBuilder::new();
gps.set(t::GPS_LATITUDE_REF, Value::Ascii("S".into()));
gps.set(t::GPS_LATITUDE, Value::Rational(vec![(33, 1), (51, 1), (3564, 100)]));
gps.set(t::GPS_LONGITUDE_REF, Value::Ascii("E".into()));
gps.set(t::GPS_LONGITUDE, Value::Rational(vec![(151, 1), (12, 1), (4032, 100)]));
gps.set(t::GPS_ALTITUDE_REF, Value::Byte(vec![1]));
gps.set(t::GPS_ALTITUDE, Value::Rational(vec![(125, 10)]));
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::MAKE, Value::Ascii("Maker Inc.".into()));
ifd0.set(t::MODEL, Value::Ascii("Model X ".into()));
ifd0.set(t::ORIENTATION, Value::Short(vec![6]));
ifd0.set(t::ARTIST, Value::Ascii("Jane".into()));
ifd0.set(t::COPYRIGHT, Value::Ascii("(c) Jane".into()));
ifd0.set(t::RATING, Value::Short(vec![3]));
ifd0.set_child(t::EXIF_IFD, exif);
ifd0.set_child(t::GPS_IFD, gps);
TiffWriter::new(order, false).write(&[ifd0]).unwrap()
}
#[test]
fn reads_all_fields() {
for order in [ByteOrder::Little, ByteOrder::Big] {
let m = read_exif(&sample_exif(order));
assert_eq!(m.make.as_deref(), Some("Maker Inc."));
assert_eq!(m.model.as_deref(), Some("Model X"));
assert_eq!(m.exposure_time, Some(0.004));
assert_eq!(m.f_number, Some(2.8));
assert_eq!(m.iso, Some(400));
let dt = m.capture_time.unwrap();
assert_eq!(dt.to_iso(), "2023-07-14T18:30:05.420+02:00");
assert!((m.exposure_bias.unwrap() + 0.6667).abs() < 1e-3);
assert_eq!(m.metering_mode, Some(5));
assert_eq!(m.flash, Some(Flash { fired: true, raw: 0x19 }));
assert_eq!(m.focal_length, Some(50.0));
assert_eq!(m.focal_length_35mm, Some(75.0));
assert_eq!(m.orientation, Some(Orientation::Rotate90));
assert_eq!(m.lens_model.as_deref(), Some("50mm F1.8"));
assert_eq!(m.lens_make.as_deref(), Some("LensCo"));
assert_eq!(m.serial_number.as_deref(), Some("12345"));
assert_eq!(m.lens_spec, Some([50.0, 50.0, 1.8, 1.8]));
assert_eq!((m.width, m.height), (Some(6000), Some(4000)));
assert_eq!(m.artist.as_deref(), Some("Jane"));
assert_eq!(m.rating, Some(3));
let g = m.gps.unwrap();
assert!((g.latitude + 33.8599).abs() < 1e-4, "{g:?}");
assert!((g.longitude - 151.2112).abs() < 1e-4);
assert_eq!(g.altitude, Some(-12.5));
}
}
#[test]
fn placeholder_gps_block_is_no_location() {
// Android phones without a fix write NUL refs and 0/0 rationals (#1617).
let read = |lat_ref: &str, lat: Vec<(u32, u32)>| {
let mut gps = IfdBuilder::new();
gps.set(t::GPS_LATITUDE_REF, Value::Ascii(lat_ref.into()));
gps.set(t::GPS_LATITUDE, Value::Rational(lat));
gps.set(t::GPS_LONGITUDE_REF, Value::Ascii("E".into()));
gps.set(t::GPS_LONGITUDE, Value::Rational(vec![(151, 1), (12, 1), (4032, 100)]));
let mut ifd0 = IfdBuilder::new();
ifd0.set_child(t::GPS_IFD, gps);
read_exif(&TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap()).gps
};
let valid = vec![(33, 1), (51, 1), (3564, 100)];
assert!(read("N", valid.clone()).is_some());
assert_eq!(read("N", vec![(0, 0), (0, 0), (0, 0)]), None, "0/0 rationals");
assert_eq!(read("N", vec![(33, 1), (0, 0), (0, 0)]), None, "0/0 minutes");
assert_eq!(read("", valid.clone()), None, "NUL ref");
assert_eq!(read("", valid.clone()), None, "empty ref");
assert_eq!(read("X", valid), None, "invalid ref");
}
#[test]
fn exif_prefix_and_garbage() {
let mut b = b"Exif\0\0".to_vec();
b.extend(sample_exif(ByteOrder::Little));
assert_eq!(read_exif(&b).iso, Some(400));
assert_eq!(read_exif(b"garbage"), Metadata::default());
assert!(try_read_exif(b"garbage").is_err());
}
#[test]
fn apex_fallbacks_and_extended_iso() {
let mut exif = IfdBuilder::new();
exif.set(t::SHUTTER_SPEED_VALUE, Value::SRational(vec![(8, 1)]));
exif.set(t::APERTURE_VALUE, Value::Rational(vec![(4, 1)]));
exif.set(t::ISO_SPEED, Value::Short(vec![65535]));
exif.set(t::RECOMMENDED_EXPOSURE_INDEX, Value::Long(vec![102400]));
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::DATE_TIME, Value::Ascii("2020:01:02 03:04:05".into()));
ifd0.set_child(t::EXIF_IFD, exif);
let m = read_exif(&TiffWriter::default().write(&[ifd0]).unwrap());
assert_eq!(m.exposure_time, Some(1.0 / 256.0));
assert_eq!(m.f_number, Some(4.0));
assert_eq!(m.iso, Some(102400));
assert_eq!(m.capture_time.unwrap().to_exif(), "2020:01:02 03:04:05");
}
#[test]
fn xmp_in_ifd0_overrides_user_fields() {
let mut meta = Metadata { rating: Some(5), title: Some("From XMP".into()), ..Default::default() };
meta.keywords = vec!["a".into()];
let x = crate::write_xmp(&meta, None);
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::RATING, Value::Short(vec![1]));
ifd0.set(t::XMP, Value::Byte(x.into_bytes()));
let m = read_exif(&TiffWriter::default().write(&[ifd0]).unwrap());
assert_eq!(m.rating, Some(5));
assert_eq!(m.title.as_deref(), Some("From XMP"));
}
}
/// An exact `1/N` rational for a sub-second value whose reciprocal is a whole number (shutter speeds such as
/// 1/12800 s, which [`craft_tiff::writer::rational`]'s decimal denominators cannot represent).
fn reciprocal(v: Option<f64>) -> Option<craft_tiff::Value> {
let v = v.filter(|v| v.is_finite() && *v > 0.0 && *v < 1.0)?;
let inv = 1.0 / v;
((inv - inv.round()).abs() < 1e-6 && inv.round() <= u32::MAX as f64).then(|| craft_tiff::Value::Rational(vec![(1, inv.round() as u32)]))
}
/// Serialise the interchange subset of `meta` as a TIFF-structured Exif block (little-endian, no
/// `Exif\0\0` prefix): IFD0 (make, model, software, artist, copyright, description, orientation,
/// date), the Exif IFD (capture settings, lens) and, when present, the GPS IFD.
pub fn write_exif(meta: &Metadata) -> Vec<u8> {
use craft_tiff::writer::{rational, srational};
use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
let ascii = |s: &Option<String>| s.as_ref().filter(|v| !v.is_empty()).map(|v| Value::Ascii(v.clone()));
let mut ifd0 = IfdBuilder::new();
for (tag, v) in [
(t::MAKE, ascii(&meta.make)),
(t::MODEL, ascii(&meta.model)),
(t::SOFTWARE, ascii(&meta.software)),
(t::ARTIST, ascii(&meta.artist)),
(t::COPYRIGHT, ascii(&meta.copyright)),
(t::IMAGE_DESCRIPTION, ascii(&meta.caption)),
(t::DATE_TIME, meta.capture_time.map(|d| Value::Ascii(d.to_exif()))),
(t::ORIENTATION, meta.orientation.map(|o| Value::Short(vec![o.to_exif()]))),
] {
if let Some(v) = v {
ifd0.set(tag, v);
}
}
let mut ex = IfdBuilder::new();
ex.set(t::EXIF_VERSION, Value::Undefined(b"0232".to_vec()));
let r = |v: Option<f64>| v.filter(|v| v.is_finite() && *v > 0.0).map(|v| Value::Rational(vec![rational(v)]));
for (tag, v) in [
(t::DATE_TIME_ORIGINAL, meta.capture_time.map(|d| Value::Ascii(d.to_exif()))),
(t::EXPOSURE_TIME, reciprocal(meta.exposure_time).or_else(|| r(meta.exposure_time))),
(t::F_NUMBER, r(meta.f_number)),
(t::FOCAL_LENGTH, r(meta.focal_length)),
(t::ISO_SPEED, meta.iso.map(|i| Value::Short(vec![i.min(65_535) as u16]))),
(t::ISO_SPEED_RATINGS_EXT, meta.iso.filter(|&i| i > 65_534).map(|i| Value::Long(vec![i]))),
(t::LENS_MAKE, ascii(&meta.lens_make)),
(t::LENS_MODEL, ascii(&meta.lens_model)),
(t::EXPOSURE_BIAS, meta.exposure_bias.map(|v| Value::SRational(vec![srational(v)]))),
] {
if let Some(v) = v {
ex.set(tag, v);
}
}
if let Some(d) = meta.capture_time {
// an offset past 18 h is not a real one (a deserialized value can be anything): write none
let offset = d.offset_minutes.filter(|o| o.unsigned_abs() <= 18 * 60).map(|o| {
let sign = if o < 0 { '-' } else { '+' };
format!("{sign}{:02}:{:02}", o.unsigned_abs() / 60, o.unsigned_abs() % 60)
});
let subsec = (d.millis != 0).then(|| format!("{:03}", d.millis));
for (tag, v) in [(t::OFFSET_TIME, &offset), (t::OFFSET_TIME_ORIGINAL, &offset), (t::SUBSEC_TIME, &subsec), (t::SUBSEC_TIME_ORIGINAL, &subsec)]
{
if let Some(v) = v {
ex.set(tag, Value::Ascii(v.clone()));
}
}
}
ifd0.set_child(t::EXIF_IFD, ex);
if let Some(g) = meta.gps {
let dms = |v: f64| {
let v = v.abs();
let d = v.floor();
let m = ((v - d) * 60.0).floor();
let s = (v - d - m / 60.0) * 3600.0;
Value::Rational(vec![(d as u32, 1), (m as u32, 1), ((s * 1000.0).round() as u32, 1000)])
};
let mut gps = IfdBuilder::new();
gps.set(t::GPS_VERSION_ID, Value::Byte(vec![2, 3, 0, 0]));
gps.set(t::GPS_LATITUDE_REF, Value::Ascii(if g.latitude < 0.0 { "S" } else { "N" }.into()));
gps.set(t::GPS_LATITUDE, dms(g.latitude));
gps.set(t::GPS_LONGITUDE_REF, Value::Ascii(if g.longitude < 0.0 { "W" } else { "E" }.into()));
gps.set(t::GPS_LONGITUDE, dms(g.longitude));
if let Some(a) = g.altitude {
gps.set(t::GPS_ALTITUDE_REF, Value::Byte(vec![u8::from(a < 0.0)]));
gps.set(t::GPS_ALTITUDE, Value::Rational(vec![rational(a.abs())]));
}
ifd0.set_child(t::GPS_IFD, gps);
}
TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap_or_default()
craft_metadata::write_exif(&to_craft(meta))
}
pub(crate) fn ifd0_orientation(bytes: &[u8]) -> Option<Orientation> {
let tiff = Tiff::parse(strip_exif_header(bytes)).ok()?;
tiff.ifds.first()?.u16(t::ORIENTATION).map(Orientation::from_exif)
}
#[cfg(test)]
mod write_tests {
use super::*;
use crate::{DateTime, Gps};
#[test]
fn capture_time_offset_and_subsec_round_trip() {
@@ -756,4 +101,14 @@ mod write_tests {
assert!((1.0 / got - den).abs() < 0.5, "1/{den} s came back as 1/{}", 1.0 / got);
}
}
#[test]
fn written_shutter_speeds_show_as_the_same_reciprocal() {
// #1619 / #2542: the exact time is what export writes, and it reads back as the text shown
for (t, want) in [(1.0 / 3.0, "1/3"), (1.0 / 250.0, "1/250"), (1.0 / 12_800.0, "1/12800"), (0.3, "0.3"), (1.0 / 2.8, "0.3571")] {
let back = read_exif(&write_exif(&Metadata { exposure_time: Some(t), ..Default::default() }));
let got = back.exposure_time.unwrap();
assert_eq!(crate::format_exposure_time(got).as_deref(), Some(want), "{t} came back as {got}");
}
}
}
+28 -252
View File
@@ -1,37 +1,15 @@
//! Where the camera focused: the autofocus point a camera records in its maker notes, as a box on the
//! upright photo ([`FocusPoint`]). Sony only for now.
//!
//! **Sony** (the MakerNote IFD: header-less in ARWs, after a `SONY DSC` header in JPEGs). Tag identities and value names come from the public ExifTool
//! tag-name documentation (Sony table); every layout below was confirmed on real ILCE-1 (α1) and
//! ILCE-7SM3 (A7S III) ARWs, compared with ExifTool's output as a black box. No third-party code was read.
//!
//! | Tag | Layout (confirmed) | Use |
//! |---|---|---|
//! | `0x2027` FocusLocation | 4 × int16u: the width and height of the frame it is measured in, then the focus centre x, y in pixels of that frame (the sensor's landscape frame: a portrait shot still says 8640 × 5760) | the point |
//! | `0x2037` FocusFrameSize | 6 bytes: int16u width, int16u height of the frame the camera showed, then 2 bytes that are zero when there is no frame (manual focus) | the box size |
//! | `0x201b` FocusMode | int8u: 0 Manual, 2 AF-S, 3 AF-C, 4 AF-A, 6 DMF, 7 AF-D | manual = no point |
//! | `0x201c` AFAreaModeSetting | int8u: 0 Wide, 1 Center, 3 Flexible Spot, 11 Zone, 12 Expanded Flexible Spot, 13 Custom AF Area | shown |
//! | `0x2021` AFTracking | int8u: 0 Off, 1 Face tracking, 2 Lock On AF | shown |
//! | `0x9402` (enciphered block) byte 0x16, 0x17 | FocusMode (low 7 bits) and the AF area mode actually used: 0 Multi, 1 Center, 2 Spot, 3 Flexible Spot, 11 Zone, 12 Expanded Flexible Spot, 13 Custom AF Area, 14 Tracking, 15 Face Tracking, 20 Animal Eye Tracking, 21 Human Eye Tracking, 255 Manual | shown; read only when its focus mode agrees with `0x201b` |
//!
//! The `0x94xx` blocks are enciphered byte by byte (the documentation calls it "a simple substitution
//! cipher"). On the sample files each plain byte `p < 249` is stored as `p³ mod 249` and bytes 249–255
//! as themselves (e.g. a stored `0x20` reads as AFAreaMode 20, stored `0x77` as `0x83`, FocusMode AF-C
//! with its top bit set); the map is a bijection on 0..249 (cubing is invertible mod 3 and mod 83), so
//! it is undone by a table of its inverse.
//!
//! **No real point** (nothing is stored, so nothing is drawn and Z zooms as before):
//! - a body the layout hasn't been confirmed on ([`SONY_MODELS`]), a missing or malformed tag, a zero
//! frame size, or a centre outside its frame;
//! - manual focus (`0x201b` = 0, or the block's area mode says Manual): the camera still records where
//! the AF frame was parked, not where anything was in focus (on the samples these are off-centre);
//! - the exact frame centre while the area used was Multi (Wide with nothing tracked): on the samples
//! the wide area reports the centre when it picked no particular spot. A centred Spot, Zone or
//! Flexible Spot frame is a real choice and is kept.
pub use crate::focus_read::{HEADER_PREFIX, HeaderRead, MAX_HEADER_BYTES, read_header};
use crate::{Orientation, Rect};
use craft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t};
pub use craft_metadata::focus::{HEADER_PREFIX, MAX_HEADER_BYTES, camera_supported, decoder_tag, synthetic_arw};
pub struct HeaderRead {
pub focus: Option<FocusPoint>,
pub bytes_read: u64,
}
pub fn read_header(len: u64, read_at: &mut dyn FnMut(u64, &mut [u8]) -> std::io::Result<()>) -> std::io::Result<HeaderRead> {
craft_metadata::focus::read_header(len, read_at)
.map(|r| HeaderRead { focus: r.focus.map(crate::convert::focus_from_craft), bytes_read: r.bytes_read })
}
use serde::{Deserialize, Serialize};
/// Where the camera focused, on the upright photo.
@@ -60,225 +38,23 @@ impl FocusPoint {
pub fn words(&self) -> Vec<&str> {
[&self.mode, &self.area, &self.tracking].into_iter().filter_map(|s| s.as_deref()).filter(|s| !s.is_empty()).collect()
}
/// The box clipped to the frame and checked: `None` when it is not a usable box (non-finite,
/// empty, or entirely outside the photo).
pub fn sanitized(mut self) -> Option<FocusPoint> {
let r = self.rect;
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
return None;
/// The box clipped to the frame and checked: `None` when it is not a usable box.
pub fn sanitized(self) -> Option<FocusPoint> {
let craft_fp =
craft_metadata::FocusPoint { rect: crate::convert::rect_to_craft(self.rect), mode: self.mode, area: self.area, tracking: self.tracking };
craft_fp.sanitized().map(crate::convert::focus_from_craft)
}
/// Orient a normalized sensor-frame box to the upright photo's frame.
pub fn orient_box(r: Rect, o: Orientation) -> Rect {
match o.to_exif() {
2 => Rect { x0: 1.0 - r.x1, y0: r.y0, x1: 1.0 - r.x0, y1: r.y1 },
3 => Rect { x0: 1.0 - r.x1, y0: 1.0 - r.y1, x1: 1.0 - r.x0, y1: 1.0 - r.y0 },
4 => Rect { x0: r.x0, y0: 1.0 - r.y1, x1: r.x1, y1: 1.0 - r.y0 },
5 => Rect { x0: r.y0, y0: r.x0, x1: r.y1, y1: r.x1 },
6 => Rect { x0: 1.0 - r.y1, y0: r.x0, x1: 1.0 - r.y0, y1: r.x1 },
7 => Rect { x0: 1.0 - r.y1, y0: 1.0 - r.x1, x1: 1.0 - r.y0, y1: 1.0 - r.x0 },
8 => Rect { x0: r.y0, y0: 1.0 - r.x1, x1: r.y1, y1: 1.0 - r.x0 },
_ => r,
}
let (x0, x1) = (r.x0.min(r.x1).clamp(0.0, 1.0), r.x0.max(r.x1).clamp(0.0, 1.0));
let (y0, y1) = (r.y0.min(r.y1).clamp(0.0, 1.0), r.y0.max(r.y1).clamp(0.0, 1.0));
if x1 - x0 <= 0.0 || y1 - y0 <= 0.0 {
return None;
}
self.rect = Rect { x0, y0, x1, y1 };
Some(self)
}
}
/// Sony bodies whose focus tags have been checked against real files. Another body may store the same
/// tags differently (or not mean the same by them): it shows no focus point until its files are checked.
pub const SONY_MODELS: &[&str] = &["ILCE-1", "ILCE-7SM3"];
/// Whether a camera as the catalog names it (`"SONY ILCE-1"`: the Exif Make, a space, the Model) is
/// one whose files can carry a focus point, so a photo from any other camera is never opened to look.
pub fn camera_supported(camera: &str) -> bool {
let camera = camera.trim();
camera.get(..4).is_some_and(|m| m.eq_ignore_ascii_case("SONY")) && camera.rsplit(' ').next().is_some_and(|model| SONY_MODELS.contains(&model))
}
/// Names what [`read`] decodes (its bodies), so a record of "looked, found nothing" made by this
/// decoder is not trusted by one that knows more bodies.
pub fn decoder_tag() -> String {
format!("sony-v1:{}", SONY_MODELS.join(","))
}
const FOCUS_MODE: u16 = 0x201b;
const AF_AREA_SETTING: u16 = 0x201c;
const AF_TRACKING: u16 = 0x2021;
const FOCUS_LOCATION: u16 = 0x2027;
const FOCUS_FRAME_SIZE: u16 = 0x2037;
const TAG_9402: u16 = 0x9402;
/// Side of the box drawn when the camera gave a point but no frame size, as a fraction of the frame's
/// short side (about the size of the α1's smallest frames).
const DEFAULT_SIDE: f64 = 0.03;
/// The focus point a file's maker note records, or `None` (see the module notes for when).
/// `data` is the TIFF stream the maker note's offsets refer to (a whole raw, or an Exif block).
pub fn read(data: &[u8], tiff: &Tiff, make: Option<&str>, model: Option<&str>, orientation: Option<Orientation>) -> Option<FocusPoint> {
let make = make?;
if !make.to_ascii_uppercase().starts_with("SONY") || !SONY_MODELS.contains(&model?.trim()) {
return None;
}
let e = tiff.exif()?.get(t::MAKER_NOTE)?;
let mn = makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, make)?;
// ARWs from these bodies carry a header-less IFD; their JPEGs the `SONY DSC` header
if !matches!(mn.kind, makernote::MakerNoteKind::Sony | makernote::MakerNoteKind::Plain) {
return None;
}
sony(&mn.ifd, mn.order, orientation.unwrap_or_default())
}
fn byte(ifd: &Ifd, tag: u16) -> Option<u8> {
ifd.value(tag)?.get_u64(0).and_then(|v| u8::try_from(v).ok())
}
/// Decode the Sony tags of a parsed maker-note IFD.
pub(crate) fn sony(ifd: &Ifd, order: ByteOrder, orientation: Orientation) -> Option<FocusPoint> {
let loc = ifd.value(FOCUS_LOCATION)?;
let [w, h, x, y] = [0, 1, 2, 3].map(|i| loc.get_u64(i));
let (w, h, x, y) = (w? as f64, h? as f64, x? as f64, y? as f64);
if w < 1.0 || h < 1.0 || x > w || y > h {
return None;
}
let mode = byte(ifd, FOCUS_MODE);
if mode == Some(0) {
return None;
}
// the enciphered block: its focus mode must agree with the plain one, else its layout is not the one we know
let block = ifd.bytes(TAG_9402).and_then(|b| {
let (m, area) = (decipher(*b.get(0x16)?) & 0x7f, decipher(*b.get(0x17)?));
(Some(m) == mode).then_some(area)
});
if block == Some(255) {
return None;
}
let setting = byte(ifd, AF_AREA_SETTING);
let tracking = byte(ifd, AF_TRACKING);
let wide_untracked = match block {
Some(a) => a == 0,
None => setting == Some(0) && tracking.is_none_or(|t| t == 0),
};
if wide_untracked && x * 2.0 == w && y * 2.0 == h {
return None;
}
// frame size: two int16u in the note's byte order, then a non-zero marker when there is a frame
let size = ifd.bytes(FOCUS_FRAME_SIZE).and_then(|b| {
let (fw, fh) = (order.read_u16(b, 0)? as f64, order.read_u16(b, 2)? as f64);
let shown = b.get(4..6).is_none_or(|m| m.iter().any(|&v| v != 0));
(shown && fw >= 1.0 && fh >= 1.0).then_some((fw, fh))
});
let (fw, fh) = size.unwrap_or_else(|| {
let side = w.min(h) * DEFAULT_SIDE;
(side, side)
});
let sensor = Rect { x0: (x - fw / 2.0) / w, y0: (y - fh / 2.0) / h, x1: (x + fw / 2.0) / w, y1: (y + fh / 2.0) / h };
let name = |v: Option<u8>, f: fn(u8) -> Option<&'static str>| v.and_then(f).map(str::to_string);
let area = name(setting, area_setting_name);
let used = name(block, area_used_name);
// what it followed: the area mode used when it says more than the setting (Animal Eye Tracking on
// Wide), else the tracking setting when it is on
let tracking = used.filter(|u| Some(u) != area.as_ref() && u != "Multi").or_else(|| name(tracking, tracking_name).filter(|t| t != "Off"));
FocusPoint { rect: orientation.map_norm_rect(sensor), mode: name(mode, focus_mode_name), area, tracking }.sanitized()
}
/// A minimal little-endian TIFF laid out as an α1 ARW's metadata is (IFD0 with Make `SONY` and Model `ILCE-1` →
/// Exif IFD → a header-less maker note with the focus tags: AF-C or the given FocusMode byte, Wide, Face tracking,
/// Animal Eye Tracking at (3226, 1980) of 8640 × 5760), followed by `samples` bytes standing in for sensor data. For
/// tests of the readers and the backfill in other crates; not a real raw (it has no image).
#[doc(hidden)]
pub fn synthetic_arw(mode: u8, samples: usize) -> Vec<u8> {
fn entry(f: &mut Vec<u8>, tag: u16, typ: u16, count: u32, value: [u8; 4]) {
f.extend_from_slice(&tag.to_le_bytes());
f.extend_from_slice(&typ.to_le_bytes());
f.extend_from_slice(&count.to_le_bytes());
f.extend_from_slice(&value);
}
let encipher = |p: u8| if p >= 249 { p } else { (u32::from(p).pow(3) % 249) as u8 };
let mut f = b"II*\0".to_vec();
f.extend_from_slice(&8u32.to_le_bytes());
// IFD0 at 8: Make (at 62), Model (at 68), Orientation, the Exif IFD (at 76)
f.extend_from_slice(&4u16.to_le_bytes());
entry(&mut f, t::MAKE, 2, 5, 62u32.to_le_bytes());
entry(&mut f, t::MODEL, 2, 7, 68u32.to_le_bytes());
entry(&mut f, t::ORIENTATION, 3, 1, [1, 0, 0, 0]);
entry(&mut f, t::EXIF_IFD, 4, 1, 76u32.to_le_bytes());
f.extend_from_slice(&[0; 4]);
f.extend_from_slice(b"SONY\0\0ILCE-1\0\0");
// the Exif IFD: the maker note at 94, 156 bytes
f.extend_from_slice(&1u16.to_le_bytes());
entry(&mut f, t::MAKER_NOTE, 7, 156, 94u32.to_le_bytes());
f.extend_from_slice(&[0; 4]);
// the maker note's IFD, its values from 172
f.extend_from_slice(&6u16.to_le_bytes());
entry(&mut f, FOCUS_MODE, 1, 1, [mode, 0, 0, 0]);
entry(&mut f, AF_AREA_SETTING, 1, 1, [0, 0, 0, 0]);
entry(&mut f, AF_TRACKING, 1, 1, [1, 0, 0, 0]);
entry(&mut f, FOCUS_LOCATION, 3, 4, 172u32.to_le_bytes());
entry(&mut f, FOCUS_FRAME_SIZE, 7, 6, 180u32.to_le_bytes());
entry(&mut f, TAG_9402, 7, 64, 186u32.to_le_bytes());
f.extend_from_slice(&[0; 4]);
for v in [8640u16, 5760, 3226, 1980] {
f.extend_from_slice(&v.to_le_bytes());
}
f.extend_from_slice(&[0xaf, 0, 0xb4, 0, 1, 1]);
let mut block = [0u8; 64];
block[0x16] = encipher(0x80 | mode);
block[0x17] = encipher(20);
f.extend_from_slice(&block);
f.extend((0..samples).map(|i| (i % 251) as u8));
f
}
/// Undo the `0x94xx` byte substitution: the stored byte is `p³ mod 249` for `p < 249`.
fn decipher(b: u8) -> u8 {
if b >= 249 {
return b;
}
(0..249u32).find(|p| (p * p * p) % 249 == u32::from(b)).and_then(|p| u8::try_from(p).ok()).unwrap_or(b)
}
fn focus_mode_name(v: u8) -> Option<&'static str> {
Some(match v {
0 => "Manual",
2 => "AF-S",
3 => "AF-C",
4 => "AF-A",
6 => "DMF",
7 => "AF-D",
_ => return None,
})
}
fn area_setting_name(v: u8) -> Option<&'static str> {
Some(match v {
0 => "Wide",
1 | 9 => "Center",
3 | 4 => "Flexible Spot",
11 => "Zone",
12 => "Expanded Flexible Spot",
13 => "Custom AF Area",
_ => return None,
})
}
fn tracking_name(v: u8) -> Option<&'static str> {
Some(match v {
0 => "Off",
1 => "Face tracking",
2 => "Lock On AF",
_ => return None,
})
}
fn area_used_name(v: u8) -> Option<&'static str> {
Some(match v {
0 => "Multi",
1 => "Center",
2 => "Spot",
3 => "Flexible Spot",
11 => "Zone",
12 => "Expanded Flexible Spot",
13 => "Custom AF Area",
14 => "Tracking",
15 => "Face Tracking",
20 => "Animal Eye Tracking",
21 => "Human Eye Tracking",
_ => return None,
})
}
#[cfg(test)]
mod tests;
-472
View File
@@ -1,472 +0,0 @@
//! Reading a file's focus point without reading the file: [`read_header`] asks for the few byte
//! ranges [`crate::focus::read`] looks at (a TIFF raw's IFD0, its Exif IFD, the maker-note IFD and
//! the values of the focus tags; a JPEG's Exif segment) and decodes them exactly as a whole-file
//! read would. On the α1 and the A7S III all of it sits in the first 16 KB of a 50–120 MB ARW, so a
//! library of them can be backfilled from a slow disk by reading one small block per photo.
//!
//! The ranges are found by walking the structure as the readers do (the IFD tables and the value
//! offsets they hold), round by round: each round asks only for what the bytes loaded so far point
//! at. A TIFF is decoded from a buffer of the file's length in which only the loaded ranges hold the
//! file's bytes (the rest stays zero and its pages are never touched), so every offset and bound the
//! reader checks is the one it checks on the whole file. Rounds, bytes and the buffer are bounded:
//! a file that wants more is reported as having no focus point.
use std::io;
use crate::focus::FocusPoint;
use craft_tiff::{ByteOrder, FieldType, Tiff, tags as t};
/// Bytes read first: the α1's and A7S III's focus data ends before 16 KB, so one read covers it.
pub const HEADER_PREFIX: u64 = 32 * 1024;
/// Later reads are widened to this granularity (fewer, larger reads on a spinning disk).
const ALIGN: u64 = 4 * 1024;
/// The most rounds of reads one file gets (a real file needs one; the walk takes at most nine).
const MAX_ROUNDS: usize = 12;
/// The most bytes read from one file: past this the layout is not one the decoder knows.
pub const MAX_HEADER_BYTES: u64 = 2 << 20;
/// The largest TIFF given a buffer of its length (its untouched pages are never written, but the
/// allocation must succeed: the engine's planned preview reads use the same bound). Raws are far below it.
const MAX_SPARSE_FILE: u64 = 1 << 30;
/// JPEG segments walked before giving up.
const MAX_SEGMENTS: usize = 1024;
/// Entries read from one IFD (the TIFF reader's limit).
const MAX_ENTRIES: u64 = 8192;
/// The focus tags whose values [`crate::focus`] reads from a Sony maker note.
const FOCUS_TAGS: [u16; 6] = [0x201b, 0x201c, 0x2021, 0x2027, 0x2037, 0x9402];
/// What [`read_header`] found, and what it cost.
#[derive(Clone, Debug, PartialEq)]
pub struct HeaderRead {
/// The focus point a whole-file read gives ([`crate::extract`]`(file).focus`).
pub focus: Option<FocusPoint>,
/// Bytes read from the file.
pub bytes_read: u64,
}
/// The focus point of a file of `len` bytes, reading only what it needs through `read_at(offset,
/// buf)`, which fills `buf` with the file's bytes at `offset` (an error — a file that shrank or
/// went away — is returned). A malformed or unknown file is `Ok` with no point.
pub fn read_header(len: u64, read_at: &mut dyn FnMut(u64, &mut [u8]) -> io::Result<()>) -> io::Result<HeaderRead> {
let mut reader = Reader { len, read_at, bytes: 0 };
let head = reader.fetch(0, HEADER_PREFIX.min(len))?;
let focus = if head.starts_with(&[0xff, 0xd8]) {
jpeg(&mut reader, &head)?
} else if matches!(Tiff::sniff(&head), Some((_, false))) {
tiff(&mut reader, head)?
} else {
None
};
Ok(HeaderRead { focus, bytes_read: reader.bytes })
}
struct Reader<'a> {
len: u64,
read_at: &'a mut dyn FnMut(u64, &mut [u8]) -> io::Result<()>,
bytes: u64,
}
impl Reader<'_> {
/// `[start, end)` of the file (clipped to it), counted against [`MAX_HEADER_BYTES`].
fn fetch(&mut self, start: u64, end: u64) -> io::Result<Vec<u8>> {
let end = end.min(self.len);
let n = end.saturating_sub(start);
if self.bytes.saturating_add(n) > MAX_HEADER_BYTES {
return Err(io::Error::other(OverBudget));
}
let mut buf = vec![0u8; usize::try_from(n).map_err(|_| io::Error::other("range too large"))?];
if n > 0 {
(self.read_at)(start, &mut buf)?;
}
self.bytes = self.bytes.saturating_add(n);
Ok(buf)
}
}
/// A file whose focus data would take more than [`MAX_HEADER_BYTES`] to read.
#[derive(Debug)]
struct OverBudget;
impl std::fmt::Display for OverBudget {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("focus data larger than a header")
}
}
impl std::error::Error for OverBudget {}
fn over_budget(e: &io::Error) -> bool {
e.get_ref().is_some_and(|i| i.is::<OverBudget>())
}
/// An over-budget read is "no focus point here", not a failure to report.
fn budget_is_none<T>(r: io::Result<Option<T>>) -> io::Result<Option<T>> {
match r {
Err(e) if over_budget(&e) => Ok(None),
r => r,
}
}
/// A JPEG's first `Exif` APP1 segment, found as [`crate::jpeg_segments`] finds it.
fn jpeg(r: &mut Reader, head: &[u8]) -> io::Result<Option<FocusPoint>> {
budget_is_none(jpeg_inner(r, head))
}
fn jpeg_inner(r: &mut Reader, head: &[u8]) -> io::Result<Option<FocusPoint>> {
let len = r.len;
let at = |r: &mut Reader, start: u64, n: u64| -> io::Result<Vec<u8>> {
let local = usize::try_from(start).ok().zip(usize::try_from(start.saturating_add(n)).ok()).and_then(|(a, b)| head.get(a..b));
match local {
Some(s) => Ok(s.to_vec()),
None => r.fetch(start, start.saturating_add(n)),
}
};
let mut i = 2u64;
for _ in 0..MAX_SEGMENTS {
if i.saturating_add(4) > len {
break;
}
let h = at(r, i, 4)?;
let (Some(&ff), Some(&marker), Some(&a), Some(&b)) = (h.first(), h.get(1), h.get(2), h.get(3)) else { break };
if ff != 0xff {
break;
}
if marker == 0xff {
i += 1;
continue;
}
if marker == 0xd8 || (0xd0..=0xd7).contains(&marker) || marker == 0x01 {
i += 2;
continue;
}
if marker == 0xd9 || marker == 0xda {
break;
}
let seg = u64::from(u16::from_be_bytes([a, b]));
if seg < 2 {
break;
}
let end = i.saturating_add(2).saturating_add(seg).min(len);
if marker == 0xe1 {
let payload = at(r, i + 4, end.saturating_sub(i + 4))?;
if payload.starts_with(b"Exif\0") {
return Ok(crate::read_exif(payload.get(6..).unwrap_or(&[])).focus);
}
}
i = end;
}
Ok(None)
}
/// A TIFF raw, decoded from a buffer of its length holding only the ranges [`plan`] asked for.
fn tiff(r: &mut Reader, head: Vec<u8>) -> io::Result<Option<FocusPoint>> {
if r.len > MAX_SPARSE_FILE {
return Ok(None);
}
let Ok(len) = usize::try_from(r.len) else { return Ok(None) };
let mut buf = vec![0u8; len];
let Some(dst) = buf.get_mut(..head.len()) else { return Ok(None) };
dst.copy_from_slice(&head);
let mut loaded = Loaded::default();
loaded.insert(0, head.len() as u64);
for _ in 0..MAX_ROUNDS {
match plan(&buf, &loaded) {
Step::Ready => {
// The decoder's allocation budget follows the bytes actually fetched, not the logical
// file length: only the loaded ranges are data, and an unrelated entry that claims a
// huge value must be cut by what leaving it cost, not by what the buffer claims to hold.
// The same 8 × / + 1 MiB shape the general TIFF reader uses, over `reader.bytes` instead.
let opts = craft_tiff::ParseOptions { value_budget: Some(r.bytes.saturating_mul(8).saturating_add(1 << 20)), ..Default::default() };
return Ok(crate::try_read_exif_with(&buf, &opts).ok().and_then(|m| m.focus));
}
Step::Nothing => return Ok(None),
Step::Need(ranges) => {
for (a, b) in ranges {
// widen to the read granularity, but never re-read what is loaded
let (wa, wb) = ((a / ALIGN) * ALIGN, b.div_ceil(ALIGN).saturating_mul(ALIGN).min(r.len));
for (s, e) in loaded.gaps(wa, wb) {
let bytes = match r.fetch(s, e) {
Err(e) if over_budget(&e) => return Ok(None),
other => other?,
};
let (Ok(su), Ok(eu)) = (usize::try_from(s), usize::try_from(e)) else { return Ok(None) };
let Some(dst) = buf.get_mut(su..eu) else { return Ok(None) };
dst.copy_from_slice(&bytes);
loaded.insert(s, e);
}
}
}
}
}
Ok(None)
}
/// Sorted, disjoint, non-touching byte ranges.
#[derive(Default)]
struct Loaded(Vec<(u64, u64)>);
impl Loaded {
fn insert(&mut self, start: u64, end: u64) {
if start >= end {
return;
}
let (mut s, mut e) = (start, end);
let mut out = Vec::with_capacity(self.0.len() + 1);
for &(a, b) in &self.0 {
if b < s || a > e {
out.push((a, b));
} else {
s = s.min(a);
e = e.max(b);
}
}
out.push((s, e));
out.sort_unstable();
self.0 = out;
}
fn contains(&self, start: u64, end: u64) -> bool {
start >= end || self.0.iter().any(|&(a, b)| a <= start && end <= b)
}
/// The parts of `[start, end)` not loaded.
fn gaps(&self, start: u64, end: u64) -> Vec<(u64, u64)> {
let mut out = Vec::new();
let mut at = start;
for &(a, b) in &self.0 {
if b <= at || a >= end {
continue;
}
if a > at {
out.push((at, a.min(end)));
}
at = at.max(b);
if at >= end {
break;
}
}
if at < end {
out.push((at, end));
}
out
}
}
enum Step {
/// Load these and ask again.
Need(Vec<(u64, u64)>),
/// Everything the decoder reads is loaded.
Ready,
/// The file has nothing the decoder could read (no Exif, no maker note, a structure it rejects).
Nothing,
}
/// One IFD entry as the TIFF reader sees it: where its value is (absolute), if it fits the file.
struct RawEntry {
tag: u16,
typ: FieldType,
start: u64,
end: u64,
}
struct Want<'a> {
buf: &'a [u8],
order: ByteOrder,
loaded: &'a Loaded,
need: Vec<(u64, u64)>,
}
impl Want<'_> {
fn len(&self) -> u64 {
self.buf.len() as u64
}
/// Whether `[start, end)` (clipped to the file) is loaded; asks for it if not.
fn want(&mut self, start: u64, end: u64) -> bool {
let end = end.min(self.len());
if self.loaded.contains(start, end) {
return true;
}
self.need.push((start, end));
false
}
/// The entries of the IFD at `off` (values relative to 0), once its table is loaded; `Some(empty)`
/// for one the reader would reject.
fn table(&mut self, off: u64) -> Option<Vec<RawEntry>> {
let len = self.len();
if off == 0 || off >= len {
return Some(Vec::new());
}
if !self.want(off, off.saturating_add(2)) {
return None;
}
let pos = usize::try_from(off).ok()?;
let n = u64::from(self.order.read_u16(self.buf, pos)?);
let table = off + 2;
let n_read = n.min(len.saturating_sub(table) / 12).min(MAX_ENTRIES);
let end = table + n_read * 12 + if n_read == n { 4 } else { 0 };
if !self.want(off, end) {
return None;
}
let mut out = Vec::new();
for i in 0..n_read {
let Ok(p) = usize::try_from(table + i * 12) else { continue };
let (Some(tag), Some(typ), Some(count)) = (
self.order.read_u16(self.buf, p),
self.order.read_u16(self.buf, p + 2).and_then(FieldType::from_u16),
self.order.read_u32(self.buf, p + 4),
) else {
continue;
};
let Some(total) = u64::from(count).checked_mul(typ.size() as u64) else { continue };
let field = p as u64 + 8;
let start = if total <= 4 {
field
} else {
match self.order.read_u32(self.buf, p + 8) {
Some(v) => u64::from(v),
None => continue,
}
};
let Some(end) = start.checked_add(total).filter(|&e| e <= len) else { continue };
out.push(RawEntry { tag, typ, start, end });
}
Some(out)
}
/// The first unsigned value of an entry (loaded).
fn first_value(&self, e: &RawEntry) -> Option<u64> {
let pos = usize::try_from(e.start).ok()?;
match e.typ.size() {
1 => self.buf.get(pos).map(|&b| u64::from(b)),
2 => self.order.read_u16(self.buf, pos).map(u64::from),
4 => self.order.read_u32(self.buf, pos).map(u64::from),
_ => self.order.read_u64(self.buf, pos),
}
}
fn step(self) -> Step {
if self.need.is_empty() { Step::Ready } else { Step::Need(self.need) }
}
}
/// What of a classic TIFF the focus decoder still needs, given what is `loaded`: IFD0 (Make, Model,
/// the Exif pointer), the Exif IFD (the maker-note entry), the maker note's header and IFD as
/// `craft_tiff::makernote` locates it, and the focus tags' values.
fn plan(buf: &[u8], loaded: &Loaded) -> Step {
let Some((order, false)) = Tiff::sniff(buf) else { return Step::Nothing };
let mut w = Want { buf, order, loaded, need: Vec::new() };
let Some(ifd0) = order.read_u32(buf, 4).map(u64::from) else { return Step::Nothing };
let Some(e0) = w.table(ifd0) else { return w.step() };
let mut exif = None;
for e in &e0 {
if matches!(e.tag, t::MAKE | t::MODEL | t::UNIQUE_CAMERA_MODEL | t::ORIENTATION) {
w.want(e.start, e.end);
}
if e.tag == t::EXIF_IFD && exif.is_none() && w.want(e.start, e.end) {
exif = w.first_value(e);
}
}
if !w.need.is_empty() {
return w.step();
}
let Some(exif) = exif.filter(|&o| o != 0) else { return Step::Nothing };
let Some(ee) = w.table(exif) else { return w.step() };
let Some(note) = ee.iter().find(|e| e.tag == t::MAKER_NOTE) else { return Step::Nothing };
let head_end = note.start.saturating_add(12).min(note.end);
if !w.want(note.start, head_end) {
return w.step();
}
let head = usize::try_from(note.start).ok().zip(usize::try_from(head_end).ok()).and_then(|(a, b)| buf.get(a..b)).unwrap_or(&[]);
let sony = head.starts_with(b"SONY") || head.starts_with(b"VHAB \0");
// another maker's header: `focus::read` only decodes Sony and header-less notes
let foreign: [&[u8]; 13] = [
b"Nikon\0",
b"FUJIFILM",
b"GENERALE",
b"OLYMPUS\0",
b"OM SYSTEM\0",
b"OLYMP\0",
b"EPSON\0",
b"MINOL\0",
b"CAMER\0",
b"SANYO\0",
b"Panasonic\0",
b"AOC\0",
b"PENTAX \0",
];
if !sony && foreign.iter().any(|p| head.starts_with(p)) {
return Step::Nothing;
}
let mut entries = None;
if sony {
match w.table(note.start.saturating_add(12)) {
None => return w.step(),
Some(e) if !e.is_empty() => entries = Some(e),
Some(_) => {}
}
}
let entries = match entries {
Some(e) => e,
None => match w.table(note.start) {
Some(e) => e,
None => return w.step(),
},
};
for e in entries.iter().filter(|e| FOCUS_TAGS.contains(&e.tag)) {
w.want(e.start, e.end);
}
w.step()
}
#[cfg(test)]
mod tests {
use super::*;
/// A reader over `file` that counts what it is asked for.
fn read(file: &[u8]) -> (io::Result<HeaderRead>, u64) {
let mut asked = 0u64;
let r = read_header(file.len() as u64, &mut |off, buf: &mut [u8]| {
asked += buf.len() as u64;
let start = usize::try_from(off).map_err(io::Error::other)?;
let src = file.get(start..start + buf.len()).ok_or_else(|| io::Error::from(io::ErrorKind::UnexpectedEof))?;
buf.copy_from_slice(src);
Ok(())
});
(r, asked)
}
#[test]
fn loaded_ranges() {
let mut l = Loaded::default();
l.insert(10, 20);
l.insert(30, 40);
assert_eq!(l.gaps(0, 50), vec![(0, 10), (20, 30), (40, 50)]);
l.insert(20, 30);
assert_eq!(l.0, vec![(10, 40)]);
assert!(l.contains(12, 38) && !l.contains(5, 12));
assert!(l.gaps(15, 35).is_empty());
}
#[test]
fn garbage_and_empty_files_are_no_point() {
for file in [vec![], vec![0xff, 0xd8], b"II*\0\x08\0\0\0".to_vec(), b"MM\0*\xff\xff\xff\xff".to_vec(), vec![0x42; 100_000]] {
let (r, _) = read(&file);
assert_eq!(r.unwrap().focus, None);
}
// a JPEG of nothing but fill bytes and tiny segments stops at its bounds
let mut j = vec![0xff, 0xd8];
for _ in 0..5000 {
j.extend_from_slice(&[0xff, 0xe2, 0, 2]);
}
assert_eq!(read(&j).0.unwrap().focus, None);
}
#[test]
fn a_file_that_shrinks_mid_read_is_an_error() {
// the reader is told the file is longer than it is (replaced between the stat and the read)
let r = read_header(1 << 20, &mut |_, _| Err(io::Error::from(io::ErrorKind::UnexpectedEof)));
assert!(r.is_err());
}
}
-491
View File
@@ -1,491 +0,0 @@
//! GPS track logs in GPX 1.0 / 1.1 (the open GPS Exchange Format, <https://www.topografix.com/gpx.asp>):
//! the timed track points of every `<trk>`, and the position at any moment for geotagging photos.
//!
//! What we use from the format: `<trk>` → `<trkseg>` → `<trkpt lat=… lon=…>` with optional `<ele>`
//! (metres) and `<time>` (an `xsd:dateTime`, UTC per the schema — a time without a zone is read as
//! UTC). Points without a time can't be matched to a photo and are left out; waypoints (`<wpt>`) and
//! routes (`<rte>`) carry no timeline and are ignored. The schema defines a track segment as one
//! continuous span of logging, so positions are only interpolated *within* a segment, never across
//! the gap where reception was lost or the logger was off.
use quick_xml::events::Event;
use crate::{DateTime, Gps};
/// Nesting / size limits (a track log is flat; these only stop hostile input).
const MAX_DEPTH: usize = 64;
const MAX_POINTS: usize = 5_000_000;
/// One timed point of a track.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TrackPoint {
/// Seconds since 1970-01-01T00:00:00Z (fractional when the log has sub-second times).
pub time: f64,
pub latitude: f64,
pub longitude: f64,
/// Metres above sea level.
pub elevation: Option<f64>,
/// Track segment number, counted across the whole file (continuous logging spans).
pub segment: u32,
}
/// How a position was found by [`Tracklog::locate`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Match {
/// The time falls between two points of the same segment: linear interpolation.
Interpolated,
/// The nearest point (at a segment's start or end, or across a gap).
Nearest,
}
/// The timed points of a GPX file, sorted by time.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Tracklog {
pub points: Vec<TrackPoint>,
/// Tracks (`<trk>`) in the file.
pub tracks: usize,
/// Track points without a usable time (left out of `points`).
pub untimed: usize,
}
#[derive(Clone, Debug, PartialEq)]
pub enum GpxError {
Xml(String),
/// Not a GPX document (no `<gpx>` root).
NotGpx,
/// Nesting / size limits exceeded.
TooComplex,
}
impl std::fmt::Display for GpxError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GpxError::Xml(e) => write!(f, "malformed GPX: {e}"),
GpxError::NotGpx => f.write_str("not a GPX file (no <gpx> element)"),
GpxError::TooComplex => f.write_str("GPX file too large or too deeply nested"),
}
}
}
impl std::error::Error for GpxError {}
/// Local name of a possibly prefixed XML name (`gpx:trkpt` → `trkpt`).
fn local(name: &[u8]) -> &[u8] {
name.rsplit(|&b| b == b':').next().unwrap_or(name)
}
/// An `xsd:dateTime` as seconds since the Unix epoch; no zone = UTC (the GPX schema's convention).
fn parse_time(s: &str) -> Option<f64> {
let mut d = DateTime::parse_iso(s)?;
// a bare date (no time of day) is too coarse to place a photo
if !s.contains('T') {
return None;
}
d.offset_minutes.get_or_insert(0);
Some(d.unix_seconds() as f64 + d.millis as f64 / 1000.0)
}
#[derive(Default)]
struct Pending {
lat: Option<f64>,
lon: Option<f64>,
ele: Option<f64>,
time: Option<f64>,
}
/// Parse a GPX document.
pub fn parse_gpx(s: &str) -> Result<Tracklog, GpxError> {
let mut reader = quick_xml::Reader::from_str(s);
// Mismatched end tags must be rejected; otherwise the path stack can
// attribute a point's time or segment to the wrong enclosing element.
reader.config_mut().check_end_names = true;
let mut path: Vec<Vec<u8>> = Vec::new();
let mut seen_gpx = false;
let mut seen_root = false;
let mut log = Tracklog::default();
let mut segment: u32 = 0;
let mut pt: Option<Pending> = None;
let mut text = String::new();
loop {
let ev = reader.read_event().map_err(|e| GpxError::Xml(e.to_string()))?;
match ev {
Event::Start(ref e) | Event::Empty(ref e) => {
let name = local(e.name().as_ref()).to_vec();
let parent = path.last().map(Vec::as_slice);
if path.is_empty() {
if seen_root {
return Err(GpxError::Xml("multiple document elements".into()));
}
seen_root = true;
}
match name.as_slice() {
b"gpx" if path.is_empty() => seen_gpx = true,
b"trk" if parent == Some(b"gpx") => log.tracks += 1,
b"trkseg" if parent == Some(b"trk") && log.points.last().is_some_and(|p| p.segment == segment) => segment += 1,
b"trkpt" if parent == Some(b"trkseg") => {
let mut p = Pending::default();
for a in e.attributes().with_checks(false).flatten() {
match local(a.key.as_ref()) {
b"lat" => {
let v = a
.decoded_and_normalized_value(quick_xml::XmlVersion::Implicit1_0, reader.decoder())
.map_err(|e| GpxError::Xml(e.to_string()))?;
p.lat = v.trim().parse().ok();
}
b"lon" => {
let v = a
.decoded_and_normalized_value(quick_xml::XmlVersion::Implicit1_0, reader.decoder())
.map_err(|e| GpxError::Xml(e.to_string()))?;
p.lon = v.trim().parse().ok();
}
_ => {}
}
}
pt = Some(p);
}
_ => {}
}
text.clear();
if matches!(ev, Event::Start(_)) {
if path.len() >= MAX_DEPTH {
return Err(GpxError::TooComplex);
}
path.push(name);
} else if name == b"trkpt" {
finish_point(&mut log, pt.take(), segment)?;
}
}
Event::Text(t) => text.push_str(&t.decode().map_err(|e| GpxError::Xml(e.to_string()))?),
Event::CData(t) => text.push_str(&String::from_utf8_lossy(&t)),
Event::GeneralRef(r) => {
if let Some(c) = r.resolve_char_ref().map_err(|e| GpxError::Xml(e.to_string()))? {
text.push(c);
} else {
let name = r.decode().map_err(|e| GpxError::Xml(e.to_string()))?;
let entity = format!("&{name};");
let value = quick_xml::escape::unescape(&entity).map_err(|e| GpxError::Xml(e.to_string()))?;
text.push_str(value.as_ref());
}
}
Event::End(_) => {
let Some(name) = path.pop() else { continue };
let parent = path.last().map(Vec::as_slice);
match name.as_slice() {
b"ele" if parent == Some(b"trkpt") => {
if let Some(p) = pt.as_mut() {
p.ele = text.trim().parse().ok().filter(|v: &f64| v.is_finite());
}
}
b"time" if parent == Some(b"trkpt") => {
if let Some(p) = pt.as_mut() {
p.time = parse_time(text.trim());
}
}
b"trkpt" => finish_point(&mut log, pt.take(), segment)?,
_ => {}
}
text.clear();
}
Event::Eof => break,
_ => {}
}
}
if !seen_gpx {
return Err(GpxError::NotGpx);
}
if !path.is_empty() {
return Err(GpxError::Xml("unclosed GPX elements".into()));
}
// stable: points logged at the same second keep their file order
log.points.sort_by(|a, b| a.time.total_cmp(&b.time));
Ok(log)
}
fn finish_point(log: &mut Tracklog, p: Option<Pending>, segment: u32) -> Result<(), GpxError> {
let Some(p) = p else { return Ok(()) };
let (Some(lat), Some(lon)) = (p.lat, p.lon) else { return Ok(()) };
if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {
return Ok(());
}
let Some(time) = p.time else {
log.untimed += 1;
return Ok(());
};
if log.points.len() >= MAX_POINTS {
return Err(GpxError::TooComplex);
}
log.points.push(TrackPoint { time, latitude: lat, longitude: lon, elevation: p.ele, segment });
Ok(())
}
impl Tracklog {
/// First and last point times (seconds since the epoch, UTC).
pub fn span(&self) -> Option<(f64, f64)> {
Some((self.points.first()?.time, self.points.last()?.time))
}
/// Where the logger was at `time` (seconds since the epoch, UTC).
///
/// Between two points of the same segment that are at most `max_gap` seconds apart, the position
/// is interpolated linearly in time. Otherwise the nearest point counts if it is within `max_gap`
/// seconds; beyond that there is no position (the photo was taken while nothing was logged).
pub fn locate(&self, time: f64, max_gap: f64) -> Option<(Gps, Match)> {
let pts = &self.points;
if pts.is_empty() || !time.is_finite() {
return None;
}
let i = pts.partition_point(|p| p.time < time);
let next = pts.get(i);
let prev = i.checked_sub(1).and_then(|j| pts.get(j));
if let Some(n) = next
&& n.time == time
{
return Some((gps(n), Match::Interpolated));
}
if let (Some(a), Some(b)) = (prev, next)
&& a.segment == b.segment
&& b.time - a.time <= max_gap
{
let t = (time - a.time) / (b.time - a.time);
return Some((lerp(a, b, t), Match::Interpolated));
}
let near = match (prev, next) {
(Some(a), Some(b)) => {
if time - a.time <= b.time - time {
a
} else {
b
}
}
(Some(a), None) => a,
(None, Some(b)) => b,
(None, None) => return None,
};
((near.time - time).abs() <= max_gap).then(|| (gps(near), Match::Nearest))
}
}
fn gps(p: &TrackPoint) -> Gps {
Gps { latitude: p.latitude, longitude: p.longitude, altitude: p.elevation }
}
/// Linear interpolation, taking the short way across the ±180° meridian.
fn lerp(a: &TrackPoint, b: &TrackPoint, t: f64) -> Gps {
let mut dlon = b.longitude - a.longitude;
if dlon > 180.0 {
dlon -= 360.0;
} else if dlon < -180.0 {
dlon += 360.0;
}
let mut lon = a.longitude + dlon * t;
if lon > 180.0 {
lon -= 360.0;
} else if lon < -180.0 {
lon += 360.0;
}
let altitude = match (a.elevation, b.elevation) {
(Some(x), Some(y)) => Some(x + (y - x) * t),
(x, y) => x.or(y),
};
Gps { latitude: a.latitude + (b.latitude - a.latitude) * t, longitude: lon, altitude }
}
#[cfg(test)]
mod tests {
use super::*;
const LOG: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1">
<wpt lat="1.0" lon="1.0"><time>2026-05-01T10:00:30Z</time></wpt>
<trk><name>Walk</name>
<trkseg>
<trkpt lat="46.0000" lon="7.0000"><ele>1600</ele><time>2026-05-01T10:00:00Z</time></trkpt>
<trkpt lat="46.0010" lon="7.0020"><ele>1610</ele><time>2026-05-01T10:01:00Z</time></trkpt>
<trkpt lat="46.0020" lon="7.0040"><time>2026-05-01T10:02:00.500Z</time></trkpt>
<trkpt lat="46.5" lon="7.5"/>
</trkseg>
<trkseg>
<trkpt lat="47.0000" lon="8.0000"><time>2026-05-01T12:00:00Z</time></trkpt>
<trkpt lat="47.0010" lon="8.0010"><time>2026-05-01T12:00:10+00:00</time></trkpt>
</trkseg>
</trk>
</gpx>"#;
fn t(s: &str) -> f64 {
parse_time(s).unwrap()
}
#[test]
fn parses_timed_track_points() {
let log = parse_gpx(LOG).unwrap();
assert_eq!(log.tracks, 1);
assert_eq!(log.points.len(), 5, "waypoints and the untimed point are left out");
assert_eq!(log.untimed, 1);
assert_eq!(log.points[0].elevation, Some(1600.0));
assert_eq!(log.points[2].time, t("2026-05-01T10:02:00Z") + 0.5);
assert_eq!((log.points[0].segment, log.points[2].segment, log.points[3].segment), (0, 0, 1));
assert_eq!(log.span(), Some((t("2026-05-01T10:00:00Z"), t("2026-05-01T12:00:10Z"))));
// 2026-05-01T10:00:00Z
assert_eq!(log.points[0].time, 1_777_629_600.0);
}
#[test]
fn malformed_iso_time_is_untimed_and_cannot_match_midnight() {
let source = r#"<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1"><trk><trkseg>
<trkpt lat="45" lon="7"><time>2026-01-01T</time></trkpt>
<trkpt lat="46" lon="8"><time>2026-01-01T01:00:00Z</time></trkpt>
</trkseg></trk></gpx>"#;
let log = parse_gpx(source).unwrap();
assert_eq!(log.untimed, 1);
assert_eq!(log.points.len(), 1);
assert_eq!((log.points[0].latitude, log.points[0].longitude), (46.0, 8.0));
assert!(log.locate(t("2026-01-01T00:00:00Z"), 0.0).is_none());
}
#[test]
fn interpolates_within_a_segment() {
let log = parse_gpx(LOG).unwrap();
let (g, m) = log.locate(t("2026-05-01T10:00:30Z"), 300.0).unwrap();
assert_eq!(m, Match::Interpolated);
assert!((g.latitude - 46.0005).abs() < 1e-9 && (g.longitude - 7.0010).abs() < 1e-9, "{g:?}");
assert_eq!(g.altitude, Some(1605.0));
// exactly on a point
let (g, _) = log.locate(t("2026-05-01T10:01:00Z"), 300.0).unwrap();
assert_eq!((g.latitude, g.longitude), (46.0010, 7.0020));
}
#[test]
fn never_interpolates_across_segments() {
let log = parse_gpx(LOG).unwrap();
// between the segments (10:02 … 12:00): only near either end
let (g, m) = log.locate(t("2026-05-01T10:04:00Z"), 300.0).unwrap();
assert_eq!((m, g.latitude), (Match::Nearest, 46.0020));
let (g, m) = log.locate(t("2026-05-01T11:58:00Z"), 300.0).unwrap();
assert_eq!((m, g.latitude), (Match::Nearest, 47.0));
assert!(log.locate(t("2026-05-01T11:00:00Z"), 300.0).is_none(), "an hour from any point");
// before the first and after the last point
assert!(log.locate(t("2026-05-01T09:59:00Z"), 300.0).is_some());
assert!(log.locate(t("2026-05-01T09:50:00Z"), 300.0).is_none());
assert!(log.locate(t("2026-05-01T12:10:00Z"), 300.0).is_none());
}
#[test]
fn max_gap_limits_interpolation() {
let log = parse_gpx(LOG).unwrap();
// the points are 60 s apart: with a 20 s limit, only the nearest point within 20 s counts
assert!(log.locate(t("2026-05-01T10:00:30Z"), 20.0).is_none());
let (g, m) = log.locate(t("2026-05-01T10:00:50Z"), 20.0).unwrap();
assert_eq!((m, g.latitude), (Match::Nearest, 46.0010));
}
#[test]
fn gpx_1_0_prefixes_and_zones() {
let s = r#"<gpx:gpx version="1.0" xmlns:gpx="http://www.topografix.com/GPX/1/0"><gpx:trk><gpx:trkseg>
<gpx:trkpt lat="-33.9" lon="151.2"><gpx:time>2026-01-02T10:00:00+11:00</gpx:time></gpx:trkpt>
<gpx:trkpt lat="-33.8" lon="151.3"><gpx:time>2026-01-01T23:01:00</gpx:time></gpx:trkpt>
</gpx:trkseg></gpx:trk></gpx:gpx>"#;
let log = parse_gpx(s).unwrap();
assert_eq!(log.points.len(), 2);
// +11:00 is converted to UTC; no zone = UTC
assert_eq!(log.points[1].time - log.points[0].time, 60.0);
}
fn point_document(lat: &str, lon: &str, ele: &str, time: &str) -> String {
format!(
r#"<gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1"><trk><trkseg><trkpt lat="{lat}" lon="{lon}"><ele>{ele}</ele><time>{time}</time></trkpt></trkseg></trk></gpx>"#
)
}
#[test]
fn character_reference_elevation_is_not_truncated() {
let log = parse_gpx(&point_document("45", "7", "1&#50;3", "2026-01-01T00:00:00Z")).unwrap();
assert_eq!(log.points.first().and_then(|p| p.elevation), Some(123.0));
}
#[test]
fn character_reference_latitude_is_not_dropped() {
let log = parse_gpx(&point_document("4&#53;", "7&#x2E;5", "123", "2026-01-01T00:00:00Z")).unwrap();
let point = log.points.first().copied();
assert_eq!(log.points.len(), 1);
assert_eq!(point.map(|p| (p.latitude, p.longitude)), Some((45.0, 7.5)));
}
#[test]
fn character_reference_time_is_not_shifted() {
let encoded = parse_gpx(&point_document("45", "7", "123", "2026-01-01T00:00:&#51;0Z")).unwrap();
let plain = parse_gpx(&point_document("45", "7", "123", "2026-01-01T00:00:30Z")).unwrap();
assert_eq!(encoded.points.first().map(|p| p.time), plain.points.first().map(|p| p.time));
assert_eq!(encoded.points.first().map(|p| p.time), Some(1_767_225_630.0));
}
#[test]
fn predefined_entities_are_decoded_once_and_cdata_stays_literal() {
let with_predefined_entity = point_document("45", "7", "1&amp;23", "2026-01-01T00:00:00Z");
let log = parse_gpx(&with_predefined_entity).unwrap();
assert_eq!(log.points.first().and_then(|p| p.elevation), None);
let cdata = point_document("45", "7", "<![CDATA[1&#50;3]]>", "2026-01-01T00:00:00Z");
let log = parse_gpx(&cdata).unwrap();
assert_eq!(log.points.first().and_then(|p| p.elevation), None);
}
#[test]
fn unknown_and_malformed_character_references_are_rejected() {
let unknown = point_document("45", "7", "&undeclared;", "2026-01-01T00:00:00Z");
assert!(matches!(parse_gpx(&unknown), Err(GpxError::Xml(_))));
let malformed = point_document("45", "7", "&#xZZ;", "2026-01-01T00:00:00Z");
assert!(matches!(parse_gpx(&malformed), Err(GpxError::Xml(_))));
let unknown_attribute = point_document("4&undeclared;", "7", "123", "2026-01-01T00:00:00Z");
assert!(matches!(parse_gpx(&unknown_attribute), Err(GpxError::Xml(_))));
let malformed_attribute = point_document("&#xZZ;", "7", "123", "2026-01-01T00:00:00Z");
assert!(matches!(parse_gpx(&malformed_attribute), Err(GpxError::Xml(_))));
}
#[test]
fn non_finite_elevation_is_dropped() {
for ele in ["inf", "-inf", "NaN", "infinity"] {
let s = format!(
r#"<gpx><trk><trkseg><trkpt lat="45" lon="7"><ele>{ele}</ele><time>2026-01-01T00:00:00Z</time></trkpt></trkseg></trk></gpx>"#
);
let log = parse_gpx(&s).unwrap();
assert_eq!(log.points.len(), 1, "{ele}");
assert_eq!(log.points[0].elevation, None, "{ele}");
}
}
#[test]
fn interpolation_across_the_antimeridian() {
let a = TrackPoint { time: 0.0, latitude: 0.0, longitude: 179.0, elevation: None, segment: 0 };
let b = TrackPoint { time: 10.0, latitude: 0.0, longitude: -179.0, elevation: None, segment: 0 };
let g = lerp(&a, &b, 0.75);
assert!((g.longitude - -179.5).abs() < 1e-9, "{g:?}");
}
#[test]
fn rejects_multiple_document_roots() {
assert!(matches!(parse_gpx("<gpx/><gpx/>"), Err(GpxError::Xml(_))));
}
#[test]
fn rejects_non_gpx_and_bad_input() {
assert_eq!(parse_gpx("<kml><Document/></kml>"), Err(GpxError::NotGpx));
assert!(parse_gpx("").is_err());
// A partial logger write must not be mistaken for a complete track,
// even if it contains a valid timed point.
let point = r#"<gpx><trk><trkseg><trkpt lat="45" lon="7"><time>2026-01-01T00:00:00Z</time></trkpt></trkseg></trk>"#;
assert!(matches!(parse_gpx(point), Err(GpxError::Xml(_))));
let wrong_close = r#"<gpx><trk><trkseg><trkpt lat="45" lon="7"><time>2026-01-01T00:00:00Z</time></trkpt></trk></trkseg></gpx>"#;
assert!(matches!(parse_gpx(wrong_close), Err(GpxError::Xml(_))));
assert!(
parse_gpx("<gpx><trk><trkseg><trkpt lat=\"x\" lon=\"1\"><time>2026-01-01T00:00:00Z</time></trkpt></trkseg></trk></gpx>")
.unwrap()
.points
.is_empty()
);
let deep = "<gpx>".to_string() + &"<a>".repeat(100);
assert_eq!(parse_gpx(&deep), Err(GpxError::TooComplex));
}
}
+60 -3
View File
@@ -11,8 +11,65 @@
//! packet is a `mime` item whose content type is `application/rdf+xml`. The ICC profile is an item
//! *property*, not an item, and is read by the decoder instead.
use crate::container::Embedded;
use crate::cr3::{MAX_BOXES, be16, be32, be64, boxes};
use crate::Embedded;
const MAX_BOXES: usize = 4096;
#[derive(Clone, Copy)]
struct BoxRef {
kind: [u8; 4],
body: usize,
end: usize,
}
fn be16(b: &[u8], at: usize) -> Option<u16> {
let s = b.get(at..at + 2)?;
Some(u16::from_be_bytes([s[0], s[1]]))
}
fn be32(b: &[u8], at: usize) -> Option<u32> {
let s = b.get(at..at + 4)?;
Some(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
}
fn be64(b: &[u8], at: usize) -> Option<u64> {
let s = b.get(at..at + 8)?;
Some(u64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]))
}
fn boxes(bytes: &[u8], mut at: usize, end: usize, budget: &mut usize) -> Vec<BoxRef> {
let mut out = Vec::new();
let end = end.min(bytes.len());
while at + 8 <= end && *budget > 0 {
*budget -= 1;
let Some(size32) = be32(bytes, at) else { break };
let Some(kind_slice) = bytes.get(at + 4..at + 8) else { break };
let mut kind = [0u8; 4];
kind.copy_from_slice(kind_slice);
let (hdr, box_end) = match size32 {
0 => (8, end),
1 => {
let Some(s64) = be64(bytes, at + 8) else { break };
let Ok(s) = usize::try_from(s64) else { break };
if s < 16 {
break;
}
(16, at.saturating_add(s).min(end))
}
s if s >= 8 => (8, at.saturating_add(s as usize).min(end)),
_ => break,
};
if at + hdr > box_end {
break;
}
out.push(BoxRef { kind, body: at + hdr, end: box_end });
if box_end <= at {
break;
}
at = box_end;
}
out
}
/// Brands that declare a still image in the ISO base media container.
const IMAGE_BRANDS: [&[u8]; 12] = [b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"hevm", b"hevs", b"mif1", b"msf1", b"avif", b"avis"];
@@ -79,7 +136,7 @@ pub fn metadata(bytes: &[u8]) -> Embedded {
/// `iinf` → one `(item_ID, item_type, content_type)` per `infe` entry. Entries of version 0 and 1
/// name no item type and are skipped; HEIF files use version 2 or 3.
fn item_infos(bytes: &[u8], iinf: &crate::cr3::BoxRef, budget: &mut usize) -> Vec<(u32, [u8; 4], String)> {
fn item_infos(bytes: &[u8], iinf: &BoxRef, budget: &mut usize) -> Vec<(u32, [u8; 4], String)> {
// FullBox version and flags, then a 16- or 32-bit entry count before the `infe` boxes
let version = *bytes.get(iinf.body).unwrap_or(&0);
let entries_at = iinf.body.saturating_add(if version == 0 { 6 } else { 8 });
+4 -149
View File
@@ -1,151 +1,6 @@
//! IPTC-IIM (Information Interchange Model 4.2) — the record-2 datasets people still carry in JPEGs.
//!
//! Stream of `0x1C record dataset size(u16 BE, or extended) data` tags. Text is UTF-8 when the record-1
//! `CodedCharacterSet` (1:90) is `ESC % G`, otherwise decoded as UTF-8 when valid and Latin-1 otherwise.
use crate::Metadata;
use crate::convert::from_craft;
use crate::{DateTime, Metadata};
fn decode(b: &[u8], utf8: bool) -> String {
match std::str::from_utf8(b) {
Ok(s) => s.trim_end_matches('\0').trim().to_string(),
Err(_) if utf8 => String::from_utf8_lossy(b).trim_end_matches('\0').trim().to_string(),
Err(_) => b.iter().map(|&c| c as char).collect::<String>().trim_end_matches('\0').trim().to_string(),
}
}
/// Parse an IIM stream into the fields [`Metadata`] carries (title, keywords, artist, copyright, caption,
/// creation date/time).
pub fn parse_iptc(b: &[u8]) -> Metadata {
let mut m = Metadata::default();
let mut utf8 = false;
let mut date: Option<String> = None;
let mut time: Option<String> = None;
let mut seen_keywords = std::collections::HashSet::new();
let mut i = 0usize;
while i + 5 <= b.len() {
if b[i] != 0x1c {
break;
}
let (rec, ds) = (b[i + 1], b[i + 2]);
let mut size = u16::from_be_bytes([b[i + 3], b[i + 4]]) as usize;
let mut at = i + 5;
if size & 0x8000 != 0 {
// extended dataset: next (size & 0x7fff) bytes hold the length
let n = size & 0x7fff;
if n == 0 || n > 4 || at + n > b.len() {
break;
}
size = b[at..at + n].iter().fold(0usize, |a, &c| (a << 8) | c as usize);
at += n;
}
let Some(data) = b.get(at..at.saturating_add(size)) else { break };
match (rec, ds) {
(1, 90) => utf8 = data == b"\x1b%G",
(2, 5) => m.title = Some(decode(data, utf8)).filter(|s| !s.is_empty()),
(2, 25) => {
let k = decode(data, utf8);
if !k.is_empty() && seen_keywords.insert(k.clone()) {
m.keywords.push(k);
}
}
(2, 80) => m.artist = Some(decode(data, utf8)).filter(|s| !s.is_empty()),
(2, 116) => m.copyright = Some(decode(data, utf8)).filter(|s| !s.is_empty()),
(2, 120) => m.caption = Some(decode(data, utf8)).filter(|s| !s.is_empty()),
(2, 55) => date = Some(decode(data, utf8)),
(2, 60) => time = Some(decode(data, utf8)),
_ => {}
}
i = at + size;
}
if let Some(d) = date.filter(|d| d.len() == 8 && d.bytes().all(|c| c.is_ascii_digit())) {
let mut s = format!("{}-{}-{}", &d[..4], &d[4..6], &d[6..8]);
if let Some(t) = time.filter(|t| t.is_ascii() && t.len() >= 6 && t[..6].bytes().all(|c| c.is_ascii_digit())) {
s += &format!("T{}:{}:{}", &t[..2], &t[2..4], &t[4..6]);
if t.len() >= 11 {
s += &format!("{}:{}", &t[6..9], &t[9..11]);
}
}
m.capture_time = DateTime::parse_iso(&s);
}
m
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
fn ds(out: &mut Vec<u8>, rec: u8, ds: u8, data: &[u8]) {
out.extend_from_slice(&[0x1c, rec, ds]);
out.extend_from_slice(&(data.len() as u16).to_be_bytes());
out.extend_from_slice(data);
}
#[test]
fn distinct_keywords_are_kept_once_each_without_rescanning() {
let mut b = Vec::new();
for i in 0..50_000u32 {
ds(&mut b, 2, 25, format!("k{i}").as_bytes());
ds(&mut b, 2, 25, b"same");
}
let m = parse_iptc(&b);
assert_eq!(m.keywords.len(), 50_001);
assert_eq!(m.keywords.iter().filter(|k| *k == "same").count(), 1);
}
pub(crate) fn sample_iim() -> Vec<u8> {
let mut v = Vec::new();
ds(&mut v, 1, 90, b"\x1b%G");
ds(&mut v, 2, 0, &[0, 4]);
ds(&mut v, 2, 5, "Tïtle".as_bytes());
ds(&mut v, 2, 25, b"alpha");
ds(&mut v, 2, 25, b"beta");
ds(&mut v, 2, 25, b"alpha");
ds(&mut v, 2, 80, b"Photographer");
ds(&mut v, 2, 116, b"CC0");
ds(&mut v, 2, 120, b"A caption");
ds(&mut v, 2, 55, b"20210304");
ds(&mut v, 2, 60, b"101112+0100");
v
}
#[test]
fn parses_record2() {
let m = parse_iptc(&sample_iim());
assert_eq!(m.title.as_deref(), Some("Tïtle"));
assert_eq!(m.keywords, vec!["alpha".to_string(), "beta".to_string()]);
assert_eq!(m.artist.as_deref(), Some("Photographer"));
assert_eq!(m.copyright.as_deref(), Some("CC0"));
assert_eq!(m.caption.as_deref(), Some("A caption"));
assert_eq!(m.capture_time.unwrap().to_iso(), "2021-03-04T10:11:12+01:00");
}
#[test]
fn non_utf8_text_drops_trailing_nul() {
let mut v = Vec::new();
ds(&mut v, 2, 5, &[0x43, 0xe9, 0x00]);
ds(&mut v, 2, 25, &[0x6b, 0xe9, 0x00]);
let m = parse_iptc(&v);
assert_eq!(m.title.as_deref(), Some("Cé"));
assert_eq!(m.keywords, vec!["ké".to_string()]);
let mut u = Vec::new();
ds(&mut u, 1, 90, b"\x1b%G");
ds(&mut u, 2, 5, &[0x43, 0xff, 0x00]);
assert_eq!(parse_iptc(&u).title.as_deref(), Some("C\u{fffd}"));
}
#[test]
fn latin1_and_extended_and_garbage() {
let mut v = Vec::new();
ds(&mut v, 2, 5, &[0x43, 0xe9]); // "Cé" in Latin-1
v.extend_from_slice(&[0x1c, 2, 120, 0x80, 0x02, 0x00, 0x03]);
v.extend_from_slice(b"abc");
let m = parse_iptc(&v);
assert_eq!(m.title.as_deref(), Some("Cé"));
assert_eq!(m.caption.as_deref(), Some("abc"));
let s = sample_iim();
for n in 0..s.len() {
let _ = parse_iptc(&s[..n]);
}
assert_eq!(parse_iptc(&[0x1c, 2, 5, 0xff, 0xff]), Metadata::default());
}
pub fn parse_iptc(bytes: &[u8]) -> Metadata {
from_craft(craft_metadata::parse_iptc(bytes))
}
+127 -54
View File
@@ -14,51 +14,69 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod container;
pub mod cr3;
mod datetime;
mod convert;
mod exif;
pub mod focus;
mod focus_read;
mod gpx;
pub mod heif;
mod iptc;
pub mod mrw;
mod psd;
pub mod tags;
mod xmp;
mod xmp_merge;
pub use container::{Embedded, embedded, jpeg_segments, png_chunks, webp_chunks};
pub use datetime::DateTime;
pub use craft_metadata::DateTime;
pub use craft_metadata::cr3;
pub use craft_metadata::{Embedded, jpeg_segments, png_chunks, webp_chunks};
pub use craft_metadata::{Flash, Gps, RegionKind};
pub use craft_metadata::{GpxError, Match, TrackPoint, Tracklog, parse_gpx};
pub use craft_metadata::{TagRow, tag_rows};
/// Collect all EXIF/TIFF tag rows from a file (including PSD/PSB and HEIF containers).
pub fn file_tag_rows(bytes: &[u8]) -> Vec<TagRow> {
if bytes.starts_with(b"8BPS") || heif::is_heif(bytes) {
let Some(exif) = embedded(bytes).exif else { return Vec::new() };
let data = strip_exif_header(&exif);
return craft_tiff::Tiff::parse(data).map(|t| tag_rows(&t)).unwrap_or_default();
}
craft_metadata::file_tag_rows(bytes)
}
/// Sniff the container and collect its metadata blocks. Unknown containers yield an empty result.
pub fn embedded(bytes: &[u8]) -> Embedded {
if bytes.starts_with(b"8BPS") {
return psd::parse(bytes).unwrap_or_default();
}
if heif::is_heif(bytes) {
return heif::metadata(bytes);
}
craft_metadata::embedded(bytes)
}
pub use exif::{from_tiff, read_exif, strip_exif_header, try_read_exif, try_read_exif_with, write_exif};
pub use focus::FocusPoint;
pub use gpx::{GpxError, Match, TrackPoint, Tracklog, parse_gpx};
pub use iptc::parse_iptc;
pub use lightcraft_geom::{Orientation, Rect};
pub use tags::{TagRow, file_tag_rows, tag_rows};
pub use xmp::{CRS_NS, LC_NS, XmpData, XmpError, XmpValue, parse_xmp, write_xmp, write_xmp_lc};
pub use xmp_merge::{MergeRules, merge_xmp};
/// Which properties [`merge_xmp`] takes from the fresh packet.
#[derive(Clone, Copy, Debug, Default)]
pub struct MergeRules<'a> {
/// Always replaced: removed from the existing packet, written from the fresh one if stated.
pub owned: &'a [&'a str],
/// Replaced only when the fresh packet states them; otherwise the existing value stays.
pub owned_if_present: &'a [&'a str],
}
/// Merge `fresh` into `existing` following `rules`.
pub fn merge_xmp(existing: &str, fresh: &str, rules: MergeRules) -> Result<String, XmpError> {
let namespaces = [craft_metadata::XmpNamespace { prefix: "lc", uri: LC_NS }];
craft_metadata::merge_xmp(
existing,
fresh,
craft_metadata::MergeRules { owned: rules.owned, owned_if_present: rules.owned_if_present, namespaces: &namespaces },
)
}
use serde::{Deserialize, Serialize};
/// GPS position (WGS 84). Latitude/longitude in signed decimal degrees (north / east positive).
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Gps {
pub latitude: f64,
pub longitude: f64,
/// Metres above sea level (negative below).
pub altitude: Option<f64>,
}
/// Exif `Flash` value decoded.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Flash {
pub fired: bool,
/// The raw Exif `Flash` bit field.
pub raw: u16,
}
/// A named region of interest on a photo (MWG Region Guidelines, `mwg-rs:Regions`): most often a face,
/// drawn by Lightroom, digiKam, Picasa or similar tools. Read-only for now — LightCraft does not write
/// regions yet (see `docs/xmp-interop.md`).
@@ -73,17 +91,6 @@ pub struct Region {
pub description: Option<String>,
}
/// `mwg-rs:Type`. Unrecognised values are kept verbatim rather than dropped.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum RegionKind {
Face,
Pet,
Focus,
BarCode,
/// `mwg-rs:Type` was missing, empty, or a value we don't recognise.
Other(String),
}
/// Everything LightCraft shows or searches about a photo. All fields are optional; unknown = `None`/empty.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Metadata {
@@ -163,6 +170,29 @@ macro_rules! overlay {
($self:ident, $o:ident, $($f:ident),*) => { $( if $o.$f.is_some() { $self.$f = $o.$f.clone(); } )* };
}
/// How far (relative) a duration may be from an exact `1/n` second and still be shown as `1/n`:
/// absorbs decimal EXIF rationals such as `3333/10000` for 1/3 s without turning 0.3 s or
/// 1/2.8 s into a reciprocal they aren't.
pub const RECIPROCAL_TOLERANCE: f64 = 1e-3;
/// The one shutter-speed formatter for display (catalog `shutter`, Info panel, All Metadata):
/// a near-exact `1/n` second as `1/n` (`1/3`, `1/250`), anything else rounded to four
/// significant digits with trailing zeros dropped (`0.3`, `0.3571`, `2.5`, `30`). Display only:
/// export writes the exact duration. `None` for a time that isn't positive and finite.
pub fn format_exposure_time(t: f64) -> Option<String> {
if !t.is_finite() || t <= 0.0 {
return None;
}
let n = (1.0 / t).round();
if n >= 2.0 && n.is_finite() && (1.0 / (n * t) - 1.0).abs() <= RECIPROCAL_TOLERANCE {
return Some(format!("1/{n}"));
}
// four significant digits; whole seconds never lose digits
let decimals = (3 - t.log10().floor() as i32).max(0) as usize;
let text = format!("{t:.decimals$}");
Some(if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.').to_string() } else { text })
}
impl Metadata {
/// Fill every empty field of `self` from `other`.
pub fn fill_missing(&mut self, other: &Metadata) {
@@ -246,19 +276,10 @@ impl Metadata {
}
}
/// Exposure time formatted like cameras show it: `1/250`, `0.5`, `2″`.
/// Exposure time formatted like cameras show it: `1/250`, `0.3571`, `2.5″` (see [`format_exposure_time`]).
pub fn exposure_display(&self) -> Option<String> {
let t = self.exposure_time?;
if t.is_nan() || t <= 0.0 {
return None;
}
Some(if t < 0.3 {
format!("1/{}", (1.0 / t).round())
} else if t < 1.0 {
format!("{}", (t * 10.0).round() / 10.0)
} else {
format!("{}″", (t * 10.0).round() / 10.0)
})
format_exposure_time(t).map(|text| if t >= 1.0 { format!("{text}″") } else { text })
}
/// Human name of the metering mode.
@@ -304,8 +325,8 @@ pub fn extract(bytes: &[u8]) -> Metadata {
/// Read metadata while reporting malformed PSD/PSB containers, embedded EXIF, or embedded XMP instead of treating
/// them as empty. Other container formats retain [`extract`]'s best-effort behavior.
pub fn try_extract(bytes: &[u8]) -> Result<Metadata, ExtractError> {
let e = container::try_embedded(bytes)?;
let is_psd = bytes.starts_with(b"8BPS");
let e = if is_psd { psd::parse(bytes).ok_or(ExtractError::MalformedPsd)? } else { embedded(bytes) };
let exif = match e.exif.as_deref() {
Some(exif) if is_psd => try_read_exif(exif).map_err(|_| ExtractError::MalformedPsd)?,
Some(exif) => read_exif(exif),
@@ -387,6 +408,7 @@ pub fn lens_spec_name(spec: [f64; 4]) -> Option<String> {
}
/// Lenient number parsing used by XMP/IPTC: `"28/10"`, `"2.8"`, `"+0.7"`.
#[cfg(test)]
pub(crate) fn parse_number(s: &str) -> Option<f64> {
let s = s.trim();
if let Some((n, d)) = s.split_once('/') {
@@ -420,12 +442,58 @@ mod tests {
assert_eq!(parse_number("inf"), None);
}
#[test]
fn exposure_time_formats_reciprocals_and_significant_digits() {
for (t, want) in [
(1.0 / 3.0, "1/3"),
(1.0 / 250.0, "1/250"),
(1.0 / 8000.0, "1/8000"),
(0.5, "1/2"),
(0.3, "0.3"),
(0.4, "0.4"),
(1.0 / 2.8, "0.3571"),
(0.625, "0.625"),
(0.003, "0.003"),
(1.0, "1"),
(1.3, "1.3"),
(2.5, "2.5"),
(30.0, "30"),
(9.99996, "10"),
(1800.0, "1800"),
] {
assert_eq!(format_exposure_time(t).as_deref(), Some(want), "{t}");
}
for t in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert_eq!(format_exposure_time(t), None, "{t}");
}
}
#[test]
fn exposure_time_reciprocal_tolerance() {
// a camera's decimal rational for 1/3 s, and times just inside the tolerance either side
assert_eq!(format_exposure_time(3333.0 / 10000.0).as_deref(), Some("1/3"));
// a microsecond-level rational error still reads as 1/8000; above ~1/1000 s every time is
// within the tolerance of some 1/n, which is how cameras show those speeds anyway
assert_eq!(format_exposure_time(1.0 / 8000.0 * (1.0 + 1e-5)).as_deref(), Some("1/8000"));
for n in [3.0, 10.0, 250.0] {
let inside = 0.9 * RECIPROCAL_TOLERANCE;
let outside = 1.1 * RECIPROCAL_TOLERANCE;
let want = format!("1/{n}");
assert_eq!(format_exposure_time(1.0 / n * (1.0 + inside)).as_deref(), Some(want.as_str()), "{n} +inside");
assert_eq!(format_exposure_time(1.0 / n * (1.0 - inside)).as_deref(), Some(want.as_str()), "{n} -inside");
assert_ne!(format_exposure_time(1.0 / n * (1.0 + outside)).as_deref(), Some(want.as_str()), "{n} +outside");
assert_ne!(format_exposure_time(1.0 / n * (1.0 - outside)).as_deref(), Some(want.as_str()), "{n} -outside");
}
}
#[test]
fn exposure_display() {
let mut m = Metadata { exposure_time: Some(1.0 / 250.0), ..Default::default() };
assert_eq!(m.exposure_display().as_deref(), Some("1/250"));
m.exposure_time = Some(0.5);
assert_eq!(m.exposure_display().as_deref(), Some("0.5"));
assert_eq!(m.exposure_display().as_deref(), Some("1/2"));
m.exposure_time = Some(0.3);
assert_eq!(m.exposure_display().as_deref(), Some("0.3"));
m.exposure_time = Some(2.0);
assert_eq!(m.exposure_display().as_deref(), Some("2″"));
m.exposure_time = Some(0.0);
@@ -555,7 +623,12 @@ mod tests {
j.extend(payload);
};
// orientation 6, 6000 × 4000 as stored
seg([b"Exif\0\0".as_slice(), &crate::exif::tests::sample_exif(craft_tiff::ByteOrder::Little)].concat());
let mut ifd0 = craft_tiff::IfdBuilder::new();
ifd0.set(craft_tiff::tags::IMAGE_WIDTH, craft_tiff::Value::Long(vec![6000]));
ifd0.set(craft_tiff::tags::IMAGE_LENGTH, craft_tiff::Value::Long(vec![4000]));
ifd0.set(craft_tiff::tags::ORIENTATION, craft_tiff::Value::Short(vec![6]));
let sample_exif = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd0]).unwrap();
seg([b"Exif\0\0".as_slice(), &sample_exif].concat());
seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat());
j.extend([0xff, 0xd9]);
j
+10 -63
View File
@@ -1,74 +1,21 @@
//! EXIF and XMP image resources in Photoshop PSD and PSB files.
use crate::container::Embedded;
struct Reader<'a> {
bytes: &'a [u8],
offset: usize,
}
impl<'a> Reader<'a> {
fn take(&mut self, length: usize) -> Option<&'a [u8]> {
let end = self.offset.checked_add(length)?;
let bytes = self.bytes.get(self.offset..end)?;
self.offset = end;
Some(bytes)
}
fn u16(&mut self) -> Option<u16> {
let bytes = self.take(2)?;
Some(u16::from_be_bytes([*bytes.first()?, *bytes.get(1)?]))
}
fn u32(&mut self) -> Option<u32> {
let bytes = self.take(4)?;
Some(u32::from_be_bytes([*bytes.first()?, *bytes.get(1)?, *bytes.get(2)?, *bytes.get(3)?]))
}
}
pub(crate) fn embedded(bytes: &[u8]) -> Embedded {
parse(bytes).unwrap_or_default()
}
use crate::Embedded;
/// The EXIF (1058) and XMP (1060) resources of the head `craft-psd` reads (header, colour mode data, image
/// 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<Embedded> {
let mut reader = Reader { bytes, offset: 0 };
if reader.take(4)? != b"8BPS" || !matches!(reader.u16()?, 1 | 2) {
return None;
}
// The fixed header after the version is reserved bytes, channels, dimensions, depth and colour mode.
reader.take(6 + 2 + 4 + 4 + 2 + 2)?;
let colour_mode_length = usize::try_from(reader.u32()?).ok()?;
reader.take(colour_mode_length)?;
let resource_length = usize::try_from(reader.u32()?).ok()?;
let resources = reader.take(resource_length)?;
parse_resources(resources)
}
fn parse_resources(bytes: &[u8]) -> Option<Embedded> {
let mut reader = Reader { bytes, offset: 0 };
let head = craft_psd::Head::from_bytes(bytes).ok()?;
let (mut exif, mut xmp) = (None, None);
while reader.offset < bytes.len() {
if reader.take(4)? != b"8BIM" {
return None;
}
let id = reader.u16()?;
let name_length = usize::from(*reader.take(1)?.first()?);
let pascal_length = 1usize.checked_add(name_length)?.checked_add(1)? & !1;
reader.take(pascal_length.checked_sub(1)?)?;
let data_length = usize::try_from(reader.u32()?).ok()?;
let data = reader.take(data_length)?;
if !data_length.is_multiple_of(2) {
reader.take(1)?;
}
match id {
for r in &head.resources {
match r.id {
1058 if exif.is_some() => return None,
1058 => exif = Some(data),
1058 => exif = Some(r.data.as_slice()),
1060 if xmp.is_some() => return None,
1060 => xmp = Some(std::str::from_utf8(data).ok()?),
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()),
@@ -78,8 +25,8 @@ fn parse_resources(bytes: &[u8]) -> Option<Embedded> {
#[cfg(test)]
mod tests {
use super::embedded;
use crate::container::Embedded;
use crate::Embedded;
use crate::embedded;
use crate::{DateTime, Gps, Metadata};
fn resource(id: u16, name: &[u8], data: &[u8]) -> Vec<u8> {
-529
View File
@@ -1,529 +0,0 @@
//! Every EXIF / TIFF / GPS tag of a file as readable `(group, name, value)` rows (the Info
//! panel's "All Metadata"). Names follow the public TIFF 6.0 / EXIF 2.3 / DNG specifications;
//! common enumerations are spelled out, everything else is shown as stored. Maker notes and
//! binary blobs are summarised by size; of a maker note only the lens name is listed (the
//! Panasonic one, as Panasonic writes no Exif LensModel).
use craft_tiff::{Ifd, Tiff, Value};
/// One metadata row.
#[derive(Clone, Debug, PartialEq)]
pub struct TagRow {
/// `TIFF`, `EXIF`, `GPS`, `Interop`, or a maker note's (`Panasonic`).
pub group: &'static str,
pub tag: u16,
pub name: String,
pub value: String,
}
const NAMES: &[(u16, &str)] = &[
// TIFF / IFD0
(0x00fe, "Subfile Type"),
(0x0100, "Image Width"),
(0x0101, "Image Height"),
(0x0102, "Bits Per Sample"),
(0x0103, "Compression"),
(0x0106, "Photometric Interpretation"),
(0x010e, "Image Description"),
(0x010f, "Make"),
(0x0110, "Model"),
(0x0112, "Orientation"),
(0x0115, "Samples Per Pixel"),
(0x0116, "Rows Per Strip"),
(0x0214, "Reference Black/White"),
(0x9216, "TIFF/EP Standard ID"),
(0x828d, "CFA Repeat Pattern Dim"),
(0x828e, "CFA Pattern"),
(0xa302, "CFA Pattern"),
(0x9217, "Sensing Method"),
(0xc4a5, "Print Image Matching"),
(0xa500, "Gamma"),
(0x011a, "X Resolution"),
(0x011b, "Y Resolution"),
(0x011c, "Planar Configuration"),
(0x0128, "Resolution Unit"),
(0x0131, "Software"),
(0x0132, "Date/Time Modified"),
(0x013b, "Artist"),
(0x013e, "White Point"),
(0x013f, "Primary Chromaticities"),
(0x0213, "YCbCr Positioning"),
(0x8298, "Copyright"),
(0xc612, "DNG Version"),
(0xc614, "Unique Camera Model"),
(0xc62f, "Camera Serial Number"),
// EXIF
(0x829a, "Exposure Time"),
(0x829d, "F-Number"),
(0x8822, "Exposure Program"),
(0x8824, "Spectral Sensitivity"),
(0x8827, "ISO Speed"),
(0x8830, "Sensitivity Type"),
(0x8832, "Recommended Exposure Index"),
(0x9000, "Exif Version"),
(0x9003, "Date/Time Original"),
(0x9004, "Date/Time Digitized"),
(0x9010, "Offset Time"),
(0x9011, "Offset Time Original"),
(0x9012, "Offset Time Digitized"),
(0x9101, "Components Configuration"),
(0x9102, "Compressed Bits Per Pixel"),
(0x9201, "Shutter Speed Value"),
(0x9202, "Aperture Value"),
(0x9203, "Brightness Value"),
(0x9204, "Exposure Compensation"),
(0x9205, "Max Aperture Value"),
(0x9206, "Subject Distance"),
(0x9207, "Metering Mode"),
(0x9208, "Light Source"),
(0x9209, "Flash"),
(0x920a, "Focal Length"),
(0x9214, "Subject Area"),
(0x927c, "Maker Note"),
(0x9286, "User Comment"),
(0x9290, "Sub-second Time"),
(0x9291, "Sub-second Time Original"),
(0x9292, "Sub-second Time Digitized"),
(0xa000, "FlashPix Version"),
(0xa001, "Color Space"),
(0xa002, "Pixel X Dimension"),
(0xa003, "Pixel Y Dimension"),
(0xa20e, "Focal Plane X Resolution"),
(0xa20f, "Focal Plane Y Resolution"),
(0xa210, "Focal Plane Resolution Unit"),
(0xa215, "Exposure Index"),
(0xa217, "Sensing Method"),
(0xa300, "File Source"),
(0xa301, "Scene Type"),
(0xa401, "Custom Rendered"),
(0xa402, "Exposure Mode"),
(0xa403, "White Balance"),
(0xa404, "Digital Zoom Ratio"),
(0xa405, "Focal Length in 35mm Film"),
(0xa406, "Scene Capture Type"),
(0xa407, "Gain Control"),
(0xa408, "Contrast"),
(0xa409, "Saturation"),
(0xa40a, "Sharpness"),
(0xa40c, "Subject Distance Range"),
(0xa420, "Image Unique ID"),
(0xa430, "Camera Owner Name"),
(0xa431, "Body Serial Number"),
(0xa432, "Lens Specification"),
(0xa433, "Lens Make"),
(0xa434, "Lens Model"),
(0xa435, "Lens Serial Number"),
// GPS
(0x0000, "GPS Version"),
(0x0001, "GPS Latitude Ref"),
(0x0002, "GPS Latitude"),
(0x0003, "GPS Longitude Ref"),
(0x0004, "GPS Longitude"),
(0x0005, "GPS Altitude Ref"),
(0x0006, "GPS Altitude"),
(0x0007, "GPS Time Stamp"),
(0x000c, "GPS Speed Ref"),
(0x000d, "GPS Speed"),
(0x0010, "GPS Img Direction Ref"),
(0x0011, "GPS Img Direction"),
(0x0012, "GPS Map Datum"),
(0x001d, "GPS Date Stamp"),
];
/// GPS tags reuse low numbers, so they are looked up separately.
fn name(group: &str, tag: u16) -> String {
let gps = group == "GPS";
NAMES
.iter()
.find(|(t, n)| *t == tag && (n.starts_with("GPS") == gps || (gps && tag > 0x1f)))
.map(|(_, n)| n.to_string())
.unwrap_or_else(|| format!("Tag 0x{tag:04X}"))
}
fn rational(n: f64, d: f64) -> String {
if d == 0.0 {
return "—".into();
}
let v = n / d;
if (v - v.round()).abs() < 1e-9 {
let r = v.round();
if r == 0.0 { "0".to_string() } else { format!("{}", r) }
} else {
let s = format!("{:.4}", v);
let s = s.trim_end_matches('0').trim_end_matches('.');
if s == "-0" { "0".to_string() } else { s.to_string() }
}
}
fn list<T: ToString>(v: &[T]) -> String {
list_with(v, T::to_string)
}
/// The first 16 values of `v` written by `f`, and how many there are when that's not all of them.
fn list_with<T>(v: &[T], f: impl Fn(&T) -> String) -> String {
let shown: Vec<String> = v.iter().take(16).map(f).collect();
if v.len() > 16 { format!("{} … ({} values)", shown.join(", "), v.len()) } else { shown.join(", ") }
}
/// Spelled-out enumerations for the commonest tags.
fn enumerated(group: &str, tag: u16, v: i64) -> Option<&'static str> {
if group == "GPS" {
return None;
}
Some(match (tag, v) {
(0x0112, 1) => "Horizontal (normal)",
(0x0112, 3) => "Rotated 180°",
(0x0112, 6) => "Rotated 90° CW",
(0x0112, 8) => "Rotated 90° CCW",
(0x0112, 2) => "Mirrored horizontally",
(0x0112, 4) => "Mirrored vertically",
(0x0103, 1) => "Uncompressed",
(0x0103, 6) => "JPEG (old-style)",
(0x0103, 7) => "JPEG",
(0x0103, 8) => "Deflate",
(0x0103, 32773) => "PackBits",
(0x0103, 34892) => "Lossy JPEG",
(0x0103, 34713) => "Nikon NEF Compressed",
(0x0103, 32767) => "Sony ARW Compressed",
(0x0103, 52546) => "JPEG XL",
(0x0106, 0) => "WhiteIsZero",
(0x0106, 1) => "BlackIsZero",
(0x0106, 2) => "RGB",
(0x0106, 6) => "YCbCr",
(0x0106, 32803) => "Color Filter Array",
(0x0106, 34892) => "Linear Raw",
(0x011c, 1) => "Chunky",
(0x011c, 2) => "Planar",
(0x0128, 2) => "inches",
(0x0128, 3) => "centimetres",
(0x8822, 1) => "Manual",
(0x8822, 2) => "Program",
(0x8822, 3) => "Aperture priority",
(0x8822, 4) => "Shutter priority",
(0x9207, 2) => "Center-weighted average",
(0x9207, 3) => "Spot",
(0x9207, 5) => "Pattern",
(0xa001, 1) => "sRGB",
(0xa001, 0xffff) => "Uncalibrated",
(0xa402, 0) => "Auto",
(0xa402, 1) => "Manual",
(0xa402, 2) => "Auto bracket",
(0xa403, 0) => "Auto",
(0xa403, 1) => "Manual",
(0xa406, 0) => "Standard",
(0xa406, 1) => "Landscape",
(0xa406, 2) => "Portrait",
(0xa406, 3) => "Night",
(0x9209, 0) => "No flash",
(0x9209, 1) => "Fired",
(0x9209, 5) => "Fired, return not detected",
(0x9209, 7) => "Fired, return detected",
(0x9209, 9) => "On, fired",
(0x9209, 16) => "Off, did not fire",
(0x9209, 24) => "Auto, did not fire",
(0x9209, 25) => "Auto, fired",
(0x9209, 32) => "No flash function",
(0x9208, 0) => "Unknown",
(0x9208, 1) => "Daylight",
(0x9208, 2) => "Fluorescent",
(0x9208, 3) => "Tungsten",
(0x9208, 4) => "Flash",
_ => return None,
})
}
fn value_text(group: &str, tag: u16, v: &Value) -> String {
let single = |x: i64| enumerated(group, tag, x).map(str::to_string).unwrap_or_else(|| x.to_string());
match v {
Value::Ascii(s) => s.trim().to_string(),
Value::Short(a) if a.len() == 1 => single(a[0] as i64),
Value::Long(a) if a.len() == 1 => single(a[0] as i64),
Value::Short(a) => list(a),
Value::Long(a) => list(a),
Value::SShort(a) => list(a),
Value::SLong(a) => list(a),
Value::Long8(a) => list(a),
Value::SLong8(a) => list(a),
Value::Float(a) => list(a),
Value::Double(a) => list(a),
Value::Rational(a) if tag == 0x829a && group != "GPS" && a.len() == 1 && a[0].1 != 0 => {
// exposure time as a fraction of a second
let (n, d) = a[0];
let s = n as f64 / d as f64;
if s >= 1.0 || n == 0 { format!("{} s", rational(n as f64, d as f64)) } else { format!("1/{} s", (1.0 / s).round()) }
}
Value::Rational(a) if tag == 0x829d && group != "GPS" && a.len() == 1 => format!("f/{}", rational(a[0].0 as f64, a[0].1 as f64)),
Value::Rational(a) if tag == 0x920a && group != "GPS" && a.len() == 1 => format!("{} mm", rational(a[0].0 as f64, a[0].1 as f64)),
Value::Rational(a) => list_with(a, |(n, d)| rational(*n as f64, *d as f64)),
Value::SRational(a) => list_with(a, |(n, d)| rational(*n as f64, *d as f64)),
Value::Byte(b) | Value::Undefined(b) => {
// version tags and short printable values read as text
let printable = b.len() <= 64 && b.iter().all(|c| c.is_ascii_graphic() || *c == b' ' || *c == 0);
if printable && !b.is_empty() {
String::from_utf8_lossy(b).trim_end_matches('\0').trim().to_string()
} else if b.len() <= 8 {
list(b)
} else {
format!("({} bytes)", b.len())
}
}
Value::SByte(a) => list(a),
Value::Ifd(a) => format!("(IFD at {})", list(a)),
Value::Ifd8(a) => format!("(IFD at {})", list(a)),
}
}
fn rows_of(group: &'static str, ifd: &Ifd, out: &mut Vec<TagRow>) {
for e in &ifd.entries {
// pointers to other IFDs and image data are structure, not metadata
if matches!(e.tag, 0x8769 | 0x8825 | 0xa005 | 0x014a | 0x0111 | 0x0117 | 0x0144 | 0x0145 | 0x0201 | 0x0202 | 0x02bc | 0x83bb | 0x8773)
&& group != "GPS"
{
continue;
}
out.push(TagRow { group, tag: e.tag, name: name(group, e.tag), value: value_text(group, e.tag, &e.value) });
}
}
/// The IFD holding a raw file's sensor data when it is not IFD0 (a colour-filter-array or linear-raw
/// image in a sub-IFD). IFD0 of such files describes a thumbnail, so its Compression is not the raw's.
fn raw_image_ifd(ifd0: &Ifd) -> Option<&Ifd> {
ifd0.sub_ifds.iter().find(|s| matches!(s.u32(0x0106), Some(32803 | 34892)))
}
/// Nikon maker note `NEFCompression` (0x0093) spelled out, per the public Nikon tag documentation.
fn nef_compression(v: u32) -> Option<&'static str> {
Some(match v {
1 => "Lossy (type 1)",
2 => "Uncompressed",
3 => "Lossless",
4 => "Lossy (type 2)",
5 => "Striped packed 12 bits",
6 => "Uncompressed (reduced to 12 bit)",
7 => "Unpacked 12 bits",
8 => "Small",
9 => "Packed 12 bits",
10 => "Packed 14 bits",
13 => "High Efficiency",
14 => "High Efficiency*",
_ => return None,
})
}
/// Nikon maker note NEFCompression of a raw file, spelled out; `None` for other files or values.
fn nikon_nef_compression(tiff: &Tiff, bytes: &[u8]) -> Option<&'static str> {
let ifd0 = tiff.ifds.first()?;
let make = ifd0.string(0x010f)?;
if !make.to_ascii_uppercase().starts_with("NIKON") {
return None;
}
let e = ifd0.exif.as_ref()?.get(0x927c)?;
let mn = craft_tiff::makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)?;
nef_compression(mn.ifd.u32(0x0093)?)
}
/// The Panasonic maker note's lens name (LensType, `0x0051`) as a row, the name `photo.inspect` shows as the lens.
fn panasonic_lens_row(data: &[u8], tiff: &Tiff, out: &mut Vec<TagRow>) {
if let Some(lens) = crate::exif::panasonic_maker_note_lens(data, tiff) {
out.push(TagRow { group: "Panasonic", tag: 0x0051, name: "Lens Type".into(), value: lens.trim().to_string() });
}
}
/// Every tag of a parsed TIFF structure (a TIFF-based raw, a TIFF, or an EXIF block): IFD0,
/// then the EXIF, GPS and interoperability IFDs. A raw file's Compression row is the sensor
/// image's, not IFD0's thumbnail's.
pub fn tag_rows(tiff: &Tiff) -> Vec<TagRow> {
let mut out = Vec::new();
if let Some(ifd0) = tiff.ifds.first() {
rows_of("TIFF", ifd0, &mut out);
if let Some(c) = raw_image_ifd(ifd0).and_then(|r| r.value(0x0103))
&& let Some(row) = out.iter_mut().find(|r| r.tag == 0x0103)
{
// lossless JPEG (DNG, CR2) on the sensor image; plain "JPEG" would read as lossy
row.value = if c.get_u64(0) == Some(7) { "Lossless JPEG".to_string() } else { value_text("TIFF", 0x0103, c) };
}
if let Some(e) = &ifd0.exif {
rows_of("EXIF", e, &mut out);
if let Some(i) = &e.interop {
rows_of("Interop", i, &mut out);
}
}
if let Some(g) = &ifd0.gps {
rows_of("GPS", g, &mut out);
}
}
out
}
/// [`tag_rows`] of a file's bytes: a TIFF-based file directly, else its embedded EXIF block
/// (JPEG, PNG, WebP, HEIF, PSD/PSB…). Empty when there is none.
pub fn file_tag_rows(bytes: &[u8]) -> Vec<TagRow> {
if Tiff::sniff(bytes).is_some()
&& let Ok(t) = Tiff::parse(bytes)
{
let mut rows = tag_rows(&t);
if let Some(words) = nikon_nef_compression(&t, bytes)
&& let Some(row) = rows.iter_mut().find(|r| r.group == "TIFF" && r.tag == 0x0103)
{
row.value = words.to_string();
}
panasonic_lens_row(bytes, &t, &mut rows);
return rows;
}
let Some(exif) = crate::embedded(bytes).exif else { return Vec::new() };
let data = crate::strip_exif_header(&exif);
let Ok(t) = Tiff::parse(data) else { return Vec::new() };
let mut rows = tag_rows(&t);
panasonic_lens_row(data, &t, &mut rows);
rows
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rational_has_no_trailing_dot() {
assert_eq!(rational(1.0, 100000.0), "0");
assert_eq!(rational(-1.0, 100000.0), "0");
assert_eq!(rational(-1.0, 1e10), "0");
assert_eq!(rational(1000001.0, 100000.0), "10");
assert_eq!(rational(1.0, 3.0), "0.3333");
assert_eq!(rational(5.0, 2.0), "2.5");
}
/// Rational lists were joined whole, unlike every other list (#2579): a tag of millions of
/// fractions became a string as long in the tag panel.
#[test]
fn rational_lists_show_sixteen_values_like_other_lists() {
let first16 = (1..=16).map(|i| i.to_string()).collect::<Vec<_>>().join(", ");
let many: Vec<(u32, u32)> = (1..=1000).map(|i| (i, 1)).collect();
assert_eq!(value_text("EXIF", 0x9999, &Value::Rational(many)), format!("{first16} … (1000 values)"));
let signed: Vec<(i32, i32)> = (1..=1000).map(|i| (-i, 1)).collect();
assert!(value_text("EXIF", 0x9999, &Value::SRational(signed)).ends_with("-16 … (1000 values)"));
assert_eq!(value_text("EXIF", 0x9999, &Value::Rational(vec![(1, 2), (3, 4)])), "0.5, 0.75");
}
#[test]
fn rows_from_written_exif() {
let m = crate::Metadata {
make: Some("Maker".into()),
model: Some("Model X".into()),
exposure_time: Some(1.0 / 250.0),
f_number: Some(2.8),
iso: Some(400),
focal_length: Some(35.0),
gps: Some(crate::Gps { latitude: 51.5, longitude: -0.12, altitude: Some(20.0) }),
..Default::default()
};
let exif = crate::write_exif(&m);
let t = Tiff::parse(crate::strip_exif_header(&exif)).unwrap();
let rows = tag_rows(&t);
let get = |n: &str| rows.iter().find(|r| r.name == n).map(|r| r.value.clone());
assert_eq!(get("Make").as_deref(), Some("Maker"));
assert_eq!(get("Exposure Time").as_deref(), Some("1/250 s"));
assert_eq!(get("F-Number").as_deref(), Some("f/2.8"));
assert_eq!(get("Focal Length").as_deref(), Some("35 mm"));
assert_eq!(get("ISO Speed").as_deref(), Some("400"));
assert!(rows.iter().any(|r| r.group == "GPS" && r.name == "GPS Latitude"), "{rows:?}");
assert!(!rows.iter().any(|r| r.tag == 0x8769), "IFD pointers are left out");
}
fn entry(tag: u16, ty: u16, count: u32, val: u32) -> Vec<u8> {
let mut e = Vec::new();
e.extend(tag.to_le_bytes());
e.extend(ty.to_le_bytes());
e.extend(count.to_le_bytes());
e.extend(val.to_le_bytes());
e
}
fn ifd(entries: &[Vec<u8>]) -> Vec<u8> {
let mut b = (entries.len() as u16).to_le_bytes().to_vec();
entries.iter().for_each(|e| b.extend(e));
b.extend(0u32.to_le_bytes());
b
}
/// A little-endian raw with a thumbnail IFD0 (`Compression` 1), a CFA sub-IFD (`Compression`
/// 34713) and, when `nef` is set, a Nikon maker note whose NEFCompression is that value.
fn synthetic_raw(nef: Option<u16>) -> Vec<u8> {
let make = b"NIKON CORPORATION";
let mut note = b"NikonII*".to_vec();
note.extend(ifd(&[entry(0x0093, 3, 1, nef.unwrap_or(0) as u32)]));
let ifd0_len = 2 + 4 * 12 + 4;
let sub_at = 8 + ifd0_len;
let sub = ifd(&[entry(0x0103, 3, 1, 34713), entry(0x0106, 3, 1, 32803)]);
let exif_at = sub_at + sub.len();
let exif_len = 2 + 12 + 4;
let make_at = exif_at + exif_len;
let note_at = make_at + make.len();
let mut b = b"II*".to_vec();
b.extend(ifd(&[
entry(0x0103, 3, 1, 1),
entry(0x010f, 2, make.len() as u32, make_at as u32),
entry(0x014a, 4, 1, sub_at as u32),
entry(0x8769, 4, 1, exif_at as u32),
]));
b.extend(sub);
b.extend(ifd(&[entry(0x927c, 7, note.len() as u32, if nef.is_some() { note_at as u32 } else { 0 })]));
b.extend(make);
b.extend(note);
b
}
fn compression(rows: &[TagRow]) -> Vec<&str> {
rows.iter().filter(|r| r.group == "TIFF" && r.tag == 0x0103).map(|r| r.value.as_str()).collect()
}
#[test]
fn raw_compression_is_the_sensor_images_not_the_thumbnails() {
let b = synthetic_raw(None);
assert_eq!(compression(&file_tag_rows(&b)), ["Nikon NEF Compressed"]);
}
#[test]
fn nef_compression_is_spelled_out_from_the_maker_note() {
for (v, words) in [(3, "Lossless"), (10, "Packed 14 bits"), (2, "Uncompressed"), (14, "High Efficiency*")] {
let b = synthetic_raw(Some(v));
assert_eq!(compression(&file_tag_rows(&b)), [words]);
}
}
#[test]
fn dng_raw_sub_ifd_jpeg_is_lossless_but_a_plain_jpeg_tiff_is_not() {
let b = synthetic_raw(None);
// switch the sensor sub-IFD's Compression from 34713 to 7
let pos = b.windows(12).position(|w| w == entry(0x0103, 3, 1, 34713).as_slice()).unwrap();
let mut dng = b.clone();
dng[pos + 8] = 7;
dng[pos + 9] = 0;
assert_eq!(compression(&file_tag_rows(&dng)), ["Lossless JPEG"]);
let plain = [b"II*".to_vec(), ifd(&[entry(0x0103, 3, 1, 7)])].concat();
assert_eq!(compression(&file_tag_rows(&plain)), ["JPEG"]);
}
#[test]
fn plain_tiff_keeps_its_own_compression() {
let b = [b"II*".to_vec(), ifd(&[entry(0x0103, 3, 1, 8)])].concat();
assert_eq!(compression(&file_tag_rows(&b)), ["Deflate"]);
}
#[test]
fn panasonic_lens_is_listed_from_the_maker_note() {
let lens = |rows: &[TagRow]| rows.iter().filter(|r| r.group == "Panasonic" && r.tag == 0x0051).map(|r| r.value.clone()).collect::<Vec<_>>();
// a RW2: the note is only in the JpgFromRaw's Exif
let rw2 = crate::exif::tests::panasonic_rw2("LUMIX S 85/F1.8");
assert_eq!(lens(&file_tag_rows(&rw2)), ["LUMIX S 85/F1.8"]);
// a JPEG: the note is in its own Exif
let exif = crate::exif::tests::panasonic_exif(craft_tiff::ByteOrder::Big, Some("LUMIX G 25/F1.7"), None);
let mut jpg = vec![0xff, 0xd8, 0xff, 0xe1];
jpg.extend_from_slice(&((exif.len() + 8) as u16).to_be_bytes());
jpg.extend(b"Exif\0\0");
jpg.extend(exif);
jpg.extend_from_slice(&[0xff, 0xda, 0, 2, 0xff, 0xd9]);
assert_eq!(lens(&file_tag_rows(&jpg)), ["LUMIX G 25/F1.7"]);
// no Panasonic note, no row
assert!(lens(&file_tag_rows(&synthetic_raw(Some(3)))).is_empty());
}
}
+17 -759
View File
@@ -1,66 +1,14 @@
//! XMP packets (ISO 16684-1 / Adobe XMP Specification Part 1–2): read and write.
//!
//! Reading builds a small namespace-resolved tree with `quick-xml`, then collects every property of every
//! `rdf:Description` (attribute form, element form, `rdf:Seq`/`rdf:Bag`/`rdf:Alt` arrays, `rdf:parseType="Resource"`
//! and nested-description structs, flattened as `parent/field`). Prefixes are canonicalised by namespace URI, so
//! a packet that binds `http://purl.org/dc/elements/1.1/` to `foo:` still yields `dc:title`.
//!
//! Writing emits the interchange subset in standard namespaces (dc, xmp, photoshop, exif, exifEX, tiff, lr) and
//! LightCraft's full develop settings as an opaque JSON string in `lc:settings`.
//! XMP packets (ISO 16684-1 / Adobe XMP Specification Part 1–2): read and write via `craft-metadata`.
use crate::{DateTime, Flash, Gps, Metadata, Orientation, Region, RegionKind, parse_number};
use lightcraft_geom::{Point, Rect};
use quick_xml::escape::{escape, partial_escape};
use quick_xml::events::Event;
use crate::Metadata;
use crate::convert::{to_craft, xmp_from_craft};
pub use craft_metadata::{CRS_NS, XmpError, XmpNamespace, XmpValue, XmpWrite, parse_xmp_with, write_xmp_with};
use std::collections::BTreeMap;
/// LightCraft's XMP namespace URI (prefix `lc`).
pub const LC_NS: &str = "http://ns.lightcraft.app/lc/1.0/";
const NAMESPACES: &[(&str, &str)] = &[
("x", "adobe:ns:meta/"),
("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
("dc", "http://purl.org/dc/elements/1.1/"),
("xmp", "http://ns.adobe.com/xap/1.0/"),
("xmpRights", "http://ns.adobe.com/xap/1.0/rights/"),
("photoshop", "http://ns.adobe.com/photoshop/1.0/"),
("exif", "http://ns.adobe.com/exif/1.0/"),
("exifEX", "http://cipa.jp/exif/1.0/"),
("tiff", "http://ns.adobe.com/tiff/1.0/"),
("aux", "http://ns.adobe.com/exif/1.0/aux/"),
("lr", "http://ns.adobe.com/lightroom/1.0/"),
("Iptc4xmpCore", "http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/"),
("lc", LC_NS),
// Read-only: develop settings written by other raw developers (interchange; see docs/xmp-interop.md).
("crs", CRS_NS),
// Read-only: face/pet/focus regions written by Lightroom, digiKam, Picasa and others (MWG Region
// Guidelines v2.0). Canonicalising these three lets a packet use any prefix for them.
("mwg-rs", "http://www.metadataworkinggroup.com/schemas/regions/"),
("stArea", "http://ns.adobe.com/xmp/sType/Area#"),
("stDim", "http://ns.adobe.com/xap/1.0/sType/Dimensions#"),
];
/// The camera-raw-settings namespace URI (prefix `crs`), read for interchange only.
pub const CRS_NS: &str = "http://ns.adobe.com/camera-raw-settings/1.0/";
/// XMP read failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum XmpError {
Xml(String),
/// Nesting / size limits exceeded.
TooComplex,
}
impl std::fmt::Display for XmpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
XmpError::Xml(e) => write!(f, "XMP is not well-formed XML: {e}"),
XmpError::TooComplex => write!(f, "XMP packet too deeply nested or too large"),
}
}
}
impl std::error::Error for XmpError {}
const LC_NAMESPACES: &[XmpNamespace<'static>] = &[XmpNamespace { prefix: "lc", uri: LC_NS }];
/// Result of [`parse_xmp`].
#[derive(Clone, Debug, Default, PartialEq)]
@@ -68,19 +16,15 @@ pub struct XmpData {
pub metadata: Metadata,
/// The opaque `lc:settings` JSON string, if present.
pub lc_settings: Option<String>,
/// Every property found, keyed `prefix:name` (struct fields as `prefix:name/prefix:field`); arrays keep
/// item order, language alternatives put `x-default` first. Foreign namespaces that reuse a recognized
/// prefix use `Q{hex-encoded namespace URI}local` instead, so they cannot impersonate known properties.
/// Every property found, keyed `prefix:name`.
pub properties: BTreeMap<String, Vec<String>>,
/// Every top-level property with its full structure (arrays of structs such as local
/// corrections, which [`XmpData::properties`] flattens).
/// Every top-level property with its full structure.
pub values: BTreeMap<String, XmpValue>,
}
impl XmpData {
/// The pixel size the packet's regions were drawn on (`mwg-rs:AppliedToDimensions`), unless one of them says how
/// the photo was turned (`mwg-rs:Rotation`: Lightroom's boxes, which the reader already turns upright). It tells
/// boxes drawn on the photo as stored from boxes drawn on it upright: see [`crate::upright_regions`].
/// the photo was turned (`mwg-rs:Rotation`).
pub fn regions_drawn_on(&self) -> Option<(f64, f64)> {
let regions = self.values.get("mwg-rs:Regions")?;
let turned = regions.field("mwg-rs:RegionList").is_some_and(|l| l.items().iter().any(|r| r.field("mwg-rs:Rotation").is_some()));
@@ -88,709 +32,23 @@ impl XmpData {
}
}
/// A structured XMP value.
#[derive(Clone, Debug, PartialEq)]
pub enum XmpValue {
Text(String),
Array(Vec<XmpValue>),
Struct(BTreeMap<String, XmpValue>),
}
impl XmpValue {
/// A struct field (`prefix:name`).
pub fn field(&self, k: &str) -> Option<&XmpValue> {
match self {
XmpValue::Struct(m) => m.get(k),
_ => None,
}
}
pub fn text(&self) -> Option<&str> {
match self {
XmpValue::Text(s) => Some(s.trim()),
XmpValue::Array(a) => a.first().and_then(XmpValue::text),
XmpValue::Struct(_) => None,
}
}
/// Array items (a lone value is a one-item array).
pub fn items(&self) -> &[XmpValue] {
match self {
XmpValue::Array(a) => a,
other => std::slice::from_ref(other),
}
}
}
fn node_struct(n: &Node) -> XmpValue {
let mut m = BTreeMap::new();
for (k, v) in &n.attrs {
if !is_rdf_meta_attr(k) {
m.insert(k.clone(), XmpValue::Text(v.clone()));
}
}
for c in &n.children {
m.insert(c.name.clone(), node_value(c));
}
XmpValue::Struct(m)
}
fn node_value(n: &Node) -> XmpValue {
if let Some(arr) = n.children.iter().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt")) {
return XmpValue::Array(arr.children.iter().filter(|li| li.name == "rdf:li").map(node_value).collect());
}
if let Some(d) = n.children.iter().find(|c| c.name == "rdf:Description") {
return node_struct(d);
}
if !n.children.is_empty() || n.attrs.iter().any(|(k, _)| !is_rdf_meta_attr(k)) {
return node_struct(n);
}
XmpValue::Text(n.attr("rdf:resource").map(str::to_string).unwrap_or_else(|| n.text.trim().to_string()))
}
#[derive(Debug, Default)]
struct Node {
name: String,
attrs: Vec<(String, String)>,
children: Vec<Node>,
text: String,
}
impl Node {
fn attr(&self, n: &str) -> Option<&str> {
self.attrs.iter().find(|(k, _)| k == n).map(|(_, v)| v.as_str())
}
}
const MAX_DEPTH: usize = 64;
const MAX_NODES: usize = 200_000;
// Expanding a long namespace URI on many short names must not amplify a small packet without bound.
pub(crate) const MAX_OPAQUE_NAME_BYTES: usize = 8 * 1024 * 1024;
/// Most text a converter's flattened property keys may add up to. Keys repeat their whole ancestor
/// path (`parent/field`), so a document with a long nested name and a wide child fan-out otherwise
/// retains its prefix once per property: node limits alone cannot bound that duplication.
const MAX_KEY_BYTES: usize = 1 << 20;
/// Most namespace declarations in scope at once. Prefix lookup scans them, so declarations times the names of a
/// start tag is the work; real packets declare a few dozen.
const MAX_NS_DECLS: usize = 512;
/// Refuses a scope stack holding more than [`MAX_NS_DECLS`] declarations (one count per start tag over a stack at most [`MAX_DEPTH`] deep).
pub(crate) fn check_scopes(scopes: &[Vec<(String, String)>]) -> Result<(), XmpError> {
if scopes.iter().map(Vec::len).sum::<usize>() > MAX_NS_DECLS {
return Err(XmpError::TooComplex);
}
Ok(())
}
/// Names canonicalised by namespace URI (see [`NAMESPACES`]); conflicting foreign prefixes are opaque.
pub(crate) fn canonical_name(qname: &str, scopes: &[Vec<(String, String)>], opaque_budget: &mut usize) -> Result<String, XmpError> {
canonical(qname, scopes, opaque_budget)
}
fn canonical(qname: &str, scopes: &[Vec<(String, String)>], opaque_budget: &mut usize) -> Result<String, XmpError> {
let (prefix, local) = qname.split_once(':').unwrap_or(("", qname));
if prefix == "xml" || prefix == "xmlns" {
return Ok(qname.to_string());
}
let uri = scopes.iter().rev().flat_map(|s| s.iter().rev()).find(|(p, _)| p == prefix).map(|(_, u)| u.as_str());
Ok(match uri {
Some(u) => match NAMESPACES.iter().find(|(_, nu)| *nu == u) {
Some((p, _)) => format!("{p}:{local}"),
None if NAMESPACES.iter().any(|(p, _)| *p == prefix) => {
// A foreign `lc:settings` must never match our `lc:*` ownership rule (nor may a
// foreign `xmp:Rating` become a rating). Braces cannot occur in an XML QName;
// hex keeps URI slashes out of the flattened property's `/` path separators.
let size =
u.len().checked_mul(2).and_then(|n| n.checked_add(3)).and_then(|n| n.checked_add(local.len())).ok_or(XmpError::TooComplex)?;
*opaque_budget = opaque_budget.checked_sub(size).ok_or(XmpError::TooComplex)?;
let mut key = String::with_capacity(size);
key.push_str("Q{");
for byte in u.bytes() {
for nibble in [byte >> 4, byte & 15] {
key.push(char::from(if nibble < 10 { b'0' + nibble } else { b'a' + (nibble - 10) }));
}
}
key.push('}');
key.push_str(local);
key
}
None if prefix.is_empty() => local.to_string(),
None => qname.to_string(),
},
None => qname.to_string(),
})
}
fn entity(name: &str) -> Option<char> {
Some(match name {
"lt" => '<',
"gt" => '>',
"amp" => '&',
"quot" => '"',
"apos" => '\'',
_ => {
let n = name.strip_prefix('#')?;
let v = match n.strip_prefix(['x', 'X']) {
Some(h) if h.bytes().all(|b| b.is_ascii_hexdigit()) => u32::from_str_radix(h, 16).ok()?,
Some(_) => return None,
None if n.bytes().all(|b| b.is_ascii_digit()) => n.parse().ok()?,
None => return None,
};
char::from_u32(v).filter(|&c| is_xml_char(c))?
}
})
}
/// The XML 1.0 `Char` production (the surrogate range can't occur in a `char`).
fn is_xml_char(c: char) -> bool {
matches!(c, '\t' | '\n' | '\r') || (c >= '\u{20}' && c != '\u{FFFE}' && c != '\u{FFFF}')
}
/// Drop the characters XML 1.0 forbids, which strict parsers (Adobe XMP Toolkit, expat, libxml2) reject the
/// whole document for.
fn xml_safe(s: &str) -> String {
s.chars().filter(|&c| is_xml_char(c)).collect()
}
/// Index of the `;` that ends a reference starting at `rest` (its `&`). The scan stops at the first
/// byte that cannot appear in a name or a numeric reference, so zero-padded references such as
/// `&#000000097;` are found and each run of name bytes is read once, not once per `&`.
fn entity_end(rest: &str) -> Option<usize> {
let n = rest.bytes().skip(1).take_while(|b| b.is_ascii_alphanumeric() || *b == b'#').count();
(rest.as_bytes().get(n + 1) == Some(&b';')).then_some(n + 1)
}
pub(crate) fn unescape_attr(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(i) = rest.find('&') {
out.push_str(&rest[..i]);
rest = &rest[i..];
match entity_end(rest).and_then(|j| entity(&rest[1..j]).map(|c| (c, j))) {
Some((c, j)) => {
out.push(c);
rest = &rest[j + 1..];
}
None => {
out.push('&');
rest = &rest[1..];
}
}
}
out.push_str(rest);
out
}
fn parse_tree(s: &str) -> Result<Node, XmpError> {
let mut reader = quick_xml::Reader::from_str(s);
reader.config_mut().check_end_names = false;
let mut stack: Vec<Node> = vec![Node { name: "#root".into(), ..Default::default() }];
let mut scopes: Vec<Vec<(String, String)>> = vec![vec![("xml".into(), "http://www.w3.org/XML/1998/namespace".into())]];
let mut count = 0usize;
let mut opaque_budget = MAX_OPAQUE_NAME_BYTES;
loop {
let ev = reader.read_event().map_err(|e| XmpError::Xml(e.to_string()))?;
match ev {
Event::Start(ref e) | Event::Empty(ref e) => {
count += 1;
if count > MAX_NODES || stack.len() > MAX_DEPTH {
return Err(XmpError::TooComplex);
}
let mut scope = Vec::new();
let mut raw_attrs = Vec::new();
for a in e.attributes().with_checks(false).flatten() {
let k = String::from_utf8_lossy(a.key.as_ref()).into_owned();
let v = unescape_attr(&String::from_utf8_lossy(&a.value));
if k == "xmlns" {
scope.push((String::new(), v));
} else if let Some(p) = k.strip_prefix("xmlns:") {
scope.push((p.to_string(), v));
} else {
raw_attrs.push((k, v));
}
}
scopes.push(scope);
check_scopes(&scopes)?;
let name = canonical(&String::from_utf8_lossy(e.name().as_ref()), &scopes, &mut opaque_budget)?;
let attrs =
raw_attrs.into_iter().map(|(k, v)| Ok((canonical(&k, &scopes, &mut opaque_budget)?, v))).collect::<Result<_, XmpError>>()?;
let node = Node { name, attrs, ..Default::default() };
if matches!(ev, Event::Empty(_)) {
scopes.pop();
if let Some(parent) = stack.last_mut() {
parent.children.push(node);
}
} else {
stack.push(node);
}
}
Event::End(_) if stack.len() > 1 => {
let Some(n) = stack.pop() else { return Err(XmpError::Xml("end tag without an open element".into())) };
scopes.pop();
if let Some(parent) = stack.last_mut() {
parent.children.push(n);
}
}
Event::Text(t) => {
if let Some(top) = stack.last_mut() {
top.text.push_str(&t.decode().map_err(|e| XmpError::Xml(e.to_string()))?);
}
}
Event::CData(t) => {
if let Some(top) = stack.last_mut() {
top.text.push_str(&String::from_utf8_lossy(&t));
}
}
Event::GeneralRef(r) => {
let name = String::from_utf8_lossy(&r).into_owned();
if let Some(top) = stack.last_mut() {
match entity(&name) {
Some(c) => top.text.push(c),
None => {
top.text.push('&');
top.text.push_str(&name);
top.text.push(';');
}
}
}
}
Event::Eof => break,
_ => {}
}
}
// close unterminated elements leniently
while stack.len() > 1 {
let Some(n) = stack.pop() else { return Err(XmpError::Xml("unterminated element without a node".into())) };
let Some(parent) = stack.last_mut() else { return Err(XmpError::Xml("unterminated element without a parent".into())) };
parent.children.push(n);
}
stack.pop().ok_or_else(|| XmpError::Xml("xmp packet without a root element".into()))
}
fn is_rdf_meta_attr(k: &str) -> bool {
matches!(k, "rdf:about" | "rdf:ID" | "rdf:nodeID" | "xml:lang" | "rdf:parseType" | "rdf:resource" | "rdf:datatype") || k.starts_with("xmlns")
}
fn collect_description(d: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<String>>, budget: &mut usize) {
for (k, v) in &d.attrs {
// the budget is checked before the path is built, not after
if is_rdf_meta_attr(k) || *budget < prefix.len().saturating_add(k.len()) {
continue;
}
let key = format!("{prefix}{k}");
if take_key_bytes(&key, budget) {
props.entry(key).or_default().push(v.clone());
}
}
for c in &d.children {
collect_property(c, prefix, props, budget);
}
}
/// Charge one flattened key's length to the key budget; `false` when the budget is spent (the
/// property is then left out, like other elements a limit has cut).
fn take_key_bytes(key: &str, budget: &mut usize) -> bool {
let n = key.len();
if *budget < n {
return false;
}
*budget -= n;
true
}
fn collect_property(p: &Node, prefix: &str, props: &mut BTreeMap<String, Vec<String>>, budget: &mut usize) {
// a path that can't fit the budget isn't built (a long ancestor path shared by many children
// would otherwise be copied for each of them after the budget is spent)
if *budget < prefix.len().saturating_add(p.name.len()) {
return;
}
let key = format!("{prefix}{}", p.name);
if let Some(arr) = p.children.iter().find(|c| matches!(c.name.as_str(), "rdf:Seq" | "rdf:Bag" | "rdf:Alt")) {
let mut items: Vec<(bool, String)> = arr
.children
.iter()
.filter(|li| li.name == "rdf:li")
.map(|li| {
(li.attr("xml:lang") == Some("x-default"), li.attr("rdf:resource").map(str::to_string).unwrap_or_else(|| li.text.trim().to_string()))
})
.collect();
if arr.name == "rdf:Alt" {
items.sort_by_key(|(default, _)| !*default);
}
if take_key_bytes(&key, budget) {
props.entry(key).or_default().extend(items.into_iter().map(|(_, v)| v));
}
return;
}
let struct_prefix = format!("{key}/");
// a struct's path is charged like a key before its fields copy it: that work too is bounded
// by the budget, kept fields or not
let is_struct = p.attr("rdf:parseType") == Some("Resource") || p.children.iter().any(|c| c.name == "rdf:Description");
if is_struct && !take_key_bytes(&key, budget) {
return;
}
if p.attr("rdf:parseType") == Some("Resource") {
for c in &p.children {
collect_property(c, &struct_prefix, props, budget);
}
return;
}
if let Some(d) = p.children.iter().find(|c| c.name == "rdf:Description") {
collect_description(d, &struct_prefix, props, budget);
return;
}
let field_attrs: Vec<&(String, String)> = p.attrs.iter().filter(|(k, _)| !is_rdf_meta_attr(k)).collect();
if !field_attrs.is_empty() && p.children.is_empty() && p.text.trim().is_empty() {
for (k, v) in field_attrs {
let full = format!("{struct_prefix}{k}");
if take_key_bytes(&full, budget) {
props.entry(full).or_default().push(v.clone());
}
}
return;
}
let v = p.attr("rdf:resource").map(str::to_string).unwrap_or_else(|| p.text.trim().to_string());
if take_key_bytes(&key, budget) {
props.entry(key).or_default().push(v);
}
}
fn find_descriptions<'a>(n: &'a Node, out: &mut Vec<&'a Node>) {
if n.name == "rdf:Description" {
out.push(n);
return;
}
for c in &n.children {
find_descriptions(c, out);
}
}
/// XMP GPS coordinate `DDD,MM,SSk` or `DDD,MM.mmk` (k = N/S/E/W) → signed degrees.
fn parse_gps_coord(s: &str) -> Option<f64> {
let s = s.trim();
let dir = s.chars().last()?;
let body = &s[..s.len() - dir.len_utf8()];
let parts: Vec<f64> = body.split(',').map(|p| p.trim().parse::<f64>().ok()).collect::<Option<_>>()?;
let v = match parts.as_slice() {
[d] => *d,
[d, m] => d + m / 60.0,
[d, m, sec] => d + m / 60.0 + sec / 3600.0,
_ => return None,
};
let v = match dir.to_ascii_uppercase() {
'N' | 'E' => v,
'S' | 'W' => -v,
_ => return None,
};
v.is_finite().then_some(v)
}
/// `mwg-rs:Regions` → every region in its `RegionList`, converted to the full-image normalized frame.
/// Malformed or out-of-range entries are skipped rather than rejecting the whole list: one bad region
/// (from Lightroom, digiKam, Picasa, or a hand-edited file) shouldn't hide the rest.
fn parse_regions(regions: &XmpValue) -> Vec<Region> {
// `AppliedToDimensions` documents the pixel size regions were authored against. Here it's only consulted
// for the rare region whose own Area is in pixel units instead of MWG's normalized default below.
let px_dims = applied_to(regions);
let Some(list) = regions.field("mwg-rs:RegionList") else { return Vec::new() };
list.items().iter().filter_map(|item| parse_one_region(item, px_dims)).collect()
}
/// `mwg-rs:AppliedToDimensions` of a `mwg-rs:Regions` struct: (width, height) in pixels, both positive.
fn applied_to(regions: &XmpValue) -> Option<(f64, f64)> {
regions.field("mwg-rs:AppliedToDimensions").and_then(|d| {
let w = d.field("stDim:w").and_then(XmpValue::text).and_then(parse_number)?;
let h = d.field("stDim:h").and_then(XmpValue::text).and_then(parse_number)?;
(w > 0.0 && h > 0.0).then_some((w, h))
})
let dims = regions.field("mwg-rs:AppliedToDimensions")?;
let w = dims.field("stDim:w")?.text()?.parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0)?;
let h = dims.field("stDim:h")?.text()?.parse::<f64>().ok().filter(|v| v.is_finite() && *v > 0.0)?;
let unit = dims.field("stDim:unit").and_then(XmpValue::text).unwrap_or("pixel");
(unit.is_empty() || unit.eq_ignore_ascii_case("pixel")).then_some((w, h))
}
fn parse_one_region(item: &XmpValue, px_dims: Option<(f64, f64)>) -> Option<Region> {
let area = item.field("mwg-rs:Area")?;
let num_attr = |k: &str| area.field(k).and_then(XmpValue::text).and_then(parse_number);
// stArea:x/y are the region's CENTER, not its top-left corner (MWG Region Guidelines §Area).
let (cx, cy, w, h) = (num_attr("stArea:x")?, num_attr("stArea:y")?, num_attr("stArea:w")?, num_attr("stArea:h")?);
let finite_and_sane = [cx, cy, w, h].iter().all(|v| v.is_finite() && v.abs() <= 1.0e6);
if !finite_and_sane || w <= 0.0 || h <= 0.0 {
return None;
}
// `stArea:unit` is "normalized" (a fraction of AppliedToDimensions) in every writer we know of, and
// that needs no cross-referencing at all. Only a region that explicitly says "pixel" gets divided
// down, and only if AppliedToDimensions is there to divide by; otherwise it's dropped rather than
// stored as a nonsense fraction.
let is_pixels = area.field("stArea:unit").and_then(XmpValue::text).is_some_and(|u| u.eq_ignore_ascii_case("pixel"));
let (cx, cy, w, h) = match (is_pixels, px_dims) {
(false, _) => (cx, cy, w, h),
(true, Some((dw, dh))) => (cx / dw, cy / dh, w / dw, h / dh),
(true, None) => return None,
};
// Lightroom Classic stores the box of a photo with Exif orientation 3 / 6 / 8 in the sensor's own
// frame and writes the orientation as the region's `mwg-rs:Rotation` (π for 3, −π/2 for 6, +π/2 for
// 8; 0 for 1) while `AppliedToDimensions` names the upright size. Turn it into the upright frame.
// MWG has no way to say "mirrored", so orientations 2/4/5/7 can't be told apart from their unmirrored
// twins here; boxes on mirrored photos are taken as written (see LR-LIB-PEOPLE in docs/parity-checklist.md).
let rotation = item.field("mwg-rs:Rotation").and_then(XmpValue::text).and_then(parse_number).filter(|r| r.is_finite());
let (quarter, half) = (std::f64::consts::FRAC_PI_2, std::f64::consts::PI);
let (cx, cy, w, h) = match rotation {
Some(r) if (r + quarter).abs() < 0.05 => (1.0 - cy, cx, h, w),
Some(r) if (r - quarter).abs() < 0.05 => (cy, 1.0 - cx, h, w),
Some(r) if (r.abs() - half).abs() < 0.05 => (1.0 - cx, 1.0 - cy, w, h),
_ => (cx, cy, w, h),
};
// Keep only the part of the box inside the photo: a region hanging off an edge (common for faces
// cut by the frame) is clipped, and one entirely outside it (hostile or stale) is dropped, so every
// stored rect is within 0..1 and non-empty.
let rect = Rect::from_center(Point::new(cx, cy), w, h).intersect(&Rect::UNIT);
if rect.is_empty() {
return None;
}
let name = item.field("mwg-rs:Name").and_then(XmpValue::text).map(str::to_string).filter(|s| !s.is_empty());
let description = item.field("mwg-rs:Description").and_then(XmpValue::text).map(str::to_string).filter(|s| !s.is_empty());
let kind = match item.field("mwg-rs:Type").and_then(XmpValue::text).unwrap_or("") {
t if t.eq_ignore_ascii_case("face") => RegionKind::Face,
t if t.eq_ignore_ascii_case("pet") => RegionKind::Pet,
t if t.eq_ignore_ascii_case("focus") => RegionKind::Focus,
t if t.eq_ignore_ascii_case("barcode") => RegionKind::BarCode,
t => RegionKind::Other(t.to_string()),
};
Some(Region { rect, kind, name, description })
}
fn fmt_gps_coord(v: f64, pos: char, neg: char) -> String {
let a = v.abs();
let mut d = a.trunc();
let mut m = ((a - d) * 60.0 * 1e6).round() / 1e6;
if m >= 60.0 {
d += 1.0;
m = 0.0;
}
format!("{},{:.6}{}", d as i64, m, if v < 0.0 { neg } else { pos })
}
/// Parse an XMP packet (with or without the `<?xpacket?>` wrapper / `x:xmpmeta` element).
pub fn parse_xmp(s: &str) -> Result<XmpData, XmpError> {
let s = s.trim_start_matches('\u{feff}');
let tree = parse_tree(s)?;
let mut descs = Vec::new();
find_descriptions(&tree, &mut descs);
let mut props = BTreeMap::new();
let mut values = BTreeMap::new();
// One budget for the whole document: several descriptions cannot each spend a fresh one.
let mut key_budget = MAX_KEY_BYTES;
for d in descs {
collect_description(d, "", &mut props, &mut key_budget);
if let XmpValue::Struct(m) = node_struct(d) {
values.extend(m);
}
}
let first = |k: &str| props.get(k).and_then(|v| v.first()).map(|s| s.trim().to_string()).filter(|s| !s.is_empty());
let num = |k: &str| first(k).and_then(|s| parse_number(&s));
let mut m = Metadata {
make: first("tiff:Make"),
model: first("tiff:Model"),
serial_number: first("exifEX:BodySerialNumber").or_else(|| first("aux:SerialNumber")),
software: first("xmp:CreatorTool"),
lens_make: first("exifEX:LensMake"),
lens_model: first("exifEX:LensModel").or_else(|| first("aux:Lens")),
lens_serial_number: first("exifEX:LensSerialNumber").or_else(|| first("aux:LensSerialNumber")),
exposure_time: num("exif:ExposureTime").filter(|v| *v > 0.0),
f_number: num("exif:FNumber").filter(|v| *v > 0.0),
focal_length: num("exif:FocalLength").filter(|v| *v > 0.0),
focal_length_35mm: num("exif:FocalLengthIn35mmFilm").filter(|v| *v > 0.0),
exposure_bias: num("exif:ExposureBiasValue"),
exposure_program: num("exif:ExposureProgram").map(|v| v as u16),
metering_mode: num("exif:MeteringMode").map(|v| v as u16),
white_balance: num("exif:WhiteBalance").map(|v| v as u16),
orientation: num("tiff:Orientation").map(|v| v as u16).filter(|v| (1..=8).contains(v)).map(Orientation::from_exif),
width: num("tiff:ImageWidth").filter(|v| *v >= 0.0).or_else(|| num("exif:PixelXDimension").filter(|v| *v >= 0.0)).map(|v| v as u32),
height: num("tiff:ImageLength").filter(|v| *v >= 0.0).or_else(|| num("exif:PixelYDimension").filter(|v| *v >= 0.0)).map(|v| v as u32),
title: first("dc:title"),
caption: first("dc:description"),
alt_text: first("Iptc4xmpCore:AltTextAccessibility"),
extended_description: first("Iptc4xmpCore:ExtDescrAccessibility"),
sublocation: first("Iptc4xmpCore:Location"),
city: first("photoshop:City"),
state: first("photoshop:State"),
country: first("photoshop:Country"),
copyright: first("dc:rights"),
copyright_marked: first("xmpRights:Marked").and_then(|s| match s.to_ascii_lowercase().as_str() {
"true" => Some(true),
"false" => Some(false),
_ => None,
}),
usage_terms: first("xmpRights:UsageTerms"),
copyright_url: first("xmpRights:WebStatement"),
rating: num("xmp:Rating").map(|v| v.round().clamp(-1.0, 5.0) as i8),
label: first("xmp:Label"),
..Default::default()
};
m.iso = [num("exif:ISOSpeedRatings"), num("exifEX:PhotographicSensitivity")].into_iter().flatten().find(|v| *v > 0.0).map(|v| v as u32);
if let Some(spec) = props.get("exifEX:LensSpecification").filter(|v| v.len() == 4) {
let v: Vec<f64> = spec.iter().filter_map(|s| parse_number(s)).collect();
if v.len() == 4 {
m.lens_spec = Some([v[0], v[1], v[2], v[3]]);
}
}
if let Some(creators) = props.get("dc:creator").filter(|c| !c.is_empty()) {
m.artist = Some(creators.join("; "));
}
m.keywords = props.get("dc:subject").cloned().unwrap_or_default().into_iter().filter(|k| !k.is_empty()).collect();
m.hierarchical_keywords = props.get("lr:hierarchicalSubject").cloned().unwrap_or_default().into_iter().filter(|k| !k.is_empty()).collect();
m.capture_time =
["exif:DateTimeOriginal", "photoshop:DateCreated", "xmp:CreateDate"].iter().find_map(|k| first(k).and_then(|s| DateTime::parse_iso(&s)));
if let Some(fired) = first("exif:Flash/exif:Fired") {
let b = |k: &str| first(k).is_some_and(|s| s.eq_ignore_ascii_case("true"));
let n = |k: &str| num(k).unwrap_or(0.0) as u16;
let fired = fired.eq_ignore_ascii_case("true");
let raw = fired as u16
| (n("exif:Flash/exif:Return") & 3) << 1
| (n("exif:Flash/exif:Mode") & 3) << 3
| (b("exif:Flash/exif:Function") as u16) << 5
| (b("exif:Flash/exif:RedEyeMode") as u16) << 6;
m.flash = Some(Flash { fired, raw });
}
if let (Some(lat), Some(lon)) =
(first("exif:GPSLatitude").and_then(|s| parse_gps_coord(&s)), first("exif:GPSLongitude").and_then(|s| parse_gps_coord(&s)))
&& (-90.0..=90.0).contains(&lat)
&& (-180.0..=180.0).contains(&lon)
{
let altitude = num("exif:GPSAltitude").map(|a| if first("exif:GPSAltitudeRef").as_deref() == Some("1") { -a } else { a });
m.gps = Some(Gps { latitude: lat, longitude: lon, altitude });
}
m.regions = values.get("mwg-rs:Regions").map(parse_regions).unwrap_or_default();
let lc_settings = props.get("lc:settings").and_then(|v| v.first()).cloned();
Ok(XmpData { metadata: m, lc_settings, properties: props, values })
parse_xmp_with(s, LC_NAMESPACES).map(xmp_from_craft)
}
fn frac(v: f64) -> String {
if v > 0.0 && v < 1.0 {
let inv = 1.0 / v;
if (inv - inv.round()).abs() < 1e-6 {
return format!("1/{}", inv.round() as u64);
}
}
let (n, d) = craft_tiff::writer::rational(v);
format!("{n}/{d}")
}
fn sfrac(v: f64) -> String {
let (n, d) = craft_tiff::writer::srational(v);
format!("{n}/{d}")
}
/// Serialise the interchange subset of `meta` (plus `lc_settings`, an opaque JSON string, in `lc:settings`)
/// as a complete XMP packet.
pub fn write_xmp(meta: &Metadata, lc_settings: Option<&str>) -> String {
let lc: Vec<(&str, &str)> = lc_settings.map(|s| ("settings", s)).into_iter().collect();
write_xmp_lc(meta, &lc)
let settings = lc_settings.map(|s| [("settings", s)]);
write_xmp_lc(meta, settings.as_ref().map_or(&[], |a| a.as_slice()))
}
/// Like [`write_xmp`], with any number of simple `lc:<name>` properties (e.g. `settings`, `flag`).
pub fn write_xmp_lc(meta: &Metadata, lc: &[(&str, &str)]) -> String {
let mut simple: Vec<(&str, String)> = Vec::new();
let mut push = |k: &'static str, v: Option<String>| {
if let Some(v) = v {
simple.push((k, v));
}
};
push("tiff:Make", meta.make.clone());
push("tiff:Model", meta.model.clone());
push("tiff:Orientation", meta.orientation.map(|o| o.to_exif().to_string()));
push("tiff:ImageWidth", meta.width.map(|v| v.to_string()));
push("tiff:ImageLength", meta.height.map(|v| v.to_string()));
push("xmp:CreatorTool", meta.software.clone());
push("xmp:Rating", meta.rating.map(|v| v.to_string()));
push("xmp:Label", meta.label.clone());
push("exif:DateTimeOriginal", meta.capture_time.map(|d| d.to_iso()));
push("photoshop:DateCreated", meta.capture_time.map(|d| d.to_iso()));
push("exif:ExposureTime", meta.exposure_time.map(frac));
push("exif:FNumber", meta.f_number.map(frac));
push("exif:FocalLength", meta.focal_length.map(frac));
push("exif:FocalLengthIn35mmFilm", meta.focal_length_35mm.map(|v| format!("{}", v.round() as i64)));
push("exif:ExposureBiasValue", meta.exposure_bias.map(sfrac));
push("exif:ExposureProgram", meta.exposure_program.map(|v| v.to_string()));
push("exif:MeteringMode", meta.metering_mode.map(|v| v.to_string()));
push("exif:WhiteBalance", meta.white_balance.map(|v| v.to_string()));
push("exifEX:BodySerialNumber", meta.serial_number.clone());
push("exifEX:LensMake", meta.lens_make.clone());
push("exifEX:LensModel", meta.lens_model.clone());
push("exifEX:LensSerialNumber", meta.lens_serial_number.clone());
push("Iptc4xmpCore:Location", meta.sublocation.clone());
push("photoshop:City", meta.city.clone());
push("photoshop:State", meta.state.clone());
push("photoshop:Country", meta.country.clone());
push("xmpRights:Marked", meta.copyright_marked.map(|m| if m { "True" } else { "False" }.to_string()));
push("xmpRights:WebStatement", meta.copyright_url.clone());
if let Some(g) = meta.gps {
push("exif:GPSLatitude", Some(fmt_gps_coord(g.latitude, 'N', 'S')));
push("exif:GPSLongitude", Some(fmt_gps_coord(g.longitude, 'E', 'W')));
if let Some(a) = g.altitude {
push("exif:GPSAltitude", Some(frac(a.abs())));
push("exif:GPSAltitudeRef", Some(if a < 0.0 { "1" } else { "0" }.into()));
}
}
let mut x = String::new();
x.push_str("<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n");
x.push_str("<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"LightCraft\">\n");
x.push_str(" <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n");
x.push_str(" <rdf:Description rdf:about=\"\"");
for (p, u) in NAMESPACES.iter().skip(2).filter(|(p, _)| *p != "crs") {
x.push_str(&format!("\n xmlns:{p}=\"{u}\""));
}
x.push_str(">\n");
for (k, v) in &simple {
x.push_str(&format!(" <{k}>{}</{k}>\n", escape(xml_safe(v))));
}
for (k, v) in lc {
if !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
// element content: quotes needn't be escaped, which keeps the JSON readable
x.push_str(&format!(" <lc:{k}>{}</lc:{k}>\n", partial_escape(xml_safe(v))));
}
}
let array = |x: &mut String, k: &str, kind: &str, items: &[String], lang: bool| {
if items.is_empty() {
return;
}
x.push_str(&format!(" <{k}>\n <rdf:{kind}>\n"));
for it in items {
if lang {
x.push_str(&format!(" <rdf:li xml:lang=\"x-default\">{}</rdf:li>\n", escape(xml_safe(it))));
} else {
x.push_str(&format!(" <rdf:li>{}</rdf:li>\n", escape(xml_safe(it))));
}
}
x.push_str(&format!(" </rdf:{kind}>\n </{k}>\n"));
};
let one = |v: &Option<String>| v.iter().cloned().collect::<Vec<_>>();
array(&mut x, "dc:title", "Alt", &one(&meta.title), true);
array(&mut x, "dc:description", "Alt", &one(&meta.caption), true);
array(&mut x, "Iptc4xmpCore:AltTextAccessibility", "Alt", &one(&meta.alt_text), true);
array(&mut x, "Iptc4xmpCore:ExtDescrAccessibility", "Alt", &one(&meta.extended_description), true);
array(&mut x, "dc:rights", "Alt", &one(&meta.copyright), true);
array(&mut x, "xmpRights:UsageTerms", "Alt", &one(&meta.usage_terms), true);
array(&mut x, "dc:creator", "Seq", &one(&meta.artist), false);
array(&mut x, "dc:subject", "Bag", &meta.keywords, false);
array(&mut x, "lr:hierarchicalSubject", "Bag", &meta.hierarchical_keywords, false);
array(&mut x, "exif:ISOSpeedRatings", "Seq", &meta.iso.map(|v| vec![v.to_string()]).unwrap_or_default(), false);
if let Some(s) = meta.lens_spec {
array(&mut x, "exifEX:LensSpecification", "Seq", &s.iter().map(|&v| frac(v)).collect::<Vec<_>>(), false);
}
if let Some(f) = meta.flash {
let r = f.raw;
let tf = |b: bool| if b { "True" } else { "False" };
x.push_str(&format!(
" <exif:Flash rdf:parseType=\"Resource\">\n <exif:Fired>{}</exif:Fired>\n <exif:Return>{}</exif:Return>\n <exif:Mode>{}</exif:Mode>\n <exif:Function>{}</exif:Function>\n <exif:RedEyeMode>{}</exif:RedEyeMode>\n </exif:Flash>\n",
tf(f.fired),
(r >> 1) & 3,
(r >> 3) & 3,
tf(r & 0x20 != 0),
tf(r & 0x40 != 0)
));
}
x.push_str(" </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"w\"?>");
x
write_xmp_with(&to_craft(meta), &XmpWrite { toolkit: "LightCraft", namespace: Some(XmpNamespace { prefix: "lc", uri: LC_NS }), properties: lc })
}
#[cfg(test)]
mod tests;
-513
View File
@@ -1,513 +0,0 @@
//! Merging a freshly written XMP packet into an existing one (a sidecar another application
//! wrote, e.g. with its develop settings and edit history), keeping everything the writer does not
//! own byte for byte.
//!
//! The existing packet is scanned once (namespace-resolved, with byte positions). Only top-level
//! properties of the `rdf:Description` elements directly under `rdf:RDF` are considered, in
//! attribute form (`xmp:Rating="3"`) and element form (`<dc:subject>…</dc:subject>`):
//! - properties the writer owns ([`MergeRules::owned`]) are removed, and written from the fresh
//! packet when it has them (so a cleared field is cleared in the file too);
//! - properties owned only when stated ([`MergeRules::owned_if_present`]) are replaced when the
//! fresh packet has them and kept otherwise;
//! - any other property of the fresh packet (e.g. `xmp:CreatorTool`) is not written: the file
//! keeps describing itself as its creator left it;
//! - everything else — other namespaces (e.g. `crs:`), `xmpMM:History`, unknown properties,
//! comments, the packet wrapper and padding — is copied unchanged.
//!
//! The written properties go into one new `rdf:Description` (declaring its own namespaces, so
//! the existing prefix bindings never matter) just before `</rdf:RDF>`. A description left empty
//! by the removals is dropped, so repeated saves don't accumulate. The result is checked by
//! parsing it again: every written property must read back as in the fresh packet.
use std::collections::{BTreeSet, HashSet};
use quick_xml::events::Event;
use crate::xmp::{MAX_OPAQUE_NAME_BYTES, XmpError, canonical_name, check_scopes, parse_xmp, unescape_attr};
/// Which properties [`merge_xmp`] takes from the fresh packet. Names are canonical
/// `prefix:name` (prefixes as [`crate::parse_xmp`] reports them); `prefix:*` is a whole namespace.
#[derive(Clone, Copy, Debug, Default)]
pub struct MergeRules<'a> {
/// Always replaced: removed from the existing packet, written from the fresh one if stated.
pub owned: &'a [&'a str],
/// Replaced only when the fresh packet states them; otherwise the existing value stays.
pub owned_if_present: &'a [&'a str],
}
fn listed(list: &[&str], name: &str) -> bool {
list.iter().any(|p| match p.strip_suffix('*') {
Some(ns) => name.starts_with(ns),
None => *p == name,
})
}
#[derive(Debug)]
struct Attr {
raw: String,
name: String,
/// The value as written (still escaped).
value: String,
}
#[derive(Debug)]
struct Prop {
name: String,
start: usize,
end: usize,
}
#[derive(Debug, Default)]
struct Desc {
tag_start: usize,
tag_end: usize,
/// The element name as written (`rdf:Description`, or another prefix for the RDF namespace).
raw_name: String,
empty: bool,
attrs: Vec<Attr>,
props: Vec<Prop>,
/// The end of `</rdf:Description>` (`tag_end` when self-closing).
end: usize,
}
#[derive(Debug, Default)]
struct Scan {
descs: Vec<Desc>,
/// Where the first `</rdf:RDF>` starts.
rdf_close: Option<usize>,
/// The span of a self-closing `<rdf:RDF/>` (used only when there is no `</rdf:RDF>`).
rdf_empty: Option<(usize, usize)>,
}
enum Kind {
Other,
Rdf,
Desc(usize),
Prop { desc: usize, start: usize, name: String },
}
fn is_meta_attr(name: &str) -> bool {
name.starts_with("xmlns")
|| matches!(name, "rdf:about" | "rdf:ID" | "rdf:nodeID" | "xml:lang" | "rdf:parseType" | "rdf:resource" | "rdf:datatype")
}
fn pos(r: &quick_xml::Reader<&[u8]>) -> usize {
usize::try_from(r.buffer_position()).unwrap_or(usize::MAX)
}
/// Locate the descriptions, their top-level properties and `</rdf:RDF>` in a packet.
fn scan(s: &str) -> Result<Scan, XmpError> {
let mut reader = quick_xml::Reader::from_reader(s.as_bytes());
reader.config_mut().check_end_names = true;
let mut out = Scan::default();
let mut stack: Vec<Kind> = Vec::new();
let mut scopes: Vec<Vec<(String, String)>> = vec![vec![("xml".into(), "http://www.w3.org/XML/1998/namespace".into())]];
let mut count = 0usize;
let mut opaque_budget = MAX_OPAQUE_NAME_BYTES;
loop {
let before = pos(&reader);
let ev = reader.read_event().map_err(|e| XmpError::Xml(e.to_string()))?;
let after = pos(&reader);
match ev {
Event::Start(ref e) | Event::Empty(ref e) => {
count += 1;
if count > 200_000 || stack.len() > 64 {
return Err(XmpError::TooComplex);
}
let empty = matches!(ev, Event::Empty(_));
let mut scope = Vec::new();
let mut raw_attrs = Vec::new();
// repeated names are refused with a set, in linear time (quick-xml's own check is quadratic)
let mut seen = HashSet::new();
for a in e.attributes().with_checks(false) {
let a = a.map_err(|e| XmpError::Xml(e.to_string()))?;
let k = String::from_utf8_lossy(a.key.as_ref()).into_owned();
if !seen.insert(k.clone()) {
return Err(XmpError::Xml(format!("repeated attribute {k}")));
}
let v = String::from_utf8_lossy(&a.value).into_owned();
if k == "xmlns" {
scope.push((String::new(), unescape_attr(&v)));
} else if let Some(p) = k.strip_prefix("xmlns:") {
scope.push((p.to_string(), unescape_attr(&v)));
}
raw_attrs.push((k, v));
}
scopes.push(scope);
check_scopes(&scopes)?;
let raw_name = String::from_utf8_lossy(e.name().as_ref()).into_owned();
let name = canonical_name(&raw_name, &scopes, &mut opaque_budget)?;
let kind = match stack.last() {
Some(Kind::Rdf) if name == "rdf:Description" => {
let attrs = raw_attrs
.into_iter()
.map(|(raw, value)| Ok(Attr { name: canonical_name(&raw, &scopes, &mut opaque_budget)?, raw, value }))
.collect::<Result<_, XmpError>>()?;
out.descs.push(Desc { tag_start: before, tag_end: after, raw_name, empty, attrs, props: Vec::new(), end: after });
Kind::Desc(out.descs.len() - 1)
}
Some(Kind::Desc(i)) => Kind::Prop { desc: *i, start: before, name },
_ if name == "rdf:RDF" && out.rdf_close.is_none() => Kind::Rdf,
_ => Kind::Other,
};
if empty {
if matches!(kind, Kind::Rdf) {
out.rdf_empty = out.rdf_empty.or(Some((before, after)));
}
scopes.pop();
if let Kind::Prop { desc, start, name } = kind
&& let Some(d) = out.descs.get_mut(desc)
{
d.props.push(Prop { name, start, end: after });
}
} else {
stack.push(kind);
}
}
Event::End(_) => {
scopes.pop();
match stack.pop() {
Some(Kind::Prop { desc, start, name }) => {
if let Some(d) = out.descs.get_mut(desc) {
d.props.push(Prop { name, start, end: after });
}
}
Some(Kind::Desc(i)) => {
if let Some(d) = out.descs.get_mut(i) {
d.end = after;
}
}
Some(Kind::Rdf) => out.rdf_close = out.rdf_close.or(Some(before)),
Some(Kind::Other) => {}
None => return Err(XmpError::Xml("unbalanced end tag".into())),
}
}
Event::Eof => break,
_ => {}
}
}
if !stack.is_empty() {
return Err(XmpError::Xml("unclosed element".into()));
}
Ok(out)
}
/// `start` moved back over the indentation and line break before it (so a removed property
/// takes its line with it).
fn line_start(s: &str, start: usize) -> usize {
let b = s.as_bytes();
let mut i = start;
while i > 0 && matches!(b.get(i - 1), Some(b' ' | b'\t')) {
i -= 1;
}
if i > 0 && b.get(i - 1) == Some(&b'\n') {
i -= 1;
if i > 0 && b.get(i - 1) == Some(&b'\r') {
i -= 1;
}
}
i
}
/// Merge `fresh` (a packet as [`crate::write_xmp_lc`] writes it) into `existing` following
/// `rules` (see the module docs). Fails — and the caller must not overwrite `existing` blindly —
/// when `existing` isn't a well-formed XMP packet.
pub fn merge_xmp(existing: &str, fresh: &str, rules: MergeRules) -> Result<String, XmpError> {
let (bom, old) = match existing.strip_prefix('\u{feff}') {
Some(rest) => ("\u{feff}", rest),
None => ("", existing),
};
parse_xmp(old)?;
let ex = scan(old)?;
if ex.rdf_close.is_none() && ex.rdf_empty.is_none() {
return Err(XmpError::Xml("no rdf:RDF element".into()));
}
let new = scan(fresh)?;
let fresh_desc = new.descs.first().ok_or_else(|| XmpError::Xml("the new packet has no rdf:Description".into()))?;
let fresh_names: BTreeSet<&str> = fresh_desc.props.iter().map(|p| p.name.as_str()).collect();
let remove = |name: &str| listed(rules.owned, name) || (listed(rules.owned_if_present, name) && fresh_names.contains(name));
let write = |name: &str| listed(rules.owned, name) || listed(rules.owned_if_present, name);
// edits on `old`: (start, end, replacement), applied back to front
let mut edits: Vec<(usize, usize, String)> = Vec::new();
for d in &ex.descs {
let gone_attrs: Vec<&Attr> = d.attrs.iter().filter(|a| !is_meta_attr(&a.name) && remove(&a.name)).collect();
let gone_props: Vec<&Prop> = d.props.iter().filter(|p| remove(&p.name)).collect();
if gone_attrs.is_empty() && gone_props.is_empty() {
continue;
}
let attrs_left = d.attrs.iter().any(|a| !is_meta_attr(&a.name) && !remove(&a.name));
if !attrs_left && gone_props.len() == d.props.len() {
// nothing of its own left: drop the whole description
edits.push((line_start(old, d.tag_start), d.end, String::new()));
continue;
}
if !gone_attrs.is_empty() {
let mut tag = format!("<{}", d.raw_name);
for a in d.attrs.iter().filter(|a| is_meta_attr(&a.name) || !remove(&a.name)) {
tag.push_str(&format!("\n {}=\"{}\"", a.raw, a.value.replace('"', "&quot;")));
}
tag.push_str(if d.empty { "/>" } else { ">" });
edits.push((d.tag_start, d.tag_end, tag));
}
for p in gone_props {
edits.push((line_start(old, p.start), p.end, String::new()));
}
}
// the new description: its own namespace declarations, the properties to write
let mut block = String::from("\n <rdf:Description rdf:about=\"\"\n xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"");
for a in fresh_desc.attrs.iter().filter(|a| a.raw.starts_with("xmlns:") && a.raw != "xmlns:rdf") {
block.push_str(&format!("\n {}=\"{}\"", a.raw, a.value));
}
block.push('>');
let mut written = 0;
for p in fresh_desc.props.iter().filter(|p| write(&p.name)) {
let text = fresh.get(p.start..p.end).ok_or_else(|| XmpError::Xml("bad property span".into()))?;
block.push_str("\n ");
block.push_str(text);
written += 1;
}
block.push_str("\n </rdf:Description>");
if written > 0 {
if let Some(rdf_close) = ex.rdf_close {
let at = old.get(..rdf_close).map_or(rdf_close, |h| h.trim_end().len());
edits.push((at, at, block));
} else if let Some((s, e)) = ex.rdf_empty {
// a self-closing `<rdf:RDF .../>` is opened up around the new description
let tag = old.get(s..e).ok_or_else(|| XmpError::Xml("bad span".into()))?;
let open = tag.trim_end().strip_suffix("/>").ok_or_else(|| XmpError::Xml("bad rdf:RDF tag".into()))?;
let name = tag.get(1..).and_then(|t| t.split(|c: char| c.is_whitespace() || c == '/' || c == '>').next()).unwrap_or("rdf:RDF");
edits.push((s, e, format!("{open}>{block}\n</{name}>")));
}
}
edits.sort_by_key(|e| (e.0, e.1));
// overlapping edits can't happen (properties sit inside their description, which is either
// dropped whole or edited piecewise), but never splice blindly
let mut out = String::with_capacity(old.len() + 4096);
out.push_str(bom);
let mut at = 0;
for (s, e, r) in &edits {
if *s < at {
return Err(XmpError::Xml("overlapping edits".into()));
}
out.push_str(old.get(at..*s).ok_or_else(|| XmpError::Xml("bad span".into()))?);
out.push_str(r);
at = *e;
}
out.push_str(old.get(at..).ok_or_else(|| XmpError::Xml("bad span".into()))?);
// read back: everything written must come out as written
let merged = parse_xmp(&out)?;
let want = parse_xmp(fresh)?;
for (k, v) in &want.properties {
let top = k.split('/').next().unwrap_or(k);
if write(top) && merged.properties.get(k) != Some(v) {
return Err(XmpError::Xml(format!("{k} did not survive the merge")));
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
const RULES: MergeRules =
MergeRules { owned: &["xmp:Rating", "xmp:Label", "dc:subject", "dc:title", "lc:*"], owned_if_present: &["exif:DateTimeOriginal"] };
/// A sidecar as another raw developer writes it: attribute-form simple properties, develop
/// settings, a structured history, an unknown namespace.
const FOREIGN: &str = "<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>
<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Some Toolkit 1.0\">
<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">
<rdf:Description rdf:about=\"\"
xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"
xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"
xmlns:stEvt=\"http://ns.adobe.com/xap/1.0/sType/ResourceEvent#\"
xmlns:crs=\"http://ns.adobe.com/camera-raw-settings/1.0/\"
xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
xmlns:foo=\"http://example.com/foo/\"
xmp:Rating=\"2\"
xmp:CreatorTool=\"Other App\"
crs:Exposure2012=\"+0.50\"
crs:Contrast2012=\"-12\"
foo:Thing=\"a &amp; b\">
<xmpMM:History>
<rdf:Seq>
<rdf:li stEvt:action=\"saved\" stEvt:when=\"2026-01-02T03:04:05\"/>
</rdf:Seq>
</xmpMM:History>
<crs:ToneCurvePV2012>
<rdf:Seq>
<rdf:li>0, 0</rdf:li>
<rdf:li>255, 255</rdf:li>
</rdf:Seq>
</crs:ToneCurvePV2012>
<dc:subject>
<rdf:Bag>
<rdf:li>old</rdf:li>
</rdf:Bag>
</dc:subject>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
";
/// With the packet's whitespace padding and trailer.
fn foreign() -> String {
format!("{FOREIGN}{}\n<?xpacket end=\"w\"?>", " ".repeat(100))
}
fn fresh(rating: i8, keywords: &[&str]) -> String {
let m = crate::Metadata {
software: Some("LightCraft".into()),
rating: Some(rating),
keywords: keywords.iter().map(|k| k.to_string()).collect(),
..Default::default()
};
crate::write_xmp_lc(&m, &[("settings", "{\"a\":1}"), ("flag", "pick")])
}
#[test]
fn keeps_foreign_properties_and_replaces_owned_ones() {
let out = merge_xmp(&foreign(), &fresh(4, &["new", "two"]), RULES).unwrap();
let d = parse_xmp(&out).unwrap();
let p = |k: &str| d.properties.get(k).cloned().unwrap_or_default();
assert_eq!(p("xmp:Rating"), vec!["4"]);
assert_eq!(p("dc:subject"), vec!["new", "two"]);
assert_eq!(p("lc:settings"), vec!["{\"a\":1}"]);
assert_eq!(p("lc:flag"), vec!["pick"]);
assert_eq!(p("xmp:CreatorTool"), vec!["Other App"], "not ours: kept");
assert_eq!(p("crs:Exposure2012"), vec!["+0.50"]);
assert_eq!(p("foo:Thing").len(), 1);
// untouched parts are byte for byte the same
for part in [
" <xmpMM:History>\n <rdf:Seq>\n <rdf:li stEvt:action=\"saved\" stEvt:when=\"2026-01-02T03:04:05\"/>\n </rdf:Seq>\n </xmpMM:History>",
" <crs:ToneCurvePV2012>\n <rdf:Seq>\n <rdf:li>0, 0</rdf:li>",
"crs:Contrast2012=\"-12\"",
"foo:Thing=\"a &amp; b\"",
"<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Some Toolkit 1.0\">",
&format!("</x:xmpmeta>\n{}\n<?xpacket end=\"w\"?>", " ".repeat(100)),
] {
assert!(out.contains(part), "lost {part:?} in\n{out}");
}
assert!(!out.contains("xmp:Rating=\"2\""));
assert!(!out.contains("<rdf:li>old</rdf:li>"));
// saving again changes only our part, and doesn't pile up descriptions
let again = merge_xmp(&out, &fresh(1, &[]), RULES).unwrap();
let d = parse_xmp(&again).unwrap();
assert_eq!(d.properties.get("xmp:Rating"), Some(&vec!["1".to_string()]));
assert!(!d.properties.contains_key("dc:subject"), "a cleared field is cleared");
assert_eq!(again.matches("<rdf:Description").count(), 2, "{again}");
assert_eq!(merge_xmp(&again, &fresh(1, &[]), RULES).unwrap(), again, "idempotent");
}
#[test]
fn a_self_closing_rdf_element_is_opened_not_replaced() {
let ex = "<!-- keep me --><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><r:RDF xmlns:r=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"/></x:xmpmeta>";
let out = merge_xmp(ex, &fresh(3, &[]), RULES).unwrap();
assert!(out.starts_with("<!-- keep me --><x:xmpmeta"), "{out}");
assert!(out.contains("</r:RDF></x:xmpmeta>"), "{out}");
assert_eq!(parse_xmp(&out).unwrap().properties.get("xmp:Rating"), Some(&vec!["3".to_string()]));
assert!(merge_xmp("<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>", &fresh(3, &[]), RULES).is_err(), "no RDF element at all");
}
#[test]
fn owned_if_present_and_prefix_independence() {
// the existing packet binds the namespaces to other prefixes, and has a capture time
let ex = "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><r:RDF xmlns:r=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
<r:Description r:about=\"\" xmlns:a=\"http://ns.adobe.com/xap/1.0/\" xmlns:e=\"http://ns.adobe.com/exif/1.0/\" \
a:Rating=\"5\" e:DateTimeOriginal=\"2020-01-01T00:00:00\"/></r:RDF></x:xmpmeta>";
let out = merge_xmp(ex, &fresh(3, &[]), RULES).unwrap();
let d = parse_xmp(&out).unwrap();
assert_eq!(d.properties.get("xmp:Rating"), Some(&vec!["3".to_string()]));
assert_eq!(d.properties.get("exif:DateTimeOriginal"), Some(&vec!["2020-01-01T00:00:00".to_string()]), "fresh has none: kept");
let mut m = crate::Metadata { rating: Some(3), ..Default::default() };
m.capture_time = crate::DateTime::parse_iso("2024-05-06T07:08:09");
let out = merge_xmp(ex, &crate::write_xmp_lc(&m, &[]), RULES).unwrap();
let d = parse_xmp(&out).unwrap();
assert_eq!(d.properties.get("exif:DateTimeOriginal"), Some(&vec!["2024-05-06T07:08:09".to_string()]));
}
#[test]
fn preserves_foreign_properties_using_known_prefixes() {
for property in [r#"lc:Secret="keep-me"/>"#, r#"><lc:Secret>keep-me</lc:Secret></rdf:Description>"#] {
let desc = format!(r#"<rdf:Description rdf:about="" xmlns:lc="https://example.org/vendor/" {property}"#);
let old = format!(r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">{desc}</rdf:RDF>"#);
let out = merge_xmp(&old, &fresh(4, &[]), RULES).unwrap();
assert!(out.contains(&desc), "lost foreign description: {out}");
assert_eq!(parse_xmp(&out).unwrap().metadata.rating, Some(4));
assert_eq!(merge_xmp(&out, &fresh(4, &[]), RULES).unwrap(), out);
}
}
#[test]
fn namespace_aliases_remain_distinct_during_merge() {
// The alias URI includes a character reference: scanning and parsing must resolve it identically.
let foreign = r#"<rdf:Description xmlns:xmp="https://example.org/vendor/" xmp:Rating="2"/>"#;
let old = format!(
r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">{foreign}
<rdf:Description xmlns:a="http://ns.adobe.com/xap/1.0&#47;" a:Rating="3"/>
</rdf:RDF>"#
);
let out = merge_xmp(&old, &fresh(5, &[]), RULES).unwrap();
assert!(out.contains(foreign), "lost foreign rating: {out}");
assert!(!out.contains("a:Rating="), "genuine alias must be replaced: {out}");
assert_eq!(parse_xmp(&out).unwrap().metadata.rating, Some(5));
assert_eq!(merge_xmp(&out, &fresh(5, &[]), RULES).unwrap(), out);
}
#[test]
fn opaque_namespace_expansion_is_bounded() {
// A roughly 40 KiB packet must not expand the same long URI into every property name indefinitely.
let packet = format!(
r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description
xmlns:lc="https://example.org/{}">{}</rdf:Description></rdf:RDF>"#,
"a".repeat(1024),
"<lc:p/>".repeat(5000)
);
assert_eq!(parse_xmp(&packet).unwrap_err(), XmpError::TooComplex);
assert!(matches!(scan(&packet), Err(XmpError::TooComplex)));
}
#[test]
fn many_attributes_scan_in_linear_time() {
// quick-xml's duplicate-name check compares each attribute with all earlier ones: 200 000 attributes on
// one description took over 20 s to scan, about 30 ms with the set
let n = 200_000;
let mut s = String::from(
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
<rdf:Description rdf:about=\"\" xmlns:foo=\"http://example.com/foo/\"",
);
for i in 0..n {
s.push_str(&format!(" foo:a{i}=\"{i}\""));
}
s.push_str("/></rdf:RDF></x:xmpmeta>");
let t = std::time::Instant::now();
let found = scan(&s).unwrap();
let took = t.elapsed();
assert_eq!(found.descs[0].attrs.len(), n + 2, "every attribute is read");
assert!(took < std::time::Duration::from_secs(5), "{n} attributes took {took:?}");
}
#[test]
fn refuses_what_it_cannot_read() {
for bad in ["", "not xml at all", "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF", "<a><b></a>", "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>"] {
assert!(merge_xmp(bad, &fresh(1, &[]), RULES).is_err(), "{bad:?}");
}
}
#[test]
fn refuses_a_repeated_attribute() {
// not well-formed XML (strict readers such as expat refuse it): no merge, so the caller keeps a backup.
// An owned name, a foreign one and one on a nested element (a merge would keep both copies of the last two).
for (once, twice) in [
("xmp:Rating=\"2\"", "xmp:Rating=\"2\" xmp:Rating=\"3\""),
("foo:Thing=\"a &amp; b\"", "foo:Thing=\"a &amp; b\" foo:Thing=\"c\""),
("stEvt:action=\"saved\"", "stEvt:action=\"saved\" stEvt:action=\"saved\""),
] {
let ex = foreign().replace(once, twice);
assert!(merge_xmp(&ex, &fresh(1, &[]), RULES).is_err(), "{twice}");
}
}
}
+1 -1
View File
@@ -22,5 +22,5 @@ serde = { workspace = true }
dhat = { workspace = true }
lightcraft-scenes = { workspace = true }
proptest = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
serde_json = { workspace = true }
+7 -3
View File
@@ -8,7 +8,8 @@ fn main() {
let lib = lightcraft_scenes::demo_library();
let picks = [0usize, 2, 3, 6, 8, 5];
let (cw, ch) = (420usize, 280usize);
let mut sheet = image::RgbImage::new((cw * 2) as u32, (ch * picks.len()) as u32);
let (sw, sh) = (cw * 2, ch * picks.len());
let mut sheet = vec![0u8; sw * sh * 3];
for (row, &i) in picks.iter().enumerate() {
let src = lib[i].render_fit(900);
let mut edited = DevelopSettings::default();
@@ -27,11 +28,14 @@ fn main() {
for y in 0..r.height {
for x in 0..r.width {
let p = r.get(x, y);
sheet.put_pixel((ox + x) as u32, (oy + y) as u32, image::Rgb([p[0], p[1], p[2]]));
let idx = ((oy + y) * sw + (ox + x)) * 3;
sheet[idx..idx + 3].copy_from_slice(&[p[0], p[1], p[2]]);
}
}
}
}
sheet.save(&out).unwrap();
let img = craft_image_codecs::Image::from_u8(sw as u32, sh as u32, craft_image_codecs::ChannelLayout::Rgb, sheet).unwrap();
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &Default::default()).unwrap();
std::fs::write(&out, png).unwrap();
println!("{out}");
}
+1 -1
View File
@@ -13,7 +13,7 @@
use lightcraft_color::{D50, D65, PROPHOTO, REC2020, bradford};
use lightcraft_geom::Point;
use lightcraft_raster::Rgb32f;
use lightcraft_raw::gaintable::{GainTableMap, SourcePlacement};
use lightcraft_raw::gaintable::{GainTableMap, GainTableMapApply, SourcePlacement};
use crate::{Plan, SourceInfo};
use lightcraft_develop::DevelopSettings;
+1 -3
View File
@@ -11,7 +11,5 @@ workspace = true
[dependencies]
lightcraft-raster = { workspace = true }
siphasher = { workspace = true }
jpeg-encoder = { workspace = true }
zune-jpeg = { workspace = true }
zune-core = { workspace = true }
craft-image-codecs = { workspace = true }
log = { workspace = true }
+45 -23
View File
@@ -516,11 +516,9 @@ pub fn encode_jpeg(img: &Rgba8) -> Option<Vec<u8>> {
for p in &img.data {
rgb.extend_from_slice(&p[..3]);
}
let mut out = Vec::new();
let mut enc = jpeg_encoder::Encoder::new(&mut out, QUALITY);
enc.set_sampling_factor(jpeg_encoder::SamplingFactor::R_4_2_0);
enc.encode(&rgb, img.width as u16, img.height as u16, jpeg_encoder::ColorType::Rgb).ok()?;
Some(out)
let ic_img = craft_image_codecs::Image::from_u8(img.width as u32, img.height as u32, craft_image_codecs::ChannelLayout::Rgb, rgb).ok()?;
let opts = craft_image_codecs::EncodeOptions { jpeg_quality: QUALITY, jpeg_chroma_subsampling: true, ..Default::default() };
craft_image_codecs::encode(&ic_img, craft_image_codecs::Format::Jpeg, &opts).ok()
}
/// How much of a cached file [`DiskCache::dims`] reads: the JPEG headers this cache writes come
@@ -531,27 +529,51 @@ const FIRST_HEADER_BYTES: u64 = 4 << 10;
/// A JPEG's (width, height) from its headers (`None`: not a JPEG, or cut short before its frame header).
pub fn jpeg_dims(bytes: &[u8]) -> Option<(usize, usize)> {
use zune_core::bytestream::ZCursor;
let mut d = zune_jpeg::JpegDecoder::new(ZCursor::new(bytes));
d.decode_headers().ok()?;
let info = d.info()?;
let (w, h) = (info.width as usize, info.height as usize);
(w > 0 && h > 0).then_some((w, h))
if !bytes.starts_with(&[0xFF, 0xD8]) {
return None;
}
let mut i = 2;
while i + 4 <= bytes.len() {
if bytes[i] != 0xFF {
i += 1;
continue;
}
let m = bytes[i + 1];
if m == 0xFF {
i += 1;
continue;
}
if m == 0xD8 || (0xD0..=0xD7).contains(&m) || m == 0x01 {
i += 2;
continue;
}
if m == 0xD9 || m == 0xDA {
break;
}
let len = u16::from_be_bytes([bytes[i + 2], bytes[i + 3]]) as usize;
if len < 2 || i + 2 + len > bytes.len() {
break;
}
if matches!(m, 0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF) && len >= 7 {
let h = u16::from_be_bytes([bytes[i + 5], bytes[i + 6]]) as usize;
let w = u16::from_be_bytes([bytes[i + 7], bytes[i + 8]]) as usize;
return (w > 0 && h > 0).then_some((w, h));
}
i += 2 + len;
}
None
}
/// Decode a cached thumbnail (see [`encode_jpeg`]).
pub fn decode_jpeg(bytes: &[u8]) -> Option<Rgba8> {
use zune_core::bytestream::ZCursor;
use zune_core::colorspace::ColorSpace;
use zune_core::options::DecoderOptions;
let opts = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGB);
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), opts);
let px = d.decode().ok()?;
let info = d.info()?;
let (w, h) = (info.width as usize, info.height as usize);
if px.len() < w * h * 3 {
return None;
}
let data = px.as_chunks::<3>().0.iter().take(w * h).map(|c| [c[0], c[1], c[2], 255]).collect();
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Jpeg, bytes, &craft_image_codecs::DecodeOptions::default()).ok()?;
let (w, h) = (img.width() as usize, img.height() as usize);
let px = img.as_u8()?;
let data = match img.layout() {
craft_image_codecs::ChannelLayout::Gray => px.iter().take(w * h).map(|&y| [y, y, y, 255]).collect(),
craft_image_codecs::ChannelLayout::Rgb => px.as_chunks::<3>().0.iter().take(w * h).map(|c| [c[0], c[1], c[2], 255]).collect(),
craft_image_codecs::ChannelLayout::Rgba => px.as_chunks::<4>().0.iter().take(w * h).copied().collect(),
_ => return None,
};
Some(Rgba8 { width: w, height: h, data })
}
+3 -10
View File
@@ -10,31 +10,24 @@ workspace = true
[dependencies]
craft-tiff = { workspace = true }
craft-raw = { workspace = true }
lightcraft-meta = { workspace = true }
lightcraft-raster = { workspace = true }
lightcraft-color = { workspace = true }
lightcraft-geom = { workspace = true }
serde = { workspace = true }
chrono = { workspace = true }
craft-crw = { workspace = true }
thiserror = { workspace = true }
rayon = { workspace = true }
miniz_oxide = { workspace = true }
zune-jpeg = { workspace = true }
zune-core = { workspace = true }
jpeg-encoder = { workspace = true }
jxl-oxide = { workspace = true, optional = true }
[features]
default = ["jxl"]
## JPEG XL compressed DNGs (DNG 1.7, compression 52546) via jxl-oxide (pure Rust, MIT OR Apache-2.0).
jxl = ["dep:jxl-oxide"]
craft-image-codecs = { workspace = true }
[dev-dependencies]
# tests record why they skip (`cargo xtask ci` lists the skips)
lightcraft-testkit = { workspace = true }
proptest = { workspace = true }
zune-jpegxl = { workspace = true }
zune-core = { workspace = true }
# Pinned CC0 corpus identities; not a product dependency.
sha2 = { version = "0.10", default-features = false, features = ["std"] }
# Peak-heap regression tests (tests/sr2_heap.rs); not a product dependency.
+1 -1
View File
@@ -24,7 +24,7 @@ impl RawImage {
/// and B; Bayer: `k` even, so that every block has the same layout)?
pub fn can_bin(&self, k: usize) -> bool {
let Some(cfa) = &self.cfa else { return false };
if k < 2 || self.cpp != 1 || (self.pixel_aspect - 1.0).abs() >= 0.01 || !cfa.valid() || (cfa.is_bayer() && !k.is_multiple_of(2)) {
if k < 2 || self.cpp != 1 || (self.pixel_aspect - 1.0).abs() >= 0.01 || !crate::cfa_valid(cfa) || (cfa.is_bayer() && !k.is_multiple_of(2)) {
return false;
}
// every window position relative to the pattern
+221
View File
@@ -0,0 +1,221 @@
//! The makers `craft-raw` decodes (DNG, Hasselblad, CRW, CR2, NEF / NRW, PEF, SRW, MRW, ERF, MEF, Kodak DCS), mapped
//! onto this crate's [`RawImage`]: the colour tags into LightCraft's colour types, and what the format layer leaves
//! to the developer added here:
//!
//! - [`Metadata`] from the file's Exif (a CRW, which has none, from its own records), with the developed size;
//! - DNG and Hasselblad samples stuck below the stated white level raised to it ([`RawImage::lift_clipped_samples`]);
//! - Epson ERF and Mamiya MEF, which record no white balance, get one estimated from their preview
//! ([`crate::wb_estimate`]); their header probe decodes the samples for it, as before;
//! - Nikon bodies whose files record no white-balance presets get LightCraft's built-in ones
//! ([`crate::kelvin_builtin`]).
use craft_tiff::{Tiff, tags as t};
use lightcraft_color::Xy;
use lightcraft_meta::{DateTime, Metadata};
use crate::{ColorData, Mat3, Mode, Orientation, RawFormat, RawImage, Rect, Result};
pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
let format = crate::probe(bytes);
// the white balance of these two is measured from the samples, so the probe decodes them too
let estimate_wb = matches!(format, Some(RawFormat::Erf | RawFormat::Mef));
let mut img = if mode == Mode::Full || estimate_wb {
let raw = craft_raw::decode(bytes)?;
let metadata = metadata(bytes, raw.format, &raw.camera, raw.info().developed_size());
image(raw, metadata)
} else {
let info = craft_raw::probe_info(bytes)?;
let metadata = metadata(bytes, info.format, &info.camera, info.developed_size());
header_image(info, metadata)
};
if estimate_wb && img.wb_multipliers.is_none() {
img.wb_multipliers = estimated_wb(bytes, &img);
}
if mode == Mode::Header {
img.data = craft_raw::RawData::U16(Vec::new());
}
finish(&mut img);
Ok(img)
}
pub(crate) fn decode_reduced(bytes: &[u8], min_long: usize) -> Result<Option<RawImage>> {
let Some(raw) = craft_raw::decode_reduced(bytes, min_long, &craft_raw::Limits::default())? else { return Ok(None) };
// the developed size of the whole picture, which the metadata reports whatever copy the samples come from
let full = craft_raw::probe_info(bytes)?;
let metadata = metadata(bytes, full.format, &full.camera, full.developed_size());
let mut img = image(raw, metadata);
finish(&mut img);
Ok(Some(img))
}
/// What LightCraft adds to every decoded file of these makers.
fn finish(img: &mut RawImage) {
// DNG writers state a white level the sensor may never reach; samples stuck at the real saturation point are
// raised to the white level so they count as clipped
if matches!(img.format, RawFormat::Dng | RawFormat::CfaTiff) {
img.lift_clipped_samples();
}
// a CRW's rotation is its ImageInfo record's, not an Exif tag's
if img.format == RawFormat::Crw {
img.metadata.orientation = Some(img.orientation);
}
if matches!(img.format, RawFormat::Nef | RawFormat::Nrw) && img.color.kelvin_presets.is_none() {
img.color.kelvin_presets = img.metadata.model.as_deref().and_then(|model| crate::kelvin_builtin::find(img.metadata.make.as_deref(), model));
}
}
/// The file's Exif as [`Metadata`], with `size` (the developed size) as its width and height. A CRW has no Exif:
/// its make, model and capture time come from its own records.
fn metadata(bytes: &[u8], format: RawFormat, camera: &craft_raw::Camera, size: (usize, usize)) -> Metadata {
let mut m = if format == RawFormat::Crw {
Metadata {
make: camera.make.clone(),
model: camera.model.clone(),
capture_time: camera.capture_unix.and_then(datetime_from_unix),
..Metadata::default()
}
} else {
// CR3 (ISO BMFF) and RAF (Fuji container) do not start with a TIFF header; lightcraft_meta::extract handles them.
// An MRW keeps its Exif TIFF in the `TTW` block.
match format {
RawFormat::Cr3 | RawFormat::Raf => lightcraft_meta::extract(bytes),
RawFormat::Mrw => lightcraft_meta::mrw::parse(bytes)
.and_then(|m| m.block(b"TTW"))
.and_then(|b| Tiff::parse(b).ok())
.as_ref()
.map(lightcraft_meta::from_tiff)
.unwrap_or_default(),
_ => Tiff::parse_with(bytes, &craft_tiff::ParseOptions { max_ifds: 256, ..Default::default() })
.ok()
.as_ref()
.map(lightcraft_meta::from_tiff)
.unwrap_or_default(),
}
};
m.width = Some(size.0 as u32);
m.height = Some(size.1 as u32);
m
}
/// Civil date-time from a CRW TimeStamp record's Unix seconds (the camera's local clock, no UTC offset; inverse of
/// [`DateTime::unix_seconds`]). Before 1970 or after 2200 is a garbage clock, not a capture time.
fn datetime_from_unix(t: i64) -> Option<DateTime> {
use chrono::{Datelike, Timelike};
let c = chrono::DateTime::from_timestamp(t, 0)?.naive_utc();
let dt = DateTime {
year: u16::try_from(c.year()).ok()?,
month: u8::try_from(c.month()).ok()?,
day: u8::try_from(c.day()).ok()?,
hour: u8::try_from(c.hour()).ok()?,
minute: u8::try_from(c.minute()).ok()?,
second: u8::try_from(c.second()).ok()?,
millis: 0,
offset_minutes: None,
precision: Default::default(),
};
((1970..=2200).contains(&dt.year)).then_some(dt)
}
fn orientation(o: craft_raw::Orientation) -> Orientation {
Orientation::from_exif(o.to_exif())
}
fn color(c: craft_raw::ColorData) -> ColorData {
let m = |p: [Option<craft_raw::Matrix3>; 2]| p.map(|m| m.map(Mat3));
ColorData {
illuminant: c.illuminant,
color_matrix: m(c.color_matrix),
forward_matrix: m(c.forward_matrix),
camera_calibration: m(c.camera_calibration),
analog_balance: c.analog_balance,
as_shot_neutral: c.as_shot_neutral,
as_shot_white_xy: c.as_shot_white_xy.map(|[x, y]| Xy::new(x, y)),
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())),
}
}
fn image(r: craft_raw::RawImage, metadata: Metadata) -> RawImage {
RawImage {
format: r.format,
width: r.width,
height: r.height,
cpp: r.cpp,
data: r.data,
cfa: r.cfa,
bits: r.bits,
black: r.black,
white: r.white,
active_area: r.active_area,
crop: r.crop,
orientation: orientation(r.orientation),
color: color(r.color),
wb_multipliers: r.wb_multipliers,
linearized: r.linearized,
pixel_aspect: r.pixel_aspect,
opcodes: r.opcodes,
metadata,
lens_metadata: r.lens_metadata,
}
}
/// An image without samples from a header probe; only [`RawImage::into_info`] looks at it.
fn header_image(i: craft_raw::RawInfo, metadata: Metadata) -> RawImage {
RawImage {
format: i.format,
width: i.width,
height: i.height,
cpp: i.cpp,
data: craft_raw::RawData::U16(Vec::new()),
cfa: i.cfa,
bits: i.bits,
black: Default::default(),
white: vec![65535.0],
active_area: i.active_area,
crop: i.crop,
orientation: orientation(i.orientation),
color: color(i.color),
wb_multipliers: i.wb_multipliers,
linearized: false,
pixel_aspect: i.pixel_aspect,
opcodes: i.opcodes,
metadata,
lens_metadata: i.lens_metadata,
}
}
/// The as-shot white balance of an ERF or MEF, from its preview's neutral pixels (an MEF's uncompressed RGB
/// preview, an ERF's JPEG), else grey world.
fn estimated_wb(bytes: &[u8], img: &RawImage) -> Option<[f32; 3]> {
let craft_raw::RawData::U16(data) = &img.data else { return None };
let (a, c) = (img.active_area, img.crop);
let crop = Rect::new(a.x.checked_add(c.x)?, a.y.checked_add(c.y)?, c.width, c.height);
let cfa = img.cfa.as_ref()?;
let frame = crate::wb_estimate::Frame { data, width: img.width, crop, cfa, black: &img.black, white: img.white_at(0) };
match (img.format == RawFormat::Mef).then(|| rgb_preview(bytes)).flatten() {
Some((px, pw, ph)) => crate::wb_estimate::as_shot_rgb(px, pw, ph, &frame),
None => crate::wb_estimate::as_shot(bytes, &frame),
}
}
/// The largest uncompressed 8-bit RGB sub-IFD of a TIFF (an MEF's preview): its pixels, width and height.
fn rgb_preview(bytes: &[u8]) -> Option<(&[u8], usize, usize)> {
let tiff = Tiff::parse(bytes).ok()?;
tiff.all_ifds()
.into_iter()
.filter_map(|i| {
let info = i.image().ok()?;
let ok = i.u16(t::PHOTOMETRIC) == Some(2)
&& i.u16(t::COMPRESSION).unwrap_or(1) == 1
&& i.u16(t::SAMPLES_PER_PIXEL) == Some(3)
&& i.u64s(t::BITS_PER_SAMPLE).is_some_and(|b| b.iter().all(|&v| v == 8));
let (w, h) = (info.width as usize, info.height as usize);
let chunks = info.chunks(bytes.len() as u64);
let [c] = chunks.as_slice() else { return None };
let px = craft_tiff::image::chunk_bytes(bytes, c)?;
(ok && px.len() >= w.checked_mul(h)?.checked_mul(3)?).then_some((px, w, h))
})
.max_by_key(|(_, w, h)| w * h)
}
+77 -3
View File
@@ -4,10 +4,12 @@
//! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the
//! hue/saturation map, look table and tone curve. Nothing here ships a profile.
use craft_tiff::{Ifd, ParseOptions, Tiff, tags as t};
use craft_tiff::{ByteOrder, Ifd, ParseOptions, Tiff, tags as t};
use lightcraft_color::Xy;
use crate::ColorData;
use crate::dng::color_data;
use crate::gaintable::GainTableMap;
use crate::profile::{HsvTable, ProfileLook, ToneCurve};
use crate::{ColorData, Mat3};
/// The magic number of a DNG camera profile file (`IIRC` / `MMCR`).
pub const DCP_MAGIC: u16 = 0x4352;
@@ -171,6 +173,78 @@ pub fn write_dcp(p: &DcpProfile) -> Result<Vec<u8>, DcpError> {
Ok(out)
}
// The colour tags a profile shares with DNG, read as DNG reads them (a DNG's own are read by `craft-raw`).
fn mat3(v: Option<Vec<f64>>) -> Option<Mat3> {
let v = v?;
if v.len() != 9 || v.iter().any(|x| !x.is_finite()) {
return None;
}
let m = Mat3([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]);
(m.determinant().abs() > 1e-12).then_some(m)
}
fn vec3(v: Option<Vec<f64>>) -> Option<[f64; 3]> {
let v = v?;
(v.len() == 3 && v.iter().all(|x| x.is_finite() && *x > 0.0)).then(|| [v[0], v[1], v[2]])
}
/// Colour tags: DNG puts them in IFD0, but some writers use the raw IFD; prefer the raw IFD.
/// `order` is the file's byte order (for the binary gain-table-map tags).
fn color_data(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ColorData {
let get = |tag: u16| raw.f64s(tag).or_else(|| ifd0.f64s(tag));
let geti = |tag: u16| raw.u16(tag).or_else(|| ifd0.u16(tag));
ColorData {
illuminant: [geti(t::CALIBRATION_ILLUMINANT_1).unwrap_or(0), geti(t::CALIBRATION_ILLUMINANT_2).unwrap_or(0)],
color_matrix: [mat3(get(t::COLOR_MATRIX_1)), mat3(get(t::COLOR_MATRIX_2))],
forward_matrix: [mat3(get(t::FORWARD_MATRIX_1)), mat3(get(t::FORWARD_MATRIX_2))],
camera_calibration: [mat3(get(t::CAMERA_CALIBRATION_1)), mat3(get(t::CAMERA_CALIBRATION_2))],
analog_balance: vec3(get(t::ANALOG_BALANCE)),
as_shot_neutral: vec3(get(t::AS_SHOT_NEUTRAL)),
as_shot_white_xy: get(t::AS_SHOT_WHITE_XY).filter(|v| v.len() == 2 && v[0] > 0.0 && v[1] > 0.0).map(|v| Xy::new(v[0], v[1])),
baseline_exposure: get(t::BASELINE_EXPOSURE).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0)
+ get(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0),
// DNG 1.7 BaselineSharpness (IFD 0 or the enhanced IFD); implausible values are ignored
baseline_sharpness: get(t::BASELINE_SHARPNESS).and_then(|v| v.first().copied()).filter(|v| v.is_finite() && *v > 0.0 && *v <= 16.0),
profile: profile_look(ifd0, raw, order),
kelvin_presets: None,
}
}
/// The profile look tags (`ProfileHueSatMap*`, `ProfileLookTable*`, `ProfileToneCurve`,
/// `ProfileGainTableMap*`); malformed ones are ignored. Like the colour tags, read from the raw IFD
/// first, else IFD 0.
fn profile_look(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ProfileLook {
let pick = |tag: u16| if raw.contains(tag) { raw } else { ifd0 };
let table = |dims: u16, data: u16, enc: u16| {
let ifd = pick(dims);
let dims = ifd.u64s(dims)?;
let data = ifd.f64s(data)?;
HsvTable::from_tags(&dims, &data, ifd.u64s(enc).and_then(|v| v.first().copied()).unwrap_or(0))
};
ProfileLook {
hue_sat_map: [
table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_1, t::PROFILE_HUE_SAT_MAP_ENCODING),
table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_2, t::PROFILE_HUE_SAT_MAP_ENCODING),
],
look_table: table(t::PROFILE_LOOK_TABLE_DIMS, t::PROFILE_LOOK_TABLE_DATA, t::PROFILE_LOOK_TABLE_ENCODING),
tone_curve: pick(t::PROFILE_TONE_CURVE).f64s(t::PROFILE_TONE_CURVE).and_then(|v| ToneCurve::from_tag(&v)),
gain_table_map: gain_table_map(ifd0, raw, order),
}
}
/// The gain table map (DNG 1.7 precedence): `ProfileGainTableMap2` from IFD 0 (the embedded
/// camera profile), else from the raw IFD; else `ProfileGainTableMap` from the raw IFD (where DNG
/// 1.6 put it, and where Apple writes it), else from IFD 0 (where DNG 1.7 says it was meant to be).
/// A malformed tag falls through to the next one.
fn gain_table_map(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> Option<GainTableMap> {
let parse = |ifd: &Ifd, tag: u16| ifd.bytes(tag).and_then(|b| GainTableMap::parse(b, order, tag == t::PROFILE_GAIN_TABLE_MAP_2));
parse(ifd0, t::PROFILE_GAIN_TABLE_MAP_2)
.or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP_2))
.or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP))
.or_else(|| parse(ifd0, t::PROFILE_GAIN_TABLE_MAP))
}
#[cfg(test)]
mod tests {
use super::*;
-551
View File
@@ -1,551 +0,0 @@
//! DNG (Adobe Digital Negative Specification 1.7): raw IFD selection, pixel data (via [`crate::tiffraw`]),
//! linearization, black/white levels, active area, default crop, CFA description, colour tags, opcode lists.
use crate::gaintable::GainTableMap;
use crate::profile::{HsvTable, ProfileLook, ToneCurve};
use crate::tiffraw::{Packing, read_image_in};
use crate::{BlackLevel, Cfa, ColorData, Mat3, Mode, RawData, RawError, RawFormat, RawImage, Rect, Result, opcodes};
use craft_tiff::tags::{self as t, photometric};
use craft_tiff::{ByteOrder, Ifd, Tiff};
use lightcraft_color::Xy;
use lightcraft_geom::Orientation;
/// The main raw IFD: full-resolution (NewSubfileType 0) CFA or LinearRaw image with the most pixels.
pub(crate) fn raw_ifd(tiff: &Tiff) -> Option<&Ifd> {
tiff.all_ifds()
.into_iter()
.filter(|i| i.u32(t::NEW_SUBFILE_TYPE).unwrap_or(0) == 0)
.filter(|i| matches!(i.u16(t::PHOTOMETRIC), Some(photometric::CFA) | Some(photometric::LINEAR_RAW)))
.max_by_key(|i| i.u64(t::IMAGE_WIDTH).unwrap_or(0).saturating_mul(i.u64(t::IMAGE_LENGTH).unwrap_or(0)))
}
/// Undo the DNG 1.7 row/column interleave, which reorders the stored raster without changing its
/// size: with `RowInterleaveFactor = n` the rows are stored as `n` consecutive fields, field `g`
/// holding rows `g, g+n, g+2n, …` of the image (and likewise for columns).
///
/// The tag counts fields, not a divisor of the raster — see [`field_map`] — so a dimension the
/// factor does not divide is decoded, with the trailing fields short, rather than refused.
///
/// Left alone, a file like this decodes as `n × m` scaled-down copies of the scene, one per
/// field, with the CFA pattern then read across permuted samples — so it is not merely misplaced,
/// it is the wrong colour as well (`RowInterleaveFactor = ColumnInterleaveFactor = 2` is what DNG
/// 1.7 JPEG XL files from Adobe's converter carry).
fn deinterleave(data: &mut RawData, w: usize, h: usize, cpp: usize, rows: usize, cols: usize) -> Result<()> {
if rows <= 1 && cols <= 1 {
return Ok(());
}
// The spec sets no bound on the value (it is only "the number of interleaved fields"); this
// caps the field table we build and the permutation, and rejects a hostile tag.
if !(1..=16).contains(&rows) || !(1..=16).contains(&cols) {
return Err(RawError::Unsupported(format!("interleave factors {rows} × {cols}")));
}
let (map_r, map_c) = (field_map(h, rows), field_map(w, cols));
let dest = |r: usize, c: usize| map_r[r] * w + map_c[c];
match data {
RawData::U16(v) => permute(v, w, h, cpp, dest),
RawData::F32(v) => permute(v, w, h, cpp, dest),
}
}
/// The stored-line → image-line map for one axis: a factor of `n` splits `len` lines into `n`
/// interleaved fields, field `g` holding lines `g, g+n, g+2n, …`. The fields are stored
/// consecutively, so field `g` starts at stored line `offs[g]` and its `k`-th line is image line
/// `g + n*k`. Field sizes follow from the round-robin split — field `g` has `ceil((len - g) / n)`
/// lines — so when `n` does not divide `len` the trailing fields are short, and when `n` exceeds
/// `len` the trailing fields are empty.
fn field_map(len: usize, n: usize) -> Vec<usize> {
let mut offs = Vec::with_capacity(n + 1);
let mut acc = 0usize;
for g in 0..=n {
offs.push(acc);
if g < n && g < len {
acc += (len - 1 - g) / n + 1;
}
}
let mut map = vec![0usize; len];
for g in 0..n {
for (k, i) in (offs[g]..offs[g + 1]).enumerate() {
map[i] = g + n * k;
}
}
map
}
/// Move every `cpp`-sample pixel of `v` from its stored position to `dest(r, c)`, the image
/// position it belongs at. The permutation is not its own inverse, so it needs a destination.
fn permute<T: Copy + Default, F: Fn(usize, usize) -> usize>(v: &mut Vec<T>, w: usize, h: usize, cpp: usize, dest: F) -> Result<()> {
let n = w.checked_mul(h).and_then(|n| n.checked_mul(cpp)).ok_or_else(|| RawError::Corrupt("image too large".into()))?;
if v.len() != n {
return Err(RawError::Corrupt("mosaic size does not match the image".into()));
}
let mut out = vec![T::default(); n];
for r in 0..h {
for c in 0..w {
let (from, to) = ((r * w + c) * cpp, dest(r, c) * cpp);
out[to..to + cpp].copy_from_slice(&v[from..from + cpp]);
}
}
*v = out;
Ok(())
}
fn mat3(v: Option<Vec<f64>>) -> Option<Mat3> {
let v = v?;
if v.len() != 9 || v.iter().any(|x| !x.is_finite()) {
return None;
}
let m = Mat3([[v[0], v[1], v[2]], [v[3], v[4], v[5]], [v[6], v[7], v[8]]]);
(m.determinant().abs() > 1e-12).then_some(m)
}
fn vec3(v: Option<Vec<f64>>) -> Option<[f64; 3]> {
let v = v?;
(v.len() == 3 && v.iter().all(|x| x.is_finite() && *x > 0.0)).then(|| [v[0], v[1], v[2]])
}
/// Colour tags: DNG puts them in IFD0, but some writers use the raw IFD; prefer the raw IFD.
/// `order` is the file's byte order (for the binary gain-table-map tags).
pub(crate) fn color_data(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ColorData {
let get = |tag: u16| raw.f64s(tag).or_else(|| ifd0.f64s(tag));
let geti = |tag: u16| raw.u16(tag).or_else(|| ifd0.u16(tag));
ColorData {
illuminant: [geti(t::CALIBRATION_ILLUMINANT_1).unwrap_or(0), geti(t::CALIBRATION_ILLUMINANT_2).unwrap_or(0)],
color_matrix: [mat3(get(t::COLOR_MATRIX_1)), mat3(get(t::COLOR_MATRIX_2))],
forward_matrix: [mat3(get(t::FORWARD_MATRIX_1)), mat3(get(t::FORWARD_MATRIX_2))],
camera_calibration: [mat3(get(t::CAMERA_CALIBRATION_1)), mat3(get(t::CAMERA_CALIBRATION_2))],
analog_balance: vec3(get(t::ANALOG_BALANCE)),
as_shot_neutral: vec3(get(t::AS_SHOT_NEUTRAL)),
as_shot_white_xy: get(t::AS_SHOT_WHITE_XY).filter(|v| v.len() == 2 && v[0] > 0.0 && v[1] > 0.0).map(|v| Xy::new(v[0], v[1])),
baseline_exposure: get(t::BASELINE_EXPOSURE).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0)
+ get(t::BASELINE_EXPOSURE_OFFSET).and_then(|v| v.first().copied()).filter(|v| v.is_finite()).unwrap_or(0.0),
// DNG 1.7 BaselineSharpness (IFD 0 or the enhanced IFD); implausible values are ignored
baseline_sharpness: get(t::BASELINE_SHARPNESS).and_then(|v| v.first().copied()).filter(|v| v.is_finite() && *v > 0.0 && *v <= 16.0),
profile: profile_look(ifd0, raw, order),
kelvin_presets: None,
}
}
/// The profile look tags (`ProfileHueSatMap*`, `ProfileLookTable*`, `ProfileToneCurve`,
/// `ProfileGainTableMap*`); malformed ones are ignored. Like the colour tags, read from the raw IFD
/// first, else IFD 0.
pub(crate) fn profile_look(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ProfileLook {
let pick = |tag: u16| if raw.contains(tag) { raw } else { ifd0 };
let table = |dims: u16, data: u16, enc: u16| {
let ifd = pick(dims);
let dims = ifd.u64s(dims)?;
let data = ifd.f64s(data)?;
HsvTable::from_tags(&dims, &data, ifd.u64s(enc).and_then(|v| v.first().copied()).unwrap_or(0))
};
ProfileLook {
hue_sat_map: [
table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_1, t::PROFILE_HUE_SAT_MAP_ENCODING),
table(t::PROFILE_HUE_SAT_MAP_DIMS, t::PROFILE_HUE_SAT_MAP_DATA_2, t::PROFILE_HUE_SAT_MAP_ENCODING),
],
look_table: table(t::PROFILE_LOOK_TABLE_DIMS, t::PROFILE_LOOK_TABLE_DATA, t::PROFILE_LOOK_TABLE_ENCODING),
tone_curve: pick(t::PROFILE_TONE_CURVE).f64s(t::PROFILE_TONE_CURVE).and_then(|v| ToneCurve::from_tag(&v)),
gain_table_map: gain_table_map(ifd0, raw, order),
}
}
/// The gain table map (DNG 1.7 precedence): `ProfileGainTableMap2` from IFD 0 (the embedded
/// camera profile), else from the raw IFD; else `ProfileGainTableMap` from the raw IFD (where DNG
/// 1.6 put it, and where Apple writes it), else from IFD 0 (where DNG 1.7 says it was meant to be).
/// A malformed tag falls through to the next one.
fn gain_table_map(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> Option<GainTableMap> {
let parse = |ifd: &Ifd, tag: u16| ifd.bytes(tag).and_then(|b| GainTableMap::parse(b, order, tag == t::PROFILE_GAIN_TABLE_MAP_2));
parse(ifd0, t::PROFILE_GAIN_TABLE_MAP_2)
.or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP_2))
.or_else(|| parse(raw, t::PROFILE_GAIN_TABLE_MAP))
.or_else(|| parse(ifd0, t::PROFILE_GAIN_TABLE_MAP))
}
pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
decode_as(bytes, mode, RawFormat::Dng)
}
/// Whether a TIFF that is not a DNG describes a raw image the way DNG does: a full-resolution CFA IFD
/// and DNG's own statement of the white balance (`AsShotNeutral`, in IFD0 or the raw IFD), in a coding
/// [`decode_as`] reads: uncompressed, or lossless JPEG whose scan header the lossless decoder accepts.
/// Such files (Hasselblad 3FR and FFF) carry no DNG version tag, so they are not DNGs, but nothing else
/// in them needs a maker-specific reader. Without the white-balance tag nothing in the file says how
/// to read its colour, and the file stays an undecodable raw.
pub(crate) fn is_plain_cfa_tiff(tiff: &Tiff, bytes: &[u8]) -> bool {
let Some(raw) = raw_ifd(tiff) else { return false };
if !raw.contains(t::AS_SHOT_NEUTRAL) && !tiff.ifds.first().is_some_and(|i| i.contains(t::AS_SHOT_NEUTRAL)) {
return false;
}
let Ok(info) = raw.image() else { return false };
if info.samples_per_pixel != 1 || !(1..=16).contains(&info.bits()) || info.sample_format == 3 {
return false;
}
match info.compression {
t::compression::NONE => true,
t::compression::JPEG => info
.chunks(bytes.len() as u64)
.first()
.and_then(|c| craft_tiff::image::chunk_bytes(bytes, c))
.is_some_and(|src| crate::ljpeg::frame_info(src).is_ok()),
_ => false,
}
}
/// [`decode`] for the TIFF-based raws that follow the DNG layout without being DNGs (`format` says
/// which). They differ in one respect: when the raw IFD states no `CFAPattern`, the layout is RGGB
/// anchored at the sensor origin.
pub(crate) fn decode_as(bytes: &[u8], mode: Mode, format: RawFormat) -> Result<RawImage> {
let tiff = Tiff::parse(bytes)?;
let raw = raw_ifd(&tiff).ok_or_else(|| RawError::Corrupt("DNG without a raw image IFD".into()))?;
decode_ifd(bytes, &tiff, raw, raw, mode, format)
}
/// The smallest reduced-resolution copy of a DNG's LinearRaw image whose default crop still has a long edge of
/// `min_long` px: Lightroom keeps 256, 512 and 2048 px copies beside the full image of its HDR and panorama
/// merges, so a thumbnail decodes a 512 px copy instead of a 24k × 7k image (about 19 s). Only a copy that the main
/// image's tags describe as well: same samples per pixel and aspect ratio (within 1 %), and a main image without
/// opcode lists, a linearization table or black-level deltas (all in full-size pixel coordinates).
fn reduced_ifd<'a>(tiff: &'a Tiff, main: &Ifd, min_long: usize) -> Option<&'a Ifd> {
if main.u16(t::PHOTOMETRIC) != Some(photometric::LINEAR_RAW) {
return None;
}
let full_size_tags =
[t::OPCODE_LIST_1, t::OPCODE_LIST_2, t::OPCODE_LIST_3, t::LINEARIZATION_TABLE, t::BLACK_LEVEL_DELTA_H, t::BLACK_LEVEL_DELTA_V];
if full_size_tags.iter().any(|&tag| main.contains(tag)) {
return None;
}
let (mw, mh) = (main.u64(t::IMAGE_WIDTH)?, main.u64(t::IMAGE_LENGTH)?);
if mw == 0 || mh == 0 {
return None;
}
let crop_long = match main.f64s(t::DEFAULT_CROP_SIZE).as_deref() {
Some([w, h]) if w.is_finite() && h.is_finite() && *w >= 1.0 && *h >= 1.0 => w.max(*h).min(mw.max(mh) as f64),
_ => mw.max(mh) as f64,
};
let cpp = main.u16(t::SAMPLES_PER_PIXEL).unwrap_or(1);
tiff.all_ifds()
.into_iter()
.filter(|i| i.u32(t::NEW_SUBFILE_TYPE) == Some(1) && i.u16(t::PHOTOMETRIC) == Some(photometric::LINEAR_RAW))
.filter(|i| i.u16(t::SAMPLES_PER_PIXEL).unwrap_or(1) == cpp)
.filter_map(|i| {
let (w, h) = (i.u64(t::IMAGE_WIDTH)?, i.u64(t::IMAGE_LENGTH)?);
let (a, b) = (w.checked_mul(mh)?, h.checked_mul(mw)?);
let same_aspect = w > 0 && h > 0 && a.abs_diff(b).saturating_mul(100) <= a;
let covers = crop_long * w as f64 / mw as f64 >= min_long as f64;
(same_aspect && covers && w < mw && h < mh).then_some((i, w))
})
.min_by_key(|&(_, w)| w)
.map(|(i, _)| i)
}
/// [`decode`] from the smallest reduced-resolution copy of the raw image that covers `min_long` ([`reduced_ifd`]):
/// the main image's levels, colour and metadata, its active area and default crop scaled to the copy. `None` when the
/// file keeps no such copy.
pub(crate) fn decode_reduced(bytes: &[u8], min_long: usize) -> Result<Option<RawImage>> {
let tiff = Tiff::parse(bytes)?;
let Some(main) = raw_ifd(&tiff) else { return Ok(None) };
let Some(small) = reduced_ifd(&tiff, main, min_long) else { return Ok(None) };
decode_ifd(bytes, &tiff, small, main, Mode::Full, RawFormat::Dng).map(Some)
}
/// [`decode_as`] of the samples in `pixels`, described by the raw IFD `main`: the same IFD, or (see
/// [`decode_reduced`]) a reduced-resolution copy of it, whose own level tags win and whose geometry is `main`'s
/// scaled to its size.
fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, format: RawFormat) -> Result<RawImage> {
let ifd0 = &tiff.ifds[0];
let raw = main;
// GoPro's GPR: a DNG whose raw data is VC-5 coded, which is not decoded (yet). Named here, before
// the generic "TIFF compression 9" of the chunk decoder. Header mode still describes the file
// (a GPR has no embedded preview, and a library keeps the photo with this reason shown, as it
// does for any file whose pixels fail to decode, rather than refusing to import it).
if mode == Mode::Full
&& let Some(c) = pixels.u16(t::COMPRESSION).filter(|&c| c == t::compression::VC5)
{
return Err(RawError::Unsupported(format!("DNG compression {c} (GoPro VC-5) is not decoded yet")));
}
let info = pixels.image()?;
let (w, h, cpp) = (info.width as usize, info.height as usize, info.samples_per_pixel as usize);
// one sample (CFA or monochrome), RGB or four colours; two are neither and can't be developed (issue #1511)
if !matches!(cpp, 1 | 3 | 4) {
return Err(RawError::Unsupported(format!("{cpp} samples per pixel")));
}
let mut data = read_image_in(mode, bytes, &info, tiff.order, Packing::Msb)?;
let bits = info.bits() as u32;
// DNG 1.7 interleaved storage: the raster is a permutation of the mosaic, so undo it before
// anything reads a sample as a pixel.
if mode == Mode::Full {
let factor = |tag| pixels.u16(tag).map(usize::from).unwrap_or(1);
deinterleave(&mut data, w, h, cpp, factor(t::ROW_INTERLEAVE_FACTOR), factor(t::COLUMN_INTERLEAVE_FACTOR))?;
}
// linearization table (integer data only)
let mut linearized = false;
if let (RawData::U16(v), Some(table)) = (&mut data, pixels.u64s(t::LINEARIZATION_TABLE).filter(|t| !t.is_empty())) {
let table: Vec<u16> = table.iter().map(|&x| x.min(65535) as u16).collect();
let last = table.len() - 1;
v.iter_mut().for_each(|s| *s = table[(*s as usize).min(last)]);
linearized = true;
}
// a reduced copy's own levels, where it states them
let levels = |tag| if pixels.contains(tag) { pixels } else { raw };
let float = matches!(data, RawData::F32(_));
let default_white = if float { 1.0 } else { ((1u64 << bits.min(16)) - 1) as f32 };
let mut white: Vec<f32> =
levels(t::WHITE_LEVEL).f64s(t::WHITE_LEVEL).unwrap_or_default().into_iter().map(|v| v as f32).filter(|v| *v > 0.0).collect();
if white.is_empty() {
white = vec![default_white];
}
// No sensor records NaN or infinity, so such a float sample is damage. Left in, it turns into NaN in demosaic
// arithmetic and spreads; NaN and −∞ read as black (0), +∞ as the white level (a clipped highlight). Finite
// samples, negative or above white included, are kept as stored.
if let RawData::F32(v) = &mut data {
for (i, s) in v.iter_mut().enumerate() {
if !s.is_finite() {
*s = if *s > 0.0 { white.get(i % cpp).or(white.first()).copied().unwrap_or(default_white) } else { 0.0 };
}
}
}
let dim = levels(t::BLACK_LEVEL).u64s(t::BLACK_LEVEL_REPEAT_DIM).unwrap_or_default();
let (br, bc) = match dim.as_slice() {
[r, c] if (1..=16).contains(r) && (1..=16).contains(c) => (*r as usize, *c as usize),
_ => (1, 1),
};
// (a FLOAT / DOUBLE tag can hold NaN or infinity: such a level reads as 0, in its place)
let level = |v: f64| Some(v as f32).filter(|v| v.is_finite()).unwrap_or(0.0);
let mut values: Vec<f32> = levels(t::BLACK_LEVEL).f64s(t::BLACK_LEVEL).unwrap_or_default().into_iter().map(level).collect();
if values.len() != br * bc * cpp {
values = vec![values.first().copied().unwrap_or(0.0)];
}
let (br, bc) = if values.len() == 1 { (1, 1) } else { (br, bc) };
let floats = |tag| raw.f64s(tag).unwrap_or_default().into_iter().map(level).collect::<Vec<f32>>();
let black =
BlackLevel { repeat_rows: br, repeat_cols: bc, values, delta_h: floats(t::BLACK_LEVEL_DELTA_H), delta_v: floats(t::BLACK_LEVEL_DELTA_V) };
// geometry in the main image's pixels (a reduced copy's is scaled below)
let (full_w, full_h) = if std::ptr::eq(pixels, raw) {
(w, h)
} else {
(raw.u64(t::IMAGE_WIDTH).unwrap_or(0) as usize, raw.u64(t::IMAGE_LENGTH).unwrap_or(0) as usize)
};
if full_w == 0 || full_h == 0 {
return Err(RawError::Corrupt("raw image IFD without a size".into()));
}
let active_area = match raw.u64s(t::ACTIVE_AREA).as_deref() {
Some([top, left, bottom, right]) if bottom > top && right > left && (*bottom as usize) <= full_h && (*right as usize) <= full_w => {
Rect::new(*left as usize, *top as usize, (*right - *left) as usize, (*bottom - *top) as usize)
}
_ => Rect::new(0, 0, full_w, full_h),
};
let crop = match (raw.f64s(t::DEFAULT_CROP_ORIGIN).as_deref(), raw.f64s(t::DEFAULT_CROP_SIZE).as_deref()) {
(Some([x, y]), Some([cw, ch])) if *cw >= 1.0 && *ch >= 1.0 && *x >= 0.0 && *y >= 0.0 => {
Rect::new(x.round() as usize, y.round() as usize, cw.round() as usize, ch.round() as usize).clipped(active_area.width, active_area.height)
}
_ => Rect::new(0, 0, active_area.width, active_area.height),
};
// the developed size, which the metadata reports whatever copy the samples come from
let developed = (crop.width, crop.height);
let (active_area, crop) = if (full_w, full_h) == (w, h) {
(active_area, crop)
} else {
let (sx, sy) = (w as f64 / full_w as f64, h as f64 / full_h as f64);
let scale = |r: Rect| {
let (x, y) = ((r.x as f64 * sx).round() as usize, (r.y as f64 * sy).round() as usize);
let (x1, y1) = (((r.x + r.width) as f64 * sx).round() as usize, ((r.y + r.height) as f64 * sy).round() as usize);
Rect::new(x, y, x1.saturating_sub(x).max(1), y1.saturating_sub(y).max(1))
};
let area = scale(active_area).clipped(w, h);
(area, scale(crop).clipped(area.width, area.height))
};
let cfa = if info.photometric == photometric::CFA {
if raw.u16(t::CFA_LAYOUT).unwrap_or(1) != 1 {
return Err(RawError::Unsupported("non-rectangular CFA layout".into()));
}
let dim = raw.u64s(t::CFA_REPEAT_PATTERN_DIM).unwrap_or_else(|| vec![2, 2]);
let (rows, cols) = match dim.as_slice() {
[r, c] if (1..=16).contains(r) && (1..=16).contains(c) => (*r as usize, *c as usize),
_ => return Err(RawError::Corrupt("bad CFARepeatPatternDim".into())),
};
// a TIFF that is not a DNG may leave the layout out: RGGB from the sensor origin
let assumed = [0u8, 1, 1, 2];
let pat = match raw.bytes(t::CFA_PATTERN_EP) {
Some(p) => p,
None if format != RawFormat::Dng && (rows, cols) == (2, 2) => &assumed,
None => return Err(RawError::Corrupt("missing CFAPattern".into())),
};
if pat.len() != rows * cols {
return Err(RawError::Corrupt("CFAPattern size mismatch".into()));
}
let planes = raw.bytes(t::CFA_PLANE_COLOR).map(|b| b.to_vec()).unwrap_or_else(|| vec![0, 1, 2]);
let pattern: Vec<u8> = pat
.iter()
.map(|c| planes.iter().position(|p| p == c).map(|i| i as u8).filter(|&i| i < 3))
.collect::<Option<_>>()
.ok_or_else(|| RawError::Unsupported("CFA with more than three colours".into()))?;
if cpp != 1 {
return Err(RawError::Unsupported("CFA data with several samples per pixel".into()));
}
// the tag is anchored at the top-left of the ActiveArea (DNG spec); `RawImage::cfa` is anchored at the
// sensor origin (the crop to the active area shifts it back), so move the anchor out by the area's offset
// (LightCraft's own DNGs from before the writer followed the spec carry the sensor-origin pattern; they are marked by
// a bare "LightCraft" Software tag, the writer now says [`crate::dngwrite::SOFTWARE`], and keep their original reading)
let at_origin = Cfa { width: cols, height: rows, pattern };
let legacy_writer = [raw, ifd0].iter().any(|i| i.string(t::SOFTWARE).as_deref().map(str::trim) == Some("LightCraft"));
Some(if legacy_writer { at_origin } else { at_origin.shifted(cols - active_area.x % cols, rows - active_area.y % rows) })
} else {
None
};
let opcode_list = |tag| raw.bytes(tag).map(opcodes::parse_list).unwrap_or_default();
let opcodes =
crate::OpcodeLists { list1: opcode_list(t::OPCODE_LIST_1), list2: opcode_list(t::OPCODE_LIST_2), list3: opcode_list(t::OPCODE_LIST_3) };
let mut metadata = lightcraft_meta::from_tiff(tiff);
metadata.width = Some(developed.0 as u32);
metadata.height = Some(developed.1 as u32);
let img = RawImage {
format,
width: w,
height: h,
cpp,
data,
cfa,
bits,
black,
white,
active_area,
crop,
orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)),
color: color_data(ifd0, raw, tiff.order),
wb_multipliers: None,
linearized,
pixel_aspect: default_scale_aspect(raw.f64s(t::DEFAULT_SCALE).as_deref()),
opcodes,
metadata,
lens_metadata: Default::default(),
};
img.validate_for(mode)?;
Ok(img)
}
/// Pixel height over width from `DefaultScale` (horizontal, vertical): only a clear 1.5 to 4 ratio counts (the rows stretch; a wider-than-tall pixel is left alone).
fn default_scale_aspect(scale: Option<&[f64]>) -> f32 {
match scale {
Some([h, v]) if *h > 0.0 && *v > 0.0 && (1.5..=4.0).contains(&(v / h)) => (v / h) as f32,
_ => 1.0,
}
}
#[cfg(test)]
mod tests {
#[test]
fn default_scale_makes_tall_pixels() {
assert_eq!(default_scale_aspect(Some(&[1.0, 2.0])), 2.0);
assert_eq!(default_scale_aspect(Some(&[1.0, 1.0])), 1.0);
assert_eq!(default_scale_aspect(Some(&[2.0, 1.0])), 1.0);
assert_eq!(default_scale_aspect(Some(&[1.0, 1.2])), 1.0);
assert_eq!(default_scale_aspect(None), 1.0);
}
use super::*;
/// Store `image` the way DNG 1.7 interleaves it: row `r` of the image is written to stored row
/// `(r % rows) * (h / rows) + r / rows`, and columns likewise. This is the inverse of
/// [`deinterleave`]'s destination map for a raster the factor divides, i.e. what a writer
/// produces (the short-trailing-field case is covered by the hand-written fixtures below).
fn interleave(image: &[u16], w: usize, h: usize, rows: usize, cols: usize) -> Vec<u16> {
let (gh, gw) = (h / rows, w / cols);
let mut out = vec![0u16; w * h];
for r in 0..h {
for c in 0..w {
out[((r % rows) * gh + r / rows) * w + (c % cols) * gw + c / cols] = image[r * w + c];
}
}
out
}
fn samples(d: &RawData) -> Vec<u16> {
match d {
RawData::U16(v) => v.clone(),
RawData::F32(_) => Vec::new(),
}
}
/// The image `image` laid out in stored order, given the image line each stored row and column
/// holds. Written out by hand from the tag's plain reading, so it does not share a formula with
/// the code under test.
fn store(image: &[u16], w: usize, rows_img: &[usize], cols_img: &[usize]) -> Vec<u16> {
let mut out = vec![0u16; image.len()];
for (sr, &ir) in rows_img.iter().enumerate() {
for (sc, &ic) in cols_img.iter().enumerate() {
out[sr * w + sc] = image[ir * w + ic];
}
}
out
}
#[test]
fn deinterleaves_an_interleaved_raster() {
// 3×3 rather than 2×2 on purpose: the 2×2 permutation is its own inverse, so a 2×2 fixture
// would pass even with the direction of the permutation reversed. This is the shape a DNG
// 1.7 file caught in the wild carried (JPEG XL, `RowInterleaveFactor`/`ColumnInterleaveFactor`
// both 2) — its real-file ground truth is that it renders bit-identical to its
// non-interleaved twin.
let (w, h, rows, cols) = (12, 9, 3, 3);
let image: Vec<u16> = (0..w * h).map(|i| i as u16).collect();
let mut data = RawData::U16(interleave(&image, w, h, rows, cols));
assert_ne!(samples(&data), image, "the fixture has to actually be permuted");
deinterleave(&mut data, w, h, 1, rows, cols).unwrap();
assert_eq!(samples(&data), image);
// 2×2 as well, the shape Adobe's converter writes.
let (w2, h2) = (12, 8);
let image2: Vec<u16> = (0..w2 * h2).map(|i| i as u16).collect();
let mut two = RawData::U16(interleave(&image2, w2, h2, 2, 2));
deinterleave(&mut two, w2, h2, 1, 2, 2).unwrap();
assert_eq!(samples(&two), image2);
}
#[test]
fn deinterleave_pins_the_field_direction() {
// Hand-computed ground truth for the tag's plain reading ("field g holds lines g, g+n,
// g+2n, …"). The 3×3 test above round-trips against a helper written from the same reading
// of the tag, so it fixes consistency but not the direction; and a 2×2 fixture cannot tell
// the two directions apart, being its own inverse. These maps are written out literally so
// a reversed permutation fails here. 3 row fields of h = 9 start at stored rows 0, 3, 6 and
// hold image rows [0,3,6,1,4,7,2,5,8]; 2 column fields of w = 4 give [0,2,1,3].
let (w, h) = (4, 9);
let image: Vec<u16> = (0..(w * h) as u16).collect();
let mut data = RawData::U16(store(&image, w, &[0, 3, 6, 1, 4, 7, 2, 5, 8], &[0, 2, 1, 3]));
assert_ne!(samples(&data), image, "the fixture has to actually be permuted");
deinterleave(&mut data, w, h, 1, 3, 2).unwrap();
assert_eq!(samples(&data), image);
}
#[test]
fn deinterleaves_a_raster_the_factor_does_not_divide() {
// The spec fixes the number of fields, not that the size is a multiple of it: h = 7 over 3
// row fields is 3 + 2 + 2 (the round-robin split), so field 0 starts at stored row 0 holding
// image rows 0, 3, 6; field 1 at stored row 3 holding 1, 4; field 2 at stored row 5 holding
// 2, 5. Columns: w = 5 over 2 fields is 3 + 2 → image columns [0,2,4,1,3].
let (w, h) = (5, 7);
let image: Vec<u16> = (0..(w * h) as u16).collect();
let mut data = RawData::U16(store(&image, w, &[0, 3, 6, 1, 4, 2, 5], &[0, 2, 4, 1, 3]));
assert_ne!(samples(&data), image, "the fixture has to actually be permuted");
deinterleave(&mut data, w, h, 1, 3, 2).unwrap();
assert_eq!(samples(&data), image);
}
#[test]
fn deinterleave_is_a_no_op_at_one_and_refuses_a_hostile_factor() {
let image: Vec<u16> = (0..48).collect();
let mut plain = RawData::U16(image.clone());
deinterleave(&mut plain, 8, 6, 1, 1, 1).unwrap();
assert_eq!(samples(&plain), image);
// A hostile factor is an error, not a scrambled image.
let mut hostile = RawData::U16(image);
assert!(deinterleave(&mut hostile, 8, 6, 1, 1 << 20, 1).is_err());
}
}
+4 -4
View File
@@ -357,10 +357,10 @@ pub fn write_dng(raw: &RawImage, opts: &DngWriteOptions) -> Result<Vec<u8>> {
}
}
}
let mut out = Vec::new();
jpeg_encoder::Encoder::new(&mut out, quality)
.encode(&buf, tile as u16, tile as u16, jpeg_encoder::ColorType::Rgb)
.map(|()| out)
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::<Result<_>>()?;
+15 -292
View File
@@ -40,144 +40,32 @@
//! `MapPointsV` / `MapPointsH` is below 256 (their product is at most [`MAX_TABLES`]), so swapped
//! it is at least 2^24 and the size checks reject it. We write in the file's byte order.
use craft_tiff::ByteOrder;
pub use craft_raw::gaintable::GainTableMap;
use serde::{Deserialize, Serialize};
/// Upper bound on `MapPointsV × MapPointsH` (Apple uses 6 × 8).
const MAX_TABLES: usize = 1 << 12;
/// Upper bound on the total number of gains (Apple: 6 × 8 × 257 = 12 336).
const MAX_GAINS: usize = 1 << 22;
/// A parsed `ProfileGainTableMap` / `ProfileGainTableMap2`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GainTableMap {
/// Tables vertically (`MapPointsV`) and horizontally (`MapPointsH`), and points per table (`MapPointsN`).
pub points_v: usize,
pub points_h: usize,
pub points_n: usize,
/// Grid spacing and origin, relative to the active area's height (`_v`) and width (`_h`).
pub spacing_v: f64,
pub spacing_h: f64,
pub origin_v: f64,
pub origin_h: f64,
/// Weights of (R, G, B, min, max) for the table input.
pub weights: [f32; 5],
/// Exponent for the table input (1.0 for the version-1 tag).
pub gamma: f32,
/// `points_v × points_h × points_n` gains, row-major with the table points innermost. Integer
/// storage has already been mapped onto `GainMin..=GainMax`. Mapping before interpolating is
/// the same as mapping after, because the mapping is linear.
pub gains: Vec<f32>,
}
impl GainTableMap {
/// Parse the tag's bytes from a file in byte order `order` (`version2`: `ProfileGainTableMap2`):
/// in that order, else big-endian (see the module docs). `None` when malformed.
pub fn parse(b: &[u8], order: ByteOrder, version2: bool) -> Option<GainTableMap> {
Self::parse_in(b, order, version2).or_else(|| if order == ByteOrder::Big { None } else { Self::parse_in(b, ByteOrder::Big, version2) })
}
/// Parse the tag's bytes with every multi-byte field in `order`.
fn parse_in(b: &[u8], order: ByteOrder, version2: bool) -> Option<GainTableMap> {
let take = |o: usize, n: usize| b.get(o..o.checked_add(n)?);
let u32_at = |o: usize| take(o, 4).and_then(|s| s.try_into().ok()).map(|a: [u8; 4]| order.u32(a));
let f32_at = |o: usize| u32_at(o).map(f32::from_bits);
let f64_at = |o: usize| take(o, 8).and_then(|s| s.try_into().ok()).map(|a: [u8; 8]| f64::from_bits(order.u64(a)));
let (points_v, points_h) = (u32_at(0)? as usize, u32_at(4)? as usize);
let (spacing_v, spacing_h, origin_v, origin_h) = (f64_at(8)?, f64_at(16)?, f64_at(24)?, f64_at(32)?);
let points_n = u32_at(40)? as usize;
let mut weights = [0f32; 5];
for (i, w) in weights.iter_mut().enumerate() {
*w = f32_at(44 + 4 * i)?;
}
let tables = points_v.checked_mul(points_h).filter(|&t| t > 0 && t <= MAX_TABLES)?;
let count = tables.checked_mul(points_n).filter(|&c| c > 0 && c <= MAX_GAINS)?;
let spacing_ok = |s: f64, points: usize| s.is_finite() && (s > 0.0 || points == 1);
if !spacing_ok(spacing_v, points_v)
|| !spacing_ok(spacing_h, points_h)
|| !origin_v.is_finite()
|| !origin_h.is_finite()
|| !weights.iter().all(|w| w.is_finite())
{
return None;
}
let (header, data_type, gamma, gain_min, gain_max) =
if version2 { (80, u32_at(64)?, f32_at(68)?, f32_at(72)?, f32_at(76)?) } else { (64, 3, 1.0, 0.0, 1.0) };
if !(0.25..=4.0).contains(&gamma) {
return None;
}
let width = match data_type {
0 => 1,
1 | 2 => 2,
3 => 4,
_ => return None,
};
if b.len() != count.checked_mul(width)?.checked_add(header)? {
return None;
}
let data = b.get(header..)?;
let scaled = |q: f32, max: f32| gain_min + q / max * (gain_max - gain_min);
let gains: Vec<f32> = match data_type {
0 => data.iter().map(|&q| scaled(q as f32, 255.0)).collect(),
1 => data.as_chunks::<2>().0.iter().map(|c| scaled(order.u16(*c) as f32, 65535.0)).collect(),
2 => data.as_chunks::<2>().0.iter().map(|c| crate::unpack::f16_to_f32(order.u16(*c))).collect(),
_ => data.as_chunks::<4>().0.iter().map(|c| f32::from_bits(order.u32(*c))).collect(),
};
if gains.len() != count || !gains.iter().all(|g| g.is_finite() && *g >= 0.0) {
return None;
}
Some(GainTableMap { points_v, points_h, points_n, spacing_v, spacing_h, origin_v, origin_h, weights, gamma, gains })
}
/// The tag's bytes in `order`: version 1 (DNG 1.6, f32 gains) when the gamma is 1, else
/// version 2 with f32 gains. Returns `(version2, bytes)`.
pub fn to_bytes(&self, order: ByteOrder) -> (bool, Vec<u8>) {
let version2 = self.gamma != 1.0;
let mut out = Vec::with_capacity(80 + 4 * self.gains.len());
let u32b = |v: u32| match order {
ByteOrder::Big => v.to_be_bytes(),
ByteOrder::Little => v.to_le_bytes(),
};
let f64b = |v: f64| match order {
ByteOrder::Big => v.to_be_bytes(),
ByteOrder::Little => v.to_le_bytes(),
};
let dim = |v: usize| u32b(u32::try_from(v).unwrap_or(u32::MAX));
out.extend_from_slice(&dim(self.points_v));
out.extend_from_slice(&dim(self.points_h));
for v in [self.spacing_v, self.spacing_h, self.origin_v, self.origin_h] {
out.extend_from_slice(&f64b(v));
}
out.extend_from_slice(&dim(self.points_n));
for w in self.weights {
out.extend_from_slice(&u32b(w.to_bits()));
}
if version2 {
// DataType 3 (f32); GainMin/GainMax are ignored for float data
for v in [3, self.gamma.to_bits(), 0f32.to_bits(), 1f32.to_bits()] {
out.extend_from_slice(&u32b(v));
}
}
for g in &self.gains {
out.extend_from_slice(&u32b(g.to_bits()));
}
(version2, out)
}
/// Applying a gain table map (the map, and reading and writing its tag, is `craft-raw`'s).
pub trait GainTableMapApply {
/// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM)
/// colour after the baseline exposure. 1.0 for a map that can't be evaluated. For many pixels,
/// [`Self::evaluator`] once and [`GainEval::gain`] per pixel.
fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32;
/// The map ready to evaluate per pixel, or `None` when it can't be (inconsistent sizes).
fn evaluator(&self) -> Option<GainEval<'_>>;
}
/// Applying the map (see the module docs). Index arithmetic saturates and every lookup is
/// checked: the fields are public and the struct is deserializable, so a hand-built or damaged map
/// must not overflow or panic, whatever it holds.
impl GainTableMap {
impl GainTableMapApply for GainTableMap {
/// The gain at relative active-area position (`x`, `y`) for `p`, a linear ProPhoto (RIMM)
/// colour after the baseline exposure. 1.0 for a map that can't be evaluated. For many pixels,
/// [`Self::evaluator`] once and [`GainEval::gain`] per pixel.
pub fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 {
fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 {
self.evaluator().map_or(1.0, |e| e.gain(p, x, y))
}
/// The map ready to evaluate per pixel, or `None` when it can't be (inconsistent sizes).
pub fn evaluator(&self) -> Option<GainEval<'_>> {
fn evaluator(&self) -> Option<GainEval<'_>> {
let n = self.points_n;
let tables = self.points_v.saturating_mul(self.points_h);
if n == 0 || tables == 0 || tables.saturating_mul(n) != self.gains.len() {
@@ -234,7 +122,7 @@ pub struct GainEval<'a> {
}
impl GainEval<'_> {
/// [`GainTableMap::gain`].
/// [`GainTableMapApply::gain`].
#[inline]
pub fn gain(&self, p: [f32; 3], x: f64, y: f64) -> f32 {
let m = self.map;
@@ -274,7 +162,7 @@ fn input(m: &GainTableMap, p: [f32; 3]) -> f32 {
if m.gamma == 1.0 { x } else { x.powf(m.gamma) }
}
/// Where the pixels of a developed source sit in the raw's active area, for [`GainTableMap::gain`].
/// Where the pixels of a developed source sit in the raw's active area, for [`GainTableMapApply::gain`].
/// The source is the default crop of the active area (`rect`, relative to the active area),
/// then EXIF-`orientation`ed. Resolution independent.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
@@ -298,172 +186,6 @@ impl SourcePlacement {
mod tests {
use super::*;
/// Tag bytes: the header fields (`v2`: data type, gamma, gain min, gain max), then `data`.
fn tag(
order: ByteOrder,
dims: [u32; 3],
spacing: [f64; 2],
origin: [f64; 2],
weights: [f32; 5],
v2: Option<(u32, f32, f32, f32)>,
data: &[u8],
) -> Vec<u8> {
let be = order == ByteOrder::Big;
let u = |v: u32| if be { v.to_be_bytes() } else { v.to_le_bytes() };
let d = |v: f64| if be { v.to_be_bytes() } else { v.to_le_bytes() };
let mut b = Vec::new();
b.extend_from_slice(&u(dims[0]));
b.extend_from_slice(&u(dims[1]));
for v in [spacing[0], spacing[1], origin[0], origin[1]] {
b.extend_from_slice(&d(v));
}
b.extend_from_slice(&u(dims[2]));
for w in weights {
b.extend_from_slice(&u(w.to_bits()));
}
if let Some((dt, gamma, min, max)) = v2 {
for v in [dt, gamma.to_bits(), min.to_bits(), max.to_bits()] {
b.extend_from_slice(&u(v));
}
}
b.extend_from_slice(data);
b
}
fn floats(order: ByteOrder, g: &[f32]) -> Vec<u8> {
g.iter().flat_map(|v| if order == ByteOrder::Big { v.to_be_bytes() } else { v.to_le_bytes() }).collect()
}
const GREEN: [f32; 5] = [0.0, 1.0, 0.0, 0.0, 0.0];
/// 2 × 2 tables of N = 4 points: table (r, c) = base · [1, 2, 3, 4] with base 1, 2, 3, 4.
fn grid() -> Vec<f32> {
(0..4).flat_map(|t| (1..=4).map(move |i| (t + 1) as f32 * i as f32)).collect()
}
#[test]
fn version_2_storage_types_and_gamma() {
let order = ByteOrder::Little;
let v2 = |dt: u32, gamma: f32, data: &[u8]| {
GainTableMap::parse(&tag(order, [1, 1, 4], [1.0, 1.0], [0.0, 0.0], GREEN, Some((dt, gamma, 0.5, 2.5)), data), order, true)
};
// u8: 0 → GainMin, 255 → GainMax
let m = v2(0, 1.0, &[0, 51, 255, 255]).unwrap();
let want = [0.5, 0.9, 2.5, 2.5];
assert!(m.gains.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6), "{:?}", m.gains);
// u16
let m = v2(1, 1.0, &[0, 0, 0xff, 0xff, 0, 0, 0xff, 0xff]).unwrap();
assert_eq!(m.gains, vec![0.5, 2.5, 0.5, 2.5]);
// f16 ignores GainMin/GainMax: 1.0, 2.0, 0.5, 0
let m = v2(2, 1.0, &[0x00, 0x3c, 0x00, 0x40, 0x00, 0x38, 0, 0]).unwrap();
assert_eq!(m.gains, vec![1.0, 2.0, 0.5, 0.0]);
// f32 with gamma 2
let m = v2(3, 2.0, &floats(order, &[1.0, 2.0, 3.0, 4.0])).unwrap();
assert_eq!((m.gains.clone(), m.gamma), (vec![1.0, 2.0, 3.0, 4.0], 2.0));
// unknown data type, gamma out of range, size for another type: ignored
assert!(v2(4, 1.0, &[0; 4]).is_none());
assert!(v2(0, 0.1, &[0; 4]).is_none());
assert!(v2(0, 5.0, &[0; 4]).is_none());
assert!(v2(1, 1.0, &[0; 4]).is_none());
// negative integer range
let neg = tag(order, [1, 1, 4], [1.0, 1.0], [0.0, 0.0], GREEN, Some((0, 1.0, -1.0, 1.0)), &[0; 4]);
assert!(GainTableMap::parse(&neg, order, true).is_none());
}
#[test]
fn malformed_tags_are_rejected() {
let order = ByteOrder::Big;
let good = tag(order, [2, 2, 4], [0.5, 0.5], [0.25, 0.25], GREEN, None, &floats(order, &grid()));
assert!(GainTableMap::parse(&good, order, false).is_some());
// every truncation (and an extra byte)
for n in 0..good.len() {
assert!(GainTableMap::parse(&good[..n], order, false).is_none(), "{n} bytes");
}
let mut long = good.clone();
long.push(0);
assert!(GainTableMap::parse(&long, order, false).is_none());
// the wrong byte order reads absurd dimensions
assert!(GainTableMap::parse_in(&good, ByteOrder::Little, false).is_none());
// read as version 2 the header is too short for the data
assert!(GainTableMap::parse(&good, order, true).is_none());
let bad = |dims: [u32; 3], spacing: [f64; 2], origin: [f64; 2], gains: &[f32]| {
GainTableMap::parse(&tag(order, dims, spacing, origin, GREEN, None, &floats(order, gains)), order, false)
};
let mut g = grid();
g[5] = f32::NAN;
assert!(bad([2, 2, 4], [0.5, 0.5], [0.0, 0.0], &g).is_none(), "NaN gain");
g[5] = -1.0;
assert!(bad([2, 2, 4], [0.5, 0.5], [0.0, 0.0], &g).is_none(), "negative gain");
g[5] = f32::INFINITY;
assert!(bad([2, 2, 4], [0.5, 0.5], [0.0, 0.0], &g).is_none(), "infinite gain");
assert!(bad([2, 2, 4], [0.0, 0.5], [0.0, 0.0], &grid()).is_none(), "zero spacing");
assert!(bad([2, 2, 4], [0.5, f64::NAN], [0.0, 0.0], &grid()).is_none(), "NaN spacing");
assert!(bad([2, 2, 4], [0.5, 0.5], [f64::INFINITY, 0.0], &grid()).is_none(), "infinite origin");
assert!(bad([0, 2, 4], [0.5, 0.5], [0.0, 0.0], &[]).is_none(), "no rows");
assert!(bad([1, 1, 0], [0.5, 0.5], [0.0, 0.0], &[]).is_none(), "no points");
// huge dimensions (whose product overflows or exceeds the cap) are rejected before allocating
assert!(bad([u32::MAX, u32::MAX, u32::MAX], [0.5, 0.5], [0.0, 0.0], &grid()).is_none());
assert!(bad([4096, 4096, 1], [0.5, 0.5], [0.0, 0.0], &grid()).is_none());
assert!(bad([1, 1, u32::MAX], [0.5, 0.5], [0.0, 0.0], &grid()).is_none());
// a single table needs no spacing
assert!(bad([1, 1, 2], [0.0, 0.0], [0.0, 0.0], &[1.0, 2.0]).is_some());
let mut w = GREEN;
w[3] = f32::NAN;
assert!(GainTableMap::parse(&tag(order, [1, 1, 1], [1.0, 1.0], [0.0, 0.0], w, None, &floats(order, &[1.0])), order, false).is_none());
}
/// The payload is read in the file's byte order, else big-endian; a little-endian payload in
/// a big-endian file is malformed.
#[test]
fn byte_order_is_the_files_with_a_big_endian_fallback() {
use ByteOrder::{Big, Little};
let v1 = |o: ByteOrder| tag(o, [2, 2, 4], [0.5, 0.5], [0.25, 0.25], GREEN, None, &floats(o, &grid()));
let v2 = |o: ByteOrder| {
let mut gains = Vec::new();
for q in [0u16, 0x1234, 0xffff, 0x8000] {
gains.extend_from_slice(&if o == Big { q.to_be_bytes() } else { q.to_le_bytes() });
}
tag(o, [1, 1, 4], [1.0, 1.0], [0.0, 0.0], GREEN, Some((1, 2.0, 0.5, 2.5)), &gains)
};
let (want1, want2) = (GainTableMap::parse_in(&v1(Big), Big, false).unwrap(), GainTableMap::parse_in(&v2(Big), Big, true).unwrap());
assert_eq!(want1.gains, grid());
assert_eq!((want2.gains[0], want2.gains[2], want2.gamma), (0.5, 2.5, 2.0));
// in the file's order
assert_eq!(GainTableMap::parse(&v1(Little), Little, false).as_ref(), Some(&want1));
assert_eq!(GainTableMap::parse(&v2(Little), Little, true).as_ref(), Some(&want2));
assert_eq!(GainTableMap::parse(&v1(Big), Big, false).as_ref(), Some(&want1));
// a big-endian payload in a little-endian file: the fallback
assert_eq!(GainTableMap::parse(&v1(Big), Little, false).as_ref(), Some(&want1));
assert_eq!(GainTableMap::parse(&v2(Big), Little, true).as_ref(), Some(&want2));
// no little-endian fallback in a big-endian file
assert!(GainTableMap::parse(&v1(Little), Big, false).is_none());
assert!(GainTableMap::parse(&v2(Little), Big, true).is_none());
// whatever the grid, a read in the wrong order fails the size checks
for dims in [[1, 1, 1], [6, 8, 257], [48, 64, 2], [255, 16, 1], [256, 16, 1], [1, 4096, 1]] {
for (o, wrong) in [(Big, Little), (Little, Big)] {
let g = vec![1.0; dims.iter().product::<u32>() as usize];
let b = tag(o, dims, [0.5, 0.5], [0.0, 0.0], GREEN, None, &floats(o, &g));
assert!(GainTableMap::parse_in(&b, o, false).is_some(), "{dims:?}");
assert!(GainTableMap::parse_in(&b, wrong, false).is_none(), "{dims:?} read {wrong:?}");
}
}
}
#[test]
fn writes_what_it_reads() {
for order in [ByteOrder::Big, ByteOrder::Little] {
let m =
GainTableMap::parse(&tag(order, [2, 2, 4], [0.5, 0.5], [0.25, 0.25], GREEN, None, &floats(order, &grid())), order, false).unwrap();
let (v2, b) = m.to_bytes(order);
assert!(!v2);
assert_eq!(GainTableMap::parse(&b, order, false).unwrap(), m);
let g = GainTableMap { gamma: 2.0, ..m };
let (v2, b) = g.to_bytes(order);
assert!(v2);
assert_eq!(GainTableMap::parse(&b, order, true).unwrap(), g);
}
}
fn map(dims: [usize; 3], spacing: [f64; 2], origin: [f64; 2], weights: [f32; 5], gains: Vec<f32>) -> GainTableMap {
let [points_v, points_h, points_n] = dims;
let [spacing_v, spacing_h] = spacing;
@@ -548,6 +270,7 @@ mod tests {
/// the cost of [`GainEval::gain`] per pixel on a real file's map.
#[cfg(test)]
mod bench {
use super::GainTableMapApply;
#[test]
#[ignore]
fn gain_throughput() {
+1 -1
View File
@@ -140,7 +140,7 @@ impl RawImage {
let black = self.black.mean();
let RawData::U16(d) = &mut self.data else { return 0 };
if self.cpp != 1
|| !cfa.valid()
|| !crate::cfa_valid(&cfa)
|| w.checked_mul(h) != Some(d.len())
|| a.width < 4 * MARGIN
|| a.height < 4 * MARGIN
-574
View File
@@ -1,574 +0,0 @@
//! JPEG XL tiles and strips (DNG 1.7 compression 52546), decoded with `jxl-oxide` (pure Rust).
//!
//! Per the DNG 1.7 specification a JPEG XL chunk holds N-bit unsigned integers (8 ≤ N ≤ 16) or 16-bit
//! floats, in 1 or 3 planes, as either a bare codestream or an ISO-BMFF container; jxl-oxide reads both.
//!
//! jxl-oxide renders every channel as `f32`: integer samples come out as `value / (2^bits − 1)` with
//! `bits` the codestream's own declared bit depth, so scaling back by that maximum and rounding gives the
//! stored integers exactly (an `f32` holds `v / 65535` to far better than half a code value) — lossless
//! tiles decode bit-exactly, whatever bit depth the encoder declared relative to the IFD's
//! `BitsPerSample`. Float samples are returned as decoded.
//!
//! Lossless (non-XYB) tiles are rendered in the codestream's own colour encoding, which is the identity,
//! keeping the values in the raw IFD's sample space. Lossy (XYB) tiles are decoded by jxl-oxide to linear
//! sRGB primaries; the codestream's declared encoding is then restored by hand: its primaries with a
//! plain 3×3 matrix, then its transfer curve. A grey (single-plane) lossy tile is still coded as three
//! XYB channels; its declared grey encoding is restored as the luminance (CIE Y, D65 white) of the
//! linear sRGB output, then its transfer curve. The samples of a lossy tile mean what they would in a
//! lossless one with the same header, so a declared transfer curve is part of the stored values, not a
//! display hint. Lightroom Classic's lossy LinearRaw DNGs (Convert to DNG with lossy compression) store
//! perceptually shaped samples, label them with the sRGB curve and linearise them with a cubic
//! `MapPolynomial` per plane in `OpcodeList2`. Measured against Lightroom's own preview of two such
//! files, the polynomial applied to the samples in the declared encoding tracks Lightroom's rendering
//! (midtone log-log slope 0.98 and 1.38, about 1 EV apart); applied to the decoder's linear output it is
//! 3.6 EV too dark. We never let jxl-oxide convert to the declared encoding itself:
//! that step gamut-maps and clips to [0, 1], which destroys raw values above 1.0 (a `WhiteLevel` of
//! 32768 puts them far above) and desaturates. The result is the sample space the DNG's `WhiteLevel`
//! refers to, up to the codec's loss, and can exceed 1.0 or dip below 0.
//!
//! Every tile is decoded with wide (32-bit) modular buffers. A lossy tile whose header sets
//! `modular_16bit_buffers` can still carry values that need more than 16 bits; the narrow buffers then
//! fail with `InvalidAnsStream` or `UnexpectedEof`.
use crate::tiffraw::ChunkPx;
use crate::{RawError, Result};
use jxl_oxide::color::{ColourEncoding, ColourSpace, Primaries, TransferFunction, WhitePoint};
use jxl_oxide::frame::Encoding;
use jxl_oxide::image::BitDepth;
use jxl_oxide::{AllocTracker, EnumColourEncoding, JxlImage, JxlThreadPool, RenderingIntent};
/// Decoder memory (bytes) allowed per sample of a tile. jxl-oxide 0.12 peaks at about three 32-bit
/// buffers per sample: measured ≤ 10.3 bytes for lossless (modular) tiles and ≤ 13.5 bytes per
/// colour sample for lossy (VarDCT) ones, photon noise included.
const BYTES_PER_SAMPLE: usize = 16;
/// Fixed decoder overhead on top (headers, entropy-coding tables, group metadata): under 10 KiB
/// on a 16 × 16 tile.
const MARGIN_BYTES: usize = 64 << 10;
/// Linear sRGB primaries with a D65 white point (the space jxl-oxide decodes XYB to) and the matrix that
/// takes a linear colour in it to the codestream's declared primaries (row-major, D65 white point).
type Matrix = [[f64; 3]; 3];
const D65: [f64; 2] = [0.3127, 0.3290];
const SRGB: [[f64; 2]; 3] = [[0.640, 0.330], [0.300, 0.600], [0.150, 0.060]];
const BT2100: [[f64; 2]; 3] = [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]];
const P3: [[f64; 2]; 3] = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]];
fn inverse(m: Matrix) -> Matrix {
let c =
|i: usize, j: usize| m[(i + 1) % 3][(j + 1) % 3] * m[(i + 2) % 3][(j + 2) % 3] - m[(i + 1) % 3][(j + 2) % 3] * m[(i + 2) % 3][(j + 1) % 3];
let det = m[0][0] * c(0, 0) + m[0][1] * c(0, 1) + m[0][2] * c(0, 2);
let mut out = [[0.0; 3]; 3];
for (i, row) in out.iter_mut().enumerate() {
for (j, v) in row.iter_mut().enumerate() {
*v = c(j, i) / det;
}
}
out
}
fn mul(a: Matrix, b: Matrix) -> Matrix {
let mut out = [[0.0; 3]; 3];
for (i, row) in out.iter_mut().enumerate() {
for (j, v) in row.iter_mut().enumerate() {
*v = (0..3).map(|k| a[i][k] * b[k][j]).sum();
}
}
out
}
/// Linear RGB → XYZ for primaries `p` (xy) and the D65 white point.
fn rgb_to_xyz(p: [[f64; 2]; 3]) -> Matrix {
let xyz = |[x, y]: [f64; 2]| [x / y, 1.0, (1.0 - x - y) / y];
let cols = [xyz(p[0]), xyz(p[1]), xyz(p[2])];
let prim = [[cols[0][0], cols[1][0], cols[2][0]], [1.0, 1.0, 1.0], [cols[0][2], cols[1][2], cols[2][2]]];
let w = xyz(D65);
let inv = inverse(prim);
let s: [f64; 3] = std::array::from_fn(|i| (0..3).map(|k| inv[i][k] * w[k]).sum());
std::array::from_fn(|i| std::array::from_fn(|j| prim[i][j] * s[j]))
}
/// A declared transfer curve, applied to linear values (linear → coded). Mirrored for negative values
/// and not clipped above 1.0, so lossy undershoot and raw values above white survive.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Curve {
Linear,
/// IEC 61966-2-1 (sRGB).
Srgb,
/// ITU-R BT.709.
Bt709,
/// A pure power: coded = linear^exponent.
Power(f32),
}
impl Curve {
fn encode(self, v: f32) -> f32 {
let a = v.abs();
let e = match self {
Curve::Linear => return v,
Curve::Srgb if a <= 0.003_130_8 => 12.92 * a,
Curve::Srgb => 1.055 * a.powf(1.0 / 2.4) - 0.055,
Curve::Bt709 if a < 0.018 => 4.5 * a,
Curve::Bt709 => 1.099 * a.powf(0.45) - 0.099,
Curve::Power(p) => a.powf(p),
};
e.copysign(v)
}
}
/// How a chunk is rendered by jxl-oxide.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Output {
/// In the codestream's own colour encoding (non-XYB: the identity).
AsCoded,
/// XYB (lossy) data: linear sRGB primaries from the decoder, then `matrix` to the declared
/// primaries (`None` when those are sRGB's), then the declared transfer `curve`.
FromXyb { matrix: Option<[[f32; 3]; 3]>, curve: Curve },
}
/// Decide how to render a chunk from its header: whether it is XYB-coded, the declared colour
/// encoding and the intensity target. Lossy data is only accepted when the declared encoding is an RGB
/// one (three planes) or a grey one (one plane) with a D65 white point and an SDR transfer curve (linear, sRGB, BT.709 or a power: what raw DNG
/// writers signal) and no HDR tone mapping would apply, otherwise the samples cannot be restored
/// faithfully.
fn output_for(xyb: bool, encoding: &ColourEncoding, intensity_target: f32, planes: usize) -> Result<Output> {
if !xyb {
return Ok(Output::AsCoded);
}
let unsupported = |what: &str| RawError::Unsupported(format!("lossy JPEG XL tile with {what}"));
let ColourEncoding::Enum(e) = encoding else {
return Err(unsupported("an ICC profile instead of a colour encoding"));
};
// a single plane is declared grey, three are declared RGB (the header's grey flag is the colour space)
let grey = planes == 1;
if grey && e.colour_space != ColourSpace::Grey {
return Err(unsupported("a single colour plane that is not declared grey"));
}
if !grey && e.colour_space != ColourSpace::Rgb {
return Err(unsupported("a declared encoding that is not RGB"));
}
let curve = match e.tf {
TransferFunction::Linear => Curve::Linear,
TransferFunction::Srgb => Curve::Srgb,
TransferFunction::Bt709 => Curve::Bt709,
TransferFunction::Dci => Curve::Power(1.0 / 2.6),
// as jxl-oxide reads it: a codestream's gamma is the encoding exponent (×1e7) with `inverted`
TransferFunction::Gamma { g, inverted } => {
let g = g as f32 / 1e7;
Curve::Power(if inverted { g } else { 1.0 / g })
}
TransferFunction::Pq | TransferFunction::Hlg => return Err(unsupported("an HDR transfer curve (PQ or HLG)")),
TransferFunction::Unknown => return Err(unsupported("an unknown transfer curve")),
};
if let Curve::Power(p) = curve
&& !(p.is_finite() && p > 0.0)
{
return Err(unsupported("an invalid gamma"));
}
if e.white_point != WhitePoint::D65 {
return Err(unsupported("a white point other than D65"));
}
if intensity_target > 255.0 {
return Err(unsupported("an intensity target above 255 nits"));
}
if grey {
// a grey encoding has no primaries, only the white point: its single plane is the luminance (CIE Y)
// of the decoder's linear sRGB, which is the row of sRGB → XYZ that gives Y. The rows of the
// matrix are all that row; only the first is used for one plane.
let y = rgb_to_xyz(SRGB)[1].map(|v| v as f32);
return Ok(Output::FromXyb { matrix: Some([y; 3]), curve });
}
let primaries = match e.primaries {
Primaries::Srgb => return Ok(Output::FromXyb { matrix: None, curve }),
Primaries::Bt2100 => BT2100,
Primaries::P3 => P3,
Primaries::Custom { red, green, blue } => [red, green, blue].map(|c| c.as_float().map(f64::from)),
};
if primaries.iter().any(|p| p[1] <= 0.0) {
return Err(unsupported("invalid primaries"));
}
let m = mul(inverse(rgb_to_xyz(primaries)), rgb_to_xyz(SRGB));
if m.iter().flatten().any(|v| !v.is_finite()) {
return Err(unsupported("degenerate primaries"));
}
Ok(Output::FromXyb { matrix: Some(m.map(|r| r.map(|v| v as f32))), curve })
}
fn corrupt(e: impl std::fmt::Display) -> RawError {
RawError::Corrupt(format!("JPEG XL tile: {e}"))
}
/// Parse a chunk's headers (no pixel decoding) and check them against the chunk it must fill:
/// nominal `cw × ch`, or the part of it inside the image `vw × vh` (edge tiles), `cpp` colour planes,
/// a sample type matching the IFD. Returns the decoder and the codestream's integer maximum (0 for float).
#[allow(clippy::too_many_arguments)]
fn open(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp: usize, bits: u32, float: bool) -> Result<(JxlImage, f32, Output)> {
if !matches!(cpp, 1 | 3) {
return Err(RawError::Unsupported(format!("JPEG XL with {cpp} samples per pixel")));
}
if float && bits != 16 || !float && !(8..=16).contains(&bits) {
return Err(RawError::Unsupported(format!("JPEG XL with {bits}-bit {} samples", if float { "float" } else { "integer" })));
}
// The decoder's memory is bounded by the tile itself: a codestream that needs more (extra
// channels, layers, …) fails to decode instead of allocating what its header asks for.
let pixels = cw.saturating_mul(ch);
let budget = |planes: usize| pixels.saturating_mul(planes).saturating_mul(BYTES_PER_SAMPLE);
let tracker = AllocTracker::with_limit(budget(cpp).saturating_add(MARGIN_BYTES));
let mut img = JxlImage::builder()
.pool(JxlThreadPool::none()) // chunks are already decoded in parallel
.force_wide_buffers(true) // see the module documentation
.alloc_tracker(tracker.clone())
.read(std::io::Cursor::new(src))
.map_err(corrupt)?;
// lossy (VarDCT) decoding always works on three colour channels, even for a grey tile
if cpp == 1 && img.frame_header(0).is_some_and(|f| f.encoding == Encoding::VarDct) {
tracker.expand_limit(budget(2));
}
let header = img.image_header();
let (jw, jh) = (img.width() as usize, img.height() as usize);
if (jw, jh) != (cw, ch) && (jw, jh) != (vw, vh) {
return Err(RawError::Corrupt(format!("JPEG XL tile is {jw}×{jh}, expected {cw}×{ch} (or {vw}×{vh} at the image edge)")));
}
if header.metadata.orientation != 1 {
return Err(RawError::Corrupt("JPEG XL tile with a non-identity orientation".into()));
}
let planes = if header.metadata.grayscale() { 1 } else { 3 };
if planes != cpp {
return Err(RawError::Corrupt(format!("JPEG XL tile has {planes} colour planes, the IFD {cpp} samples per pixel")));
}
let max = match header.metadata.bit_depth {
BitDepth::IntegerSample { bits_per_sample } if !float && (1..=16).contains(&bits_per_sample) => ((1u32 << bits_per_sample) - 1) as f32,
BitDepth::FloatSample { .. } if float => 0.0,
d => return Err(RawError::Corrupt(format!("JPEG XL tile sample type {d:?} does not match the IFD"))),
};
let output = output_for(header.metadata.xyb_encoded, &header.metadata.colour_encoding, header.metadata.tone_mapping.intensity_target, planes)?;
if matches!(output, Output::FromXyb { .. }) {
img.request_color_encoding(EnumColourEncoding::srgb_linear(RenderingIntent::Relative));
}
Ok((img, max, output))
}
/// Check the first chunk's headers ([`open`]) without decoding pixels (header-only probing).
#[allow(clippy::too_many_arguments)]
pub(crate) fn check(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp: usize, bits: u32, float: bool) -> Result<()> {
open(src, cw, ch, vw, vh, cpp, bits, float).map(|_| ())
}
/// Decode one chunk into `cw × ch × cpp` samples (row-major, interleaved); a chunk coded at its
/// in-image size `vw × vh` fills the top-left of that, the rest stays 0.
#[allow(clippy::too_many_arguments)]
pub(crate) fn decode(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp: usize, bits: u32, float: bool) -> Result<ChunkPx> {
let (img, max, output) = open(src, cw, ch, vw, vh, cpp, bits, float)?;
if img.num_loaded_keyframes() == 0 {
return Err(corrupt("no complete frame"));
}
let render = img.render_frame(0).map_err(corrupt)?;
let fb = render.image_all_channels();
let (jw, jh, fc) = (fb.width(), fb.height(), fb.channels());
if jw == 0 || jh == 0 || jw > cw || jh > ch || fc < cpp {
return Err(corrupt(format!("rendered {jw}×{jh}×{fc}, expected {cw}×{ch}×{cpp}")));
}
let n = cw.saturating_mul(ch).saturating_mul(cpp);
let rows = fb.buf().chunks_exact(jw * fc);
// lossy data: restore the declared primaries and transfer curve (see the module documentation)
let (matrix, curve) = match output {
Output::FromXyb { matrix, curve } => (matrix, curve),
Output::AsCoded => (None, Curve::Linear),
};
let restore = |s: &[f32], d: &mut [f32]| {
match matrix {
Some(m) => {
for (d, row) in d.iter_mut().zip(&m) {
*d = row[0] * s[0] + row[1] * s[1] + row[2] * s[2];
}
}
None => d.copy_from_slice(&s[..cpp]),
}
if curve != Curve::Linear {
d.iter_mut().for_each(|v| *v = curve.encode(*v));
}
};
Ok(if float {
let mut out = vec![0f32; n];
for (dst, src) in out.chunks_exact_mut(cw * cpp).zip(rows) {
for (d, s) in dst.chunks_exact_mut(cpp).zip(src.chunks_exact(fc)) {
restore(s, d);
}
}
ChunkPx::F32(out)
} else {
let mut out = vec![0u16; n];
let mut px = [0f32; 3];
for (dst, src) in out.chunks_exact_mut(cw * cpp).zip(rows) {
for (d, s) in dst.chunks_exact_mut(cpp).zip(src.chunks_exact(fc)) {
restore(s, &mut px[..cpp]);
// `as` saturates (NaN → 0): lossy overshoot clips to the integer range
d.iter_mut().zip(&px).for_each(|(d, s)| *d = (s * max).round() as u16);
}
}
ChunkPx::U16(out)
})
}
#[cfg(test)]
mod tests {
use super::*;
use jxl_oxide::color::Customxy;
fn linear(primaries: Primaries) -> ColourEncoding {
ColourEncoding::Enum(EnumColourEncoding {
colour_space: ColourSpace::Rgb,
white_point: WhitePoint::D65,
primaries,
tf: TransferFunction::Linear,
rendering_intent: RenderingIntent::Perceptual,
})
}
fn matrix(o: Output) -> [[f32; 3]; 3] {
match o {
Output::FromXyb { matrix: Some(m), .. } => m,
other => panic!("expected a matrix, got {other:?}"),
}
}
#[test]
fn data_that_is_not_xyb_is_rendered_as_coded() {
// lossless tiles: whatever the header declares, the decoder must not convert anything
for e in
[linear(Primaries::Srgb), linear(Primaries::Bt2100), ColourEncoding::Enum(EnumColourEncoding::srgb_gamma22(RenderingIntent::Relative))]
{
assert_eq!(output_for(false, &e, 255.0, 3).unwrap(), Output::AsCoded);
assert_eq!(output_for(false, &e, 10_000.0, 1).unwrap(), Output::AsCoded);
}
}
#[test]
fn lossy_data_with_srgb_primaries_needs_no_matrix() {
assert_eq!(output_for(true, &linear(Primaries::Srgb), 255.0, 3).unwrap(), Output::FromXyb { matrix: None, curve: Curve::Linear });
}
#[test]
fn lossy_grey_data_is_the_luminance_in_the_declared_curve() {
// Lightroom Classic's merged monochrome LinearRaw DNGs: one plane, declared grey with a linear
// (16-bit float) or an sRGB (16-bit integer) curve
let grey = |tf| {
let mut e = EnumColourEncoding::srgb_linear(RenderingIntent::Perceptual);
e.colour_space = ColourSpace::Grey;
e.tf = tf;
output_for(true, &ColourEncoding::Enum(e), 255.0, 1).unwrap()
};
let Output::FromXyb { matrix: Some(m), curve: Curve::Linear } = grey(TransferFunction::Linear) else { panic!("grey, linear") };
// the luminance of linear sRGB (IEC 61966-2-1: 0.2126, 0.7152, 0.0722); white stays white
for (v, e) in m[0].iter().zip([0.2126, 0.7152, 0.0722]) {
assert!((v - e).abs() < 1e-4, "{m:?}");
}
assert!((m[0].iter().sum::<f32>() - 1.0).abs() < 1e-5, "{m:?}");
assert!(matches!(grey(TransferFunction::Srgb), Output::FromXyb { curve: Curve::Srgb, .. }));
}
#[test]
fn lossy_data_keeps_the_declared_transfer_curve() {
// Lightroom Classic's lossy LinearRaw DNGs: Rec.2100 primaries, sRGB transfer curve
let mut e = EnumColourEncoding::srgb_linear(RenderingIntent::Perceptual);
e.primaries = Primaries::Bt2100;
e.tf = TransferFunction::Srgb;
let curve = |tf| {
let mut e = e.clone();
e.tf = tf;
match output_for(true, &ColourEncoding::Enum(e), 255.0, 3).unwrap() {
Output::FromXyb { matrix: Some(_), curve } => curve,
other => panic!("expected a matrix and a curve, got {other:?}"),
}
};
assert_eq!(curve(TransferFunction::Srgb), Curve::Srgb);
assert_eq!(curve(TransferFunction::Bt709), Curve::Bt709);
assert_eq!(curve(TransferFunction::Dci), Curve::Power(1.0 / 2.6));
// a codestream's gamma (as read: inverted) is the encoding exponent; jxl-oxide's own γ 2.2 is not
assert_eq!(curve(TransferFunction::Gamma { g: 4_545_455, inverted: true }), Curve::Power(0.454_545_5));
assert_eq!(curve(TransferFunction::Gamma { g: 22_000_000, inverted: false }), Curve::Power(1.0 / 2.2));
}
#[test]
fn transfer_curves_encode_unclipped_and_mirrored() {
let close = |a: f32, b: f32| (a - b).abs() < 1e-4;
// sRGB: linear toe, 18 % grey, white, and the toe/power junction is continuous
assert!(close(Curve::Srgb.encode(0.002), 0.002 * 12.92));
assert!(close(Curve::Srgb.encode(0.18), 0.461_356));
assert!(close(Curve::Srgb.encode(1.0), 1.0));
assert!(close(Curve::Srgb.encode(0.003_130_8), Curve::Srgb.encode(0.003_130_9)));
assert!(close(Curve::Bt709.encode(1.0), 1.0));
assert!((Curve::Bt709.encode(0.017_999) - Curve::Bt709.encode(0.018)).abs() < 1e-3);
assert!(close(Curve::Power(0.5).encode(0.25), 0.5));
// raw values above white keep growing, lossy undershoot keeps its sign, linear is the identity
assert!(Curve::Srgb.encode(2.0) > 1.3);
assert!(close(Curve::Srgb.encode(-0.18), -0.461_356));
assert_eq!(Curve::Linear.encode(-3.5), -3.5);
assert_eq!(Curve::Power(0.5).encode(0.0), 0.0);
}
#[test]
fn lossy_data_is_restored_to_the_declared_primaries() {
// linear sRGB to linear BT.2020/BT.2100 primaries (D65), as published in ITU-R BT.2087
let expect = [[0.6274, 0.3293, 0.0433], [0.0691, 0.9195, 0.0114], [0.0164, 0.0880, 0.8956]];
let m = matrix(output_for(true, &linear(Primaries::Bt2100), 255.0, 3).unwrap());
for (r, e) in m.iter().zip(&expect) {
for (v, e) in r.iter().zip(e) {
assert!((v - e).abs() < 1e-3, "{m:?}");
}
// the white point maps to itself: rows sum to one
assert!((r.iter().sum::<f32>() - 1.0).abs() < 1e-5, "{m:?}");
}
// custom primaries equal to the named ones give the same matrix
let xy = |[x, y]: [f64; 2]| Customxy { x: (x * 1e6) as i32, y: (y * 1e6) as i32 };
let custom = Primaries::Custom { red: xy(BT2100[0]), green: xy(BT2100[1]), blue: xy(BT2100[2]) };
let c = matrix(output_for(true, &linear(custom), 255.0, 3).unwrap());
assert!(c.iter().flatten().zip(m.iter().flatten()).all(|(a, b)| (a - b).abs() < 1e-5), "{c:?} {m:?}");
// the sRGB primaries lie inside the wider P3 gamut: the full-saturation sRGB green is a valid P3 colour
let inv = matrix(output_for(true, &linear(Primaries::P3), 255.0, 3).unwrap());
let srgb_green_in_p3 = [inv[0][1], inv[1][1], inv[2][1]];
assert!(srgb_green_in_p3.iter().all(|v| (0.0..=1.0).contains(v)), "sRGB green lies inside P3");
}
// 16 × 16 RGB tiles of 16-bit samples coded lossily (XYB) by libjxl at distance 0.5, each declaring BT.2020
// primaries, a D65 white point and the named transfer curve. The samples are [`gradient`]; generated for these
// tests (original work).
const SRGB_TILE: &[u8] = &[
0xff, 0x0a, 0x43, 0xf0, 0x93, 0x90, 0xc7, 0x8d, 0x00, 0x13, 0x08, 0x00, 0xf0, 0x01, 0x77, 0x3f, 0xc8, 0x01, 0x00, 0x50, 0xa1, 0x32, 0xca,
0xb8, 0xc1, 0xcb, 0xb9, 0x9e, 0x2f, 0x3f, 0x74, 0x58, 0x4c, 0xdb, 0xb8, 0xce, 0xd0, 0x56, 0xdb, 0x16, 0x96, 0x30, 0x36, 0xdb, 0x0b, 0x83,
0x84, 0x84, 0x33, 0x70, 0xde, 0x90, 0x97, 0xbd, 0x79, 0x64, 0xe4, 0x3b, 0x62, 0xaf, 0x1b, 0xb2, 0x74, 0xf6, 0x36, 0x43, 0x17, 0x72, 0xe7,
0x31, 0x86, 0xb6, 0x41, 0x1c, 0x00, 0x15, 0x52, 0x20, 0x11, 0x70, 0xcb, 0x46, 0x32, 0x92, 0x65, 0xcd, 0xc8, 0x18, 0xc9, 0x48, 0xe6, 0x49,
0xe6, 0x4f, 0x94, 0x35, 0xc7, 0x5c, 0x91, 0xb0, 0x5d, 0xdf, 0x2b, 0x9b, 0x93, 0x3b, 0xb6, 0x70, 0x7d, 0x24, 0xf0, 0xdd, 0x26, 0xb2, 0x26,
0xdf, 0x49, 0x5f, 0xd4, 0xaa, 0x1c, 0x8f, 0x7d, 0xc4, 0xf2, 0x6a, 0xd2, 0x27, 0x86, 0x93, 0xe7, 0x15, 0x9a, 0x01, 0x60, 0x84, 0xc0, 0x09,
];
const BT709_TILE: &[u8] = &[
0xff, 0x0a, 0x43, 0xf0, 0x93, 0x90, 0xa7, 0x08, 0x00, 0x13, 0x08, 0x00, 0xe8, 0x01, 0x77, 0x3f, 0xc8, 0x01, 0x00, 0x50, 0xa1, 0x32, 0xca,
0xb8, 0xc1, 0xcb, 0xb9, 0x9e, 0x2f, 0x3f, 0x74, 0x58, 0x4c, 0xdb, 0xb8, 0xce, 0xd0, 0x56, 0xdb, 0x16, 0x96, 0x30, 0x36, 0xdb, 0x0b, 0x83,
0x84, 0x84, 0x33, 0xd8, 0x9c, 0x32, 0xe2, 0x85, 0x6f, 0x3e, 0x6c, 0xa2, 0x1c, 0xaa, 0xdf, 0x1b, 0x32, 0xf4, 0xef, 0x36, 0xe3, 0x96, 0xf2,
0xe0, 0x65, 0xe8, 0x15, 0xc4, 0x01, 0x50, 0x21, 0x05, 0xd2, 0x00, 0xd8, 0x8c, 0x8c, 0x14, 0x59, 0xc9, 0x31, 0x32, 0x46, 0x52, 0x60, 0x82,
0x71, 0x03, 0xd9, 0xff, 0x8a, 0x3e, 0x7c, 0xb4, 0xc1, 0xa8, 0x49, 0xfa, 0x83, 0xa8, 0x74, 0xd7, 0x1d, 0xa8, 0xb4, 0x25, 0x67, 0xc1, 0x83,
0x93, 0x3a, 0xf3, 0x81, 0xb5, 0x2f, 0x44, 0x50, 0x35, 0x36, 0x68, 0x1c, 0xf9, 0x20, 0x17, 0x98, 0x87, 0x1d, 0x83, 0xb0, 0x02,
];
const GAMMA22_TILE: &[u8] = &[
0xff, 0x0a, 0x43, 0xf0, 0x93, 0x90, 0xf7, 0x75, 0xab, 0x28, 0x02, 0x00, 0x13, 0x08, 0x00, 0xf8, 0x01, 0x77, 0x3f, 0xc8, 0x01, 0x00, 0x50,
0xa1, 0x32, 0xca, 0xb8, 0xc1, 0xcb, 0xb9, 0x9e, 0x2f, 0x3f, 0x74, 0x58, 0x4c, 0xdb, 0xb8, 0xce, 0xd0, 0x56, 0xdb, 0x16, 0x96, 0x30, 0x36,
0xdb, 0x0b, 0x83, 0x84, 0x84, 0x33, 0xd8, 0x9c, 0x02, 0xed, 0x85, 0x6f, 0x3e, 0x2c, 0x72, 0x1e, 0xb8, 0xe3, 0x3b, 0x12, 0x75, 0xf8, 0x4e,
0xa3, 0x97, 0x71, 0xea, 0x31, 0x43, 0xa7, 0x20, 0x0e, 0x80, 0x0a, 0x29, 0x90, 0x08, 0xc0, 0x8a, 0x8c, 0x8a, 0x64, 0x74, 0x59, 0x45, 0xc6,
0x48, 0x46, 0x32, 0x4c, 0x32, 0x4c, 0xa0, 0xa5, 0x39, 0x23, 0xff, 0xdf, 0xcd, 0xf9, 0x33, 0x93, 0x5c, 0xb4, 0xec, 0xc1, 0x06, 0xf5, 0xcc,
0x92, 0x12, 0xf4, 0xbb, 0xef, 0x15, 0x84, 0xc7, 0xf2, 0xf1, 0x48, 0xfc, 0x80, 0xb9, 0x7a, 0xab, 0x58, 0x3e, 0x79, 0x3a, 0xcf, 0x67, 0xc7,
0xd3, 0xfc, 0x80, 0x60, 0x00,
];
const LINEAR_TILE: &[u8] = &[
0xff, 0x0a, 0x43, 0xf0, 0x93, 0x90, 0x47, 0x8b, 0x00, 0x13, 0x08, 0x00, 0x14, 0x02, 0x77, 0x3f, 0xc8, 0x01, 0x00, 0x50, 0xa1, 0x32, 0xca,
0xb8, 0xc1, 0xcb, 0xb9, 0x9e, 0x2f, 0x3f, 0x74, 0x58, 0x4c, 0xdb, 0xb8, 0xce, 0xd0, 0x56, 0xdb, 0x16, 0x96, 0x30, 0x36, 0xdb, 0x0b, 0x83,
0x84, 0x84, 0x43, 0xd8, 0x36, 0xe1, 0xbe, 0x88, 0x9b, 0x27, 0x48, 0x71, 0x04, 0xe2, 0xeb, 0x4e, 0xf9, 0x74, 0x9d, 0xe7, 0x00, 0x8d, 0x74,
0xcb, 0xc0, 0xe0, 0x5d, 0x58, 0x10, 0x80, 0x0a, 0x29, 0x90, 0x06, 0xd8, 0xac, 0x18, 0x19, 0x45, 0xc5, 0x28, 0x89, 0x8a, 0x24, 0xd3, 0xff,
0xff, 0x1c, 0xc4, 0x2f, 0xd8, 0x26, 0x80, 0x6c, 0xe1, 0xc3, 0xbe, 0xef, 0xab, 0xe1, 0x79, 0x1e, 0xff, 0x1b, 0x2e, 0x57, 0xf7, 0x2c, 0x1f,
0x1f, 0xf8, 0xec, 0xd3, 0x33, 0x21, 0x9e, 0x12, 0x22, 0x43, 0xc2, 0xfd, 0xb3, 0xf2, 0xe0, 0x40, 0xdf, 0x25, 0x0f, 0x67, 0xe7, 0xca, 0x7e,
0xa5, 0x7f, 0x1f, 0x21, 0xa4, 0x6a, 0x1e, 0xa0, 0x0e,
];
/// The samples the fixture tiles were coded from: `(x, y)` → RGB.
fn gradient(x: usize, y: usize) -> [f32; 3] {
let (x, y) = (x as f32, y as f32);
[4000.0 + x * 3500.0, 6000.0 + y * 3200.0, 30000.0 + (x - y) * 1500.0]
}
#[test]
fn lossy_tiles_decode_to_their_samples_whatever_sdr_curve_they_declare() {
for (name, tile) in [("sRGB", SRGB_TILE), ("BT.709", BT709_TILE), ("gamma 2.2", GAMMA22_TILE), ("linear", LINEAR_TILE)] {
let ChunkPx::U16(px) = decode(tile, 16, 16, 16, 16, 3, 16, false).unwrap() else { panic!("{name}: integer samples") };
let (mut sum, mut worst) = (0.0f32, 0.0f32);
for (i, p) in px.as_chunks::<3>().0.iter().enumerate() {
for (got, want) in p.iter().zip(gradient(i % 16, i / 16)) {
let err = (f32::from(*got) - want).abs();
sum += err;
worst = worst.max(err);
}
}
// the reference decoder (libjxl) lands within 0.5 % on average and 6 % at worst on these tiles
let mean = sum / px.len() as f32;
assert!(mean < 0.01 * 65535.0, "{name}: mean error {mean}");
assert!(worst < 0.1 * 65535.0, "{name}: worst error {worst}");
}
}
/// A fixture tile re-declared grey: its colour encoding's colour space goes from RGB to Grey and,
/// as a grey encoding has no primaries, the 6-bit BT.2100 primaries field is dropped (ISO/IEC 18181-1
/// ColourEncoding; the bits after it move up and the header's zero padding to the frame grows by 6).
/// The XYB frame data is untouched, so the codestream is one grey plane coded as three XYB channels
/// whose colour is the gradient's, like Lightroom Classic's merged monochrome DNGs.
fn as_grey(tile: &[u8]) -> Vec<u8> {
// bit offset of the colour space, read LSB first, and the frame's first byte in these fixture tiles
const AT: usize = 42;
const FRAME: usize = 8;
let mut bits: Vec<u8> = tile.iter().flat_map(|b| (0..8).map(move |i| (b >> i) & 1)).collect();
// colour space Rgb (selector 0), white point D65 (selector 1), primaries Bt2100 (selector 2 + 4 bits of 7)
assert_eq!(bits[AT..AT + 10], [0, 0, 1, 0, 0, 1, 1, 1, 1, 0], "the fixture's colour encoding");
bits[AT] = 1; // colour space Grey (selector 1)
bits.drain(AT + 4..AT + 10);
bits.splice(FRAME * 8 - 6..FRAME * 8 - 6, [0; 6]);
bits.as_chunks::<8>().0.iter().map(|b| b.iter().enumerate().fold(0, |a, (i, v)| a | v << i)).collect()
}
#[test]
fn lossy_grey_tiles_decode_to_the_luminance_of_their_colour() {
let srgb_eotf = |v: f32| if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
let y = rgb_to_xyz(BT2100)[1].map(|v| v as f32);
for (name, tile, curve) in [("linear", LINEAR_TILE, Curve::Linear), ("sRGB", SRGB_TILE, Curve::Srgb)] {
let grey = as_grey(tile);
// the decoder still renders three unequal channels: the restore must reduce them, not pick one
let mut img = JxlImage::builder().read(std::io::Cursor::new(&grey)).unwrap();
assert!(img.image_header().metadata.grayscale(), "{name}: declared grey");
img.request_color_encoding(EnumColourEncoding::srgb_linear(RenderingIntent::Relative));
let render = img.render_frame(0).unwrap();
let fb = render.image_all_channels();
assert_eq!(fb.channels(), 3, "{name}");
assert!((fb.buf()[2] - fb.buf()[0]).abs() > 0.1, "{name}: the rendered channels differ");
let ChunkPx::U16(px) = decode(&grey, 16, 16, 16, 16, 1, 16, false).unwrap() else { panic!("{name}: integer samples") };
assert_eq!(px.len(), 256, "{name}: one plane");
let (mut sum, mut worst) = (0.0f32, 0.0f32);
for (i, got) in px.iter().enumerate() {
// the gradient's samples are coded in the tile's curve: back to linear for the luminance
let rgb = gradient(i % 16, i / 16).map(|v| if curve == Curve::Srgb { srgb_eotf(v / 65535.0) } else { v / 65535.0 });
let want = curve.encode(y[0] * rgb[0] + y[1] * rgb[1] + y[2] * rgb[2]) * 65535.0;
let err = (f32::from(*got) - want).abs();
sum += err;
worst = worst.max(err);
}
let mean = sum / px.len() as f32;
assert!(mean < 0.02 * 65535.0, "{name}: mean error {mean}");
assert!(worst < 0.1 * 65535.0, "{name}: worst error {worst}");
}
}
#[test]
fn lossy_data_that_cannot_be_restored_is_unsupported() {
let bad = |xyb_planes: usize, e: ColourEncoding, it: f32| matches!(output_for(true, &e, it, xyb_planes), Err(RawError::Unsupported(_)));
assert!(bad(1, linear(Primaries::Srgb), 255.0), "one plane declared RGB");
let mut g = EnumColourEncoding::srgb_linear(RenderingIntent::Relative);
g.colour_space = ColourSpace::Grey;
assert!(bad(1, ColourEncoding::Enum(g.clone()), 10_000.0), "grey with an HDR intensity target");
g.tf = TransferFunction::Pq;
assert!(bad(1, ColourEncoding::Enum(g.clone()), 255.0), "grey with PQ");
g.tf = TransferFunction::Linear;
g.white_point = WhitePoint::Dci;
assert!(bad(1, ColourEncoding::Enum(g), 255.0), "grey with a white point other than D65");
assert!(bad(3, linear(Primaries::Srgb), 10_000.0), "HDR intensity target would tone-map");
let mut e = EnumColourEncoding::srgb_linear(RenderingIntent::Relative);
for tf in [TransferFunction::Pq, TransferFunction::Hlg, TransferFunction::Unknown, TransferFunction::Gamma { g: 0, inverted: true }] {
e.tf = tf;
assert!(bad(3, ColourEncoding::Enum(e.clone()), 255.0), "{tf:?}");
}
e.tf = TransferFunction::Linear;
e.white_point = WhitePoint::Dci;
assert!(bad(3, ColourEncoding::Enum(e.clone()), 255.0), "white point");
e.white_point = WhitePoint::D65;
e.primaries =
Primaries::Custom { red: Customxy { x: 0, y: 0 }, green: Customxy { x: 300_000, y: 600_000 }, blue: Customxy { x: 150_000, y: 60_000 } };
assert!(bad(3, ColourEncoding::Enum(e.clone()), 255.0), "degenerate primaries");
e.colour_space = ColourSpace::Grey;
assert!(bad(3, ColourEncoding::Enum(e.clone()), 255.0), "grey declared");
}
}
-189
View File
@@ -1,189 +0,0 @@
//! Lens-correction data a raw file records, kept with where it came from and separately from what LightCraft
//! applies.
//!
//! A readable table is not a correction. Each component carries a [`SonyLensStatus`]: only
//! [`SonyLensStatus::Applied`] components were converted into the image's `OpcodeList3`, and that is decided by
//! independent validation per model, coding and component (see `docs/sony-lens-corrections.md`), never by the mere
//! presence of a table. Everything else here is metadata for diagnostics and later validation work.
use crate::Rect;
use serde::{Deserialize, Serialize};
/// Vendor lens-correction metadata of a raw file (see the module docs). Empty for formats that record none, or
/// whose tables are read straight into opcodes.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LensMetadata {
/// Sony ARW: the raw image IFD's shading, lateral chromatic aberration and distortion records, with their
/// encrypted `SR2SubIFD` copies. `None` when neither directory holds any of them.
#[serde(default)]
pub sony: Option<SonyLensCorrections>,
}
/// Sony's in-file lens-correction record: three independent components, each a camera setting and a radial table.
///
/// Tag identities and storage types from the ExifTool EXIF / Sony tag-name documentation: raw-IFD `0x7031` / `0x7032`
/// (shading, "VignettingCorrection" / "VignettingCorrParams"), `0x7034` / `0x7035` (lateral chromatic aberration),
/// `0x7036` / `0x7037` (distortion), and the `SR2SubIFD` tables `0x797d`, `0x7980`, `0x7982`. The `SR2SubIFD` setting
/// tags `0x797c`, `0x797f`, `0x7981` are unnamed there; they sit next to the tables and equal the raw-IFD settings
/// in every file inspected.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SonyLensCorrections {
/// Shading (vignetting): 16 radial samples whose gain function, radius convention and processing stage are not
/// established. Opaque signed data.
pub shading: SonyComponent<[i16; 16]>,
/// Lateral chromatic aberration: two 16-sample radial curves. A public analysis reads them as red, then blue,
/// relative to green; that is not validated here.
pub chromatic_aberration: SonyComponent<[[i16; 16]; 2]>,
/// Distortion: 16 radial samples (see `docs/sony-lens-corrections.md` for the validated interpretation).
pub distortion: SonyComponent<[i16; 16]>,
/// Whether the encrypted `SR2SubIFD` was found and decrypted. `false`: no copies to fall back on or compare.
pub sr2_read: bool,
/// The framing and coding the tables have to be interpreted against.
pub geometry: SonyLensGeometry,
}
/// One correction component: the camera's setting, its table, and whether LightCraft applies it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SonyComponent<T> {
pub setting: SonyField<SonySetting>,
/// The table's samples after the leading sample count, which must equal their number.
pub table: SonyField<T>,
pub status: SonyLensStatus,
}
/// One field read from the raw IFD and from the `SR2SubIFD`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SonyField<T> {
/// The value in use: the raw IFD's when it holds a well-formed one, else the `SR2SubIFD`'s when the raw IFD
/// lacks the tag. `None` when no copy is usable, and when the raw IFD's copy is malformed: a corrupt field is
/// reported, not silently replaced by the other copy. The raw IFD's copy is the one the TIFF reader that decodes
/// the image parsed (its first occurrence, within the reader's limits).
pub value: Option<T>,
pub source: Option<SonySource>,
pub raw_ifd: SonyCopy,
pub sr2: SonyCopy,
/// Whether the two copies are equal, when both are well-formed. The raw IFD's wins when they differ.
pub copies_agree: Option<bool>,
/// Diagnostics: the tag occurs more than once in the raw IFD / the `SR2SubIFD`. Only the first occurrence is used,
/// as the TIFF reader does (the raw IFD's: the first one whose values it could read).
#[serde(default)]
pub raw_ifd_repeated: bool,
#[serde(default)]
pub sr2_repeated: bool,
}
/// Where a value was read.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SonySource {
/// The plain raw image IFD.
RawIfd,
/// The encrypted `SR2SubIFD`.
Sr2SubIfd,
}
/// How one copy of a field was found.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SonyCopy {
/// Not in that directory (or the `SR2SubIFD` could not be read).
Absent,
/// Present with exactly the supported type and layout.
Valid,
/// Present, but refused.
Rejected(SonyFieldError),
}
/// Why a present field was refused.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SonyFieldError {
/// Another TIFF field type than SSHORT (8) for a table, or SHORT (3) / SSHORT for a setting.
FieldType(u16),
/// Another number of values than the supported layout's: 17 (shading, distortion), 33 (CA) or 1 (setting).
Count(u64),
/// The leading sample count is not the layout's 16 (32 for CA). Older bodies store 11 (22) samples padded to the
/// same length, a layout that is not interpreted; a count of 0 goes with an "unavailable" setting.
CountPrefix(i16),
/// The values lie outside the file (raw IFD) or the decrypted block (`SR2SubIFD`).
OutsideData,
/// In the raw IFD but past what the TIFF reader that decodes the image reads (8,192 entries per directory, a
/// total value budget), so the image doesn't use it either.
PastReaderLimits,
/// A setting stored as a negative SSHORT.
NegativeSetting(i16),
}
/// A camera correction setting: the stored number and its documented meaning.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SonySetting {
pub value: u16,
pub meaning: SonySettingMeaning,
}
/// The documented meaning of a setting value (ExifTool EXIF tag-name documentation). Values are compared whole;
/// they are not read as bit masks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SonySettingMeaning {
/// Shading 256, CA 0, distortion 0. The table is still recorded: Off does not mean absent.
Off,
/// Shading 257 or 272, CA 1, distortion 1.
Auto,
/// Distortion 17: Auto, fixed by the lens.
ForcedAuto,
/// "No correction params available": shading 511, CA 255, distortion 255.
Unavailable,
/// Any other value (e.g. a shading "Low" setting, whose number is not documented). Never treated as Off.
Unknown(u16),
}
/// Whether a component is applied, and if not, why.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SonyLensStatus {
/// Converted into the image's `OpcodeList3` (ILCE-7RM4A, ILCE-7RM6 or eligible full-frame ILCE-7CR Bayer distortion).
Applied,
/// No usable table.
NoTable,
/// Decoded only: no independent validation covers this component's rendering semantics on any body (shading,
/// lateral CA).
NotValidatedComponent,
/// Decoded only: the component is validated on other camera models, not on this one.
NotValidatedModel,
/// Decoded only: the model is validated, but not this coding or framing (linear YCbCr, a non-3:2 crop) or a
/// table found only in the `SR2SubIFD`.
NotValidatedMode,
/// A7CR distortion is Off, unavailable, missing or unknown. Its uncorrected JPEG and render keep the same geometry.
CameraCorrectionDisabled,
/// Validated scope, but the table is all zeros: a valid no-op, nothing to apply.
Neutral,
/// Validated scope, but the conversion refused this table (values outside the validated range, a degenerate
/// crop, or a fitted map that misses the table or folds).
Rejected,
}
/// The framing and coding evidence for interpreting the tables, all in raw-frame pixels.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SonyLensGeometry {
/// The stored raw frame, including any padding (lossless L files are padded).
pub storage_width: usize,
pub storage_height: usize,
/// Sony's crop tags (`0x74c7` / `0x74c8`) as recorded.
pub sony_crop: Option<Rect>,
/// The raw IFD's `DefaultCropOrigin` / `DefaultCropSize` as recorded.
pub default_crop: Option<Rect>,
/// The image's crop (the decoder's precedence: Sony's tags, then the default crop, then the recorded size).
pub image_crop: Rect,
/// The rectangle the validated distortion conversion is centred on and normalised to: the default crop when
/// the file has one, else the image crop. Clipped to the frame.
pub reference: Rect,
/// TIFF compression of the raw image (1 uncompressed, 7 lossless, 32767 ARW2, 32766 ARW6).
pub compression: u16,
/// Downsized lossless M/S data (linear YCbCr, not sensor CFA).
pub linear_ycbcr: bool,
/// Both the image crop and the reference are 3:2 within 0.5 %, the only framing validated.
pub native_3_2: bool,
}
impl<T> SonyField<T> {
/// Whether either directory holds the tag (well-formed or not).
pub fn is_present(&self) -> bool {
self.raw_ifd != SonyCopy::Absent || self.sr2 != SonyCopy::Absent
}
}
+28 -509
View File
@@ -29,32 +29,29 @@
mod binned;
pub mod color;
mod convert;
pub mod dcp;
pub mod demosaic;
mod dng;
pub mod dngwrite;
pub mod gaintable;
pub mod highlight;
mod hotpixel;
#[cfg(feature = "jxl")]
mod jxl;
pub mod kelvin_builtin;
pub mod kelvin_presets;
pub mod lens_metadata;
pub mod ljpeg;
pub(crate) mod llvc;
pub use craft_raw::lens_metadata;
pub mod opcodes;
mod preview;
pub mod profile;
mod saturation;
pub mod semantic;
pub mod sparse;
pub use craft_raw::sparse;
pub mod spectral;
mod tiffraw;
mod unpack;
mod vendor;
mod wb_estimate;
pub use craft_raw::{
BlackLevel, Cfa, MAX_SAMPLES, PREVIEW_PREFIX, PreviewColorSpace, PreviewRange, RawData, RawError, RawFormat, Rect, Result, SemanticMask,
bounded_preview, embedded_preview, embedded_preview_color_space, embedded_preview_covering, embedded_preview_dynamic_range_optimized,
embedded_preview_from_range, ljpeg, probe, semantic_masks, stretched_height,
};
pub use demosaic::{Method, demosaic};
pub use dngwrite::{DngCompression, DngWriteOptions, write_dng, write_rendered_dng};
pub use hotpixel::HOT_PIXEL_MAX_SHARE;
@@ -64,19 +61,10 @@ pub use lightcraft_geom::Orientation;
pub use lightcraft_meta::Metadata;
pub use lightcraft_raster::Rgb32f;
pub use opcodes::{Opcode, OpcodeLists};
pub use preview::{
PREVIEW_PREFIX, PreviewColorSpace, PreviewRange, bounded_preview, embedded_preview, embedded_preview_color_space, embedded_preview_covering,
embedded_preview_dynamic_range_optimized, embedded_preview_from_range,
};
pub use semantic::{SemanticMask, semantic_masks};
use craft_tiff::{Tiff, TiffError};
use lightcraft_color::Xy;
use serde::{Deserialize, Serialize};
/// Upper bound on decoded samples (guards allocations driven by header values).
pub const MAX_SAMPLES: usize = 1 << 30;
/// Checked product of input-derived dimensions, in u64 so it cannot wrap
/// on either 32-bit (wasm32) or 64-bit targets. The arguments are u64 too, so callers can feed
/// unchecked products of header values (row bytes, sample counts) without truncating on 32-bit.
@@ -86,289 +74,20 @@ pub(crate) fn checked_pixel_count(width: u64, height: u64) -> Option<u64> {
width.checked_mul(height).filter(|&n| n > 0 && n <= MAX_SAMPLES as u64)
}
/// Errors from raw decoding.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RawError {
#[error("not a recognised raw file")]
NotRaw,
#[error("unsupported raw variant: {0}")]
Unsupported(String),
#[error("corrupt raw data: {0}")]
Corrupt(String),
#[error("limit exceeded: {0}")]
Limit(&'static str),
#[error(transparent)]
Tiff(#[from] TiffError),
/// Whether [`decode`] reads this container (possibly not every compression inside it): `craft-raw`'s makers and
/// the ones still decoded here (Canon CR3, Sony ARW, Fujifilm RAF, Panasonic RW2).
pub fn is_supported(format: RawFormat) -> bool {
format.is_supported()
}
pub type Result<T> = std::result::Result<T, RawError>;
/// Raw container formats recognised by [`probe`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RawFormat {
Dng,
Cr2,
Cr3,
Nef,
Nrw,
Arw,
Raf,
Orf,
Rw2,
Pef,
Srw,
/// Canon CRW (CIFF heap), the bodies before the CR2 era.
Crw,
/// Minolta MRW (`\0MRM` block container, `vendor::mrw`).
Mrw,
/// Sigma / Foveon X3F (`FOVb`).
X3f,
/// A TIFF-based raw that has no DNG version tag but describes itself the way DNG does (a
/// full-resolution CFA image with black/white levels, a default crop and `AsShotNeutral`):
/// Hasselblad 3FR and FFF. Read by `vendor::hasselblad` (the DNG reader plus what Hasselblad adds).
CfaTiff,
/// Kodak DCS520C TIFF: a two-component lossless JPEG CFA sub-IFD with a response curve (`vendor::kodak`).
KodakDcs,
/// Epson ERF: a CFA sub-IFD of 12-bit samples in 16-byte blocks (`vendor::erf`).
Erf,
/// Mamiya MEF: an uncompressed 12-bit packed CFA sub-IFD (`vendor::mef`).
Mef,
/// Another TIFF-based raw (3FR, IIQ, ERF, KDC, DCR, MOS, …).
OtherTiff,
#[cfg(test)]
pub(crate) fn bayer(s: &'static str) -> Cfa {
Cfa::bayer(s).unwrap_or(Cfa { width: 2, height: 2, origin_x: 0, origin_y: 0, pattern: vec![0, 1, 1, 2] })
}
impl RawFormat {
/// Whether [`decode`] supports this container (possibly not every compression inside it).
pub fn is_supported(self) -> bool {
matches!(
self,
RawFormat::Dng
| RawFormat::Cr2
| RawFormat::Cr3
| RawFormat::Crw
| RawFormat::Nef
| RawFormat::Nrw
| RawFormat::Arw
| RawFormat::Raf
| RawFormat::Rw2
| RawFormat::Pef
| RawFormat::CfaTiff
| RawFormat::Srw
| RawFormat::KodakDcs
| RawFormat::Mrw
| RawFormat::Erf
| RawFormat::Mef
)
}
}
/// Recognise a raw file from its first bytes / TIFF structure.
pub fn probe(bytes: &[u8]) -> Option<RawFormat> {
if bytes.len() >= 12 && &bytes[4..12] == b"ftypcrx " {
return Some(RawFormat::Cr3);
}
if bytes.starts_with(b"FUJIFILMCCD-RAW") {
return Some(RawFormat::Raf);
}
if bytes.starts_with(b"IIRO") || bytes.starts_with(b"IIRS") || bytes.starts_with(b"MMOR") {
return Some(RawFormat::Orf);
}
if bytes.starts_with(b"IIU\0") {
return Some(RawFormat::Rw2);
}
if bytes.starts_with(b"\0MRM") {
return Some(RawFormat::Mrw);
}
if bytes.starts_with(b"FOVb") {
return Some(RawFormat::X3f);
}
if bytes.len() >= 14 && bytes.starts_with(b"II") && &bytes[6..14] == b"HEAPCCDR" {
return Some(RawFormat::Crw);
}
if bytes.len() >= 10 && bytes.starts_with(b"II*\0") && &bytes[8..10] == b"CR" {
return Some(RawFormat::Cr2);
}
let (_, _) = Tiff::sniff(bytes)?;
let opts = craft_tiff::ParseOptions { max_ifds: 256, ..Default::default() };
let t = Tiff::parse_with(bytes, &opts).ok()?;
let ifd0 = t.ifds.first()?;
if ifd0.contains(craft_tiff::tags::DNG_VERSION) {
return Some(RawFormat::Dng);
}
let make = t.find(craft_tiff::tags::MAKE).and_then(|e| e.value.as_str()).unwrap_or_default().to_ascii_uppercase();
let has_cfa = has_raw_ifd(&t);
// Pentax's reader takes the layout from the Exif `CFAPattern` when no IFD has a CFA photometric (uncompressed
// and PackBits PEFs), so for the Pentax family that tag counts as raw evidence too
let pentax_raw = has_cfa || t.exif().is_some_and(|e| e.contains(vendor::EXIF_CFA_PATTERN));
// Samsung's raw IFD uses private compressions 32769..=32773 (`vendor::srw`), 32773 being PackBits elsewhere
let samsung_raw = has_cfa || t.all_ifds().iter().any(|i| i.u16(craft_tiff::tags::COMPRESSION).is_some_and(|c| (32769..=32773).contains(&c)));
// Sony raws without a CFA IFD (#702): SRF (DSC-F828), whose IFD0 looks like RGB but holds 14-bit samples (12 or
// 14 count: raw sensor depths; the raw is in Sony's SRF blocks), and the DSLR-A100, whose IFD0 is an old-style
// JPEG thumbnail (compression 6, which today's TIFF writers don't produce) and whose `SubIFDs` tag addresses its
// raw data. A camera-authored or exported TIFF has 8- or 16-bit samples, and its SubIFDs hold ordinary images
let model = t.find(craft_tiff::tags::MODEL).and_then(|e| e.value.as_str()).unwrap_or_default().trim().to_ascii_uppercase();
let sony_raw = has_cfa
|| ifd0.u64s(craft_tiff::tags::BITS_PER_SAMPLE).is_some_and(|b| b.iter().any(|v| matches!(v, 12 | 14)))
|| (model == "DSLR-A100" && ifd0.u16(craft_tiff::tags::COMPRESSION) == Some(6) && ifd0.contains(craft_tiff::tags::SUB_IFDS));
if make.starts_with("CANON") && t.ifds.len() >= 4 && t.ifds[3].u16(craft_tiff::tags::COMPRESSION) == Some(6) {
return Some(RawFormat::Cr2);
}
if make.starts_with("NIKON") && has_cfa {
return Some(if t.all_ifds().len() > 1 { RawFormat::Nef } else { RawFormat::Nrw });
}
// Hasselblad's Sony-built bodies (the Lunar is a NEX-7 inside) write a Sony ARW under their own Make. Sony's
// raw coding gives them away: compression 32767 or the raw IFD's tone-curve tag 0x7010, which no 3FR / FFF has
let sony_coded = || t.all_ifds().iter().any(|i| i.u16(craft_tiff::tags::COMPRESSION) == Some(32767) || i.contains(0x7010));
if (make.starts_with("SONY") && sony_raw) || (make.starts_with("HASSELBLAD") && sony_coded()) {
return Some(RawFormat::Arw);
}
if (make.starts_with("PENTAX") || make.starts_with("RICOH")) && pentax_raw {
return Some(RawFormat::Pef);
}
// a Samsung-branded body built on a Pentax design writes a Pentax-style maker note (the note's own magic)
if make.starts_with("SAMSUNG") && pentax_raw && has_pentax_maker_note(&t, bytes) {
return Some(RawFormat::Pef);
}
if make.starts_with("SAMSUNG") && samsung_raw {
return Some(RawFormat::Srw);
}
if vendor::erf::raw_ifd(&t, bytes.len()).is_some() {
return Some(RawFormat::Erf);
}
if vendor::mef::raw_ifd(&t, bytes.len()).is_some() {
return Some(RawFormat::Mef);
}
if vendor::kodak::raw_ifd(&t, bytes).is_some() {
return Some(RawFormat::KodakDcs);
}
if dng::is_plain_cfa_tiff(&t, bytes) {
return Some(RawFormat::CfaTiff);
}
if has_cfa || thumbnail_shell(&t, bytes.len()).is_some() || is_preview_container(ifd0) || is_leaf_mosaic(ifd0) {
return Some(RawFormat::OtherTiff);
}
None
}
/// Leaf's private data block in IFD0, tag `0x8606` (`LeafData` in the ExifTool EXIF tag-name documentation, which
/// says the Leaf tags "are found in .MOS images from Leaf digital camera backs").
const LEAF_DATA: u16 = 0x8606;
/// An uncompressed Leaf MOS: IFD0 is the 16-bit mosaic itself (compression 1, BlackIsZero, one sample per pixel),
/// with no Make tag and no CFA photometric, so only Leaf's data block marks it as a raw (issue #1275). A rendered
/// RGB image that kept the block stays an ordinary image.
fn is_leaf_mosaic(ifd0: &craft_tiff::Ifd) -> bool {
ifd0.contains(LEAF_DATA) && ifd0.u16(craft_tiff::tags::SAMPLES_PER_PIXEL).unwrap_or(1) == 1
}
/// Whether the Exif maker note starts with the signature of the Pentax layouts (`AOC\0` or `PENTAX \0`).
fn has_pentax_maker_note(t: &Tiff, bytes: &[u8]) -> bool {
let Some(e) = t.exif().and_then(|e| e.get(craft_tiff::tags::MAKER_NOTE)) else { return false };
bytes.get(e.offset as usize..).is_some_and(|n| n.starts_with(b"AOC\0") || n.starts_with(b"PENTAX \0"))
}
/// Whether some IFD is marked as raw: CFA photometric, or a raw-only compression value (99 is not a
/// registered TIFF compression; Leaf MOS files use it for their tiled 16-bit lossless-JPEG raw),
/// or vendor-specific raw tags (Sony tone curve, CFA pattern, or Pentax compression 65535).
fn has_raw_ifd(t: &Tiff) -> bool {
t.all_ifds().iter().any(|i| {
i.u16(craft_tiff::tags::PHOTOMETRIC) == Some(craft_tiff::tags::photometric::CFA)
|| i.u16(craft_tiff::tags::COMPRESSION).is_some_and(|c| matches!(c, 34713 | 32767 | 32769 | 32770 | 99 | 65535))
|| i.contains(0x7010)
|| i.contains(craft_tiff::tags::CFA_PATTERN_EP)
|| i.contains(craft_tiff::tags::CFA_REPEAT_PATTERN_DIM)
})
}
/// IFD0 that is not an image at all: no `ImageWidth` / `ImageLength`, but a JPEG preview pointer or
/// `SubIFDs` (the layout of Kodak KDC files, whose pictures sit in private tags). A plain TIFF reader
/// rejects such a file as malformed even though it carries a preview.
fn is_preview_container(ifd0: &craft_tiff::Ifd) -> bool {
use craft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, JPEG_INTERCHANGE_FORMAT, SUB_IFDS};
!ifd0.contains(IMAGE_WIDTH) && !ifd0.contains(IMAGE_LENGTH) && (ifd0.contains(JPEG_INTERCHANGE_FORMAT) || ifd0.contains(SUB_IFDS))
}
/// A TIFF whose first image is only a reduced copy of a picture stored somewhere else.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ThumbnailShell {
/// Size of the first image (IFD0).
pub thumb: (u32, u32),
/// Size of the picture it stands in for.
pub full: (u32, u32),
}
/// Some raw files are a TIFF "shell" around a private block: IFD0 holds a small RGB preview and nothing
/// in the TIFF structure marks the real image as raw (no CFA photometric, no raw compression). The
/// structure still gives them away, with a generic rule that names no maker or model: the file
/// declares a picture at least 4x larger than IFD0 in both directions, and either
/// - a `SubIFDs` child of IFD0 is that bigger image (an 8-bit grey mosaic in one such file), or
/// - the Exif `PixelXDimension` / `PixelYDimension` say so *and* the file holds enough bytes outside
/// every IFD's strips and tiles to carry that many pixels at one bit each (a downsized copy that kept
/// its old Exif size has no such block).
///
/// A multi-page TIFF is not caught (its pages are the IFD chain, not `SubIFDs`), nor a pyramid whose
/// IFD0 is the full image.
fn thumbnail_shell(t: &Tiff, len: usize) -> Option<ThumbnailShell> {
use craft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, PIXEL_X_DIMENSION, PIXEL_Y_DIMENSION};
let ifd0 = t.ifds.first()?;
let (w0, h0) = (ifd0.u32(IMAGE_WIDTH)?, ifd0.u32(IMAGE_LENGTH)?);
if w0 == 0 || h0 == 0 {
return None;
}
let much_bigger = |(w, h): (u32, u32)| u64::from(w) >= 4 * u64::from(w0) && u64::from(h) >= 4 * u64::from(h0);
let shell = |full| Some(ThumbnailShell { thumb: (w0, h0), full });
let mut best: Option<(u32, u32)> = None;
for s in &ifd0.sub_ifds {
if s.image().is_ok()
&& let (Some(w), Some(h)) = (s.u32(IMAGE_WIDTH), s.u32(IMAGE_LENGTH))
&& much_bigger((w, h))
&& best.is_none_or(|(bw, bh)| u64::from(w) * u64::from(h) > u64::from(bw) * u64::from(bh))
{
best = Some((w, h));
}
}
if let Some(full) = best {
return shell(full);
}
let exif = t.exif()?;
let full = (exif.u32(PIXEL_X_DIMENSION)?, exif.u32(PIXEL_Y_DIMENSION)?);
if !much_bigger(full) {
return None;
}
// bytes covered by image data (strips and tiles shared between IFDs, e.g. IFD0 and its thumbnail, count once)
let mut seen = std::collections::BTreeMap::new();
for ifd in t.all_ifds() {
if let Ok(info) = ifd.image() {
for c in info.chunks(len as u64) {
seen.insert(c.offset, c.len);
}
}
}
let covered = seen.values().fold(0u64, |a, &l| a.saturating_add(l));
let spare = (len as u64).saturating_sub(covered);
(spare.saturating_mul(8) >= u64::from(full.0) * u64::from(full.1)).then_some(())?;
shell(full)
}
/// Why [`decode`] gives up on a file [`probe`] called [`RawFormat::OtherTiff`].
fn other_tiff_reason(bytes: &[u8]) -> String {
let t = Tiff::parse_with(bytes, &craft_tiff::ParseOptions { max_ifds: 256, ..Default::default() }).ok();
// a DNG-style CFA IFD whose lossless JPEG the lossless decoder rejects: say why
if let Some(t) = &t
&& let Some(info) = dng::raw_ifd(t).and_then(|i| i.image().ok())
&& info.compression == craft_tiff::tags::compression::JPEG
&& let Some(src) = info.chunks(bytes.len() as u64).first().and_then(|c| craft_tiff::image::chunk_bytes(bytes, c))
&& let Err(e) = ljpeg::frame_info(src)
{
return format!("raw image coded as lossless JPEG that is not decoded yet ({e})");
}
match t.as_ref().filter(|t| !has_raw_ifd(t)).and_then(|t| thumbnail_shell(t, bytes.len())) {
Some(s) => format!(
"{}x{} raw image in a private block, not decoded yet (the file's first image is a {}x{} reduced copy)",
s.full.0, s.full.1, s.thumb.0, s.thumb.1
),
None => "OtherTiff files are not decoded yet".to_string(),
}
/// A CFA pattern this crate can address: 1 to 16 sites a side, one colour index per site.
pub(crate) fn cfa_valid(c: &Cfa) -> bool {
c.width > 0 && c.height > 0 && c.width <= 16 && c.height <= 16 && c.pattern.len() == c.width * c.height
}
/// Decode a raw file.
@@ -381,10 +100,7 @@ pub fn decode(bytes: &[u8]) -> Result<RawImage> {
/// px ones) decodes the smallest that covers it. The image has the full one's levels, colour and metadata; its
/// active area and crop are scaled to its size. `Ok(None)` when the file keeps no such copy: decode it whole.
pub fn decode_reduced(bytes: &[u8], min_long: usize) -> Result<Option<RawImage>> {
if probe(bytes) != Some(RawFormat::Dng) {
return Ok(None);
}
Ok(dng::decode_reduced(bytes, min_long)?.map(lift_clipped))
convert::decode_reduced(bytes, min_long)
}
/// Everything [`decode`] learns about a raw file except its samples: geometry, orientation, CFA,
@@ -393,13 +109,11 @@ pub fn decode_reduced(bytes: &[u8], min_long: usize) -> Result<Option<RawImage>>
/// [`RawImage::info`] of the decoded image. Black and white levels are not included (some formats
/// measure them from the samples).
///
/// A few vendor formats derive part of this from the samples themselves (Nikon NEF: optically
/// masked trailing columns; Olympus ORF: the bit depth of 16-bit files, and the CFA phase of files
/// without an Exif `CFAPattern`; Pentax PEF without crop tags: dark borders). Those read the
/// samples they need and drop them: ORF and PEF unpack their uncompressed data; NEF reads only the
/// first 128 rows (`vendor::nef::MASK_ROWS`), which both the probe and the full decode judge the masked
/// columns from, so a compressed NEF probes in a few milliseconds instead of decoding its whole
/// Huffman stream (issue #708).
/// A few formats derive part of this from the samples themselves (Nikon NEF: optically masked trailing columns;
/// Olympus ORF: the bit depth of 16-bit files, and the CFA phase of files without an Exif `CFAPattern`; Pentax PEF
/// without crop tags: dark borders; Epson ERF and Mamiya MEF: the white balance, estimated from the samples).
/// Those read the samples they need and drop them; a compressed NEF reads only the rows its masked columns are
/// judged from (issue #708).
pub fn probe_info(bytes: &[u8]) -> Result<RawInfo> {
decode_with(bytes, Mode::Header).map(RawImage::into_info)
}
@@ -415,33 +129,10 @@ pub(crate) enum Mode {
}
fn decode_with(bytes: &[u8], mode: Mode) -> Result<RawImage> {
match probe(bytes).ok_or(RawError::NotRaw)? {
RawFormat::Dng => dng::decode(bytes, mode).map(lift_clipped),
RawFormat::Cr2 => vendor::cr2::decode(bytes, mode),
RawFormat::Cr3 => vendor::cr3::decode(bytes, mode),
RawFormat::Crw => vendor::crw::decode(bytes, mode),
RawFormat::Nef | RawFormat::Nrw => vendor::nef::decode(bytes, mode),
RawFormat::Arw => vendor::arw::decode(bytes, mode),
RawFormat::Raf => vendor::raf::decode(bytes, mode),
RawFormat::Rw2 => vendor::rw2::decode(bytes, mode),
RawFormat::Pef => vendor::pef::decode(bytes, mode),
RawFormat::Orf => vendor::orf::decode(bytes, mode),
RawFormat::CfaTiff => vendor::hasselblad::decode(bytes, mode).map(lift_clipped),
RawFormat::Srw => vendor::srw::decode(bytes, mode),
RawFormat::KodakDcs => vendor::kodak::decode(bytes, mode),
RawFormat::Mrw => vendor::mrw::decode(bytes, mode),
RawFormat::Erf => vendor::erf::decode(bytes, mode),
RawFormat::Mef => vendor::mef::decode(bytes, mode),
RawFormat::OtherTiff => Err(RawError::Unsupported(other_tiff_reason(bytes))),
other => Err(RawError::Unsupported(format!("{other:?} files are not decoded yet"))),
if probe(bytes).is_none() {
return Err(RawError::NotRaw);
}
}
/// DNG writers state a white level the sensor may never reach; samples stuck at the real saturation point are
/// raised to the white level so they count as clipped (see [`RawImage::lift_clipped_samples`]).
fn lift_clipped(mut r: RawImage) -> RawImage {
r.lift_clipped_samples();
r
convert::decode(bytes, mode)
}
/// A raw file's description without its samples (see [`probe_info`]).
@@ -474,11 +165,6 @@ fn square_pixels() -> f32 {
1.0
}
/// Rows of a picture `height` rows tall once its pixels (taller than wide by `aspect`) are made square.
pub fn stretched_height(height: usize, aspect: f32) -> usize {
if (aspect - 1.0).abs() < 0.01 { height } else { ((height as f32 * aspect).round() as usize).max(1) }
}
impl RawInfo {
/// Size of the developed image before orientation: the default crop, else the active area, with the rows
/// stretched for non-square pixels.
@@ -489,168 +175,6 @@ impl RawInfo {
}
}
/// Sensor samples.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RawData {
U16(Vec<u16>),
/// Floating-point DNGs (already linear, typically white = 1.0).
F32(Vec<f32>),
}
impl RawData {
pub fn len(&self) -> usize {
match self {
RawData::U16(v) => v.len(),
RawData::F32(v) => v.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub fn get(&self, i: usize) -> f32 {
match self {
RawData::U16(v) => v[i] as f32,
RawData::F32(v) => v[i],
}
}
}
/// Colour filter array pattern. Colour indices: 0 = red, 1 = green, 2 = blue.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Cfa {
pub width: usize,
pub height: usize,
/// `width × height` colour indices, row-major, anchored at image pixel (0, 0).
pub pattern: Vec<u8>,
}
impl Cfa {
/// A 2×2 Bayer pattern from a string such as `"RGGB"`.
pub fn bayer(s: &str) -> Option<Cfa> {
let p: Vec<u8> = s
.chars()
.map(|c| {
Some(match c {
'R' => 0,
'G' => 1,
'B' => 2,
_ => return None,
})
})
.collect::<Option<_>>()?;
(p.len() == 4).then_some(Cfa { width: 2, height: 2, pattern: p })
}
/// A 2×2 Bayer layout named in code (`"RGGB"`, `"BGGR"`, `"GRBG"`, `"GBRG"`). Only for literal
/// names (tested below); anything else falls back to RGGB instead of failing.
pub(crate) fn bayer_static(s: &'static str) -> Cfa {
Cfa::bayer(s).unwrap_or(Cfa { width: 2, height: 2, pattern: vec![0, 1, 1, 2] })
}
/// The Fujifilm X-Trans 6×6 layout (as commonly documented), anchored at (0, 0).
pub fn xtrans() -> Cfa {
let rows = ["GGRGGB", "GGBGGR", "BRGRBG", "GGBGGR", "GGRGGB", "RBGBRG"];
let pattern = rows
.iter()
.flat_map(|r| {
r.chars().map(|c| match c {
'R' => 0,
'G' => 1,
_ => 2,
})
})
.collect();
Cfa { width: 6, height: 6, pattern }
}
#[inline]
pub fn color_at(&self, x: usize, y: usize) -> u8 {
self.pattern[(y % self.height) * self.width + (x % self.width)]
}
/// The same pattern anchored at `(dx, dy)` of the current anchor (e.g. after cropping to an active area).
pub fn shifted(&self, dx: usize, dy: usize) -> Cfa {
let pattern = (0..self.height).flat_map(|y| (0..self.width).map(move |x| (x, y))).map(|(x, y)| self.color_at(x + dx, y + dy)).collect();
Cfa { width: self.width, height: self.height, pattern }
}
pub fn is_bayer(&self) -> bool {
if self.width != 2 || self.height != 2 {
return false;
}
let mut c = [0; 3];
for &p in &self.pattern {
if p > 2 {
return false;
}
c[p as usize] += 1;
}
c == [1, 2, 1]
}
/// Pattern name like `"RGGB"` for 2×2 patterns.
pub fn name(&self) -> String {
self.pattern.iter().map(|&c| ['R', 'G', 'B', '?'][c.min(3) as usize]).collect()
}
fn valid(&self) -> bool {
self.width > 0 && self.height > 0 && self.width <= 16 && self.height <= 16 && self.pattern.len() == self.width * self.height
}
}
/// Integer rectangle (pixels).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Rect {
pub x: usize,
pub y: usize,
pub width: usize,
pub height: usize,
}
impl Rect {
pub fn new(x: usize, y: usize, width: usize, height: usize) -> Rect {
Rect { x, y, width, height }
}
/// Clip to a `w × h` area.
pub fn clipped(self, w: usize, h: usize) -> Rect {
let x = self.x.min(w);
let y = self.y.min(h);
Rect { x, y, width: self.width.min(w - x), height: self.height.min(h - y) }
}
}
/// Black level model (DNG `BlackLevelRepeatDim`, `BlackLevel`, `BlackLevelDeltaH/V`). The repeat pattern and
/// the deltas are anchored at the active area's top-left corner.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BlackLevel {
pub repeat_rows: usize,
pub repeat_cols: usize,
/// `repeat_rows × repeat_cols × cpp` values.
pub values: Vec<f32>,
/// Per active-area column.
pub delta_h: Vec<f32>,
/// Per active-area row.
pub delta_v: Vec<f32>,
}
impl Default for BlackLevel {
fn default() -> Self {
BlackLevel { repeat_rows: 1, repeat_cols: 1, values: vec![0.0], delta_h: vec![], delta_v: vec![] }
}
}
impl BlackLevel {
pub fn uniform(v: f32) -> BlackLevel {
BlackLevel { values: vec![v], ..Default::default() }
}
/// Black level at active-area coordinates (x, y) for sample `s` of `cpp`.
#[inline]
pub fn at(&self, x: usize, y: usize, s: usize, cpp: usize) -> f32 {
let (r, c) = (self.repeat_rows.max(1), self.repeat_cols.max(1));
let idx = ((y % r) * c + (x % c)) * cpp + s;
let base = self.values.get(idx).or_else(|| self.values.first()).copied().unwrap_or(0.0);
base + self.delta_h.get(x).copied().unwrap_or(0.0) + self.delta_v.get(y).copied().unwrap_or(0.0)
}
/// Mean of the repeat-pattern values (for display / heuristics).
pub fn mean(&self) -> f32 {
if self.values.is_empty() { 0.0 } else { self.values.iter().sum::<f32>() / self.values.len() as f32 }
}
}
/// DNG colour tags (DNG 1.7 chapter 6). Matrices are 3×3 (three-colour cameras).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ColorData {
@@ -779,11 +303,6 @@ impl RawImage {
}
}
/// Validate what a decoder read in `mode` ([`Mode::Header`]: everything but the samples).
pub(crate) fn validate_for(&self, mode: Mode) -> Result<()> {
self.check(mode == Mode::Full)
}
/// Validate internal consistency (dimensions vs data length, CFA shape, rectangles).
pub fn validate(&self) -> Result<()> {
self.check(true)
@@ -807,7 +326,7 @@ impl RawImage {
}
}
if let Some(c) = &self.cfa
&& (!c.valid() || c.pattern.iter().any(|&p| p > 2))
&& (!cfa_valid(c) || c.pattern.iter().any(|&p| p > 2))
{
return Err(RawError::Unsupported(format!("CFA pattern {}", c.name())));
}
File diff suppressed because it is too large. Load diff
-311
View File
@@ -1,311 +0,0 @@
use super::*;
/// Independent 4×4, 16-bit Sony 4:2:0 stream. Hand-specified differences in MCU order.
pub(crate) fn fixture_420() -> Vec<u8> {
fixture_subsampled(4, 4, 0x22, &[-31768, 1, 1000, 1, -16384, -16284, 1, 1, 1, 1, 1, 2, 100, 1, 1000, 1, 100, 100, 1, 1, 1, 1, 1, 2])
}
/// A 16-bit three-component frame of `width × height` pixels with the given luma `sampling` (`0x21` / `0x22`)
/// and one shared 5-bit Huffman table, whose differences are written as given (MCU order).
pub(crate) fn fixture_subsampled(width: u8, height: u8, sampling: u8, differences: &[i32]) -> Vec<u8> {
let mut out = vec![0xff, 0xd8, 0xff, 0xc3, 0, 17, 16, 0, height, 0, width, 3, 1, sampling, 0, 2, 0x11, 0, 3, 0x11, 0];
out.extend_from_slice(&[0xff, 0xc4, 0, 36, 0]);
let mut counts = [0; 16];
counts[4] = 17;
out.extend_from_slice(&counts);
out.extend(0..=16);
out.extend_from_slice(&[0xff, 0xda, 0, 12, 3, 1, 0, 2, 0, 3, 0, 1, 0, 0]);
let mut bw = BitWriter { out, acc: 0, n: 0 };
for &d in differences {
let s = ssss_of(d);
bw.put(s as u32, 5);
if s > 0 && s < 16 {
let v = if d < 0 { d - 1 } else { d };
bw.put(v as u32 & ((1 << s) - 1), s as u32);
}
}
bw.flush();
bw.out.extend_from_slice(&[0xff, 0xd9]);
bw.out
}
#[test]
fn horizontal_only_subsampling_preserves_rows_and_chroma() {
// Independent 4×2, 16-bit 4:2:2 stream: two luma samples, Cb, Cr per MCU.
let enc = fixture_subsampled(4, 2, 0x21, &[-31768, 1, -16384, -16284, 1, 1, 1, 2, 100, 1, 100, 100, 1, 1, 1, 2]);
let frame = decode_subsampled(&enc, 16, Prediction::Geometric).unwrap();
assert_eq!((frame.width, frame.height, frame.vertical_subsampling), (4, 2, 1));
assert_eq!(frame.planes[0], [1000, 1001, 1002, 1003, 1100, 1101, 1102, 1103]);
assert_eq!(frame.planes[1], [16384, 16385, 16484, 16485]);
assert_eq!(frame.planes[2], [16484, 16486, 16584, 16586]);
assert!(decode(&enc, 24).is_err());
assert!(matches!(decode_subsampled(&enc, 15, Prediction::Geometric), Err(RawError::Limit(_))));
assert!(decode_subsampled(&enc[..enc.len() - 6], 16, Prediction::Geometric).is_err());
}
#[test]
fn subsampled_mcu_order_preserves_each_plane() {
let enc = fixture_420();
let frame = decode_subsampled(&enc, 24, Prediction::Geometric).unwrap();
assert_eq!((frame.width, frame.height), (4, 4));
assert_eq!(frame.planes[0], [1000, 1001, 1002, 1003, 2000, 2001, 2002, 2003, 1100, 1101, 1102, 1103, 2100, 2101, 2102, 2103]);
assert_eq!(frame.planes[1], [16384, 16385, 16484, 16485]);
assert_eq!(frame.planes[2], [16484, 16486, 16584, 16586]);
assert!(decode(&enc, 48).is_err()); // CFA API must keep rejecting subsampling.
assert!(matches!(decode_subsampled(&enc, 23, Prediction::Geometric), Err(RawError::Limit(_))));
assert!(decode_subsampled(&enc[..enc.len() - 6], 24, Prediction::Geometric).is_err());
let mut bad = enc.clone();
bad[10] = 3; // odd frame width
assert!(frame_info_subsampled(&bad).is_err());
let sos = bad.windows(2).position(|w| w == [0xff, 0xda]).unwrap();
bad = enc.clone();
bad[sos + 11] = 2; // unsupported predictor
assert!(frame_info_subsampled(&bad).is_err());
}
#[test]
fn sequential_prediction_chains_each_component_in_decoding_order() {
// Canon sRAW / mRAW: the same stream as `subsampled_mcu_order_preserves_each_plane`, but each component
// continues from its previous sample in decoding order (the second luma row of an MCU follows the first),
// and a new MCU row starts from the first sample of the previous one. Worked out by hand from init 32768.
let enc = fixture_420();
let frame = decode_subsampled(&enc, 24, Prediction::Sequential).unwrap();
assert_eq!((frame.width, frame.height, frame.vertical_subsampling), (4, 4, 2));
assert_eq!(frame.planes[0], [1000, 1001, 2003, 2004, 2001, 2002, 2005, 2006, 1100, 1101, 2103, 2104, 2101, 2102, 2105, 2106]);
assert_eq!(frame.planes[1], [16384, 16385, 16484, 16485]);
assert_eq!(frame.planes[2], [16484, 16486, 16584, 16586]);
// 4:2:2 has one luma row per MCU row, so both predictions agree
let enc = fixture_subsampled(4, 2, 0x21, &[-31768, 1, -16384, -16284, 1, 1, 1, 2, 100, 1, 100, 100, 1, 1, 1, 2]);
assert_eq!(
decode_subsampled(&enc, 16, Prediction::Sequential).unwrap().planes,
decode_subsampled(&enc, 16, Prediction::Geometric).unwrap().planes
);
}
fn noise(n: usize, bits: u32, seed: u64) -> Vec<u16> {
let mut s = seed;
(0..n)
.map(|i| {
s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
let smooth = ((i % 97) as u32 * 37) % (1 << bits);
let jitter = ((s >> 33) as u32) % 64;
((smooth + jitter) % (1 << bits)) as u16
})
.collect()
}
#[test]
fn roundtrip_all_predictors_components_precisions() {
for pred in 1..=7u8 {
for comps in 1..=4usize {
for bits in [8u8, 12, 14, 16] {
let (w, h) = (13, 7);
let data = noise(w * h * comps, bits as u32, (pred as u64) * 31 + comps as u64);
let enc = encode(&data, w, h, comps, bits, pred, 0);
let f = decode(&enc, usize::MAX).unwrap();
assert_eq!((f.width, f.height, f.components, f.precision, f.predictor), (w, h, comps, bits, pred));
assert_eq!(f.data, data, "pred {pred} comps {comps} bits {bits}");
}
}
}
}
#[test]
fn roundtrip_extremes_and_restarts() {
// alternating 0 / 65535 forces SSSS = 16 differences
let data: Vec<u16> = (0..64).map(|i| if i % 2 == 0 { 0 } else { 65535 }).collect();
for pred in 1..=7 {
let enc = encode(&data, 8, 8, 1, 16, pred, 0);
assert_eq!(decode(&enc, usize::MAX).unwrap().data, data);
}
let data = noise(20 * 9 * 2, 12, 5);
for rst in [1usize, 7, 20, 40] {
let enc = encode(&data, 20, 9, 2, 12, 6, rst);
assert_eq!(decode(&enc, usize::MAX).unwrap().data, data, "restart {rst}");
}
}
#[test]
fn constant_image_single_symbol_table() {
let data = vec![1234u16; 16 * 4];
let enc = encode(&data, 16, 4, 1, 14, 1, 0);
assert_eq!(decode(&enc, usize::MAX).unwrap().data, data);
}
#[test]
fn rejects_bad_streams() {
assert!(decode(&[], 100).is_err());
assert!(decode(&[0xff, 0xd8, 0xff, 0xd9], 100).is_err());
let data = noise(64, 12, 1);
let enc = encode(&data, 8, 8, 1, 12, 1, 0);
assert!(matches!(decode(&enc, 10), Err(RawError::Limit(_))));
for n in 0..enc.len() {
let _ = decode(&enc[..n], usize::MAX);
}
let mut bad = enc.clone();
for i in (20..bad.len()).step_by(3) {
bad[i] ^= 0x5a;
}
let _ = decode(&bad, usize::MAX);
}
// --- selection value 8 (Hasselblad 3FR / FFF) ---
/// SOI, SOF3 (16 bits, `height` x `width`, one component), a DHT and an SOS with selection value 8, then
/// `entropy` and EOI.
fn hasselblad_stream(width: u16, height: u16, counts: &[u8; 16], values: &[u8], entropy: &[u8]) -> Vec<u8> {
let mut out = vec![0xff, 0xd8, 0xff, 0xc3, 0, 11, 16];
out.extend_from_slice(&height.to_be_bytes());
out.extend_from_slice(&width.to_be_bytes());
out.extend_from_slice(&[1, 0, 0x11, 0]);
out.extend_from_slice(&[0xff, 0xc4]);
out.extend_from_slice(&((2 + 17 + values.len()) as u16).to_be_bytes());
out.push(0);
out.extend_from_slice(counts);
out.extend_from_slice(values);
out.extend_from_slice(&[0xff, 0xda, 0, 8, 1, 0, 0, 8, 0, 0]);
out.extend_from_slice(entropy);
out.extend_from_slice(&[0xff, 0xd9]);
out
}
/// Codes: SSSS 0 = `00`, 1 = `01`, 2 = `100`, 15 = `101`, 16 = `110`.
const HAND_COUNTS: [u8; 16] = [0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
const HAND_VALUES: [u8; 5] = [0, 1, 2, 15, 16];
/// A 4 x 2 frame written out bit by bit:
/// - row 0, pair 1: codes `110` `110` (SSSS 16 twice), then 16 bits each (`FFFF`, `7FFF`) that do not count:
/// both samples are 32768 - 32768 = 0;
/// - row 0, pair 2: codes `01` `100`, bits `1` (+1) and `01` (-2): 0 + 1 = 1 and 0 - 2 = 65534 (modulo 2^16);
/// - row 1, pair 1: codes `00` `01`, bit `0` (-1): both predictors start again at 32768, so 32768 and 32767;
/// - row 1, pair 2: codes `100` `00`, bits `11` (+3): 32771 and 32767.
///
/// 58 bits, padded with zeros to two 32-bit words `DBFFFDFF` `FD9450C0`, stored little-endian. The `FF FD`
/// they start with would be a marker to a T.81 reader: this coding has no byte stuffing.
const HAND_WORDS: [u8; 8] = [0xff, 0xfd, 0xff, 0xdb, 0xc0, 0x50, 0x94, 0xfd];
const HAND_SAMPLES: [u16; 8] = [0, 0, 1, 65534, 32768, 32767, 32771, 32767];
#[test]
fn selection_value_8_known_answer() {
let enc = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS);
assert_eq!(frame_info(&enc).unwrap(), (4, 2, 1, 16));
let f = decode(&enc, 8).unwrap();
assert_eq!((f.width, f.height, f.components, f.predictor), (4, 2, 1, 8));
assert_eq!(f.data, HAND_SAMPLES);
assert_eq!(decode_hasselblad(&enc, 8).unwrap().data, HAND_SAMPLES);
assert!(matches!(decode(&enc, 7), Err(RawError::Limit(_))));
}
/// The same bits in plain byte order (not 32-bit little-endian words) are a different stream.
#[test]
fn selection_value_8_reads_little_endian_words() {
let mut plain = HAND_WORDS;
plain[..4].reverse();
plain[4..].reverse();
let enc = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &plain);
assert_ne!(decode(&enc, 8).map(|f| f.data).ok(), Some(HAND_SAMPLES.to_vec()));
}
#[test]
fn selection_value_8_rejects_bad_streams() {
// one word is not enough for the second row
let short = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS[..4]);
assert!(decode(&short, 8).is_err());
// a category above 16
let enc = hasselblad_stream(4, 2, &HAND_COUNTS, &[0, 1, 2, 15, 17], &HAND_WORDS);
assert!(decode(&enc, 8).is_err());
// layouts never seen with selection value 8 are not guessed at
let mut odd = hasselblad_stream(3, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS);
assert!(matches!(frame_info(&odd), Err(RawError::Unsupported(_))));
assert!(matches!(decode(&odd, 8), Err(RawError::Unsupported(_))));
odd = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS);
odd[6] = 14; // precision
assert!(matches!(decode(&odd, 8), Err(RawError::Unsupported(_))));
// selection values above 8 stay unknown
let mut nine = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS);
let sos = nine.windows(2).position(|w| w == [0xff, 0xda]).unwrap();
nine[sos + 7] = 9;
assert!(matches!(decode(&nine, 8), Err(RawError::Unsupported(w)) if w.contains("selection value 9")));
// every prefix fails cleanly
let enc = hasselblad_stream(4, 2, &HAND_COUNTS, &HAND_VALUES, &HAND_WORDS);
for n in 0..enc.len() {
let _ = decode(&enc[..n], 8);
}
}
/// Test-only writer of the selection-value-8 coding (the inverse of the rule in [`decode_hasselblad`]), with
/// a 5-bit code for every category. Category-16 differences carry `FFFF` as their ignored bits.
pub(crate) fn encode_hasselblad(data: &[u16], width: usize, height: usize) -> Vec<u8> {
assert!(width.is_multiple_of(2) && data.len() == width * height);
let mut bits: Vec<bool> = vec![];
let put = |bits: &mut Vec<bool>, v: u32, n: u32| {
for i in (0..n).rev() {
bits.push((v >> i) & 1 == 1);
}
};
for row in data.chunks_exact(width) {
let mut last = [32768i32, 32768];
for pair in row.as_chunks::<2>().0 {
let mut d = [0i32; 2];
for k in 0..2 {
let mut v = (pair[k] as i32 - last[k]) & 0xffff;
if v >= 32768 {
v -= 65536;
}
d[k] = v;
last[k] = pair[k] as i32;
}
let s = [ssss_of(d[0]), ssss_of(d[1])];
put(&mut bits, s[0] as u32, 5);
put(&mut bits, s[1] as u32, 5);
for k in 0..2 {
match s[k] {
0 => {}
16 => put(&mut bits, 0xffff, 16),
n => {
let v = if d[k] < 0 { d[k] - 1 } else { d[k] };
put(&mut bits, v as u32 & ((1 << n) - 1), n as u32);
}
}
}
}
}
let mut entropy = vec![];
for word in bits.chunks(32) {
let w = word.iter().enumerate().fold(0u32, |a, (i, &b)| a | ((b as u32) << (31 - i)));
entropy.extend_from_slice(&w.to_le_bytes());
}
let mut counts = [0u8; 16];
counts[4] = 17;
let values: Vec<u8> = (0..=16).collect();
hasselblad_stream(width as u16, height as u16, &counts, &values, &entropy)
}
#[test]
fn selection_value_8_round_trips_through_the_test_writer() {
// extremes force SSSS 16 and wrap-around; noise exercises every other category
let mut data = noise(10 * 7, 16, 9);
data[0] = 0;
data[1] = 65535;
data[2] = 65535;
data[3] = 0;
let enc = encode_hasselblad(&data, 10, 7);
assert_eq!(decode(&enc, 70).unwrap().data, data);
}
#[test]
fn code_lengths_are_limited_to_16() {
// Fibonacci-like frequencies produce very long codes before adjustment
let mut f = [0u32; 17];
let (mut a, mut b) = (1u32, 1u32);
for x in f.iter_mut() {
*x = a;
let c = a.saturating_add(b);
a = b;
b = c;
}
let (counts, values) = code_lengths(&f);
assert_eq!(counts.iter().map(|&c| c as usize).sum::<usize>(), 17);
assert_eq!(values.len(), 17);
assert!(Huffman::new(&counts, &values).is_ok());
}
-536
View File
@@ -1,536 +0,0 @@
//! RDD 34:2015 LLVC codec core as Sony's ARW6 uses it; see docs/arw6-compression.md.
//!
//! Clean-room: written from SMPTE RDD 34:2015 §6.3 (Figures 6.5-6.8) and checked against its worked
//! example (Figure 6.9) and Phase 0 oracle vectors. No other raw decoder's source was consulted.
use crate::vendor::pef::Bits;
use crate::{RawError, Result};
/// Largest coefficient bit depth (DPT) a stream may select; keeps `Bits::get` in range.
pub(crate) const MAX_DPT: u32 = 24;
fn corrupt(why: &str) -> RawError {
RawError::Corrupt(format!("ARW6 VLD: {why}"))
}
/// One bit, failing when the reader has run past the `source_bits` of its half.
#[inline(always)]
fn bit(bits: &mut Bits<'_>, source_bits: usize) -> Result<u32> {
let b = bits.get(1);
if bits.consumed_bits() > source_bits {
return Err(corrupt("past the end of its half"));
}
Ok(b)
}
/// Count zero bits up to and including the terminating 1 (the `0^n 1` codes), bounded by `MAX_DPT`.
fn zeros_then_one(bits: &mut Bits<'_>, source_bits: usize) -> Result<u32> {
// the next MAX_DPT + 1 bits at once (more zeros than that is corrupt either way)
let n = bits.peek(MAX_DPT + 1).leading_zeros() - (32 - (MAX_DPT + 1));
bits.skip((n + 1).min(MAX_DPT + 1));
if bits.consumed_bits() > source_bits {
return Err(corrupt("past the end of its half"));
}
if n > MAX_DPT {
return Err(corrupt("DPT code exceeds MAX_DPT"));
}
Ok(n)
}
/// Decode one coefficient line of `width.div_ceil(4)` sets (RDD 34 §6.3.6) and return exactly `width` values.
pub(crate) fn vld_decode_line(bits: &mut Bits<'_>, source_bits: usize, width: usize) -> Result<Vec<i32>> {
if width == 0 {
return Ok(Vec::new()); // no sets: the state machine below would never terminate
}
let sets = width.div_ceil(4);
let (mut abs, mut dpt, mut cnt, mut dpts) = ([0u32; 4], 0u32, sets, 0u8);
let (mut abs_v, mut abs_e, mut dpt_v, mut dpt_e, mut zr) = (false, false, true, false, 0u64);
let mut out: Vec<i32> = Vec::with_capacity(sets * 4);
loop {
// DPT value decoding (Figure 6.6).
if cnt == 0 {
dpt_v = false;
}
if cnt == 1 {
dpt_e = true;
}
cnt = cnt.saturating_sub(1);
zr = zr.saturating_sub(1);
if dpt_v {
match dpts {
0 => {
if bit(bits, source_bits)? == 0 {
// Sony deviation 1, oracle-verified in Phase 0: a zero code at DPT 0 is a zero set entering run mode.
if dpt == 0 {
dpts = 1;
}
} else if bit(bits, source_bits)? == 0 {
// "1 0 0^n 1": DPT up by n+1.
dpt = dpt.saturating_add(zeros_then_one(bits, source_bits)? + 1);
} else {
// "1 1 0^n 1" (DPT down by n+1) or "1 1 0^(DPT-1)" (DPT to 0).
let mut n = 0;
while n + 1 < dpt && bit(bits, source_bits)? == 0 {
n += 1;
}
if n + 1 >= dpt {
dpt = 0;
dpts = 1;
} else {
dpt -= n + 1;
}
}
}
1 => {
if bit(bits, source_bits)? == 1 {
// "1 0^n 1": leave run mode at DPT n+1.
dpt = zeros_then_one(bits, source_bits)? + 1;
dpts = 0;
} else {
// Run code of ceil(log2(Cnt+2)) bits (Figure 6.6).
let lim = (cnt as u64 + 2).next_power_of_two().trailing_zeros();
if lim > 32 {
return Err(corrupt("line too wide"));
}
let mut m = 1;
while m < lim && bit(bits, source_bits)? == 0 {
m += 1;
}
if m == lim {
// "0^lim": the rest of the line is zero.
zr = cnt as u64 + 2;
} else {
zr = 1;
for _ in 0..m {
zr = (zr << 1) | bit(bits, source_bits)? as u64;
}
}
dpts = 2;
}
}
_ => {
// Sony deviation 2, oracle-verified in Phase 0: the run ends at ZR == 1 (RDD 34 says 0).
if zr == 1 {
dpt = zeros_then_one(bits, source_bits)? + 1;
dpts = 0;
}
}
}
if dpt > MAX_DPT {
return Err(corrupt("DPT exceeds MAX_DPT"));
}
}
// SGN value decoding (Figure 6.7): signs of the previous set.
if abs_v {
for v in abs {
let v = v as i32;
out.push(if v != 0 && bit(bits, source_bits)? == 1 { -v } else { v });
}
}
if abs_e {
out.truncate(width);
return Ok(out);
}
abs_v = dpt_v;
abs_e = dpt_e;
// ABS value decoding (Figure 6.8).
if dpt_v {
for a in abs.iter_mut() {
*a = bits.get(dpt);
}
if bits.consumed_bits() > source_bits {
return Err(corrupt("past the end of its half"));
}
}
}
}
/// Parity dequantiser, Phase 0 (oracle-verified): 0 -> 0, qi = 0 -> q, else
/// `sign(q) * (((2|q| + 1) << (qi - 1)) - (|q| & 1))`. Saturates instead of overflowing on hostile input.
pub(crate) fn dequant(q: i32, qi: u32) -> i32 {
if q == 0 || qi == 0 {
return q;
}
let a = i64::from(q).abs();
let m = (((2 * a + 1) << (qi - 1).min(30)) - (a & 1)).min(i64::from(i32::MAX));
(if q < 0 { -m } else { m }) as i32
}
/// A row-major plane of integer samples.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Plane {
pub width: usize,
pub height: usize,
pub data: Vec<i32>,
}
impl Plane {
pub fn zeros(width: usize, height: usize) -> Plane {
Plane { width, height, data: vec![0; width.saturating_mul(height)] }
}
pub fn row(&self, y: usize) -> Option<&[i32]> {
let start = y.checked_mul(self.width)?;
self.data.get(start..start.checked_add(self.width)?)
}
fn ok(&self) -> bool {
self.width.checked_mul(self.height) == Some(self.data.len())
}
}
/// `(low, high)` sample counts of an `n`-sample signal whose low-pass samples sit at indices = `phase` (mod 2).
pub(crate) fn band_rows(n: usize, phase: u8) -> (usize, usize) {
let low = (n + 1).saturating_sub(usize::from(phase)) / 2;
(low, n - low)
}
/// Saturating narrowing: hostile coefficients clamp instead of overflowing.
fn sat(v: i64) -> i32 {
v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32
}
/// Sample `i` (`w` values wide) of a band of `n` samples, clamped into range (the whole-sample symmetric extension);
/// `zeros` for an empty band.
#[inline]
fn band_sample<'a>(v: &'a [i32], w: usize, n: usize, i: isize, zeros: &'a [i32]) -> &'a [i32] {
if n == 0 {
return zeros;
}
let i = i.clamp(0, n as isize - 1) as usize;
v.get(i * w..(i + 1) * w).unwrap_or(zeros)
}
/// Inverse 5/3 lifting, RDD 34 §6.5, with X[-1] := X[1], X[n] := X[n-2] (see `band_rows` for the sizes), of a
/// signal whose samples are `w` values wide: a band's width for all its columns at once (row by row, as each column
/// alone would give; rows in parallel). One line (`w = 1`) goes through [`lift_row`].
fn inverse_lift(l: &[i32], h: &[i32], w: usize, phase: u8) -> Result<Vec<i32>> {
use rayon::prelude::*;
let w = w.max(1);
let (nl, nh) = (l.len() / w, h.len() / w);
let (n, p) = (nl + nh, isize::from(phase));
if band_rows(n, phase) != (nl, nh) || phase > 1 {
return Err(RawError::Corrupt("ARW6 wavelet: band sizes do not match".into()));
}
let zeros = vec![0; w];
let mut even = vec![0; nl * w];
even.par_chunks_exact_mut(w).zip(l.par_chunks_exact(w)).enumerate().for_each(|(j, (e, lv))| {
let (a, b) = (band_sample(h, w, nh, j as isize - 1 + p, &zeros), band_sample(h, w, nh, j as isize + p, &zeros));
for (((e, &lv), &a), &b) in e.iter_mut().zip(lv).zip(a).zip(b) {
*e = sat(i64::from(lv) - ((i64::from(a) + i64::from(b) + 2) >> 2));
}
});
let mut out = vec![0; n * w];
let lo = usize::from(phase);
out.par_chunks_exact_mut(w).enumerate().for_each(|(t, o)| {
if t % 2 == lo {
if let Some(e) = even.get((t - lo) / 2 * w..((t - lo) / 2 + 1) * w) {
o.copy_from_slice(e);
}
return;
}
let k = (t - (1 - lo)) / 2;
let Some(hv) = h.get(k * w..(k + 1) * w) else { return };
let (a, b) = (band_sample(&even, w, nl, k as isize - p, &zeros), band_sample(&even, w, nl, k as isize + 1 - p, &zeros));
for (((o, &hv), &a), &b) in o.iter_mut().zip(hv).zip(a).zip(b) {
*o = sat(i64::from(hv) + ((i64::from(a) + i64::from(b)) >> 1));
}
});
Ok(out)
}
/// [`inverse_lift`] of one line (`w = 1`) into `out` (`l.len() + h.len()` values), without allocating: `even` is
/// scratch space. The caller has checked the band sizes.
fn lift_row(l: &[i32], h: &[i32], phase: u8, even: &mut Vec<i32>, out: &mut [i32]) {
let (nl, nh, p) = (l.len(), h.len(), isize::from(phase));
let hs = |i: isize| if nh == 0 { 0 } else { h.get(i.clamp(0, nh as isize - 1) as usize).map_or(0, |&v| i64::from(v)) };
even.clear();
even.extend(l.iter().enumerate().map(|(j, &lv)| sat(i64::from(lv) - ((hs(j as isize - 1 + p) + hs(j as isize + p) + 2) >> 2))));
let even = &*even;
let es = |i: isize| if nl == 0 { 0 } else { even.get(i.clamp(0, nl as isize - 1) as usize).map_or(0, |&v| i64::from(v)) };
let (lo, hi) = (usize::from(phase), 1 - usize::from(phase));
for (o, &e) in out.iter_mut().skip(lo).step_by(2).zip(even.iter()) {
*o = e;
}
for (k, (o, &hv)) in out.iter_mut().skip(hi).step_by(2).zip(h).enumerate() {
*o = sat(i64::from(hv) + ((es(k as isize - p) + es(k as isize + 1 - p)) >> 1));
}
}
/// Inverse transform of the `low`/`high` pair along one axis: down the columns when `vertical` (all at once, row by
/// row), else along each row.
fn lines(low: &Plane, high: &Plane, phase: u8, vertical: bool) -> Result<Plane> {
if !low.ok() || !high.ok() {
return Err(RawError::Corrupt("ARW6 wavelet: plane size mismatch".into()));
}
let (across_l, across_h) = if vertical { (low.width, high.width) } else { (low.height, high.height) };
if across_l != across_h {
return Err(RawError::Corrupt("ARW6 wavelet: band sizes do not match".into()));
}
let (nl, nh) = if vertical { (low.height, high.height) } else { (low.width, high.width) };
let n = nl + nh;
let (w, h) = if vertical { (across_l, n) } else { (n, across_l) };
if across_l == 0 {
return Ok(Plane::zeros(w, h));
}
if vertical {
return Ok(Plane { width: w, height: h, data: inverse_lift(&low.data, &high.data, w, phase)? });
}
if band_rows(n, phase) != (nl, nh) || phase > 1 {
return Err(RawError::Corrupt("ARW6 wavelet: band sizes do not match".into()));
}
use rayon::prelude::*;
let mut out = Plane::zeros(w, h);
out.data.par_chunks_exact_mut(w.max(1)).enumerate().for_each_init(Vec::new, |even, (i, r)| {
if let (Some(l), Some(hi)) = (low.row(i), high.row(i)) {
lift_row(l, hi, phase, even, r);
}
});
Ok(out)
}
/// Vertical inverse 5/3 (along rows of samples): `low`/`high` are stacked bands of equal width.
pub(crate) fn inverse_53_1d_rows(low: &Plane, high: &Plane, phase: u8) -> Result<Plane> {
lines(low, high, phase, true)
}
/// Horizontal inverse 5/3: `low`/`high` are side-by-side bands of equal height.
pub(crate) fn inverse_53_1d_cols(low: &Plane, high: &Plane, phase: u8) -> Result<Plane> {
lines(low, high, phase, false)
}
/// 2-D inverse, RDD 34 §6.5 order: vertical IWT (phase `vphase`) on (ll, lh) and (hl, hh), then horizontal (phase 0).
pub(crate) fn inverse_53_2d(ll: &Plane, lh: &Plane, hl: &Plane, hh: &Plane, vphase: u8) -> Result<Plane> {
let lo = inverse_53_1d_rows(ll, lh, vphase)?;
let hi = inverse_53_1d_rows(hl, hh, vphase)?;
inverse_53_1d_cols(&lo, &hi, 0)
}
/// The ten bands of a 3-level decomposition (LL only at the deepest level).
pub(crate) struct Bands3 {
pub ll3: Plane,
pub hl3: Plane,
pub lh3: Plane,
pub hh3: Plane,
pub hl2: Plane,
pub lh2: Plane,
pub hh2: Plane,
pub hl1: Plane,
pub lh1: Plane,
pub hh1: Plane,
}
/// Full inverse: level 3 uses `phases[2]`, level 2 `phases[1]`, level 1 `phases[0]`.
pub(crate) fn reconstruct3(b: &Bands3, phases: [u8; 3]) -> Result<Plane> {
let ll2 = inverse_53_2d(&b.ll3, &b.lh3, &b.hl3, &b.hh3, phases[2])?;
let ll1 = inverse_53_2d(&ll2, &b.lh2, &b.hl2, &b.hh2, phases[1])?;
inverse_53_2d(&ll1, &b.lh1, &b.hl1, &b.hh1, phases[0])
}
#[cfg(test)]
mod tests {
use super::*;
use crate::vendor::pef::Bits;
fn bits_of(s: &str) -> Vec<u8> {
let mut out = vec![0u8; s.len().div_ceil(8)];
for (i, c) in s.bytes().enumerate() {
if c == b'1' {
out[i / 8] |= 0x80 >> (i % 8);
}
}
out
}
fn line(s: &str, width: usize) -> (Vec<i32>, usize) {
let src = bits_of(s);
let mut b = Bits::new(&src);
let v = vld_decode_line(&mut b, src.len() * 8, width).unwrap();
(v, b.consumed_bits())
}
#[test]
fn rdd34_figure_6_9_worked_example() {
// RDD 34:2015 §6.3.6, Figure 6.9: 8 sets, 91 bits
let s = "1000010110000010000100110000101000010100110100000000000011000010010001001010011100110000000";
let (v, used) = line(s, 32);
assert_eq!(v, vec![6, 0, -8, 4, 0, 0, 0, 0, -9, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(used, 91);
}
#[test]
fn sony_zero_at_dpt0_enters_run_state() {
// Phase 0 vector "dev1": a "0" at DPT 0 is a zero set that moves to DPTs = 1; the next set uses the "1 0^n 1" code
let (v, used) = line("01001101000011001010", 8);
assert_eq!(v, vec![0, 0, 0, 0, 5, 0, -3, 1]);
assert_eq!(used, 20);
}
#[test]
fn sony_run_value_means_minus_one_zero_sets() {
// Phase 0 vector "dev2": run code value 3 = two more zero sets, then "0^n 1" post-run DPT
let (v, used) = line("001101100000000", 16);
assert_eq!(v, vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0]);
assert_eq!(used, 15);
}
#[test]
fn end_of_line_zero_code() {
let (v, used) = line("1001110100101100100", 12);
assert_eq!(v, vec![3, -1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(used, 19);
}
#[test]
fn dpt_moves_up_down_and_to_zero() {
let (v, used) = line("1011000100101111111110011101001011111100000", 20);
assert_eq!(v, vec![1, 0, 0, 0, 7, 7, -7, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(used, 43);
}
#[test]
fn all_zero_line_is_two_bits_and_width_truncates() {
let (v, used) = line("00", 6); // L = 2 sets, width 6 keeps 6 of 8 values
assert_eq!(v, vec![0; 6]);
assert_eq!(used, 2);
}
#[test]
fn width_zero_returns_empty_line() {
let (v, used) = line("1111", 0);
assert!(v.is_empty());
assert_eq!(used, 0);
}
#[test]
fn hostile_input_errors_instead_of_panicking() {
let mut climb = vec![0u8; 64];
climb[0] = 0x80; // "1 0 0^n 1" with n > MAX_DPT
let mut b = Bits::new(&climb);
assert!(matches!(vld_decode_line(&mut b, 512, 16), Err(RawError::Corrupt(_))));
let short = bits_of("10"); // needs more bits than it has
let mut b = Bits::new(&short);
assert!(matches!(vld_decode_line(&mut b, 2, 16), Err(RawError::Corrupt(_))));
}
proptest::proptest! {
#[test]
fn random_bits_never_panic(src in proptest::collection::vec(proptest::num::u8::ANY, 0..256), width in 0usize..300) {
let mut b = Bits::new(&src);
let _ = vld_decode_line(&mut b, src.len() * 8, width);
}
}
fn col(v: &[i32]) -> Plane {
Plane { width: 1, height: v.len(), data: v.to_vec() }
}
#[test]
fn dequant_parity_rule() {
for (qi, table) in
[(0u32, [-3, -2, -1, 0, 1, 2, 3]), (1, [-6, -5, -2, 0, 2, 5, 6]), (2, [-13, -10, -5, 0, 5, 10, 13]), (3, [-27, -20, -11, 0, 11, 20, 27])]
{
for (q, v) in (-3..=3).zip(table) {
assert_eq!(dequant(q, qi), v, "q={q} qi={qi}");
}
}
}
#[test]
fn quantize_inverts_dequant() {
for qi in 0..6 {
for q in -50..=50 {
assert_eq!(crate::vendor::arw6_testenc::quantize(dequant(q, qi), qi), q, "q={q} qi={qi}");
}
}
}
#[test]
fn dequant_does_not_overflow() {
assert_eq!(dequant(i32::MAX, 31), i32::MAX);
assert_eq!(dequant(i32::MIN, 40), -i32::MAX);
}
#[test]
fn extreme_coefficients_do_not_overflow() {
for v in [i32::MAX, i32::MIN] {
for (w, h) in [(7usize, 9usize), (16, 16), (9, 16)] {
let p = |w, h| Plane { width: w, height: h, data: vec![v; w * h] };
for ph in 0..2u8 {
let (lh, lw) = (band_rows(h, ph), band_rows(w, 0));
assert!(inverse_53_2d(&p(lw.0, lh.0), &p(lw.0, lh.1), &p(lw.1, lh.0), &p(lw.1, lh.1), ph).is_ok());
}
let (w3, h3) = (w * 8, h * 8);
let mut sizes = vec![];
let (mut cw, mut ch) = (w3, h3);
for ph in [0u8; 3] {
let (a, b) = (band_rows(cw, 0), band_rows(ch, ph));
sizes.push((a, b));
(cw, ch) = (a.0, b.0);
}
let q = |l: usize, xh: bool, yh: bool| {
let ((a, b), (c, d)) = sizes[l];
p(if xh { b } else { a }, if yh { d } else { c })
};
let b = Bands3 {
ll3: q(2, false, false),
hl3: q(2, true, false),
lh3: q(2, false, true),
hh3: q(2, true, true),
hl2: q(1, true, false),
lh2: q(1, false, true),
hh2: q(1, true, true),
hl1: q(0, true, false),
lh1: q(0, false, true),
hh1: q(0, true, true),
};
assert!(reconstruct3(&b, [0, 1, 0]).is_ok());
}
}
}
#[test]
fn band_rows_counts() {
assert_eq!(band_rows(1093, 0), (547, 546));
assert_eq!(band_rows(1093, 1), (546, 547));
assert_eq!(band_rows(1668, 0), (834, 834));
assert_eq!(band_rows(5, 1), (2, 3));
assert_eq!(band_rows(1, 1), (0, 1));
}
#[test]
fn inverse_53_hand_vectors() {
// computed by hand from RDD 34 §6.5 with X[-1] := X[1], X[n] := X[n-2]; checked against the Phase 0 model
assert_eq!(inverse_53_1d_rows(&col(&[10, 20]), &col(&[3, -4]), 0).unwrap().data, vec![8, 17, 20, 16]);
assert_eq!(inverse_53_1d_rows(&col(&[10, 20]), &col(&[3, -4]), 1).unwrap().data, vec![13, 10, 12, 22]);
assert_eq!(inverse_53_1d_rows(&col(&[10, 20, 30]), &col(&[3, -4]), 0).unwrap().data, vec![8, 17, 20, 22, 32]);
assert_eq!(inverse_53_1d_rows(&col(&[3, -4]), &col(&[10, 20, 30]), 1).unwrap().data, vec![5, -5, 9, -17, 13]);
}
#[test]
fn horizontal_pass_gives_the_vertical_passs_samples() {
// two implementations of one lifting: `lift_row` along rows, `inverse_lift` down columns
let mut s = 0x9e37_79b9_7f4a_7c15u64;
let mut next = || {
s ^= s << 13;
s ^= s >> 7;
s ^= s << 17;
(s % 8191) as i32 - 4095
};
for n in 1..12usize {
for phase in 0..2u8 {
let ((nl, nh), rows) = (band_rows(n, phase), 3);
let low = Plane { width: nl, height: rows, data: (0..nl * rows).map(|_| next()).collect() };
let high = Plane { width: nh, height: rows, data: (0..nh * rows).map(|_| next()).collect() };
let across = inverse_53_1d_cols(&low, &high, phase).unwrap();
for r in 0..rows {
let down = inverse_53_1d_rows(&col(low.row(r).unwrap()), &col(high.row(r).unwrap()), phase).unwrap();
assert_eq!(across.row(r).unwrap(), &down.data[..], "n {n}, phase {phase}, row {r}");
}
}
}
}
#[test]
fn inverse_53_rejects_mismatched_bands() {
assert!(inverse_53_1d_rows(&col(&[1, 2, 3]), &col(&[1]), 0).is_err());
assert!(inverse_53_1d_rows(&col(&[1, 2]), &Plane::zeros(2, 2), 0).is_err());
assert!(inverse_53_1d_cols(&col(&[1, 2]), &col(&[1, 2, 3]), 0).is_err());
}
proptest::proptest! {
#[test]
fn forward_then_inverse_is_identity(w in 1usize..24, h in 1usize..40, p1 in 0u8..2, p2 in 0u8..2, p3 in 0u8..2, seed in proptest::num::u64::ANY) {
use crate::vendor::arw6_testenc::{forward3, forward_53_2d};
use proptest::prop_assert_eq;
let mut s = seed | 1;
let mut next = || { s ^= s << 13; s ^= s >> 7; s ^= s << 17; (s % 8191) as i32 - 4095 };
let x = Plane { width: w, height: h, data: (0..w * h).map(|_| next()).collect() };
let (ll, lh, hl, hh) = forward_53_2d(&x, p1);
prop_assert_eq!(inverse_53_2d(&ll, &lh, &hl, &hh, p1).unwrap(), x.clone());
if w >= 8 && h >= 8 {
prop_assert_eq!(reconstruct3(&forward3(&x, [p1, p2, p3]), [p1, p2, p3]).unwrap(), x);
}
}
}
}
+6 -504
View File
@@ -1,6 +1,6 @@
//! DNG opcode lists (`OpcodeList1/2/3`, DNG 1.7 chapter 7). Opcode lists are always big-endian.
//!
//! Parsed: every opcode (unknown ones are kept as [`Opcode::Unknown`]). Applied: `WarpRectilinear`,
//! Parsed (by `craft-raw`): every opcode (unknown ones are kept as [`Opcode::Unknown`]). Applied: `WarpRectilinear`,
//! `WarpRectilinear2` (opcode 14, DNG 1.6; see [`Opcode::WarpRectilinear2`]), `FixVignetteRadial`,
//! `FixBadPixelsConstant`, `FixBadPixelsList`, `MapTable`, `MapPolynomial`, `GainMap`, `DeltaPerRow/Column`,
//! `ScalePerRow/Column`. `TrimBounds` and `WarpFisheye` are recorded but not applied.
@@ -12,511 +12,13 @@
//! Value convention: list 1 runs on raw sample values (16-bit scale), lists 2 and 3 on values normalised to
//! [0, 1]; table/polynomial/delta opcodes are defined on the normalised range and are rescaled accordingly.
pub use craft_raw::opcodes::{Area, Opcode, OpcodeLists, WR2_LEN, applied_ops, parse_list, wr2_factor, write_list};
use crate::{Cfa, Rgb32f};
use serde::{Deserialize, Serialize};
/// Rectangular area + plane selection + pitch shared by the "area" opcodes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Area {
pub top: u32,
pub left: u32,
pub bottom: u32,
pub right: u32,
pub plane: u32,
pub planes: u32,
pub row_pitch: u32,
pub col_pitch: u32,
}
/// Values per coefficient set of `WarpRectilinear2`: 15 radial (`kr0..kr14`), 2 tangential (`kt0`, `kt1`),
/// `min_valid_radius`, `max_valid_radius`.
pub const WR2_LEN: usize = 19;
/// Most coefficient sets (planes) a `WarpRectilinear2` may carry.
const WR2_MAX_PLANES: usize = 4;
/// Largest magnitude accepted for a `WarpRectilinear2` coefficient (a real lens fit is far below this; it keeps the
/// polynomial finite for any radius up to 1).
const WR2_MAX_COEF: f64 = 1e9;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Opcode {
/// Per-plane radial (kr0..kr3) + tangential (kt0, kt1) coefficients and the relative optical centre.
WarpRectilinear {
planes: Vec<[f64; 6]>,
center: [f64; 2],
},
WarpFisheye {
planes: Vec<[f64; 4]>,
center: [f64; 2],
},
/// DNG 1.6 `WarpRectilinear2` (opcode 14; DNG specification 1.6.0.0, chapter 7, "WarpRectilinear2"). Per plane
/// `[kr0 .. kr14, kt0, kt1, min_valid_radius, max_valid_radius]` ([`WR2_LEN`] values, see [`wr2_factor`]),
/// the relative optical centre, and `reciprocalRadial`. `optional` is opcode flag bit 0, which turns on the skip
/// rule for the next warp opcode.
WarpRectilinear2 {
planes: Vec<[f64; WR2_LEN]>,
center: [f64; 2],
reciprocal: bool,
optional: bool,
},
FixVignetteRadial {
k: [f64; 5],
center: [f64; 2],
},
FixBadPixelsConstant {
constant: u32,
bayer_phase: u32,
},
FixBadPixelsList {
bayer_phase: u32,
points: Vec<(u32, u32)>,
rects: Vec<[u32; 4]>,
},
TrimBounds {
top: u32,
left: u32,
bottom: u32,
right: u32,
},
MapTable {
area: Area,
table: Vec<u16>,
},
MapPolynomial {
area: Area,
coefficients: Vec<f64>,
},
GainMap {
area: Area,
points_v: u32,
points_h: u32,
spacing: [f64; 2],
origin: [f64; 2],
map_planes: u32,
gains: Vec<f32>,
},
DeltaPerRow {
area: Area,
deltas: Vec<f32>,
},
DeltaPerColumn {
area: Area,
deltas: Vec<f32>,
},
ScalePerRow {
area: Area,
scales: Vec<f32>,
},
ScalePerColumn {
area: Area,
scales: Vec<f32>,
},
Unknown {
id: u32,
flags: u32,
params: Vec<u8>,
},
}
impl Opcode {
/// Whether [`apply_list`] / [`apply_list3`] implement this opcode.
pub fn is_applied(&self) -> bool {
!matches!(self, Opcode::Unknown { .. } | Opcode::TrimBounds { .. } | Opcode::WarpFisheye { .. })
}
/// Whether this is a lens correction (`WarpRectilinear`, `WarpRectilinear2`, `FixVignetteRadial`): from a DNG, or
/// the equivalent of a camera's own correction recorded in its raw (Panasonic RW2). Developers that apply these
/// through the "profile corrections" of the develop settings remove them before demosaicing.
pub fn is_lens_correction(&self) -> bool {
matches!(self, Opcode::WarpRectilinear { .. } | Opcode::WarpRectilinear2 { .. } | Opcode::FixVignetteRadial { .. })
}
/// This lens correction re-expressed for the part `crop` of the `width × height` image it was written for: applied
/// to the cropped image it gives the crop of the corrected whole. The centre moves into the crop and the
/// coefficients are rescaled for the crop's farthest corner, the radius every coordinate is normalised by. Centres
/// use the warps' convention (0 and 1 at the first and last pixel), also for `FixVignetteRadial`, as the develop
/// pipeline reads them. `None` for other opcodes, an image or crop under 2 × 2, or a crop outside the image.
pub fn cropped(&self, width: usize, height: usize, crop: crate::Rect) -> Option<Opcode> {
let fits = crop.x.checked_add(crop.width).is_some_and(|r| r <= width) && crop.y.checked_add(crop.height).is_some_and(|b| b <= height);
if width < 2 || height < 2 || crop.width < 2 || crop.height < 2 || !fits {
return None;
}
let (aw, ah) = (width as f64 - 1.0, height as f64 - 1.0);
let (cw, ch) = (crop.width as f64 - 1.0, crop.height as f64 - 1.0);
// the centre in the crop, and the ratio of the crop's normalising radius to the image's
let reframe = |c: [f64; 2]| -> Option<([f64; 2], f64)> {
let (px, py) = (c[0] * aw, c[1] * ah);
let (qx, qy) = (px - crop.x as f64, py - crop.y as f64);
let s = max_radius(qx, qy, cw, ch) / max_radius(px, py, aw, ah);
(s.is_finite() && s > 0.0 && qx.is_finite() && qy.is_finite()).then_some(([qx / cw, qy / ch], s))
};
match self {
// source radius r·(kr0 + kr1 r² + kr2 r⁴ + kr3 r⁶) and tangential terms quadratic in r: with r = r'·s,
// kr_i scales by s^2i and kt by s
Opcode::WarpRectilinear { planes, center } => {
let (center, s) = reframe(*center)?;
let planes = planes
.iter()
.map(|k| {
let mut k = *k;
for (i, v) in k[..4].iter_mut().enumerate() {
*v *= s.powi(2 * i as i32);
}
k[4] *= s;
k[5] *= s;
k
})
.collect();
Some(Opcode::WarpRectilinear { planes, center })
}
// radial factor Σ kr_i r^i between the valid radii: kr_i scales by s^i, the radii by 1/s
Opcode::WarpRectilinear2 { planes, center, reciprocal, optional } => {
let (center, s) = reframe(*center)?;
let planes = planes
.iter()
.map(|k| {
let mut k = *k;
for (i, v) in k[..15].iter_mut().enumerate() {
*v *= s.powi(i as i32);
}
k[15] *= s;
k[16] *= s;
k[17] /= s;
k[18] /= s;
k
})
.collect();
Some(Opcode::WarpRectilinear2 { planes, center, reciprocal: *reciprocal, optional: *optional })
}
// gain 1 + Σ k_i r^(2i+2)
Opcode::FixVignetteRadial { k, center } => {
let (center, s) = reframe(*center)?;
let mut k = *k;
for (i, v) in k.iter_mut().enumerate() {
*v *= s.powi(2 * i as i32 + 2);
}
Some(Opcode::FixVignetteRadial { k, center })
}
_ => None,
}
}
}
/// The opcodes of a list that a reader applies, in order: all of them, minus the DNG 1.6 skip rule (specification
/// 1.6.0.0, chapter 7) — a `WarpRectilinear` or `WarpFisheye` immediately after a `WarpRectilinear2` that is marked
/// optional is not applied. A `WarpRectilinear2` that could not be parsed ([`Opcode::Unknown`]) triggers no skip.
pub fn applied_ops(list: &[Opcode]) -> impl Iterator<Item = &Opcode> {
let mut skip = false;
list.iter().filter(move |op| {
let skipped = skip && matches!(op, Opcode::WarpRectilinear { .. } | Opcode::WarpFisheye { .. });
skip = matches!(op, Opcode::WarpRectilinear2 { optional: true, .. });
!skipped
})
}
/// `WarpRectilinear2` radial factor `r_real / r_ideal` for one coefficient set `k` at ideal radius `r`
/// (specification 1.6.0.0, "WarpRectilinear2"): `f(r) = Σ kr_p · r^p` (p = 0..14) evaluated at `r` clamped to
/// `[min_valid_radius, max_valid_radius]`, so `r_real = r · f` — or `r / f` when `reciprocalRadial` is non-zero.
/// `None` when the factor is not finite (a degenerate set, or `f = 0` with `reciprocalRadial`).
pub fn wr2_factor(k: &[f64; WR2_LEN], reciprocal: bool, r: f64) -> Option<f64> {
let rc = r.clamp(k[17].min(k[18]), k[17].max(k[18]));
let f = k[..15].iter().rev().fold(0.0, |acc, &c| acc * rc + c);
let f = if reciprocal { 1.0 / f } else { f };
f.is_finite().then_some(f)
}
/// The three opcode lists of a DNG raw IFD.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct OpcodeLists {
pub list1: Vec<Opcode>,
pub list2: Vec<Opcode>,
pub list3: Vec<Opcode>,
}
struct Rd<'a> {
d: &'a [u8],
p: usize,
}
impl Rd<'_> {
fn u32(&mut self) -> Option<u32> {
let v = u32::from_be_bytes(self.d.get(self.p..self.p + 4)?.try_into().ok()?);
self.p += 4;
Some(v)
}
fn u16(&mut self) -> Option<u16> {
let v = u16::from_be_bytes(self.d.get(self.p..self.p + 2)?.try_into().ok()?);
self.p += 2;
Some(v)
}
fn f64(&mut self) -> Option<f64> {
let v = f64::from_be_bytes(self.d.get(self.p..self.p + 8)?.try_into().ok()?);
self.p += 8;
Some(v)
}
fn finite_f64(&mut self) -> Option<f64> {
self.f64().filter(|v| v.is_finite())
}
fn f32(&mut self) -> Option<f32> {
let v = f32::from_be_bytes(self.d.get(self.p..self.p + 4)?.try_into().ok()?);
self.p += 4;
Some(v)
}
fn area(&mut self) -> Option<Area> {
Some(Area {
top: self.u32()?,
left: self.u32()?,
bottom: self.u32()?,
right: self.u32()?,
plane: self.u32()?,
planes: self.u32()?,
row_pitch: self.u32()?.max(1),
col_pitch: self.u32()?.max(1),
})
}
fn remaining(&self) -> usize {
self.d.len().saturating_sub(self.p)
}
}
fn parse_one(id: u32, flags: u32, params: &[u8]) -> Option<Opcode> {
let mut reader = Rd { d: params, p: 0 };
let parsed = match id {
1 | 2 | 3 | 14 => parse_warp(id, flags, &mut reader)?,
4 => Opcode::FixBadPixelsConstant { constant: reader.u32()?, bayer_phase: reader.u32()? },
5 => parse_bad_pixel_list(&mut reader)?,
6 => Opcode::TrimBounds { top: reader.u32()?, left: reader.u32()?, bottom: reader.u32()?, right: reader.u32()? },
7..=13 => parse_area_opcode(id, &mut reader)?,
_ => Opcode::Unknown { id, flags, params: params.to_vec() },
};
Some(parsed)
}
fn parse_warp(id: u32, flags: u32, reader: &mut Rd<'_>) -> Option<Opcode> {
match id {
1 => {
let planes = parse_planes(reader, 4, |r| {
Some([r.finite_f64()?, r.finite_f64()?, r.finite_f64()?, r.finite_f64()?, r.finite_f64()?, r.finite_f64()?])
})?;
Some(Opcode::WarpRectilinear { planes, center: [reader.finite_f64()?, reader.finite_f64()?] })
}
2 => {
let planes = parse_planes(reader, 4, |r| Some([r.finite_f64()?, r.finite_f64()?, r.finite_f64()?, r.finite_f64()?]))?;
Some(Opcode::WarpFisheye { planes, center: [reader.finite_f64()?, reader.finite_f64()?] })
}
3 => Some(Opcode::FixVignetteRadial {
k: [reader.finite_f64()?, reader.finite_f64()?, reader.finite_f64()?, reader.finite_f64()?, reader.finite_f64()?],
center: [reader.finite_f64()?, reader.finite_f64()?],
}),
14 => parse_warp_rectilinear2(flags, reader),
_ => None,
}
}
fn parse_planes<const N: usize>(reader: &mut Rd<'_>, max: usize, mut parse: impl FnMut(&mut Rd<'_>) -> Option<[f64; N]>) -> Option<Vec<[f64; N]>> {
let count = reader.u32()? as usize;
if count == 0 || count > max {
return None;
}
(0..count).map(|_| parse(reader)).collect()
}
fn parse_warp_rectilinear2(flags: u32, reader: &mut Rd<'_>) -> Option<Opcode> {
let count = reader.u32()? as usize;
// N sets of 19 doubles, then the centre (2 doubles) and reciprocalRadial (LONG); nothing else.
if count == 0 || count > WR2_MAX_PLANES || reader.remaining() != count * WR2_LEN * 8 + 16 + 4 {
return None;
}
let mut planes = Vec::with_capacity(count);
for _ in 0..count {
let mut coefficients = [0.0; WR2_LEN];
for value in &mut coefficients {
*value = reader.finite_f64().filter(|value| value.abs() <= WR2_MAX_COEF)?;
}
if !(coefficients[17] >= 0.0 && coefficients[17] < coefficients[18] && coefficients[18] <= 1.0) {
return None;
}
planes.push(coefficients);
}
let center = [reader.finite_f64().filter(|value| value.abs() <= 4.0)?, reader.finite_f64().filter(|value| value.abs() <= 4.0)?];
Some(Opcode::WarpRectilinear2 { planes, center, reciprocal: reader.u32()? != 0, optional: flags & 1 != 0 })
}
fn parse_bad_pixel_list(reader: &mut Rd<'_>) -> Option<Opcode> {
let bayer_phase = reader.u32()?;
let (point_count, rect_count) = (reader.u32()? as usize, reader.u32()? as usize);
if point_count.saturating_mul(8).saturating_add(rect_count.saturating_mul(16)) > reader.remaining() {
return None;
}
let points = (0..point_count).map(|_| Some((reader.u32()?, reader.u32()?))).collect::<Option<_>>()?;
let rects = (0..rect_count).map(|_| Some([reader.u32()?, reader.u32()?, reader.u32()?, reader.u32()?])).collect::<Option<_>>()?;
Some(Opcode::FixBadPixelsList { bayer_phase, points, rects })
}
fn parse_area_opcode(id: u32, reader: &mut Rd<'_>) -> Option<Opcode> {
let area = reader.area()?;
match id {
7 => {
let count = reader.u32()? as usize;
if count == 0 || count > 65536 || count * 2 > reader.remaining() {
return None;
}
Some(Opcode::MapTable { area, table: (0..count).map(|_| reader.u16()).collect::<Option<_>>()? })
}
8 => {
let degree = reader.u32()? as usize;
if degree > 8 {
return None;
}
Some(Opcode::MapPolynomial { area, coefficients: (0..=degree).map(|_| reader.finite_f64()).collect::<Option<_>>()? })
}
9 => parse_gain_map(area, reader),
10..=13 => parse_delta_scale(id, area, reader),
_ => None,
}
}
fn parse_gain_map(area: Area, reader: &mut Rd<'_>) -> Option<Opcode> {
let (points_v, points_h) = (reader.u32()?, reader.u32()?);
let spacing = [reader.finite_f64()?, reader.finite_f64()?];
let origin = [reader.finite_f64()?, reader.finite_f64()?];
let map_planes = reader.u32()?;
let count = (points_v as usize).checked_mul(points_h as usize)?.checked_mul(map_planes as usize)?;
if count == 0 || count > reader.remaining() / 4 {
return None;
}
let gains = (0..count).map(|_| reader.f32()).collect::<Option<_>>()?;
Some(Opcode::GainMap { area, points_v, points_h, spacing, origin, map_planes, gains })
}
fn parse_delta_scale(id: u32, area: Area, reader: &mut Rd<'_>) -> Option<Opcode> {
let count = reader.u32()? as usize;
if count > reader.remaining() / 4 {
return None;
}
let values: Vec<f32> = (0..count).map(|_| reader.f32()).collect::<Option<_>>()?;
Some(match id {
10 => Opcode::DeltaPerRow { area, deltas: values },
11 => Opcode::DeltaPerColumn { area, deltas: values },
12 => Opcode::ScalePerRow { area, scales: values },
_ => Opcode::ScalePerColumn { area, scales: values },
})
}
fn put_area(o: &mut Vec<u8>, a: &Area) {
for v in [a.top, a.left, a.bottom, a.right, a.plane, a.planes, a.row_pitch, a.col_pitch] {
o.extend_from_slice(&v.to_be_bytes());
}
}
fn params(op: &Opcode) -> (u32, u32, Vec<u8>) {
let mut o = Vec::new();
let f64s = |o: &mut Vec<u8>, v: &[f64]| v.iter().for_each(|x| o.extend_from_slice(&x.to_be_bytes()));
let u32s = |o: &mut Vec<u8>, v: &[u32]| v.iter().for_each(|x| o.extend_from_slice(&x.to_be_bytes()));
let f32s = |o: &mut Vec<u8>, v: &[f32]| v.iter().for_each(|x| o.extend_from_slice(&x.to_be_bytes()));
let id = match op {
Opcode::WarpRectilinear { planes, center } => {
u32s(&mut o, &[planes.len() as u32]);
planes.iter().for_each(|p| f64s(&mut o, p));
f64s(&mut o, center);
1
}
Opcode::WarpFisheye { planes, center } => {
u32s(&mut o, &[planes.len() as u32]);
planes.iter().for_each(|p| f64s(&mut o, p));
f64s(&mut o, center);
2
}
Opcode::WarpRectilinear2 { planes, center, reciprocal, optional } => {
u32s(&mut o, &[planes.len() as u32]);
planes.iter().for_each(|p| f64s(&mut o, p));
f64s(&mut o, center);
u32s(&mut o, &[*reciprocal as u32]);
return (14, *optional as u32, o);
}
Opcode::FixVignetteRadial { k, center } => {
f64s(&mut o, k);
f64s(&mut o, center);
3
}
Opcode::FixBadPixelsConstant { constant, bayer_phase } => {
u32s(&mut o, &[*constant, *bayer_phase]);
4
}
Opcode::FixBadPixelsList { bayer_phase, points, rects } => {
u32s(&mut o, &[*bayer_phase, points.len() as u32, rects.len() as u32]);
points.iter().for_each(|&(r, c)| u32s(&mut o, &[r, c]));
rects.iter().for_each(|r| u32s(&mut o, r));
5
}
Opcode::TrimBounds { top, left, bottom, right } => {
u32s(&mut o, &[*top, *left, *bottom, *right]);
6
}
Opcode::MapTable { area, table } => {
put_area(&mut o, area);
u32s(&mut o, &[table.len() as u32]);
table.iter().for_each(|v| o.extend_from_slice(&v.to_be_bytes()));
7
}
Opcode::MapPolynomial { area, coefficients } => {
put_area(&mut o, area);
u32s(&mut o, &[coefficients.len().saturating_sub(1) as u32]);
f64s(&mut o, coefficients);
8
}
Opcode::GainMap { area, points_v, points_h, spacing, origin, map_planes, gains } => {
put_area(&mut o, area);
u32s(&mut o, &[*points_v, *points_h]);
f64s(&mut o, spacing);
f64s(&mut o, origin);
u32s(&mut o, &[*map_planes]);
f32s(&mut o, gains);
9
}
Opcode::DeltaPerRow { area, deltas: v }
| Opcode::DeltaPerColumn { area, deltas: v }
| Opcode::ScalePerRow { area, scales: v }
| Opcode::ScalePerColumn { area, scales: v } => {
put_area(&mut o, area);
u32s(&mut o, &[v.len() as u32]);
f32s(&mut o, v);
match op {
Opcode::DeltaPerRow { .. } => 10,
Opcode::DeltaPerColumn { .. } => 11,
Opcode::ScalePerRow { .. } => 12,
_ => 13,
}
}
Opcode::Unknown { id, flags, params } => return (*id, *flags, params.clone()),
};
(id, 0, o)
}
/// Serialise an opcode list (inverse of [`parse_list`]).
pub fn write_list(list: &[Opcode]) -> Vec<u8> {
let mut out = (list.len() as u32).to_be_bytes().to_vec();
for op in list {
let (id, flags, p) = params(op);
for v in [id, if id == 14 { 0x0106_0000 } else { 0x0103_0000 }, flags, p.len() as u32] {
out.extend_from_slice(&v.to_be_bytes());
}
out.extend_from_slice(&p);
}
out
}
/// Parse an opcode list blob. Malformed opcodes become [`Opcode::Unknown`]; a truncated list stops early.
pub fn parse_list(d: &[u8]) -> Vec<Opcode> {
let mut r = Rd { d, p: 0 };
let Some(count) = r.u32() else { return vec![] };
let mut out = Vec::new();
for _ in 0..count.min(4096) {
let (Some(id), Some(_ver), Some(flags), Some(size)) = (r.u32(), r.u32(), r.u32(), r.u32()) else { break };
let Some(params) = d.get(r.p..r.p.saturating_add(size as usize)) else { break };
r.p += size as usize;
out.push(parse_one(id, flags, params).unwrap_or(Opcode::Unknown { id, flags, params: params.to_vec() }));
}
out
/// Whether [`apply_list`] / [`apply_list3`] implement `op`.
pub fn is_applied(op: &Opcode) -> bool {
!matches!(op, Opcode::Unknown { .. } | Opcode::TrimBounds { .. } | Opcode::WarpFisheye { .. })
}
fn area_iter(a: &Area, w: usize, h: usize, cpp: usize) -> impl Iterator<Item = (usize, usize, usize)> + '_ {
+2 -16
View File
@@ -1,19 +1,5 @@
use super::*;
#[test]
fn reject_opcode_counts_whose_bytes_exceed_the_remaining_data() {
let mut gain_map = Vec::new();
for value in [u32::MAX, 1] {
gain_map.extend_from_slice(&value.to_be_bytes());
}
gain_map.extend(be(&[1.0, 1.0, 0.0, 0.0]));
gain_map.extend_from_slice(&1u32.to_be_bytes());
assert!(parse_gain_map(Area::default(), &mut Rd { d: &gain_map, p: 0 }).is_none());
let delta_count = u32::MAX.to_be_bytes();
assert!(parse_delta_scale(10, Area::default(), &mut Rd { d: &delta_count, p: 0 }).is_none());
}
pub(crate) struct ListWriter(pub Vec<u8>, pub u32);
impl ListWriter {
@@ -87,7 +73,7 @@ fn parse_and_apply_area_ops() {
let list = parse_list(&blob);
assert_eq!(list.len(), 4);
assert!(matches!(list[3], Opcode::Unknown { id: 99, .. }));
assert!(list[..3].iter().all(|o| o.is_applied()));
assert!(list[..3].iter().all(is_applied));
let mut buf = vec![0.25f32; w * h];
apply_list(&list, &mut buf, w, h, 1, None, 1.0);
// gain map: horizontal ramp 1 → 2 across relative x 0..1 (x / w)
@@ -264,7 +250,7 @@ fn warp_rectilinear2_parses_the_spec_layout() {
list,
vec![Opcode::WarpRectilinear2 { planes: vec![k, wr2_set(&[(0, 1.0)])], center: [0.5, 0.25], reciprocal: true, optional: false }]
);
assert!(list[0].is_applied() && list[0].is_lens_correction());
assert!(is_applied(&list[0]) && list[0].is_lens_correction());
// written back as opcode 14, version 1.6.0.0, optional flag kept
let again = vec![Opcode::WarpRectilinear2 { planes: vec![k], center: [0.5, 0.5], reciprocal: false, optional: true }];
let bytes = write_list(&again);
-722
View File
@@ -1,722 +0,0 @@
//! Embedded preview extraction: the largest baseline/progressive JPEG stored in a TIFF-based raw (IFD strips
//! with JPEG compression, `JPEGInterchangeFormat` pointers in any IFD, Nikon/others' maker-note preview IFDs),
//! or a DNG 1.7 JPEG XL preview IFD stored as a single tile/strip (a standalone `.jxl` file, as the spec
//! recommends for previews).
use craft_tiff::image::chunk_bytes;
use craft_tiff::tags as t;
use craft_tiff::{Ifd, Tiff, makernote};
/// Colour space of an embedded JPEG when the enclosing raw supplies it instead of the JPEG.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PreviewColorSpace {
Srgb,
AdobeRgb,
}
/// The colour space the raw says its embedded JPEG is in, for a JPEG that declares none itself (no ICC profile,
/// no EXIF), first available first: the Nikon maker-note ColorSpace (0x001e: 1 = sRGB, 2 = Adobe RGB, per Nikon
/// tag documentation); for a Canon CR2 or CR3, the Canon maker-note ColorSpace (0x00b4: 1 = sRGB, 2 = Adobe RGB);
/// the raw's own EXIF ColorSpace (0xA001: 1 = sRGB), or Uncalibrated (0xFFFF) with the Interoperability IFD's
/// InteropIndex "R03", the DCF option file for Adobe RGB (as a Sony body shot in Adobe RGB writes, issue #778; per
/// the Exif and DCF specifications), not for a DNG. This is a fallback only: a JPEG's own ICC/EXIF colour
/// declaration takes precedence.
pub fn embedded_preview_color_space(bytes: &[u8]) -> Option<PreviewColorSpace> {
let Ok(tiff) = Tiff::parse(bytes) else { return cr3_color_space(bytes) };
let make = tiff.ifds.first()?.string(t::MAKE).unwrap_or_default();
let exif = tiff.exif()?;
if make.to_ascii_uppercase().starts_with("NIKON")
&& let Some(space) = nikon_color_space(bytes, &tiff, exif, &make)
{
return Some(space);
}
// a DNG's EXIF describes the original capture; its previews are rendered by the converter
if tiff.ifds.first()?.contains(t::DNG_VERSION) {
return None;
}
if make.to_ascii_uppercase().starts_with("CANON")
&& let Some(e) = exif.get(t::MAKER_NOTE)
&& let Some(mn) = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)
&& let Some(space) = canon_color_space(&mn.ifd)
{
return Some(space);
}
match exif.u16(0xA001)? {
1 => Some(PreviewColorSpace::Srgb),
0xFFFF if exif.interop.as_deref()?.bytes(0x0001)?.starts_with(b"R03") => Some(PreviewColorSpace::AdobeRgb),
_ => None,
}
}
/// A CR3 keeps its EXIF and maker note in `CMT2`/`CMT3` TIFF blocks and its JPEGs carry no EXIF; a body shot in
/// Adobe RGB writes ColorSpace Uncalibrated (0xFFFF) with no Interoperability IFD (issue #2654), so the Canon
/// maker note says which, else an EXIF ColorSpace of sRGB is taken.
fn cr3_color_space(bytes: &[u8]) -> Option<PreviewColorSpace> {
let cr3 = lightcraft_meta::cr3::parse_cr3(bytes)?;
let first = |i: usize| cr3.cmt[i].and_then(|b| Tiff::parse(b).ok()).and_then(|t| t.ifds.into_iter().next());
if let Some(space) = first(2).and_then(|mn| canon_color_space(&mn)) {
return Some(space);
}
(first(1)?.u16(0xA001)? == 1).then_some(PreviewColorSpace::Srgb)
}
/// The Canon maker-note ColorSpace (0x00b4: 1 = sRGB, 2 = Adobe RGB, per ExifTool's published Canon tag names).
/// A Canon body shot in Adobe RGB writes EXIF ColorSpace Uncalibrated (0xFFFF) with InteropIndex "R98" in a CR2
/// and no Interoperability IFD in a CR3, so the EXIF alone does not say Adobe RGB (issue #2654).
fn canon_color_space(note: &Ifd) -> Option<PreviewColorSpace> {
match note.u16(0x00b4)? {
1 => Some(PreviewColorSpace::Srgb),
2 => Some(PreviewColorSpace::AdobeRgb),
_ => None,
}
}
fn nikon_color_space(bytes: &[u8], tiff: &Tiff, exif: &Ifd, make: &str) -> Option<PreviewColorSpace> {
let e = exif.get(t::MAKER_NOTE)?;
let mn = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, make)?;
match mn.ifd.u16(0x001e)? {
1 => Some(PreviewColorSpace::Srgb),
2 => Some(PreviewColorSpace::AdobeRgb),
_ => None,
}
}
/// Whether the camera optimised its embedded JPEG's dynamic range with local tone mapping that the raw data doesn't
/// carry: Sony's Dynamic Range Optimizer (maker note `0xb025`, see `vendor::arw`). Such a JPEG is brighter in its
/// darker regions than the raw developed with the camera's global tone curve. `Some(false)` when the file says it
/// was off, `None` when it doesn't say (other makers, notes without the tag, undocumented values).
pub fn embedded_preview_dynamic_range_optimized(bytes: &[u8]) -> Option<bool> {
let tiff = Tiff::parse(bytes).ok()?;
let make = tiff.ifds.first()?.string(t::MAKE)?;
if !make.trim().to_ascii_uppercase().starts_with("SONY") {
return None;
}
let e = tiff.exif()?.get(t::MAKER_NOTE)?;
let mn = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)?;
crate::vendor::arw::dynamic_range_optimizer(&mn)
}
/// The first frame (SOF) marker of a JPEG and its position, from the marker segments before the first scan.
fn first_frame(b: &[u8]) -> Option<(u8, usize)> {
first_frame_within(b, &mut { usize::MAX })
}
/// [`first_frame`] charging `work` one per step (a segment, or a fill byte); `None` too when it runs out.
fn first_frame_within(b: &[u8], work: &mut usize) -> Option<(u8, usize)> {
if b.len() < 4 || !b.starts_with(&[0xff, 0xd8]) {
return None;
}
let mut i = 2usize;
while i.checked_add(4)? <= b.len() {
*work = work.checked_sub(1)?;
if *b.get(i)? != 0xff {
return None;
}
let m = *b.get(i + 1)?;
if m == 0xff {
i += 1;
continue;
}
match m {
0xc0..=0xc3 | 0xc5..=0xc7 | 0xcb | 0xcd..=0xcf => return Some((m, i)),
0xda | 0xd9 => return None,
_ => {}
}
let len = usize::from(u16::from_be_bytes([*b.get(i + 2)?, *b.get(i + 3)?]));
i = i.checked_add(2 + len)?;
}
None
}
/// Whether `b` looks like a displayable (DCT) JPEG: SOI, and the first SOF marker is not lossless.
fn is_dct_jpeg(b: &[u8]) -> bool {
first_frame(b).is_some_and(|(m, _)| matches!(m, 0xc0..=0xc2))
}
/// Width, height and component count of a displayable (DCT) JPEG, from its frame header.
fn jpeg_frame(b: &[u8]) -> Option<(u32, u32, u8)> {
let (_, i) = first_frame(b).filter(|(m, _)| matches!(m, 0xc0..=0xc2))?;
let at = |k: usize| b.get(i.checked_add(k)?).copied();
let be16 = |k: usize| Some(u32::from(u16::from_be_bytes([at(k)?, at(k + 1)?])));
Some((be16(7)?, be16(5)?, at(9)?))
}
fn is_jxl(b: &[u8]) -> bool {
b.starts_with(&[0xff, 0x0a]) || b.starts_with(&[0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a])
}
/// The bytes a file's own (offset, length) pair names, cut at the file's end; `None` when the offset
/// lies past it. Both numbers come from the file: never cast them (a `u64` offset past 4 GiB would
/// wrap to a small, wrong one on a 32-bit build) nor add them unchecked. A span the file's end cuts
/// short is kept only when it is a JPEG whose own end marker is inside it, after its scan (an
/// overstated length with the whole JPEG inside), cut at that marker: a truncated JPEG passes the
/// frame-header check, would win as the largest preview and then fail to decode (CodeRabbit on
/// #3077). An `FF D9` inside an APP payload doesn't count, bytes that don't start a JPEG are refused
/// without a scan, and the walks share `budget` (bytes, as [`scan_with_budget`]'s do), so a file of
/// many such pointers stays linear.
fn file_span<'a>(data: &'a [u8], offset: u64, len: u64, budget: &mut usize) -> Option<&'a [u8]> {
let start = usize::try_from(offset).ok()?;
let wanted = usize::try_from(offset.saturating_add(len)).unwrap_or(usize::MAX);
let span = data.get(start..wanted.min(data.len()))?;
if wanted > data.len() {
return span.get(..jpeg_end(span, budget)?);
}
Some(span)
}
/// Where the JPEG at the start of `s` ends (just past its end marker), walking its marker segments:
/// a segment's payload is skipped by its stated length (so an `FF D9` inside APP data isn't taken
/// for the end), entropy-coded bytes one at a time (stuffed `FF 00` and restart markers included).
/// `None` when `s` isn't a JPEG, ends first, reaches its end marker before a start of scan (no image
/// data), or the walk spends `budget` (one per step, shared by a file's walks). Each step moves
/// forward, so it ends within `s`.
fn jpeg_end(s: &[u8], budget: &mut usize) -> Option<usize> {
if !s.starts_with(&[0xff, 0xd8]) {
return None;
}
let (mut i, mut scanned) = (2usize, false);
loop {
*budget = budget.checked_sub(1)?;
match (s.get(i), s.get(i.checked_add(1)?)) {
(None, _) | (Some(&0xff), None) => return None,
(Some(&0xff), Some(&m)) => match m {
0xd9 => return if scanned { i.checked_add(2) } else { None },
// fill byte
0xff => i += 1,
// stuffed zero, restart marker, TEM: no length follows
0x00 | 0x01 | 0xd0..=0xd7 => i = i.checked_add(2)?,
_ => {
let (&hi, &lo) = (s.get(i.checked_add(2)?)?, s.get(i.checked_add(3)?)?);
let len = usize::from(u16::from_be_bytes([hi, lo]));
if len < 2 {
return None;
}
scanned |= m == 0xda;
i = i.checked_add(2)?.checked_add(len)?;
}
},
// entropy-coded data
(Some(_), _) => i += 1,
}
}
}
fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>, budget: &mut usize) {
// whole JPEG files stored as an undefined-type tag value (e.g. Panasonic `JpgFromRaw` 0x002e)
for e in &ifd.entries {
if matches!(e.value, craft_tiff::Value::Undefined(_))
&& e.count() > 1024
&& let Some(s) = file_span(data, e.offset, e.count() as u64, budget)
&& s.starts_with(&[0xff, 0xd8])
{
out.push(s);
}
}
if let (Some(off), Some(len)) = (ifd.u64(t::JPEG_INTERCHANGE_FORMAT), ifd.u64(t::JPEG_INTERCHANGE_FORMAT_LENGTH)) {
let off = off.saturating_add(base);
if let Some(s) = file_span(data, off, len, budget) {
out.push(s);
}
}
if matches!(ifd.u16(t::COMPRESSION), Some(6) | Some(7) | Some(34892))
&& let Ok(info) = ifd.image()
&& let Some(chunk) = info.single_chunk(data.len() as u64)
&& let Some(s) = chunk_bytes(data, &chunk)
{
out.push(s);
}
// a rendered (RGB or grey, never CFA/LinearRaw/mask) JPEG XL preview in one chunk
if ifd.u16(t::COMPRESSION) == Some(t::compression::JPEG_XL)
&& matches!(ifd.u16(t::PHOTOMETRIC), Some(t::photometric::BLACK_IS_ZERO | t::photometric::RGB))
&& let Ok(info) = ifd.image()
&& let Some(chunk) = info.single_chunk(data.len() as u64)
&& let Some(s) = chunk_bytes(data, &chunk)
&& is_jxl(s)
{
out.push(s);
}
}
/// The largest embedded preview, if any: a JPEG, or (DNG 1.7) a JPEG XL file, or for a Hasselblad 3FR / FFF, which
/// has no JPEG, its uncompressed RGB preview wrapped as a baseline TIFF — all decode with `lightcraft_codecs::decode`.
pub fn embedded_preview(bytes: &[u8]) -> Option<Vec<u8>> {
preview_covering(bytes, None)
}
/// The smallest embedded JPEG whose long edge is at least `min_edge` and that looks like a copy of the largest preview
/// (its aspect ratio within 1 %, so not a letterboxed or cropped thumbnail, and as many colour components, so not a
/// grey mask or depth map), else [`embedded_preview`]. Only TIFF-based raws keep several: an A7R VI's 1616 × 1080
/// preview is 0.3 MB beside its 9984 × 6656 one (5.6 MB), so a stand-in up to 1616 px decodes about a twentieth of the data.
pub fn embedded_preview_covering(bytes: &[u8], min_edge: u32) -> Option<Vec<u8>> {
preview_covering(bytes, Some(min_edge))
}
/// Of the DCT JPEGs in `found`, the one with the shortest long edge of at least `min_edge` with `largest`'s aspect
/// ratio (within 1 %) and component count.
fn smallest_covering<'a>(found: &[&'a [u8]], largest: &[u8], min_edge: u32) -> Option<&'a [u8]> {
let (bw, bh, bc) = jpeg_frame(largest)?;
let like = |(w, h, c): (u32, u32, u8)| {
let (a, b) = (u64::from(w) * u64::from(bh), u64::from(h) * u64::from(bw));
w > 0 && h > 0 && c == bc && a.abs_diff(b) * 100 <= a
};
// (one cut short before its end marker would fail to decode, and nothing would try another: CodeRabbit
// on #3583)
let whole = |s: &[u8]| trim_eoi(s).ends_with(&[0xff, 0xd9]);
found
.iter()
.filter(|s| whole(s))
.filter_map(|&s| jpeg_frame(s).filter(|&f| like(f) && f.0.max(f.1) >= min_edge).map(|(w, h, _)| (s, w.max(h))))
.min_by_key(|&(_, long)| long)
.map(|(s, _)| s)
}
fn preview_covering(bytes: &[u8], min_edge: Option<u32>) -> Option<Vec<u8>> {
if bytes.starts_with(b"FUJIFILMCCD-RAW") {
let j = crate::vendor::raf::header(bytes).ok()?.jpeg?;
return is_dct_jpeg(j).then(|| trim_eoi(j).to_vec());
}
let format = crate::probe(bytes);
if format == Some(crate::RawFormat::Cr3) {
// a Canon CR3 keeps its full-size JPEG beside a 1620 px `PRVW` (and a 160 px `THMB`): a
// thumbnail decodes the small copy, not 45 MP of JPEG (about 150 ms a photo, the grid's
// "popcorn" on a folder of R5 / R5 C raws)
// (without a JPEG track, the largest box is the picture's shape: the boxes alone may hold several)
if let Some(min) = min_edge {
let mut found = cr3_preview_box_list(bytes);
let full = cr3_full_jpeg(bytes);
found.extend(full);
if let Some(largest) = full.or_else(|| largest_by_pixels(&found))
&& let Some(j) = smallest_covering(&found, largest, min)
{
return Some(trim_eoi(j).to_vec());
}
}
return cr3_preview(bytes).map(|j| trim_eoi(j).to_vec());
}
if matches!(format, Some(crate::RawFormat::Crw | crate::RawFormat::Mrw | crate::RawFormat::X3f)) {
return scan_for_jpeg(bytes);
}
let tiff = Tiff::parse(bytes).ok()?;
let mut found: Vec<&[u8]> = Vec::new();
// the walks of pointers past the file's end share one budget (see file_span)
let mut budget = scan_budget(bytes.len());
for ifd in tiff.all_ifds() {
candidates(bytes, ifd, 0, &mut found, &mut budget);
}
// maker-note preview IFDs (e.g. Nikon PreviewIFD 0x0011 holds JPEGInterchangeFormat relative to the note base)
if let Some(exif) = tiff.exif()
&& let Some(e) = exif.get(t::MAKER_NOTE)
{
let make = tiff.find(t::MAKE).and_then(|e| e.value.as_str()).unwrap_or_default();
if let Some(mn) = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make) {
candidates(bytes, &mn.ifd, mn.base, &mut found, &mut budget);
if let Some(off) = mn.ifd.u64(0x0011)
&& let Ok((pifd, _)) = craft_tiff::parse_ifd_at(bytes, mn.base + off, mn.order, mn.base, false, &Default::default())
{
candidates(bytes, &pifd, mn.base, &mut found, &mut budget);
}
}
}
// Olympus: CameraSettings preview
if let Some(p) = crate::vendor::orf::preview(bytes) {
found.push(p);
}
bound_candidates(&mut found, bytes.len());
let largest = found.iter().copied().filter(|s| is_dct_jpeg(s) || is_jxl(s)).max_by_key(|s| s.len());
let best = min_edge
.zip(largest)
.and_then(|(min, big)| smallest_covering(&found, big, min))
.or(largest)
.map(|s| if is_jxl(s) { s.to_vec() } else { trim_eoi(s).to_vec() });
// a TIFF raw whose preview no tag points to: one we can't decode (Leaf MOS), or Epson ERF (in its maker note)
best.or_else(|| format.filter(|f| !f.is_supported() || *f == crate::RawFormat::Erf).and_then(|_| scan_for_jpeg(bytes)))
// Hasselblad 3FR / FFF carry no JPEG, only uncompressed RGB images: one wrapped as a baseline TIFF
.or_else(|| (format == Some(crate::RawFormat::CfaTiff)).then(|| crate::vendor::hasselblad::rgb_preview(&tiff, bytes)).flatten())
}
/// Drops candidate ranges that repeat an earlier one, that are not a displayable JPEG or JPEG XL, and valid ones
/// past a shared budget of [`scan_budget`] bytes: a range is charged only once it validates, so invalid ranges
/// covering most of the file cannot use up the budget before a valid preview. The header walks that validate
/// (or reject) the ranges share a second budget of the same size, charged for every walk, so many ranges
/// that start a JPEG header and run through fill bytes cannot each cost a walk of their length.
fn bound_candidates(found: &mut Vec<&[u8]>, file_len: usize) {
let mut seen = std::collections::HashSet::new();
let mut left = scan_budget(file_len);
let mut work = scan_budget(file_len);
found.retain(|s| {
let mut dct = || first_frame_within(s, &mut work).is_some_and(|(m, _)| matches!(m, 0xc0..=0xc2));
if !seen.insert((s.as_ptr() as usize, s.len())) || !(dct() || is_jxl(s)) || s.len() > left {
return false;
}
left -= s.len();
true
});
}
/// The end of the DCT JPEG whose SOI is at `soi` (exclusive index after its EOI) and its component count,
/// walking the marker segments and the entropy-coded data. `None` when it is not a complete, displayable
/// (baseline or progressive) JPEG, so a stray `D8 FF` in other data is rejected. `*reach` is left at
/// the furthest byte looked at (what the walk cost; see [`scan_for_jpeg`]).
/// Where a preview lives in a file, so a caller with a seekable file can read just that part of it.
///
/// Why it exists: a 56 MB Fuji RAF keeps its JPEG in the first 5.6 MB (measured: DSCF9492.RAF at
/// 5.6 MB), so a grid thumbnail or a loupe preview has no reason to pull the remaining 50 MB —
/// which on a network share is the difference between a moment and half a minute. A caller that has
/// only bytes (`wasm`, tests) keeps using [`embedded_preview`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PreviewRange {
/// Byte offset of the preview in the file.
pub offset: u64,
/// Bytes to read at [`Self::offset`]: the container's declared preview extent, which may carry
/// padding past the preview's end-of-image marker.
pub window_len: u64,
}
/// The preview's range in the file, when the file's header alone locates it.
///
/// `bytes` is the file's first [`PREVIEW_PREFIX`] bytes (more is fine). `None` means "read the file
/// whole and call [`embedded_preview`]": the formats not covered here (a TIFF-based raw's pointer
/// tag can sit in an IFD the prefix cuts short; CR3 scans box by box) and files whose pointer is
/// damaged.
///
/// The caller reads `[range.offset, range.offset + range.window_len)` and passes those bytes to
/// [`embedded_preview_from_range`], which returns exactly what [`embedded_preview`] returns for the
/// whole file.
///
/// Pass a prefix that actually covers the pointer's range (read [`Self::offset`] +
/// [`Self::window_len`] bytes, or start with [`PREVIEW_PREFIX`] and grow when it is not enough):
/// [`crate::vendor::raf::header`] clamps a slice to the buffer it was given, so a prefix that stops
/// inside the declared extent yields a shorter `window_len` than the file really holds.
pub fn bounded_preview(bytes: &[u8]) -> Option<PreviewRange> {
if !bytes.starts_with(b"FUJIFILMCCD-RAW") {
return None;
}
let jpeg = crate::vendor::raf::header(bytes).ok()?.jpeg?;
let offset = (jpeg.as_ptr() as usize).checked_sub(bytes.as_ptr() as usize)?;
if offset.checked_add(jpeg.len())? > bytes.len() {
return None;
}
Some(PreviewRange { offset: offset as u64, window_len: jpeg.len() as u64 })
}
/// The preview inside `window`, which holds the file's bytes at `[range.offset, range.offset +
/// range.window_len)`: the counterpart of [`bounded_preview`]. Padding past the end-of-image marker
/// is dropped, exactly as [`embedded_preview`] drops it.
pub fn embedded_preview_from_range(window: &[u8], range: PreviewRange) -> Option<Vec<u8>> {
let preview = window.get(..usize::try_from(range.window_len).ok()?)?;
if !is_dct_jpeg(preview) {
return None;
}
Some(trim_eoi(preview).to_vec())
}
/// How many bytes of a raw file are enough for [`bounded_preview`]: every covered format keeps its
/// preview pointer in a fixed header, well inside this.
pub const PREVIEW_PREFIX: usize = 4096;
fn jpeg_extent(b: &[u8], soi: usize, reach: &mut usize) -> Option<(usize, u8)> {
let mut i = soi + 2;
let r = walk_jpeg(b, &mut i);
*reach = i;
r
}
fn walk_jpeg(b: &[u8], i: &mut usize) -> Option<(usize, u8)> {
let mut components = None;
for _ in 0..4096 {
if *b.get(*i)? != 0xff {
return None;
}
while *b.get(*i)? == 0xff {
*i += 1;
}
let m = *b.get(*i)?;
*i += 1;
match m {
0xd9 => return components.map(|c| (*i, c)),
0x01 | 0xd0..=0xd8 => continue,
_ => {}
}
let len = usize::from(u16::from_be_bytes([*b.get(*i)?, *b.get(*i + 1)?]));
if len < 2 {
return None;
}
match m {
0xc0..=0xc2 => {
// precision, height, width, component count
let h = u16::from_be_bytes([*b.get(*i + 3)?, *b.get(*i + 4)?]);
let w = u16::from_be_bytes([*b.get(*i + 5)?, *b.get(*i + 6)?]);
if h == 0 || w == 0 || components.is_some() {
return None;
}
components = Some(*b.get(*i + 7)?);
}
0xc3 | 0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf => return None, // lossless, arithmetic, hierarchical
_ => {}
}
*i += len;
if m == 0xda {
// entropy-coded data up to the next marker that is not a stuffed 0xff or a restart
loop {
let Some(p) = b.get(*i..)?.iter().position(|&x| x == 0xff) else {
// the terminal search examined the rest of the slice: charge it before failing,
// or a crafted file can repeat full-file searches while the budget stays positive
*i = b.len();
return None;
};
*i += p;
match *b.get(*i + 1)? {
0x00 | 0xd0..=0xd7 => *i += 2,
0xff => *i += 1,
_ => break,
}
}
}
}
None
}
/// Last resort for the containers whose structure is not walked (Canon CRW, Minolta MRW, Sigma X3F, TIFF raws
/// with private blocks such as Leaf MOS or Epson ERF): the largest complete colour DCT JPEG stored as a plain
/// byte run in the file. A one-component JPEG is skipped (a Canon PowerShot CRW stores its sensor mosaic as one).
///
/// Evidence: in the Minolta and Epson files the first byte of the stored preview is not `ff` (it is `00`, `02` or
/// `ee`) while the rest is a regular JPEG, so a run is found by its `d8 ff` and starts one byte earlier,
/// with that byte restored to `ff`.
///
/// A crafted file can hold millions of JPEG-like starts whose walks each run to its end: the walks
/// share a budget of eight times the file's size, so the scan stays linear (a real file's candidates
/// fail within a few bytes, or are the preview itself).
fn scan_for_jpeg(data: &[u8]) -> Option<Vec<u8>> {
scan_with_budget(data, scan_budget(data.len())).0
}
/// The walks' shared budget: eight times the file's size, at least 1 MiB (a tiny file still gets a
/// useful allowance), saturating so a hostile length cannot wrap it.
fn scan_budget(len: usize) -> usize {
len.saturating_mul(8).max(1 << 20)
}
/// [`scan_for_jpeg`] with the walks' shared budget passed in, returning the walks' charged extent:
/// `(preview, bytes charged)`. The counter records the work each walk did whether or not budget
/// remains, so it stays a measure of work rather than of `budget - left`; a last walk may overshoot
/// the remaining budget by its own reach. It is a conservative charged-work measure, not literally
/// the bytes read: marker payloads skipped by `*i += len` are charged without being read, and a
/// failed terminal search is charged to the end of the slice. That over-count is safe for the
/// budget. It is a `u64` with saturating addition because the unbudgeted worst case is quadratic in
/// the file size (32-bit `usize` could otherwise overflow), and it costs one addition per
/// candidate, no allocation.
fn scan_with_budget(data: &[u8], budget: usize) -> (Option<Vec<u8>>, u64) {
let mut best: Option<(usize, usize)> = None;
let mut at = 1;
let mut left = budget;
let mut walked = 0u64;
while let Some(off) = data.get(at..).and_then(|s| s.iter().position(|&b| b == 0xd8)) {
let d8 = at + off;
at = d8 + 1;
if data.get(d8 + 1) != Some(&0xff) || !matches!(data.get(d8 + 2), Some(0xc0..=0xc4 | 0xdb | 0xe0..=0xef | 0xfe)) {
continue;
}
let start = d8 - 1; // `at` starts at 1, so d8 >= 1
let mut reach = start;
let found = jpeg_extent(data, start, &mut reach);
let spent = reach.saturating_sub(start);
left = left.saturating_sub(spent);
walked = walked.saturating_add(spent as u64);
if left == 0 {
break;
}
if let Some((end, 3)) = found {
if best.is_none_or(|(s, e)| end - start > e - s) {
best = Some((start, end));
}
at = end;
}
}
let jpeg = best.and_then(|(start, end)| {
let mut jpeg = data.get(start..end)?.to_vec();
if let Some(first) = jpeg.first_mut() {
*first = 0xff;
}
Some(jpeg)
});
(jpeg, walked)
}
/// Canon CR3: the full-size JPEG track (see [`lightcraft_meta::cr3`]), else the `PRVW` / `THMB` boxes.
fn cr3_preview(bytes: &[u8]) -> Option<&[u8]> {
cr3_full_jpeg(bytes).or_else(|| cr3_preview_boxes(bytes))
}
/// A CR3's full-size JPEG track, when it holds a DCT JPEG.
fn cr3_full_jpeg(bytes: &[u8]) -> Option<&[u8]> {
let full = lightcraft_meta::cr3::parse_cr3(bytes)
.and_then(|c| c.tracks.iter().find(|t| t.kind == lightcraft_meta::cr3::Cr3TrackKind::Jpeg).and_then(|t| t.data));
full.and_then(|(at, len)| bytes.get(at..at.checked_add(len)?)).filter(|j| is_dct_jpeg(j))
}
/// Marker-walk budget of the CR3 fallback: candidates can overlap (each claiming the rest of the file) and
/// [`is_dct_jpeg`] walks each marker by marker, so walking every candidate would be quadratic in file size.
/// The `THMB`/`PRVW` previews this finds are far below the cap together; once it is spent the scan stops.
const CR3_MAX_WALK: usize = 8 << 20;
/// Canon CR3 (ISO base media file): the `PRVW` box (Laurent Clévy's CR3 notes; layout confirmed on a CC0
/// sample) is `u32 size, "PRVW", u32 0, u16 ?, u16 width, u16 height, u16 ?, u32 jpeg length, JPEG`; the smaller
/// `THMB` box has the same shape. Returns the larger valid one.
fn cr3_preview_boxes(bytes: &[u8]) -> Option<&[u8]> {
largest_by_pixels(&cr3_preview_box_list(bytes))
}
/// Of `found`, the JPEG with the longest edge in pixels (a smaller picture can take more bytes); the
/// first of equals. CodeRabbit on #3077.
fn largest_by_pixels<'a>(found: &[&'a [u8]]) -> Option<&'a [u8]> {
let long = |j: &[u8]| jpeg_frame(j).map_or(0, |(w, h, _)| w.max(h));
found.iter().copied().rev().max_by_key(|j| long(j))
}
/// The valid JPEGs of a CR3's `PRVW` and `THMB` boxes, every one: a file may carry more than one
/// `PRVW`, and the smallest that covers a size is picked from them all.
fn cr3_preview_box_list(bytes: &[u8]) -> Vec<&[u8]> {
let mut out: Vec<&[u8]> = Vec::new();
let mut walked = 0usize;
// the boxes sit outside the media data: only the rest of the file is searched (the media data
// is most of the file, and a thumbnail is asked for every photo in view)
let file = bytes;
// (every top-level `mdat` is left out, not only the first: a PRVW-shaped JPEG in media data is not a
// preview; CodeRabbit on #3583)
let media = cr3_media_data(file);
let whole_file = media.is_empty();
let mut regions: Vec<&[u8]> = Vec::new();
let mut from = 0usize;
for (start, end) in media {
if start >= from {
regions.extend(file.get(from..start));
}
from = from.max(end);
}
regions.extend(file.get(from..));
for tag in [b"PRVW", b"THMB"] {
// the whole file searched (its media data not found): the first valid box of a kind only, as
// the declared one comes before the media data and a later look-alike must not win
let mut taken = false;
for &bytes in &regions {
if whole_file && taken {
break;
}
let mut from = 0;
while let Some(i) = bytes.get(from..).and_then(|s| s.windows(4).position(|w| w == tag)).map(|p| p + from) {
from = i + 4;
let Some(start) = i.checked_sub(4) else { continue };
// (the sizes are the file's: checked, a 32-bit build must not wrap them)
let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize);
let (Some(size), Some(len)) = (be32(start), start.checked_add(20).and_then(be32)) else { continue };
let (Some(j), Some(box_end)) = (start.checked_add(24), start.checked_add(size.max(24))) else { continue };
let Some(end) = j.checked_add(len).filter(|e| len >= 4 && *e <= box_end && *e <= bytes.len()) else { continue };
let Some(jpeg) = bytes.get(j..end) else { continue };
// One that doesn't fit the budget left is skipped; a smaller one later may still fit.
if walked.saturating_add(jpeg.len()) > CR3_MAX_WALK {
continue;
}
walked = walked.saturating_add(jpeg.len());
if is_dct_jpeg(jpeg) {
out.push(jpeg);
taken = true;
if whole_file {
break;
}
// (past it: a tag inside its JPEG is not another box)
from = end;
}
}
}
}
out
}
/// Where a CR3's top-level `mdat` boxes lie (`start..end` each, `end` clamped to the file, in file
/// order): the media data, most of the file. Empty when there is none, or the boxes stop making sense
/// before the first. The metadata and the small previews are in the other top-level boxes.
fn cr3_media_data(bytes: &[u8]) -> Vec<(usize, usize)> {
let mut out = Vec::new();
let _ = cr3_media_walk(bytes, &mut out);
out
}
/// [`cr3_media_data`]'s walk of the top-level boxes; `None` where they stop making sense.
fn cr3_media_walk(bytes: &[u8], out: &mut Vec<(usize, usize)>) -> Option<()> {
let be32 = |at: usize| bytes.get(at..at.checked_add(4)?).map(|s| u64::from(u32::from_be_bytes([s[0], s[1], s[2], s[3]])));
let be64 = |at: usize| bytes.get(at..at.checked_add(8)?).map(|s| u64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]));
let mut at = 0usize;
for _ in 0..64 {
let size = be32(at)?;
let len = match size {
// (a box running to the end of the file)
0 => u64::try_from(bytes.len().saturating_sub(at)).unwrap_or(u64::MAX),
1 => be64(at.checked_add(8)?)?,
n => n,
};
let next = usize::try_from(len).ok().filter(|l| *l >= 8).and_then(|l| at.checked_add(l));
if bytes.get(at.checked_add(4)?..at.checked_add(8)?) == Some(b"mdat".as_slice()) {
out.push((at, next.unwrap_or(bytes.len()).min(bytes.len())));
}
at = next.filter(|n| *n < bytes.len())?;
}
None
}
/// Trim trailing garbage after the last EOI when a stored length over-reports.
fn trim_eoi(s: &[u8]) -> &[u8] {
let end = s.windows(2).rposition(|w| w == [0xff, 0xd9]).map(|p| p + 2).unwrap_or(s.len());
&s[..end]
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod bound_tests {
#[test]
fn repeated_and_over_budget_candidates_are_dropped() {
let mut data = vec![0u8; 4 << 20];
// a valid JPEG header every 16 bytes, so each range below validates
for i in 0..64 {
data[i * 16..i * 16 + 15].copy_from_slice(&[0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 8, 0, 8, 1, 1, 0x11, 0]);
}
let mut found: Vec<&[u8]> = vec![&data[..], &data[..], &data[..]];
super::bound_candidates(&mut found, data.len());
assert_eq!(found.len(), 1);
// overlapping but unequal ranges stop at the shared budget (8 x the file, at least 1 MiB)
let mut found: Vec<&[u8]> = (0..64).map(|i| &data[i * 16..]).collect();
super::bound_candidates(&mut found, data.len());
assert!(found.len() <= 8 && found.iter().map(|s| s.len()).sum::<usize>() <= 8 * data.len());
}
#[test]
fn invalid_ranges_do_not_use_up_the_budget_before_a_valid_preview() {
let mut data = vec![0u8; 2 << 20];
let jpeg = [0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 8, 0, 8, 1, 1, 0x11, 0];
data[1 << 20..(1 << 20) + jpeg.len()].copy_from_slice(&jpeg);
// 40 distinct invalid ranges of nearly the whole file (far past the 8 x budget), then the valid one
let mut found: Vec<&[u8]> = (0..40).map(|i| &data[i..1 << 20]).collect();
found.push(&data[1 << 20..]);
super::bound_candidates(&mut found, data.len());
assert_eq!(found.len(), 1);
assert!(found[0].starts_with(&[0xff, 0xd8]));
}
#[test]
fn header_walks_of_many_fill_byte_ranges_share_a_budget() {
// a JPEG header followed by 100 000 fill bytes and no frame: each walk would run to the end
let mut data = vec![0xffu8; 100_100];
data[..2].copy_from_slice(&[0xff, 0xd8]);
let valid = [0xff, 0xd8, 0xff, 0xc0, 0, 11, 8, 0, 8, 0, 8, 1, 1, 0x11, 0];
// 50 distinct such ranges (5 M steps against the 1 MiB budget), then a valid header
let mut found: Vec<&[u8]> = (0..50).map(|i| &data[..100_000 + i]).collect();
found.push(&valid);
super::bound_candidates(&mut found, data.len());
assert!(found.is_empty(), "the walks stop at the shared budget, so the later header is not reached");
// the same header with no hostile ranges before it is kept
let mut found: Vec<&[u8]> = vec![&valid];
super::bound_candidates(&mut found, data.len());
assert_eq!(found.len(), 1);
}
}
-853
View File
@@ -1,853 +0,0 @@
use super::*;
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
fn fake_jpeg(n: usize) -> Vec<u8> {
let mut j = vec![0xff, 0xd8, 0xff, 0xc0, 0x00, 0x0b, 8, 0, 1, 0, 1, 1, 1, 0x11, 0];
j.extend(std::iter::repeat_n(0x55u8, n));
j.extend_from_slice(&[0xff, 0xd9]);
j
}
/// Preview extraction only serves single-chunk JPEG-compressed IFDs and asks the `single_chunk` first:
/// a TIFF whose strip array declares 100 000 one-row strips and no StripByteCounts must not build their
/// descriptor vector, and of course finds no preview in it.
#[test]
fn a_multi_strip_jpeg_ifd_costs_no_descriptor_vector() {
let mut ifd = IfdBuilder::new();
ifd.set(t::COMPRESSION, Value::Short(vec![7]));
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![16]));
ifd.set(t::IMAGE_LENGTH, Value::Long(vec![100_000]));
ifd.set(t::ROWS_PER_STRIP, Value::Short(vec![1]));
ifd.set(t::STRIP_OFFSETS, Value::Byte((0..100_000).map(|i| (i % 255 + 1) as u8).collect()));
let file = TiffWriter::default().write(&[ifd]).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || tx.send(embedded_preview(&file)));
assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(2)), Ok(None));
}
/// CR3 candidates claim overlapping extents: each block's first bytes double as a 40-byte jump marker so
/// a walk jogs past the next header and reaches the end of the file, making every one of the 9000
/// candidates walk its whole suffix before the marker-walk budget — quadratic without it. Nothing here
/// is a JPEG (no frame header), so the answer is `None` either way.
#[test]
fn cr3_preview_boxes_stop_walking_when_the_budget_is_spent() {
// one 256-byte block per candidate, all marker-aligned so walks chain through later blocks:
// 0..4, size (itself a jump marker of 40 bytes); 4..8, "PRVW"; 20..24, the claimed length
// (to the file end); 24..28, an SOI plus a marker jumping to the fill at 40; 64..256, a fill of
// 4-byte markers (`ff 01 00 02`).
let blocks = 9000usize;
let total = blocks * 256;
let mut f = Vec::with_capacity(total);
for k in 0..blocks {
let base = k * 256;
f.extend_from_slice(&[0xff, 0x01, 0x00, 0x26, b'P', b'R', b'V', b'W', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
f.extend_from_slice(&u32::try_from(total - base - 24).unwrap().to_be_bytes());
f.extend_from_slice(&[0xff, 0xd8, 0x00, 0x24, 0xff, 0x01, 0x00, 0x26, 0, 0, 0, 0, 0, 0, 0, 0]);
f.resize(base + 64, 0); // 40..64 filler: walks jump over it, so its bytes are free
for _ in 0..48 {
f.extend_from_slice(&[0xff, 0x01, 0x00, 0x02]);
}
}
assert_eq!(f.len(), total);
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || tx.send(cr3_preview_boxes(&f).map(|s| s.len())));
assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(2)), Ok(None), "no PRVW candidate is a JPEG");
}
/// A minimal RAF: the fixed header (JPEG offset/length at 84/88), the JPEG, then a raw tail the
/// caller must not have to read. `jpeg_len` is written as declared, so a test can claim more than
/// the JPEG holds the way a padded container does.
fn raf_fixture(jpeg: &[u8], gap: usize, preamble: usize, declared_len: Option<usize>) -> Vec<u8> {
let head = 160 + preamble;
let jpeg_off = head;
let mut f = vec![0u8; head];
f[..16].copy_from_slice(b"FUJIFILMCCD-RAW ");
f[84..88].copy_from_slice(&(jpeg_off as u32).to_be_bytes());
f[88..92].copy_from_slice(&(declared_len.unwrap_or(jpeg.len()) as u32).to_be_bytes());
// records directory and raw block are absent (offset 0), which `header` reads as "none"
f.extend_from_slice(jpeg);
f.extend(std::iter::repeat_n(0x33u8, gap));
f
}
/// A RAF's preview pointer sits at a fixed offset, so a header-sized prefix locates it and the
/// caller reads just that range instead of the whole file — the whole point on a network share.
#[test]
fn bounded_preview_locates_a_rafs_jpeg_from_the_header_alone() {
let jpeg = fake_jpeg(5000);
let file = raf_fixture(&jpeg, 40_000, 0, None);
// A prefix that covers the pointer's range: header + JPEG, and nothing of the tail.
let prefix_len = 8192.min(file.len());
let prefix = &file[..prefix_len];
let range = bounded_preview(prefix).expect("a RAF's preview is found from its header");
assert_eq!(range.offset, 160);
assert_eq!(range.window_len, jpeg.len() as u64);
assert!(range.offset + range.window_len <= prefix_len as u64, "the prefix covers the whole range: {range:?} of {prefix_len}");
assert!((range.offset + range.window_len) < file.len() as u64, "the range stops short of the tail: {range:?} of {}", file.len());
// What the caller reads, and what it holds afterwards: identical to the whole-file answer.
let window = prefix.get(range.offset as usize..(range.offset + range.window_len) as usize).expect("the range lies inside the prefix");
let bounded = embedded_preview_from_range(window, range).expect("the range holds the preview");
assert_eq!(Some(bounded.clone()), embedded_preview(&file));
assert!(bounded.ends_with(&[0xff, 0xd9]), "the preview ends at its EOI marker");
// A prefix that stops inside the declared extent is clamped by the container reader. The
// caller then reads a short window; what comes back is the whole JPEG it holds (the EOI
// marker is inside), never bytes past the window.
let short = &file[..2000];
let clipped = bounded_preview(short).expect("a pointer before the cut is still found");
assert!(clipped.window_len < jpeg.len() as u64, "clamped: {clipped:?}");
let window = short.get(clipped.offset as usize..).expect("inside");
let preview = embedded_preview_from_range(window, clipped).expect("the bytes are a JPEG start");
// No end-of-image marker inside the window: the bytes come back as they are, exactly as the
// whole-file path returns an unclosed JPEG. The decoder refuses it later; nothing is invented.
assert_eq!(preview, window, "an unclosed JPEG is handed on unchanged, never padded");
assert!(preview.len() <= window.len(), "never past the window");
}
/// The preview pointer may sit past the prefix (a long maker-note record before it), and a
/// container may declare padding after the JPEG: both stay correct, and the padding is dropped.
#[test]
fn bounded_preview_handles_a_late_pointer_and_padding() {
let jpeg = fake_jpeg(300);
let late = raf_fixture(&jpeg, 0, 9000, None);
let range = bounded_preview(&late).expect("the whole file is always a valid prefix");
assert_eq!(range.offset, (160 + 9000) as u64);
let padded = raf_fixture(&jpeg, 500, 0, Some(jpeg.len() + 500));
let range = bounded_preview(&padded).expect("a padded extent is still located");
assert_eq!(range.window_len, (jpeg.len() + 500) as u64);
let window = padded.get(range.offset as usize..(range.offset + range.window_len) as usize).expect("the window is inside the file");
let preview = embedded_preview_from_range(window, range).expect("the padding is dropped");
assert_eq!(preview, embedded_preview(&padded).expect("the whole-file answer agrees"));
assert!(preview.ends_with(&[0xff, 0xd9]));
}
/// Without a usable header or pointer the caller must read the file whole: the answer is `None`,
/// never a wrong range.
#[test]
fn bounded_preview_declines_what_the_header_cannot_answer() {
let jpeg = fake_jpeg(64);
let file = raf_fixture(&jpeg, 0, 0, None);
assert_eq!(bounded_preview(&jpeg), None, "not a raw at all");
assert_eq!(bounded_preview(b""), None);
if let Some(short) = file.get(..64) {
assert_eq!(bounded_preview(short), None, "a header cut short has not shown the pointer yet");
}
// a pointer that claims more than the file holds: `header` clamps the slice to the buffer,
// so the range never runs past the end (no out-of-bounds read can follow from it)
let mut lying = raf_fixture(&jpeg, 4096, 0, None);
lying[88..92].copy_from_slice(&(u32::MAX / 2).to_be_bytes());
let clamped = bounded_preview(&lying).expect("a pointer inside the file is still usable");
assert!(clamped.offset + clamped.window_len <= lying.len() as u64, "clamped to the file: {clamped:?}");
// a range the window cannot satisfy yields nothing
assert_eq!(embedded_preview_from_range(&jpeg, PreviewRange { offset: 0, window_len: u64::MAX }), None);
// a TIFF-based raw: its pointer tag lives in an IFD this prefix may cut short
let mut tiff = b"II*\0\x08\0\0\0".to_vec();
tiff.extend_from_slice(&[0u8; 64]);
assert_eq!(bounded_preview(&tiff), None);
}
/// A range that does not hold a JPEG yields nothing, rather than a truncated image handed on.
#[test]
fn a_range_that_does_not_hold_a_jpeg_yields_nothing() {
let jpeg = fake_jpeg(200);
let range = PreviewRange { offset: 0, window_len: jpeg.len() as u64 };
assert_eq!(embedded_preview_from_range(&jpeg, range).as_deref(), Some(&jpeg[..]));
assert_eq!(embedded_preview_from_range(&jpeg[..10], range), None, "window shorter than the range claims");
let not_jpeg = vec![0u8; jpeg.len()];
assert_eq!(embedded_preview_from_range(&not_jpeg, range), None, "not a JPEG");
assert_eq!(embedded_preview_from_range(&[], PreviewRange { offset: 0, window_len: 0 }), None, "empty window");
}
#[test]
fn picks_largest_dct_jpeg() {
let small = fake_jpeg(10);
let big = fake_jpeg(500);
let lossless = crate::ljpeg::encode(&[1u16; 64], 8, 8, 1, 12, 1, 0);
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::COMPRESSION, Value::Short(vec![6]));
ifd0.set(t::IMAGE_WIDTH, Value::Long(vec![1]));
ifd0.set(t::IMAGE_LENGTH, Value::Long(vec![1]));
ifd0.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![small.clone()] });
let mut raw = IfdBuilder::new();
raw.set(t::COMPRESSION, Value::Short(vec![7]));
raw.set(t::IMAGE_WIDTH, Value::Long(vec![8]));
raw.set(t::IMAGE_LENGTH, Value::Long(vec![8]));
raw.set_image(ImageData::Strips { rows_per_strip: 8, strips: vec![lossless] });
ifd0.add_sub_ifd(raw);
let mut sub = IfdBuilder::new();
sub.set(t::COMPRESSION, Value::Short(vec![7]));
sub.set(t::IMAGE_WIDTH, Value::Long(vec![2]));
sub.set(t::IMAGE_LENGTH, Value::Long(vec![2]));
sub.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![1]));
sub.set_image(ImageData::Strips { rows_per_strip: 2, strips: vec![big.clone()] });
ifd0.add_sub_ifd(sub);
let bytes = TiffWriter::default().write(&[ifd0]).unwrap();
assert_eq!(embedded_preview(&bytes).unwrap(), big);
assert!(embedded_preview(b"nope").is_none());
// CR3: a PRVW box after the ftyp
let mut cr3 = b"\0\0\0\x18ftypcrx \0\0\0\x01crx isom".to_vec();
let j = fake_jpeg(300);
cr3.extend_from_slice(&((24 + j.len()) as u32).to_be_bytes());
cr3.extend_from_slice(b"PRVW\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01");
cr3.extend_from_slice(&(j.len() as u32).to_be_bytes());
cr3.extend_from_slice(&j);
assert_eq!(embedded_preview(&cr3).unwrap(), j);
for n in 0..cr3.len() {
let _ = embedded_preview(&cr3[..n]);
}
}
/// #2569: `PRVW` box and JPEG lengths near `u32::MAX` (which wrap `usize` on wasm32) find no preview, never panic.
#[test]
fn cr3_preview_box_huge_lengths_are_rejected() {
let j = fake_jpeg(300);
for (size, len) in [(u32::MAX, u32::MAX), (u32::MAX, u32::MAX - 23), (24 + j.len() as u32, u32::MAX - 3)] {
let mut cr3 = b"\x00\x00\x00\x18ftypcrx \x00\x00\x00\x01crx isom".to_vec();
cr3.extend_from_slice(&size.to_be_bytes());
cr3.extend_from_slice(b"PRVW\x00\x00\x00\x00\x00\x01\x06T\x048\x00\x01");
cr3.extend_from_slice(&len.to_be_bytes());
cr3.extend_from_slice(&j);
assert_eq!(cr3_preview_boxes(&cr3), None, "size {size:#x}, len {len:#x}");
}
}
/// A JPEG like [`fake_jpeg`] whose frame header says `w` x `h` with `nc` components.
fn sized_jpeg(w: u16, h: u16, nc: u8, n: usize) -> Vec<u8> {
let mut j = vec![0xff, 0xd8, 0xff, 0xc0, 0x00, 8 + 3 * nc, 8];
j.extend_from_slice(&h.to_be_bytes());
j.extend_from_slice(&w.to_be_bytes());
j.push(nc);
for c in 0..nc {
j.extend_from_slice(&[c + 1, 0x11, 0]);
}
j.extend(std::iter::repeat_n(0x55u8, n));
j.extend_from_slice(&[0xff, 0xd9]);
j
}
/// A TIFF raw holding `jpegs` as JPEG-compressed strips: the first in IFD0, the others in sub-IFDs.
fn tiff_with_jpegs(jpegs: &[&[u8]]) -> Vec<u8> {
let ifd = |j: &[u8]| {
let mut ifd = IfdBuilder::new();
ifd.set(t::COMPRESSION, Value::Short(vec![6]));
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1]));
ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1]));
ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![j.to_vec()] });
ifd
};
let mut ifd0 = ifd(jpegs[0]);
for j in &jpegs[1..] {
ifd0.add_sub_ifd(ifd(j));
}
TiffWriter::default().write(&[ifd0]).unwrap()
}
/// A stand-in decodes the smallest JPEG that covers its box and shows the same picture as the largest: not a
/// thumbnail of another shape (a letterboxed one) or a grey mask, and the largest when no smaller one is big enough.
#[test]
fn a_stand_in_takes_the_smallest_covering_jpeg_of_the_same_shape() {
let (big, small, boxed) = (sized_jpeg(9984, 6656, 3, 500), sized_jpeg(1616, 1080, 3, 50), sized_jpeg(160, 120, 3, 10));
// a ProRAW DNG keeps grey semantic masks of the picture's shape as JPEGs too
let mask = sized_jpeg(768, 512, 1, 20);
let file = tiff_with_jpegs(&[&small, &big, &boxed, &mask]);
assert_eq!(embedded_preview(&file).unwrap(), big, "unchanged: the largest");
assert_eq!(embedded_preview_covering(&file, 1600).unwrap(), small, "1616 px covers a 1600 px box");
assert_eq!(embedded_preview_covering(&file, 1616).unwrap(), small);
assert_eq!(embedded_preview_covering(&file, 1617).unwrap(), big, "too small: the largest");
assert_eq!(embedded_preview_covering(&file, u32::MAX).unwrap(), big);
assert_eq!(embedded_preview_covering(&file, 100).unwrap(), small, "the 4:3 thumbnail and the grey mask are not this picture");
// a small copy of the same shape (within 1 %) is taken
let thumb = sized_jpeg(160, 107, 3, 10);
let file = tiff_with_jpegs(&[&small, &big, &thumb]);
assert_eq!(embedded_preview_covering(&file, 100).unwrap(), thumb);
assert_eq!(embedded_preview_covering(&tiff_with_jpegs(&[&big]), 100).unwrap(), big, "one preview: that one");
for n in (0..file.len()).step_by(7) {
let _ = embedded_preview_covering(&file[..n], 100);
}
}
/// CR3 with a full-size JPEG track: that JPEG wins over the smaller `PRVW` box.
#[test]
fn cr3_prefers_the_full_size_jpeg_track() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat());
let (small, big) = (fake_jpeg(300), fake_jpeg(3000));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
let mut prvw = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
prvw.extend_from_slice(&(small.len() as u32).to_be_bytes());
prvw.extend_from_slice(&small);
file.extend(bx(b"PRVW", &prvw));
// CRAW sample entry: 82 bytes, then a JPEG child box; one sample at `at`
let mut craw = vec![0u8; 82];
craw.extend(bx(b"JPEG", &[0; 4]));
let at = 2048u64;
let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat());
let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat());
let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat());
let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat()))));
file.extend(bx(b"moov", &trak));
file.resize(at as usize, 0);
file.extend_from_slice(&big);
assert_eq!(embedded_preview(&file).unwrap(), big);
// a track pointing past the end falls back to PRVW
file.truncate(at as usize + 100);
assert_eq!(embedded_preview(&file).unwrap(), small);
}
/// A CR3 whose `PRVW` box holds `prvw` and whose JPEG track holds `big`.
fn cr3_with(prvw_jpeg: &[u8], big: &[u8]) -> Vec<u8> {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat());
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
let mut prvw = b"\0\0\0\0\0\x01\x06T\x048\0\x01".to_vec();
prvw.extend_from_slice(&(prvw_jpeg.len() as u32).to_be_bytes());
prvw.extend_from_slice(prvw_jpeg);
file.extend(bx(b"PRVW", &prvw));
let mut craw = vec![0u8; 82];
craw.extend(bx(b"JPEG", &[0; 4]));
let at = 4096u64;
let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat());
let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat());
let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat());
let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat()))));
file.extend(bx(b"moov", &trak));
file.resize(at as usize, 0);
file.extend_from_slice(big);
file
}
/// A CR3 thumbnail decodes the 1620 px `PRVW` copy, not the full-size JPEG (PERF-THUMB-FIRST:
/// 150 ms a photo for the full one); a size the copy can't cover, and the largest preview, are
/// still the full JPEG; a `PRVW` of another shape is never taken for the picture.
#[test]
fn cr3_thumbnails_take_the_smallest_copy_that_covers_them() {
let (prvw, big) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(6000, 4000, 3, 3000));
let file = cr3_with(&prvw, &big);
assert_eq!(embedded_preview_covering(&file, 512).unwrap(), prvw);
assert_eq!(embedded_preview_covering(&file, 1620).unwrap(), prvw);
assert_eq!(embedded_preview_covering(&file, 2000).unwrap(), big);
assert_eq!(embedded_preview(&file).unwrap(), big);
let letterboxed = cr3_with(&sized_jpeg(1620, 1215, 3, 300), &big);
assert_eq!(embedded_preview_covering(&letterboxed, 512).unwrap(), big, "another shape is not a copy");
for n in (0..file.len()).step_by(13) {
let _ = embedded_preview_covering(&file[..n], 512);
}
}
/// PERF-CULL-4: the smallest preview that covers the size asked for, of the largest one's shape;
/// the largest when none covers it. A CR3's 8192 px track, 1620 px `PRVW` and 160 px `THMB`.
#[test]
fn the_smallest_preview_covering_the_size_is_chosen() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat());
let boxed = |j: &[u8]| {
let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
b.extend_from_slice(&(j.len() as u32).to_be_bytes());
b.extend_from_slice(j);
b
};
let (thmb, prvw, big) = (sized_jpeg(160, 107, 1, 50), sized_jpeg(1620, 1080, 1, 300), sized_jpeg(8192, 5464, 1, 3000));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"THMB", &boxed(&thmb)));
file.extend(bx(b"PRVW", &boxed(&prvw)));
let mut craw = vec![0u8; 82];
craw.extend(bx(b"JPEG", &[0; 4]));
let at = 4096u64;
let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat());
let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat());
let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat());
let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat()))));
file.extend(bx(b"moov", &trak));
file.resize(at as usize, 0);
file.extend_from_slice(&big);
assert_eq!(embedded_preview(&file).unwrap(), big);
assert_eq!(embedded_preview_covering(&file, 512).unwrap(), prvw, "a grid thumbnail");
assert_eq!(embedded_preview_covering(&file, 1620).unwrap(), prvw);
assert_eq!(embedded_preview_covering(&file, 100).unwrap(), thmb);
assert_eq!(embedded_preview_covering(&file, 2560).unwrap(), big, "a large loupe");
assert_eq!(embedded_preview_covering(&file, u32::MAX).unwrap(), big);
// a smaller preview of another shape (letterboxed 16:9) is never a stand-in for the 3:2 one
let mut wide = file.clone();
let p = wide.windows(4).position(|w| w == b"PRVW").unwrap();
// the JPEG starts 20 bytes after the tag; its frame height 7 bytes into it
let height = p + 20 + 7;
wide[height..height + 2].copy_from_slice(&911u16.to_be_bytes());
assert_eq!(embedded_preview_covering(&wide, 512).unwrap(), big);
// without the JPEG track the boxes are chosen from too: the smallest that covers, else the largest
// (CodeRabbit on #3577: a box-only CR3 always gave its largest box)
let boxes_only = &file[..file.windows(4).position(|w| w == b"moov").unwrap() - 4];
assert_eq!(embedded_preview_covering(boxes_only, 100).unwrap(), thmb);
assert_eq!(embedded_preview_covering(boxes_only, 512).unwrap(), prvw);
assert_eq!(embedded_preview_covering(boxes_only, 2560).unwrap(), prvw, "none covers: the largest");
assert_eq!(embedded_preview(boxes_only).unwrap(), prvw);
// damaged files never panic
for n in (0..file.len()).step_by(7) {
let _ = embedded_preview_covering(&file[..n], 512);
}
}
/// A minimal CR3 whose Canon box holds `CMT2` (EXIF ColorSpace `exif`) and `CMT3` (maker-note ColorSpace `note`).
fn cr3_with_color_space(exif: Option<u16>, note: Option<u16>) -> Vec<u8> {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let block = |tag: u16, v: Option<u16>| {
let ifd =
v.map_or_else(|| IfdBuilder::new().with(t::ISO_SPEED, Value::Short(vec![100])), |v| IfdBuilder::new().with(tag, Value::Short(vec![v])));
TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap()
};
let cmt1 = TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[IfdBuilder::new().with(t::MAKE, Value::Ascii("Canon".into()))]).unwrap();
let canon_uuid = [0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48];
let boxes = [bx(b"CMT1", &cmt1), bx(b"CMT2", &block(0xA001, exif)), bx(b"CMT3", &block(0x00b4, note))].concat();
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"moov", &bx(b"uuid", &[&canon_uuid[..], &boxes].concat())));
file
}
/// A CR3 (not TIFF-based) says its preview's colour space in the Canon maker note (`CMT3` 0x00b4), else an
/// EXIF ColorSpace of sRGB in `CMT2`: an EOS R shot in Adobe RGB writes Uncalibrated with no interop (issue #2654).
#[test]
fn cr3_preview_colour_space_comes_from_the_canon_maker_note() {
use PreviewColorSpace::{AdobeRgb, Srgb};
let space = |exif, note| embedded_preview_color_space(&cr3_with_color_space(exif, note));
assert_eq!(space(Some(0xFFFF), Some(2)), Some(AdobeRgb));
assert_eq!(space(Some(1), Some(1)), Some(Srgb));
assert_eq!(space(Some(1), Some(2)), Some(AdobeRgb), "the maker note wins");
assert_eq!(space(Some(1), None), Some(Srgb), "no maker-note value: the EXIF sRGB");
assert_eq!(space(Some(0xFFFF), Some(0xFFFF)), None, "neither says");
assert_eq!(space(Some(0xFFFF), None), None);
assert_eq!(space(None, None), None);
let f = cr3_with_color_space(Some(0xFFFF), Some(2));
for n in 0..f.len() {
let _ = embedded_preview_color_space(&f[..n]);
}
}
/// A CR2 shot in Adobe RGB writes EXIF ColorSpace Uncalibrated with InteropIndex "R98", not "R03": the Canon
/// maker note (0x00b4) says Adobe RGB (issue #2654). Another make's note is not read for it.
#[test]
fn cr2_preview_colour_space_comes_from_the_canon_maker_note() {
use PreviewColorSpace::{AdobeRgb, Srgb};
let cr2 = |make: &str, exif_space: u16, note: Option<u16>| {
let mut exif = IfdBuilder::new();
exif.set(0xA001, Value::Short(vec![exif_space]));
exif.set_child(t::INTEROP_IFD, IfdBuilder::new().with(0x0001, Value::Undefined(b"R98".to_vec())));
if let Some(v) = note {
// a plain one-entry IFD, its SHORT value inline
let mut mn = 1u16.to_le_bytes().to_vec();
mn.extend([0x00b4u16.to_le_bytes(), 3u16.to_le_bytes()].concat());
mn.extend(1u32.to_le_bytes());
mn.extend([v.to_le_bytes(), [0, 0]].concat());
mn.extend(0u32.to_le_bytes());
exif.set(t::MAKER_NOTE, Value::Undefined(mn));
}
let mut ifd0 = IfdBuilder::new().with(t::MAKE, Value::Ascii(make.into()));
ifd0.set_child(t::EXIF_IFD, exif);
TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd0]).unwrap()
};
assert_eq!(embedded_preview_color_space(&cr2("Canon", 0xFFFF, Some(2))), Some(AdobeRgb));
assert_eq!(embedded_preview_color_space(&cr2("Canon", 1, Some(1))), Some(Srgb));
assert_eq!(embedded_preview_color_space(&cr2("Canon", 1, None)), Some(Srgb), "no maker note: the EXIF");
assert_eq!(embedded_preview_color_space(&cr2("Canon", 0xFFFF, None)), None, "R98 is not Adobe RGB's R03");
assert_eq!(embedded_preview_color_space(&cr2("Canon", 0xFFFF, Some(0xFFFF))), None);
assert_eq!(embedded_preview_color_space(&cr2("Leica", 0xFFFF, Some(2))), None, "only a Canon note");
}
/// A structurally complete DCT JPEG (no real image data): `nc` components, `n` entropy bytes.
fn scan_jpeg(nc: u8, n: usize) -> Vec<u8> {
let mut j = vec![0xff, 0xd8, 0xff, 0xdb, 0x00, 0x43, 0x00];
j.extend(std::iter::repeat_n(8u8, 64));
j.extend_from_slice(&[0xff, 0xc0, 0x00, 8 + 3 * nc, 8, 0, 16, 0, 24, nc]);
for c in 0..nc {
j.extend_from_slice(&[c + 1, 0x11, 0]);
}
j.extend_from_slice(&[0xff, 0xda, 0x00, 6 + 2 * nc, nc]);
for c in 0..nc {
j.extend_from_slice(&[c + 1, 0]);
}
j.extend_from_slice(&[0, 63, 0]);
j.extend(std::iter::repeat_n(0x55u8, n));
j.extend_from_slice(&[0xff, 0x00, 0x12, 0xff, 0xd0, 0x34, 0xff, 0xd9]);
j
}
/// `units` copies of a 200-byte record whose `d8 ff db` start runs each walk on through the
/// starts after it (a crafted Minolta-like container).
fn many_fake_jpegs(units: usize) -> Vec<u8> {
let mut unit = vec![0u8, 0xd8, 0xff, 0xdb, 0x00, 0x02, 0xff, 0xda, 0x00, 0x02];
unit.extend(std::iter::repeat_n(0x55u8, 190));
let mut f = b"\0MRM\0\x01\0\0".to_vec();
f.reserve(units * unit.len());
for _ in 0..units {
f.extend_from_slice(&unit);
}
f
}
/// The production scan's budget policy, restated here so the tests assert an expected bound
/// independently instead of calling the helper under test: eight times the file's size, at
/// least 1 MiB.
fn policy_budget(len: usize) -> u64 {
(len as u64 * 8).max(1 << 20)
}
/// A crafted 40 MB container full of JPEG-like starts (each walk running on through the starts
/// after it) is scanned in bounded work: the walks share a budget (without it this file would
/// walk about 8·10^10 bytes), so the charged work stays within the policy budget plus one walk's
/// reach. No wall clock: this cannot fail on a slow runner, and removing the budget shows up as
/// the work exploding.
#[test]
fn a_scan_through_many_fake_jpegs_stays_linear() {
let f = many_fake_jpegs(200_000);
assert_eq!(f.len(), 40_000_008, "the adversarial fixture the budget was measured on");
let (found, walked) = scan_with_budget(&f, policy_budget(f.len()) as usize);
assert_eq!(found, None);
let bound = policy_budget(f.len()) + f.len() as u64;
assert!(walked <= bound, "walked {walked} bytes of a {} byte file (bound {bound})", f.len());
}
/// A walk whose final entropy search finds no `ff` has examined the rest of the file, so that
/// search is charged to the budget before the walk fails. Without the charge the 40 MB tail is
/// scanned for free and only the few KB before it are reported, while `left` stays positive and
/// the budget no longer bounds the work.
#[test]
fn a_failed_terminal_search_is_charged_to_the_budget() {
let mut f = many_fake_jpegs(20);
f.extend(std::iter::repeat_n(0x55u8, 40_000_000));
let (found, walked) = scan_with_budget(&f, 1);
assert_eq!(found, None);
assert!(walked >= 40_000_000, "terminal search was not charged: {walked} of {} bytes", f.len());
}
/// The production wrapper stops at the same shared budget. Eighteen fake candidates each declare
/// a segment length that makes their walk jump 0xFFF0 bytes, exhausting the tiny file's 1 MiB
/// allowance before the valid JPEG after them: the wrapper finds nothing. A `usize::MAX` budget
/// (or no budget at all) would walk on and return that JPEG.
#[test]
fn the_production_wrapper_stops_at_the_shared_budget() {
let mut f = b"\0MRM\0\x01\0\0".to_vec();
for _ in 0..18 {
f.extend_from_slice(&[0x00, 0xd8, 0xff, 0xe1, 0xff, 0xf0]);
}
f.extend_from_slice(&scan_jpeg(3, 100));
assert_eq!(scan_for_jpeg(&f), None);
}
/// The shared budget is what bounds the work, and the counter reports the work itself. The same
/// generator at 200 starts is a 40 KB file: without the budget (never decremented, or restarted
/// for each candidate) the scan walks all 200 walks, 4 MB, instead of about 1 MB — so a negative
/// run costs megabytes, not the 8·10^10 bytes of the 40 MB fixture.
#[test]
fn the_scan_budget_bounds_the_work_a_crafted_file_can_cause() {
let f = many_fake_jpegs(200);
let budget = policy_budget(f.len());
let (found, walked) = scan_with_budget(&f, budget as usize);
assert_eq!(found, None);
assert!(walked >= (f.len() as u64) / 2, "the walks ran: {walked} bytes of {}", f.len());
assert!(walked <= budget + (f.len() as u64), "walked {walked} with a {budget} byte budget");
// The counter records the work, not the unspent budget: a budget of one file size is spent
// by the first walk, and the second walk is still counted in full (it overshoots).
let (_, spent) = scan_with_budget(&f, f.len());
let len = f.len() as u64;
assert!(spent > len && spent <= 2 * len, "spent {spent} with a {len}-byte budget");
// No candidate, no work counted.
let none = b"no jpeg here";
assert_eq!(scan_with_budget(none, policy_budget(none.len()) as usize).1, 0);
// One real candidate: the counter counts exactly the reach of its walk.
let mut one = vec![0u8];
let jpeg = scan_jpeg(3, 100);
one.extend_from_slice(&jpeg);
let (found, walked) = scan_with_budget(&one, policy_budget(one.len()) as usize);
assert!(found.is_some());
assert_eq!(walked, jpeg.len() as u64, "one walk of the JPEG's {} bytes", jpeg.len());
// The production wrapper takes the same path and returns the counter's preview.
assert_eq!(scan_for_jpeg(&one).as_deref(), found.as_deref());
}
/// Containers whose structure we do not walk give up their largest colour JPEG, found by scanning.
#[test]
fn scanned_containers_give_the_largest_colour_jpeg() {
let (small, big, mosaic) = (scan_jpeg(3, 100), scan_jpeg(3, 900), scan_jpeg(1, 5000));
let heads: [&[u8]; 3] = [b"II\x1a\0\0\0HEAPCCDR", b"\0MRM\0\x01\0\0", b"FOVb\x02\0\x02\0"];
for head in heads {
let mut f = head.to_vec();
for part in [&small, &mosaic, &big] {
f.extend_from_slice(&[0xff, 0xd8, 0xff, 0x00, 0x00]); // a stray SOI-like run: not a JPEG
f.extend_from_slice(part);
f.extend_from_slice(&[0u8; 7]);
}
// CRW and MRW decode; their previews are still found by the scan, the others stay preview-only containers
assert!(crate::probe(&f).is_some_and(|p| !p.is_supported() || p == crate::RawFormat::Crw || p == crate::RawFormat::Mrw), "{head:?}");
assert_eq!(embedded_preview(&f).as_deref(), Some(&big[..]), "{head:?}");
for n in (0..f.len()).step_by(11) {
let _ = embedded_preview(&f[..n]);
}
}
// a preview whose first byte was overwritten (Minolta and Epson files store 00, 02 or ee there) is restored
let mut f = b"\0MRM\0\x01\0\0".to_vec();
f.push(0x02);
f.extend_from_slice(&big[1..]);
assert_eq!(embedded_preview(&f).as_deref(), Some(&big[..]));
// only a one-component JPEG, or none: nothing
let mut f = b"FOVb\x02\0\x02\0".to_vec();
f.extend_from_slice(&mosaic);
assert_eq!(embedded_preview(&f), None);
}
/// A CR3's `PRVW` / `THMB` boxes are searched outside the media data only, but before and after
/// it: a `moov` after the `mdat` (its Canon `uuid` holding the `THMB`) still gives its preview, and
/// bytes inside the media data that look like a preview box are never taken for one.
#[test]
fn cr3_preview_boxes_after_the_media_data_are_found() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let boxed = |j: &[u8]| {
let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
b.extend_from_slice(&(j.len() as u32).to_be_bytes());
b.extend_from_slice(j);
b
};
let (thmb, in_media) = (sized_jpeg(160, 107, 1, 50), sized_jpeg(1620, 1080, 1, 300));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"mdat", &bx(b"PRVW", &boxed(&in_media))));
file.extend(bx(b"moov", &bx(b"uuid", &[&[0x85u8; 16][..], &bx(b"THMB", &boxed(&thmb))].concat())));
assert_eq!(embedded_preview(&file).unwrap(), thmb);
for n in (0..file.len()).step_by(5) {
let _ = embedded_preview(&file[..n]);
}
}
/// Every valid `PRVW` of a CR3 is a candidate (CodeRabbit on #3055): with a small one first and
/// one that covers the size after it, a thumbnail takes the second, not the full-size track.
#[test]
fn a_cr3_with_two_prvw_boxes_offers_both() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let full = |kind: &[u8; 4], body: &[u8]| bx(kind, &[&[0u8; 4][..], body].concat());
let boxed = |j: &[u8]| {
let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
b.extend_from_slice(&(j.len() as u32).to_be_bytes());
b.extend_from_slice(j);
b
};
let (small, covering, big) = (sized_jpeg(300, 200, 1, 50), sized_jpeg(1620, 1080, 1, 300), sized_jpeg(8192, 5464, 1, 3000));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"PRVW", &boxed(&small)));
file.extend(bx(b"PRVW", &boxed(&covering)));
let mut craw = vec![0u8; 82];
craw.extend(bx(b"JPEG", &[0; 4]));
let at = 4096u64;
let stsd = full(b"stsd", &[&1u32.to_be_bytes()[..], &bx(b"CRAW", &craw)].concat());
let stsz = full(b"stsz", &[0u32.to_be_bytes(), 1u32.to_be_bytes(), (big.len() as u32).to_be_bytes()].concat());
let co64 = full(b"co64", &[&1u32.to_be_bytes()[..], &at.to_be_bytes()].concat());
let trak = bx(b"trak", &bx(b"mdia", &bx(b"minf", &bx(b"stbl", &[stsd, stsz, co64].concat()))));
file.extend(bx(b"moov", &trak));
// (the track in the media data, as a camera writes it, after a `free` box up to it)
let pad = at as usize - 16 - file.len();
file.extend(bx(b"free", &vec![0u8; pad]));
file.extend(bx(b"mdat", &big));
assert_eq!(embedded_preview_covering(&file, 1024).unwrap(), covering);
assert_eq!(embedded_preview_covering(&file, 200).unwrap(), small);
}
/// A CR3 preview box claiming the largest sizes a file can give is skipped, never wrapped or
/// panicked on (CodeRabbit on #3080: on a 32-bit build the plain sums could overflow).
#[test]
fn a_cr3_preview_box_with_hostile_sizes_is_skipped() {
let mut file = b"\0\0\0\x18ftypcrx \0\0\0\x01crx isom".to_vec();
file.extend_from_slice(&u32::MAX.to_be_bytes());
file.extend_from_slice(b"PRVW\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01");
file.extend_from_slice(&u32::MAX.to_be_bytes());
file.extend_from_slice(&fake_jpeg(64));
assert!(embedded_preview(&file).is_none());
assert!(embedded_preview_covering(&file, 64).is_none());
}
/// A corrupt raw whose preview pointer (JPEGInterchangeFormat and its length) lies past the end
/// of the file, or whose length runs past it, finds no preview and never panics; a real preview
/// beside the lying pointer is still found (FredApps on #3080: the preview must be read with
/// bounds on its offset and size).
#[test]
fn a_preview_pointer_past_the_end_of_the_file_finds_no_preview() {
let real = sized_jpeg(640, 480, 3, 200);
let lying = |off: u32, len: u32, with_real: bool| {
let mut ifd = IfdBuilder::new();
ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![off]));
ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![len]));
if with_real {
ifd.set(t::COMPRESSION, Value::Short(vec![6]));
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1]));
ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1]));
ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![real.clone()] });
}
TiffWriter::default().write(&[ifd]).unwrap()
};
let short = lying(0, 0, false).len() as u32;
for (off, len) in [(u32::MAX, u32::MAX), (u32::MAX, 16), (short + 10, 4096), (8, u32::MAX), (short - 2, u32::MAX - 1)] {
let file = lying(off, len, false);
assert_eq!(embedded_preview(&file), None, "pointer {off:#x}+{len:#x} in a {} byte file", file.len());
assert_eq!(embedded_preview_covering(&file, 64), None);
assert_eq!(embedded_preview_color_space(&file), None);
let with_real = lying(off, len, true);
assert_eq!(embedded_preview(&with_real).as_deref(), Some(&real[..]), "the strip preview beside pointer {off:#x}+{len:#x}");
// and every truncation of the file (a raw cut short by a failed copy) is safe too
for n in 0..with_real.len() {
let _ = embedded_preview_covering(&with_real[..n], 64);
}
}
}
/// A preview pointer whose length runs past the end of a file that cuts its JPEG short (no end
/// marker) finds no preview, so a smaller whole one wins; an overstated length whose JPEG is whole
/// inside the file still finds it (CodeRabbit on #3077).
#[test]
fn a_preview_cut_short_by_the_end_of_the_file_is_not_taken() {
let big = sized_jpeg(1600, 1200, 3, 4000);
let small = sized_jpeg(160, 120, 3, 100);
// the small JPEG as a strip, the big one pointed to at the end of the file
let with_tail = |tail: &[u8], declared: u32| {
let probe = {
let mut ifd = IfdBuilder::new();
ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![0]));
ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![0]));
ifd.set(t::COMPRESSION, Value::Short(vec![6]));
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1]));
ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1]));
ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![small.clone()] });
ifd
};
let at = TiffWriter::default().write(&[probe]).unwrap().len() as u32;
let mut ifd = IfdBuilder::new();
ifd.set(t::JPEG_INTERCHANGE_FORMAT, Value::Long(vec![at]));
ifd.set(t::JPEG_INTERCHANGE_FORMAT_LENGTH, Value::Long(vec![declared]));
ifd.set(t::COMPRESSION, Value::Short(vec![6]));
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![1]));
ifd.set(t::IMAGE_LENGTH, Value::Long(vec![1]));
ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![small.clone()] });
let mut file = TiffWriter::default().write(&[ifd]).unwrap();
assert_eq!(file.len() as u32, at, "the pointer lands right after the TIFF");
file.extend_from_slice(tail);
file
};
// the big one with a start of scan after its frame header (sized_jpeg has none), as a real JPEG
let mut big = big;
big.splice(21..21, [0xff, 0xda, 0x00, 0x02]);
let declared = big.len() as u32 + 64;
// cut short: half of the big JPEG, no end marker
let cut = with_tail(&big[..big.len() / 2], declared);
assert_eq!(embedded_preview(&cut).as_deref(), Some(&small[..]), "the truncated JPEG is not taken");
// whole, its length overstated past the file's end: still the largest
let whole = with_tail(&big, declared);
assert_eq!(embedded_preview(&whole).as_deref(), Some(&big[..]), "a whole JPEG with an overstated length is kept");
// an end marker inside an APP1 payload is not the JPEG's end: cut short, still not taken
let mut with_app = vec![0xff, 0xd8, 0xff, 0xe1, 0x00, 0x08, 0x12, 0xff, 0xd9, 0x34, 0x56, 0x78];
with_app.extend_from_slice(&big[2..]);
let declared = with_app.len() as u32 + 64;
let cut = with_tail(&with_app[..with_app.len() / 2], declared);
assert_eq!(embedded_preview(&cut).as_deref(), Some(&small[..]), "an FF D9 in APP1 doesn't make a cut JPEG whole");
// whole, with other bytes after it up to the file's end: kept, cut at its own end marker
let mut tail = with_app.clone();
tail.extend_from_slice(&[0x11, 0xff, 0xd9, 0x22]);
let whole = with_tail(&tail, declared);
assert_eq!(embedded_preview(&whole).as_deref(), Some(&with_app[..]), "a whole JPEG is cut at its own end");
// an end marker before any start of scan: no image data, not taken (CodeRabbit on #3080)
let unscanned = sized_jpeg(1600, 1200, 3, 4000);
let whole = with_tail(&unscanned, unscanned.len() as u32 + 64);
assert_eq!(embedded_preview(&whole).as_deref(), Some(&small[..]), "a JPEG without a scan is not taken");
}
/// The walk to a JPEG's end refuses what isn't one and never runs past the bytes it has.
#[test]
fn the_end_of_a_jpeg_is_its_own_end_marker() {
let jpeg_end = |s: &[u8]| super::jpeg_end(s, &mut (1usize << 20));
assert_eq!(jpeg_end(&[0x12, 0x34, 0xff, 0xd9]), None, "not a JPEG");
assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xd9]), None, "an end before any scan: no image data");
// a stuffed zero and a restart marker in the scan data, then the end
assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xda, 0x00, 0x02, 0x55, 0xff, 0x00, 0xff, 0xd3, 0x66, 0xff, 0xd9]), Some(14));
// a segment length of 0 or 1, or one running past the end
assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0x00, 0x01, 0xff, 0xd9]), None);
assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0xff, 0xff, 0xff, 0xd9]), None);
for n in 0..12 {
assert_eq!(jpeg_end(&[0xff, 0xd8, 0xff, 0xe1, 0x00, 0x04, 0xff, 0xd9, 0x55, 0xff, 0xff, 0xff][..n]), None, "{n} bytes");
}
}
/// CodeRabbit on #3080: the walks to a JPEG's end share one budget, so a file of many pointers past
/// its end can't make each walk run the whole file: a walk that would overspend it gives up.
#[test]
fn the_walks_to_a_jpegs_end_share_a_budget() {
use super::jpeg_end;
let mut j = vec![0xff, 0xd8, 0xff, 0xda, 0x00, 0x02];
j.extend(std::iter::repeat_n(0x55u8, 1000));
j.extend_from_slice(&[0xff, 0xd9]);
let mut budget = 1500;
assert_eq!(jpeg_end(&j, &mut budget), Some(j.len()), "the first walk fits");
assert!(budget < 1500 - 1000, "and is charged for its steps: {budget} left");
assert_eq!(jpeg_end(&j, &mut budget), None, "the second would overspend what is left");
assert_eq!(budget, 0);
}
/// A CR3 without a JPEG track whose smaller `PRVW` (another shape) takes more bytes: the picture is
/// the box with the most pixels, not the most bytes (CodeRabbit on #3077).
#[test]
fn a_box_only_cr3_is_judged_by_pixels_not_bytes() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let boxed = |j: &[u8]| {
let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
b.extend_from_slice(&(j.len() as u32).to_be_bytes());
b.extend_from_slice(j);
b
};
let (big, square) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(800, 800, 3, 5000));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"PRVW", &boxed(&square)));
file.extend(bx(b"PRVW", &boxed(&big)));
// no media data found: the whole file is searched, and only its first box counts (a later look-alike could be
// in media data; CodeRabbit on #3583)
assert_eq!(embedded_preview(&file).unwrap(), square);
file.extend(bx(b"mdat", &[0u8; 16]));
assert_eq!(embedded_preview(&file).unwrap(), big);
assert_eq!(embedded_preview_covering(&file, 100).unwrap(), big, "the square is another picture's shape");
}
/// Every top-level `mdat` is media data, not only the first: a PRVW-shaped JPEG in a second one is
/// never the preview; and a `PRVW` cut short before its end marker isn't chosen to cover a size
/// (CodeRabbit on #3583).
#[test]
fn cr3_boxes_in_any_media_data_or_cut_short_are_not_previews() {
let bx = |kind: &[u8; 4], body: &[u8]| -> Vec<u8> { [&((body.len() + 8) as u32).to_be_bytes()[..], kind, body].concat() };
let boxed = |j: &[u8]| {
let mut b = b"\0\0\0\0\0\x01\x06\x54\x04\x38\0\x01".to_vec();
b.extend_from_slice(&(j.len() as u32).to_be_bytes());
b.extend_from_slice(j);
b
};
let (real, fake) = (sized_jpeg(1620, 1080, 3, 300), sized_jpeg(3000, 2000, 3, 300));
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
file.extend(bx(b"PRVW", &boxed(&real)));
file.extend(bx(b"mdat", &[0u8; 64]));
file.extend(bx(b"mdat", &bx(b"PRVW", &boxed(&fake))));
assert_eq!(embedded_preview(&file).unwrap(), real, "the look-alike in the second mdat is media data");
// a PRVW cut short (no end marker): the full-size track covers a thumbnail instead
let mut short = real.clone();
short.truncate(real.len() - 2);
let big = sized_jpeg(6000, 4000, 3, 3000);
assert_eq!(embedded_preview_covering(&cr3_with(&short, &big), 512).unwrap(), big);
assert_eq!(embedded_preview_covering(&cr3_with(&real, &big), 512).unwrap(), real, "a whole one is still taken");
}
/// The copy a CR3 thumbnail is given decodes, whichever is chosen (CodeRabbit on #3583: the other CR3 fixtures have
/// no scan): real encoded JPEGs, the `PRVW` for a small size, the full-size track past it.
#[test]
fn the_cr3_copy_chosen_for_a_thumbnail_decodes() {
let encode = |w: u16, h: u16| {
let px: Vec<u8> = (0..usize::from(w) * usize::from(h)).flat_map(|i| [(i % 251) as u8, 90, 160]).collect();
let mut j = Vec::new();
jpeg_encoder::Encoder::new(&mut j, 85).encode(&px, w, h, jpeg_encoder::ColorType::Rgb).unwrap();
j
};
let file = cr3_with(&encode(96, 64), &encode(384, 256));
for (min, want) in [(64u32, (96, 64)), (200, (384, 256))] {
let j = embedded_preview_covering(&file, min).unwrap();
let (_, w, h, c) = crate::tiffraw::lossy_jpeg(&j, 3, 1 << 20).unwrap();
assert_eq!(((w, h), c), (want, 3), "covering {min} px");
}
}
+95 -139
View File
@@ -22,46 +22,25 @@
//! Values above 1.0 (highlight headroom) keep their headroom: the table's value scale only ever
//! lowers them, so a lookup can't clip what the scene-referred pipeline still needs.
use crate::gaintable::GainTableMap;
pub use craft_raw::profile::{HsvTable, ProfileLook, ToneCurve};
use lightcraft_color::transfer::{linear_to_srgb, srgb_to_linear};
use lightcraft_color::{D50, D65, Mat3, PROPHOTO, REC2020, bradford};
use serde::{Deserialize, Serialize};
/// Upper bound on table entries (Adobe profiles use ≤ 90 × 30 × 16; guards header-driven sizes).
const MAX_ENTRIES: usize = 1 << 20;
/// A DNG hue/saturation/value mapping table (`ProfileHueSatMapData*` / `ProfileLookTableData`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HsvTable {
pub hue_divisions: usize,
pub sat_divisions: usize,
pub val_divisions: usize,
/// `(hue shift °, saturation scale, value scale)`, value-major, hue-middle, saturation-minor.
pub data: Vec<[f32; 3]>,
/// The value axis is indexed through the sRGB encoding curve (`…Encoding` = 1).
pub srgb_value: bool,
/// Applying a hue/saturation/value table (the table, and reading it from its tags, is `craft-raw`'s).
pub trait HsvTableApply: Sized {
/// The entry-wise blend `g · a + (1 − g) · b` of two tables of the same shape (`None` otherwise).
fn blend(a: &Self, b: &Self, g: f64) -> Option<Self>;
/// Tri-linear lookup at hue `h` (degrees), saturation `s` and value `v` (table coordinates).
fn lookup(&self, h: f32, s: f32, v: f32) -> [f32; 3];
/// Apply the table to one linear ProPhoto RGB colour.
fn apply(&self, rgb: [f32; 3]) -> [f32; 3];
/// [`Self::apply`] to `N` colours at once (`rgb[channel][lane]`), bit for bit.
fn apply_lanes<const N: usize>(&self, rgb: [[f32; N]; 3]) -> [[f32; N]; 3];
}
impl HsvTable {
/// A table from its `…Dims` (hue, saturation, value divisions), data floats and encoding.
/// `None` when the dimensions are out of range, the data length doesn't match or a value is
/// not finite.
pub fn from_tags(dims: &[u64], data: &[f64], encoding: u64) -> Option<HsvTable> {
let [h, s, v] = <[u64; 3]>::try_from(dims).ok()?;
let (h, s, v) = (usize::try_from(h).ok()?, usize::try_from(s).ok()?, usize::try_from(v).ok()?);
if h < 1 || s < 2 || v < 1 || h > 4096 || s > 4096 || v > 4096 {
return None;
}
let n = h.checked_mul(s)?.checked_mul(v)?;
if n > MAX_ENTRIES || data.len() != n * 3 || data.iter().any(|x| !x.is_finite()) {
return None;
}
let data = data.as_chunks::<3>().0.iter().map(|c| [c[0] as f32, (c[1] as f32).max(0.0), (c[2] as f32).max(0.0)]).collect();
Some(HsvTable { hue_divisions: h, sat_divisions: s, val_divisions: v, data, srgb_value: encoding == 1 && v > 1 })
}
impl HsvTableApply for HsvTable {
/// The entry-wise blend `g · a + (1 − g) · b` of two tables of the same shape (`None` otherwise).
pub fn blend(a: &HsvTable, b: &HsvTable, g: f64) -> Option<HsvTable> {
fn blend(a: &HsvTable, b: &HsvTable, g: f64) -> Option<HsvTable> {
if (a.hue_divisions, a.sat_divisions, a.val_divisions) != (b.hue_divisions, b.sat_divisions, b.val_divisions) {
return None;
}
@@ -70,12 +49,8 @@ impl HsvTable {
Some(HsvTable { data, ..a.clone() })
}
fn entry(&self, v: usize, h: usize, s: usize) -> [f32; 3] {
self.data.get((v * self.hue_divisions + h) * self.sat_divisions + s).copied().unwrap_or([0.0, 1.0, 1.0])
}
/// Tri-linear lookup at hue `h` (degrees), saturation `s` and value `v` (table coordinates).
pub fn lookup(&self, h: f32, s: f32, v: f32) -> [f32; 3] {
fn lookup(&self, h: f32, s: f32, v: f32) -> [f32; 3] {
let hf = (wrap(h, 360.0) / 360.0 * self.hue_divisions as f32).clamp(0.0, self.hue_divisions as f32);
let h0 = (hf as usize).min(self.hue_divisions - 1);
let h1 = (h0 + 1) % self.hue_divisions;
@@ -90,15 +65,15 @@ impl HsvTable {
let (v0, v1, tv) = if self.val_divisions > 1 { axis(v, self.val_divisions) } else { (0, 0, 0.0) };
let lerp = |a: [f32; 3], b: [f32; 3], t: f32| -> [f32; 3] { std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) };
let plane = |vi: usize| {
let lo = lerp(self.entry(vi, h0, s0), self.entry(vi, h0, s1), ts);
let hi = lerp(self.entry(vi, h1, s0), self.entry(vi, h1, s1), ts);
let lo = lerp(entry(self, vi, h0, s0), entry(self, vi, h0, s1), ts);
let hi = lerp(entry(self, vi, h1, s0), entry(self, vi, h1, s1), ts);
lerp(lo, hi, th)
};
if v0 == v1 { plane(v0) } else { lerp(plane(v0), plane(v1), tv) }
}
/// Apply the table to one linear ProPhoto RGB colour.
pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {
fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {
let max = rgb[0].max(rgb[1]).max(rgb[2]);
if max.is_nan() || max <= 0.0 || !max.is_finite() {
return rgb;
@@ -127,9 +102,9 @@ impl HsvTable {
/// [`Self::apply`] to `N` colours at once (`rgb[channel][lane]`), bit for bit: the same operations, with the
/// branches on the data (largest channel, hue sector, wrap-around) turned into selects so the compiler
/// vectorises them. The table reads, `powf` and the rare `rem_euclid` run lane by lane.
pub fn apply_lanes<const N: usize>(&self, rgb: [[f32; N]; 3]) -> [[f32; N]; 3] {
fn apply_lanes<const N: usize>(&self, rgb: [[f32; N]; 3]) -> [[f32; N]; 3] {
let [r, g, b] = rgb;
if !self.fits_lanes() {
if !fits_lanes(self) {
let mut out = rgb;
for l in 0..N {
[out[0][l], out[1][l], out[2][l]] = self.apply([r[l], g[l], b[l]]);
@@ -172,7 +147,7 @@ impl HsvTable {
}
}
}
let [shift, ss, vs] = self.lookup_lanes(&hue, &sat, &v_index, active);
let [shift, ss, vs] = lookup_lanes(self, &hue, &sat, &v_index, active);
let (mut s2, mut v2, mut curve) = ([0.0f32; N], [0.0f32; N], [false; N]);
for l in 0..N {
s2[l] = limited_select(sat[l], ss[l]);
@@ -228,72 +203,76 @@ impl HsvTable {
}
out
}
}
/// Whether [`Self::lookup_lanes`] can do this table's index arithmetic in `f32`: every index below 2²³.
fn fits_lanes(&self) -> bool {
let entries = self.hue_divisions.checked_mul(self.sat_divisions).and_then(|n| n.checked_mul(self.val_divisions.max(1)));
self.hue_divisions >= 1 && self.sat_divisions >= 1 && entries.is_some_and(|n| n <= 1 << 23)
fn entry(table: &HsvTable, v: usize, h: usize, s: usize) -> [f32; 3] {
table.data.get((v * table.hue_divisions + h) * table.sat_divisions + s).copied().unwrap_or([0.0, 1.0, 1.0])
}
/// Whether [`lookup_lanes`] can do this table's index arithmetic in `f32`: every index below 2²³.
fn fits_lanes(table: &HsvTable) -> bool {
let entries = table.hue_divisions.checked_mul(table.sat_divisions).and_then(|n| n.checked_mul(table.val_divisions.max(1)));
table.hue_divisions >= 1 && table.sat_divisions >= 1 && entries.is_some_and(|n| n <= 1 << 23)
}
/// [`HsvTableApply::lookup`] at `N` points (`(shift, saturation scale, value scale)[lane]`), bit for bit for the lanes
/// `wanted`, on a table that [`fits_lanes`]. The indices are computed as `f32` (exact integers below 2²³:
/// `x as usize` is a saturating conversion that doesn't vectorise).
fn lookup_lanes<const N: usize>(table: &HsvTable, h: &[f32; N], s: &[f32; N], v: &[f32; N], wanted: [bool; N]) -> [[f32; N]; 3] {
const EXACT: f32 = 8_388_608.0; // 2²³: ulp 1 from here
// `x as usize` for `0 ≤ x < 2²³`: rounded to an integer, minus 1 if it rounded up; NaN is 0
let floor = |x: f32| {
let nearest = (x + EXACT) - EXACT;
let floor = if nearest > x { nearest - 1.0 } else { nearest };
if x.is_nan() { 0.0 } else { floor }
};
let (hn, sn, vn) = (table.hue_divisions as f32, table.sat_divisions as f32, table.val_divisions as f32);
let axis = |x: f32, n: f32| {
let f = x.clamp(0.0, 1.0) * (n - 1.0);
let i0 = floor(f).min((n - 2.0).max(0.0));
let i1 = (i0 + 1.0).min(n - 1.0);
(i0, i1, (f - i0).clamp(0.0, 1.0))
};
let h = wrap_lanes(*h, 360.0, wanted);
// the corners' indices (v, h, s), s fastest, and the weights between them
let (mut at, mut t) = ([[0u32; N]; 8], [[0.0f32; N]; 3]);
for l in 0..N {
let hf = (h[l] / 360.0 * hn).clamp(0.0, hn);
let h0 = floor(hf).min(hn - 1.0);
// (h0 + 1) % hn
let h1 = if h0 + 1.0 == hn { 0.0 } else { h0 + 1.0 };
let (s0, s1, ts) = axis(s[l], sn);
let (v0, v1, tv) = axis(v[l], vn);
let (v0, v1, tv) = if table.val_divisions > 1 { (v0, v1, tv) } else { (0.0, 0.0, 0.0) };
for (k, (vi, hi)) in [(v0, h0), (v0, h1), (v1, h0), (v1, h1)].into_iter().enumerate() {
let row = (vi * hn + hi) * sn;
// an exact integer below 2²³ plus 2²³ has it as its mantissa
at[2 * k][l] = (row + s0 + EXACT).to_bits().wrapping_sub(EXACT.to_bits());
at[2 * k + 1][l] = (row + s1 + EXACT).to_bits().wrapping_sub(EXACT.to_bits());
}
[t[0][l], t[1][l], t[2][l]] = [(hf - h0).clamp(0.0, 1.0), ts, tv];
}
/// [`Self::lookup`] at `N` points (`(shift, saturation scale, value scale)[lane]`), bit for bit for the lanes
/// `wanted`, on a table that [`Self::fits_lanes`]. The indices are computed as `f32` (exact integers below 2²³:
/// `x as usize` is a saturating conversion that doesn't vectorise).
fn lookup_lanes<const N: usize>(&self, h: &[f32; N], s: &[f32; N], v: &[f32; N], wanted: [bool; N]) -> [[f32; N]; 3] {
const EXACT: f32 = 8_388_608.0; // 2²³: ulp 1 from here
// `x as usize` for `0 ≤ x < 2²³`: rounded to an integer, minus 1 if it rounded up; NaN is 0
let floor = |x: f32| {
let nearest = (x + EXACT) - EXACT;
let floor = if nearest > x { nearest - 1.0 } else { nearest };
if x.is_nan() { 0.0 } else { floor }
};
let (hn, sn, vn) = (self.hue_divisions as f32, self.sat_divisions as f32, self.val_divisions as f32);
let axis = |x: f32, n: f32| {
let f = x.clamp(0.0, 1.0) * (n - 1.0);
let i0 = floor(f).min((n - 2.0).max(0.0));
let i1 = (i0 + 1.0).min(n - 1.0);
(i0, i1, (f - i0).clamp(0.0, 1.0))
};
let h = wrap_lanes(*h, 360.0, wanted);
// the corners' indices (v, h, s), s fastest, and the weights between them
let (mut at, mut t) = ([[0u32; N]; 8], [[0.0f32; N]; 3]);
for l in 0..N {
let hf = (h[l] / 360.0 * hn).clamp(0.0, hn);
let h0 = floor(hf).min(hn - 1.0);
// (h0 + 1) % hn
let h1 = if h0 + 1.0 == hn { 0.0 } else { h0 + 1.0 };
let (s0, s1, ts) = axis(s[l], sn);
let (v0, v1, tv) = axis(v[l], vn);
let (v0, v1, tv) = if self.val_divisions > 1 { (v0, v1, tv) } else { (0.0, 0.0, 0.0) };
for (k, (vi, hi)) in [(v0, h0), (v0, h1), (v1, h0), (v1, h1)].into_iter().enumerate() {
let row = (vi * hn + hi) * sn;
// an exact integer below 2²³ plus 2²³ has it as its mantissa
at[2 * k][l] = (row + s0 + EXACT).to_bits().wrapping_sub(EXACT.to_bits());
at[2 * k + 1][l] = (row + s1 + EXACT).to_bits().wrapping_sub(EXACT.to_bits());
}
[t[0][l], t[1][l], t[2][l]] = [(hf - h0).clamp(0.0, 1.0), ts, tv];
let mut corner = [[[0.0f32; N]; 3]; 8];
for l in 0..N {
for (corner, at) in corner.iter_mut().zip(&at) {
[corner[0][l], corner[1][l], corner[2][l]] = table.data.get(at[l] as usize).copied().unwrap_or([0.0, 1.0, 1.0]);
}
let mut corner = [[[0.0f32; N]; 3]; 8];
}
let lerp = |a: &[f32; N], b: &[f32; N], t: &[f32; N]| {
let mut out = [0.0f32; N];
for l in 0..N {
for (corner, at) in corner.iter_mut().zip(&at) {
[corner[0][l], corner[1][l], corner[2][l]] = self.data.get(at[l] as usize).copied().unwrap_or([0.0, 1.0, 1.0]);
}
}
let lerp = |a: &[f32; N], b: &[f32; N], t: &[f32; N]| {
let mut out = [0.0f32; N];
for l in 0..N {
out[l] = a[l] + (b[l] - a[l]) * t[l];
}
out
};
let [th, ts, tv] = &t;
let mut out = [[0.0f32; N]; 3];
for (c, out) in out.iter_mut().enumerate() {
let plane = |k: usize| lerp(&lerp(&corner[k][c], &corner[k + 1][c], ts), &lerp(&corner[k + 2][c], &corner[k + 3][c], ts), th);
// `lookup`'s `v0 == v1` for every lane: `axis` gives `v1 = v0 + 1` whenever there are two values or more
*out = if self.val_divisions > 1 { lerp(&plane(0), &plane(4), tv) } else { plane(0) };
out[l] = a[l] + (b[l] - a[l]) * t[l];
}
out
};
let [th, ts, tv] = &t;
let mut out = [[0.0f32; N]; 3];
for (c, out) in out.iter_mut().enumerate() {
let plane = |k: usize| lerp(&lerp(&corner[k][c], &corner[k + 1][c], ts), &lerp(&corner[k + 2][c], &corner[k + 3][c], ts), th);
// `lookup`'s `v0 == v1` for every lane: `axis` gives `v1 = v0 + 1` whenever there are two values or more
*out = if table.val_divisions > 1 { lerp(&plane(0), &plane(4), tv) } else { plane(0) };
}
out
}
/// `x · k` clipped to 1, for `x ≤ 1`; above 1, only scale factors below 1 apply (continuous at 1).
@@ -378,26 +357,15 @@ fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] {
}
}
/// A DNG tone curve (`ProfileToneCurve`): linear-gamma (input, output) pairs, increasing input.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToneCurve {
pub points: Vec<[f32; 2]>,
/// Evaluating a profile tone curve.
pub trait ToneCurveEval {
/// The curve at `x` (0..=1): monotone cubic (Fritsch–Carlson) through the samples.
fn eval(&self, x: f32) -> f32;
}
impl ToneCurve {
/// From the tag's flat float pairs. `None` unless there are 2..=65536 finite pairs within
/// 0..=1 with strictly increasing inputs.
pub fn from_tag(v: &[f64]) -> Option<ToneCurve> {
if !v.len().is_multiple_of(2) || v.len() < 4 || v.len() > 131_072 {
return None;
}
let points: Vec<[f32; 2]> = v.as_chunks::<2>().0.iter().map(|p| [p[0] as f32, p[1] as f32]).collect();
let ok = points.iter().all(|p| p.iter().all(|x| x.is_finite() && (0.0..=1.0).contains(x))) && points.windows(2).all(|w| w[1][0] > w[0][0]);
ok.then_some(ToneCurve { points })
}
impl ToneCurveEval for ToneCurve {
/// The curve at `x` (0..=1): monotone cubic (Fritsch–Carlson) through the samples.
pub fn eval(&self, x: f32) -> f32 {
fn eval(&self, x: f32) -> f32 {
let p = &self.points;
let n = p.len();
let x = x.clamp(p[0][0], p[n - 1][0]);
@@ -425,27 +393,15 @@ impl ToneCurve {
}
}
/// The DNG profile look tags of a file (all optional).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ProfileLook {
/// `ProfileHueSatMapData1/2` (same shape, `ProfileHueSatMapDims`).
pub hue_sat_map: [Option<HsvTable>; 2],
/// `ProfileLookTableData`.
pub look_table: Option<HsvTable>,
/// `ProfileToneCurve`.
pub tone_curve: Option<ToneCurve>,
/// `ProfileGainTableMap2`, else `ProfileGainTableMap`.
#[serde(default)]
pub gain_table_map: Option<GainTableMap>,
/// The hue/saturation map of a profile look for a white balance.
pub trait ProfileLookHueSat {
/// The hue/saturation map for calibration-1 weight `g` (one table: used for any white).
fn hue_sat_for(&self, g: f64) -> Option<HsvTable>;
}
impl ProfileLook {
pub fn is_empty(&self) -> bool {
self.hue_sat_map.iter().all(Option::is_none) && self.look_table.is_none() && self.tone_curve.is_none() && self.gain_table_map.is_none()
}
impl ProfileLookHueSat for ProfileLook {
/// The hue/saturation map for calibration-1 weight `g` (one table: used for any white).
pub fn hue_sat_for(&self, g: f64) -> Option<HsvTable> {
fn hue_sat_for(&self, g: f64) -> Option<HsvTable> {
match &self.hue_sat_map {
[Some(a), Some(b)] => HsvTable::blend(a, b, g).or_else(|| Some(a.clone())),
[Some(a), None] | [None, Some(a)] => Some(a.clone()),
+7 -2
View File
@@ -28,12 +28,16 @@ const ABOVE_MARGIN: f32 = 0.01;
const NEIGHBOURHOOD: usize = 64;
// CR3 gain-normalized saturation can occupy several nearby codes, rather than one exact value.
#[cfg(test)]
const CR3_BINS: usize = 256;
#[cfg(test)]
const CR3_PLATEAU_BINS: usize = 8;
#[cfg(test)]
const CR3_MIN_SAMPLES: u64 = 64;
/// The lower edge of a terminal pile-up, ignoring a few brighter outliers. A continuous
/// highlight distribution has comparable density below it and therefore has no plateau.
#[cfg(test)]
fn cr3_plateau(hist: &[[u64; 3]; CR3_BINS], first: &[[u16; 3]; CR3_BINS], colour: usize, from: usize, white: f32) -> Option<f32> {
let (start, end, count) = (from + 1..=CR3_BINS)
.map(|end| {
@@ -64,7 +68,7 @@ impl RawImage {
let black = self.black.mean();
// a hostile file can state any levels: NaN, negative or inverted ones are left alone
let levels_ok = black.is_finite() && white.is_finite() && black >= 0.0 && white > black && white <= 65535.0;
if self.cpp != 1 || !cfa.valid() || self.width.checked_mul(self.height) != Some(d.len()) || !levels_ok {
if self.cpp != 1 || !crate::cfa_valid(cfa) || self.width.checked_mul(self.height) != Some(d.len()) || !levels_ok {
return none;
}
let a = self.active_area;
@@ -135,6 +139,7 @@ impl RawImage {
/// coarse bins so gain-spread saturation (e.g. R100) is found too. With enough above-white
/// data but no clear pile-up, the bit-depth ceiling keeps all that unclipped headroom.
/// One shared range and its compensating baseline EV preserve lower tones and colour ratios.
#[cfg(test)]
pub(crate) fn extend_cr3_white(&mut self) -> bool {
if self.format != crate::RawFormat::Cr3 || !self.color.baseline_exposure.is_finite() || !(1..=16).contains(&self.bits) {
return false;
@@ -143,7 +148,7 @@ impl RawImage {
let (old, black) = (self.white_at(0), self.black.mean());
let ceiling = ((1u32 << self.bits) - 1) as f32;
if self.cpp != 1
|| !cfa.valid()
|| !crate::cfa_valid(cfa)
|| self.width.checked_mul(self.height) != Some(data.len())
|| !black.is_finite()
|| !old.is_finite()
+9 -108
View File
@@ -1,121 +1,22 @@
//! DNG semantic masks (DNG 1.6+, chapter "Semantic Masks"): single-channel segmentation mattes
//! stored in their own IFDs (NewSubFileType 10004.H, PhotometricInterpretation 52527) with a
//! `SemanticName`, an optional `SemanticInstanceID` and an optional `MaskSubArea`. iPhone ProRAW
//! stores e.g. a sky matte this way.
//!
//! [`semantic_masks`] reads them separately from [`crate::decode`] (only callers that use them
//! pay for them); malformed or unsupported mask IFDs are skipped.
//! Developed semantic mask conversion to `lightcraft_raster::Image<u8>`.
use crate::Rect;
use crate::tiffraw::{Packing, read_image};
use crate::{RawData, Result};
use craft_tiff::Tiff;
use craft_tiff::tags::{self as t, photometric};
pub use craft_raw::semantic::*;
use lightcraft_raster::Image;
/// At most this many mask IFDs are read from one file.
pub const MAX_MASKS: usize = 16;
/// Masks with more samples than this are skipped (a mask is a low-resolution matte; this is
/// 8192 × 4096).
pub const MAX_MASK_SAMPLES: usize = 1 << 25;
/// Where a cropped mask sits in the uncropped mask (DNG `MaskSubArea`). The uncropped mask
/// (`full_width × full_height`) spans the main image's active area.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MaskSubArea {
pub top: u32,
pub left: u32,
pub full_width: u32,
pub full_height: u32,
/// Extension trait to render a [`SemanticMask`] onto the developed image.
pub trait SemanticMaskExt {
/// The mask over the developed image (the default `crop` of the `active_area`, before
/// orientation), at the mask's own resolution, as 0..255 alpha. `None` for an empty crop.
fn developed(&self, active_area: craft_raw::Rect, crop: craft_raw::Rect) -> Option<Image<u8>>;
}
/// One semantic mask: `width × height` values, 0 = not part of the attribute, 65535 = fully part.
#[derive(Clone, Debug, PartialEq)]
pub struct SemanticMask {
/// `SemanticName`, e.g. `urn:com:apple:photo:2020:aux:semanticskymatte`.
pub name: String,
pub instance_id: Option<String>,
pub width: usize,
pub height: usize,
/// `None`: the mask covers the whole active area.
pub sub_area: Option<MaskSubArea>,
pub data: Vec<u16>,
}
/// The semantic masks of a DNG, in file order (none for other files). Only the first
/// [`MAX_MASKS`] mask IFDs are looked at, malformed ones included, so a file full of mask IFDs
/// costs at most that many decodes.
pub fn semantic_masks(bytes: &[u8]) -> Vec<SemanticMask> {
let Ok(tiff) = Tiff::parse(bytes) else { return Vec::new() };
tiff.all_ifds()
.into_iter()
.filter(|i| i.u16(t::PHOTOMETRIC) == Some(photometric::MASK) || i.u32(t::NEW_SUBFILE_TYPE) == Some(t::SUBFILE_SEMANTIC_MASK))
.take(MAX_MASKS)
.filter_map(|ifd| read_mask(bytes, &tiff, ifd).ok().flatten())
.collect()
}
fn read_mask(bytes: &[u8], tiff: &Tiff, ifd: &craft_tiff::Ifd) -> Result<Option<SemanticMask>> {
let Some(name) = ifd.string(t::SEMANTIC_NAME).filter(|n| !n.is_empty()) else { return Ok(None) };
let info = ifd.image()?;
let (w, h) = (info.width as usize, info.height as usize);
if info.samples_per_pixel != 1 || w.checked_mul(h).is_none_or(|n| n > MAX_MASK_SAMPLES) {
return Ok(None);
}
let bits = info.bits() as u32;
let data: Vec<u16> = match read_image(bytes, &info, tiff.order, Packing::Msb)? {
RawData::U16(v) if (1..=16).contains(&bits) => {
let max = ((1u32 << bits) - 1) as f32;
if bits == 16 { v } else { v.into_iter().map(|s| (s as f32 / max * 65535.0).round().min(65535.0) as u16).collect() }
}
RawData::F32(v) => v.into_iter().map(|s| if s.is_finite() { (s.clamp(0.0, 1.0) * 65535.0).round() as u16 } else { 0 }).collect(),
RawData::U16(_) => return Ok(None),
};
if data.len() != w * h {
return Ok(None);
}
// the tag is ignored when the stored mask does not fit inside the uncropped one
let sub_area = match ifd.u64s(t::MASK_SUB_AREA).as_deref() {
Some(&[top, left, fw, fh]) => {
let fits = fw > 0 && fh > 0 && left.saturating_add(w as u64) <= fw && top.saturating_add(h as u64) <= fh && fw.max(fh) <= u32::MAX as u64;
fits.then_some(MaskSubArea { top: top as u32, left: left as u32, full_width: fw as u32, full_height: fh as u32 })
}
_ => None,
};
Ok(Some(SemanticMask { name, instance_id: ifd.string(t::SEMANTIC_INSTANCE_ID).filter(|s| !s.is_empty()), width: w, height: h, sub_area, data }))
}
impl SemanticMask {
/// The mask value (0..1) at a continuous position of the uncropped mask (pixel centres at
/// +0.5); 0 outside the stored (cropped) mask.
pub fn value_at(&self, x: f64, y: f64) -> f32 {
let (left, top) = self.sub_area.map_or((0.0, 0.0), |a| (a.left as f64, a.top as f64));
let (x, y) = (x - left, y - top);
if self.width == 0 || self.height == 0 || !(x >= 0.0 && y >= 0.0 && x <= self.width as f64 && y <= self.height as f64) {
return 0.0;
}
let (fx, fy) = ((x - 0.5).max(0.0), (y - 0.5).max(0.0));
let (x0, y0) = (fx.floor() as usize, fy.floor() as usize);
let (tx, ty) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32);
let at = |x: usize, y: usize| {
let (x, y) = (x.min(self.width - 1), y.min(self.height - 1));
self.data.get(y * self.width + x).copied().unwrap_or(0) as f32 / 65535.0
};
let top = at(x0, y0) + (at(x0 + 1, y0) - at(x0, y0)) * tx;
let bottom = at(x0, y0 + 1) + (at(x0 + 1, y0 + 1) - at(x0, y0 + 1)) * tx;
top + (bottom - top) * ty
}
/// The mask over the developed image ([`crate::RawImage::develop`]: the default `crop` of the
/// `active_area`, before orientation), at the mask's own resolution, as 0..255 alpha. `None`
/// for an empty crop.
pub fn developed(&self, active_area: Rect, crop: Rect) -> Option<Image<u8>> {
impl SemanticMaskExt for SemanticMask {
fn developed(&self, active_area: craft_raw::Rect, crop: craft_raw::Rect) -> Option<Image<u8>> {
let c = crop.clipped(active_area.width, active_area.height);
if c.width == 0 || c.height == 0 || self.width == 0 || self.height == 0 {
return None;
}
let (fw, fh) = self.sub_area.map_or((self.width, self.height), |a| (a.full_width as usize, a.full_height as usize));
// uncropped-mask px per active-area px
let (sx, sy) = (fw as f64 / active_area.width as f64, fh as f64 / active_area.height as f64);
let ow = ((c.width as f64 * sx).round() as usize).clamp(1, self.width.max(fw));
let oh = ((c.height as f64 * sy).round() as usize).clamp(1, self.height.max(fh));
-749
View File
@@ -1,749 +0,0 @@
//! Describing a raw file without reading its pixel data.
//!
//! [`probe_info`](crate::probe_info) and `lightcraft_meta::extract` read only a raw file's
//! headers, but those are a few hundred kilobytes of a file of tens of megabytes: an import from a
//! slow drive spends nearly all its time reading samples nothing looks at. [`header_plan`] says
//! which byte ranges of a file those readers need. It is asked about a buffer of the file's full
//! length in which only the ranges in `loaded` hold the file's bytes (the rest is zeros); the caller
//! loads the ranges it names and asks again. Once it says [`HeaderPlan::Ready`], probing the buffer
//! gives what probing the whole file gives.
//!
//! Only bulk sample data is left out: the strips and tiles of each large TIFF image (keeping the
//! start of the first one, where the coding headers a header probe validates sit), a CR3's image
//! tracks (keeping the raw track's coding headers and quantization maps, and the timed-metadata
//! track where Canon puts the as-shot white balance), a RAF's CFA strip (keeping its compression
//! header) and a Panasonic RW2's raw data. Formats whose header probe reads samples (NEF: masked
//! columns; ORF: bit depth and CFA phase; PEF: dark borders; ARW6, for its header plan only: the
//! start of every tile) and anything else get [`HeaderPlan::Whole`], as does a structure that is
//! incomplete, inconsistent or keeps metadata inside its sample data: the plan never guesses.
use std::collections::HashSet;
use craft_tiff::{ByteOrder, FieldType, Tiff, tags as t};
use lightcraft_meta::cr3::{Cr3TrackKind, XMP_UUID, is_cr3, parse_cr3};
use crate::RawFormat;
/// Bytes kept at the start of a skipped block: the coding headers a header probe validates there
/// (lossless-JPEG frame headers, a RAF's compression header and stripe table) fit with room to spare.
const HEAD: u64 = 64 * 1024;
/// An image whose chunks hold fewer bytes than this is read (thumbnails, small previews).
const BULK: u64 = 256 * 1024;
/// The same bounds as `craft_tiff`'s reader.
const MAX_IFDS: usize = 1024;
const MAX_ENTRIES: u64 = 8192;
const MAX_BOXES: usize = 4096;
/// Child IFDs listed by one `SubIFDs` entry.
const MAX_CHILDREN: u64 = 4096;
/// Pending child-IFD offsets the walker may queue at once: no more than it can ever visit
/// (the same [`MAX_IFDS`] the seen set is held to, deduplicated as they are popped), so an alley
/// of hostile `SubIFDs` entries can't grow the queue into the tens of millions of pointers.
/// The plan never guesses: the walk refuses and the plan reports the whole file when it would go
/// past the cap.
const MAX_PENDING: usize = MAX_IFDS;
/// The RAF raw container's pointer to its raw IFD.
const RAF_RAW_IFD: u16 = 0xf000;
/// Byte ranges `[start, end)` of a file: sorted, disjoint and not touching.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Ranges(Vec<(u64, u64)>);
impl Ranges {
pub fn new() -> Self {
Self::default()
}
/// Add `[start, end)` (nothing when it is empty).
pub fn insert(&mut self, start: u64, end: u64) {
if start >= end {
return;
}
let (mut start, mut end) = (start, end);
let mut out = Vec::with_capacity(self.0.len() + 1);
let mut placed = false;
for &(a, b) in &self.0 {
if b < start {
out.push((a, b));
} else if a > end {
if !placed {
out.push((start, end));
placed = true;
}
out.push((a, b));
} else {
start = start.min(a);
end = end.max(b);
}
}
if !placed {
out.push((start, end));
}
self.0 = out;
}
/// Add every `[start, end)` of `spans` in one sort and merge (empty ones add nothing).
pub fn extend(&mut self, spans: impl IntoIterator<Item = (u64, u64)>) {
let mut all: Vec<(u64, u64)> = std::mem::take(&mut self.0);
all.extend(spans.into_iter().filter(|&(a, b)| a < b));
all.sort_unstable();
let mut out: Vec<(u64, u64)> = Vec::with_capacity(all.len());
for (a, b) in all {
match out.last_mut() {
Some(last) if a <= last.1 => last.1 = last.1.max(b),
_ => out.push((a, b)),
}
}
self.0 = out;
}
/// Whether all of `[start, end)` is covered (an empty range always is).
pub fn contains(&self, start: u64, end: u64) -> bool {
start >= end || self.0.iter().any(|&(a, b)| a <= start && end <= b)
}
/// Whether some of `[start, end)` is covered.
pub fn overlaps(&self, start: u64, end: u64) -> bool {
start < end && self.0.iter().any(|&(a, b)| a < end && start < b)
}
pub fn spans(&self) -> &[(u64, u64)] {
&self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Bytes covered.
pub fn total(&self) -> u64 {
self.0.iter().fold(0u64, |n, &(a, b)| n.saturating_add(b - a))
}
/// The parts of `[start, end)` not covered.
pub fn gaps(&self, start: u64, end: u64) -> Ranges {
// the gaps come in order, apart from each other: pushed, not merged in one by one
let mut out = Vec::new();
let mut at = start;
for &(a, b) in &self.0 {
if b <= at {
continue;
}
if a >= end {
break;
}
if a > at {
out.push((at, a));
}
at = at.max(b);
}
if at < end {
out.push((at, end));
}
Ranges(out)
}
/// These ranges without the ones in `other`.
pub fn minus(&self, other: &Ranges) -> Ranges {
let mut out = Ranges::new();
out.extend(self.0.iter().flat_map(|&(a, b)| other.gaps(a, b).0));
out
}
}
/// What [`header_plan`] says about a partly loaded file.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HeaderPlan {
/// Load these ranges (none of them loaded yet) and ask again.
Need(Ranges),
/// Everything the header readers look at is loaded: probing the buffer gives the whole file's
/// result.
Ready,
/// The file can't be described from part of it (why): read it whole.
Whole(&'static str),
}
/// What of the raw file in `bytes` a header probe reads. `bytes` has the file's full length;
/// only the ranges in `loaded` hold its bytes (see the module docs).
pub fn header_plan(bytes: &[u8], loaded: &Ranges) -> HeaderPlan {
plan(bytes, loaded, false)
}
/// [`header_plan`] for a raw shown from its embedded preview (a coding not decoded yet): also what
/// [`crate::embedded_preview`] reads — a CR3's JPEG track and preview boxes, the strips of a TIFF
/// raw's preview images.
pub fn preview_plan(bytes: &[u8], loaded: &Ranges) -> HeaderPlan {
plan(bytes, loaded, true)
}
fn plan(bytes: &[u8], loaded: &Ranges, preview: bool) -> HeaderPlan {
let mut w = Want::new(bytes, loaded);
if !w.want(0, 16) {
return w.into_plan().unwrap_or(HeaderPlan::Whole("file too short"));
}
if is_cr3(bytes) {
cr3_plan(bytes, loaded, preview)
} else if bytes.starts_with(b"FUJIFILMCCD-RAW") {
// (its preview, the embedded JPEG, is read anyway: its metadata are there)
raf_plan(bytes, loaded)
} else if bytes.get(..4).is_some_and(|m| matches!(m, b"IIRO" | b"IIRS" | b"MMOR")) {
HeaderPlan::Whole("an ORF header probe reads samples")
} else if Tiff::sniff(bytes).is_some() {
tiff_plan(bytes, loaded, preview)
} else {
HeaderPlan::Whole("not a raw layout read in part")
}
}
/// Collects the ranges a plan still needs.
struct Want<'a> {
len: u64,
loaded: &'a Ranges,
/// What is missing, as found; merged once into the plan (merging each find into the ranges so
/// far was a copy of them per find: quadratic over a file of many out-of-line values).
need: Vec<(u64, u64)>,
/// `need` is merged when it reaches this long, so repeated finds of one gap stay bounded by
/// the distinct gaps (merging when it doubles keeps the cost linear).
compact_at: usize,
}
impl<'a> Want<'a> {
fn new(bytes: &[u8], loaded: &'a Ranges) -> Self {
Self { len: bytes.len() as u64, loaded, need: Vec::new(), compact_at: 64 }
}
/// Whether `[start, end)` (clipped to the file) is loaded; asks for what isn't.
fn want(&mut self, start: u64, end: u64) -> bool {
let end = end.min(self.len);
if self.loaded.contains(start, end) {
return true;
}
self.need.extend(self.loaded.gaps(start, end).0);
if self.need.len() >= self.compact_at {
let mut merged = Ranges::new();
merged.extend(std::mem::take(&mut self.need));
self.need = merged.spans().to_vec();
self.compact_at = (self.need.len() * 2).max(64);
}
false
}
/// `Need` when something is missing.
fn into_plan(self) -> Option<HeaderPlan> {
let mut need = Ranges::new();
need.extend(self.need);
(!need.is_empty()).then_some(HeaderPlan::Need(need))
}
}
/// Everything but `holes` is needed. `meta` (IFD tables and out-of-line values) must not lie in a
/// hole; once all is loaded, `ready` decides.
fn finish(len: u64, loaded: &Ranges, holes: &Ranges, meta: &Ranges, ready: impl FnOnce() -> HeaderPlan) -> HeaderPlan {
if holes.spans().iter().any(|&(a, b)| meta.overlaps(a, b)) {
return HeaderPlan::Whole("metadata inside sample data");
}
let missing = holes.gaps(0, len).minus(loaded);
if missing.is_empty() { ready() } else { HeaderPlan::Need(missing) }
}
fn tiff_plan(bytes: &[u8], loaded: &Ranges, preview: bool) -> HeaderPlan {
let len = bytes.len() as u64;
let mut w = Want::new(bytes, loaded);
let meta = match walk_tiff(&mut w, 0, bytes, &[]) {
Ok(meta) => meta,
Err(why) => return HeaderPlan::Whole(why),
};
if let Some(plan) = w.into_plan() {
return plan;
}
// (the Make is usually in the first kilobytes: a NEF, PEF or ORF is known before the rest is read)
if matches!(crate::probe(bytes), Some(RawFormat::Nef | RawFormat::Nrw | RawFormat::Orf | RawFormat::Pef | RawFormat::Erf | RawFormat::Mef)) {
return HeaderPlan::Whole("its header probe reads samples");
}
let Ok(tiff) = Tiff::parse(bytes) else { return HeaderPlan::Whole("TIFF structure") };
let mut holes = Ranges::new();
let mut spans = Vec::new();
for ifd in tiff.all_ifds() {
let chunks: Vec<(u64, u64)> = match ifd.image() {
// a preview's strips are read when the preview is wanted: only the raw image is skipped
Ok(info) if preview && !matches!(info.photometric, t::photometric::CFA | t::photometric::LINEAR_RAW) => continue,
// (Sony Compressed RAW 2: the header probe decodes the start of every tile; a preview reads none)
Ok(info) if !preview && info.compression == 32766 => return HeaderPlan::Whole("an ARW6 header probe reads its tiles"),
Ok(info) => info.chunks(len).iter().map(|c| (c.offset, c.len)).collect(),
// a raw IFD without the tags a TIFF image needs (an older CR2's) still lists its strips
Err(_) => match (ifd.u64s(t::STRIP_OFFSETS), ifd.u64s(t::STRIP_BYTE_COUNTS)) {
(Some(offsets), Some(counts)) if offsets.len() == counts.len() => offsets.into_iter().zip(counts).collect(),
_ => continue,
},
};
let total = chunks.iter().fold(0u64, |n, c| n.saturating_add(c.1));
if total < BULK {
continue;
}
spans.extend(chunks.iter().enumerate().map(|(i, &(offset, size))| {
let start = if i == 0 { offset.saturating_add(HEAD) } else { offset };
(start, offset.saturating_add(size).min(len))
}));
}
holes.extend(spans);
// A Panasonic RW2 keeps its raw data from `RawDataOffset` to the end, outside any TIFF image.
if holes.is_empty()
&& bytes.starts_with(b"IIU\0")
&& let Some(off) = tiff.ifds.first().and_then(|i| i.u64(crate::vendor::rw2::RAW_OFFSET))
{
holes.insert(off.saturating_add(HEAD), len);
}
finish(len, loaded, &holes, &meta, || match crate::probe(bytes) {
Some(RawFormat::Nef | RawFormat::Nrw | RawFormat::Orf | RawFormat::Pef | RawFormat::Erf | RawFormat::Mef) => {
HeaderPlan::Whole("its header probe reads samples")
}
Some(f) if f.is_supported() => HeaderPlan::Ready,
_ => HeaderPlan::Whole("not a supported raw"),
})
}
/// Walk the IFDs of the TIFF in `data` (which starts at `origin` in the file) as `craft_tiff`'s
/// reader does — the chain, `SubIFDs`, Exif, GPS and Interop, plus the `extra` pointer tags —
/// asking for every IFD table and for the values that locate IFDs and image chunks. Returns the IFD
/// tables and out-of-line values found (absolute ranges); incomplete while `w` needs more.
fn walk_tiff(w: &mut Want, origin: u64, data: &[u8], extra: &[u16]) -> Result<Ranges, &'static str> {
let len = data.len() as u64;
let at = |rel: u64| origin.saturating_add(rel);
let mut meta = Ranges::new();
if !w.want(origin, at(len.min(16))) {
return Ok(meta);
}
let (order, big) = Tiff::sniff(data).ok_or("not a TIFF")?;
let first = if big { order.read_u64(data, 8) } else { order.read_u32(data, 4).map(u64::from) }.ok_or("truncated TIFF header")?;
meta.insert(origin, at(len.min(if big { 16 } else { 8 })));
let (head, entry, inline) = if big { (8u64, 20u64, 8u64) } else { (2, 12, 4) };
let offset_at = |pos: u64| -> Option<u64> {
let pos = usize::try_from(pos).ok()?;
if big { order.read_u64(data, pos) } else { order.read_u32(data, pos).map(u64::from) }
};
let mut stack = vec![first];
let mut seen = HashSet::new();
// Every offset ever queued: the pending cap counts distinct IFDs, so a thousand references to
// one child cost one visit, not a thousand.
let mut queued = HashSet::from([first]);
// Every IFD table and out-of-line value, collected and merged once at the end: an insert
// per entry would scan the ranges of every entry before it — quadratic in the metadata
// this walker collects.
let mut spans: Vec<(u64, u64)> = Vec::new();
while let Some(off) = stack.pop() {
if off == 0 || off >= len || seen.len() >= MAX_IFDS || !seen.insert(off) {
continue;
}
if !w.want(at(off), at(off.saturating_add(head))) {
continue;
}
let Ok(pos) = usize::try_from(off) else { continue };
let n = if big { order.read_u64(data, pos) } else { order.read_u16(data, pos).map(u64::from) }.unwrap_or(0);
let table = off.saturating_add(head);
let n_read = n.min(len.saturating_sub(table) / entry).min(MAX_ENTRIES);
if n_read == 0 {
continue;
}
let table_end = table.saturating_add(n_read * entry);
// the reader reads the next-IFD pointer only when every entry fits
let complete = n_read == n;
let end = if complete { table_end.saturating_add(inline).min(len) } else { table_end };
if !w.want(at(off), at(end)) {
continue;
}
spans.push((at(off), at(end)));
for i in 0..n_read {
let p = table + i * entry;
let Ok(pu) = usize::try_from(p) else { continue };
let (Some(tag), Some(typ)) = (order.read_u16(data, pu), order.read_u16(data, pu + 2).and_then(FieldType::from_u16)) else { continue };
let count = if big { order.read_u64(data, pu + 4) } else { order.read_u32(data, pu + 4).map(u64::from) };
let Some(count) = count else { continue };
let field = p + if big { 12 } else { 8 };
let Some(total) = count.checked_mul(typ.size() as u64) else { continue };
let start = if total <= inline {
field
} else {
match offset_at(field) {
Some(v) => v,
None => continue,
}
};
let Some(value_end) = start.checked_add(total).filter(|&e| e <= len) else { continue };
if total > inline {
spans.push((at(start), at(value_end)));
}
let child = matches!(tag, t::SUB_IFDS | t::EXIF_IFD | t::GPS_IFD | t::INTEROP_IFD) || extra.contains(&tag);
let locates = child || matches!(tag, t::STRIP_OFFSETS | t::STRIP_BYTE_COUNTS | t::TILE_OFFSETS | t::TILE_BYTE_COUNTS);
if !locates || !w.want(at(start), at(value_end)) || !child {
continue;
}
// the reader follows every `SubIFDs` value and the first value of the other pointers
let take = if tag == t::SUB_IFDS { count.min(MAX_CHILDREN) } else { count.min(1) };
for k in 0..take {
if let Some(v) = unsigned(data, order, typ, start + k * typ.size() as u64) {
if v == 0 || v >= len || !queued.insert(v) {
continue;
}
if stack.len() >= MAX_PENDING {
return Err("too many child IFDs queued to visit");
}
stack.push(v);
}
}
}
if complete && let Some(next) = offset_at(table_end).filter(|&next| next != 0 && next < len && queued.insert(next)) {
if stack.len() >= MAX_PENDING {
return Err("too many child IFDs queued to visit");
}
stack.push(next);
}
}
meta.extend(spans);
Ok(meta)
}
/// One unsigned value of type `typ` at `pos`.
fn unsigned(data: &[u8], order: ByteOrder, typ: FieldType, pos: u64) -> Option<u64> {
let pos = usize::try_from(pos).ok()?;
match typ.size() {
1 => data.get(pos).map(|&b| u64::from(b)),
2 => order.read_u16(data, pos).map(u64::from),
4 => order.read_u32(data, pos).map(u64::from),
_ => order.read_u64(data, pos),
}
}
fn be32(bytes: &[u8], at: u64) -> Option<u64> {
let at = usize::try_from(at).ok()?;
bytes.get(at..at.checked_add(4)?).map(|s| u64::from(u32::from_be_bytes([s[0], s[1], s[2], s[3]])))
}
fn be64(bytes: &[u8], at: u64) -> Option<u64> {
let at = usize::try_from(at).ok()?;
bytes.get(at..at.checked_add(8)?).map(|s| u64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]))
}
/// A CR3 is read where `lightcraft_meta::cr3::parse_cr3` and the CR3 decoder look: the file type,
/// `moov` and the XMP `uuid` box, the first sample of each timed-metadata (`CTMD`) track, and the
/// main raw track's coding headers and quantization maps. Previews and image tracks are skipped,
/// unless `preview`: then every top-level box but `mdat` and the JPEG tracks are read too.
fn cr3_plan(bytes: &[u8], loaded: &Ranges, preview: bool) -> HeaderPlan {
let len = bytes.len() as u64;
let mut w = Want::new(bytes, loaded);
// top-level boxes, walked as `parse_cr3` walks them (it stops at the first malformed header)
let mut at = 0u64;
let mut boxes = 0;
while at.saturating_add(8) <= len && boxes < MAX_BOXES {
boxes += 1;
// size, type, a 64-bit size and a uuid
if !w.want(at, at.saturating_add(32)) {
break;
}
let Some(size) = be32(bytes, at) else { break };
let (box_len, hdr) = match size {
0 => (len - at, 8),
1 => match be64(bytes, at + 8) {
Some(l) => (l, 16),
None => break,
},
n => (n, 8),
};
let Some(end) = at.checked_add(box_len).filter(|&e| e <= len && box_len >= hdr) else { break };
let kind = bytes.get(at as usize + 4..at as usize + 8);
let needed = match kind {
Some(b"mdat") => false,
Some(b"moov") => true,
Some(b"uuid") => preview || bytes.get((at + hdr) as usize..(at + hdr + 16) as usize) == Some(XMP_UUID.as_slice()),
_ => preview,
};
if needed {
w.want(at, end);
}
at = end;
}
if let Some(plan) = w.into_plan() {
return plan;
}
let mut w = Want::new(bytes, loaded);
let Some(cr3) = parse_cr3(bytes) else { return HeaderPlan::Whole("CR3 structure") };
for track in &cr3.tracks {
if (track.kind == Cr3TrackKind::Other(*b"CTMD") || preview && track.kind == Cr3TrackKind::Jpeg)
&& let Some((offset, size)) = track.data
{
w.want(offset as u64, offset.saturating_add(size) as u64);
}
}
if let Some(track) = crate::vendor::cr3::main_track(&cr3.tracks)
&& let Some((offset, size)) = track.data
&& let Some(coding) = track.compression(bytes)
{
let o = offset as u64;
if w.want(o, o.saturating_add(u64::from(coding.header_size)))
&& let Some(sample) = bytes.get(offset..offset.saturating_add(size))
&& let Ok(ranges) = crate::vendor::crx::header_ranges(sample, &coding)
{
for r in ranges {
w.want(o.saturating_add(r.start as u64), o.saturating_add(r.end as u64));
}
}
}
w.into_plan().unwrap_or(HeaderPlan::Ready)
}
/// A RAF is read whole but for its CFA strip: the header, the embedded JPEG (its metadata), the
/// record directory and the raw container's IFDs and compression header.
fn raf_plan(bytes: &[u8], loaded: &Ranges) -> HeaderPlan {
let len = bytes.len() as u64;
let mut w = Want::new(bytes, loaded);
if !w.want(0, 160) {
return w.into_plan().unwrap_or(HeaderPlan::Whole("RAF header"));
}
let (Some(start), Some(size)) = (be32(bytes, 100), be32(bytes, 104)) else { return HeaderPlan::Whole("RAF header") };
let Some(end) = start.checked_add(size).filter(|&e| start > 0 && size > 0 && e <= len) else { return HeaderPlan::Whole("RAF raw container") };
let Some(container) = bytes.get(start as usize..end as usize) else { return HeaderPlan::Whole("RAF raw container") };
let meta = match walk_tiff(&mut w, start, container, &[RAF_RAW_IFD]) {
Ok(meta) => meta,
Err(why) => return HeaderPlan::Whole(why),
};
if let Some(plan) = w.into_plan() {
return plan;
}
let Ok(ifd) = crate::vendor::raf::raw_ifd(container) else { return HeaderPlan::Whole("RAF raw IFD") };
let (Some(off), Some(strip)) = (ifd.u64(0xf007), ifd.u64(0xf008)) else { return HeaderPlan::Whole("RAF raw strip") };
let mut holes = Ranges::new();
if strip >= BULK {
let s = start.saturating_add(off);
holes.insert(s.saturating_add(HEAD), s.saturating_add(strip).min(end));
}
finish(len, loaded, &holes, &meta, || HeaderPlan::Ready)
}
#[cfg(test)]
mod tests {
use super::*;
/// Run a plan to its end, loading from `file` what it asks for; the buffer's unloaded bytes are `fill`.
pub(crate) fn run(file: &[u8], prefix: usize, fill: u8) -> (HeaderPlan, Vec<u8>, Ranges) {
let mut buf = vec![fill; file.len()];
let mut loaded = Ranges::new();
let load = |buf: &mut Vec<u8>, loaded: &mut Ranges, a: u64, b: u64| {
buf[a as usize..b as usize].copy_from_slice(&file[a as usize..b as usize]);
loaded.insert(a, b);
};
load(&mut buf, &mut loaded, 0, prefix.min(file.len()) as u64);
for _ in 0..32 {
match header_plan(&buf, &loaded) {
HeaderPlan::Need(r) => {
for &(a, b) in r.spans() {
assert!(!loaded.overlaps(a, b), "asked again for {a}..{b}");
load(&mut buf, &mut loaded, a, b);
}
}
done => return (done, buf, loaded),
}
}
panic!("no answer after 32 rounds");
}
#[test]
fn ranges_merge_and_subtract() {
let mut r = Ranges::new();
r.insert(10, 20);
r.insert(30, 40);
r.insert(20, 25); // touching: merged
r.insert(5, 5); // empty
assert_eq!(r.spans(), &[(10, 25), (30, 40)]);
r.insert(0, 100);
assert_eq!(r.spans(), &[(0, 100)]);
let mut r = Ranges::new();
r.insert(10, 20);
r.insert(30, 40);
assert!(r.contains(12, 18) && r.contains(5, 5) && !r.contains(15, 35));
assert!(r.overlaps(15, 35) && !r.overlaps(20, 30));
assert_eq!(r.gaps(0, 50).spans(), &[(0, 10), (20, 30), (40, 50)]);
assert_eq!(r.gaps(12, 18).spans(), &[] as &[(u64, u64)]);
let mut cut = Ranges::new();
cut.insert(15, 32);
assert_eq!(r.minus(&cut).spans(), &[(10, 15), (32, 40)]);
assert_eq!(r.total(), 20);
}
#[test]
fn a_plan_of_many_missing_values_is_gathered_in_one_merge() {
// 200 000 loaded spans with a byte missing between each: every gap wanted once
let mut loaded = Ranges::new();
loaded.extend((0..20_000u64).map(|i| (i * 4, i * 4 + 3)));
let bytes = vec![0u8; 80_000];
let mut w = Want::new(&bytes, &loaded);
for i in 0..20_000u64 {
assert!(!w.want(i * 4 + 2, i * 4 + 4));
}
let Some(HeaderPlan::Need(need)) = w.into_plan() else { panic!("a plan") };
assert_eq!(need.spans().len(), 20_000);
assert_eq!(need.total(), 20_000);
assert_eq!(loaded.gaps(0, 12).spans(), &[(3, 4), (7, 8), (11, 12)]);
}
#[test]
fn repeated_wants_of_one_gap_keep_the_buffer_bounded() {
let loaded = Ranges::new();
let bytes = vec![0u8; 1000];
let mut w = Want::new(&bytes, &loaded);
for _ in 0..100_000 {
assert!(!w.want(10, 20));
assert!(w.need.len() <= 64);
}
let Some(HeaderPlan::Need(need)) = w.into_plan() else { panic!("a plan") };
assert_eq!(need.spans(), &[(10, 20)]);
}
#[test]
fn hostile_input_never_panics_and_ends() {
let mut loaded = Ranges::new();
for len in [0usize, 1, 8, 15, 16, 200] {
let bytes = vec![0u8; len];
loaded.insert(0, len as u64);
assert!(matches!(header_plan(&bytes, &loaded), HeaderPlan::Whole(_)));
}
// an IFD that points at itself, an IFD count past the end, a huge SubIFDs count
let mut tiff = b"II*\0\x08\0\0\0".to_vec();
tiff.extend_from_slice(&2u16.to_le_bytes());
tiff.extend_from_slice(&[0x4a, 0x01, 4, 0, 0xff, 0xff, 0xff, 0x0f, 8, 0, 0, 0]); // SubIFDs, 0x0fffffff values at 8
tiff.extend_from_slice(&[0x69, 0x87, 4, 0, 1, 0, 0, 0, 8, 0, 0, 0]); // Exif → itself
tiff.extend_from_slice(&8u32.to_le_bytes()); // next → itself
let (plan, _, _) = run(&tiff, 4, 0);
assert!(matches!(plan, HeaderPlan::Whole(_)), "{plan:?}");
// a CR3 whose `moov` claims more than the file holds: walked as the parser walks it (it
// stops there), so the plan ends with the little there is, and the probe then fails as
// it does on the whole file
let mut cr3 = 24u32.to_be_bytes().to_vec();
cr3.extend_from_slice(b"ftypcrx \0\0\0\x01crx isom");
cr3.extend_from_slice(&u32::MAX.to_be_bytes());
cr3.extend_from_slice(b"moov");
cr3.resize(4096, 0);
let (plan, buf, loaded) = run(&cr3, 16, 0);
assert_eq!(plan, HeaderPlan::Ready);
assert_eq!(loaded.total(), 24 + 32, "only the two box headers are read");
assert_eq!(format!("{:?}", crate::probe_info(&buf)), format!("{:?}", crate::probe_info(&cr3)));
// a RAF whose container lies outside the file
let mut raf = b"FUJIFILMCCD-RAW 0201FF383501".to_vec();
raf.resize(160, 0);
raf[100..104].copy_from_slice(&1000u32.to_be_bytes());
raf[104..108].copy_from_slice(&1000u32.to_be_bytes());
assert_eq!(run(&raf, 160, 0).0, HeaderPlan::Whole("RAF raw container"));
}
/// An ARW6 header probe reads every tile's headers and the first lines of its data, which lie in the strip a
/// plan would skip: here the second tile, past a first one of bulk size.
#[test]
fn arw6_is_described_from_the_whole_file() {
use crate::vendor::arw6_testenc::{Qis, arw6_file, one_tile_quantised};
let (tile, _) = one_tile_quantised(64, 48, 0, Qis::REAL);
let mut first = tile.clone();
first.resize(BULK as usize, 0);
let file = arw6_file(&[(0, 0, 64, 48, first), (64, 0, 64, 48, tile)], 128, 48);
assert!(crate::probe_info(&file).is_ok());
assert_eq!(run(&file, 16, 0).0, HeaderPlan::Whole("an ARW6 header probe reads its tiles"));
}
/// An IFD whose `SubIFDs` entries would queue 33 million child pointers (8192 entries of
/// 4096 values apiece, all pointing at the same array) is refused at the walker's pending
/// cap instead of growing the queue — and the plan reports the whole file, never guessing.
#[test]
fn a_subifds_alley_is_refused_at_the_pending_cap() {
// First read everything, so the walk reaches the directory table itself.
let n = 8192u32;
let len = 8 + 2 + (n * 12 + 4 + 4 * 4096) as usize;
let mut tiff = b"II*\0\x08\0\0\0".to_vec();
tiff.extend_from_slice(&(n as u16).to_le_bytes());
let mut entry = |tag: u16, typ: u16, count: u32, value: u32| {
tiff.extend_from_slice(&tag.to_le_bytes());
tiff.extend_from_slice(&typ.to_le_bytes());
tiff.extend_from_slice(&count.to_le_bytes());
tiff.extend_from_slice(&value.to_le_bytes());
};
// header (8) + count field (2) + the {n} numbers and pointer (4), then the value array
let values_at = (8 + 2u64 + u64::from(n) * 12 + 4) as u32;
for _ in 0..n {
entry(t::SUB_IFDS, 4, MAX_CHILDREN as u32, values_at);
}
tiff.extend_from_slice(&0u32.to_le_bytes());
tiff.extend((1..=4096u32).flat_map(u32::to_le_bytes));
let mut loaded = Ranges::new();
loaded.insert(0, len as u64);
let mut w = Want::new(&tiff, &loaded);
assert_eq!(walk_tiff(&mut w, 0, &tiff, &[]), Err("too many child IFDs queued to visit"));
}
/// A TIFF with many out-of-line values across 512 directories is planned in one sort and
/// merge, not one pass over all accumulated ranges per value (CodeRabbit #52: before, each
/// `Ranges::insert` copied every range found before it — the ~million disjoint values of the
/// fixture below ask for more copying than the timeout allows).
#[test]
fn many_out_of_line_values_plan_fast() {
let (ifds, values) = (512usize, 2048usize);
let ifd_len = 2 + values * 12 + 4;
let values_at = 8 + ifds * ifd_len;
let len = values_at + values * 8;
let mut tiff = vec![0u8; len];
tiff[..8].copy_from_slice(b"II*\0\x08\0\0\0");
for i in 0..ifds {
let at = 8 + i * ifd_len;
// {values} out-of-line strings (count 8 > the 4 inline bytes), then the next-IFD
// pointer; every value is a disjoint 8-byte range for the merge to handle.
tiff[at..at + 2].copy_from_slice(&(values as u16).to_le_bytes());
for k in 0..values {
let e = at + 2 + k * 12;
tiff[e..e + 2].copy_from_slice(&t::MAKE.to_le_bytes());
tiff[e + 2..e + 4].copy_from_slice(&2u16.to_le_bytes()); // ASCII: 8 bytes > inline — a span per entry
tiff[e + 4..e + 8].copy_from_slice(&8u32.to_le_bytes());
tiff[e + 8..e + 12].copy_from_slice(&(values_at as u32 + (k * 8) as u32).to_le_bytes());
}
let next = if i == ifds - 1 { 0u32 } else { (at + ifd_len) as u32 };
tiff[at + ifd_len - 4..at + ifd_len].copy_from_slice(&next.to_le_bytes());
}
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut loaded = Ranges::new();
loaded.insert(0, len as u64);
let _ = tx.send(header_plan(&tiff, &loaded));
});
rx.recv_timeout(std::time::Duration::from_secs(20)).expect("header_plan took longer than 20 s");
}
/// A TIFF with a million one-byte strips listed in descending order and all byte counts 0:
/// the plan is built in one sort and merge, not one pass over all strips (or all holes) per
/// strip.
#[test]
fn many_strips_without_byte_counts_plan_fast() {
let n = 1_000_000u32;
let (offsets_at, counts_at) = (8 + 2 + 5 * 12 + 4, 8 + 2 + 5 * 12 + 4 + 4 * n);
let data = counts_at + 4 * n;
let mut tiff = b"II*\0\x08\0\0\0".to_vec();
tiff.extend_from_slice(&5u16.to_le_bytes());
let entry = |tiff: &mut Vec<u8>, tag: u16, typ: u16, count: u32, value: u32| {
tiff.extend_from_slice(&tag.to_le_bytes());
tiff.extend_from_slice(&typ.to_le_bytes());
tiff.extend_from_slice(&count.to_le_bytes());
tiff.extend_from_slice(&value.to_le_bytes());
};
entry(&mut tiff, 256, 4, 1, 1);
entry(&mut tiff, 257, 4, 1, n);
entry(&mut tiff, 273, 4, n, offsets_at);
entry(&mut tiff, 278, 4, 1, 1);
entry(&mut tiff, 279, 4, n, counts_at);
tiff.extend_from_slice(&0u32.to_le_bytes());
for i in (0..n).rev() {
tiff.extend_from_slice(&(data + i).to_le_bytes());
}
tiff.resize(data as usize + n as usize, 0);
let len = tiff.len() as u64;
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut loaded = Ranges::new();
loaded.insert(0, len);
let _ = tx.send(header_plan(&tiff, &loaded));
});
let plan = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("header_plan took longer than 20 s");
assert!(!matches!(plan, HeaderPlan::Need(_)), "{plan:?}");
}
}
+6 -19
View File
@@ -10,7 +10,7 @@ fn cfa_helpers() {
assert_eq!(c.shifted(1, 1).name(), "BGGR");
assert!(Cfa::bayer("RGGX").is_none());
for name in ["RGGB", "BGGR", "GRBG", "GBRG"] {
assert_eq!(Cfa::bayer_static(name).name(), name);
assert_eq!(crate::bayer(name).name(), name);
}
let x = Cfa::xtrans();
assert!(!x.is_bayer());
@@ -206,7 +206,7 @@ fn ordinary_tiffs_are_not_shells() {
let mut pef = rgb_ifd(400, 300);
pef.set(t::MAKE, Value::Ascii("PENTAX Corporation".into()));
let mut exif = exif_size(400, 300);
exif.set(vendor::EXIF_CFA_PATTERN, Value::Undefined(vec![0, 2, 0, 2, 0, 1, 1, 2]));
exif.set(0xa302, Value::Undefined(vec![0, 2, 0, 2, 0, 1, 1, 2]));
pef.set_child(t::EXIF_IFD, exif);
assert_eq!(probe(&padded(&[pef])), Some(RawFormat::Pef));
let mut srw = rgb_ifd(400, 300);
@@ -259,9 +259,9 @@ fn private_containers_are_recognised_by_their_magic() {
assert_eq!(probe(b"\0MRM\0\x01\0\0"), Some(RawFormat::Mrw));
assert_eq!(probe(b"FOVb\x02\0\x02\0"), Some(RawFormat::X3f));
for f in [RawFormat::Crw, RawFormat::Mrw] {
assert!(f.is_supported());
assert!(crate::is_supported(f));
}
assert!(!RawFormat::X3f.is_supported());
assert!(!crate::is_supported(RawFormat::X3f));
// a CRW signature with no heap behind it is corrupt, not a panic
assert!(matches!(decode(b"II\x1a\0\0\0HEAPCCDR\0\0"), Err(RawError::Corrupt(_))));
assert!(matches!(decode(b"FOVb\x02\0\x02\0"), Err(RawError::Unsupported(w)) if w.contains("X3f")));
@@ -393,6 +393,7 @@ fn private_compression_99_is_a_raw() {
/// without the block, or an RGB image carrying it, stays an ordinary image.
#[test]
fn uncompressed_leaf_mos_is_a_raw() {
const LEAF_DATA: u16 = 0x8606;
let mosaic = |leaf_data: bool| {
let mut ifd = IfdBuilder::new();
ifd.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0]));
@@ -542,20 +543,6 @@ fn lossless_jpeg_cfa_tiff_decodes() {
assert_eq!(r.cfa.unwrap().name(), "RGGB");
}
/// Hasselblad's own lossless-JPEG coding (selection value 8, as in FFF and most compressed 3FR files) of the
/// same layout decodes: the file is read like the uncompressed one.
#[test]
fn selection_value_8_cfa_tiff_decodes() {
let strip = ljpeg::tests::encode_hasselblad(&cfa_samples(), 8, 6);
let bytes = plain_cfa_tiff(7, strip, None);
assert_eq!(probe(&bytes), Some(RawFormat::CfaTiff));
let r = decode(&bytes).unwrap();
assert_eq!((r.format, r.width, r.height), (RawFormat::CfaTiff, 8, 6));
assert_eq!(r.data, RawData::U16(cfa_samples()));
assert_eq!(r.cfa.unwrap().name(), "RGGB");
assert_eq!(probe_info(&bytes).unwrap().format, RawFormat::CfaTiff);
}
/// A lossless-JPEG scan whose predictor selection value is neither 0 to 7 (T.81) nor 8 (Hasselblad) is not a
/// coding the lossless decoder knows: the file stays an undecodable raw, with that as the reason, and keeps the
/// stand-in preview an unsupported container gets.
@@ -569,7 +556,7 @@ fn cfa_tiff_with_an_unknown_predictor_stays_undecodable() {
assert!(matches!(ljpeg::decode(&strip, 1 << 20), Err(RawError::Unsupported(w)) if w.contains("selection value 9")));
let bytes = plain_cfa_tiff(7, strip, None);
assert_eq!(probe(&bytes), Some(RawFormat::OtherTiff));
assert!(!RawFormat::OtherTiff.is_supported());
assert!(!crate::is_supported(RawFormat::OtherTiff));
let Err(RawError::Unsupported(why)) = decode(&bytes) else { panic!("expected Unsupported") };
assert!(why.contains("lossless JPEG") && why.contains("selection value 9"), "{why}");
}
-779
View File
@@ -1,779 +0,0 @@
//! Reading the pixel data of a TIFF IFD (strips or tiles; uncompressed, lossless/lossy JPEG, Deflate, JPEG XL), in parallel.
use crate::unpack::{f16_to_f32, f24_to_f32, inflate, read_u16s, undo_diff_u16, undo_float_predictor, unpack_lsb, unpack_msb, unpack_words32_msb};
use crate::{MAX_SAMPLES, RawData, RawError, Result, ljpeg};
use craft_tiff::image::{Chunk, ImageInfo, chunk_bytes};
use craft_tiff::{ByteOrder, tags::compression as comp};
use rayon::prelude::*;
/// Bit packing for uncompressed integer data with bit depths other than 8/16.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(dead_code)] // vendor decoders use the other variants
pub enum Packing {
/// TIFF standard: MSB-first, rows start on byte boundaries.
Msb,
/// LSB-first little-endian bit stream (some vendor raws), rows byte aligned.
Lsb,
/// Each sample stored in 16 bits in file byte order, regardless of `bits`.
Word16,
/// MSB-first bit stream inside 32-bit words stored in file byte order ([`unpack_words32_msb`]); rows start on a
/// word boundary.
Words32Msb,
}
pub(crate) enum ChunkPx {
U16(Vec<u16>),
F32(Vec<f32>),
}
/// The checks [`read_image`] makes before decoding anything (sample format, size limits, data
/// present); returns the number of samples.
pub fn check_image(data: &[u8], info: &ImageInfo) -> Result<usize> {
let (w, h) = (info.width as usize, info.height as usize);
let cpp = info.samples_per_pixel as usize;
let total = w.checked_mul(h).and_then(|v| v.checked_mul(cpp)).ok_or(RawError::Limit("image too large"))?;
if total > MAX_SAMPLES || total == 0 {
return Err(RawError::Limit("image too large"));
}
let bits = info.bits() as u32;
let float = info.sample_format == 3;
if float && !matches!(bits, 16 | 24 | 32) {
return Err(RawError::Unsupported(format!("{bits}-bit floating point samples")));
}
if !float && !(1..=16).contains(&bits) {
return Err(RawError::Unsupported(format!("{bits}-bit integer samples")));
}
let chunks = info.chunks(data.len() as u64);
if chunks.is_empty() {
return Err(RawError::Corrupt("no image data chunks".into()));
}
// every visible sample needs a chunk: a short offsets table would leave zero-filled (black) regions
let (across, down) = info.grid();
let planes = if info.planar == 2 { cpp } else { 1 };
let expected = (across as usize).saturating_mul(down as usize).saturating_mul(planes);
// the offsets table says how many chunks the image declares: craft-tiff builds at most one
// descriptor per byte of file (craft-libs#827), so `chunks` may be shorter on a grid of tiles
// sharing one payload, and the bytes behind it are what the bounds below count.
if info.offsets.len() < expected {
return Err(RawError::Corrupt(format!("{} image data chunks, expected {expected}", info.offsets.len())));
}
// Tile sizes don't depend on the image size, and every tile is decoded at its nominal size and held until the copy:
// a grid of tiles no larger than the image covers less than twice its width and height, so more than four times
// its samples (or one tile of more than TILE_SAMPLES_FLOOR on a tiny image) is no picture (issue #2554).
let ccpp = if info.planar == 2 { 1 } else { cpp as u64 };
let nominal = chunks.iter().fold(0u64, |sum, c| sum.saturating_add(u64::from(c.width).saturating_mul(u64::from(c.height)).saturating_mul(ccpp)));
if nominal > (total as u64).saturating_mul(4).max(TILE_SAMPLES_FLOOR) {
return Err(RawError::Limit("image data chunks far larger than the image"));
}
// Plausibility bound before allocating: no supported coding stores more than ~2000 samples per byte
// (Deflate of constant data is the extreme), so tiny files cannot trigger huge allocations. The
// bytes are counted once however many chunks point at them: a grid of tiles sharing one small
// payload holds that payload's samples, not the grid's.
let mut spans: Vec<(u64, u64)> =
chunks.iter().filter_map(|c| Some((c.offset, c.offset.checked_add(chunk_bytes(data, c)?.len() as u64)?))).collect();
spans.sort_unstable();
let (mut available, mut end) = (0u64, 0u64);
for (a, b) in spans {
let a = a.max(end);
if b > a {
available = available.saturating_add(b - a);
end = b;
}
}
if available.saturating_mul(2048) < total as u64 {
return Err(RawError::Corrupt(format!("{available} bytes of image data cannot hold {total} samples")));
}
Ok(total)
}
/// Read the samples of `info` in `mode`: [`Mode::Header`] only checks them ([`check_image`]) and
/// returns no samples (floating-point data as an empty `F32`).
pub(crate) fn read_image_in(mode: crate::Mode, data: &[u8], info: &ImageInfo, order: ByteOrder, packing: Packing) -> Result<RawData> {
match mode {
crate::Mode::Full => read_image(data, info, order, packing),
crate::Mode::Header => {
check_image(data, info)?;
// a lossless-JPEG layout the decoder rejects (subsampled components, e.g. Sony's
// lossless M/S sizes) must fail here too, as the full decode will; likewise a JPEG XL
// chunk whose headers don't match the IFD
let first = info.chunks(data.len() as u64).first().copied();
if let Some(c) = first
&& let Some(src) = chunk_bytes(data, &c)
{
match info.compression {
7 => {
ljpeg::frame_info(src)?;
}
comp::JPEG_XL => {
let planar = info.planar == 2 && info.samples_per_pixel > 1;
let cpp = if planar { 1 } else { info.samples_per_pixel as usize };
let (cw, ch, vw, vh) = chunk_dims(info, &c);
jxl_chunk_check(src, cw, ch, vw, vh, cpp, info.bits() as u32, info.sample_format == 3)?;
}
_ => {}
}
}
Ok(if info.sample_format == 3 { RawData::F32(Vec::new()) } else { RawData::U16(Vec::new()) })
}
}
}
/// The nominal samples of all chunks [`check_image`] allows whatever the image size: one 2048 × 2048 tile.
const TILE_SAMPLES_FLOOR: u64 = 1 << 22;
/// Decode all chunks of `info` into one buffer of `width × height × cpp` samples.
pub fn read_image(data: &[u8], info: &ImageInfo, order: ByteOrder, packing: Packing) -> Result<RawData> {
let (w, h) = (info.width as usize, info.height as usize);
let total = check_image(data, info)?;
let cpp = info.samples_per_pixel as usize;
let bits = info.bits() as u32;
let float = info.sample_format == 3;
let chunks = info.chunks(data.len() as u64);
let planar = info.planar == 2 && cpp > 1;
let ccpp = if planar { 1 } else { cpp };
// The chunks are decoded and copied into the output in groups whose combined nominal size stays within
// a few times the output buffer's: everything decoded at once would retain the whole image twice, and
// a hostile tile table's chosen padding could stretch that much further (issue #1517). One group
// still decodes in parallel; the grid order groups make, the copies stay disjoint.
// The tile grid decides how much is decoded, whatever the file's bytes: the nominal sizes of all
// the chunks stay within a few times the image (edge tiles pad it) before any is decoded.
let nominal = chunks.iter().fold(0usize, |sum, c| sum.saturating_add(chunk_samples(c, ccpp)));
if nominal > total.saturating_mul(4).saturating_add(1 << 24) {
return Err(RawError::Corrupt("the tile grid is much larger than the image".into()));
}
let group_samples = (total / 4).max(1 << 20);
let mut out_u16 = if float { Vec::new() } else { vec![0u16; total] };
let mut out_f32 = if float { vec![0f32; total] } else { Vec::new() };
let mut decode_from = 0usize;
while decode_from < chunks.len() {
let mut to = decode_from;
let mut taken = 0usize;
for (k, c) in chunks[decode_from..].iter().enumerate() {
let n = chunk_samples(c, ccpp);
if taken > 0 && taken.saturating_add(n) > group_samples {
break;
}
taken = taken.saturating_add(n);
to = decode_from + k + 1;
}
let decoded: Vec<Result<(Chunk, ChunkPx)>> =
chunks[decode_from..to].par_iter().map(|c| decode_chunk(data, info, c, order, packing, ccpp, bits, float).map(|p| (*c, p))).collect();
for r in decoded {
// a chunk that cannot be decoded is not a partial image: the file stays preview-only
let (c, px) = r?;
let (cw, ch) = (c.width as usize, c.height as usize);
let (x0, y0) = (c.x as usize, c.y as usize);
if x0 >= w || y0 >= h {
continue;
}
let copy_w = cw.min(w - x0);
let copy_h = ch.min(h - y0);
for y in 0..copy_h {
for x in 0..copy_w {
for s in 0..ccpp {
let src = (y * cw + x) * ccpp + s;
let dst_s = if planar { c.plane as usize } else { s };
if dst_s >= cpp {
continue;
}
let dst = ((y0 + y) * w + x0 + x) * cpp + dst_s;
match &px {
ChunkPx::U16(v) => {
if let (Some(o), Some(&s)) = (out_u16.get_mut(dst), v.get(src)) {
*o = s;
}
}
ChunkPx::F32(v) => {
if let (Some(o), Some(&s)) = (out_f32.get_mut(dst), v.get(src)) {
*o = s;
}
}
}
}
}
}
}
decode_from = to;
}
Ok(if float { RawData::F32(out_f32) } else { RawData::U16(out_u16) })
}
/// Bytes that `n` samples take in a row of an uncompressed or inflated chunk, laid out as
/// [`unpack_chunk`] reads them: whole bytes or 16-bit words, or 32-bit words for `Words32Msb`.
fn packed_row_bytes(n: u64, bits: u32, packing: Packing, float: bool) -> u64 {
if float {
return n.saturating_mul(u64::from(bits.div_ceil(8)));
}
let bit_len = n.saturating_mul(u64::from(bits));
match (bits, packing) {
(8, _) => n,
(16, _) | (_, Packing::Word16) => n.saturating_mul(2),
(_, Packing::Msb | Packing::Lsb) => bit_len.div_ceil(8),
(_, Packing::Words32Msb) => bit_len.div_ceil(32).saturating_mul(4),
}
}
/// A chunk's nominal decoded size in samples (per plane, as the decoder builds it).
fn chunk_samples(c: &Chunk, ccpp: usize) -> usize {
(c.width as usize).saturating_mul(c.height as usize).saturating_mul(ccpp)
}
#[allow(clippy::too_many_arguments)]
fn decode_chunk(data: &[u8], info: &ImageInfo, c: &Chunk, order: ByteOrder, packing: Packing, cpp: usize, bits: u32, float: bool) -> Result<ChunkPx> {
let src = chunk_bytes(data, c).ok_or_else(|| RawError::Corrupt("chunk offset past end of file".into()))?;
let (cw, ch, vw, vh) = chunk_dims(info, c);
let n = cw.checked_mul(ch).and_then(|v| v.checked_mul(cpp)).ok_or(RawError::Limit("chunk too large"))?;
if n > MAX_SAMPLES {
return Err(RawError::Limit("chunk too large"));
}
match info.compression {
comp::NONE => {
// uncompressed: missing rows are filled with zeros, but a chunk holding a small fraction of what its
// samples need is no picture: refused before the nominal chunk is allocated (issue #1512)
let need = (n as u64).saturating_mul(u64::from(bits)) / 8;
if (src.len() as u64).saturating_mul(64) < need {
return Err(RawError::Corrupt(format!("an uncompressed chunk of {n} samples has only {} bytes", src.len())));
}
unpack_chunk(src, order, packing, cw, ch, cpp, bits, float, 1)
}
comp::JPEG => {
let f = ljpeg::decode(src, n.saturating_mul(2).max(1 << 16))?;
if f.data.len() < n {
// Some writers encode edge tiles smaller than nominal: accept a frame that covers the rows inside the image.
if f.data.is_empty() || f.data.len() % (cw * cpp) != 0 || f.data.len() / (cw * cpp) < vh {
return Err(RawError::Corrupt(format!("lossless JPEG tile has {} samples, expected {n}", f.data.len())));
}
}
let mut v = f.data;
v.resize(n, 0);
Ok(ChunkPx::U16(v))
}
comp::LOSSY_JPEG => {
// lossy DNG: each chunk is a baseline (DCT) JPEG of 8-bit samples
// a JPEG decoded for a tile may hold no more samples than the tile (a real one is exactly the tile):
// many small tiles pointing at one big JPEG would otherwise each decode all of it
// (the JPEG codes whole MCUs, at most 32 × 32 pixels each, so its size is the tile's rounded up to them)
let mcu = |v: usize| v.div_ceil(32).saturating_mul(32);
let tile_budget = mcu(cw).saturating_mul(mcu(ch)).saturating_mul(if cpp == 1 { 1 } else { 3 }).clamp(1, MAX_JPEG_SAMPLES);
let (px, jw, jh, jc) = lossy_jpeg(src, cpp, tile_budget)?;
// the buffer holds the rows the decoded JPEG covers (the caller zero-fills the tile's
// remainder and reads only rows it fills): a tile-many-larger decoded JPEG does not
// get the nominal tile's full buffer (issue #1517)
let rows = ch.min(jh);
let mut v = vec![0u16; rows.max(1).saturating_mul(cw).saturating_mul(cpp)];
for y in 0..rows {
for x in 0..cw.min(jw) {
for k in 0..cpp {
v[(y * cw + x) * cpp + k] = px[(y * jw + x) * jc + k.min(jc - 1)] as u16;
}
}
}
Ok(ChunkPx::U16(v))
}
comp::ADOBE_DEFLATE | comp::DEFLATE => {
// row bytes in u64: a wrapping `cw · cpp · …` in usize could come out small on 32-bit targets and slip past the gate
let row_bytes = packed_row_bytes(cw as u64 * cpp as u64, bits, packing, float);
// the gate caps at MAX_SAMPLES (≤ 2^30), so the `usize` cast below is lossless on 32-bit targets too
let inflate_len =
crate::checked_pixel_count(row_bytes, ch as u64).ok_or_else(|| RawError::Corrupt("bad TIFF chunk dimensions".into()))?;
// Deflate compresses at most about 1:1032, so a source this far under half of its
// nominal length cannot reconstruct the chunk: refused before the nominal buffer is
// inflated and predicted, which padding-only work would make gigabytes.
// Nor may the nominal chunk be mostly padding outside the image (a tile far larger than the picture):
// its allocation and predictor pass would be spent on samples nobody reads.
if n > vw
.saturating_mul(vh)
.saturating_mul(cpp)
.saturating_mul(MAX_PADDING_FACTOR)
.saturating_add(MAX_WRITER_TILE_SAMPLES.saturating_mul(cpp))
{
return Err(RawError::Limit("deflated chunk is mostly padding outside the image"));
}
if (src.len() as u64).saturating_mul(2048) < inflate_len {
return Err(RawError::Corrupt(format!("a deflated chunk of {inflate_len} bytes is packed into only {} bytes", src.len())));
}
let raw = inflate(src, inflate_len as usize)?;
// The stream has to reach the last row inside the image (edge strips may stop there);
// it is laid out in nominal rows, so shorter is a truncated chunk, not a picture.
let last = packed_row_bytes(vw as u64 * cpp as u64, bits, packing, float);
let visible = row_bytes.saturating_mul(vh.saturating_sub(1) as u64).saturating_add(last);
if (raw.len() as u64) < visible {
return Err(RawError::Corrupt(format!(
"a deflated chunk holds {} bytes, fewer than the {visible} bytes its in-image samples span",
raw.len()
)));
}
unpack_chunk(&raw, order, packing, cw, ch, cpp, bits, float, info.predictor)
}
comp::JPEG_XL => jxl_chunk(src, cw, ch, vw, vh, cpp, bits, float),
other => Err(RawError::Unsupported(format!("TIFF compression {other}"))),
}
}
/// A chunk's nominal size and the part of it inside the image (smaller for edge tiles).
fn chunk_dims(info: &ImageInfo, c: &Chunk) -> (usize, usize, usize, usize) {
let (cw, ch) = (c.width as usize, c.height as usize);
let vw = cw.min(info.width.saturating_sub(c.x) as usize);
let vh = ch.min(info.height.saturating_sub(c.y) as usize);
(cw, ch, vw, vh)
}
#[cfg(feature = "jxl")]
use crate::jxl::{check as jxl_chunk_check, decode as jxl_chunk};
#[cfg(not(feature = "jxl"))]
#[allow(clippy::too_many_arguments)]
fn jxl_chunk(_: &[u8], _: usize, _: usize, _: usize, _: usize, _: usize, _: u32, _: bool) -> Result<ChunkPx> {
Err(RawError::Unsupported("JPEG XL DNG (built without the `jxl` feature)".into()))
}
#[cfg(not(feature = "jxl"))]
#[allow(clippy::too_many_arguments)]
fn jxl_chunk_check(src: &[u8], cw: usize, ch: usize, vw: usize, vh: usize, cpp: usize, bits: u32, float: bool) -> Result<()> {
jxl_chunk(src, cw, ch, vw, vh, cpp, bits, float).map(|_| ())
}
/// How many times its in-image samples a deflated chunk's nominal size may reach (plus a writer tile of slack):
/// edge tiles of real files are mostly inside the image.
const MAX_PADDING_FACTOR: usize = 32;
/// Samples per plane of the largest Deflate tile the DNG writer pads to (2048 × 2048, `dngwrite::MAX_DEFLATE_TILE`),
/// which a small image's one tile is nearly all padding of: such files still decode.
const MAX_WRITER_TILE_SAMPLES: usize = 2048 * 2048;
/// The most samples a tiled JPEG chunk or a white-balance preview may decode to: far more than
/// any real lossy tile or preview carries, and small enough that a JPEG header alone cannot size
/// a multi-gigabyte allocation.
pub(crate) const MAX_JPEG_SAMPLES: usize = 1 << 26;
/// Decode one baseline JPEG chunk to 8-bit samples: (samples, width, height, channels).
pub(crate) fn lossy_jpeg(src: &[u8], cpp: usize, max_samples: usize) -> Result<(Vec<u8>, usize, usize, usize)> {
use zune_core::bytestream::ZCursor;
use zune_core::colorspace::ColorSpace;
use zune_core::options::DecoderOptions;
let cs = if cpp == 1 { ColorSpace::Luma } else { ColorSpace::RGB };
let opts = DecoderOptions::default().set_max_width(1 << 16).set_max_height(1 << 16).set_strict_mode(false).jpeg_set_out_colorspace(cs);
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(src), opts);
// The header is read first: the JPEG's own dimensions, not the enclosing tile's, size every
// allocation `decode` makes, and they may claim billions of pixels.
d.decode_headers().map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?;
let info = d.info().ok_or_else(|| RawError::Corrupt("lossy JPEG tile without a header".into()))?;
let (w, h) = (info.width as usize, info.height as usize);
let c = if cpp == 1 { 1 } else { 3 };
let out = w as u64 * h as u64 * c as u64;
if w == 0 || h == 0 || out > max_samples as u64 {
return Err(RawError::Corrupt(format!("a lossy JPEG of {w} × {h} × {c} would exceed the {max_samples} output samples allowed")));
}
let px = d.decode().map_err(|e| RawError::Corrupt(format!("lossy JPEG tile: {e}")))?;
if px.len() < w * h * c {
return Err(RawError::Corrupt("lossy JPEG tile: short output".into()));
}
Ok((px, w, h, c))
}
#[allow(clippy::too_many_arguments)]
fn unpack_chunk(
src: &[u8],
order: ByteOrder,
packing: Packing,
cw: usize,
ch: usize,
cpp: usize,
bits: u32,
float: bool,
predictor: u16,
) -> Result<ChunkPx> {
let row_n = cw * cpp;
let (factor, fp) = match predictor {
1 => (0, false),
2 => (1, false),
3 => (1, true),
34892 => (2, false),
34893 => (4, false),
34894 => (2, true),
34895 => (4, true),
p => return Err(RawError::Unsupported(format!("predictor {p}"))),
};
if float {
let bp = bits.div_ceil(8) as usize;
let row_bytes = row_n * bp;
let mut out = vec![0f32; row_n * ch];
let mut rowbuf = vec![0u8; row_bytes];
for y in 0..ch {
let s = src.get(y * row_bytes..).unwrap_or(&[]);
let len = s.len().min(row_bytes);
rowbuf[..len].copy_from_slice(&s[..len]);
rowbuf[len..].fill(0);
let big = if fp {
undo_float_predictor(&mut rowbuf, row_n, bp, cpp * factor);
true
} else {
if factor > 0 {
return Err(RawError::Unsupported("integer predictor on float data".into()));
}
order == ByteOrder::Big
};
for (i, o) in out[y * row_n..(y + 1) * row_n].iter_mut().enumerate() {
let b = &rowbuf[i * bp..(i + 1) * bp];
*o = match (bp, big) {
(2, true) => f16_to_f32(u16::from_be_bytes([b[0], b[1]])),
(2, false) => f16_to_f32(u16::from_le_bytes([b[0], b[1]])),
(3, true) => f24_to_f32(u32::from_be_bytes([0, b[0], b[1], b[2]])),
(3, false) => f24_to_f32(u32::from_le_bytes([b[0], b[1], b[2], 0])),
(4, true) => f32::from_be_bytes([b[0], b[1], b[2], b[3]]),
_ => f32::from_le_bytes([b[0], b[1], b[2], b[3]]),
};
}
}
return Ok(ChunkPx::F32(out));
}
if fp {
return Err(RawError::Unsupported("floating-point predictor on integer data".into()));
}
let mut out = vec![0u16; row_n * ch];
let (row_bytes, kind) = match (bits, packing) {
(8, _) => (row_n, 0),
(16, _) | (_, Packing::Word16) => (row_n * 2, 1),
(_, Packing::Msb) => ((row_n * bits as usize).div_ceil(8), 2),
(_, Packing::Lsb) => ((row_n * bits as usize).div_ceil(8), 3),
(_, Packing::Words32Msb) => ((row_n * bits as usize).div_ceil(32) * 4, 4),
};
for y in 0..ch {
let s = src.get(y * row_bytes..).unwrap_or(&[]);
let s = &s[..s.len().min(row_bytes)];
let row = &mut out[y * row_n..(y + 1) * row_n];
match kind {
0 => row.iter_mut().zip(s).for_each(|(o, &b)| *o = b as u16),
1 => read_u16s(s, order, row),
2 => unpack_msb(s, bits, row),
4 => unpack_words32_msb(s, order, bits, row),
_ => unpack_lsb(s, bits, row),
}
if factor > 0 {
if bits == 8 {
for i in cpp * factor..row.len() {
row[i] = (row[i] as u8).wrapping_add(row[i - cpp * factor] as u8) as u16;
}
} else {
undo_diff_u16(row, cpp * factor);
}
}
}
Ok(ChunkPx::U16(out))
}
#[cfg(test)]
mod lossy_tests {
use super::*;
use craft_tiff::image::Layout;
/// 65 536 tiles all pointing at the same 256 bytes: the image's samples can't come from them,
/// and nothing of its size is allocated to find that out.
#[test]
fn tiles_sharing_one_payload_count_its_bytes_once() {
let file = vec![0u8; 8 + 256];
let info = ImageInfo {
width: 4096,
height: 4096,
bits_per_sample: vec![8],
samples_per_pixel: 1,
compression: comp::NONE,
photometric: 34892,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Tiles { tile_width: 16, tile_height: 16 },
offsets: vec![8; 65_536],
byte_counts: vec![256; 65_536],
};
let err = check_image(&file, &info).unwrap_err().to_string();
assert!(err.contains("cannot hold"), "{err}");
}
/// A lossy-DNG-style image: two 16×8 tiles, each a baseline JPEG, the right one cut short
/// by the image edge.
#[test]
fn lossy_jpeg_tiles_decode() {
let (tw, th) = (16usize, 8usize);
let tile = |shade: u8| {
let px: Vec<u8> = (0..tw * th).flat_map(|i| [shade, (i % tw * 15) as u8, 200]).collect();
let mut out = Vec::new();
jpeg_encoder::Encoder::new(&mut out, 100).encode(&px, tw as u16, th as u16, jpeg_encoder::ColorType::Rgb).unwrap();
out
};
let (a, b) = (tile(40), tile(220));
let mut file = vec![0u8; 8];
let oa = file.len() as u64;
file.extend_from_slice(&a);
let ob = file.len() as u64;
file.extend_from_slice(&b);
let info = ImageInfo {
width: 24,
height: 8,
bits_per_sample: vec![8, 8, 8],
samples_per_pixel: 3,
compression: comp::LOSSY_JPEG,
photometric: 34892,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Tiles { tile_width: tw as u32, tile_height: th as u32 },
offsets: vec![oa, ob],
byte_counts: vec![a.len() as u64, b.len() as u64],
};
let RawData::U16(v) = read_image(&file, &info, ByteOrder::Little, Packing::Msb).unwrap() else { panic!("integer samples") };
assert_eq!(v.len(), 24 * 8 * 3);
let px = |x: usize, y: usize| &v[(y * 24 + x) * 3..(y * 24 + x) * 3 + 3];
assert!((px(2, 3)[0] as i32 - 40).abs() <= 3 && (px(2, 3)[2] as i32 - 200).abs() <= 3, "{:?}", px(2, 3));
assert!((px(20, 3)[0] as i32 - 220).abs() <= 3, "second tile: {:?}", px(20, 3));
assert!((px(10, 5)[1] as i32 - 150).abs() <= 6, "green ramp: {:?}", px(10, 5));
}
/// A small tile may not decode a JPEG much larger than itself (a table of tiny tiles all pointing at one big
/// JPEG would decode it once per tile); a JPEG that fills the tile's whole 32 × 32 MCU block still decodes.
#[test]
fn a_lossy_tile_may_not_decode_a_much_larger_jpeg() {
let encode = |w: usize, h: usize| {
let mut out = Vec::new();
jpeg_encoder::Encoder::new(&mut out, 90).encode(&vec![128u8; w * h * 3], w as u16, h as u16, jpeg_encoder::ColorType::Rgb).unwrap();
out
};
let image = |jpeg: &[u8]| {
let mut file = vec![0u8; 8];
file.extend_from_slice(jpeg);
let info = ImageInfo {
width: 4,
height: 4,
bits_per_sample: vec![8, 8, 8],
samples_per_pixel: 3,
compression: comp::LOSSY_JPEG,
photometric: 34892,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Tiles { tile_width: 16, tile_height: 16 },
offsets: vec![8],
byte_counts: vec![jpeg.len() as u64],
};
read_image(&file, &info, ByteOrder::Little, Packing::Msb)
};
assert!(image(&encode(32, 32)).is_ok());
assert!(matches!(image(&encode(256, 256)), Err(RawError::Corrupt(_))));
}
fn strip_info(compression: u16, offsets: Vec<u64>, byte_counts: Vec<u64>) -> ImageInfo {
ImageInfo {
width: 4,
height: 4,
bits_per_sample: vec![8],
samples_per_pixel: 1,
compression,
photometric: 1,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Strips { rows_per_strip: 2 },
offsets,
byte_counts,
}
}
/// A missing strip or a strip that fails to decode is an error, not a black band in a "successful" image.
#[test]
fn missing_or_failed_chunks_are_errors() {
let file = vec![9u8; 8 + 8];
// both strips present
let ok = strip_info(comp::NONE, vec![0, 8], vec![8, 8]);
assert!(read_image(&file, &ok, ByteOrder::Little, Packing::Msb).is_ok());
// the second strip has no offset
let missing = strip_info(comp::NONE, vec![0], vec![8]);
assert!(read_image(&file, &missing, ByteOrder::Little, Packing::Msb).is_err());
// the header-only read rejects it too, as the full decode will
assert!(read_image_in(crate::Mode::Header, &file, &missing, ByteOrder::Little, Packing::Msb).is_err());
// the second strip starts past the end of the file
let past_end = strip_info(comp::NONE, vec![0, 100], vec![8, 8]);
assert!(read_image(&file, &past_end, ByteOrder::Little, Packing::Msb).is_err());
}
/// A small image whose uncompressed tile claims to be enormous (2048 x 2048 nominal, a few bytes of data) is
/// refused before that tile is allocated (issue #1512); an edge tile stored at its full nominal size decodes. (A
/// tile larger still is refused by `check_image` before any decode: `tiles_far_larger_than_the_image_are_refused`.)
#[test]
fn a_huge_nominal_uncompressed_tile_with_little_data_is_refused() {
let info = |tile: u32, bytes: u64| ImageInfo {
width: 8,
height: 8,
bits_per_sample: vec![16],
samples_per_pixel: 1,
compression: comp::NONE,
photometric: 32803,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Tiles { tile_width: tile, tile_height: tile },
offsets: vec![0],
byte_counts: vec![bytes],
};
let small = vec![1u8; 2 * 16 * 16];
assert!(read_image(&small, &info(16, small.len() as u64), ByteOrder::Little, Packing::Msb).is_ok());
let data = vec![1u8; 4096];
assert!(matches!(read_image(&data, &info(2048, data.len() as u64), ByteOrder::Little, Packing::Msb), Err(RawError::Corrupt(_))));
}
/// A 16 × 16 image whose lossless-JPEG tile claims to be 16384 × 16384 (coded only as tall as the image, so the
/// file is small) is refused before the tile is allocated, by the header check too (issue #2554); a 256 × 256
/// tile on the same image, as a writer with a fixed tile size stores it, still decodes.
#[test]
fn tiles_far_larger_than_the_image_are_refused() {
let read = |tile: u32, mode: crate::Mode| {
let t = ljpeg::encode(&vec![300u16; tile as usize * 16], tile as usize, 16, 1, 12, 1, 0);
let info = ImageInfo {
width: 16,
height: 16,
bits_per_sample: vec![12],
samples_per_pixel: 1,
compression: comp::JPEG,
photometric: 32803,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Tiles { tile_width: tile, tile_height: tile },
offsets: vec![0],
byte_counts: vec![t.len() as u64],
};
read_image_in(mode, &t, &info, ByteOrder::Little, Packing::Msb)
};
assert_eq!(read(256, crate::Mode::Full), Ok(RawData::U16(vec![300; 16 * 16])));
for mode in [crate::Mode::Header, crate::Mode::Full] {
assert!(matches!(read(16384, mode), Err(RawError::Limit(_))));
}
}
/// A lossless-JPEG tile may be coded only as tall as the part inside the image, never shorter.
#[test]
fn short_lossless_jpeg_tiles_are_errors() {
let tile = |rows: usize| ljpeg::encode(&vec![300u16; 8 * rows], 8, rows, 1, 12, 1, 0);
let decode = |height: u32, rows: usize| {
let t = tile(rows);
let info = ImageInfo {
width: 8,
height,
bits_per_sample: vec![12],
samples_per_pixel: 1,
compression: comp::JPEG,
photometric: 32803,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Tiles { tile_width: 8, tile_height: 8 },
offsets: vec![0],
byte_counts: vec![t.len() as u64],
};
read_image(&t, &info, ByteOrder::Little, Packing::Msb)
};
// an edge tile coded at its in-image height, and a full tile
assert_eq!(decode(6, 6), Ok(RawData::U16(vec![300; 8 * 6])));
assert_eq!(decode(8, 8), Ok(RawData::U16(vec![300; 8 * 8])));
// half of the visible rows are missing
assert!(decode(8, 4).is_err());
}
/// A lossy JPEG whose header alone claims more samples than any real tile or preview (here
/// 40000 × 40000 × 3) is refused from the header, before the decoder allocates its output
/// from the JPEG's own dimensions.
#[test]
fn an_oversized_lossy_jpeg_header_is_refused_before_decoding() {
// A real 8 × 8 baseline JPEG, whose frame header then claims other dimensions: the decoder
// parses the header, and the size check is what refuses it.
let px = vec![128u8; 8 * 8 * 3];
let mut j = Vec::new();
jpeg_encoder::Encoder::new(&mut j, 90).encode(&px, 8, 8, jpeg_encoder::ColorType::Rgb).unwrap();
// SOF0: marker, length, precision, then the height and the width
let sof = j.windows(2).position(|w| w == [0xff, 0xc0]).expect("a baseline frame header");
let claim = |j: &mut Vec<u8>, size: u16| {
j[sof + 5..sof + 7].copy_from_slice(&size.to_be_bytes());
j[sof + 7..sof + 9].copy_from_slice(&size.to_be_bytes());
};
claim(&mut j, 40_000);
let RawError::Corrupt(refused) = lossy_jpeg(&j, 3, MAX_JPEG_SAMPLES).unwrap_err() else { panic!("a corrupt-data error") };
assert!(refused.contains("would exceed"), "{refused}");
// a header inside the budget passes the size check (and then fails to decode only for lack of data)
claim(&mut j, 1024);
match lossy_jpeg(&j, 3, MAX_JPEG_SAMPLES) {
Ok(_) => {}
Err(RawError::Corrupt(m)) => assert!(!m.contains("would exceed"), "the smaller header was refused for its size: {m}"),
Err(other) => panic!("unexpected error: {other:?}"),
}
}
/// A lossy tile whose JPEG decodes far less than the nominal tile is fine: the rows the JPEG
/// covers hold its pixels, the rest of the output stays zero (and the tile's intermediate buffer
/// is sized by the JPEG, not by the nominal tile).
#[test]
fn a_small_lossy_jpeg_in_a_large_nominal_tile_decodes_with_zeros_below() {
let px: Vec<u8> = (0..8 * 8).flat_map(|_| [30u8, 90, 150]).collect();
let mut j = Vec::new();
jpeg_encoder::Encoder::new(&mut j, 100).encode(&px, 8, 8, jpeg_encoder::ColorType::Rgb).unwrap();
let info = ImageInfo {
width: 16,
height: 16,
bits_per_sample: vec![8, 8, 8],
samples_per_pixel: 3,
compression: comp::LOSSY_JPEG,
photometric: 34892,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Tiles { tile_width: 16, tile_height: 16 },
offsets: vec![0],
byte_counts: vec![j.len() as u64],
};
let RawData::U16(v) = read_image(&j, &info, ByteOrder::Little, Packing::Msb).unwrap() else { panic!("integer samples") };
assert_eq!(v.len(), 16 * 16 * 3, "the output is the full nominal image");
let px = |x: usize, y: usize| &v[(y * 16 + x) * 3..(y * 16 + x) * 3 + 3];
assert!((px(3, 3)[0] as i32 - 30).abs() <= 3 && (px(3, 3)[2] as i32 - 150).abs() <= 3, "covered rows: {:?}", px(3, 3));
assert!(px(3, 12).iter().all(|&s| s == 0), "rows below the JPEG stay zero: {:?}", px(3, 12));
}
/// A deflated tile is refused when its packed bytes are too few for deflate to have produced
/// the nominal chunk, or when the stream stops short of the rows inside the image; a fully
/// covered flat tile still decodes.
#[test]
fn a_short_or_undercovering_deflated_tile_is_refused() {
let info = |byte_counts: u64| ImageInfo {
width: 512,
height: 512,
bits_per_sample: vec![16],
samples_per_pixel: 1,
compression: comp::ADOBE_DEFLATE,
photometric: 32803,
planar: 1,
predictor: 1,
sample_format: 1,
new_subfile_type: 0,
layout: Layout::Tiles { tile_width: 512, tile_height: 512 },
offsets: vec![0],
byte_counts: vec![byte_counts],
};
// a complete flat tile: 512 KiB of zeros compresses to a few hundred bytes (well within
// deflate's packing bound) and inflates to every nominal byte the tile claims
let zlib = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 512 * 512 * 2], 6);
assert_eq!(read_image(&zlib, &info(zlib.len() as u64), ByteOrder::Little, Packing::Msb), Ok(RawData::U16(vec![0; 512 * 512])));
// the same 1 KiB packed, but the stream claims a whole tile: a few hundred bytes cannot
// reconstruct 512 KiB from a decoder that compresses no further than about 1:1032
let zlib = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 1024], 6);
assert!(matches!(read_image(&zlib, &info(512 * 512 * 2), ByteOrder::Little, Packing::Msb), Err(RawError::Corrupt(_))), "{zlib:?}");
// 500 KiB of zeros compress to a stream within the packing bound and inflating to more
// bytes than the in-image samples span, but 24 KiB short of the whole nominal tile:
// refused as truncated rather than filled with the predictor's padding
let zlib = miniz_oxide::deflate::compress_to_vec_zlib(&vec![0u8; 500 * 1000], 6);
assert!(matches!(read_image(&zlib, &info(zlib.len() as u64), ByteOrder::Little, Packing::Msb), Err(RawError::Corrupt(_))));
}
}
-223
View File
@@ -1,223 +0,0 @@
//! Sample unpacking: bit packing, byte orders, 16/24/32-bit floats, Deflate and TIFF / DNG predictors.
//!
//! Sources: TIFF 6.0 §14 (Differencing Predictor), Adobe Photoshop TIFF Technical Note 3 (floating-point
//! predictor), DNG 1.7 (predictors 34892–34895, bit packing, 16/24-bit floats), RFC 1950/1951 (zlib/deflate).
use crate::{RawError, Result};
use craft_tiff::ByteOrder;
/// Unpack `out.len()` MSB-first packed samples of `bits` (1..=16) from `src` (TIFF bit order).
pub fn unpack_msb(src: &[u8], bits: u32, out: &mut [u16]) {
debug_assert!((1..=16).contains(&bits));
let mut acc: u64 = 0;
let mut nacc: u32 = 0;
let mut it = src.iter();
let mask = (1u64 << bits) - 1;
for o in out.iter_mut() {
while nacc < bits {
acc = (acc << 8) | *it.next().unwrap_or(&0) as u64;
nacc += 8;
}
*o = ((acc >> (nacc - bits)) & mask) as u16;
nacc -= bits;
}
}
/// Unpack LSB-first packed samples (bits taken from the low end of little-endian words).
pub fn unpack_lsb(src: &[u8], bits: u32, out: &mut [u16]) {
let mut acc: u64 = 0;
let mut nacc: u32 = 0;
let mut it = src.iter();
let mask = (1u64 << bits) - 1;
for o in out.iter_mut() {
while nacc < bits {
acc |= (*it.next().unwrap_or(&0) as u64) << nacc;
nacc += 8;
}
*o = (acc & mask) as u16;
acc >>= bits;
nacc -= bits;
}
}
/// Unpack MSB-first packed samples of `bits` from a stream of 32-bit words stored in `order` (a word is read as a
/// number first, then its bits are taken from the top): the layout of some cameras' uncompressed 12- and 14-bit
/// data, which is not the byte-wise MSB stream of [`unpack_msb`] unless `order` is big-endian. A short last word
/// is padded with zeros.
pub fn unpack_words32_msb(src: &[u8], order: ByteOrder, bits: u32, out: &mut [u16]) {
let words = src.chunks(4).flat_map(|c| {
let mut w = [0u8; 4];
w[..c.len()].copy_from_slice(c);
order.u32(w).to_be_bytes()
});
unpack_msb(&words.collect::<Vec<u8>>(), bits, out);
}
pub fn read_u16s(src: &[u8], order: ByteOrder, out: &mut [u16]) {
for (o, c) in out.iter_mut().zip(src.as_chunks::<2>().0) {
*o = order.u16([c[0], c[1]]);
}
}
/// IEEE 754 half → f32.
pub fn f16_to_f32(h: u16) -> f32 {
let sign = ((h >> 15) as u32) << 31;
let exp = ((h >> 10) & 0x1f) as u32;
let man = (h & 0x3ff) as u32;
let bits = if exp == 0 {
if man == 0 {
sign
} else {
// subnormal: normalise
let mut e = 127 - 15 + 1;
let mut m = man;
while m & 0x400 == 0 {
m <<= 1;
e -= 1;
}
sign | (e << 23) | ((m & 0x3ff) << 13)
}
} else if exp == 31 {
sign | 0x7f80_0000 | (man << 13)
} else {
sign | ((exp + 127 - 15) << 23) | (man << 13)
};
f32::from_bits(bits)
}
/// DNG 24-bit float (1 sign, 7 exponent bias 63, 16 mantissa) → f32.
pub fn f24_to_f32(v: u32) -> f32 {
let sign = (v >> 23) & 1;
let exp = (v >> 16) & 0x7f;
let man = v & 0xffff;
let bits = if exp == 0 && man == 0 {
sign << 31
} else if exp == 0x7f {
(sign << 31) | 0x7f80_0000 | (man << 7)
} else if exp == 0 {
// denormal: value = man * 2^(1-63-16)
let v = man as f32 * 2f32.powi(1 - 63 - 16);
return if sign == 1 { -v } else { v };
} else {
(sign << 31) | ((exp + 127 - 63) << 23) | (man << 7)
};
f32::from_bits(bits)
}
/// Inflate a zlib stream, refusing to produce more than `limit` bytes.
pub fn inflate(src: &[u8], limit: usize) -> Result<Vec<u8>> {
miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(src, limit).map_err(|e| RawError::Corrupt(format!("deflate: {e:?}")))
}
/// Undo horizontal differencing on one row of integer samples with a sample `stride` (cpp × factor).
pub fn undo_diff_u16(row: &mut [u16], stride: usize) {
for i in stride..row.len() {
row[i] = row[i].wrapping_add(row[i - stride]);
}
}
pub fn undo_diff_u8(row: &mut [u8], stride: usize) {
for i in stride..row.len() {
row[i] = row[i].wrapping_add(row[i - stride]);
}
}
/// Undo the floating-point predictor on one row: `row` holds `n` samples of `bytes_per` bytes, byte-differenced
/// with stride `stride` samples, then stored as byte planes (most significant first). Returns the samples as
/// big-endian byte groups in place.
pub fn undo_float_predictor(row: &mut [u8], n: usize, bytes_per: usize, stride: usize) {
undo_diff_u8(row, stride);
let tmp = row.to_vec();
for i in 0..n {
for b in 0..bytes_per {
if let (Some(dst), Some(&s)) = (row.get_mut(i * bytes_per + b), tmp.get(b * n + i)) {
*dst = s;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn words32_are_read_as_numbers_then_msb_first() {
// eight 12-bit samples occupy 96 bits = three 32-bit words, filled from the top
let samples: [u16; 8] = [0x123, 0x456, 0x789, 0xabc, 0xdef, 0x012, 0x345, 0x678];
let stream = samples.iter().fold(0u128, |acc, &v| (acc << 12) | v as u128);
let words = [(stream >> 64) as u32, (stream >> 32) as u32, stream as u32];
let le: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
let be: Vec<u8> = words.iter().flat_map(|w| w.to_be_bytes()).collect();
let mut o = [0u16; 8];
unpack_words32_msb(&le, ByteOrder::Little, 12, &mut o);
assert_eq!(o, samples);
o = [0; 8];
unpack_words32_msb(&be, ByteOrder::Big, 12, &mut o);
assert_eq!(o, samples);
// read as a plain byte stream the little-endian words give different samples
o = [0; 8];
unpack_msb(&le, 12, &mut o);
assert_ne!(o, samples);
// a short last word is zero padded
let mut o = [9u16; 2];
unpack_words32_msb(&[0x34, 0x12], ByteOrder::Little, 12, &mut o);
assert_eq!(o, [0x000, 0x012]); // the word 0x00001234, top bits first
}
#[test]
fn packing() {
// 12-bit MSB: 0xABC, 0xDEF -> AB CD EF
let mut o = [0u16; 2];
unpack_msb(&[0xab, 0xcd, 0xef], 12, &mut o);
assert_eq!(o, [0xabc, 0xdef]);
unpack_lsb(&[0xbc, 0xfa, 0xde], 12, &mut o);
assert_eq!(o, [0xabc, 0xdef]);
let mut o = [0u16; 3];
unpack_msb(&[0b1010_1100, 0b0100_0000], 3, &mut o);
assert_eq!(o, [0b101, 0b011, 0b000]);
let mut o = [0u16; 2];
read_u16s(&[1, 2, 3, 4], ByteOrder::Big, &mut o);
assert_eq!(o, [0x0102, 0x0304]);
// short source: pads with zeros
let mut o = [9u16; 4];
unpack_msb(&[0xff], 14, &mut o);
assert_eq!(o, [0x3fc0, 0, 0, 0]);
}
#[test]
fn floats() {
assert_eq!(f16_to_f32(0x3c00), 1.0);
assert_eq!(f16_to_f32(0xc000), -2.0);
assert_eq!(f16_to_f32(0x0001), 2f32.powi(-24));
assert!(f16_to_f32(0x7c00).is_infinite());
// 24-bit: 1.0 = exp 63, mantissa 0
assert_eq!(f24_to_f32(63 << 16), 1.0);
assert_eq!(f24_to_f32((1 << 23) | (64 << 16) | 0x8000), -3.0);
assert_eq!(f24_to_f32(0), 0.0);
}
#[test]
fn predictors() {
let mut r = [1u16, 1, 1, 1, 65535, 2];
undo_diff_u16(&mut r, 2);
assert_eq!(r, [1, 1, 2, 2, 1, 4]);
// float predictor: two 32-bit samples 1.0 (3f800000), 2.0 (40000000), stride 1
let planes: [u8; 8] = [0x3f, 0x40, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00];
let mut row = planes;
for i in (1..row.len()).rev() {
row[i] = row[i].wrapping_sub(row[i - 1]);
}
undo_float_predictor(&mut row, 2, 4, 1);
assert_eq!(f32::from_be_bytes([row[0], row[1], row[2], row[3]]), 1.0);
assert_eq!(f32::from_be_bytes([row[4], row[5], row[6], row[7]]), 2.0);
}
#[test]
fn inflate_limit() {
let z = miniz_oxide::deflate::compress_to_vec_zlib(&[7u8; 1000], 6);
assert_eq!(inflate(&z, 1000).unwrap(), vec![7u8; 1000]);
assert!(inflate(&z, 10).is_err());
assert!(inflate(&[1, 2, 3], 10).is_err());
}
}
-379
View File
@@ -1,379 +0,0 @@
//! Vendor raw formats (TIFF-based) and helpers shared by them.
pub mod arw;
pub mod arw6;
mod arw6_curve;
#[cfg(test)]
pub(crate) mod arw6_testenc;
mod arw_lens;
pub(crate) mod arw_lens_rm6;
pub mod cr2;
pub mod cr3;
pub mod crw;
pub mod crx;
pub(crate) mod crx_wavelet;
pub mod erf;
pub(crate) mod hasselblad;
pub mod kodak;
pub mod mef;
pub mod mrw;
pub mod nef;
mod nef_lens;
pub mod nefc;
pub mod orf;
pub mod pef;
pub mod raf;
mod raf_lens;
mod rafc;
pub mod rw2;
mod sr2;
pub mod srw;
use crate::{BlackLevel, Cfa, Rect};
use craft_tiff::Tiff;
use std::ops::Range;
/// Exif `CFAPattern`.
pub(crate) const EXIF_CFA_PATTERN: u16 = 0xa302;
/// The colour-filter layout from the Exif `CFAPattern` tag (`0xa302`: two 16-bit repeat counts, found in either
/// byte order, then one byte per site: 0 = red, 1 = green, 2 = blue), when it describes a 2×2 Bayer cell.
pub(crate) fn cfa_from_exif(tiff: &Tiff) -> Option<Cfa> {
let &[c0, c1, r0, r1, s0, s1, s2, s3] = tiff.exif()?.bytes(EXIF_CFA_PATTERN)? else { return None };
let two = |a: u8, b: u8| matches!((a, b), (2, 0) | (0, 2));
let name = match [s0, s1, s2, s3] {
[0, 1, 1, 2] => "RGGB",
[2, 1, 1, 0] => "BGGR",
[1, 0, 2, 1] => "GRBG",
[1, 2, 0, 1] => "GBRG",
_ => return None,
};
(two(c0, c1) && two(r0, r1)).then(|| Cfa::bayer_static(name))
}
/// Black level per 2×2 CFA position (anchored at the active area origin) from masked sensor columns `cols` over
/// rows `rows`. Falls back to 0 when the region is empty.
pub(crate) fn black_from_columns(data: &[u16], width: usize, cols: Range<usize>, rows: Range<usize>, active: Rect) -> BlackLevel {
let height = data.len() / width.max(1);
let (mut sum, mut n) = ([0f64; 4], [0u64; 4]);
for y in rows.start..rows.end.min(height) {
let py = (y as isize - active.y as isize).rem_euclid(2) as usize;
for x in cols.start..cols.end.min(width) {
let px = (x as isize - active.x as isize).rem_euclid(2) as usize;
sum[py * 2 + px] += data[y * width + x] as f64;
n[py * 2 + px] += 1;
}
}
if n.contains(&0) {
return BlackLevel::uniform(0.0);
}
BlackLevel { repeat_rows: 2, repeat_cols: 2, values: (0..4).map(|i| (sum[i] / n[i] as f64) as f32).collect(), delta_h: vec![], delta_v: vec![] }
}
/// Samples of up to 512 evenly spaced rows of the active area, for [`white_from_data`]: the borders can hold
/// their own saturated runs (0xffff junk on RW2, masked rows at 16383 on some Canon CR2s). The step is odd so both
/// row parities, and with them every CFA site, are read.
pub(crate) fn active_rows(data: &[u16], w: usize, a: Rect) -> Vec<u16> {
let step = (a.height / 512).max(1) | 1;
(a.y..a.y + a.height).step_by(step).filter_map(|y| data.get(y * w + a.x..y * w + a.x + a.width)).flatten().copied().collect()
}
/// White level estimate: the saturation plateau if a noticeable number of samples sit at the maximum value,
/// otherwise the full `bits` range. A few stray samples above the plateau (hot pixels, e.g. on a Canon EOS 70D
/// CR2) don't hide it.
pub(crate) fn white_from_data(data: &[u16], bits: u32) -> f32 {
let full_level = (1u32 << bits.clamp(1, 16)) - 1;
let full = full_level as f32;
let step = (data.len() / 2_000_000).max(1);
// samples above the nominal range are padding / invalid (e.g. 0xFFFF fill), not saturation
let mut hist = vec![0usize; full_level as usize + 1];
for &v in data.iter().step_by(step) {
if let Some(h) = hist.get_mut(v as usize) {
*h += 1;
}
}
let min_plateau = (data.len() / 20_000).max(16);
// the top of the data, skipping up to half a plateau's worth of strays so a real plateau can't be skipped
let strays = min_plateau / 2;
let mut above = 0usize;
let Some(mx) = hist.iter().enumerate().rev().find_map(|(v, &n)| {
above += n * step;
(above > strays).then_some(v as u32)
}) else {
return full;
};
let band = (mx / 256).max(1);
let near = mx.saturating_sub(band);
let below = near.saturating_sub(band);
let count = |from: u32, to: u32| hist.get(from as usize..to as usize).map_or(0, |h| h.iter().sum::<usize>());
// the strays count as saturated too
let top = count(near, full_level + 1);
let under = count(below, near);
// a saturation plateau is a spike: many more samples in the top band than in the band just below it
if mx as f32 > full * 0.5 && top * step >= min_plateau && top >= 4 * under + 4 {
// plateau: use its lower edge so everything at saturation maps to ≥ 1.0
near as f32
} else {
full
}
}
/// Output radii sampled to fit a radial warp.
const DISTORTION_SAMPLES: usize = 64;
/// Least-squares radial warp from a camera's forward distortion map.
///
/// `corrected` maps a source radius to the output radius it lands at; it must rise monotonically up to `t_max`, the
/// output radius of the image corners. Radii use the caller's unit; pass `WarpRectilinear`'s normalisation (distance
/// from the centre to the **farthest** corner = 1) so the result is directly a `WarpRectilinear` plane. The map is
/// scanned at 4096 points up to a source radius of `3 * t_max`: it must reach `t_max` within that range and rise at
/// every scan point (monotonicity is checked only there), otherwise `None`; a NaN at a scan point is rejected the
/// same way, other non-finite values by the fit. The map is inverted by bisection and
/// `source = u·(k0 + k1u² + k2u⁴ + k3u⁶)` is fitted over output radii `u·t_max`, `u` in [0, 1] ([`fit_radial_warp`]):
/// the returned `[k0, k1, k2, k3]` give the source radius in the caller's unit as a function of `u`. `None` too when
/// the worst fit error exceeds `max_fit_error`.
pub(crate) fn warp_from_forward_map(corrected: &dyn Fn(f64) -> f64, t_max: f64, max_fit_error: f64) -> Option<[f64; 4]> {
if !(t_max.is_finite() && t_max > 0.0) {
return None;
}
let mut top = None;
let mut prev = 0.0;
for i in 1..=4096 {
let r = 3.0 * t_max * i as f64 / 4096.0;
let v = corrected(r);
if v.is_nan() || v <= prev {
return None;
}
prev = v;
if v >= t_max {
top = Some(r);
break;
}
}
let top = top?;
let source = |t: f64| {
let (mut lo, mut hi) = (0.0, top);
for _ in 0..60 {
let m = 0.5 * (lo + hi);
if corrected(m) < t { lo = m } else { hi = m }
}
0.5 * (lo + hi)
};
fit_radial_warp(&|u| source(u * t_max), max_fit_error, 1.0)
}
/// Least-squares `source = u·(k0 + k1u² + k2u⁴ + k3u⁶)` through `source_of_u` sampled at `u = i/64`, i = 0..=64
/// (`u` = output radius, `WarpRectilinear` units, so the result is directly a plane's `[k0, k1, k2, k3]`). `None` when
/// a sample is not finite, the normal equations are singular, or the worst fit error at the samples up to the first
/// one at or beyond `gate_until` (the radii the image shows; 1 = all) exceeds `max_fit_error`.
pub(crate) fn fit_radial_warp(source_of_u: &dyn Fn(f64) -> f64, max_fit_error: f64, gate_until: f64) -> Option<[f64; 4]> {
let samples: Vec<(f64, f64)> = (0..=DISTORTION_SAMPLES)
.map(|i| {
let u = i as f64 / DISTORTION_SAMPLES as f64;
(u, source_of_u(u))
})
.collect();
if samples.iter().any(|&(_, v)| !v.is_finite()) {
return None;
}
let basis = |u: f64| {
let u2 = u * u;
[u, u * u2, u * u2 * u2, u * u2 * u2 * u2]
};
let mut a = [[0.0; 4]; 4];
let mut rhs = [0.0; 4];
for &(u, v) in &samples {
let f = basis(u);
for (i, fi) in f.iter().enumerate() {
for (j, fj) in f.iter().enumerate() {
a[i][j] += fi * fj;
}
rhs[i] += fi * v;
}
}
let k = solve4(a, rhs)?;
let fit = |u: f64| basis(u).iter().zip(&k).map(|(f, c)| f * c).sum::<f64>();
// rounded up to a sample, so the band between the last sample inside and `gate_until` itself is checked too;
// capped at 1 (`min` also turns a NaN into 1: every sample is gated)
let n = DISTORTION_SAMPLES as f64;
let gate_until = (gate_until * n).ceil().min(n) / n;
let worst = samples.iter().filter(|&&(u, _)| u <= gate_until).map(|&(u, v)| (fit(u) - v).abs()).fold(0.0, f64::max);
(worst <= max_fit_error).then_some(k)
}
/// Solve the 4 × 4 system `a·x = b` (Gaussian elimination with partial pivoting); `None` when singular or not finite.
fn solve4(mut a: [[f64; 4]; 4], mut b: [f64; 4]) -> Option<[f64; 4]> {
for c in 0..4 {
let p = (c..4).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?;
if a[p][c].is_nan() || a[p][c].abs() <= 1e-300 {
return None;
}
a.swap(c, p);
b.swap(c, p);
for r in c + 1..4 {
let f = a[r][c] / a[c][c];
for k in c..4 {
a[r][k] -= f * a[c][k];
}
b[r] -= f * b[c];
}
}
let mut x = [0.0; 4];
for c in (0..4).rev() {
let s: f64 = (c + 1..4).map(|k| a[c][k] * x[k]).sum();
x[c] = (b[c] - s) / a[c][c];
}
x.iter().all(|v| v.is_finite()).then_some(x)
}
/// Test helper: make the single-strip `StripByteCounts` entry (LONG, count 1) that holds `len` declare `declared`
/// bytes instead, as a file cut short or a hostile header does.
#[cfg(test)]
pub(crate) fn declare_strip_len(file: &mut [u8], len: u32, declared: u32) {
let big = file.starts_with(b"MM");
let entry = |v: u32| -> Vec<u8> {
if big {
[&279u16.to_be_bytes()[..], &4u16.to_be_bytes(), &1u32.to_be_bytes(), &v.to_be_bytes()].concat()
} else {
[&279u16.to_le_bytes()[..], &4u16.to_le_bytes(), &1u32.to_le_bytes(), &v.to_le_bytes()].concat()
}
};
let (old, new) = (entry(len), entry(declared));
let at: Vec<usize> = file.windows(old.len()).enumerate().filter(|(_, w)| *w == old.as_slice()).map(|(i, _)| i).collect();
assert_eq!(at.len(), 1, "one StripByteCounts entry of {len} bytes");
file[at[0]..at[0] + new.len()].copy_from_slice(&new);
}
#[cfg(test)]
mod tests {
use super::*;
use craft_tiff::tags as t;
/// `file`, whose image IFD holds one strip, as two strips at the same offset whose StripByteCounts are LONG8 (which
/// classic TIFF readers accept) `[u64::MAX, 1]`: their sum is past `u64::MAX`.
pub(super) fn huge_strip_counts(mut file: Vec<u8>) -> Vec<u8> {
let tiff = Tiff::parse(&file).unwrap();
let o = tiff.order;
let ifd = tiff.all_ifds().into_iter().find(|i| i.contains(t::STRIP_OFFSETS)).unwrap();
let (base, rows, offset) = (ifd.offset as usize, ifd.u32(t::IMAGE_LENGTH).unwrap(), ifd.u32(t::STRIP_OFFSETS).unwrap());
assert!(rows >= 2);
let at = file.len() as u32;
// appended: the two strip offsets (LONG), then the two byte counts (LONG8)
let mut tail = Vec::new();
o.put_u32(&mut tail, offset);
o.put_u32(&mut tail, offset);
o.put_u64(&mut tail, u64::MAX);
o.put_u64(&mut tail, 1);
for i in 0..usize::from(o.read_u16(&file, base).unwrap()) {
let e = base + 2 + 12 * i;
let (ty, count, value) = match o.read_u16(&file, e).unwrap() {
t::STRIP_OFFSETS => (4u16, 2u32, at),
t::ROWS_PER_STRIP => (4, 1, rows.div_ceil(2)),
t::STRIP_BYTE_COUNTS => (16, 2, at + 8),
_ => continue,
};
let mut entry = Vec::new();
o.put_u16(&mut entry, ty);
o.put_u32(&mut entry, count);
o.put_u32(&mut entry, value);
file[e + 2..e + 12].copy_from_slice(&entry);
}
file.extend_from_slice(&tail);
file
}
#[test]
fn black_columns_by_parity() {
// 8 wide, masked columns 0..4, active starts at x=4 (even)
let data: Vec<u16> = (0..8 * 6)
.map(|i| {
let (x, y) = (i % 8, i / 8);
if x < 4 { [100, 101, 102, 103][(y % 2) * 2 + x % 2] } else { 5000 }
})
.collect();
let b = black_from_columns(&data, 8, 0..4, 0..6, Rect::new(4, 0, 4, 6));
assert_eq!(b.values, vec![100.0, 101.0, 102.0, 103.0]);
let b = black_from_columns(&data, 8, 0..4, 0..6, Rect::new(3, 1, 4, 5));
assert_eq!(b.at(0, 0, 0, 1), 103.0);
assert_eq!(black_from_columns(&data, 8, 0..0, 0..6, Rect::new(0, 0, 8, 6)), BlackLevel::uniform(0.0));
}
#[test]
fn white_plateau() {
let mut d: Vec<u16> = (0..100_000).map(|i| (i % 10000) as u16).collect();
assert_eq!(white_from_data(&d, 14), 16383.0);
d.extend(std::iter::repeat_n(15000u16, 1000));
let w = white_from_data(&d, 14);
assert!((14900.0..=15000.0).contains(&w), "{w}");
assert_eq!(white_from_data(&[], 12), 4095.0);
}
/// A Canon EOS 70D CR2 saturates at 13583 but has a handful of samples up to 14426 (out of ~20M): the plateau
/// is still found instead of falling back to 16383 (≈0.3 EV too dark, highlights never seen as clipped).
/// A plateau on the blue sites alone (odd rows) is still found: an even row step would read one row parity only.
#[test]
fn active_rows_reads_both_row_parities() {
let n = 2048;
let d: Vec<u16> = (0..n * n).map(|i| if (i / n) % 2 == 1 && i % 2 == 1 { 15000 } else { (i % 10000) as u16 }).collect();
let w = white_from_data(&active_rows(&d, n, Rect::new(0, 0, n, n)), 14);
assert!((14900.0..=15000.0).contains(&w), "{w}");
}
#[test]
fn white_plateau_with_strays_above() {
let mut d: Vec<u16> = (0..100_000).map(|i| (2048 + i % 10000) as u16).collect();
d.extend(std::iter::repeat_n(13583u16, 5000));
d.extend([13700, 13900, 14100, 14426]);
let w = white_from_data(&d, 14);
assert!((13500.0..=13583.0).contains(&w), "{w}");
}
#[test]
fn warp_from_forward_map_recovers_identity_and_rejects_folds() {
let k = warp_from_forward_map(&|r| r, 1.0, 1e-9).unwrap();
assert!((k[0] - 1.0).abs() < 1e-9 && k[1].abs() < 1e-9 && k[2].abs() < 1e-9 && k[3].abs() < 1e-9);
let barrel = |r: f64| r * (1.0 + 0.05 * r * r); // mild barrel: source < output radius
let t_max = 0.9;
let k = warp_from_forward_map(&barrel, t_max, 1e-3).unwrap();
assert!(k[0] < t_max && k[0] > 0.8 && k[1] < 0.0); // source radius at u = 1 is below t_max
for i in 0..=20 {
let u = i as f64 / 20.0;
let s = u * (k[0] + u * u * (k[1] + u * u * (k[2] + u * u * k[3])));
assert!((barrel(s) - u * t_max).abs() < 1e-5, "u {u}");
}
assert!(warp_from_forward_map(&|r| if r < 0.5 { r } else { 0.5 - (r - 0.5) }, 1.0, 1e-3).is_none()); // fold, never reaches t_max
// a tiny dip (two scan points wide, 1e-4 deep) that still reaches t_max and fits well: only the monotonicity check rejects it
let dip = |r: f64| {
if r < 0.5 {
r
} else if r < 0.5015 {
0.5 - 0.05 * (r - 0.5)
} else {
r - 0.001575
}
};
assert!(warp_from_forward_map(&dip, 1.0, 1e-2).is_none());
assert!(warp_from_forward_map(&|_| f64::NAN, 1.0, 1e-3).is_none());
}
#[test]
fn fit_radial_warp_identity_and_gate() {
let k = fit_radial_warp(&|u| u, 1e-9, 1.0).unwrap();
assert!((k[0] - 1.0).abs() < 1e-9 && k[1].abs() < 1e-9 && k[2].abs() < 1e-9 && k[3].abs() < 1e-9, "{k:?}");
assert!(fit_radial_warp(&|u| if u > 0.5 { f64::NAN } else { u }, 1.0, 1.0).is_none(), "a NaN sample");
assert!(fit_radial_warp(&|u| if u > 0.5 { f64::INFINITY } else { u }, 1.0, 1.0).is_none(), "an infinite sample");
assert!(fit_radial_warp(&|u: f64| u.sqrt(), 1.0, 1.0).is_some());
assert!(fit_radial_warp(&|u: f64| u.sqrt(), 0.0, 1.0).is_none(), "not a polynomial: the gate rejects it");
// a step at u = 1 alone: worst fit error 0.057 over all samples, 0.006 over u <= 0.9 (the fit is the same)
let step = |u: f64| if u > 0.99 { 1.1 } else { u };
assert!(fit_radial_warp(&step, 0.01, 1.0).is_none());
assert_eq!(fit_radial_warp(&step, 0.01, 0.9), fit_radial_warp(&step, 1.0, 1.0), "gated only where shown");
// the first sample at or beyond `gate_until` is gated too (the band up to it is shown): 0.023 up to
// u = 62/64, 0.032 at 63/64
assert!(fit_radial_warp(&step, 0.03, 62.0 / 64.0).is_some(), "a sample exactly at the bound");
assert!(fit_radial_warp(&step, 0.03, 0.98).is_none(), "63/64 is the next sample beyond 0.98");
// capped at 1, and a NaN gates every sample (fails closed)
assert_eq!(fit_radial_warp(&step, 1.0, f64::INFINITY), fit_radial_warp(&step, 1.0, 1.0));
assert!(fit_radial_warp(&step, 0.01, f64::NAN).is_none(), "a NaN gate");
}
}
-1606
View File
File diff suppressed because it is too large. Load diff
-995
View File
@@ -1,995 +0,0 @@
//! Sony ARW6 ("Compressed RAW 2" / HQ, TIFF Compression 32766): container parsing, geometry, colour and decode.
//!
//! Clean-room. The layout comes from SMPTE RDD 34 (Picture_info in word 0) and from Phase 0 black-box
//! inspection of real ILCE-7RM6 files (tile table, group size words, stream headers and index entries), each rule
//! checked by re-serialising parsed tiles byte-for-byte. The format is described in `docs/arw6-compression.md`; section
//! names in italics below refer to it. No other raw decoder's source was consulted.
use crate::llvc::{Bands3, Plane, band_rows, dequant, reconstruct3, vld_decode_line};
use crate::vendor::arw6_curve::curve;
use crate::vendor::pef::Bits;
use crate::{RawError, Result};
use rayon::prelude::*;
use std::ops::Range;
fn corrupt(why: &str) -> RawError {
RawError::Corrupt(format!("ARW6: {why}"))
}
fn unsupported(why: &str) -> RawError {
RawError::Unsupported(format!("ARW6 {why}"))
}
fn u16_be(b: &[u8], at: usize) -> Option<usize> {
let s = b.get(at..at.checked_add(2)?)?;
Some(usize::from(u16::from_be_bytes([*s.first()?, *s.get(1)?])))
}
fn u24_be(b: &[u8], at: usize) -> Option<usize> {
let s = b.get(at..at.checked_add(3)?)?;
Some(s.iter().fold(0usize, |a, &v| (a << 8) | usize::from(v)))
}
fn u32_le(b: &[u8], at: usize) -> Option<usize> {
let s = b.get(at..at.checked_add(4)?)?;
Some(u32::from_le_bytes(s.try_into().ok()?) as usize)
}
/// One tile of the strip: its bytes run from `offset` to the next tile's offset (the last: the strip end).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct TileEntry {
pub offset: usize,
pub x: usize,
pub y: usize,
pub width: usize,
pub height: usize,
}
/// Most tiles a strip may hold (real files have 1 or 4).
const MAX_TILES: usize = 16;
/// Parse the tile table at the start of the strip (file structure, *Container*): `u32` count, `u32` 0, then
/// 24-byte entries `u64` offset (relative to the strip), `u32` x, y, width, height, all little-endian.
pub(crate) fn parse_tile_table(strip: &[u8], width: usize, height: usize) -> Result<Vec<TileEntry>> {
let count = u32_le(strip, 0).ok_or_else(|| corrupt("truncated tile table"))?;
if count == 0 || count > MAX_TILES {
return Err(unsupported("tile count outside 1..=16"));
}
let mut tiles: Vec<TileEntry> = Vec::with_capacity(count);
let mut area = 0usize;
for i in 0..count {
let at = 8 + 24 * i;
let e = strip.get(at..at + 24).ok_or_else(|| corrupt("truncated tile table"))?;
let offset = e.get(..8).and_then(|b| <[u8; 8]>::try_from(b).ok()).map(u64::from_le_bytes).and_then(|o| usize::try_from(o).ok());
let offset = offset.filter(|&o| o < strip.len()).ok_or_else(|| corrupt("tile offset outside the strip"))?;
if tiles.last().is_some_and(|p| offset <= p.offset) {
return Err(corrupt("tile offsets do not increase"));
}
let (x, y, w, h) = (u32_le(e, 8), u32_le(e, 12), u32_le(e, 16), u32_le(e, 20));
let (Some(x), Some(y), Some(w), Some(h)) = (x, y, w, h) else { return Err(corrupt("truncated tile table")) };
// Even geometry; the level-3 band width w / 16 must be whole (w/2 a multiple of 8).
if w == 0 || h == 0 || x % 2 != 0 || y % 2 != 0 || w % 2 != 0 || h % 2 != 0 || (w / 2) % 8 != 0 {
return Err(unsupported("tile geometry"));
}
let fits = x.checked_add(w).is_some_and(|r| r <= width) && y.checked_add(h).is_some_and(|b| b <= height);
if !fits {
return Err(corrupt("tile outside the image"));
}
let a = w.checked_mul(h).filter(|&a| a <= crate::MAX_SAMPLES).ok_or(RawError::Limit("ARW6 tile too large"))?;
area = area.checked_add(a).ok_or(RawError::Limit("ARW6 tiles too large"))?;
tiles.push(TileEntry { offset, x, y, width: w, height: h });
}
for (i, a) in tiles.iter().enumerate() {
for b in tiles.iter().skip(i + 1) {
if a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height {
return Err(corrupt("tiles overlap"));
}
}
}
// In-image, disjoint tiles cover the image exactly when their areas sum to it.
if width.checked_mul(height) != Some(area) {
return Err(corrupt("tiles do not cover the image"));
}
Ok(tiles)
}
/// Tile `i`'s bytes: from its offset to the next tile's offset (the last: the strip end).
pub(crate) fn tile_bytes<'a>(strip: &'a [u8], tiles: &[TileEntry], i: usize) -> Option<&'a [u8]> {
let start = tiles.get(i)?.offset;
let end = match tiles.get(i.checked_add(1)?) {
Some(next) => next.offset,
None => strip.len(),
};
strip.get(start..end)
}
/// One of a tile's 13 streams (positions in 16-byte words from the tile start).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct StreamRef {
pub group: u8,
pub comp: u8,
pub word: usize,
pub size_words: usize,
pub index_words: usize,
pub data_words: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct TileHeader {
pub hs: usize,
pub vs: usize,
/// File order: g0 c0..2, g1 c0..2, g2 c0..2, g3 c0..2, g4 c0.
pub streams: Vec<StreamRef>,
}
/// `n` bits at bit position `pos` (MSB-first) of a tile's word 0.
fn field(w: &[u8], pos: usize, n: usize) -> Option<u32> {
let mut v = 0u32;
for i in pos..pos.checked_add(n)? {
let byte = *w.get(i / 8)?;
v = (v << 1) | u32::from((byte >> (7 - i % 8)) & 1);
}
Some(v)
}
/// Streams per group: g0..g3 one per colour component, g4 the green residual.
const GROUP_STREAMS: [usize; 5] = [3, 3, 3, 3, 1];
/// Parse word 0 (RDD 34 `Picture_info`; every real file has HS = tile width, VS = tile height / 2, BBD 16, NC 3, NW 3,
/// NP 1000000000b), the group size words 3..=7 and each stream's header word (*Container*, Phase 0).
pub(crate) fn parse_tile_header(tile: &[u8], tw: usize, th: usize) -> Result<TileHeader> {
let w0 = tile.get(..16).ok_or_else(|| corrupt("tile shorter than its picture header"))?;
let f = |pos, n| field(w0, pos, n).map(|v| v as usize);
let (hs, vs, bbd, nc, nw, np) = (f(64, 16), f(80, 16), f(102, 6), f(112, 3), f(115, 3), f(118, 10));
let (Some(hs), Some(vs), Some(bbd), Some(nc), Some(nw), Some(np)) = (hs, vs, bbd, nc, nw, np) else {
return Err(corrupt("picture header"));
};
if hs != tw || vs * 2 != th || bbd != 16 || nc != 3 || nw != 3 || np != 0b10_0000_0000 {
return Err(unsupported(&format!("picture header variant (HS {hs}, VS {vs}, BBD {bbd}, NC {nc}, NW {nw}, NP {np:#b})")));
}
let mut streams = Vec::with_capacity(13);
let mut word = 8usize;
for (group, &n) in GROUP_STREAMS.iter().enumerate() {
let table = tile.get((3 + group) * 16..(4 + group) * 16).ok_or_else(|| corrupt("truncated group table"))?;
if usize::from(table.first().copied().unwrap_or(0)) != n {
return Err(unsupported("group stream count"));
}
for comp in 0..n {
let size_words = u24_be(table, 1 + 3 * comp).ok_or_else(|| corrupt("group table"))?;
let end = word.checked_add(size_words).filter(|e| e.checked_mul(16).is_some_and(|b| b <= tile.len()));
let end = end.ok_or_else(|| corrupt("stream outside the tile"))?;
let hdr = tile.get(word * 16..word * 16 + 16).ok_or_else(|| corrupt("stream outside the tile"))?;
let (index_words, data_words) =
(u16_be(hdr, 0).ok_or_else(|| corrupt("stream header"))?, u24_be(hdr, 2).ok_or_else(|| corrupt("stream header"))?);
if index_words.checked_add(data_words).and_then(|s| s.checked_add(1)).is_none_or(|s| s > size_words) {
return Err(corrupt("stream header sizes exceed the stream"));
}
streams.push(StreamRef { group: group as u8, comp: comp as u8, word, size_words, index_words, data_words });
word = end;
}
}
Ok(TileHeader { hs, vs, streams })
}
/// One half-TU of a stream: `len` bytes at byte `start` of the tile, quantiser index per band
/// (g0/g4: the single nibble repeated).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Half {
pub start: usize,
pub len: usize,
pub qi: [u32; 3],
}
fn nibbles(b: &[u8], from: usize, n: usize) -> Option<u32> {
(from..from + n).try_fold(0u32, |a, i| Some((a << 4) | u32::from((*b.get(i / 2)? >> (4 * (1 - i % 2))) & 15)))
}
/// The `2 * ntu` halves of a stream. Index entry per TU (file structure): `A:16 X B:16 X` with A / B the byte
/// lengths of half 0 / 1 and X the QI nibble (g0, g4: 1 nibble) or three nibbles HL, LH, HH (g1..g3); the data area
/// holds each TU's A bytes then B bytes, consecutive TUs contiguous.
pub(crate) fn stream_halves(tile: &[u8], s: &StreamRef, ntu: usize) -> Result<Vec<Half>> {
let nx = if s.group == 0 || s.group == 4 { 1 } else { 3 };
let esz = 4 + nx; // bytes: (16 + 4nx + 16 + 4nx) / 8
let idx_start = s.word.checked_add(1).and_then(|w| w.checked_mul(16)).ok_or_else(|| corrupt("stream position"))?;
let idx_len = s.index_words.checked_mul(16).ok_or_else(|| corrupt("stream position"))?;
if ntu.checked_mul(esz).is_none_or(|n| n > idx_len) {
return Err(corrupt("index table too small for the tile's TUs"));
}
let data_start = idx_start.checked_add(idx_len).ok_or_else(|| corrupt("stream position"))?;
let index = tile.get(idx_start..data_start).ok_or_else(|| corrupt("index table outside the tile"))?;
let data_end = s.data_words.checked_mul(16).and_then(|d| d.checked_add(data_start)).ok_or_else(|| corrupt("stream position"))?;
if data_end > tile.len() {
return Err(corrupt("stream data outside the tile"));
}
let mut halves = Vec::with_capacity(2 * ntu);
let mut pos = data_start;
for k in 0..ntu {
let e = index.get(k * esz..(k + 1) * esz).ok_or_else(|| corrupt("index table"))?;
let bad = || corrupt("index entry");
let (a, x1) = (nibbles(e, 0, 4).ok_or_else(bad)? as usize, nibbles(e, 4, nx).ok_or_else(bad)?);
let (b, x2) = (nibbles(e, 4 + nx, 4).ok_or_else(bad)? as usize, nibbles(e, 8 + nx, nx).ok_or_else(bad)?);
for (len, x) in [(a, x1), (b, x2)] {
let end = pos.checked_add(len).filter(|&e| e <= data_end).ok_or_else(|| corrupt("half outside its stream's data"))?;
let qi = if nx == 1 { [x; 3] } else { [(x >> 8) & 15, (x >> 4) & 15, x & 15] };
halves.push(Half { start: pos, len, qi });
pos = end;
}
}
Ok(halves)
}
// ---- sensor-anchored frame geometry and tile reconstruction (*Frame geometry*) ----
/// Halves of `vs` plane rows are anchored to the sensor: half `n` covers plane rows `8n - 6 + s .. 8n + 1 + s`, so
/// `ceil((vs - 2 - s) / 8) + 1` halves are needed, two per TU (*Container*).
pub(crate) fn tu_count(vs: usize, s: u8) -> usize {
let halves = vs.saturating_sub(2usize.saturating_add(usize::from(s))).div_ceil(8).saturating_add(1);
halves.div_ceil(2)
}
/// Lifting phases of levels 1..=3 for anchor offset `s` (the Phase 0 reference model, local and not in the repo; see `docs/arw6-compression.md`):
/// FF (s = 0) gives [0, 1, 1], the APS-C crop (s = 3) [1, 0, 0].
pub(crate) fn phases(s: u8) -> [u8; 3] {
let s = i32::from(s);
let p1 = s % 2;
let p2 = ((2 + s - p1) / 2) % 2;
let k3 = ((6 + s) % 8 - p1).div_euclid(2);
let p3 = (k3 - p2).div_euclid(2).rem_euclid(2);
[p1 as u8, p2 as u8, p3 as u8]
}
/// Plane rows of half `n`: `8n - 6 + s .. 8n + 2 + s`, clipped to `0..rows` (empty when disjoint).
pub(crate) fn half_rows(n: usize, s: u8, rows: usize) -> Range<usize> {
let base = n.saturating_mul(8).saturating_add(usize::from(s));
base.saturating_sub(6).min(rows)..base.saturating_add(2).min(rows)
}
/// First half's frame rows `lines - 2`, read before the TU count is known from g4's first index entry alone
/// (index table at word `g4.word + 1`, entry 0's `A` = big-endian u16; its bytes start after the index table).
/// Residual lines are decoded while at least 8 bits remain and fewer than 8 lines were read (*Frame geometry*).
pub(crate) fn first_half_shift(tile: &[u8], g4: &StreamRef, width2: usize) -> Result<u8> {
let idx = g4.word.checked_add(1).and_then(|w| w.checked_mul(16)).ok_or_else(|| corrupt("stream position"))?;
let data = g4.index_words.checked_mul(16).and_then(|l| l.checked_add(idx)).ok_or_else(|| corrupt("stream position"))?;
let a = u16_be(tile, idx).ok_or_else(|| corrupt("index table outside the tile"))?;
let bytes = tile.get(data..data.checked_add(a).ok_or_else(|| corrupt("stream position"))?).ok_or_else(|| corrupt("half outside the tile"))?;
let total = bytes.len() * 8;
let mut bits = Bits::new(bytes);
let mut lines = 0usize;
while lines < 8 && total.saturating_sub(bits.consumed_bits()) >= 8 {
vld_decode_line(&mut bits, total, width2)?;
lines += 1;
}
// The stop rule is sound because a residual line costs at least 8 bits: an all-zero line of width w costs
// 1 + ceil(log2(ceil(w/4) + 1)) bits, >= 8 for w >= 253, and real plane widths are >= 2496.
match lines.checked_sub(2) {
Some(s @ 0..=5) => Ok(s as u8),
_ => Err(unsupported("first-half row count outside 2..=7")),
}
}
/// Band rows of one half: plane rows `t` and the rows they land on at each level (`split`).
struct HalfRows {
t: Range<usize>,
l1: Vec<usize>,
h1: Vec<usize>,
l2: Vec<usize>,
h2: Vec<usize>,
l3: Vec<usize>,
h3: Vec<usize>,
}
/// Rows with `t % 2 == p` go to the low band at `(t - p) / 2`, the others to the high band at `(t - (1 - p)) / 2`.
fn split(rows: &[usize], p: u8) -> (Vec<usize>, Vec<usize>) {
let p = usize::from(p);
let (mut lo, mut hi) = (Vec::new(), Vec::new());
for &t in rows {
if t % 2 == p {
lo.push(t.saturating_sub(p) / 2);
} else {
hi.push(t.saturating_sub(1 - p) / 2);
}
}
(lo, hi)
}
fn half_layout(n: usize, s: u8, vs: usize, ph: [u8; 3]) -> HalfRows {
let t = half_rows(n, s, vs);
let rows: Vec<usize> = t.clone().collect();
let (l1, h1) = split(&rows, ph[0]);
let (l2, h2) = split(&l1, ph[1]);
let (l3, h3) = split(&l2, ph[2]);
HalfRows { t, l1, h1, l2, h2, l3, h3 }
}
/// Lines a half holds in group `g`: g0 LL3 rows; g1 HL3 + LH3 + HH3; g2 HL2 + LH2 + HH2; g3 HL1 + LH1 + HH1; g4 residual.
fn line_count(g: u8, r: &HalfRows) -> usize {
match g {
0 => r.l3.len(),
1 => r.l3.len() + 2 * r.h3.len(),
2 => r.l2.len() + 2 * r.h2.len(),
3 => r.l1.len() + 2 * r.h1.len(),
_ => r.t.len(),
}
}
/// Line width of group `g`: level-`l` bands are `(tw / 2) >> l` wide (g0, g1: level 3; g2: 2; g3: 1; g4: the plane).
fn line_width(g: u8, w2: usize) -> usize {
match g {
0 | 1 => w2 >> 3,
2 => w2 >> 2,
3 => w2 >> 1,
_ => w2,
}
}
/// A half with its decoded (still quantised) lines.
type HalfLines = (Half, Vec<Vec<i32>>);
/// Index the stream's halves and VLD-decode exactly the lines each holds; a line running past its half is `Corrupt`.
fn decode_stream(tile: &[u8], st: &StreamRef, ntu: usize, w2: usize, layouts: &[HalfRows]) -> Result<Vec<HalfLines>> {
let halves = stream_halves(tile, st, ntu)?;
let width = line_width(st.group, w2);
// halves are independent bit streams: decode them in parallel
halves
.into_par_iter()
.zip(layouts.par_iter())
.map(|(half, rows)| {
let end = half.start.checked_add(half.len).ok_or_else(|| corrupt("half position"))?;
let bytes = tile.get(half.start..end).ok_or_else(|| corrupt("half outside the tile"))?;
let total = bytes.len() * 8;
let mut bits = Bits::new(bytes);
let mut lines = Vec::with_capacity(line_count(st.group, rows));
let n = line_count(st.group, rows);
for _ in 0..n {
lines.push(vld_decode_line(&mut bits, total, width)?);
if bits.consumed_bits() > total {
return Err(corrupt("line runs past its half"));
}
}
// Phase 0 measurement: in all 3562 halves of the 8 real files the lines end within the half's last
// byte (`len*8 - 8 < consumed <= len*8`); garbage that decodes to fewer bits is corruption.
if n > 0 && bits.consumed_bits() <= total.saturating_sub(8) {
return Err(corrupt("half ends early"));
}
Ok((half, lines))
})
.collect()
}
/// Dequantise `line` into band row `row`.
fn put(plane: &mut Plane, row: usize, line: &[i32], mut f: impl FnMut(i32) -> i32) -> Result<()> {
let start = row.checked_mul(plane.width).ok_or_else(|| corrupt("band row"))?;
let dst = plane.data.get_mut(start..start.saturating_add(plane.width)).ok_or_else(|| corrupt("band row outside its band"))?;
for (d, &v) in dst.iter_mut().zip(line) {
*d = f(v);
}
Ok(())
}
/// Lay a half's lines into (band, rows, QI) in order: the natural clipped assignment of *Frame geometry*.
fn fill(set: [(&mut Plane, &[usize], u32); 3], lines: &[Vec<i32>]) -> Result<()> {
let mut it = lines.iter();
for (plane, rows, qi) in set {
for &r in rows {
put(plane, r, it.next().ok_or_else(|| corrupt("half holds fewer lines than rows"))?, |q| dequant(q, qi))?;
}
}
Ok(())
}
/// One colour component: its ten bands from streams g0..g3 (component `c`), then the 3-level inverse.
fn component(c: usize, streams: &[Vec<HalfLines>], layouts: &[HalfRows], vs: usize, w2: usize, ph: [u8; 3]) -> Result<Plane> {
let (n1l, n1h) = band_rows(vs, ph[0]);
let (n2l, n2h) = band_rows(n1l, ph[1]);
let (n3l, n3h) = band_rows(n2l, ph[2]);
let (w1, w2b, w3) = (w2 >> 1, w2 >> 2, w2 >> 3);
let z = Plane::zeros;
let mut b = Bands3 {
ll3: z(w3, n3l),
hl3: z(w3, n3l),
lh3: z(w3, n3h),
hh3: z(w3, n3h),
hl2: z(w2b, n2l),
lh2: z(w2b, n2h),
hh2: z(w2b, n2h),
hl1: z(w1, n1l),
lh1: z(w1, n1h),
hh1: z(w1, n1h),
};
let grp = |g: usize, n: usize| streams.get(3 * g + c).and_then(|s| s.get(n)).ok_or_else(|| corrupt("missing half"));
for (n, r) in layouts.iter().enumerate() {
let (h0, l0) = grp(0, n)?;
// LL3: the nibble must be 0 (Phase 0: never seen otherwise); lines are DPCM from 2048 for the green mean (c = 0) and
// from 0 for the base-free chroma planes (*Entropy coding and dequantisation*).
if h0.qi[0] != 0 {
return Err(unsupported("LL3 quantiser index"));
}
for (&row, line) in r.l3.iter().zip(l0) {
let mut acc = if c == 0 { 2048i32 } else { 0 };
put(&mut b.ll3, row, line, |d| {
acc = acc.saturating_add(d);
acc
})?;
}
let (h1, l1) = grp(1, n)?;
fill([(&mut b.hl3, &r.l3, h1.qi[0]), (&mut b.lh3, &r.h3, h1.qi[1]), (&mut b.hh3, &r.h3, h1.qi[2])], l1)?;
let (h2, l2) = grp(2, n)?;
fill([(&mut b.hl2, &r.l2, h2.qi[0]), (&mut b.lh2, &r.h2, h2.qi[1]), (&mut b.hh2, &r.h2, h2.qi[2])], l2)?;
let (h3, l3) = grp(3, n)?;
fill([(&mut b.hl1, &r.l1, h3.qi[0]), (&mut b.lh1, &r.h1, h3.qi[1]), (&mut b.hh1, &r.h1, h3.qi[2])], l3)?;
}
reconstruct3(&b, ph)
}
/// A decoded tile: the three wavelet planes (green mean, two chroma) and the green residual, each `tw/2 x th/2`.
pub(crate) struct TilePlanes {
pub m: Plane,
pub c1: Plane,
pub c2: Plane,
pub res: Plane,
}
/// Decode a tile to its planes: header, `s` from g4's first half, TU count, all 13 streams (in parallel), band
/// assembly and the 3-level inverse per component (in parallel).
pub(crate) fn decode_tile_planes(tile: &[u8], tw: usize, th: usize) -> Result<TilePlanes> {
let h = parse_tile_header(tile, tw, th)?;
let (w2, vs) = (tw / 2, h.vs);
if vs == 0 || !tw.is_multiple_of(2) || !w2.is_multiple_of(8) || w2.checked_mul(vs).is_none_or(|a| a > crate::MAX_SAMPLES) {
return Err(unsupported("tile geometry"));
}
let g4 = h.streams.get(12).ok_or_else(|| corrupt("missing residual stream"))?;
let s = first_half_shift(tile, g4, w2)?;
let (ntu, ph) = (tu_count(vs, s), phases(s));
let layouts: Vec<HalfRows> = (0..2 * ntu).map(|n| half_layout(n, s, vs, ph)).collect();
let streams =
h.streams.par_iter().map(|st| decode_stream(tile, st, ntu, w2, &layouts)).collect::<Vec<_>>().into_iter().collect::<Result<Vec<_>>>()?;
let comps =
(0..3).into_par_iter().map(|c| component(c, &streams, &layouts, vs, w2, ph)).collect::<Vec<_>>().into_iter().collect::<Result<Vec<_>>>()?;
// Residual: g4's lines are the half's plane rows, dequantised with the half's nibble.
let mut res = Plane::zeros(w2, vs);
for ((half, lines), r) in streams.get(12).ok_or_else(|| corrupt("missing residual stream"))?.iter().zip(&layouts) {
for (row, line) in r.t.clone().zip(lines) {
put(&mut res, row, line, |q| dequant(q, half.qi[0]))?;
}
}
let mut it = comps.into_iter();
let (Some(m), Some(c1), Some(c2)) = (it.next(), it.next(), it.next()) else { return Err(corrupt("missing component")) };
Ok(TilePlanes { m, c1, c2, res })
}
/// Colour reconstruction (*Colour reconstruction*, checked against Phase 0 oracle output): the planes give a
/// `(2 W2) x (2 H2)` mosaic with R at (0,0), G1 (0,1), G2 (1,0), B (1,1) of every 2x2 cell, each value passed through
/// [`curve`]. G1 comes from the green mean minus a residual average, G2 is predicted from the (unclipped) G1 plus the
/// residual, and R/B are chroma plus the mean of the greens clamped to 0..=4095.
pub(crate) fn colour(p: &TilePlanes) -> Result<Vec<u16>> {
let (w2, h2) = (p.m.width, p.m.height);
let len = w2.checked_mul(h2).ok_or_else(|| corrupt("tile size"))?;
if [&p.c1, &p.c2, &p.res].iter().any(|q| q.width != w2 || q.height != h2 || q.data.len() != len) || p.m.data.len() != len {
return Err(corrupt("plane size mismatch"));
}
let mw = w2.checked_mul(2).ok_or_else(|| corrupt("tile size"))?;
let total = len.checked_mul(4).ok_or_else(|| corrupt("tile size"))?;
// (rows as slices: `at` is 0 past a row's end, as never happens once the sizes above match)
let at = |r: &[i32], x: usize| i64::from(r.get(x).copied().unwrap_or(0));
let mut g1 = vec![0i64; len];
g1.par_chunks_mut(w2.max(1)).enumerate().for_each(|(j, row)| {
let (Some(m), Some(rp), Some(rj)) = (p.m.row(j), p.res.row(j.saturating_sub(1)), p.res.row(j)) else { return };
for (x, g) in row.iter_mut().enumerate() {
let xn = (x + 1).min(w2 - 1);
let r = at(rp, x) + at(rp, xn) + at(rj, x) + at(rj, xn);
*g = at(m, x) - ((r + 4) >> 3);
}
});
let g1_row = |j: usize| g1.get(j * w2..(j + 1) * w2).unwrap_or(&[]);
let g = |r: &[i64], x: usize| r.get(x).copied().unwrap_or(0);
let mut out = vec![0u16; total];
// each plane row gives two mosaic rows
out.par_chunks_mut((2 * mw).max(1)).enumerate().for_each(|(j, rows)| {
let (gj, gn) = (g1_row(j), g1_row((j + 1).min(h2 - 1)));
let (Some(res), Some(c1), Some(c2), Some((top, bottom))) = (p.res.row(j), p.c1.row(j), p.c2.row(j), rows.split_at_mut_checked(mw)) else {
return;
};
for (x, (t, b)) in top.as_chunks_mut::<2>().0.iter_mut().zip(bottom.as_chunks_mut::<2>().0.iter_mut()).enumerate() {
let xp = x.saturating_sub(1);
let g2 = ((g(gj, xp) + g(gj, x) + g(gn, xp) + g(gn, x)) >> 2) + at(res, x);
let mean = (g(gj, x).clamp(0, 4095) + g2.clamp(0, 4095)) >> 1;
let cells = [2 * at(c1, x) + mean, g(gj, x), g2, 2 * at(c2, x) + mean];
for (o, v) in t.iter_mut().chain(b.iter_mut()).zip(cells) {
*o = curve(v.clamp(0, 4095) as i32);
}
}
});
Ok(out)
}
/// One tile to its `tw x th` mosaic in output units.
pub(crate) fn decode_tile(tile: &[u8], tw: usize, th: usize) -> Result<Vec<u16>> {
colour(&decode_tile_planes(tile, tw, th)?)
}
/// Decode a whole ARW6 strip: [`Mode::Header`](crate::Mode) validates the tile table, tile headers and stream
/// tables and returns no samples; `Full` decodes the tiles in parallel into a `width x height` mosaic.
pub(crate) fn decode(strip: &[u8], width: usize, height: usize, mode: crate::Mode) -> Result<Vec<u16>> {
let tiles = parse_tile_table(strip, width, height)?;
let bytes = |i: usize| tile_bytes(strip, &tiles, i).ok_or_else(|| corrupt("tile outside strip"));
if mode == crate::Mode::Header {
for (i, t) in tiles.iter().enumerate() {
let tile = bytes(i)?;
let h = parse_tile_header(tile, t.width, t.height)?;
let g4 = h.streams.get(12).ok_or_else(|| corrupt("missing residual stream"))?;
let s = first_half_shift(tile, g4, t.width / 2)?;
let ntu = tu_count(h.vs, s);
for st in &h.streams {
stream_halves(tile, st, ntu)?;
}
}
return Ok(Vec::new());
}
// a tile that fails is reported before the mosaic is allocated (issue #1512)
let decoded: Vec<Vec<u16>> = tiles.par_iter().enumerate().map(|(i, t)| decode_tile(bytes(i)?, t.width, t.height)).collect::<Result<_>>()?;
let mut out = vec![0u16; width.checked_mul(height).ok_or_else(|| corrupt("image size"))?];
for (t, d) in tiles.iter().zip(decoded) {
for (r, row) in d.chunks_exact(t.width.max(1)).enumerate() {
let start = (t.y + r).checked_mul(width).and_then(|a| a.checked_add(t.x)).ok_or_else(|| corrupt("tile placement"))?;
let dst = start.checked_add(row.len()).and_then(|end| out.get_mut(start..end)).ok_or_else(|| corrupt("tile outside image"))?;
dst.copy_from_slice(row);
}
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::vendor::arw6_testenc::*;
use crate::vendor::pef::Bits;
use craft_tiff::Tiff;
use craft_tiff::image::chunk_bytes;
use craft_tiff::tags as t;
fn planes(w2: usize, h2: usize, seed: u64) -> (Plane, Plane, Plane, Plane) {
let mut x = seed.max(1);
let mut next = |span: i32| -> i32 {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
(x % (2 * span as u64 + 1)) as i32 - span
};
let mut mk = |centre: i32, span: i32| Plane { width: w2, height: h2, data: (0..w2 * h2).map(|_| centre + next(span)).collect() };
(mk(2048, 200), mk(0, 60), mk(0, 60), mk(0, 24))
}
fn one_tile(w: usize, h: usize, s: u8, qi: Qis) -> (Vec<u8>, TileSpec) {
seeded_tile(w, h, s, qi, 7)
}
fn seeded_tile(w: usize, h: usize, s: u8, qi: Qis, seed: u64) -> (Vec<u8>, TileSpec) {
let (m, c1, c2, res) = planes(w / 2, h / 2, seed);
let t = TileSpec { s, qi, m, c1, c2, res };
(encode_tile(&t), t)
}
/// The raw strip bytes of the compression-32766 IFD, as `arw.rs` locates them.
fn strip_of(file: &[u8]) -> &[u8] {
let tiff = Tiff::parse(file).unwrap();
let raw = tiff.all_ifds().into_iter().find(|i| i.u16(t::COMPRESSION) == Some(32766)).unwrap();
let info = raw.image().unwrap();
let chunks = info.chunks(file.len() as u64);
chunk_bytes(file, &chunks[0]).unwrap()
}
#[test]
fn tile_table_round_trips() {
let (tile, _) = one_tile(64, 48, 0, Qis::ZERO);
let file = arw6_file(&[(0, 0, 64, 48, tile.clone())], 64, 48);
let strip = strip_of(&file);
let t = parse_tile_table(strip, 64, 48).unwrap();
assert_eq!(t.len(), 1);
assert_eq!((t[0].x, t[0].y, t[0].width, t[0].height, t[0].offset), (0, 0, 64, 48, 512));
}
#[test]
fn tile_table_rejects_bad_layouts() {
let (tile, _) = one_tile(64, 48, 0, Qis::ZERO);
let strip = strip_of(&arw6_file(&[(0, 0, 64, 48, tile.clone())], 64, 48)).to_vec();
let mut zero = strip.clone();
zero[0] = 0;
assert!(parse_tile_table(&zero, 64, 48).is_err());
let mut far = strip.clone();
far[8..16].copy_from_slice(&u64::MAX.to_le_bytes());
assert!(parse_tile_table(&far, 64, 48).is_err());
let mut odd = strip.clone();
odd[20..24].copy_from_slice(&63u32.to_le_bytes()); // the first tile's y: odd, and no longer covering
assert!(parse_tile_table(&odd, 64, 48).is_err());
assert!(parse_tile_table(&strip, 64, 64).is_err()); // does not cover the image
let two = arw6_file(&[(0, 0, 64, 48, tile.clone()), (0, 0, 64, 48, tile.clone())], 128, 48);
assert!(parse_tile_table(strip_of(&two), 128, 48).is_err()); // overlapping
assert!(parse_tile_table(&strip[..7], 64, 48).is_err()); // truncated table
}
#[test]
fn tile_header_and_streams() {
let (tile, _) = one_tile(64, 48, 3, Qis::REAL);
let h = parse_tile_header(&tile, 64, 48).unwrap();
assert_eq!((h.hs, h.vs, h.streams.len()), (64, 24, 13));
let ntu = tu_count(24, 3);
assert_eq!(ntu, 2);
assert_eq!(
h.streams.iter().map(|s| (s.group, s.comp)).collect::<Vec<_>>(),
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4, 0)]
);
let g3 = stream_halves(&tile, &h.streams[9], ntu).unwrap();
assert_eq!(g3.len(), 4);
assert_eq!(g3[0].qi, [1, 1, 2]);
let g4 = stream_halves(&tile, &h.streams[12], ntu).unwrap();
assert_eq!(g4[1].qi, [2, 2, 2]);
assert!(g4[3].start + g4[3].len <= tile.len());
let mut bad = tile.clone();
bad[13] = 0xff; // corrupts word 0's BBD bits: any picture-header deviation is Unsupported
assert!(matches!(parse_tile_header(&bad, 64, 48), Err(RawError::Unsupported(_))));
assert!(parse_tile_header(&tile, 64, 50).is_err()); // VS != th / 2
}
fn put32(b: &mut [u8], at: usize, v: u32) {
b[at..at + 4].copy_from_slice(&v.to_le_bytes());
}
#[test]
fn tile_table_validation_cases() {
let (tile, _) = one_tile(64, 48, 0, Qis::ZERO);
let many = |n: usize| {
let tiles: Vec<_> = (0..n).map(|i| (64 * i, 0, 64, 48, tile.clone())).collect();
strip_of(&arw6_file(&tiles, 64 * n, 48)).to_vec()
};
let sixteen = many(16);
assert_eq!(parse_tile_table(&sixteen, 1024, 48).unwrap().len(), 16);
let mut seventeen = sixteen.clone();
seventeen[0] = 17;
assert!(parse_tile_table(&seventeen, 1088, 48).is_err());
let two = strip_of(&arw6_file(&[(0, 0, 64, 48, tile.clone()), (64, 0, 64, 48, tile.clone())], 128, 48)).to_vec();
assert_eq!(parse_tile_table(&two, 128, 48).unwrap().len(), 2);
let mut swapped = two.clone();
let (a, b) = (two[8..16].to_vec(), two[32..40].to_vec());
swapped[8..16].copy_from_slice(&b);
swapped[32..40].copy_from_slice(&a);
assert!(parse_tile_table(&swapped, 128, 48).is_err());
let mut at_end = two.clone();
at_end[32..40].copy_from_slice(&(two.len() as u64).to_le_bytes());
assert!(parse_tile_table(&at_end, 128, 48).is_err());
let one = many(1);
let mut wide = one.clone();
put32(&mut wide, 24, 72); // w / 2 = 36 is not a multiple of 8
assert!(parse_tile_table(&wide, 72, 48).is_err());
let mut huge = one.clone();
put32(&mut huge, 24, 1 << 20);
put32(&mut huge, 28, 1 << 20);
assert!(matches!(parse_tile_table(&huge, 1 << 20, 1 << 20), Err(RawError::Limit(_))));
}
#[test]
fn tile_bytes_span_to_the_next_offset() {
let (tile, _) = one_tile(64, 48, 0, Qis::ZERO);
let file = arw6_file(&[(0, 0, 64, 48, tile.clone()), (64, 0, 64, 48, tile.clone())], 128, 48);
let strip = strip_of(&file);
let tiles = parse_tile_table(strip, 128, 48).unwrap();
let (t0, t1) = (tile_bytes(strip, &tiles, 0).unwrap(), tile_bytes(strip, &tiles, 1).unwrap());
assert_eq!(t0.len(), tiles[1].offset - tiles[0].offset);
assert_eq!(t0, &tile[..]);
assert_eq!(t1.as_ptr() as usize + t1.len(), strip.as_ptr() as usize + strip.len());
assert!(tile_bytes(strip, &tiles, 2).is_none());
}
#[test]
fn tile_header_and_stream_validation_cases() {
let (tile, _) = one_tile(64, 48, 0, Qis::REAL);
let h = parse_tile_header(&tile, 64, 48).unwrap();
let mut two_streams = tile.clone();
two_streams[3 * 16] = 2;
assert!(parse_tile_header(&two_streams, 64, 48).is_err());
let mut big = tile.clone();
big[3 * 16 + 1..3 * 16 + 4].copy_from_slice(&[0xff; 3]); // stream 0 larger than the tile
assert!(parse_tile_header(&big, 64, 48).is_err());
let mut idx = tile.clone();
idx[8 * 16..8 * 16 + 2].copy_from_slice(&[0xff, 0xff]); // index words beyond the stream
assert!(parse_tile_header(&idx, 64, 48).is_err());
let s = &h.streams[9];
let mut bad_half = tile.clone();
let idx_start = (s.word + 1) * 16;
bad_half[idx_start..idx_start + 2].copy_from_slice(&[0xff, 0xff]); // A past the data area
assert!(stream_halves(&bad_half, s, tu_count(24, 0)).is_err());
let outside = StreamRef { index_words: 0xffff, ..s.clone() };
assert!(stream_halves(&tile, &outside, tu_count(24, 0)).is_err());
}
#[test]
fn every_stream_of_an_encoded_tile_parses() {
for s in [0u8, 3] {
let (tile, spec) = one_tile(64, 48, s, Qis::REAL);
assert_eq!(tile.len() % 4096, 0);
let h = parse_tile_header(&tile, 64, 48).unwrap();
let ntu = tu_count(24, s);
for st in &h.streams {
assert_eq!(stream_halves(&tile, st, ntu).unwrap().len(), 2 * ntu);
}
// the residual stream's halves decode to the clipped, quantised rows 8n-6+s ..= 8n+1+s
let g4 = stream_halves(&tile, &h.streams[12], ntu).unwrap();
for (n, half) in g4.iter().enumerate() {
let bytes = &tile[half.start..half.start + half.len];
let mut bits = Bits::new(bytes);
for r in (8 * n as i32 - 6 + s as i32..8 * n as i32 + 2 + s as i32).filter(|&r| (0..24).contains(&r)) {
let line = crate::llvc::vld_decode_line(&mut bits, bytes.len() * 8, 32).unwrap();
let want: Vec<i32> = spec.res.row(r as usize).unwrap().iter().map(|&v| quantize(v, 2)).collect();
assert_eq!(line, want, "s {s} half {n} row {r}");
}
}
// a stream that claims more halves than its index holds is rejected
assert!(stream_halves(&tile, &h.streams[0], 1000).is_err());
}
}
#[test]
fn encoder_decodes_its_own_lines() {
let vals: Vec<i32> = (0..100).map(|i| (i * 37) % 23 - 11).collect();
let mut w = BitWriter::default();
vld_encode_line(&vals, 100, &mut w);
let bytes = w.finish();
let mut b = Bits::new(&bytes);
assert_eq!(crate::llvc::vld_decode_line(&mut b, bytes.len() * 8, 100).unwrap(), vals);
}
#[test]
fn phases_and_half_rows_match_the_spec() {
assert_eq!(phases(0), [0, 1, 1]);
assert_eq!(phases(3), [1, 0, 0]);
assert_eq!(half_rows(0, 0, 1668), 0..2);
assert_eq!(half_rows(209, 0, 1668), 1666..1668);
assert_eq!(half_rows(1, 0, 1668), 2..10);
assert_eq!(half_rows(0, 3, 2186), 0..5);
assert_eq!(half_rows(273, 3, 2186), 2181..2186);
assert_eq!(half_rows(300, 3, 2186), 2186..2186);
}
#[test]
fn tu_count_covers_every_row() {
assert_eq!((tu_count(1668, 0), tu_count(2186, 3), tu_count(24, 3), tu_count(48, 0)), (105, 137, 2, 4));
for s in 0u8..=5 {
for vs in 1usize..200 {
let last = half_rows(2 * tu_count(vs, s) - 1, s, vs);
assert!(last.end == vs || (2 * tu_count(vs, s) - 1) * 8 + usize::from(s) + 2 >= vs, "s {s} vs {vs}");
assert_eq!((0..2 * tu_count(vs, s)).map(|n| half_rows(n, s, vs).len()).sum::<usize>(), vs, "s {s} vs {vs}");
}
}
}
#[test]
fn first_half_shift_is_read_from_the_stream() {
for s in [0u8, 3, 5] {
let (tile, _) = one_tile(64, 48, s, Qis::REAL);
let h = parse_tile_header(&tile, 64, 48).unwrap();
assert_eq!(first_half_shift(&tile, &h.streams[12], 32).unwrap(), s);
}
}
#[test]
fn round_trip_every_shift() {
for s in 0u8..=5 {
for (w, h) in [(64usize, 48usize), (80, 96), (64, 36)] {
let (tile, spec) = one_tile(w, h, s, Qis::ZERO); // QI 0: lossless, planes must come back exactly
let p = decode_tile_planes(&tile, w, h).unwrap_or_else(|e| panic!("s={s} {w}x{h}: {e}"));
assert_eq!(p.m, spec.m, "s={s} {w}x{h} m");
assert_eq!(p.c1, spec.c1);
assert_eq!(p.c2, spec.c2);
assert_eq!(p.res, spec.res);
}
}
}
#[test]
fn round_trip_with_real_quantisers() {
// bands drawn as quantised integers q, planes = reconstruct3(dequant(q)); the encoder must reproduce them bit for bit
for s in [0u8, 3] {
let (tile, spec) = one_tile_quantised(96, 64, s, Qis::REAL);
let p = decode_tile_planes(&tile, 96, 64).unwrap();
assert_eq!(p.m, spec.m);
assert_eq!(p.c1, spec.c1);
assert_eq!(p.c2, spec.c2);
assert_eq!(p.res, spec.res);
}
}
#[test]
fn half_too_short_is_corrupt() {
let (mut tile, _) = one_tile(64, 48, 0, Qis::ZERO);
let h = parse_tile_header(&tile, 64, 48).unwrap();
let w = h.streams[9].word * 16 + 16; // first index entry of g3 c0: shrink A by 1 byte
let a = u16::from_be_bytes([tile[w], tile[w + 1]]) - 1;
tile[w..w + 2].copy_from_slice(&a.to_be_bytes());
assert!(matches!(decode_tile_planes(&tile, 64, 48), Err(RawError::Corrupt(_))));
}
proptest::proptest! {
#[test]
fn mutated_tiles_never_panic(flips in proptest::collection::vec((proptest::num::usize::ANY, proptest::num::u8::ANY), 1..12), cut in proptest::num::usize::ANY) {
let (mut tile, _) = one_tile(64, 48, 3, Qis::REAL);
for (i, b) in flips { let i = i % tile.len(); tile[i] ^= b; }
let n = cut % (tile.len() + 1);
let _ = decode_tile(&tile[..n], 64, 48);
let _ = decode_tile(&tile, 64, 48);
}
}
fn plane(w: usize, v: &[i32]) -> Plane {
Plane { width: w, height: v.len() / w, data: v.to_vec() }
}
fn example() -> TilePlanes {
TilePlanes {
m: plane(3, &[2048, 2052, 2060, 2050, 2049, 2070]),
res: plane(3, &[4, -8, 2, 0, 2, -6]),
c1: plane(3, &[10, -10, 0, 0, 3, -2]),
c2: plane(3, &[-5, 7, 1, 2, 0, 4]),
}
}
#[test]
fn colour_matches_the_phase0_example() {
let out = colour(&example()).unwrap(); // 6 wide x 4 rows, curve units
let code = |r: usize, c: usize| out[r * 6 + c] as i32;
assert_eq!(
[code(0, 1), code(0, 3), code(0, 5), code(2, 1), code(2, 3), code(2, 5)],
[2049, 2053, 2059, 2050, 2050, 2071].map(|c| curve(c) as i32)
); // G1
assert_eq!(
[code(1, 0), code(1, 2), code(1, 4), code(3, 0), code(3, 2), code(3, 4)],
[2053, 2042, 2060, 2050, 2052, 2054].map(|c| curve(c) as i32)
); // G2
assert_eq!([code(0, 0), code(0, 2), code(0, 4)], [2071, 2027, 2059].map(|c| curve(c) as i32)); // R
assert_eq!([code(1, 1), code(1, 3), code(1, 5)], [2041, 2061, 2061].map(|c| curve(c) as i32)); // B
}
#[test]
fn colour_clips_like_the_oracle() {
let mut p = example();
p.m.data[1] = 4100;
let out = colour(&p).unwrap();
assert_eq!(out[3], curve(4095)); // G1 = 4101 -> clipped output
assert_eq!(out[6 + 2], curve(2554)); // G2 predicted from the unclipped G1
assert_eq!(out[2], curve(3304)); // R = 2*(-10) + ((4095 + 2554) >> 1): chroma uses the clipped greens
}
#[test]
fn colour_clamps_negative_greens() {
let p = TilePlanes {
m: plane(2, &[10, 2048, 2048, 2048]),
res: plane(2, &[100, 100, 0, 0]),
c1: plane(2, &[7, 0, 0, 0]),
c2: plane(2, &[-3, 0, 0, 0]),
};
let g1_00 = 10 - ((400 + 4) >> 3); // -40
let g1_10 = 2048 - ((200 + 4) >> 3);
let g2_00 = ((2 * g1_00 + 2 * g1_10) >> 2) + 100;
assert!(g1_00 < 0);
let mean = g2_00.clamp(0, 4095) >> 1; // G1 contributes 0
let out = colour(&p).unwrap();
assert_eq!(out[0], curve(14 + mean));
assert_eq!(out[1], curve(0)); // G1 itself clamps
assert_eq!(out[2 * 2 + 1], curve(-6 + mean)); // B at (0,0): row 1, col 1 of a 4-wide mosaic
}
#[test]
fn decode_header_and_full_and_truncations() {
let (tile, _) = one_tile(64, 48, 3, Qis::REAL);
let file = arw6_file(&[(0, 0, 64, 48, tile)], 64, 48);
let strip = strip_of(&file);
assert!(decode(strip, 64, 48, crate::Mode::Header).unwrap().is_empty());
assert_eq!(decode(strip, 64, 48, crate::Mode::Full).unwrap().len(), 64 * 48);
for n in 0..strip.len() {
let _ = decode(&strip[..n], 64, 48, crate::Mode::Full);
let _ = decode(&strip[..n], 64, 48, crate::Mode::Header);
}
}
#[test]
fn garbage_streams_import_then_fail() {
let (mut tile, _) = one_tile(64, 48, 0, Qis::REAL);
let h = parse_tile_header(&tile, 64, 48).unwrap();
let st = &h.streams[9]; // g3 c0
let start = (st.word + 1 + st.index_words) * 16;
for (i, b) in tile[start..start + st.data_words * 16].iter_mut().enumerate() {
*b = (i as u8).wrapping_mul(97) ^ 0xa5;
}
let strip = strip_of(&arw6_file(&[(0, 0, 64, 48, tile)], 64, 48)).to_vec();
assert!(decode(&strip, 64, 48, crate::Mode::Header).is_ok());
assert!(matches!(decode(&strip, 64, 48, crate::Mode::Full), Err(RawError::Corrupt(_))));
}
#[test]
fn chroma_planes_are_base_free() {
let (w2, h2) = (32, 24);
let flat = |v: i32| Plane { width: w2, height: h2, data: vec![v; w2 * h2] };
let (m, _, _, res) = planes(w2, h2, 7);
for (c1, c2) in [(0, 0), (5, -3)] {
let t = TileSpec { s: 0, qi: Qis::ZERO, m: m.clone(), c1: flat(c1), c2: flat(c2), res: res.clone() };
let tile = encode_tile(&t);
let p = decode_tile_planes(&tile, 64, 48).unwrap();
assert!(p.c1.data.iter().all(|&v| v == c1) && p.c2.data.iter().all(|&v| v == c2));
if c1 == 0 {
// zero chroma: R = B = (G1 + G2) >> 1 at every cell (no 2048 base, no saturation)
let out = decode_tile(&tile, 64, 48).unwrap();
for j in 0..h2 {
for x in 0..w2 {
let at = |dy: usize, dx: usize| out[(2 * j + dy) * 64 + 2 * x + dx];
assert_eq!(at(0, 0), at(1, 1), "R == B at ({x},{j})");
assert!(at(0, 0) < curve(4095));
}
}
}
}
}
#[test]
fn arw6_white_without_tag_is_32766() {
let (tile, _) = one_tile(64, 48, 0, Qis::ZERO);
let file = arw6_file_no_white(&[(0, 0, 64, 48, tile)], 64, 48);
let img = crate::decode(&file).unwrap();
assert_eq!(img.white, [32766.0]);
}
#[test]
fn twelve_bit_mode_is_unsupported() {
let (tile, _) = one_tile(64, 48, 0, Qis::ZERO);
let file = arw6_file_bits(&[(0, 0, 64, 48, tile)], 64, 48, 12);
assert!(matches!(crate::decode(&file), Err(RawError::Unsupported(_))));
}
#[test]
fn shift_out_of_range_is_unsupported() {
let (w2, h2) = (32, 24);
let (m, c1, c2, res) = planes(w2, h2, 7);
let tile = encode_tile(&TileSpec { s: 6, qi: Qis::ZERO, m, c1, c2, res });
assert!(matches!(decode_tile_planes(&tile, 64, 48), Err(RawError::Unsupported(_))));
}
#[test]
fn corrupt_streams_import_then_fail() {
// Garbage VLD data is self-delimiting and decodes to *something*; what is detectable is a half whose index
// length is too short for the lines it must hold.
let (mut tile, _) = one_tile(64, 48, 0, Qis::REAL);
let h = parse_tile_header(&tile, 64, 48).unwrap();
let at = (h.streams[9].word + 1) * 16; // g3 c0 index table, first entry: half 0's byte length (u16 BE)
tile[at] = 0;
tile[at + 1] = 1;
let strip = strip_of(&arw6_file(&[(0, 0, 64, 48, tile)], 64, 48)).to_vec();
assert!(decode(&strip, 64, 48, crate::Mode::Header).is_ok());
assert!(matches!(decode(&strip, 64, 48, crate::Mode::Full), Err(RawError::Corrupt(_))));
}
#[test]
fn four_tiles_place_correctly_and_arw_reports_doubled_levels() {
let tiles: Vec<_> = [(0, 0), (64, 0), (0, 48), (64, 48)]
.iter()
.enumerate()
.map(|(i, &(x, y))| {
let (t, _) = seeded_tile(64, 48, 0, Qis::ZERO, 11 + i as u64 * 17); // a different image per tile
(x, y, 64, 48, t)
})
.collect();
let file = arw6_file(&tiles, 128, 96);
let img = crate::decode(&file).unwrap();
assert_eq!((img.width, img.height, img.bits), (128, 96, 16));
assert_eq!(img.black.values, vec![1024.0; 4]);
assert_eq!(img.white, vec![30720.0]);
assert_eq!(img.cfa.as_ref().map(|c| c.pattern.clone()), Some(vec![0, 1, 1, 2]));
let crate::RawData::U16(d) = img.data else { panic!() };
for (x, y, w, h, bytes) in &tiles {
let want = decode_tile(bytes, *w, *h).unwrap();
for r in 0..*h {
assert_eq!(&d[(y + r) * 128 + x..(y + r) * 128 + x + w], &want[r * w..(r + 1) * w], "tile at ({x},{y}) row {r}");
}
}
assert_eq!(crate::probe_info(&file).unwrap().width, 128); // header mode: tile tables and headers only
}
}
-55
View File
@@ -1,55 +0,0 @@
//! The ARW6 companding curve: 12-bit tile code to output value in 2 × 14-bit DN (black 1024, white 32766).
//!
//! Piecewise linear through knots (c_k, 128 k): c_k = 128 k for k <= 11, else 356.89 + 655.646 ln(k - 6); each code's
//! value is the interpolation rounded half up. Our own measurement from the CC0 lossless / ARW6 pairs of the ILCE-7RM6,
//! not stored in the file; see docs/arw6-compression.md (*Output range*).
use std::sync::OnceLock;
/// Code of knot `k`, whose output value is 128 k.
fn knot(k: u32) -> f64 {
if k <= 11 { f64::from(128 * k) } else { 356.89 + 655.646 * f64::from(k - 6).ln() }
}
fn table() -> &'static [u16; 4096] {
static TABLE: OnceLock<[u16; 4096]> = OnceLock::new();
TABLE.get_or_init(|| {
let mut t = [0u16; 4096];
let mut k = 0u32;
for (code, v) in t.iter_mut().enumerate() {
let c = code as f64;
while knot(k + 1) < c {
k += 1;
}
let (c0, c1, u0) = (knot(k), knot(k + 1), f64::from(128 * k));
*v = (u0 + 128.0 * (c - c0) / (c1 - c0) + 0.5).floor() as u16;
}
t
})
}
/// Companding curve: 12-bit code (clamped to 0..=4095) to output value.
pub(crate) fn curve(code12: i32) -> u16 {
table().get(code12.clamp(0, 4095) as usize).copied().unwrap_or(u16::MAX)
}
#[cfg(test)]
mod tests {
use super::*;
/// Pins the whole generated table (sum and position-weighted sum of all 4096 values, from the derivation's own
/// table), so a platform whose `ln` rounds differently fails here.
#[test]
fn table_is_pinned() {
let t = table();
let sum: u64 = t.iter().map(|&v| u64::from(v)).sum();
let weighted: u64 = t.iter().enumerate().map(|(i, &v)| (i as u64 + 1) * u64::from(v)).sum();
assert_eq!((sum, weighted), (27776336, 92792980288));
for (c, v) in [(0, 0), (1408, 1408), (1536, 1542), (2048, 2457), (3000, 7979), (3500, 16227), (3977, 32767), (4095, 39077)] {
assert_eq!(curve(c), v, "code {c}");
}
assert!((0..=1408).all(|c| curve(c) == c as u16), "identity through 1408");
assert!(t.windows(2).all(|w| w[0] < w[1]), "strictly increasing");
assert_eq!((curve(-5), curve(5000)), (0, 39077));
}
}
-483
View File
@@ -1,483 +0,0 @@
//! Test-only ARW6 synthetic encoder pieces: forward 5/3 transforms (exact inverse of `llvc::inverse_*`) and `quantize`.
//! Section names in italics refer to `docs/arw6-compression.md`.
use crate::llvc::{Bands3, Plane, band_rows};
use craft_tiff::tags as t;
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
/// Exact inverse of `dequant` on representable values: `sign(v) * (|v| >> qi)`.
pub(crate) fn quantize(v: i32, qi: u32) -> i32 {
v.signum() * (v.abs() >> qi)
}
fn at(v: &[i32], i: isize) -> i32 {
if v.is_empty() { 0 } else { v[i.clamp(0, v.len() as isize - 1) as usize] }
}
/// Forward 1-D 5/3 with whole-sample symmetric extension (port of the Phase 0 reference model, local and not in the repo).
fn forward_1d(x: &[i32], phase: u8) -> (Vec<i32>, Vec<i32>) {
let n = x.len() as isize;
let p = isize::from(phase);
let xs = |i: isize| -> i32 {
let r = if i < 0 {
-i
} else if i >= n {
2 * (n - 1) - i
} else {
i
};
if (0..n).contains(&r) { x[r as usize] } else { 0 }
};
let (nl, nh) = band_rows(x.len(), phase);
let h: Vec<i32> = (0..nh as isize)
.map(|k| {
let pos = 2 * k + 1 - p;
xs(pos) - ((xs(pos - 1) + xs(pos + 1)) >> 1)
})
.collect();
let l = (0..nl as isize).map(|j| xs(2 * j + p) + ((at(&h, j - 1 + p) + at(&h, j + p) + 2) >> 2)).collect();
(l, h)
}
fn split(x: &Plane, phase: u8, vertical: bool) -> (Plane, Plane) {
let (across, n) = if vertical { (x.width, x.height) } else { (x.height, x.width) };
let (nl, nh) = band_rows(n, phase);
let dims = |m| if vertical { (across, m) } else { (m, across) };
let (mut lo, mut hi) = (Plane::zeros(dims(nl).0, dims(nl).1), Plane::zeros(dims(nh).0, dims(nh).1));
for i in 0..across {
let line: Vec<i32> = (0..n).map(|k| if vertical { x.data[k * x.width + i] } else { x.data[i * x.width + k] }).collect();
let (l, h) = forward_1d(&line, phase);
for (p, v) in [(&mut lo, l), (&mut hi, h)] {
for (k, v) in v.into_iter().enumerate() {
let idx = if vertical { k * p.width + i } else { i * p.width + k };
p.data[idx] = v;
}
}
}
(lo, hi)
}
pub(crate) fn forward_53_1d_rows(x: &Plane, phase: u8) -> (Plane, Plane) {
split(x, phase, true)
}
pub(crate) fn forward_53_1d_cols(x: &Plane, phase: u8) -> (Plane, Plane) {
split(x, phase, false)
}
/// Horizontal first (phase 0), then vertical; returns `(ll, lh, hl, hh)`, the exact inverse of `inverse_53_2d`.
pub(crate) fn forward_53_2d(x: &Plane, vphase: u8) -> (Plane, Plane, Plane, Plane) {
let (lo, hi) = forward_53_1d_cols(x, 0);
let (ll, lh) = forward_53_1d_rows(&lo, vphase);
let (hl, hh) = forward_53_1d_rows(&hi, vphase);
(ll, lh, hl, hh)
}
/// 3-level forward, the exact inverse of `reconstruct3` with the same `phases`.
pub(crate) fn forward3(x: &Plane, phases: [u8; 3]) -> Bands3 {
let (ll1, lh1, hl1, hh1) = forward_53_2d(x, phases[0]);
let (ll2, lh2, hl2, hh2) = forward_53_2d(&ll1, phases[1]);
let (ll3, lh3, hl3, hh3) = forward_53_2d(&ll2, phases[2]);
Bands3 { ll3, hl3, lh3, hh3, hl2, lh2, hh2, hl1, lh1, hh1 }
}
// ---- RDD 34 line encoder (mirror of `llvc::vld_decode_line`; port of the Phase 0 reference model's encoder) ----
/// MSB-first bit sink; one `0`/`1` per element until `finish`.
#[derive(Default)]
pub(crate) struct BitWriter {
bits: Vec<u8>,
}
impl BitWriter {
pub(crate) fn put(&mut self, bit: bool) {
self.bits.push(u8::from(bit));
}
pub(crate) fn put_n(&mut self, v: u32, n: u32) {
for i in (0..n).rev() {
self.put((v >> i) & 1 == 1);
}
}
fn zeros(&mut self, n: u32) {
for _ in 0..n {
self.put(false);
}
}
/// Zero-padded to a whole byte.
pub(crate) fn finish(self) -> Vec<u8> {
self.bits.chunks(8).map(|c| c.iter().enumerate().fold(0u8, |a, (i, &b)| a | (b << (7 - i)))).collect()
}
}
/// Encode one line (`width` coefficients, padded with zeros to whole sets of 4), with Sony's two deviations.
pub(crate) fn vld_encode_line(values: &[i32], width: usize, out: &mut BitWriter) {
let sets_n = width.div_ceil(4);
let mut vals = values[..width.min(values.len())].to_vec();
vals.resize(4 * sets_n, 0);
let sets: Vec<&[i32]> = vals.chunks(4).collect();
let dpts: Vec<u32> = sets.iter().map(|s| 32 - s.iter().map(|v| v.unsigned_abs()).max().unwrap_or(0).leading_zeros()).collect();
let (mut dpt, mut dpts_state, mut cnt, mut zr) = (0u32, 0u8, sets_n, 0usize);
let mut prev: Option<&[i32]> = None;
let mut k = 0usize;
loop {
let dpt_v = cnt != 0;
cnt = cnt.saturating_sub(1);
zr = zr.saturating_sub(1);
if dpt_v {
let d = dpts[k];
match dpts_state {
0 if d == dpt => {
out.put(false);
if dpt == 0 {
dpts_state = 1;
}
}
0 if d > dpt => {
out.put(true);
out.put(false);
out.zeros(d - dpt - 1);
out.put(true);
dpt = d;
}
0 => {
out.put(true);
out.put(true);
if d >= 1 {
out.zeros(dpt - d - 1);
out.put(true);
dpt = d;
} else {
out.zeros(dpt - 1);
dpt = 0;
dpts_state = 1;
}
}
1 if d > 0 => {
out.put(true);
out.zeros(d - 1);
out.put(true);
dpt = d;
dpts_state = 0;
}
1 => {
let r = dpts[k..].iter().take_while(|&&x| x == 0).count();
let lim = (cnt as u64 + 2).next_power_of_two().trailing_zeros();
if k + r >= sets_n {
out.zeros(lim); // the rest of the line is zero
zr = cnt + 2;
} else {
let v = (r + 1) as u32;
let m = 31 - v.leading_zeros();
assert!(m < lim);
out.zeros(m);
out.put(true);
out.put_n(v - (1 << m), m);
zr = r + 1;
}
dpts_state = 2;
}
_ if zr == 1 => {
out.zeros(d - 1);
out.put(true);
dpt = d;
dpts_state = 0;
}
_ => assert_eq!(d, 0),
}
}
if let Some(p) = prev {
for &v in p {
if v != 0 {
out.put(v < 0);
}
}
}
if k >= sets_n {
return;
}
if dpt_v {
for &v in sets[k] {
out.put_n(v.unsigned_abs(), dpt);
}
prev = Some(sets[k]);
}
k += 1;
}
}
// ---- tile / file serialiser (`tilewrite.py::TileModel.serialize`, `arw6dump.py`) ----
/// Per-band quantiser indices: `l1`/`l2`/`l3` per component, bands in HL, LH, HH order.
#[derive(Clone)]
pub(crate) struct Qis {
pub l1: [[u32; 3]; 3],
pub l2: [[u32; 3]; 3],
pub l3: [[u32; 3]; 3],
pub res: u32,
}
impl Qis {
pub(crate) const ZERO: Qis = Qis { l1: [[0; 3]; 3], l2: [[0; 3]; 3], l3: [[0; 3]; 3], res: 0 };
/// The values seen in every real file (*Container*).
pub(crate) const REAL: Qis = Qis { l1: [[1, 1, 2], [2, 2, 3], [2, 2, 3]], l2: [[0, 0, 1]; 3], l3: [[0; 3]; 3], res: 2 };
}
/// One tile to encode: `s` is the anchor offset (*Frame geometry*), planes are W/2 x H/2.
pub(crate) struct TileSpec {
pub s: u8,
pub qi: Qis,
pub m: Plane,
pub c1: Plane,
pub c2: Plane,
pub res: Plane,
}
/// Band row indices of the plane rows `rows` (low: `t % 2 == p`, row `(t-p)/2`; high: row `(t-(1-p))/2`).
fn split_rows(rows: &[usize], p: usize) -> (Vec<usize>, Vec<usize>) {
let (mut lo, mut hi) = (Vec::new(), Vec::new());
for &t in rows {
if t % 2 == p {
lo.push((t - p) / 2);
} else {
hi.push((t - (1 - p)) / 2);
}
}
(lo, hi)
}
fn quantised_rows(plane: &Plane, rows: &[usize], qi: u32) -> Vec<Vec<i32>> {
rows.iter().map(|&r| plane.row(r).unwrap().iter().map(|&v| quantize(v, qi)).collect()).collect()
}
fn encode_lines(lines: &[Vec<i32>]) -> Vec<u8> {
let mut w = BitWriter::default();
for l in lines {
vld_encode_line(l, l.len(), &mut w);
}
w.finish()
}
fn pad16(v: &mut Vec<u8>) {
v.resize(v.len().next_multiple_of(16), 0);
}
fn u24(v: usize) -> [u8; 3] {
[(v >> 16) as u8, (v >> 8) as u8, v as u8]
}
/// One stream: header word, index table, data area. `halves[i]` = (bytes, qi nibbles of the TU).
fn build_stream(halves: &[(Vec<u8>, Vec<u32>)]) -> Vec<u8> {
let (mut idx, mut data) = (Vec::new(), Vec::new());
for pair in halves.chunks(2) {
let mut nib: Vec<u32> = Vec::new();
for (bytes, qi) in pair {
nib.extend((0..4).rev().map(|i| (bytes.len() as u32 >> (4 * i)) & 15));
nib.extend(qi);
data.extend_from_slice(bytes);
}
idx.extend(nib.chunks(2).map(|c| (c[0] << 4 | c[1]) as u8));
}
pad16(&mut idx);
pad16(&mut data);
let mut out = (idx.len() as u16 / 16).to_be_bytes().to_vec();
out.extend(u24(data.len() / 16));
out.extend([0x40, 0x40, 0x01, 0x12, 0x10, 0, 0, 0, 0, 0, 0]);
out.extend(idx);
out.extend(data);
out
}
/// Encode one tile: forward 3-level 5/3 per component with the phases of `s`, quantise, pack every half in natural
/// clipped order (*Frame geometry*), then add index tables, stream headers and the tile header.
pub(crate) fn encode_tile(t: &TileSpec) -> Vec<u8> {
let (vs, s) = (t.m.height, i32::from(t.s));
let ntu = crate::vendor::arw6::tu_count(vs, t.s);
let p1 = s % 2;
let p2 = ((2 + s - p1) / 2) % 2;
let k3 = ((6 + s) % 8 - p1) / 2;
let p3 = ((k3 - p2) / 2).rem_euclid(2);
let (up1, up2, up3) = (p1 as usize, p2 as usize, p3 as usize);
let comps = [&t.m, &t.c1, &t.c2];
let bands: Vec<_> = comps.iter().map(|p| forward3(p, [p1 as u8, p2 as u8, p3 as u8])).collect();
let qi = &t.qi;
// streams[group][comp] -> halves
let mut streams: Vec<Vec<Vec<(Vec<u8>, Vec<u32>)>>> =
vec![vec![Vec::new(); 3], vec![Vec::new(); 3], vec![Vec::new(); 3], vec![Vec::new(); 3], vec![Vec::new()]];
for n in 0..2 * ntu as i32 {
let rows: Vec<usize> = (8 * n - 6 + s..8 * n + 2 + s).filter(|&r| r >= 0 && (r as usize) < vs).map(|r| r as usize).collect();
let (low1, high1) = split_rows(&rows, up1);
let (low2, high2) = split_rows(&low1, up2);
let (low3, high3) = split_rows(&low2, up3);
for (c, b) in bands.iter().enumerate() {
let cat = |parts: [Vec<Vec<i32>>; 3]| parts.into_iter().flatten().collect::<Vec<_>>();
let dpcm = {
let mut ll = quantised_rows(&b.ll3, &low3, 0);
for l in &mut ll {
let mut prev = if c == 0 { 2048 } else { 0 };
for v in l.iter_mut() {
(*v, prev) = (*v - prev, *v);
}
}
ll
};
let sets: [(usize, Vec<Vec<i32>>, Vec<u32>); 4] = [
(0, dpcm, vec![0]),
(
1,
cat([
quantised_rows(&b.hl3, &low3, qi.l3[c][0]),
quantised_rows(&b.lh3, &high3, qi.l3[c][1]),
quantised_rows(&b.hh3, &high3, qi.l3[c][2]),
]),
qi.l3[c].to_vec(),
),
(
2,
cat([
quantised_rows(&b.hl2, &low2, qi.l2[c][0]),
quantised_rows(&b.lh2, &high2, qi.l2[c][1]),
quantised_rows(&b.hh2, &high2, qi.l2[c][2]),
]),
qi.l2[c].to_vec(),
),
(
3,
cat([
quantised_rows(&b.hl1, &low1, qi.l1[c][0]),
quantised_rows(&b.lh1, &high1, qi.l1[c][1]),
quantised_rows(&b.hh1, &high1, qi.l1[c][2]),
]),
qi.l1[c].to_vec(),
),
];
for (g, lines, q) in sets {
streams[g][c].push((encode_lines(&lines), q));
}
}
streams[4][0].push((encode_lines(&quantised_rows(&t.res, &rows, qi.res)), vec![qi.res]));
}
let blobs: Vec<Vec<Vec<u8>>> = streams.iter().map(|g| g.iter().map(|s| build_stream(s)).collect()).collect();
let mut head = vec![0u8; 8 * 16];
head[..4].copy_from_slice(b"0000"); // bytes 4..8: tile index, 0
let tw = 2 * t.m.width;
let w0: u64 = (tw as u64) << 48 | (vs as u64) << 32 | 16 << 20 | 3 << 13 | 3 << 10 | 0b10_0000_0000;
head[8..16].copy_from_slice(&w0.to_be_bytes());
for (g, group) in blobs.iter().enumerate() {
let words: Vec<usize> = group.iter().map(|b| b.len() / 16).collect();
head[(3 + g) * 16] = words.len() as u8;
for (i, w) in words.iter().enumerate() {
head[(3 + g) * 16 + 1 + 3 * i..][..3].copy_from_slice(&u24(*w));
}
head[16 + 3 * g..][..3].copy_from_slice(&u24(words.iter().sum()));
}
let mut out = head;
out.extend(blobs.into_iter().flatten().flatten());
out.resize(out.len().next_multiple_of(4096), 0);
out
}
/// A little-endian ARW6 TIFF: IFD0 (Sony, ILCE-7RM6) + a SubIFD with the strip = tile table, zero padding to 512,
/// then the tiles `(x, y, w, h, bytes)` back to back.
pub(crate) fn arw6_file(tiles: &[(usize, usize, usize, usize, Vec<u8>)], width: usize, height: usize) -> Vec<u8> {
arw6_file_with(tiles, width, height, true, 14)
}
/// [`arw6_file`] with another BitsPerSample.
pub(crate) fn arw6_file_bits(tiles: &[(usize, usize, usize, usize, Vec<u8>)], width: usize, height: usize, bits: u16) -> Vec<u8> {
arw6_file_with(tiles, width, height, true, bits)
}
/// [`arw6_file`] without the WhiteLevel tag.
pub(crate) fn arw6_file_no_white(tiles: &[(usize, usize, usize, usize, Vec<u8>)], width: usize, height: usize) -> Vec<u8> {
arw6_file_with(tiles, width, height, false, 14)
}
fn arw6_file_with(tiles: &[(usize, usize, usize, usize, Vec<u8>)], width: usize, height: usize, white: bool, bits: u16) -> Vec<u8> {
let mut strip = (tiles.len() as u32).to_le_bytes().to_vec();
strip.extend([0; 4]);
let mut offset = 512u64;
for (x, y, w, h, bytes) in tiles {
strip.extend(offset.to_le_bytes());
for v in [x, y, w, h] {
strip.extend((*v as u32).to_le_bytes());
}
offset += bytes.len() as u64;
}
strip.resize(512, 0);
for (.., bytes) in tiles {
strip.extend_from_slice(bytes);
}
let mut raw = IfdBuilder::new();
raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0]));
raw.set(t::IMAGE_WIDTH, Value::Long(vec![width as u32]));
raw.set(t::IMAGE_LENGTH, Value::Long(vec![height as u32]));
raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![bits]));
raw.set(t::COMPRESSION, Value::Short(vec![32766]));
raw.set(t::PHOTOMETRIC, Value::Short(vec![t::photometric::CFA]));
raw.set(t::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2]));
raw.set(t::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2]));
raw.set(0x7310, Value::Short(vec![512; 4]));
if white {
raw.set(t::WHITE_LEVEL, Value::Long(vec![15360]));
}
raw.set_image(ImageData::Strips { rows_per_strip: height as u32, strips: vec![strip] });
let mut ifd0 = IfdBuilder::new();
ifd0.set(t::MAKE, Value::Ascii("SONY".into()));
ifd0.set(t::MODEL, Value::Ascii("ILCE-7RM6".into()));
ifd0.set(t::ORIENTATION, Value::Short(vec![1]));
ifd0.add_sub_ifd(raw);
TiffWriter::new(ByteOrder::Little, false).write(&[ifd0]).unwrap()
}
/// A tile whose bands are random quantised integers `q` (level 1 wider), `v = dequant(q, qi)`, planes by
/// `reconstruct3` (so `quantize` in the encoder is exact on them); LL3 is random around 2048 (green mean) or 0 (chroma), the residual
/// `dequant(q, qi.res)`.
pub(crate) fn one_tile_quantised(w: usize, h: usize, s: u8, qi: Qis) -> (Vec<u8>, TileSpec) {
use crate::llvc::{dequant, reconstruct3};
let (w2, vs) = (w / 2, h / 2);
let ph = crate::vendor::arw6::phases(s);
let mut x = 0x9e37_79b9_7f4a_7c15u64;
let mut rnd = |span: i32, centre: i32, q: u32| -> i32 {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
let v = (x % (2 * span as u64 + 1)) as i32 - span;
if centre == i32::MIN {
v
} else if centre == 0 {
dequant(v, q)
} else {
centre + v
}
};
let mut plane = |wd: usize, ht: usize, span: i32, centre: i32, q: u32| Plane {
width: wd,
height: ht,
data: (0..wd * ht).map(|_| rnd(span, centre, q)).collect(),
};
let mut comps = Vec::new();
for c in 0..3 {
let (n1l, n1h) = band_rows(vs, ph[0]);
let (n2l, n2h) = band_rows(n1l, ph[1]);
let (n3l, n3h) = band_rows(n2l, ph[2]);
let (w1, w2b, w3) = (w2 / 2, w2 / 4, w2 / 8);
let (a, b, d) = (qi.l1[c], qi.l2[c], qi.l3[c]);
let bands = Bands3 {
ll3: plane(w3, n3l, 60, if c == 0 { 2048 } else { i32::MIN }, 0),
hl3: plane(w3, n3l, 7, 0, d[0]),
lh3: plane(w3, n3h, 7, 0, d[1]),
hh3: plane(w3, n3h, 7, 0, d[2]),
hl2: plane(w2b, n2l, 7, 0, b[0]),
lh2: plane(w2b, n2h, 7, 0, b[1]),
hh2: plane(w2b, n2h, 7, 0, b[2]),
hl1: plane(w1, n1l, 15, 0, a[0]),
lh1: plane(w1, n1h, 15, 0, a[1]),
hh1: plane(w1, n1h, 15, 0, a[2]),
};
comps.push(reconstruct3(&bands, ph).unwrap());
}
let res = plane(w2, vs, 7, 0, qi.res);
let (m, c1, c2) = (comps.remove(0), comps.remove(0), comps.remove(0));
let t = TileSpec { s, qi, m, c1, c2, res };
(encode_tile(&t), t)
}
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff. Show more