mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-25 03:53:53 +01:00
Merge remote-tracking branch 'origin/main' into fix/sam-worker-policy-3546
This commit is contained in:
commit
cb99643367
161 files changed
+2929
-34580
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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: |
|
||||
|
||||
@@ -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
@@ -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
@@ -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 }
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -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")));
|
||||
}
|
||||
@@ -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()))
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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).
|
||||
|
||||
@@ -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
@@ -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
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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))
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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}");
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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())
|
||||
};
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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,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),
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
@@ -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") };
|
||||
|
||||
@@ -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
@@ -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
|
||||
/// `a` 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!("{};&", "&".repeat(200_000));
|
||||
assert_eq!(unescape(&hostile), format!("{};&", "&".repeat(200_000)));
|
||||
assert_eq!(unescape("<a>  &unknownreference;"), "<a> \u{10FFFF} &unknownreference;");
|
||||
fn references_and_padding_decode_and_unknown_entities_stay() {
|
||||
let root = parse("<lens maker='Canon &'>A &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("Canon A A"), "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)));
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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(" | ||||