mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-03 23:41:17 -05:00
Merge remote-tracking branch 'upstream/main' into fix/brush-flow-per-radius
# Conflicts: # docs/whats-new.md
This commit is contained in:
@@ -3,6 +3,10 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
# A nightly dry run on main: every release build except macOS, nothing signed or released
|
||||
# (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day.
|
||||
schedule:
|
||||
- cron: "4 2 * * *"
|
||||
push:
|
||||
branches: [release]
|
||||
workflow_dispatch:
|
||||
@@ -78,6 +82,7 @@ jobs:
|
||||
# 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.
|
||||
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
|
||||
with:
|
||||
dry-run: ${{ github.event_name == 'schedule' }}
|
||||
app-name: lightcraft
|
||||
app-title: LightCraft
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
|
||||
Generated
+66
-56
@@ -1199,6 +1199,23 @@ name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=c5a1cbfb5f9049f9270955caffb5bee5997aebf7#c5a1cbfb5f9049f9270955caffb5bee5997aebf7"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gainmap"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d#430a908f68819bf23d14fe73ab9b18d8f4fd4e5d"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-heif"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d#430a908f68819bf23d14fe73ab9b18d8f4fd4e5d"
|
||||
dependencies = [
|
||||
"heic-rs",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
@@ -1222,6 +1239,15 @@ dependencies = [
|
||||
"writeable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-tiff"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=430a908f68819bf23d14fe73ab9b18d8f4fd4e5d#430a908f68819bf23d14fe73ab9b18d8f4fd4e5d"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -3588,7 +3614,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-update",
|
||||
@@ -3617,7 +3643,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-catalog"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"crc32fast",
|
||||
@@ -3638,7 +3664,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-cli"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"dhat",
|
||||
"lightcraft-codecs",
|
||||
@@ -3655,10 +3681,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-codecs"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"avif-serialize",
|
||||
"bytemuck",
|
||||
"craft-gainmap",
|
||||
"craft-heif",
|
||||
"dhat",
|
||||
"image",
|
||||
"image-webp",
|
||||
@@ -3668,7 +3696,6 @@ dependencies = [
|
||||
"jxl-oxide",
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-heif",
|
||||
"lightcraft-raster",
|
||||
"lightcraft-testkit",
|
||||
"moxcms 0.9.1",
|
||||
@@ -3686,7 +3713,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-color"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"lightcraft-geom",
|
||||
"proptest",
|
||||
@@ -3695,7 +3722,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-denoise"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"faer-core",
|
||||
"lightcraft-denoise-core",
|
||||
@@ -3712,7 +3739,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-denoise-core"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"dhat",
|
||||
"lightcraft-raster",
|
||||
@@ -3728,7 +3755,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-develop"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"lightcraft-color",
|
||||
"lightcraft-geom",
|
||||
@@ -3740,11 +3767,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-engine"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"ab_glyph",
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"craft-heif",
|
||||
"craft-tiff",
|
||||
"crc32fast",
|
||||
"fs4",
|
||||
"harfrust 0.13.3",
|
||||
@@ -3761,7 +3790,6 @@ dependencies = [
|
||||
"lightcraft-geocode",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-gpu",
|
||||
"lightcraft-heif",
|
||||
"lightcraft-lensdb",
|
||||
"lightcraft-merge",
|
||||
"lightcraft-meta",
|
||||
@@ -3773,7 +3801,6 @@ dependencies = [
|
||||
"lightcraft-segment",
|
||||
"lightcraft-slideshow",
|
||||
"lightcraft-testkit",
|
||||
"lightcraft-tiff",
|
||||
"log",
|
||||
"miniz_oxide 0.9.1",
|
||||
"rayon",
|
||||
@@ -3787,7 +3814,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-faces"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"lightcraft-testkit",
|
||||
"matrixmultiply",
|
||||
@@ -3802,7 +3829,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-fetch"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"log",
|
||||
"rustls",
|
||||
@@ -3813,14 +3840,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-film"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-geocode"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"miniz_oxide 0.9.1",
|
||||
"serde",
|
||||
@@ -3828,7 +3855,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-geom"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
@@ -3836,7 +3863,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-gpu"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"lightcraft-color",
|
||||
@@ -3854,24 +3881,16 @@ dependencies = [
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-heif"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"heic-rs",
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-inpaint"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-lensdb"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"lightcraft-develop",
|
||||
"lightcraft-geom",
|
||||
@@ -3880,7 +3899,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-mcp"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"lightcraft-codecs",
|
||||
"lightcraft-engine",
|
||||
@@ -3891,7 +3910,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-merge"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"lightcraft-codecs",
|
||||
"lightcraft-color",
|
||||
@@ -3907,12 +3926,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-meta"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-heif",
|
||||
"craft-tiff",
|
||||
"lightcraft-geom",
|
||||
"lightcraft-heif",
|
||||
"lightcraft-tiff",
|
||||
"proptest",
|
||||
"quick-xml 0.41.0",
|
||||
"serde",
|
||||
@@ -3921,7 +3940,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-pipeline"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"dhat",
|
||||
"image",
|
||||
@@ -3940,7 +3959,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-preview"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"jpeg-encoder",
|
||||
"lightcraft-raster",
|
||||
@@ -3952,7 +3971,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-raster"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"lightcraft-color",
|
||||
@@ -3964,10 +3983,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-raw"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"craft-crw",
|
||||
"craft-tiff",
|
||||
"dhat",
|
||||
"jpeg-encoder",
|
||||
"jxl-oxide",
|
||||
@@ -3976,7 +3996,6 @@ dependencies = [
|
||||
"lightcraft-meta",
|
||||
"lightcraft-raster",
|
||||
"lightcraft-testkit",
|
||||
"lightcraft-tiff",
|
||||
"miniz_oxide 0.9.1",
|
||||
"proptest",
|
||||
"rayon",
|
||||
@@ -3990,7 +4009,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-scenes"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"image",
|
||||
"lightcraft-color",
|
||||
@@ -4001,7 +4020,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-segment"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"candle-core",
|
||||
"candle-nn",
|
||||
@@ -4015,7 +4034,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-slideshow"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"lightcraft-raster",
|
||||
"serde",
|
||||
@@ -4024,24 +4043,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-sysmem"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-testkit"
|
||||
version = "0.21.0"
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-tiff"
|
||||
version = "0.21.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
version = "0.21.1"
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-ui-egui"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"craft-ui",
|
||||
"craft-update",
|
||||
@@ -4074,7 +4084,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-web"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"eframe",
|
||||
@@ -4097,7 +4107,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-wincolor"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"lightcraft-testkit",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -7916,7 +7926,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
|
||||
|
||||
[[package]]
|
||||
name = "xtask"
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"flate2",
|
||||
|
||||
+7
-3
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "apps/*", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.21.0"
|
||||
version = "0.21.1"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
@@ -17,6 +17,8 @@ craft-crw = { git = "https://github.com/storytold/craft-libs", rev = "f3b62ec61f
|
||||
# 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" }
|
||||
# internal
|
||||
lightcraft-denoise-core = { path = "crates/denoise-core" }
|
||||
lightcraft-denoise = { path = "crates/denoise", default-features = false }
|
||||
@@ -26,7 +28,8 @@ lightcraft-sysmem = { path = "crates/sysmem" }
|
||||
lightcraft-wincolor = { path = "crates/wincolor" }
|
||||
lightcraft-color = { path = "crates/color" }
|
||||
lightcraft-raster = { path = "crates/raster" }
|
||||
lightcraft-tiff = { path = "crates/tiff" }
|
||||
# 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" }
|
||||
lightcraft-raw = { path = "crates/raw" }
|
||||
lightcraft-codecs = { path = "crates/codecs" }
|
||||
lightcraft-meta = { path = "crates/meta" }
|
||||
@@ -44,7 +47,8 @@ lightcraft-engine = { path = "crates/engine" }
|
||||
lightcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
lightcraft-mcp = { path = "crates/mcp" }
|
||||
lightcraft-fetch = { path = "crates/fetch" }
|
||||
lightcraft-heif = { path = "crates/heif" }
|
||||
# HEIC/HEIF: the shared decoder (moved from crates/heif; craft-libs#784).
|
||||
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "430a908f68819bf23d14fe73ab9b18d8f4fd4e5d" }
|
||||
lightcraft-segment = { path = "crates/segment" }
|
||||
lightcraft-geocode = { path = "crates/geocode" }
|
||||
lightcraft-slideshow = { path = "crates/slideshow" }
|
||||
|
||||
@@ -37,6 +37,6 @@ rawnind-model = ["denoise", "lightcraft-engine/rawnind-model"]
|
||||
# (open it in DHAT's viewer: allocation sites by bytes at the peak). Slows allocation-heavy work.
|
||||
dhat-heap = ["dep:dhat"]
|
||||
|
||||
# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose
|
||||
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
|
||||
# it (HEVC patents); build with `--features heif` to include it.
|
||||
heif = ["lightcraft-codecs/heif"]
|
||||
|
||||
@@ -77,7 +77,7 @@ web-sys = { workspace = true, features = [
|
||||
] }
|
||||
|
||||
[features]
|
||||
# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose
|
||||
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
|
||||
# it (HEVC patents); build with `--features heif` to include it. On wasm32 panics abort, so
|
||||
# heic-rs's `catch_unwind` guard does not apply there.
|
||||
heif = ["lightcraft-codecs/heif"]
|
||||
|
||||
@@ -13,7 +13,7 @@ workspace = true
|
||||
default = ["denoise"]
|
||||
denoise = ["lightcraft-engine/denoise"]
|
||||
rawnind-model = ["denoise", "lightcraft-engine/rawnind-model"]
|
||||
# Open HEIC/HEIF photos (the optional lightcraft-heif crate). Not default so distributors choose
|
||||
# Open HEIC/HEIF photos (the optional craft-heif crate). Not default so distributors choose
|
||||
# it (HEVC patents); build with `--features heif` to include it.
|
||||
heif = ["lightcraft-codecs/heif"]
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ workspace = true
|
||||
lightcraft-geom = { workspace = true }
|
||||
lightcraft-color = { workspace = true }
|
||||
lightcraft-raster = { workspace = true }
|
||||
lightcraft-heif = { workspace = true, optional = true }
|
||||
craft-gainmap = { workspace = true }
|
||||
craft-heif = { workspace = true, optional = true }
|
||||
serde = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -40,10 +41,10 @@ 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"]
|
||||
# HEIC/HEIF decode via the optional lightcraft-heif crate (heic-rs, pure Rust). Off by default so
|
||||
# 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.
|
||||
heif = ["dep:lightcraft-heif"]
|
||||
heif = ["dep:craft-heif"]
|
||||
## AVIF encoding via ravif/rav1e (pure Rust, BSD). Native targets only; a no-op on wasm32.
|
||||
avif = ["dep:ravif", "dep:rav1e", "dep:avif-serialize"]
|
||||
|
||||
@@ -54,7 +55,7 @@ lightcraft-testkit = { workspace = true }
|
||||
jxl-oxide = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
# Lossless synthetic HEIC files for the `heif` feature's tests.
|
||||
lightcraft-heif = { workspace = true, features = ["testdata"] }
|
||||
craft-heif = { workspace = true, features = ["testdata"] }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
dhat = { workspace = true }
|
||||
|
||||
@@ -48,13 +48,13 @@ CRW, MRW, X3F) are detected so the engine can route them to `lightcraft-raw`; `d
|
||||
|---|---|---|---|
|
||||
| JPEG | yes (zune-jpeg; jpeg-decoder for DCT scaling, CMYK/YCCK, 12-bit, non-interleaved scans) | yes (jpeg-encoder, baseline, 4:4:4/4:2:2/4:2:0) | EXIF (APP1), XMP (APP1, ≤ 64 KiB), ICC (APP2; only complete, consistently counted, uniquely numbered chunk sequences are assembled; malformed profiles use the existing unsupported-profile fallback), Adobe APP14, MPF previews |
|
||||
| PNG | yes, 1–16-bit, palette, tRNS, interlaced | 8/16-bit, gray/GA/RGB/RGBA | iCCP, eXIf, iTXt XMP; sRGB/cICP/cHRM/gAMA honoured when no ICC |
|
||||
| TIFF | 8/16-bit int (32/64-bit int kept to 16 bits), 16/32/64-bit float, gray/RGB/CMYK/palette, alpha (assoc./unassoc.), planar, LZW/Deflate/PackBits/JPEG | 8/16-bit, 32-bit float; none/LZW/Deflate/PackBits | ICC (34675), XMP (700), Orientation; first IFD only; EXIF not written (use `lightcraft-tiff`) |
|
||||
| TIFF | 8/16-bit int (32/64-bit int kept to 16 bits), 16/32/64-bit float, gray/RGB/CMYK/palette, alpha (assoc./unassoc.), planar, LZW/Deflate/PackBits/JPEG | 8/16-bit, 32-bit float; none/LZW/Deflate/PackBits | ICC (34675), XMP (700), Orientation; first IFD only; EXIF not written (use `craft-tiff`) |
|
||||
| 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 |
|
||||
| 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` (lightcraft-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 |
|
||||
| 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 |
|
||||
|
||||
## Colour
|
||||
|
||||
@@ -229,7 +229,7 @@ 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 `lightcraft-tiff`).
|
||||
/// 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;
|
||||
|
||||
@@ -1,547 +1,21 @@
|
||||
//! Gain map HDR images (ISO 21496-1): an SDR base image plus a gain map that a decoder uses to
|
||||
//! rebuild the HDR rendition, so the file looks right everywhere and lights up on HDR displays.
|
||||
//! Gain map JPEGs (ISO 21496-1): an SDR base image plus a gain map that a decoder uses to rebuild
|
||||
//! the HDR rendition, so the file looks right everywhere and lights up on HDR displays.
|
||||
//!
|
||||
//! The metadata formats and the arithmetic ([`compute`], [`apply`], [`GainMapMeta`]) are
|
||||
//! `craft-gainmap`'s, re-exported here. This module lays the two images out in a JPEG:
|
||||
//!
|
||||
//! - [`compute`] measures a gain map from an SDR and an HDR rendition of the same picture (linear
|
||||
//! light, same primaries). Measure it against the base *as written* (decoded from its 8-bit
|
||||
//! codes), so quantisation in the base is handed back by the gain map.
|
||||
//! - [`apply`] rebuilds the HDR rendition from a base and its gain map.
|
||||
//! - [`encode_jpeg`] writes a gain map JPEG: the base with an MPF index (CIPA DC-007), the ISO
|
||||
//! 21496-1 marker and Adobe/Google container XMP, followed by the gain map JPEG carrying the ISO
|
||||
//! 21496-1 metadata, the Adobe `hdrgm` XMP (Android, Chrome) and Apple's description of the same
|
||||
//! map (what survives an iMessage send).
|
||||
//! - [`read_jpeg`] finds and decodes the gain map of a gain map JPEG (ours, cameras, Lightroom),
|
||||
//! from its ISO 21496-1 metadata or, failing that, its `hdrgm` XMP.
|
||||
//!
|
||||
//! All gains are log2. A decoder recovers `log2(hdr + offset_hdr) − log2(sdr + offset_sdr)` as
|
||||
//! `min + (max − min) · (code / 255)^(1 / gamma)`, scaled by a weight in 0..1 that depends on how
|
||||
//! much headroom the display has between `base_headroom` and `alternate_headroom`.
|
||||
|
||||
pub use craft_gainmap::{GainImage, GainMapMeta, GainMapOptions, ISO_URN, apply, compute};
|
||||
|
||||
use crate::encode::{EncodeImage, EncodeMeta, Samples, jpeg_app_segments, xmp_segment};
|
||||
use crate::{ChromaSubsampling, Error, Format, Result, jpeg, jpeg_par};
|
||||
|
||||
/// The ISO 21496-1 namespace that opens its APP2 payloads (NUL terminated).
|
||||
pub const ISO_URN: &[u8] = b"urn:iso:std:iso:ts:21496:-1\0";
|
||||
|
||||
/// Fixed denominator for the metadata's rationals: one value per setting, byte-identical output.
|
||||
const DENOMINATOR: u32 = 1_000_000;
|
||||
|
||||
/// Gain map parameters (ISO 21496-1 / Adobe `hdrgm`). Per-channel arrays repeat the first value
|
||||
/// when the map is single-channel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct GainMapMeta {
|
||||
/// Three gain channels (R, G, B) instead of one luminance gain.
|
||||
pub multichannel: bool,
|
||||
/// The gain applies in the base image's colour space.
|
||||
pub use_base_colour_space: bool,
|
||||
/// log2 headroom at which the base is shown as is (0: an SDR base).
|
||||
pub base_headroom: f32,
|
||||
/// log2 headroom at which the gain map applies in full.
|
||||
pub alternate_headroom: f32,
|
||||
pub min: [f32; 3],
|
||||
pub max: [f32; 3],
|
||||
pub gamma: [f32; 3],
|
||||
pub base_offset: [f32; 3],
|
||||
pub alternate_offset: [f32; 3],
|
||||
}
|
||||
|
||||
impl Default for GainMapMeta {
|
||||
fn default() -> Self {
|
||||
GainMapMeta {
|
||||
multichannel: false,
|
||||
use_base_colour_space: true,
|
||||
base_headroom: 0.0,
|
||||
alternate_headroom: 1.0,
|
||||
min: [0.0; 3],
|
||||
max: [1.0; 3],
|
||||
gamma: [1.0; 3],
|
||||
base_offset: [1.0 / 64.0; 3],
|
||||
alternate_offset: [1.0 / 64.0; 3],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GainMapMeta {
|
||||
fn channels(&self) -> usize {
|
||||
if self.multichannel { 3 } else { 1 }
|
||||
}
|
||||
|
||||
/// Usable by [`apply`]: finite, positive gammas, max ≥ min, headrooms in order.
|
||||
pub fn is_valid(&self) -> bool {
|
||||
let fin = |a: &[f32; 3]| a.iter().all(|v| v.is_finite());
|
||||
fin(&self.min)
|
||||
&& fin(&self.max)
|
||||
&& fin(&self.gamma)
|
||||
&& fin(&self.base_offset)
|
||||
&& fin(&self.alternate_offset)
|
||||
&& self.gamma.iter().all(|g| *g > 0.0)
|
||||
&& self.min.iter().zip(&self.max).all(|(a, b)| b >= a)
|
||||
&& self.base_headroom.is_finite()
|
||||
&& self.alternate_headroom.is_finite()
|
||||
&& self.alternate_headroom > self.base_headroom
|
||||
}
|
||||
|
||||
/// The ISO 21496-1 APP2 payload of the gain map image, URN included.
|
||||
pub fn to_iso(&self) -> Vec<u8> {
|
||||
let mut p = ISO_URN.to_vec();
|
||||
p.extend_from_slice(&0u16.to_be_bytes()); // minimum_version: readers gate on this
|
||||
p.extend_from_slice(&0u16.to_be_bytes()); // writer_version
|
||||
let mut flags = 0u8;
|
||||
if self.multichannel {
|
||||
flags |= FLAG_MULTICHANNEL;
|
||||
}
|
||||
if self.use_base_colour_space {
|
||||
flags |= FLAG_BASE_COLOUR_SPACE;
|
||||
}
|
||||
p.push(flags);
|
||||
let unsigned = |p: &mut Vec<u8>, v: f32| {
|
||||
let n = (v as f64 * DENOMINATOR as f64).round().clamp(0.0, u32::MAX as f64) as u32;
|
||||
p.extend_from_slice(&n.to_be_bytes());
|
||||
p.extend_from_slice(&DENOMINATOR.to_be_bytes());
|
||||
};
|
||||
let signed = |p: &mut Vec<u8>, v: f32| {
|
||||
let n = (v as f64 * DENOMINATOR as f64).round().clamp(i32::MIN as f64, i32::MAX as f64) as i32;
|
||||
p.extend_from_slice(&n.to_be_bytes());
|
||||
p.extend_from_slice(&DENOMINATOR.to_be_bytes());
|
||||
};
|
||||
unsigned(&mut p, self.base_headroom.max(0.0));
|
||||
unsigned(&mut p, self.alternate_headroom.max(0.0));
|
||||
for c in 0..self.channels() {
|
||||
signed(&mut p, self.min[c]);
|
||||
signed(&mut p, self.max[c]);
|
||||
unsigned(&mut p, self.gamma[c]);
|
||||
signed(&mut p, self.base_offset[c]);
|
||||
signed(&mut p, self.alternate_offset[c]);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// Parse an ISO 21496-1 payload (the bytes after [`ISO_URN`]). `None` for the versions-only
|
||||
/// marker a primary image carries, unknown versions, a base that is the HDR rendition, or
|
||||
/// values no decoder could use.
|
||||
pub fn from_iso(p: &[u8]) -> Option<GainMapMeta> {
|
||||
let mut r = Reader { b: p, at: 0 };
|
||||
let min_version = r.u16()?;
|
||||
let _writer_version = r.u16()?;
|
||||
if min_version != 0 {
|
||||
return None;
|
||||
}
|
||||
let flags = r.u8()?;
|
||||
if flags & FLAG_BACKWARD != 0 {
|
||||
return None;
|
||||
}
|
||||
let multichannel = flags & FLAG_MULTICHANNEL != 0;
|
||||
let common = flags & FLAG_COMMON_DENOMINATOR != 0;
|
||||
let common_d = if common { r.u32()? } else { 0 };
|
||||
let unsigned = |r: &mut Reader| -> Option<f32> {
|
||||
let n = r.u32()?;
|
||||
let d = if common { common_d } else { r.u32()? };
|
||||
(d != 0).then(|| (n as f64 / d as f64) as f32)
|
||||
};
|
||||
let signed = |r: &mut Reader| -> Option<f32> {
|
||||
let n = r.u32()? as i32;
|
||||
let d = if common { common_d } else { r.u32()? };
|
||||
(d != 0).then(|| (n as f64 / d as f64) as f32)
|
||||
};
|
||||
let mut m = GainMapMeta {
|
||||
multichannel,
|
||||
use_base_colour_space: flags & FLAG_BASE_COLOUR_SPACE != 0,
|
||||
base_headroom: unsigned(&mut r)?,
|
||||
alternate_headroom: unsigned(&mut r)?,
|
||||
..GainMapMeta::default()
|
||||
};
|
||||
for c in 0..m.channels() {
|
||||
m.min[c] = signed(&mut r)?;
|
||||
m.max[c] = signed(&mut r)?;
|
||||
m.gamma[c] = unsigned(&mut r)?;
|
||||
m.base_offset[c] = signed(&mut r)?;
|
||||
m.alternate_offset[c] = signed(&mut r)?;
|
||||
}
|
||||
if !multichannel {
|
||||
m.fill_from_first();
|
||||
}
|
||||
m.is_valid().then_some(m)
|
||||
}
|
||||
|
||||
fn fill_from_first(&mut self) {
|
||||
for a in [&mut self.min, &mut self.max, &mut self.gamma, &mut self.base_offset, &mut self.alternate_offset] {
|
||||
a[1] = a[0];
|
||||
a[2] = a[0];
|
||||
}
|
||||
}
|
||||
|
||||
/// The gain parameters from Adobe `hdrgm` XMP (the gain map image's packet), for files
|
||||
/// without ISO 21496-1 metadata (the first Ultra HDR files). Attributes or `rdf:Seq` lists.
|
||||
pub fn from_hdrgm_xmp(xmp: &str) -> Option<GainMapMeta> {
|
||||
if !xmp.contains("hdrgm:") {
|
||||
return None;
|
||||
}
|
||||
let base_rendition_hdr = xmp_values(xmp, "BaseRenditionIsHDR").is_some_and(|v| v.first().is_some_and(|s| s.eq_ignore_ascii_case("true")));
|
||||
if base_rendition_hdr {
|
||||
return None;
|
||||
}
|
||||
let get = |name: &str, default: f32| -> Option<([f32; 3], bool)> {
|
||||
let Some(v) = xmp_values(xmp, name) else { return Some(([default; 3], false)) };
|
||||
let f: Vec<f32> = v.iter().map(|s| s.trim().parse::<f32>().ok()).collect::<Option<_>>()?;
|
||||
match f.as_slice() {
|
||||
[a] => Some(([*a; 3], false)),
|
||||
[a, b, c] => Some(([*a, *b, *c], true)),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let (max, m1) = get("GainMapMax", f32::NAN)?;
|
||||
if max.iter().any(|v| v.is_nan()) {
|
||||
return None; // the one required parameter
|
||||
}
|
||||
let (min, m2) = get("GainMapMin", 0.0)?;
|
||||
let (gamma, m3) = get("Gamma", 1.0)?;
|
||||
let (base_offset, m4) = get("OffsetSDR", 1.0 / 64.0)?;
|
||||
let (alternate_offset, m5) = get("OffsetHDR", 1.0 / 64.0)?;
|
||||
let (cap_min, _) = get("HDRCapacityMin", 0.0)?;
|
||||
let max_gain = max.iter().copied().fold(f32::MIN, f32::max);
|
||||
let (cap_max, _) = get("HDRCapacityMax", max_gain)?;
|
||||
let m = GainMapMeta {
|
||||
multichannel: m1 || m2 || m3 || m4 || m5,
|
||||
use_base_colour_space: true,
|
||||
base_headroom: cap_min[0].max(0.0),
|
||||
alternate_headroom: cap_max[0],
|
||||
min,
|
||||
max,
|
||||
gamma,
|
||||
base_offset,
|
||||
alternate_offset,
|
||||
};
|
||||
m.is_valid().then_some(m)
|
||||
}
|
||||
|
||||
/// The gain map image's XMP: the Adobe `hdrgm` parameters (read by Android and Chrome, which
|
||||
/// ignore the ISO payload) and Apple's description of the same map (what iMessage keeps).
|
||||
pub fn to_gain_map_xmp(&self) -> String {
|
||||
let names = ["GainMapMin", "GainMapMax", "Gamma", "OffsetSDR", "OffsetHDR"];
|
||||
let values = [&self.min, &self.max, &self.gamma, &self.base_offset, &self.alternate_offset];
|
||||
let uniform = |v: &[f32; 3]| !self.multichannel || (v[0] == v[1] && v[1] == v[2]);
|
||||
let mut s = String::from(XMP_OPEN);
|
||||
s.push_str(r#"<rdf:Description rdf:about="" xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/" hdrgm:Version="1.0""#);
|
||||
s.push_str(&format!(r#" hdrgm:HDRCapacityMin="{}""#, num(self.base_headroom)));
|
||||
s.push_str(&format!(r#" hdrgm:HDRCapacityMax="{}""#, num(self.alternate_headroom)));
|
||||
s.push_str(r#" hdrgm:BaseRenditionIsHDR="False""#);
|
||||
for (n, v) in names.iter().zip(values) {
|
||||
if uniform(v) {
|
||||
s.push_str(&format!(r#" hdrgm:{n}="{}""#, num(v[0])));
|
||||
}
|
||||
}
|
||||
s.push('>');
|
||||
// per-channel values are an rdf:Seq of three, not a comma list: readers parse each item
|
||||
for (n, v) in names.iter().zip(values) {
|
||||
if !uniform(v) {
|
||||
s.push_str(&format!("<hdrgm:{n}><rdf:Seq>"));
|
||||
for x in v {
|
||||
s.push_str(&format!("<rdf:li>{}</rdf:li>", num(*x)));
|
||||
}
|
||||
s.push_str(&format!("</rdf:Seq></hdrgm:{n}>"));
|
||||
}
|
||||
}
|
||||
s.push_str("</rdf:Description>");
|
||||
s.push_str(&self.apple_description());
|
||||
s.push_str(XMP_CLOSE);
|
||||
s
|
||||
}
|
||||
|
||||
/// Apple's own description of the map (`apdi`, `HDRGainMap`, `HDRToneMap` namespaces).
|
||||
fn apple_description(&self) -> String {
|
||||
// 'L008' (8-bit luminance) or '444f'; the stored map must really have that many channels
|
||||
let format = if self.multichannel { 0x3434_3466u32 } else { 0x4C30_3038 };
|
||||
let mut s = String::from(
|
||||
r#"<rdf:Description rdf:about="" xmlns:apdi="http://ns.apple.com/pixeldatainfo/1.0/" xmlns:HDRGainMap="http://ns.apple.com/HDRGainMap/1.0/" xmlns:HDRToneMap="http://ns.apple.com/HDRToneMap/1.0/">"#,
|
||||
);
|
||||
s.push_str("<apdi:AuxiliaryImageType>urn:com:apple:photo:2020:aux:hdrgainmap</apdi:AuxiliaryImageType>");
|
||||
s.push_str(&format!("<apdi:NativeFormat>{format}</apdi:NativeFormat><apdi:StoredFormat>{format}</apdi:StoredFormat>"));
|
||||
s.push_str("<HDRGainMap:HDRGainMapVersion>131072</HDRGainMap:HDRGainMapVersion>");
|
||||
// linear, not log2: the headroom multiplier itself
|
||||
s.push_str(&format!("<HDRGainMap:HDRGainMapHeadroom>{}</HDRGainMap:HDRGainMapHeadroom>", num(self.alternate_headroom.exp2())));
|
||||
s.push_str(&format!("<HDRToneMap:AlternateHeadroom>{}</HDRToneMap:AlternateHeadroom>", num(self.alternate_headroom)));
|
||||
s.push_str("<HDRToneMap:ChannelMetadata><rdf:Seq>");
|
||||
for c in 0..self.channels() {
|
||||
s.push_str(&format!(
|
||||
r#"<rdf:li rdf:parseType="Resource"><HDRToneMap:GainMapMin>{}</HDRToneMap:GainMapMin><HDRToneMap:GainMapMax>{}</HDRToneMap:GainMapMax><HDRToneMap:Gamma>{}</HDRToneMap:Gamma><HDRToneMap:BaseOffset>{}</HDRToneMap:BaseOffset><HDRToneMap:AlternateOffset>{}</HDRToneMap:AlternateOffset></rdf:li>"#,
|
||||
num(self.min[c]),
|
||||
num(self.max[c]),
|
||||
num(self.gamma[c]),
|
||||
num(self.base_offset[c]),
|
||||
num(self.alternate_offset[c])
|
||||
));
|
||||
}
|
||||
s.push_str("</rdf:Seq></HDRToneMap:ChannelMetadata>");
|
||||
s.push_str(&format!("<HDRToneMap:BaseHeadroom>{}</HDRToneMap:BaseHeadroom>", num(self.base_headroom)));
|
||||
s.push_str("<HDRToneMap:BaseColorIsWorkingColor>True</HDRToneMap:BaseColorIsWorkingColor><HDRToneMap:Version>1</HDRToneMap:Version>");
|
||||
s.push_str("</rdf:Description>");
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
const FLAG_MULTICHANNEL: u8 = 0x80;
|
||||
const FLAG_BASE_COLOUR_SPACE: u8 = 0x40;
|
||||
const FLAG_COMMON_DENOMINATOR: u8 = 0x08;
|
||||
const FLAG_BACKWARD: u8 = 0x04;
|
||||
|
||||
const XMP_OPEN: &str = "<?xpacket begin=\"\u{feff}\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">";
|
||||
const XMP_CLOSE: &str = "</rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>";
|
||||
|
||||
/// A short decimal (up to 6 significant digits, no exponent for ordinary values).
|
||||
fn num(v: f32) -> String {
|
||||
if !v.is_finite() {
|
||||
return "0".into();
|
||||
}
|
||||
let s = format!("{:.6}", v);
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
if s == "-0" || s.is_empty() { "0".into() } else { s.to_string() }
|
||||
}
|
||||
|
||||
/// The values of `hdrgm:<name>`: an attribute (`name="v"`) or an element holding an `rdf:Seq`.
|
||||
fn xmp_values(xmp: &str, name: &str) -> Option<Vec<String>> {
|
||||
let attr = format!("hdrgm:{name}=");
|
||||
if let Some(i) = xmp.find(&attr) {
|
||||
let rest = xmp.get(i + attr.len()..)?;
|
||||
let q = rest.chars().next()?;
|
||||
if q == '"' || q == '\'' {
|
||||
let body = rest.get(1..)?;
|
||||
let end = body.find(q)?;
|
||||
return Some(vec![body.get(..end)?.to_string()]);
|
||||
}
|
||||
}
|
||||
let open = format!("<hdrgm:{name}>");
|
||||
let close = format!("</hdrgm:{name}>");
|
||||
let i = xmp.find(&open)?;
|
||||
let body = xmp.get(i + open.len()..)?;
|
||||
let body = body.get(..body.find(&close)?)?;
|
||||
let mut out = Vec::new();
|
||||
let mut rest = body;
|
||||
while let Some(a) = rest.find("<rdf:li>") {
|
||||
let after = rest.get(a + 8..)?;
|
||||
let b = after.find("</rdf:li>")?;
|
||||
out.push(after.get(..b)?.to_string());
|
||||
rest = after.get(b..)?;
|
||||
if out.len() > 3 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
// a plain element value
|
||||
out.push(body.trim().to_string());
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
struct Reader<'a> {
|
||||
b: &'a [u8],
|
||||
at: usize,
|
||||
}
|
||||
|
||||
impl Reader<'_> {
|
||||
fn take<const N: usize>(&mut self) -> Option<[u8; N]> {
|
||||
let s = self.b.get(self.at..self.at.checked_add(N)?)?;
|
||||
self.at += N;
|
||||
s.try_into().ok()
|
||||
}
|
||||
fn u8(&mut self) -> Option<u8> {
|
||||
self.take::<1>().map(|a| a[0])
|
||||
}
|
||||
fn u16(&mut self) -> Option<u16> {
|
||||
self.take().map(u16::from_be_bytes)
|
||||
}
|
||||
fn u32(&mut self) -> Option<u32> {
|
||||
self.take().map(u32::from_be_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// A gain map image: `channels` (1 or 3) interleaved 8-bit codes.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GainImage {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub channels: usize,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl GainImage {
|
||||
/// Bilinear code of channel `c` at gain map coordinates (`x`, `y`) (pixel centres at +0.5).
|
||||
fn sample(&self, x: f32, y: f32, c: usize) -> f32 {
|
||||
let (w, h) = (self.width, self.height);
|
||||
let fx = (x - 0.5).clamp(0.0, (w - 1) as f32);
|
||||
let fy = (y - 0.5).clamp(0.0, (h - 1) as f32);
|
||||
let (x0, y0) = (fx as usize, fy as usize);
|
||||
let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1));
|
||||
let (tx, ty) = (fx - x0 as f32, fy - y0 as f32);
|
||||
let at = |x: usize, y: usize| self.data.get((y * w + x) * self.channels + c).copied().unwrap_or(0) as f32;
|
||||
let a = at(x0, y0) + (at(x1, y0) - at(x0, y0)) * tx;
|
||||
let b = at(x0, y1) + (at(x1, y1) - at(x0, y1)) * tx;
|
||||
a + (b - a) * ty
|
||||
}
|
||||
}
|
||||
|
||||
/// How [`compute`] builds the map.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct GainMapOptions {
|
||||
/// Downscale factor of the map (1, 2 or 4).
|
||||
pub scale: usize,
|
||||
/// Three gains (R, G, B) instead of one luminance gain. Apple's readers want a single
|
||||
/// channel, so this is off by default.
|
||||
pub multichannel: bool,
|
||||
pub gamma: f32,
|
||||
/// Offsets added to SDR and HDR before the ratio (keep blacks finite and noise quiet).
|
||||
pub offset: f32,
|
||||
}
|
||||
|
||||
impl Default for GainMapOptions {
|
||||
fn default() -> Self {
|
||||
GainMapOptions { scale: 2, multichannel: false, gamma: 1.0, offset: 1.0 / 64.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Measure the gain map that turns `sdr` into `hdr` (both `width × height` linear RGB in the same
|
||||
/// primaries; `luma` = that space's luminance weights).
|
||||
pub fn compute(
|
||||
sdr: &[[f32; 3]],
|
||||
hdr: &[[f32; 3]],
|
||||
width: usize,
|
||||
height: usize,
|
||||
luma: [f32; 3],
|
||||
o: &GainMapOptions,
|
||||
) -> Result<(GainImage, GainMapMeta)> {
|
||||
let n = width.checked_mul(height).ok_or_else(|| Error::Encode("gain map: image too large".into()))?;
|
||||
if n == 0 || sdr.len() < n || hdr.len() < n {
|
||||
return Err(Error::Encode("gain map: SDR and HDR renditions must match the image size".into()));
|
||||
}
|
||||
if !(matches!(o.scale, 1 | 2 | 4) && o.gamma > 0.0 && o.gamma.is_finite() && o.offset > 0.0 && o.offset.is_finite()) {
|
||||
return Err(Error::Encode("gain map: scale must be 1, 2 or 4, gamma and offset positive".into()));
|
||||
}
|
||||
let s = o.scale;
|
||||
let (gw, gh) = (width.div_ceil(s), height.div_ceil(s));
|
||||
let ch = if o.multichannel { 3 } else { 1 };
|
||||
let y = |p: &[f32; 3]| luma[0] * p[0] + luma[1] * p[1] + luma[2] * p[2];
|
||||
let ratio = |a: f32, b: f32| ((b.max(0.0) + o.offset) / (a.max(0.0) + o.offset)).log2();
|
||||
// block means of the log gains
|
||||
let mut gains = vec![0f32; gw * gh * ch];
|
||||
let mut lo = [f32::MAX; 3];
|
||||
let mut hi = [f32::MIN; 3];
|
||||
for gy in 0..gh {
|
||||
for gx in 0..gw {
|
||||
let mut acc = [0f32; 3];
|
||||
let mut count = 0f32;
|
||||
for yy in gy * s..((gy + 1) * s).min(height) {
|
||||
for xx in gx * s..((gx + 1) * s).min(width) {
|
||||
let i = yy * width + xx;
|
||||
let (Some(a), Some(b)) = (sdr.get(i), hdr.get(i)) else { continue };
|
||||
if o.multichannel {
|
||||
for c in 0..3 {
|
||||
acc[c] += ratio(a[c], b[c]);
|
||||
}
|
||||
} else {
|
||||
acc[0] += ratio(y(a), y(b));
|
||||
}
|
||||
count += 1.0;
|
||||
}
|
||||
}
|
||||
for c in 0..ch {
|
||||
let g = if count > 0.0 { acc[c] / count } else { 0.0 };
|
||||
let g = if g.is_finite() { g } else { 0.0 };
|
||||
gains[(gy * gw + gx) * ch + c] = g;
|
||||
lo[c] = lo[c].min(g);
|
||||
hi[c] = hi[c].max(g);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut m = GainMapMeta {
|
||||
multichannel: o.multichannel,
|
||||
gamma: [o.gamma; 3],
|
||||
base_offset: [o.offset; 3],
|
||||
alternate_offset: [o.offset; 3],
|
||||
..GainMapMeta::default()
|
||||
};
|
||||
for c in 0..ch {
|
||||
// the range always includes 0 (no change) so an SDR-only area encodes exactly
|
||||
m.min[c] = lo[c].min(0.0);
|
||||
m.max[c] = hi[c].max(m.min[c] + 1e-4);
|
||||
}
|
||||
if !o.multichannel {
|
||||
m.fill_from_first();
|
||||
}
|
||||
m.base_headroom = 0.0;
|
||||
m.alternate_headroom = m.max.iter().copied().fold(0.0f32, f32::max).max(1e-3);
|
||||
let data = gains
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, g)| {
|
||||
let c = i % ch;
|
||||
let norm = ((g - m.min[c]) / (m.max[c] - m.min[c])).clamp(0.0, 1.0);
|
||||
(norm.powf(o.gamma) * 255.0).round() as u8
|
||||
})
|
||||
.collect();
|
||||
Ok((GainImage { width: gw, height: gh, channels: ch, data }, m))
|
||||
}
|
||||
|
||||
/// Rebuild the HDR rendition in place: `base` (`width × height` linear RGB) is replaced by the
|
||||
/// rendition at `weight` (0 = the base, 1 = the full alternate rendition; a display with headroom
|
||||
/// `H` uses `(H − base_headroom) / (alternate_headroom − base_headroom)`, clamped).
|
||||
pub fn apply(base: &mut [[f32; 3]], width: usize, height: usize, gain: &GainImage, m: &GainMapMeta, weight: f32) -> Result<()> {
|
||||
let n = width.checked_mul(height).ok_or_else(|| Error::Encode("gain map: image too large".into()))?;
|
||||
if base.len() < n
|
||||
|| gain.width == 0
|
||||
|| gain.height == 0
|
||||
|| !matches!(gain.channels, 1 | 3)
|
||||
|| gain.data.len() < gain.width * gain.height * gain.channels
|
||||
{
|
||||
return Err(Error::Encode("gain map: base and gain map sizes don't match".into()));
|
||||
}
|
||||
if !m.is_valid() {
|
||||
return Err(Error::Encode("gain map: unusable metadata".into()));
|
||||
}
|
||||
let weight = if weight.is_finite() { weight.clamp(0.0, 1.0) } else { 1.0 };
|
||||
let (sx, sy) = (gain.width as f32 / width as f32, gain.height as f32 / height as f32);
|
||||
let inv_gamma = m.gamma.map(|g| 1.0 / g);
|
||||
for (i, p) in base.iter_mut().enumerate().take(n) {
|
||||
let (x, y) = ((i % width) as f32 + 0.5, (i / width) as f32 + 0.5);
|
||||
let (gx, gy) = (x * sx, y * sy);
|
||||
let mut g = [0f32; 3];
|
||||
for (c, gc) in g.iter_mut().enumerate() {
|
||||
let src = if gain.channels == 3 { c } else { 0 };
|
||||
let norm = (gain.sample(gx, gy, src) / 255.0).clamp(0.0, 1.0).powf(inv_gamma[c]);
|
||||
*gc = m.min[c] + (m.max[c] - m.min[c]) * norm;
|
||||
}
|
||||
for c in 0..3 {
|
||||
let v = (p[c] + m.base_offset[c]) * (g[c] * weight).exp2() - m.alternate_offset[c];
|
||||
p[c] = v.max(0.0);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The primary image's container XMP: `hdrgm:Version` (marks the file as a gain map image for
|
||||
/// Adobe/Google readers) and the Container directory naming the gain map and its length.
|
||||
fn primary_description(gain_len: usize) -> String {
|
||||
format!(
|
||||
concat!(
|
||||
r#"<rdf:Description rdf:about="" xmlns:Container="http://ns.google.com/photos/1.0/container/" xmlns:Item="http://ns.google.com/photos/1.0/container/item/" xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/" hdrgm:Version="1.0">"#,
|
||||
r#"<Container:Directory><rdf:Seq>"#,
|
||||
r#"<rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="Primary" Item:Mime="image/jpeg"/></rdf:li>"#,
|
||||
r#"<rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="GainMap" Item:Mime="image/jpeg" Item:Length="{}"/></rdf:li>"#,
|
||||
r#"</rdf:Seq></Container:Directory></rdf:Description>"#
|
||||
),
|
||||
gain_len
|
||||
)
|
||||
}
|
||||
|
||||
/// `xmp` with `description` added as another `rdf:Description` (a fresh packet when there is
|
||||
/// none, or when it has no `rdf:RDF` to add to).
|
||||
fn merge_xmp(xmp: Option<&str>, description: &str) -> String {
|
||||
if let Some(x) = xmp
|
||||
&& let Some(i) = x.rfind("</rdf:RDF>")
|
||||
&& let (Some(a), Some(b)) = (x.get(..i), x.get(i..))
|
||||
{
|
||||
return format!("{a}{description}{b}");
|
||||
}
|
||||
format!("{XMP_OPEN}{description}{XMP_CLOSE}")
|
||||
}
|
||||
|
||||
/// Offsets within the MPF payload (from "MPF\0"): the endian field, then the index IFD (3 tags).
|
||||
const MPF_ENTRIES_FROM_ENDIAN: usize = 8 + 2 + 3 * 12 + 4;
|
||||
|
||||
@@ -598,11 +72,9 @@ pub fn encode_jpeg(base: &EncodeImage, gain: &GainImage, m: &GainMapMeta, qualit
|
||||
let gain_segs = vec![(0xE1, xmp_segment(&m.to_gain_map_xmp())?), (0xE2, m.to_iso())];
|
||||
let gain_jpeg = jpeg_par::encode(&gain.data, gain.width, gain.height, gain.channels, quality, ChromaSubsampling::S444, &gain_segs);
|
||||
|
||||
let xmp = merge_xmp(meta.xmp, &primary_description(gain_jpeg.len()));
|
||||
let xmp = craft_gainmap::primary_xmp(meta.xmp, gain_jpeg.len());
|
||||
let mut segs = jpeg_app_segments(&EncodeMeta { xmp: Some(&xmp), ..*meta })?;
|
||||
let mut iso_marker = ISO_URN.to_vec();
|
||||
iso_marker.extend_from_slice(&[0, 0, 0, 0]); // versions only: "this image has a gain map"
|
||||
segs.push((0xE2, iso_marker));
|
||||
segs.push((0xE2, craft_gainmap::primary_iso_marker()));
|
||||
segs.push((0xE2, mpf_placeholder()));
|
||||
let mut primary = jpeg_par::encode(data, w, h, base.channels as usize, quality, sub, &segs);
|
||||
|
||||
@@ -672,77 +144,6 @@ pub fn is_gain_map_jpeg(bytes: &[u8]) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn meta3() -> GainMapMeta {
|
||||
GainMapMeta {
|
||||
multichannel: true,
|
||||
use_base_colour_space: true,
|
||||
base_headroom: 0.0,
|
||||
alternate_headroom: 2.5,
|
||||
min: [-0.25, -0.5, 0.0],
|
||||
max: [2.5, 2.25, 2.0],
|
||||
gamma: [1.0, 1.25, 0.75],
|
||||
base_offset: [0.015625; 3],
|
||||
alternate_offset: [0.015625, 0.03125, 0.015625],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iso_metadata_round_trips() {
|
||||
for m in [GainMapMeta { alternate_headroom: 3.0, max: [3.0; 3], ..GainMapMeta::default() }, meta3()] {
|
||||
let p = m.to_iso();
|
||||
assert!(p.starts_with(ISO_URN));
|
||||
let back = GainMapMeta::from_iso(&p[ISO_URN.len()..]).unwrap();
|
||||
for (a, b) in [(back.min, m.min), (back.max, m.max), (back.gamma, m.gamma), (back.alternate_offset, m.alternate_offset)] {
|
||||
for c in 0..3 {
|
||||
assert!((a[c] - b[c]).abs() < 1e-6, "{a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(back.multichannel, m.multichannel);
|
||||
assert!((back.alternate_headroom - m.alternate_headroom).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iso_common_denominator_and_rejections() {
|
||||
// common-denominator form, single channel: d = 4, headrooms 0 and 2, min 0, max 2, gamma 1, offsets 0
|
||||
let mut p = vec![0, 0, 0, 0, FLAG_COMMON_DENOMINATOR];
|
||||
for v in [4u32, 0, 8, 0, 8, 4, 0, 0] {
|
||||
p.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
let m = GainMapMeta::from_iso(&p).unwrap();
|
||||
assert_eq!((m.alternate_headroom, m.max[2], m.gamma[1]), (2.0, 2.0, 1.0));
|
||||
// versions only (a primary image's marker), unknown version, truncated, backward
|
||||
assert!(GainMapMeta::from_iso(&[0, 0, 0, 0]).is_none());
|
||||
assert!(GainMapMeta::from_iso(&[0, 1, 0, 0, 0]).is_none());
|
||||
assert!(GainMapMeta::from_iso(&p[..p.len() - 1]).is_none());
|
||||
let mut back = p.clone();
|
||||
back[4] |= FLAG_BACKWARD;
|
||||
assert!(GainMapMeta::from_iso(&back).is_none());
|
||||
// a zero denominator is rejected, not divided by
|
||||
let mut z = p.clone();
|
||||
z[5..9].copy_from_slice(&0u32.to_be_bytes());
|
||||
assert!(GainMapMeta::from_iso(&z).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hdrgm_xmp_round_trips_including_per_channel_sequences() {
|
||||
for m in [GainMapMeta { alternate_headroom: 2.0, max: [2.0; 3], ..GainMapMeta::default() }, meta3()] {
|
||||
let x = m.to_gain_map_xmp();
|
||||
assert!(x.contains("apdi:AuxiliaryImageType"));
|
||||
if m.multichannel {
|
||||
assert!(x.contains("<hdrgm:GainMapMax><rdf:Seq><rdf:li>2.5</rdf:li>"), "{x}");
|
||||
}
|
||||
let back = GainMapMeta::from_hdrgm_xmp(&x).unwrap();
|
||||
assert_eq!(back.multichannel, m.multichannel);
|
||||
for c in 0..3 {
|
||||
assert!((back.max[c] - m.max[c]).abs() < 1e-5 && (back.gamma[c] - m.gamma[c]).abs() < 1e-5);
|
||||
}
|
||||
assert!((back.alternate_headroom - m.alternate_headroom).abs() < 1e-5);
|
||||
}
|
||||
assert!(GainMapMeta::from_hdrgm_xmp("<x hdrgm:Version=\"1.0\"/>").is_none(), "no GainMapMax");
|
||||
assert!(GainMapMeta::from_hdrgm_xmp("hdrgm:GainMapMax=\"nope\"").is_none());
|
||||
}
|
||||
|
||||
fn renditions(w: usize, h: usize) -> (Vec<[f32; 3]>, Vec<[f32; 3]>) {
|
||||
// a ramp: SDR rolls off at 1, HDR keeps going to 6
|
||||
let hdr: Vec<[f32; 3]> = (0..w * h)
|
||||
@@ -765,31 +166,6 @@ mod tests {
|
||||
(sdr, hdr)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_then_apply_recovers_the_hdr_rendition() {
|
||||
let (w, h) = (64, 8);
|
||||
let (sdr, hdr) = renditions(w, h);
|
||||
for multichannel in [false, true] {
|
||||
let o = GainMapOptions { scale: 1, multichannel, ..GainMapOptions::default() };
|
||||
let (g, m) = compute(&sdr, &hdr, w, h, [0.2126, 0.7152, 0.0722], &o).unwrap();
|
||||
assert!(m.is_valid() && m.alternate_headroom > 1.0);
|
||||
let mut out = sdr.clone();
|
||||
apply(&mut out, w, h, &g, &m, 1.0).unwrap();
|
||||
for (a, b) in out.iter().zip(&hdr) {
|
||||
for c in 0..3 {
|
||||
// 8-bit codes over the gain range: within ~2 % in linear light
|
||||
assert!((a[c] - b[c]).abs() <= 0.03 * b[c] + 0.01, "{multichannel}: {a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
// weight 0 is the base
|
||||
let mut base = sdr.clone();
|
||||
apply(&mut base, w, h, &g, &m, 0.0).unwrap();
|
||||
for (a, b) in base.iter().zip(&sdr) {
|
||||
assert!((a[0] - b[0]).abs() < 1e-5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gain_map_wider_than_a_jpeg_allows_is_refused() {
|
||||
let base = [0u8; 3];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! HEIF / HEIC (the iPhone and Mac photo format), read-only.
|
||||
//!
|
||||
//! Decoding lives in the optional `lightcraft-heif` crate (heic-rs, a pure-Rust HEVC
|
||||
//! Decoding lives in the optional `craft-heif` crate (heic-rs, a pure-Rust HEVC
|
||||
//! still-picture decoder, plus a libheif-matching colour conversion), enabled by this crate's
|
||||
//! `heif` feature — off by default because HEVC is patent-encumbered and whether a build carries
|
||||
//! an HEVC decoder is the distributor's call (the same policy as the sibling PhotoCraft). Without
|
||||
@@ -35,10 +35,10 @@ pub(crate) fn header(_bytes: &[u8]) -> Result<(u32, u32, u16)> {
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
fn err(e: lightcraft_heif::Error) -> Error {
|
||||
fn err(e: craft_heif::Error) -> Error {
|
||||
match e {
|
||||
lightcraft_heif::Error::Unsupported(why) => Error::Unsupported(F, why),
|
||||
lightcraft_heif::Error::Limit(m) | lightcraft_heif::Error::Malformed(m) => Error::Malformed(F, m),
|
||||
craft_heif::Error::Unsupported(why) => Error::Unsupported(F, why),
|
||||
craft_heif::Error::Limit(m) | craft_heif::Error::Malformed(m) => Error::Malformed(F, m),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,24 +46,24 @@ fn err(e: lightcraft_heif::Error) -> Error {
|
||||
/// alone: no picture is decoded.
|
||||
#[cfg(feature = "heif")]
|
||||
pub(crate) fn header(bytes: &[u8]) -> Result<(u32, u32, u16)> {
|
||||
let info = lightcraft_heif::probe(bytes).map_err(err)?;
|
||||
let info = craft_heif::probe(bytes).map_err(err)?;
|
||||
Ok((info.width, info.height, 1))
|
||||
}
|
||||
|
||||
#[cfg(feature = "heif")]
|
||||
pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
|
||||
// The container alone: the declared size is checked before any pixel is decoded.
|
||||
let info = lightcraft_heif::probe(bytes).map_err(err)?;
|
||||
let info = craft_heif::probe(bytes).map_err(err)?;
|
||||
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 = lightcraft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true };
|
||||
let options = craft_heif::Options { max_pixels: opts.max_pixels, apply_transforms: true, ..craft_heif::Options::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.
|
||||
let thumb = match opts.max_size {
|
||||
Some((mw, mh)) if mw > 0 && mh > 0 && mw.max(mh) < info.width.max(info.height) => {
|
||||
lightcraft_heif::decode_thumbnail(bytes, mw.max(mh), &options).ok().flatten().filter(|t| {
|
||||
craft_heif::decode_thumbnail(bytes, mw.max(mh), &options).ok().flatten().filter(|t| {
|
||||
// Only a thumbnail of the same picture: same orientation and aspect within 1 %.
|
||||
let aspect = |w: u32, h: u32| w as f64 / h.max(1) as f64;
|
||||
(aspect(t.width, t.height) / aspect(info.width, info.height) - 1.0).abs() < 0.01
|
||||
@@ -73,7 +73,7 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
|
||||
};
|
||||
let mut decoded = match thumb {
|
||||
Some(t) => t,
|
||||
None => lightcraft_heif::decode(bytes, &options).map_err(err)?,
|
||||
None => craft_heif::decode(bytes, &options).map_err(err)?,
|
||||
};
|
||||
let raw = Raw {
|
||||
width: decoded.width as usize,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! HEIC/HEIF through the codec API (feature `heif`), on lossless synthetic files from
|
||||
//! `lightcraft_heif::testdata`: an iPhone-like grid with a Display P3 profile, rotation, EXIF, a
|
||||
//! `craft_heif::testdata`: an iPhone-like grid with a Display P3 profile, rotation, EXIF, a
|
||||
//! thumbnail and an HDR gain map; `nclx`-only colour; 10-bit; and hostile input.
|
||||
|
||||
use craft_heif::testdata::{Prop, Spec, build};
|
||||
use lightcraft_codecs::*;
|
||||
use lightcraft_heif::testdata::{Prop, Spec, build};
|
||||
|
||||
fn grey(x: u32, y: u32) -> [u16; 3] {
|
||||
[((x * 7 + y * 13) % 220 + 20) as u16, 128, 128]
|
||||
|
||||
@@ -66,6 +66,6 @@ lightcraft-testkit = { workspace = true }
|
||||
# HDR JPEG XL tests read the file's colour encoding
|
||||
jxl-oxide = { workspace = true }
|
||||
# Lossless synthetic HEIC files (the import test; decoded when the codecs' `heif` feature is on).
|
||||
lightcraft-heif = { workspace = true, features = ["testdata"] }
|
||||
craft-heif = { workspace = true, features = ["testdata"] }
|
||||
libc = { workspace = true }
|
||||
lightcraft-tiff = { workspace = true }
|
||||
craft-tiff = { workspace = true }
|
||||
|
||||
@@ -489,12 +489,11 @@ pub fn export_effects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if chosen.is_empty() {
|
||||
return Err(bad(C, "no effect presets to export"));
|
||||
}
|
||||
if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(dir).map_err(|e| crate::EngineError::Other(format!("{}: {e}", dir.display())))?;
|
||||
}
|
||||
let target = path.to_string_lossy();
|
||||
s.check_write_target(&target).map_err(|e| bad(C, e))?;
|
||||
let text = serde_json::to_string_pretty(&json!({"format": FILE_FORMAT, "version": 2, "effects": chosen}))
|
||||
.map_err(|e| crate::EngineError::Other(e.to_string()))?;
|
||||
std::fs::write(&path, text).map_err(|e| crate::EngineError::Other(format!("{}: {e}", path.display())))?;
|
||||
crate::export::write_file_durable(&target, text.as_bytes()).map_err(crate::EngineError::Other)?;
|
||||
Ok(json!({"path": path.display().to_string(), "count": chosen.len()}))
|
||||
}
|
||||
|
||||
|
||||
@@ -281,7 +281,7 @@ fn tiff_with_preview_strip(strip: &[u8], tail: usize, what: Fixture) -> Vec<u8>
|
||||
/// [`tiff_with_preview_strip`] that also keeps the `smaller` JPEGs in sub-IFDs of IFD0, as an ARW keeps its
|
||||
/// 1616 px preview beside the full-size one.
|
||||
fn tiff_with_preview_strips(strip: &[u8], smaller: &[&[u8]], tail: usize, what: Fixture) -> Vec<u8> {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
let mut preview = IfdBuilder::new();
|
||||
if what.dng {
|
||||
preview.set(t::DNG_VERSION, Value::Byte(vec![1, 4, 0, 0]));
|
||||
@@ -662,7 +662,7 @@ fn corpus_a7cr_warp_keeps_coordinates_after_orientation_and_resizing() {
|
||||
let Ok(mut bytes) = std::fs::read(root.join("raw").join(name)) else { continue };
|
||||
let off = lightcraft_raw::probe_info(&bytes).unwrap();
|
||||
assert!(embedded_lens(&off).is_none());
|
||||
let tiff = lightcraft_tiff::Tiff::parse(&bytes).unwrap();
|
||||
let tiff = craft_tiff::Tiff::parse(&bytes).unwrap();
|
||||
let at = tiff.find(0x7036).unwrap().offset as usize;
|
||||
let mut enabled = Vec::new();
|
||||
tiff.order.put_u16(&mut enabled, 17);
|
||||
@@ -1220,8 +1220,8 @@ fn corpus_clipped_sky_beside_a_tree_has_no_coloured_halo() {
|
||||
/// copy's samples are much brighter than the image's here, so a picture says which one it came from.
|
||||
#[test]
|
||||
fn exports_never_develop_a_dngs_reduced_copy() {
|
||||
use lightcraft_tiff::tags::{self as t, photometric};
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::tags::{self as t, photometric};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use serde_json::json;
|
||||
let linear = |subfile: u32, w: u32, h: u32, sample: u16| {
|
||||
let mut ifd = IfdBuilder::new();
|
||||
@@ -1298,10 +1298,10 @@ fn exports_never_develop_a_dngs_reduced_copy() {
|
||||
/// heuristic would never look) is used; a matte with an unknown name is ignored.
|
||||
#[test]
|
||||
fn dng_sky_matte_drives_the_sky_mask() {
|
||||
use craft_tiff::tags::{self as t, photometric};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use lightcraft_develop::{DevelopSettings, LocalAdjustments, Mask, MaskComponent, MaskOp, MaskShape};
|
||||
use lightcraft_pipeline::{RenderRequest, render};
|
||||
use lightcraft_tiff::tags::{self as t, photometric};
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let (w, h) = (16u32, 8u32);
|
||||
let image = |ifd: &mut IfdBuilder, w: u32, h: u32, cpp: u16, bits: u16, data: Vec<u8>| {
|
||||
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![w]));
|
||||
@@ -1536,7 +1536,7 @@ fn unsupported_raw_imports_as_preview_only_and_survives_reopen() {
|
||||
/// A raw whose TIFF shell holds only a small RGB image (IFD0) next to a private block, as Exif
|
||||
/// declares a picture 25x its size.
|
||||
fn tiff_shell(w: u32, h: u32, shell: bool) -> Vec<u8> {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
let mut ifd0 = IfdBuilder::new();
|
||||
ifd0.set(t::IMAGE_WIDTH, Value::Long(vec![w]));
|
||||
ifd0.set(t::IMAGE_LENGTH, Value::Long(vec![h]));
|
||||
@@ -1577,7 +1577,7 @@ fn thumbnail_only_tiff_raw_is_preview_only_not_a_plain_image() {
|
||||
|
||||
// TIFFs preserving camera Make tags (SONY, NIKON, etc.) are ordinary images, not raws (#281)
|
||||
for make in ["SONY", "NIKON CORPORATION", "PENTAX", "RICOH", "SAMSUNG"] {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
let mut ifd0 = IfdBuilder::new();
|
||||
ifd0.set(t::IMAGE_WIDTH, Value::Long(vec![24]));
|
||||
ifd0.set(t::IMAGE_LENGTH, Value::Long(vec![16]));
|
||||
@@ -1621,7 +1621,7 @@ fn undecodable_container_with_a_preview_imports_as_preview_only() {
|
||||
/// holds the preview) imports as a raw shown from its preview, not as a greyscale image of the mosaic.
|
||||
#[test]
|
||||
fn uncompressed_leaf_mos_imports_as_a_preview_only_raw() {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
let px: Vec<u8> = (0..40 * 30).flat_map(|i| [(i % 251) as u8, 128, 200]).collect();
|
||||
let jpeg = encode_jpeg(&EncodeImage::new(40, 30, 3, Samples::U8(&px)), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap();
|
||||
let mos = |leaf_data: bool| {
|
||||
@@ -1652,7 +1652,7 @@ fn uncompressed_leaf_mos_imports_as_a_preview_only_raw() {
|
||||
/// headers; loading it says what is wrong instead of naming a bare TIFF compression number.
|
||||
#[test]
|
||||
fn gopro_vc5_dng_imports_and_fails_to_load_with_a_clear_reason() {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
let mut ifd = IfdBuilder::new();
|
||||
ifd.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0]));
|
||||
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![32]));
|
||||
@@ -1681,7 +1681,7 @@ fn decode_failures_of_recognised_raws_may_fall_back_to_the_preview() {
|
||||
assert_eq!(preview_reason(b"x", RawError::Unsupported("x".into())), Ok("x".to_string()));
|
||||
assert!(preview_reason(b"x", RawError::Corrupt("bad strip".into())).is_ok_and(|w| w.contains("bad strip")));
|
||||
assert!(preview_reason(b"x", RawError::Limit("too big")).is_ok());
|
||||
assert!(preview_reason(b"x", RawError::Tiff(lightcraft_tiff::TiffError::MissingTag(256))).is_ok());
|
||||
assert!(preview_reason(b"x", RawError::Tiff(craft_tiff::TiffError::MissingTag(256))).is_ok());
|
||||
assert!(preview_reason(b"x", RawError::NotRaw).is_err());
|
||||
assert!(preview_reason(cr3, RawError::Corrupt("bad".into())).is_ok_and(|w| w.starts_with("CR3 ")));
|
||||
}
|
||||
@@ -1746,8 +1746,8 @@ fn a_quick_thumbnail_without_an_embedded_preview_renders_the_raw() {
|
||||
/// A Sony ARW of `model`: a 64 × 48 uncompressed 14-bit CFA strip in a SubIFD (as `crates/raw/tests/it/vendor_robust.rs`
|
||||
/// lays it out) whose IFD carries the full-frame 16–35 mm distortion table (tag 0x7037).
|
||||
fn sony_arw(model: &str) -> Vec<u8> {
|
||||
use lightcraft_tiff::tags::{self as t, photometric};
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::tags::{self as t, photometric};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
// 3:2, the aspect Sony's lens opcodes are limited to
|
||||
let (w, h) = (72u32, 48u32);
|
||||
let mut raw = IfdBuilder::new();
|
||||
|
||||
@@ -224,8 +224,15 @@ impl crate::Session {
|
||||
/// without building the guard over the whole library.
|
||||
pub fn check_write_target(&self, path: &str) -> Result<(), String> {
|
||||
let path = Path::new(path);
|
||||
if std::fs::symlink_metadata(path).is_err() && !is_xmp(path) {
|
||||
return Ok(()); // nothing there to replace, and no sidecar to create
|
||||
if std::fs::symlink_metadata(path).is_err() {
|
||||
// `missing/../IMG_1.jpg` names an existing file once the writer creates `missing`, so a
|
||||
// `..` that cannot be resolved now cannot be checked: refuse it.
|
||||
if path.components().any(|c| c == std::path::Component::ParentDir) && std::fs::canonicalize(folder_of(path)).is_err() {
|
||||
return Err(format!("{}: the folder part has `..` components that cannot be resolved; use a path without them", path.display()));
|
||||
}
|
||||
if !is_xmp(path) {
|
||||
return Ok(()); // nothing there to replace, and no sidecar to create
|
||||
}
|
||||
}
|
||||
self.original_guard().check(path)
|
||||
}
|
||||
|
||||
@@ -374,6 +374,8 @@ fn library_with_jpeg(tag: &str) -> (Session, lightcraft_catalog::PhotoId, std::p
|
||||
|
||||
fn preset_export_preserves_originals(command: &str, selection: serde_json::Value, tag: &str) {
|
||||
let (mut s, _, dir, src, original) = library_with_jpeg(tag);
|
||||
// something for mask.exportEffects to write (the other commands ignore it)
|
||||
s.mask_effects.push(crate::cmd::mask_effects::MaskEffect { name: "Glow".into(), ..Default::default() });
|
||||
let sidecar = src.with_extension("xmp");
|
||||
let appended_sidecar = dir.join("IMG_1.jpg.xmp");
|
||||
std::fs::write(&sidecar, b"existing sidecar").unwrap();
|
||||
@@ -399,6 +401,14 @@ fn preset_export_preserves_originals(command: &str, selection: serde_json::Value
|
||||
assert_eq!(std::fs::read(&sidecar).unwrap(), b"existing sidecar");
|
||||
assert_eq!(std::fs::read(&appended_sidecar).unwrap(), b"appended sidecar");
|
||||
}
|
||||
// `..` through a folder that does not exist yet could reach the original once it is created
|
||||
let mut params = selection.clone();
|
||||
params["path"] = json!(dir.join("missing/../IMG_1.jpg").to_string_lossy());
|
||||
let error = s.execute(command, ¶ms).unwrap_err().to_string();
|
||||
// Windows resolves `..` lexically and finds the original; Unix cannot resolve it and refuses
|
||||
assert!(error.contains("cannot be resolved") || error.contains("never writes over an original"), "{error}");
|
||||
assert!(!dir.join("missing").exists());
|
||||
assert_eq!(std::fs::read(&src).unwrap(), original);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
@@ -460,9 +470,12 @@ fn keyword_export_preserves_the_previous_file_on_write_failure() {
|
||||
fn preset_exports_preserve_previous_files_on_write_failure() {
|
||||
let dir = temp_dir("preset-export-failure");
|
||||
let mut s = Session::new();
|
||||
for (command, selection, file) in
|
||||
[("preset.export", json!({"ids": ["lc.warm-glow"]}), "look.lcpreset"), ("curve.exportPresets", json!({"names": ["Linear"]}), "curve.lccurve")]
|
||||
{
|
||||
s.mask_effects.push(crate::cmd::mask_effects::MaskEffect { name: "Glow".into(), ..Default::default() });
|
||||
for (command, selection, file) in [
|
||||
("preset.export", json!({"ids": ["lc.warm-glow"]}), "look.lcpreset"),
|
||||
("curve.exportPresets", json!({"names": ["Linear"]}), "curve.lccurve"),
|
||||
("mask.exportEffects", json!({"names": ["Glow"]}), "effects.lceffect"),
|
||||
] {
|
||||
let path = dir.join(file);
|
||||
let mut params = selection;
|
||||
params["path"] = json!(path.to_string_lossy());
|
||||
@@ -475,10 +488,15 @@ fn preset_exports_preserve_previous_files_on_write_failure() {
|
||||
assert_eq!(std::fs::read(&path).unwrap(), previous, "{command} preserves the prior export");
|
||||
assert_eq!(s.execute(command, ¶ms).unwrap()["count"], 1, "replacement still succeeds");
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2, "no temporary files remain");
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 3, "no temporary files remain");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mask_effect_export_never_overwrites_originals_or_sidecars() {
|
||||
preset_export_preserves_originals("mask.exportEffects", json!({"names": ["Glow"]}), "effect-export-guard");
|
||||
}
|
||||
|
||||
fn disk_batch(
|
||||
s: &mut Session,
|
||||
id: lightcraft_catalog::PhotoId,
|
||||
|
||||
@@ -46,7 +46,7 @@ fn jpeg(w: u32, h: u32, px: impl Fn(u32, u32) -> [u8; 3]) -> Vec<u8> {
|
||||
/// photo by its largest preview (600 × 400) and the develop path renders from it, after reading
|
||||
/// the whole file.
|
||||
fn raw_with_two_previews(tail: usize) -> Vec<u8> {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
let preview = |w: u32, h: u32, bytes: Vec<u8>, first: bool| {
|
||||
let mut ifd = IfdBuilder::new();
|
||||
if first {
|
||||
|
||||
@@ -34,7 +34,7 @@ fn write_png(path: &Path, seed: u8) {
|
||||
}
|
||||
|
||||
fn exif_clock_block(original: Option<&str>, digitized: Option<&str>) -> Vec<u8> {
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
|
||||
|
||||
let mut exif = IfdBuilder::new();
|
||||
if let Some(value) = original {
|
||||
@@ -2820,7 +2820,7 @@ fn a_file_gone_since_the_import_review_is_not_imported() {
|
||||
/// a JPEG. In a build without the codecs' `heif` feature it is reported as failed, saying why.
|
||||
#[test]
|
||||
fn heic_imports_as_a_normal_photo_or_says_why_not() {
|
||||
use lightcraft_heif::testdata::{Prop, Spec, build};
|
||||
use craft_heif::testdata::{Prop, Spec, build};
|
||||
let src = temp_dir("heic");
|
||||
let photo = |x: u32, y: u32| [((x * 7 + y * 13) % 200 + 30) as u16, 110, 150];
|
||||
let p3 = lightcraft_codecs::icc::write_named(lightcraft_codecs::NamedSpace::DisplayP3);
|
||||
@@ -2857,8 +2857,8 @@ fn heic_imports_as_a_normal_photo_or_says_why_not() {
|
||||
/// writes as UTC: an iPhone photo landed five hours late and after 19:00 on the wrong day.
|
||||
#[test]
|
||||
fn a_heic_is_dated_by_its_exif_and_not_by_the_file() {
|
||||
use lightcraft_heif::testdata::{Spec, build};
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t};
|
||||
use craft_heif::testdata::{Spec, build};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t};
|
||||
let src = temp_dir("heic-capture-time");
|
||||
let photo = |x: u32, y: u32| [((x * 7 + y * 13) % 200 + 30) as u16, 110, 150];
|
||||
let mut exif = IfdBuilder::new();
|
||||
|
||||
@@ -638,7 +638,7 @@ fn an_orientation_only_the_xmp_states_leaves_stored_frame_regions_as_written() {
|
||||
let img = lightcraft_raster::Rgba8::from_fn(32, 24, |x, y| [(x * 7) as u8, (y * 9) as u8, 90, 255]);
|
||||
// an Exif that states the size as stored (32 × 24, as cameras do) and no orientation
|
||||
let exif = {
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t};
|
||||
let mut sub = IfdBuilder::new();
|
||||
sub.set(t::PIXEL_X_DIMENSION, Value::Long(vec![32]));
|
||||
sub.set(t::PIXEL_Y_DIMENSION, Value::Long(vec![24]));
|
||||
@@ -681,7 +681,7 @@ fn a_raws_decoder_orientation_turns_stored_frame_regions_on_import_and_reread()
|
||||
let px: Vec<u16> = (0..16 * 6).map(|i| (i * 41 % 4096) as u16).collect();
|
||||
let strip: Vec<u8> = px.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 15) << 4) as u8 | (p[1] >> 8) as u8, p[1] as u8]).collect();
|
||||
{
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
let mut raw = IfdBuilder::new();
|
||||
raw.set(t::NEW_SUBFILE_TYPE, Value::Long(vec![0]));
|
||||
raw.set(t::IMAGE_WIDTH, Value::Long(vec![16]));
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
[package]
|
||||
name = "lightcraft-heif"
|
||||
description = "Optional HEIF/HEIC still-image decoder for LightCraft (heic-rs for the container and HEVC, libheif-matching colour conversion, panic-guarded)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
# Pure Rust, no unsafe. Pinned exactly: a young, single-owner crate that parses untrusted files;
|
||||
# moving the pin is a reviewed change (re-run the heif tests and the codecs corpus tests).
|
||||
# Mirrors PhotoCraft's photocraft-heif (same team, same decision): heic-rs was chosen over the
|
||||
# other permissive candidates (heif-oxide's HEVC decoder, rust_h265, follows FFmpeg's (LGPL)
|
||||
# code structure; gamut-heic has no HEVC decoder of its own).
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std"] }
|
||||
|
||||
# The tiles of a HEIC photo decode in parallel on native; wasm stays single-threaded.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"] }
|
||||
rayon = { workspace = true }
|
||||
|
||||
[features]
|
||||
# `lightcraft_heif::testdata`: lossless synthetic HEIF files, for the tests of the crates above.
|
||||
testdata = []
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,47 +0,0 @@
|
||||
# lightcraft-heif
|
||||
|
||||
The optional HEIF / HEIC decoder of LightCraft: iPhone and Mac photos. [`heic-rs`](https://github.com/tbraun96/heic-rs)
|
||||
(pure Rust, no `unsafe`, MIT OR Apache-2.0, written from the H.265 / HEIF specifications) reads the
|
||||
container and reconstructs the HEVC pictures; this crate turns them into 16-bit RGB itself so the
|
||||
result matches libheif to within one code value:
|
||||
|
||||
- the colour description is the item's `colr nclx` (or its first tile's), else the HEVC VUI
|
||||
(iPhones: full range), else the H.265 defaults; an unspecified matrix is BT.601. heic-rs alone
|
||||
assumes BT.709 limited range, about 8 code values off on every iPhone photo;
|
||||
- chroma is upsampled by nearest neighbour, or centred bilinear when a `clap` starts on an odd
|
||||
pixel, as libheif does;
|
||||
- `imir` axis 0 flips top and bottom, as libheif writes and reads it (heic-rs names it the other way);
|
||||
- a grid's ICC profile may sit on its tiles.
|
||||
|
||||
Single pictures and grid-tiled photos, 4:2:0 and monochrome, 8- to 10-bit, alpha auxiliary images
|
||||
(other auxiliary images — HDR gain maps, depth — are ignored), the container's rotation/mirror/crop,
|
||||
ICC, EXIF and XMP, and the file's thumbnail item. 4:2:2 and 4:4:4 (Canon/Sony "HIF") are refused
|
||||
with `Error::Unsupported`: heic-rs 0.1.1 loses sync on them. Read-only.
|
||||
|
||||
```rust
|
||||
let info = lightcraft_heif::probe(&bytes)?; // size, depth, alpha: check limits first
|
||||
let img = lightcraft_heif::decode(&bytes, &lightcraft_heif::Options::default())?;
|
||||
// img.width, img.height, img.has_alpha, img.bit_depth, img.data (RGB/RGBA u16), img.colour, img.icc, img.exif, img.xmp
|
||||
let thumb = lightcraft_heif::decode_thumbnail(&bytes, 256, &Default::default())?; // Option<Decoded>
|
||||
```
|
||||
|
||||
Errors are `Error::Unsupported` (image sequences, overlays, 4:2:2/4:4:4, …), `Error::Limit` or
|
||||
`Error::Malformed`. It never panics: every call into heic-rs runs under `catch_unwind`, and a panic
|
||||
inside it (PhotoCraft's fuzzing found two in 0.1.1) becomes `Error::Malformed`.
|
||||
|
||||
Feature `testdata` exposes `lightcraft_heif::testdata`: lossless synthetic HEIF files (PCM-coded
|
||||
32 × 32 HEVC pictures, grids, every property above) for the tests of the crates above.
|
||||
|
||||
## Why it is a separate, optional crate
|
||||
|
||||
- **A young decoder.** heic-rs is new and has a single maintainer. It is pinned exactly
|
||||
(`=0.1.1`); moving the pin is a reviewed change (re-run the crate tests and
|
||||
`cargo test -p lightcraft-codecs --features heif`). The other permissive candidates were
|
||||
rejected: heif-oxide's HEVC decoder (rust_h265) follows FFmpeg's (LGPL) code structure, and
|
||||
gamut-heic has no HEVC decoder of its own.
|
||||
- **HEVC patents are a distributor's call.** `lightcraft-codecs` uses this crate only behind its
|
||||
non-default `heif` feature; the apps forward it and the release packages enable it. Without it,
|
||||
HEIC files are still recognised and opening one is a clear "HEIC/HEIF support isn't included in
|
||||
this build" error — the same policy as PhotoCraft.
|
||||
|
||||
The crate depends on no other LightCraft crate; `codecs` → `heif` is the only edge between them.
|
||||
@@ -1,122 +0,0 @@
|
||||
//! Caps on the container's metadata boxes, counted before heic-rs touches the file.
|
||||
//!
|
||||
//! heic-rs 0.1.4 (pinned `=0.1.4`) has no aggregate work budget inside its container parsing:
|
||||
//! every `ipma` association entry rescans the vector of already-seen item ids (quadratic in
|
||||
//! the number of entries), and an `iloc` extent using construction method 2 reconstructs its
|
||||
//! source item afresh for every extent that references it, with no shared cache. Legitimate
|
||||
//! phone-photo metadata never comes near these caps — real corpora keep both well under a few
|
||||
//! kilobytes — so anything above them is hostile or corrupt and is refused before the
|
||||
//! countable CPU work happens.
|
||||
//!
|
||||
//! [`depth_boxes`] stops silently at structural blips: heic-rs's own parser reports those
|
||||
//! better than this walk could, and an `ipma` box past the cap is caught wherever it parses.
|
||||
|
||||
use heic_rs::boxes::BoxIter;
|
||||
|
||||
use crate::Error;
|
||||
|
||||
/// The largest `ipma` box (item ↔ property associations) payload accepted, 64 KiB. An entry
|
||||
/// costs at least 3 bytes, so this bounds heic-rs's per-entry rescan of earlier item ids to
|
||||
/// ~21 000 entries ≈ 220 million comparisons: long enough to be annoying, never minutes.
|
||||
const MAX_IPMA_BYTES: usize = 64 << 10;
|
||||
|
||||
/// The largest `iloc` box (item locations) payload accepted, 64 KiB. An extent costs at least
|
||||
/// 12 bytes, so this bounds both the parse itself and how many extents a
|
||||
/// construction-method-2 reconstruction chain can visit.
|
||||
const MAX_ILOC_BYTES: usize = 64 << 10;
|
||||
|
||||
/// Falls through unless the container declares more `ipma` or `iloc` payload than a
|
||||
/// legitimate phone photo ever does.
|
||||
pub fn cap(bytes: &[u8]) -> Result<(), Error> {
|
||||
let mut c = Census::default();
|
||||
depth_boxes(&mut c, BoxIter::new(bytes), 0);
|
||||
if c.ipma > MAX_IPMA_BYTES {
|
||||
return Err(Error::Limit(format!("the image carries {} bytes of property associations, over the {MAX_IPMA_BYTES}-byte cap", c.ipma)));
|
||||
}
|
||||
if c.iloc > MAX_ILOC_BYTES {
|
||||
return Err(Error::Limit(format!("the image carries {} bytes of item locations, over the {MAX_ILOC_BYTES}-byte cap", c.iloc)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The metadata-box payload sizes seen so far.
|
||||
#[derive(Default)]
|
||||
struct Census {
|
||||
ipma: usize,
|
||||
iloc: usize,
|
||||
}
|
||||
|
||||
/// Walks boxes, adding the payload sizes of those named in [`Census`].
|
||||
///
|
||||
/// Only `meta` and `iprp` (the two nesting boxes the metadata is built from) are descended
|
||||
/// into, no deeper than that depth, so a nested-box trick can't hide a box from the count.
|
||||
fn depth_boxes(c: &mut Census, boxes: BoxIter<'_>, depth: u32) {
|
||||
if depth > 3 {
|
||||
return;
|
||||
}
|
||||
for b in boxes {
|
||||
// A structural error stops the walk; `heic_rs::probe` reports it properly afterwards.
|
||||
let Ok(b) = b else { return };
|
||||
if b.is(b"ipma") {
|
||||
c.ipma = c.ipma.saturating_add(b.payload.len());
|
||||
} else if b.is(b"iloc") {
|
||||
c.iloc = c.iloc.saturating_add(b.payload.len());
|
||||
} else if b.is(b"meta") {
|
||||
// `meta` is a FullBox: version and flags sit between its header and its children.
|
||||
if b.payload.len() >= 4 {
|
||||
depth_boxes(c, BoxIter::new(&b.payload[4..]), depth + 1);
|
||||
}
|
||||
} else if b.is(b"iprp") {
|
||||
depth_boxes(c, b.children(), depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Assembles ftyp + meta(version/flags + iprp(ipco, ipma)) by hand; only the structure
|
||||
/// the census walks matters, no item is ever defined.
|
||||
fn file_with(ipma_payload: &[u8]) -> Vec<u8> {
|
||||
let mut out = b"\0\0\0\x18ftypheic\0\0\0\0mif1heic".to_vec();
|
||||
let mut iprp = Vec::new();
|
||||
iprp.extend(box_of(b"ipco", b""));
|
||||
iprp.extend(box_of(b"ipma", ipma_payload));
|
||||
let mut meta = vec![0u8, 0, 0, 0]; // version 0, flags 0
|
||||
meta.extend(box_of(b"iprp", &iprp));
|
||||
out.extend(box_of(b"meta", &meta));
|
||||
out
|
||||
}
|
||||
|
||||
fn box_of(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(8 + body.len());
|
||||
let size = u32::try_from(8 + body.len()).expect("test box fits in u32");
|
||||
out.extend_from_slice(&size.to_be_bytes());
|
||||
out.extend_from_slice(kind);
|
||||
out.extend_from_slice(body);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_ipma_is_refused() {
|
||||
// 40 000 entries of 6 bytes: 240 KiB of ipma, far over the cap, and quadratic if
|
||||
// parsed (each entry rescans the earlier item ids in heic-rs 0.1.4).
|
||||
let mut ipma = Vec::new();
|
||||
for _ in 0..40_000u32 {
|
||||
ipma.extend_from_slice(&[0u8, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
let bytes = file_with(&ipma);
|
||||
let r = crate::probe(&bytes).map(|_| ());
|
||||
assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("associations")), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_undersized_ipma_is_untouched_by_the_caps() {
|
||||
// The same shape with a normal ipma (two entries): the caps pass, and whatever error
|
||||
// follows must not come from them.
|
||||
let bytes = file_with(&[0, 0, 4, 1, 1, 2, 0, 0]);
|
||||
let r = crate::probe(&bytes);
|
||||
assert!(!matches!(r, Err(Error::Limit(ref m)) if m.contains("cap")), "{r:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,605 +0,0 @@
|
||||
//! `lightcraft-heif`: the optional HEIF / HEIC (iPhone and Mac photo) decoder.
|
||||
//!
|
||||
//! `heic-rs`, a pure-Rust HEIF container and HEVC still-picture decoder, reads the container and
|
||||
//! reconstructs the coded pictures (bit-exact against libde265 on iPhone photos); this crate turns
|
||||
//! them into RGB itself ([`ycc`]) so the colours match libheif: it honours the HEVC VUI's range
|
||||
//! and matrix ([`vui`]) where heic-rs assumes BT.709 limited range, and upsamples chroma like
|
||||
//! libheif. Single pictures and grid-tiled photos, 8- to 16-bit, monochrome, alpha auxiliary
|
||||
//! images, ICC, EXIF and XMP. The API is plain data ([`Info`], [`Decoded`], [`Error`]) so the
|
||||
//! crate knows nothing about the rest of LightCraft; `lightcraft-codecs` adapts it behind its
|
||||
//! `heif` feature. Shares heic-rs and its regression fixtures with PhotoCraft's `photocraft-heif`.
|
||||
//!
|
||||
//! HEIF records orientation in the container (`irot`/`imir`, plus a `clap` crop), not in EXIF.
|
||||
//! [`Options::apply_transforms`] applies them; with it off, the pixels come back as coded.
|
||||
//! Auxiliary images other than alpha (HDR gain maps, depth maps) are ignored.
|
||||
//!
|
||||
//! Never panics: heic-rs is young, so every call into it runs under `catch_unwind` and a panic
|
||||
//! inside it becomes [`Error::Malformed`].
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod census;
|
||||
mod orient;
|
||||
/// Lossless synthetic HEIF files for tests, here and in the crates above (feature `testdata`).
|
||||
#[cfg(any(test, feature = "testdata"))]
|
||||
#[doc(hidden)]
|
||||
pub mod testdata;
|
||||
mod vui;
|
||||
mod ycc;
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use heic_rs::context::Context;
|
||||
use heic_rs::hevc::Frame;
|
||||
use heic_rs::props::ItemProps;
|
||||
use heic_rs::props::colr::Range;
|
||||
|
||||
/// What a HEIF file declares, read from the container alone (no pixel is decoded).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Info {
|
||||
/// Size after the container transforms (rotation, mirror, crop): what a viewer shows.
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Size as coded, before the transforms.
|
||||
pub coded_width: u32,
|
||||
pub coded_height: u32,
|
||||
/// The primary image has an alpha auxiliary image.
|
||||
pub has_alpha: bool,
|
||||
/// Bits per sample as coded (8 for most photos, 10 for HDR-capable ones).
|
||||
pub bit_depth: u8,
|
||||
}
|
||||
|
||||
/// Decode settings.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Options {
|
||||
/// Refuse images with more pixels than this (checked before decoding).
|
||||
pub max_pixels: u64,
|
||||
/// Apply the container's rotation, mirror and crop (`irot`/`imir`/`clap`).
|
||||
pub apply_transforms: bool,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Options { max_pixels: 1 << 28, apply_transforms: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// How the file describes its colour: the code points of ITU-T H.273, from the `colr` `nclx`
|
||||
/// box, else the HEVC VUI, else the standard defaults (2 = unspecified, limited range).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Colour {
|
||||
pub primaries: u16,
|
||||
pub transfer: u16,
|
||||
pub matrix: u16,
|
||||
pub full_range: bool,
|
||||
}
|
||||
|
||||
/// A decoded image: interleaved RGB or RGBA, 16 bits per sample whatever the coded depth,
|
||||
/// row-major, no padding.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Decoded {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Four channels (RGBA) instead of three (RGB).
|
||||
pub has_alpha: bool,
|
||||
/// Bits per sample as coded.
|
||||
pub bit_depth: u8,
|
||||
pub data: Vec<u16>,
|
||||
pub colour: Colour,
|
||||
/// The primary image's ICC profile.
|
||||
pub icc: Option<Vec<u8>>,
|
||||
/// EXIF as a TIFF structure (without HEIF's offset header). Its Orientation tag only mirrors
|
||||
/// what the container says; it is returned verbatim.
|
||||
pub exif: Option<Vec<u8>>,
|
||||
/// The XMP packet.
|
||||
pub xmp: Option<String>,
|
||||
}
|
||||
|
||||
/// Why a file could not be decoded.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
/// A valid file using something this decoder does not handle (image sequences, overlays…).
|
||||
Unsupported(&'static str),
|
||||
/// The image is larger than [`Options::max_pixels`] or holds an oversized box.
|
||||
Limit(String),
|
||||
/// Broken or truncated data (or a decoder bug, reported the same way).
|
||||
Malformed(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Error::Unsupported(m) => write!(f, "unsupported HEIF: {m}"),
|
||||
Error::Limit(m) => write!(f, "limit exceeded: {m}"),
|
||||
Error::Malformed(m) => write!(f, "malformed HEIF: {m}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
const SEQUENCE: &str = "this file holds an image sequence; only HEIF still images can be opened";
|
||||
|
||||
/// heic-rs 0.1.1 reconstructs 4:2:0 and monochrome pictures exactly but fails on the 4:2:2 and
|
||||
/// 4:4:4 ones some cameras write (Canon and Sony "HIF"); those failures are reported as this.
|
||||
const CHROMA_422_444: &str = "4:2:2 and 4:4:4 HEIF images (as some Canon and Sony cameras write) can't be decoded yet";
|
||||
|
||||
pub(crate) fn err(e: heic_rs::Error) -> Error {
|
||||
match e {
|
||||
heic_rs::Error::Unsupported(what) => Error::Unsupported(what),
|
||||
// The primary item is neither an HEVC picture nor a grid of them.
|
||||
heic_rs::Error::MissingBox("hvcC") => Error::Unsupported("the image is an overlay, an identity derivation or not HEVC-coded"),
|
||||
heic_rs::Error::PixelLimit { .. } | heic_rs::Error::BoxTooLarge { .. } => Error::Limit(e.to_string()),
|
||||
e => Error::Malformed(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f`, turning a heic-rs panic into an error. Fuzzing in the sibling app found two
|
||||
/// out-of-range slices in heic-rs 0.1.1 on malformed files: in its box parser (`boxes.rs:130`)
|
||||
/// and during reconstruction (`hevc/decode/recon.rs:70`).
|
||||
fn guarded<T>(f: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|_| Err(Error::Malformed("the HEIF decoder failed on this file".into())))
|
||||
}
|
||||
|
||||
/// Reads the container's declared size, depth and alpha without decoding pixels, so callers can
|
||||
/// check their limits first. Also refuses a file cut short: every coded picture of the primary
|
||||
/// image must lie within `bytes`.
|
||||
pub fn probe(bytes: &[u8]) -> Result<Info, Error> {
|
||||
guarded(|| probe_unguarded(bytes))
|
||||
}
|
||||
|
||||
fn probe_unguarded(bytes: &[u8]) -> Result<Info, Error> {
|
||||
census::cap(bytes)?;
|
||||
// No `meta` box: no still image, only a `moov` image sequence (a video track).
|
||||
let open_error = |e| match e {
|
||||
heic_rs::Error::MissingBox("meta") => Error::Unsupported(SEQUENCE),
|
||||
e => err(e),
|
||||
};
|
||||
let ctx = Context::open(bytes).map_err(open_error)?;
|
||||
let id = ctx.meta.primary;
|
||||
// heic-rs 0.1.4 caps the size of what it assembles, not the work: an item built from other
|
||||
// items (`iloc` construction method 2) is rebuilt once per extent, so a chain of such items
|
||||
// multiplies at every level while each result stays small. Count those visits from the
|
||||
// `iloc` table before reconstructing anything: the primary item first (`heic_rs::probe` and
|
||||
// `Context::grid` both rebuild its descriptor), then its alpha plane and, when that is a grid,
|
||||
// its tiles, then every tile reference, repeats included.
|
||||
let mut visits = 0_usize;
|
||||
item_visits(&ctx, id, 0, &mut visits)?;
|
||||
// `heic_rs::probe` reads an item without `ispe` from its parameter sets
|
||||
check_item_parameter_sets(&ctx.props(id).map_err(err)?)?;
|
||||
let info = heic_rs::probe(bytes).map_err(open_error)?;
|
||||
let alpha = ctx.alpha_item(id).map_err(err)?;
|
||||
if let Some(alpha) = alpha {
|
||||
item_visits(&ctx, alpha, 0, &mut visits)?;
|
||||
// an alpha plane may be a grid too: its tiles are rebuilt when it is decoded
|
||||
if let Some((_, tiles)) = ctx.grid(alpha).map_err(err)? {
|
||||
for &tile in tiles.iter().filter(|&&tile| tile != alpha) {
|
||||
item_visits(&ctx, tile, 0, &mut visits)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut coded = match ctx.grid(id).map_err(err)? {
|
||||
Some((_, tiles)) => tiles,
|
||||
None => vec![id],
|
||||
};
|
||||
for &item in coded.iter().filter(|&&item| item != id) {
|
||||
item_visits(&ctx, item, 0, &mut visits)?;
|
||||
}
|
||||
// A `dimg` listing may name the same tile more than once, and reconstructable items are
|
||||
// moreover rebuilt for every extent that references them in heic-rs 0.1.4. For the size
|
||||
// check each unique item counts once: the total reconstruction (all of it assembled from
|
||||
// `bytes` by heic-rs) is held below one copy of the file, above which a repeat or chain
|
||||
// wants more bytes than exist. Order doesn't matter here: this only checks that every
|
||||
// tile's bytes lie in the file.
|
||||
coded.sort_unstable();
|
||||
coded.dedup();
|
||||
let mut reconstructed = 0_usize;
|
||||
for item in coded {
|
||||
reconstructed = reconstructed.saturating_add(ctx.item_data(item).map_err(err)?.len());
|
||||
if reconstructed > bytes.len() {
|
||||
return Err(Error::Limit(format!(
|
||||
"the container holds {reconstructed} bytes of item data, over the {} bytes of the file itself",
|
||||
bytes.len()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(Info {
|
||||
width: info.width,
|
||||
height: info.height,
|
||||
coded_width: info.coded_width,
|
||||
coded_height: info.coded_height,
|
||||
has_alpha: info.has_alpha,
|
||||
bit_depth: info.bit_depth,
|
||||
})
|
||||
}
|
||||
|
||||
/// Most extent visits heic-rs may spend reconstructing the primary image's coded items; real
|
||||
/// files need one per tile (plus a few for the rare derived item).
|
||||
const MAX_ITEM_VISITS: usize = 4096;
|
||||
/// Deepest chain of items built from items we follow (heic-rs refuses beyond eight itself).
|
||||
const MAX_ITEM_CHAIN: u32 = 8;
|
||||
|
||||
/// Adds to `visits` the extents heic-rs would read to reconstruct `id`, following items built
|
||||
/// from other items, and fails once that passes [`MAX_ITEM_VISITS`] or the chain is too deep.
|
||||
fn item_visits(ctx: &Context<'_>, id: u32, depth: u32, visits: &mut usize) -> Result<(), Error> {
|
||||
use heic_rs::meta::iloc::Construction;
|
||||
if depth > MAX_ITEM_CHAIN {
|
||||
return Err(Error::Limit(format!("items built from items nest deeper than {MAX_ITEM_CHAIN} levels")));
|
||||
}
|
||||
let Some(loc) = ctx.meta.location(id) else { return Ok(()) };
|
||||
*visits = visits.saturating_add(loc.extents.len().max(1));
|
||||
if *visits > MAX_ITEM_VISITS {
|
||||
return Err(Error::Limit(format!("reconstructing the image takes over {MAX_ITEM_VISITS} item extent reads")));
|
||||
}
|
||||
if loc.construction == Construction::Item {
|
||||
for e in &loc.extents {
|
||||
if let Ok(source) = u32::try_from(e.index)
|
||||
&& source != id
|
||||
{
|
||||
item_visits(ctx, source, depth + 1, visits)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decodes the primary image, with its metadata.
|
||||
pub fn decode(bytes: &[u8], options: &Options) -> Result<Decoded, Error> {
|
||||
guarded(|| decode_unguarded(bytes, options))
|
||||
}
|
||||
|
||||
/// Decodes the smallest thumbnail image the file carries whose long edge is at least
|
||||
/// `min_edge`, if any (iPhones store one of about 320 × 240). Transforms are applied as for the
|
||||
/// primary image; the metadata (and, when the thumbnail has no profile of its own, the ICC
|
||||
/// profile) are the primary image's.
|
||||
pub fn decode_thumbnail(bytes: &[u8], min_edge: u32, options: &Options) -> Result<Option<Decoded>, Error> {
|
||||
guarded(|| {
|
||||
let ctx = Context::open(bytes).map_err(err)?;
|
||||
let primary = ctx.meta.primary;
|
||||
let mut best: Option<(u32, u32)> = None;
|
||||
// A thumbnail whose own reconstruction would cost too much is not a candidate; the visits
|
||||
// of all the candidates share one budget.
|
||||
let mut candidate_visits = 0_usize;
|
||||
for r in ctx.meta.refs.iter().filter(|r| r.kind == heic_rs::meta::iref::RefKind::Thmb && r.to.contains(&primary)) {
|
||||
if item_visits(&ctx, r.from, 0, &mut candidate_visits).is_err() {
|
||||
continue;
|
||||
}
|
||||
let Ok(p) = ctx.props(r.from) else { continue };
|
||||
if check_item_parameter_sets(&p).is_err() {
|
||||
continue;
|
||||
}
|
||||
// A grid whose tile would fail the same check must not win and then fail in
|
||||
// `decode_item`, with no fallback to a larger valid thumbnail.
|
||||
let grid = match ctx.grid(r.from) {
|
||||
Ok(grid) => grid,
|
||||
// an unreadable grid fails in `decode_item` too: not a candidate
|
||||
Err(_) => continue,
|
||||
};
|
||||
if let Some((_, tiles)) = grid {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let tiles_ok = tiles.iter().filter(|t| seen.insert(**t)).all(|&t| {
|
||||
item_visits(&ctx, t, 0, &mut candidate_visits).is_ok() && ctx.props(t).is_ok_and(|tp| check_item_parameter_sets(&tp).is_ok())
|
||||
});
|
||||
if !tiles_ok {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Ok((w, h)) = ctx.coded_size(r.from, &p) else { continue };
|
||||
let edge = w.max(h);
|
||||
if edge >= min_edge && best.is_none_or(|(_, e)| edge < e) {
|
||||
best = Some((r.from, edge));
|
||||
}
|
||||
}
|
||||
let Some((id, _)) = best else { return Ok(None) };
|
||||
// The same pre-scan as `probe`: the thumbnail's own descriptor and every tile reference
|
||||
// are counted before heic-rs rebuilds any of them.
|
||||
let mut visits = 0_usize;
|
||||
item_visits(&ctx, id, 0, &mut visits)?;
|
||||
if let Some((_, tiles)) = ctx.grid(id).map_err(err)? {
|
||||
for &tile in &tiles {
|
||||
item_visits(&ctx, tile, 0, &mut visits)?;
|
||||
}
|
||||
}
|
||||
let mut decoded = decode_item(&ctx, id, options, false)?;
|
||||
if decoded.icc.is_none() {
|
||||
decoded.icc = item_icc(&ctx, primary);
|
||||
}
|
||||
(decoded.exif, decoded.xmp) = metadata(&ctx);
|
||||
Ok(Some(decoded))
|
||||
})
|
||||
}
|
||||
|
||||
/// An item's ICC profile; a grid whose own properties carry none takes its first tile's (as on
|
||||
/// some iPhones).
|
||||
fn item_icc(ctx: &Context<'_>, id: u32) -> Option<Vec<u8>> {
|
||||
let p = ctx.props(id).ok()?;
|
||||
let icc = p.icc.or_else(|| {
|
||||
let (_, tiles) = ctx.grid(id).ok()??;
|
||||
ctx.props(*tiles.first()?).ok()?.icc
|
||||
});
|
||||
icc.map(<[u8]>::to_vec)
|
||||
}
|
||||
|
||||
fn decode_unguarded(bytes: &[u8], options: &Options) -> Result<Decoded, Error> {
|
||||
// Refuses sequences with a clear message before anything else is read.
|
||||
probe_unguarded(bytes)?;
|
||||
let ctx = Context::open(bytes).map_err(err)?;
|
||||
let mut decoded = decode_item(&ctx, ctx.meta.primary, options, true)?;
|
||||
let (exif, xmp) = metadata(&ctx);
|
||||
decoded.exif = exif;
|
||||
decoded.xmp = xmp;
|
||||
Ok(decoded)
|
||||
}
|
||||
|
||||
/// Decodes one image item (a coded picture or a grid of them) to RGB(A), alpha included when
|
||||
/// `with_alpha` and the item has an alpha auxiliary image.
|
||||
fn decode_item(ctx: &Context<'_>, id: u32, options: &Options, with_alpha: bool) -> Result<Decoded, Error> {
|
||||
let p = ctx.props(id).map_err(err)?;
|
||||
// heic-rs 0.1.4 keeps every associated transform and its [`orient::apply`] allocates the
|
||||
// full picture again for each: a file could chain the repetition and multiply decode CPU
|
||||
// without changing any checked size. Real files carry at most one `clap`, `irot` and
|
||||
// `imir`, so refuse anything approaching [`MAX_TRANSFORMS`] (CodeRabbit #44).
|
||||
if p.transforms.len() > MAX_TRANSFORMS {
|
||||
return Err(Error::Limit(format!("the image carries {} transform properties, over the {MAX_TRANSFORMS}-property cap", p.transforms.len())));
|
||||
}
|
||||
let limit = options.max_pixels;
|
||||
// The declared sizes are refused before anything is decoded or allocated (an item without
|
||||
// `ispe` takes its size from its parameter sets, checked first).
|
||||
check_item_parameter_sets(&p)?;
|
||||
let (cw, ch) = ctx.coded_size(id, &p).map_err(err)?;
|
||||
heic_rs::image::check_pixels(cw, ch, limit).map_err(err)?;
|
||||
let (tw, th) = heic_rs::transform::transformed_size(cw, ch, &p.transforms).map_err(err)?;
|
||||
heic_rs::image::check_pixels(tw, th, limit).map_err(err)?;
|
||||
|
||||
let coded = Coded::decode(ctx, id, &p, limit)?;
|
||||
let planes = coded.planes()?;
|
||||
let colour = colour(&p, &coded.first_props);
|
||||
let signal = ycc::Signal { matrix: colour.matrix, full_range: colour.full_range };
|
||||
let alpha_id = if with_alpha { ctx.alpha_item(id).map_err(err)? } else { None };
|
||||
let (w, h) = planes.size();
|
||||
// A grid's canvas dimensions come from its payload, not the checked `ispe` (CodeRabbit
|
||||
// #48): check the real one, before [`ycc::to_rgb16`] allocates for it.
|
||||
match (u32::try_from(w), u32::try_from(h)) {
|
||||
(Ok(wu), Ok(hu)) => {
|
||||
heic_rs::image::check_pixels(wu, hu, limit).map_err(err)?;
|
||||
}
|
||||
_ => return Err(Error::Limit(format!("the image canvas is {w}x{h}, beyond the {limit}-pixel limit"))),
|
||||
}
|
||||
let mode = if options.apply_transforms && orient::odd_crop(w, h, &p.transforms)? { ycc::Upsampling::Bilinear } else { ycc::Upsampling::Nearest };
|
||||
let mut data = ycc::to_rgb16(&planes, signal, alpha_id.is_some(), mode)
|
||||
.ok_or_else(|| Error::Malformed("the decoded pictures don't cover the image".into()))?;
|
||||
if let Some(aux) = alpha_id {
|
||||
let ap = ctx.props(aux).map_err(err)?;
|
||||
let alpha = Coded::decode(ctx, aux, &ap, limit)?;
|
||||
let alpha_planes = alpha.planes()?;
|
||||
if alpha_planes.size() != (w, h) {
|
||||
return Err(Error::Unsupported("an alpha image of a different size than the picture"));
|
||||
}
|
||||
ycc::put_alpha(&alpha_planes, &mut data).ok_or_else(|| Error::Malformed("the alpha image is incomplete".into()))?;
|
||||
}
|
||||
let bit_depth = planes.bit_depth();
|
||||
let has_alpha = alpha_id.is_some();
|
||||
let mut img = orient::Pixels { width: w, height: h, ch: if has_alpha { 4 } else { 3 }, data };
|
||||
if options.apply_transforms {
|
||||
img = orient::apply(img, &p.transforms)?;
|
||||
}
|
||||
Ok(Decoded {
|
||||
width: u32::try_from(img.width).map_err(|_| Error::Limit("image too wide".into()))?,
|
||||
height: u32::try_from(img.height).map_err(|_| Error::Limit("image too tall".into()))?,
|
||||
has_alpha,
|
||||
bit_depth,
|
||||
data: img.data,
|
||||
colour,
|
||||
// A grid whose own properties carry no profile takes its tiles' (as on some iPhones).
|
||||
icc: p.icc.or(coded.first_props.icc).map(<[u8]>::to_vec),
|
||||
exif: None,
|
||||
xmp: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// How many times `max_pixels` the coded pictures of one item may hold together: a grid's tiles
|
||||
/// cover its canvas rounded up to whole tiles, so legitimate grids sit near 1.
|
||||
const GRID_BUDGET: u64 = 2;
|
||||
|
||||
/// The most transform properties (`clap`/`irot`/`imir`) one item may carry. Real files have at
|
||||
/// most one of each, so anything approaching this is a reordered or hostile association list.
|
||||
const MAX_TRANSFORMS: usize = 12;
|
||||
|
||||
/// The most parameter sets one `hvcC` may carry: one per id H.265 allows (16 VPS, 16 SPS, 64 PPS).
|
||||
/// heic-rs 0.1.4 replaces a repeated id by scanning every set kept so far, so more sets (repeats,
|
||||
/// or ids past the standard's range) only make that collection quadratic.
|
||||
const MAX_PARAMETER_SETS: usize = 16 + 16 + 64;
|
||||
/// Highest `pps_pic_parameter_set_id` H.265 allows (7.4.3.3.1).
|
||||
const MAX_PPS_ID: u32 = 63;
|
||||
/// Most tile columns and rows a picture may have: H.265's level limits (Table A.8, levels 6 to
|
||||
/// 6.2). heic-rs 0.1.4 builds its tile tables by walking the tile boundaries for every coding tree
|
||||
/// block, so its work grows with blocks × tiles; these keep that a small multiple of the blocks.
|
||||
const MAX_TILE_COLS: u32 = 20;
|
||||
const MAX_TILE_ROWS: u32 = 22;
|
||||
|
||||
/// Refuses parameter sets that would make heic-rs's set collection or tile tables cost far more
|
||||
/// than the picture: too many sets, a PPS id out of range, or more tiles than any level allows.
|
||||
fn check_parameter_sets(sets: &[&[u8]]) -> Result<(), Error> {
|
||||
if sets.len() > MAX_PARAMETER_SETS {
|
||||
return Err(Error::Limit(format!("the hvcC record carries {} parameter sets, over the {MAX_PARAMETER_SETS}-set cap", sets.len())));
|
||||
}
|
||||
let layouts = vui::pps_layouts(sets).ok_or_else(|| Error::Malformed("unreadable picture parameter set".into()))?;
|
||||
for p in layouts {
|
||||
if p.id > MAX_PPS_ID {
|
||||
return Err(Error::Malformed(format!("picture parameter set id {} is out of range", p.id)));
|
||||
}
|
||||
if p.tile_cols > MAX_TILE_COLS || p.tile_rows > MAX_TILE_ROWS {
|
||||
return Err(Error::Limit(format!(
|
||||
"a picture of {} × {} tiles, over the {MAX_TILE_COLS} × {MAX_TILE_ROWS} H.265 allows",
|
||||
p.tile_cols, p.tile_rows
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`check_parameter_sets`] of a coded item's `hvcC`, if it has one.
|
||||
fn check_item_parameter_sets(p: &ItemProps<'_>) -> Result<(), Error> {
|
||||
p.hvcc.as_ref().map_or(Ok(()), |h| check_parameter_sets(&h.parameter_sets()))
|
||||
}
|
||||
|
||||
/// The decoded pictures of an item: one, or a grid's tiles in `dimg` order.
|
||||
struct Coded<'a> {
|
||||
frames: Vec<Frame>,
|
||||
grid: Option<heic_rs::grid::Grid>,
|
||||
/// The properties of the first coded picture (the item itself, or the first tile): where the
|
||||
/// HEVC configuration and its VUI live.
|
||||
first_props: ItemProps<'a>,
|
||||
/// A failed 4:2:2 / 4:4:4 picture, for the error message.
|
||||
chroma_format: u8,
|
||||
}
|
||||
|
||||
impl<'a> Coded<'a> {
|
||||
fn decode(ctx: &Context<'a>, id: u32, p: &ItemProps<'a>, limit: u64) -> Result<Coded<'a>, Error> {
|
||||
let (grid, ids) = match ctx.grid(id).map_err(err)? {
|
||||
Some((g, tiles)) => (Some(g), tiles),
|
||||
None => (None, vec![id]),
|
||||
};
|
||||
let first = *ids.first().ok_or_else(|| Error::Malformed("grid lists no tiles".into()))?;
|
||||
let first_props = if first == id { p.clone() } else { ctx.props(first).map_err(err)? };
|
||||
let chroma_format = first_props.hvcc.as_ref().map_or(1, |c| c.chroma_format);
|
||||
// #1518: the decoder allocates each picture at its SPS's uncropped size, which a
|
||||
// conformance window (or a slice picking another SPS) can make far larger than the
|
||||
// declared one, and a grid holds all its tiles at once. Both are refused before decoding.
|
||||
let mut total = 0u64;
|
||||
// A grid may list one tile thousands of times: each distinct tile is read and checked
|
||||
// once, so the work follows the file's items, not the grid's cell count.
|
||||
let mut largest_of: std::collections::HashMap<u32, u64> = std::collections::HashMap::new();
|
||||
for t in &ids {
|
||||
if let Some(largest) = largest_of.get(t) {
|
||||
total = total.saturating_add(*largest);
|
||||
continue;
|
||||
}
|
||||
let tp = ctx.props(*t).map_err(err)?;
|
||||
let hvcc = tp.hvcc.as_ref().ok_or(heic_rs::Error::MissingBox("hvcC")).map_err(err)?;
|
||||
check_parameter_sets(&hvcc.parameter_sets())?;
|
||||
let sizes = vui::coded_sizes(&hvcc.parameter_sets()).ok_or_else(|| Error::Malformed("unreadable sequence parameter set".into()))?;
|
||||
let mut largest = 0u64;
|
||||
for (w, h) in sizes {
|
||||
heic_rs::image::check_pixels(w, h, limit).map_err(err)?;
|
||||
largest = largest.max(u64::from(w) * u64::from(h));
|
||||
}
|
||||
largest_of.insert(*t, largest);
|
||||
total = total.saturating_add(largest);
|
||||
}
|
||||
if total > limit.saturating_mul(GRID_BUDGET) {
|
||||
return Err(Error::Limit(format!("the coded pictures hold {total} pixels, over the {limit}-pixel limit")));
|
||||
}
|
||||
let decode_one = |t: &u32| -> Result<Frame, Error> {
|
||||
let tp = ctx.props(*t).map_err(err)?;
|
||||
let hvcc = tp.hvcc.as_ref().ok_or(heic_rs::Error::MissingBox("hvcC")).map_err(err)?;
|
||||
let data = ctx.item_data(*t).map_err(err)?;
|
||||
let nals = hvcc.split_nals(&data).map_err(err)?;
|
||||
let params = hvcc.parameter_sets();
|
||||
if params.is_empty() {
|
||||
return Err(Error::Malformed("hvcC carries no parameter sets".into()));
|
||||
}
|
||||
let frame = heic_rs::hevc::decode_still(¶ms, &nals).map_err(err)?;
|
||||
frame.validate().map_err(err)?;
|
||||
heic_rs::image::check_pixels(frame.width, frame.height, limit).map_err(err)?;
|
||||
Ok(frame)
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let frames: Result<Vec<Frame>, Error> = {
|
||||
use rayon::prelude::*;
|
||||
ids.par_iter().map(decode_one).collect()
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let frames: Result<Vec<Frame>, Error> = ids.iter().map(decode_one).collect();
|
||||
let frames = frames.map_err(|e| match e {
|
||||
Error::Malformed(_) if chroma_format >= 2 => Error::Unsupported(CHROMA_422_444),
|
||||
e => e,
|
||||
})?;
|
||||
Ok(Coded { frames, grid, first_props, chroma_format })
|
||||
}
|
||||
|
||||
fn planes(&self) -> Result<ycc::Planes<'_>, Error> {
|
||||
match (&self.grid, self.frames.as_slice()) {
|
||||
(Some(g), tiles) => heic_rs::grid::Mosaic::new(g, tiles).map(ycc::Planes::Grid).map_err(err),
|
||||
(None, [frame]) => Ok(ycc::Planes::Picture(frame)),
|
||||
(None, _) => Err(Error::Malformed(format!("expected one coded picture (chroma format {})", self.chroma_format))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour description in force: `nclx` on the item (or, for a grid without one, on its
|
||||
/// first tile), else the VUI of its (first) coded picture, else the H.265 defaults.
|
||||
fn colour(p: &ItemProps<'_>, coded: &ItemProps<'_>) -> Colour {
|
||||
if let Some(n) = p.nclx.or(coded.nclx) {
|
||||
return Colour { primaries: n.primaries, transfer: n.transfer, matrix: n.matrix_code, full_range: n.range == Range::Full };
|
||||
}
|
||||
let s = coded.hvcc.as_ref().and_then(|c| vui::signal(&c.parameter_sets())).unwrap_or_default();
|
||||
Colour { primaries: s.primaries.into(), transfer: s.transfer.into(), matrix: s.matrix.into(), full_range: s.full_range }
|
||||
}
|
||||
|
||||
/// The primary image's EXIF (TIFF structure) and XMP packet. Metadata is a courtesy: a broken
|
||||
/// metadata item never fails a decode whose pixels came out fine.
|
||||
fn metadata(ctx: &Context<'_>) -> (Option<Vec<u8>>, Option<String>) {
|
||||
let id = ctx.meta.primary;
|
||||
// Metadata is best effort, so an item that would cost too much to rebuild is skipped, not an error.
|
||||
let mut visits = 0_usize;
|
||||
let cheap = |item: Option<u32>, visits: &mut usize| item.is_none_or(|item| item_visits(ctx, item, 0, visits).is_ok());
|
||||
let exif = if cheap(ctx.exif_item(id), &mut visits) { ctx.exif(id).ok().flatten().map(<[u8]>::to_vec) } else { None };
|
||||
let xmp_item = ctx.xmp_item(id).filter(|&x| cheap(Some(x), &mut visits));
|
||||
let xmp = xmp_item.and_then(|x| ctx.item_data(x).ok()).and_then(|d| match d {
|
||||
Cow::Borrowed(b) => String::from_utf8(b.to_vec()).ok(),
|
||||
Cow::Owned(b) => String::from_utf8(b).ok(),
|
||||
});
|
||||
(exif, xmp.map(|x| x.trim_end_matches('\0').to_string()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_synthetic;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Found by PhotoCraft's `decode_heif` fuzz target: a malformed box makes heic-rs 0.1.1 slice
|
||||
/// out of range (`boxes.rs:130`). It must be an error, not a crash.
|
||||
const HEIC_RS_BOX_PANIC: [u8; 72] = [
|
||||
0x00, 0x00, 0x00, 0x24, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x69, 0x66, 0x31, 0x4d, 0x69, 0x50,
|
||||
0x72, 0x6d, 0x69, 0x61, 0x66, 0x4d, 0x69, 0x48, 0x42, 0x72, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x65, 0x74, 0x61, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x75, 0x75, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00, 0x03, 0x08, 0x08, 0x08, 0x00, 0x03, 0x01, 0x03, 0x70,
|
||||
0x00, 0xa8, 0x00,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn a_heic_rs_panic_is_a_malformed_error() {
|
||||
for apply_transforms in [true, false] {
|
||||
let r = decode(&HEIC_RS_BOX_PANIC, &Options { apply_transforms, ..Default::default() });
|
||||
assert!(matches!(r, Err(Error::Malformed(_))), "{r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_sequence_is_unsupported_with_a_clear_message() {
|
||||
// An ftyp and nothing else: a HEIF image sequence would have a moov here instead of a meta.
|
||||
let bytes = b"\0\0\0\x18ftypmsf1\0\0\0\0msf1hevc";
|
||||
for r in [probe(bytes).map(|_| ()), decode(bytes, &Options::default()).map(|_| ())] {
|
||||
assert!(matches!(&r, Err(Error::Unsupported(m)) if m.contains("sequence")), "{r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_is_an_error() {
|
||||
for bytes in [&b""[..], b"\0\0\0\x18ftypheic\0\0\0\0mif1heic", &[0xFF; 64]] {
|
||||
assert!(probe(bytes).is_err());
|
||||
assert!(decode(bytes, &Options::default()).is_err());
|
||||
assert!(decode_thumbnail(bytes, 1, &Options::default()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_display_their_kind() {
|
||||
assert!(Error::Unsupported("x").to_string().contains("unsupported"));
|
||||
assert!(Error::Limit("x".into()).to_string().contains("limit"));
|
||||
assert!(Error::Malformed("x".into()).to_string().contains("malformed"));
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
//! The container's transformative properties (`clap` crop, `irot` rotation, `imir` mirror),
|
||||
//! applied to interleaved 16-bit pixels in the order the file associates them.
|
||||
//!
|
||||
//! `imir` follows libheif, which writes and reads `axis = 0` as a flip about the horizontal axis
|
||||
//! (top and bottom exchanged) and `axis = 1` as a left-right flip. heic-rs 0.1.1 names the coded
|
||||
//! values the other way round (`Mirror::LeftRight` is `axis = 0`), so they are swapped here.
|
||||
|
||||
use heic_rs::props::Transform;
|
||||
use heic_rs::props::simple::{Clap, Mirror, Rotation};
|
||||
|
||||
use crate::Error;
|
||||
|
||||
/// Interleaved samples, `ch` per pixel, row-major.
|
||||
pub struct Pixels {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub ch: usize,
|
||||
pub data: Vec<u16>,
|
||||
}
|
||||
|
||||
impl Pixels {
|
||||
fn remap(&self, width: usize, height: usize, src: impl Fn(usize, usize) -> (usize, usize)) -> Pixels {
|
||||
let ch = self.ch;
|
||||
let mut data = vec![0u16; width * height * ch];
|
||||
for (y, row) in data.chunks_exact_mut(width * ch).enumerate() {
|
||||
for (x, px) in row.chunks_exact_mut(ch).enumerate() {
|
||||
let (sx, sy) = src(x, y);
|
||||
let i = (sy * self.width + sx) * ch;
|
||||
if let Some(s) = self.data.get(i..i + ch) {
|
||||
px.copy_from_slice(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
Pixels { width, height, ch, data }
|
||||
}
|
||||
}
|
||||
|
||||
/// The rectangle `(left, top, width, height)` a `clap` selects from a `w` × `h` image. Its centre
|
||||
/// is `((w - 1) / 2 + horizOff, (h - 1) / 2 + vertOff)`; a corner that falls between two pixels
|
||||
/// is rounded as libheif does: left down, top up.
|
||||
pub fn crop_rect(w: usize, h: usize, c: Clap) -> Result<(usize, usize, usize, usize), Error> {
|
||||
let bad = || Error::Malformed("clap selects an impossible rectangle".into());
|
||||
let size = |(n, d): (u32, u32)| (d != 0).then(|| n / d).ok_or_else(bad);
|
||||
let (cw, ch) = (size(c.width)? as usize, size(c.height)? as usize);
|
||||
if cw == 0 || ch == 0 || cw > w || ch > h {
|
||||
return Err(bad());
|
||||
}
|
||||
// Twice the corner, so the half pixels of odd sizes stay exact.
|
||||
let twice = |full: usize, cropped: usize, (n, d): (i32, u32)| -> Result<i64, Error> {
|
||||
if d == 0 {
|
||||
return Err(bad());
|
||||
}
|
||||
Ok((full - cropped) as i64 + (2 * i64::from(n)).div_euclid(i64::from(d)))
|
||||
};
|
||||
let left = twice(w, cw, c.horiz_off)?.div_euclid(2);
|
||||
let top = (twice(h, ch, c.vert_off)? + 1).div_euclid(2);
|
||||
let left = usize::try_from(left).map_err(|_| bad())?;
|
||||
let top = usize::try_from(top).map_err(|_| bad())?;
|
||||
if left + cw > w || top + ch > h {
|
||||
return Err(bad());
|
||||
}
|
||||
Ok((left, top, cw, ch))
|
||||
}
|
||||
|
||||
/// Whether a `clap` among `transforms` (applied to a `w` × `h` image) starts at an odd column
|
||||
/// or row. libheif crops such images after upsampling their chroma bilinearly instead of with
|
||||
/// its default nearest neighbour; [`crate::ycc`] follows it so the pixels match.
|
||||
pub fn odd_crop(mut w: usize, mut h: usize, transforms: &[Transform]) -> Result<bool, Error> {
|
||||
for t in transforms {
|
||||
match *t {
|
||||
Transform::Crop(c) => {
|
||||
let (left, top, cw, ch) = crop_rect(w, h, c)?;
|
||||
if left % 2 == 1 || top % 2 == 1 {
|
||||
return Ok(true);
|
||||
}
|
||||
(w, h) = (cw, ch);
|
||||
}
|
||||
Transform::Rotate(Rotation::Ccw90 | Rotation::Ccw270) => (w, h) = (h, w),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub fn apply(mut img: Pixels, transforms: &[Transform]) -> Result<Pixels, Error> {
|
||||
for t in transforms {
|
||||
let (w, h) = (img.width, img.height);
|
||||
img = match *t {
|
||||
Transform::Crop(c) => {
|
||||
let (left, top, cw, ch) = crop_rect(w, h, c)?;
|
||||
img.remap(cw, ch, |x, y| (x + left, y + top))
|
||||
}
|
||||
// Counter-clockwise: the right column becomes the top row.
|
||||
Transform::Rotate(Rotation::Ccw90) => img.remap(h, w, |x, y| (w - 1 - y, x)),
|
||||
Transform::Rotate(Rotation::Ccw180) => img.remap(w, h, |x, y| (w - 1 - x, h - 1 - y)),
|
||||
Transform::Rotate(Rotation::Ccw270) => img.remap(h, w, |x, y| (y, h - 1 - x)),
|
||||
Transform::Rotate(Rotation::None) => img,
|
||||
// `axis = 0` (heic-rs's `LeftRight`): top and bottom exchanged, as libheif reads it.
|
||||
Transform::Mirror(Mirror::LeftRight) => img.remap(w, h, |x, y| (x, h - 1 - y)),
|
||||
// `axis = 1`: left and right exchanged.
|
||||
Transform::Mirror(Mirror::TopBottom) => img.remap(w, h, |x, y| (w - 1 - x, y)),
|
||||
};
|
||||
}
|
||||
Ok(img)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 3×2, one channel: 1 2 3 / 4 5 6.
|
||||
fn img() -> Pixels {
|
||||
Pixels { width: 3, height: 2, ch: 1, data: vec![1, 2, 3, 4, 5, 6] }
|
||||
}
|
||||
|
||||
fn run(t: Transform) -> (usize, usize, Vec<u16>) {
|
||||
let p = apply(img(), &[t]).unwrap();
|
||||
(p.width, p.height, p.data)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotations_are_counter_clockwise() {
|
||||
assert_eq!(run(Transform::Rotate(Rotation::Ccw90)), (2, 3, vec![3, 6, 2, 5, 1, 4]));
|
||||
assert_eq!(run(Transform::Rotate(Rotation::Ccw180)), (3, 2, vec![6, 5, 4, 3, 2, 1]));
|
||||
assert_eq!(run(Transform::Rotate(Rotation::Ccw270)), (2, 3, vec![4, 1, 5, 2, 6, 3]));
|
||||
assert_eq!(run(Transform::Rotate(Rotation::None)), (3, 2, vec![1, 2, 3, 4, 5, 6]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirrors_follow_libheif() {
|
||||
// axis 0 (heic-rs `LeftRight`) exchanges top and bottom; axis 1 left and right.
|
||||
assert_eq!(run(Transform::Mirror(Mirror::LeftRight)), (3, 2, vec![4, 5, 6, 1, 2, 3]));
|
||||
assert_eq!(run(Transform::Mirror(Mirror::TopBottom)), (3, 2, vec![3, 2, 1, 6, 5, 4]));
|
||||
}
|
||||
|
||||
fn clap(w: u32, h: u32, ho: i32, vo: i32) -> Clap {
|
||||
Clap { width: (w, 1), height: (h, 1), horiz_off: (ho, 1), vert_off: (vo, 1) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clap_corners_round_like_libheif() {
|
||||
// Measured against libheif 1.23 on a 512 × 512 picture.
|
||||
assert_eq!(crop_rect(512, 512, clap(301, 201, 0, 0)).unwrap(), (105, 156, 301, 201));
|
||||
assert_eq!(crop_rect(512, 512, clap(300, 200, 0, 0)).unwrap(), (106, 156, 300, 200));
|
||||
assert_eq!(crop_rect(512, 512, clap(301, 201, 37, -21)).unwrap(), (142, 135, 301, 201));
|
||||
assert_eq!(crop_rect(512, 512, clap(301, 201, -3, 5)).unwrap(), (102, 161, 301, 201));
|
||||
assert_eq!(crop_rect(512, 512, clap(300, 201, 0, 0)).unwrap(), (106, 156, 300, 201));
|
||||
assert_eq!(crop_rect(1500, 1000, clap(1001, 701, 37, -21)).unwrap(), (286, 129, 1001, 701));
|
||||
let p = apply(img(), &[Transform::Crop(clap(2, 1, 1, 0))]).unwrap();
|
||||
// The half-pixel top rounds down a row.
|
||||
assert_eq!((p.width, p.height, p.data), (2, 1, vec![5, 6]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn impossible_claps_are_errors() {
|
||||
for c in [
|
||||
clap(0, 1, 0, 0),
|
||||
clap(4, 1, 0, 0),
|
||||
clap(3, 2, 1, 0),
|
||||
clap(3, 2, 0, -1),
|
||||
Clap { width: (1, 0), ..clap(1, 1, 0, 0) },
|
||||
Clap { horiz_off: (0, 0), ..clap(1, 1, 0, 0) },
|
||||
] {
|
||||
assert!(crop_rect(3, 2, c).is_err(), "{c:?}");
|
||||
}
|
||||
assert!(apply(img(), &[Transform::Crop(clap(9, 9, 0, 0))]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_crops_are_detected_through_rotations() {
|
||||
assert!(!odd_crop(512, 512, &[Transform::Crop(clap(300, 200, 0, 0))]).unwrap());
|
||||
assert!(odd_crop(512, 512, &[Transform::Crop(clap(301, 200, 0, 0))]).unwrap());
|
||||
// After a quarter turn the crop applies to a 200 × 300 image.
|
||||
let t = [Transform::Crop(clap(300, 200, 0, 0)), Transform::Rotate(Rotation::Ccw90), Transform::Crop(clap(197, 300, 0, 0))];
|
||||
assert!(odd_crop(512, 512, &t).unwrap());
|
||||
assert!(!odd_crop(512, 512, &[Transform::Rotate(Rotation::Ccw90)]).unwrap());
|
||||
}
|
||||
}
|
||||
@@ -1,569 +0,0 @@
|
||||
//! Synthetic HEIF files for tests (feature `testdata`): lossless, so every decoded sample is known.
|
||||
//!
|
||||
//! Each coded picture is one 32 × 32 coding tree unit stored as PCM samples (H.265 7.3.8.7):
|
||||
//! the bitstream carries the YCbCr values verbatim, so the decoder's HEVC stage reproduces them
|
||||
//! exactly and a test checks everything after it (grid composition, colour, transforms,
|
||||
//! metadata) against values it chose. The few CABAC bins around the PCM data are written with a
|
||||
//! minimal arithmetic encoder (9.3.4.4). Larger images are grids of such pictures, which is how
|
||||
//! iPhones store photos too (with 512 × 512 tiles).
|
||||
//!
|
||||
//! Not a general HEIF or HEVC writer: 4:2:0 or monochrome, 8 or 10 bits, a CTU per picture.
|
||||
|
||||
/// Side of every coded picture.
|
||||
pub const TILE: u32 = 32;
|
||||
|
||||
/// YCbCr samples at a luma position (chroma is taken at even positions, 4:2:0).
|
||||
pub type Sampler<'a> = &'a dyn Fn(u32, u32) -> [u16; 3];
|
||||
|
||||
/// A property of the primary image.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Prop {
|
||||
/// `colr` of type `prof`.
|
||||
Icc(Vec<u8>),
|
||||
/// `colr` of type `nclx`: primaries, transfer, matrix, full range.
|
||||
Nclx(u16, u16, u16, bool),
|
||||
/// `irot`: quarter turns counter-clockwise.
|
||||
Irot(u8),
|
||||
/// `imir` with this axis.
|
||||
Imir(u8),
|
||||
/// `clap`: width, height, horizontal and vertical offset (whole pixels).
|
||||
Clap(u32, u32, i32, i32),
|
||||
}
|
||||
|
||||
/// What [`build`] writes.
|
||||
pub struct Spec<'a> {
|
||||
/// Displayed (grid output) size, before transforms.
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub bit_depth: u8,
|
||||
pub sample: Sampler<'a>,
|
||||
/// Properties of the primary image, in association order.
|
||||
pub props: Vec<Prop>,
|
||||
/// EXIF as a TIFF structure (written with HEIF's 4-byte offset header).
|
||||
pub exif: Option<Vec<u8>>,
|
||||
/// An alpha auxiliary image (monochrome, full range).
|
||||
pub alpha: Option<&'a dyn Fn(u32, u32) -> u16>,
|
||||
/// A thumbnail item of half the size with these samples (in its own coordinates).
|
||||
pub thumbnail: Option<Sampler<'a>>,
|
||||
/// Auxiliary images of these types the decoder must ignore (HDR gain map, depth…).
|
||||
pub ignored_aux: Vec<&'static str>,
|
||||
/// When nonzero, the alpha image is instead a grid of `n` × `n` references to one alpha tile
|
||||
/// (a hostile file: the same stored picture rebuilt for every reference).
|
||||
pub alpha_tile_repeats: u8,
|
||||
}
|
||||
|
||||
impl<'a> Spec<'a> {
|
||||
pub fn new(width: u32, height: u32, sample: Sampler<'a>) -> Spec<'a> {
|
||||
Spec {
|
||||
width,
|
||||
height,
|
||||
bit_depth: 8,
|
||||
sample,
|
||||
props: Vec::new(),
|
||||
exif: None,
|
||||
alpha: None,
|
||||
thumbnail: None,
|
||||
ignored_aux: Vec::new(),
|
||||
alpha_tile_repeats: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Bits {
|
||||
bytes: Vec<u8>,
|
||||
n: usize,
|
||||
}
|
||||
|
||||
impl Bits {
|
||||
fn put(&mut self, v: u32, len: u32) {
|
||||
for i in (0..len).rev() {
|
||||
if self.n.is_multiple_of(8) {
|
||||
self.bytes.push(0);
|
||||
}
|
||||
if (v >> i) & 1 == 1
|
||||
&& let Some(b) = self.bytes.last_mut()
|
||||
{
|
||||
*b |= 0x80 >> (self.n % 8);
|
||||
}
|
||||
self.n += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn ue(&mut self, v: u32) {
|
||||
let x = u64::from(v) + 1;
|
||||
let len = 64 - x.leading_zeros();
|
||||
self.put(0, len - 1);
|
||||
self.put((x & 0xffff_ffff) as u32, len);
|
||||
}
|
||||
|
||||
fn align_zero(&mut self) {
|
||||
while !self.n.is_multiple_of(8) {
|
||||
self.put(0, 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn trailing(&mut self) {
|
||||
self.put(1, 1);
|
||||
self.align_zero();
|
||||
}
|
||||
}
|
||||
|
||||
/// The CABAC arithmetic encoder of H.265 9.3.4.4, for the bins these pictures need.
|
||||
struct Cabac {
|
||||
low: u32,
|
||||
range: u32,
|
||||
first: bool,
|
||||
outstanding: u32,
|
||||
}
|
||||
|
||||
impl Cabac {
|
||||
fn new() -> Cabac {
|
||||
Cabac { low: 0, range: 510, first: true, outstanding: 0 }
|
||||
}
|
||||
|
||||
fn put_bit(&mut self, out: &mut Bits, b: u32) {
|
||||
if self.first {
|
||||
self.first = false;
|
||||
} else {
|
||||
out.put(b, 1);
|
||||
}
|
||||
while self.outstanding > 0 {
|
||||
out.put(1 - b, 1);
|
||||
self.outstanding -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn renorm(&mut self, out: &mut Bits) {
|
||||
while self.range < 256 {
|
||||
if self.low < 256 {
|
||||
self.put_bit(out, 0);
|
||||
} else if self.low >= 512 {
|
||||
self.low -= 512;
|
||||
self.put_bit(out, 1);
|
||||
} else {
|
||||
self.low -= 256;
|
||||
self.outstanding += 1;
|
||||
}
|
||||
self.range <<= 1;
|
||||
self.low <<= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// `part_mode` = PART_2Nx2N: the most probable symbol of a fresh context (initValue 184 at
|
||||
/// QP 26 gives pStateIdx 0, valMps 1), so the LPS range is `rangeTabLps[0][3]` = 240.
|
||||
fn part_mode_2nx2n(&mut self, out: &mut Bits) {
|
||||
let lps = [128, 176, 208, 240][((self.range >> 6) & 3) as usize];
|
||||
self.range -= lps;
|
||||
self.renorm(out);
|
||||
}
|
||||
|
||||
/// A terminating bin equal to 1 (`pcm_flag`, `end_of_slice_segment_flag`), with the flush.
|
||||
fn terminate_one(&mut self, out: &mut Bits) {
|
||||
self.range -= 2;
|
||||
self.low += self.range;
|
||||
self.range = 2;
|
||||
self.renorm(out);
|
||||
self.put_bit(out, (self.low >> 9) & 1);
|
||||
out.put(((self.low >> 7) & 3) | 1, 2);
|
||||
}
|
||||
}
|
||||
|
||||
fn nal(kind: u8, rbsp: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![kind << 1, 1];
|
||||
let mut zeros = 0;
|
||||
for &b in rbsp {
|
||||
if zeros >= 2 && b <= 3 {
|
||||
out.push(3);
|
||||
zeros = 0;
|
||||
}
|
||||
zeros = if b == 0 { zeros + 1 } else { 0 };
|
||||
out.push(b);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn profile_idc(bit_depth: u8, mono: bool) -> u32 {
|
||||
match (bit_depth, mono) {
|
||||
(_, true) => 4, // range extensions
|
||||
(8, false) => 1,
|
||||
_ => 2,
|
||||
}
|
||||
}
|
||||
|
||||
fn ptl(w: &mut Bits, idc: u32) {
|
||||
w.put(0, 2);
|
||||
w.put(0, 1);
|
||||
w.put(idc, 5);
|
||||
w.put(1 << (31 - idc), 32); // compatible with itself
|
||||
w.put(0b1001, 4); // progressive, frame only
|
||||
w.put(0, 22);
|
||||
w.put(0, 21);
|
||||
w.put(0, 1);
|
||||
w.put(93, 8); // level 3.1
|
||||
}
|
||||
|
||||
fn parameter_sets(bit_depth: u8, mono: bool) -> [Vec<u8>; 3] {
|
||||
let idc = profile_idc(bit_depth, mono);
|
||||
let bd = u32::from(bit_depth);
|
||||
let mut v = Bits::default();
|
||||
v.put(0, 4);
|
||||
v.put(3, 2);
|
||||
v.put(0, 6);
|
||||
v.put(0, 3);
|
||||
v.put(1, 1);
|
||||
v.put(0xffff, 16);
|
||||
ptl(&mut v, idc);
|
||||
v.put(0, 1); // vps_sub_layer_ordering_info_present_flag
|
||||
v.ue(0);
|
||||
v.ue(0);
|
||||
v.ue(0);
|
||||
v.put(0, 6); // vps_max_layer_id
|
||||
v.ue(0); // vps_num_layer_sets_minus1
|
||||
v.put(0, 1); // vps_timing_info_present_flag
|
||||
v.put(0, 1); // vps_extension_flag
|
||||
v.trailing();
|
||||
|
||||
let mut s = Bits::default();
|
||||
s.put(0, 4);
|
||||
s.put(0, 3);
|
||||
s.put(1, 1);
|
||||
ptl(&mut s, idc);
|
||||
s.ue(0);
|
||||
s.ue(if mono { 0 } else { 1 });
|
||||
s.ue(TILE);
|
||||
s.ue(TILE);
|
||||
s.put(0, 1); // conformance_window_flag
|
||||
s.ue(bd - 8);
|
||||
s.ue(bd - 8);
|
||||
s.ue(4);
|
||||
s.put(1, 1);
|
||||
s.ue(0);
|
||||
s.ue(0);
|
||||
s.ue(0);
|
||||
s.ue(2); // log2_min_luma_coding_block_size_minus3: 32
|
||||
s.ue(0); // log2_diff_max_min_luma_coding_block_size: CTB 32
|
||||
s.ue(0); // log2_min_luma_transform_block_size_minus2: 4
|
||||
s.ue(3); // log2_diff_max_min_luma_transform_block_size: 32
|
||||
s.ue(0);
|
||||
s.ue(0);
|
||||
s.put(0, 1); // scaling_list_enabled_flag
|
||||
s.put(0, 1); // amp_enabled_flag
|
||||
s.put(0, 1); // sample_adaptive_offset_enabled_flag
|
||||
s.put(1, 1); // pcm_enabled_flag
|
||||
s.put(bd - 1, 4); // pcm_sample_bit_depth_luma_minus1
|
||||
s.put(bd - 1, 4); // pcm_sample_bit_depth_chroma_minus1
|
||||
s.ue(2); // log2_min_pcm_luma_coding_block_size_minus3: 32
|
||||
s.ue(0); // log2_diff_max_min_pcm_luma_coding_block_size
|
||||
s.put(1, 1); // pcm_loop_filter_disabled_flag
|
||||
s.ue(0); // num_short_term_ref_pic_sets
|
||||
s.put(0, 1); // long_term_ref_pics_present_flag
|
||||
s.put(0, 1); // sps_temporal_mvp_enabled_flag
|
||||
s.put(0, 1); // strong_intra_smoothing_enabled_flag
|
||||
s.put(0, 1); // vui_parameters_present_flag
|
||||
s.put(0, 1); // sps_extension_present_flag
|
||||
s.trailing();
|
||||
|
||||
let mut p = Bits::default();
|
||||
p.ue(0);
|
||||
p.ue(0);
|
||||
p.put(0, 6); // dependent slices, output flag, 3 extra header bits, sign hiding
|
||||
p.put(0, 1); // cabac_init_present_flag
|
||||
p.ue(0);
|
||||
p.ue(0);
|
||||
p.ue(0); // init_qp_minus26 (se(0) is the same bits)
|
||||
p.put(0, 3); // constrained intra, transform skip, cu_qp_delta
|
||||
p.ue(0);
|
||||
p.ue(0);
|
||||
p.put(0, 1);
|
||||
p.put(0, 2);
|
||||
p.put(0, 1); // transquant_bypass_enabled_flag
|
||||
p.put(0, 1); // tiles_enabled_flag
|
||||
p.put(0, 1); // entropy_coding_sync_enabled_flag
|
||||
p.put(0, 1); // pps_loop_filter_across_slices_enabled_flag
|
||||
p.put(1, 1); // deblocking_filter_control_present_flag
|
||||
p.put(0, 1); // deblocking_filter_override_enabled_flag
|
||||
p.put(1, 1); // pps_deblocking_filter_disabled_flag
|
||||
p.put(0, 1);
|
||||
p.put(0, 1);
|
||||
p.ue(0);
|
||||
p.put(0, 1);
|
||||
p.put(0, 1);
|
||||
p.trailing();
|
||||
[nal(32, &v.bytes), nal(33, &s.bytes), nal(34, &p.bytes)]
|
||||
}
|
||||
|
||||
/// One coded 32 × 32 picture: the `hvcC` payload and the item data (length-prefixed NAL).
|
||||
struct Coded {
|
||||
hvcc: Vec<u8>,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
fn picture(bit_depth: u8, mono: bool, sample: &dyn Fn(u32, u32) -> [u16; 3]) -> Coded {
|
||||
let bd = u32::from(bit_depth);
|
||||
let mut w = Bits::default();
|
||||
w.put(1, 1); // first_slice_segment_in_pic_flag
|
||||
w.put(0, 1); // no_output_of_prior_pics_flag
|
||||
w.ue(0);
|
||||
w.ue(2); // I slice
|
||||
w.ue(0); // slice_qp_delta, se(0)
|
||||
w.trailing(); // byte_alignment()
|
||||
let mut c = Cabac::new();
|
||||
c.part_mode_2nx2n(&mut w);
|
||||
c.terminate_one(&mut w); // pcm_flag
|
||||
w.align_zero(); // pcm_alignment_zero_bit
|
||||
for y in 0..TILE {
|
||||
for x in 0..TILE {
|
||||
w.put(u32::from(sample(x, y)[0]), bd);
|
||||
}
|
||||
}
|
||||
if !mono {
|
||||
for k in 1..3 {
|
||||
for y in 0..TILE / 2 {
|
||||
for x in 0..TILE / 2 {
|
||||
w.put(u32::from(sample(2 * x, 2 * y)[k]), bd);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut c = Cabac::new();
|
||||
c.terminate_one(&mut w); // end_of_slice_segment_flag (its flush ends in the stop bit)
|
||||
w.align_zero();
|
||||
let slice = nal(19, &w.bytes);
|
||||
|
||||
let sets = parameter_sets(bit_depth, mono);
|
||||
let mut h = vec![1u8, profile_idc(bit_depth, mono) as u8];
|
||||
h.extend_from_slice(&(1u32 << (31 - profile_idc(bit_depth, mono))).to_be_bytes());
|
||||
h.extend_from_slice(&[
|
||||
0x90,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
93,
|
||||
0xf0,
|
||||
0,
|
||||
0xfc,
|
||||
0xfc | u8::from(!mono),
|
||||
0xf8 | (bit_depth - 8),
|
||||
0xf8 | (bit_depth - 8),
|
||||
0,
|
||||
0,
|
||||
0x0f,
|
||||
3,
|
||||
]);
|
||||
for (kind, set) in [32u8, 33, 34].into_iter().zip(&sets) {
|
||||
h.push(0x80 | kind);
|
||||
h.extend_from_slice(&1u16.to_be_bytes());
|
||||
h.extend_from_slice(&(set.len() as u16).to_be_bytes());
|
||||
h.extend_from_slice(set);
|
||||
}
|
||||
let mut data = (slice.len() as u32).to_be_bytes().to_vec();
|
||||
data.extend_from_slice(&slice);
|
||||
Coded { hvcc: h, data }
|
||||
}
|
||||
|
||||
fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
|
||||
let mut v = ((payload.len() + 8) as u32).to_be_bytes().to_vec();
|
||||
v.extend_from_slice(kind);
|
||||
v.extend_from_slice(payload);
|
||||
v
|
||||
}
|
||||
|
||||
fn full_box(kind: &[u8; 4], version: u8, payload: &[u8]) -> Vec<u8> {
|
||||
let mut p = vec![version, 0, 0, 0];
|
||||
p.extend_from_slice(payload);
|
||||
bx(kind, &p)
|
||||
}
|
||||
|
||||
struct Item {
|
||||
id: u16,
|
||||
kind: &'static [u8; 4],
|
||||
data: Vec<u8>,
|
||||
/// Indices (1-based) into the property list, with the essential flag.
|
||||
props: Vec<(u8, bool)>,
|
||||
/// Not an image of its own (a grid tile).
|
||||
hidden: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct File {
|
||||
items: Vec<Item>,
|
||||
props: Vec<Vec<u8>>,
|
||||
refs: Vec<(&'static [u8; 4], u16, Vec<u16>)>,
|
||||
}
|
||||
|
||||
impl File {
|
||||
fn prop(&mut self, b: Vec<u8>) -> u8 {
|
||||
self.props.push(b);
|
||||
self.props.len() as u8
|
||||
}
|
||||
|
||||
fn add(&mut self, kind: &'static [u8; 4], data: Vec<u8>, props: Vec<(u8, bool)>) -> u16 {
|
||||
let id = self.items.len() as u16 + 1;
|
||||
self.items.push(Item { id, kind, data, props, hidden: false });
|
||||
id
|
||||
}
|
||||
|
||||
/// A coded image of `w` × `h` (a grid when larger than a tile); returns its item id.
|
||||
fn image(&mut self, w: u32, h: u32, bit_depth: u8, mono: bool, sample: &dyn Fn(u32, u32) -> [u16; 3]) -> u16 {
|
||||
let (cols, rows) = (w.div_ceil(TILE), h.div_ceil(TILE));
|
||||
let ispe = |w: u32, h: u32| {
|
||||
let mut p = w.to_be_bytes().to_vec();
|
||||
p.extend_from_slice(&h.to_be_bytes());
|
||||
full_box(b"ispe", 0, &p)
|
||||
};
|
||||
let mut hvcc_prop = None;
|
||||
let tile_ispe = self.prop(ispe(TILE, TILE));
|
||||
let mut tiles = Vec::new();
|
||||
for r in 0..rows {
|
||||
for c in 0..cols {
|
||||
let coded = picture(bit_depth, mono, &|x, y| sample((c * TILE + x).min(w - 1), (r * TILE + y).min(h - 1)));
|
||||
let hv = *hvcc_prop.get_or_insert_with(|| self.prop(bx(b"hvcC", &coded.hvcc)));
|
||||
tiles.push(self.add(b"hvc1", coded.data, vec![(hv, true), (tile_ispe, false)]));
|
||||
}
|
||||
}
|
||||
if let ([only], true) = (tiles.as_slice(), w == TILE && h == TILE) {
|
||||
return *only;
|
||||
}
|
||||
for it in self.items.iter_mut().filter(|i| tiles.contains(&i.id)) {
|
||||
it.hidden = true;
|
||||
}
|
||||
let mut g = vec![0u8, 0, (rows - 1) as u8, (cols - 1) as u8];
|
||||
g.extend_from_slice(&(w as u16).to_be_bytes());
|
||||
g.extend_from_slice(&(h as u16).to_be_bytes());
|
||||
let grid_ispe = self.prop(ispe(w, h));
|
||||
let id = self.add(b"grid", g, vec![(grid_ispe, false)]);
|
||||
self.refs.push((b"dimg", id, tiles));
|
||||
id
|
||||
}
|
||||
|
||||
fn write(self, primary: u16) -> Vec<u8> {
|
||||
let ftyp = bx(b"ftyp", b"heic\0\0\0\0mif1heic");
|
||||
let mut hdlr = vec![0u8; 4];
|
||||
hdlr.extend_from_slice(b"pict");
|
||||
hdlr.extend_from_slice(&[0; 13]);
|
||||
let hdlr = full_box(b"hdlr", 0, &hdlr);
|
||||
let pitm = full_box(b"pitm", 0, &primary.to_be_bytes());
|
||||
let mut iinf = (self.items.len() as u16).to_be_bytes().to_vec();
|
||||
for it in &self.items {
|
||||
let mut e = vec![2, 0, 0, u8::from(it.hidden)]; // version 2, flags
|
||||
e.extend_from_slice(&it.id.to_be_bytes());
|
||||
e.extend_from_slice(&[0, 0]);
|
||||
e.extend_from_slice(it.kind);
|
||||
e.push(0);
|
||||
iinf.extend_from_slice(&bx(b"infe", &e));
|
||||
}
|
||||
let iinf = full_box(b"iinf", 0, &iinf);
|
||||
let mut iref = Vec::new();
|
||||
for (kind, from, to) in &self.refs {
|
||||
let mut r = from.to_be_bytes().to_vec();
|
||||
r.extend_from_slice(&(to.len() as u16).to_be_bytes());
|
||||
for t in to {
|
||||
r.extend_from_slice(&t.to_be_bytes());
|
||||
}
|
||||
iref.extend_from_slice(&bx(kind, &r));
|
||||
}
|
||||
let iref = full_box(b"iref", 0, &iref);
|
||||
let ipco = bx(b"ipco", &self.props.concat());
|
||||
let mut ipma = (self.items.iter().filter(|i| !i.props.is_empty()).count() as u32).to_be_bytes().to_vec();
|
||||
for it in self.items.iter().filter(|i| !i.props.is_empty()) {
|
||||
ipma.extend_from_slice(&it.id.to_be_bytes());
|
||||
ipma.push(it.props.len() as u8);
|
||||
ipma.extend(it.props.iter().map(|&(i, essential)| i | if essential { 0x80 } else { 0 }));
|
||||
}
|
||||
let iprp = bx(b"iprp", &[ipco, full_box(b"ipma", 0, &ipma)].concat());
|
||||
let iloc = |base: u32| {
|
||||
let mut l = vec![0x44, 0x00];
|
||||
l.extend_from_slice(&(self.items.len() as u16).to_be_bytes());
|
||||
let mut offset = base;
|
||||
for it in &self.items {
|
||||
l.extend_from_slice(&it.id.to_be_bytes());
|
||||
l.extend_from_slice(&[0, 0, 0, 0, 0, 1]); // construction method 0, data ref 0, one extent
|
||||
l.extend_from_slice(&offset.to_be_bytes());
|
||||
l.extend_from_slice(&(it.data.len() as u32).to_be_bytes());
|
||||
offset += it.data.len() as u32;
|
||||
}
|
||||
full_box(b"iloc", 1, &l)
|
||||
};
|
||||
let meta = |base| full_box(b"meta", 0, &[hdlr.clone(), pitm.clone(), iloc(base), iinf.clone(), iref.clone(), iprp.clone()].concat());
|
||||
let start = (ftyp.len() + meta(0).len() + 8) as u32;
|
||||
let mdat = bx(b"mdat", &self.items.iter().flat_map(|i| i.data.iter().copied()).collect::<Vec<u8>>());
|
||||
[ftyp, meta(start), mdat].concat()
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the HEIF file `spec` describes.
|
||||
pub fn build(spec: &Spec<'_>) -> Vec<u8> {
|
||||
let mut f = File::default();
|
||||
let primary = f.image(spec.width, spec.height, spec.bit_depth, false, spec.sample);
|
||||
let mut assoc = Vec::new();
|
||||
for p in &spec.props {
|
||||
let b = match p {
|
||||
Prop::Icc(icc) => bx(b"colr", &[b"prof".as_slice(), icc].concat()),
|
||||
Prop::Nclx(pr, tc, mc, full) => {
|
||||
let mut c = b"nclx".to_vec();
|
||||
for v in [pr, tc, mc] {
|
||||
c.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
c.push(if *full { 0x80 } else { 0 });
|
||||
bx(b"colr", &c)
|
||||
}
|
||||
Prop::Irot(a) => bx(b"irot", &[a & 3]),
|
||||
Prop::Imir(a) => bx(b"imir", &[a & 1]),
|
||||
Prop::Clap(w, h, ho, vo) => {
|
||||
let mut c = Vec::new();
|
||||
for v in [*w as i32, 1, *h as i32, 1, *ho, 1, *vo, 1] {
|
||||
c.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
bx(b"clap", &c)
|
||||
}
|
||||
};
|
||||
assoc.push((f.prop(b), true, matches!(p, Prop::Clap(..))));
|
||||
}
|
||||
if let Some(it) = f.items.iter_mut().find(|i| i.id == primary) {
|
||||
it.props.extend(assoc.iter().map(|&(i, e, _)| (i, e)));
|
||||
}
|
||||
if let Some(exif) = &spec.exif {
|
||||
let id = f.add(b"Exif", [&[0u8, 0, 0, 0][..], exif].concat(), Vec::new());
|
||||
f.refs.push((b"cdsc", id, vec![primary]));
|
||||
}
|
||||
let bd = spec.bit_depth;
|
||||
let aux = |f: &mut File, urn: &str, sample: &dyn Fn(u32, u32) -> [u16; 3]| {
|
||||
let id = f.image(spec.width, spec.height, bd, true, sample);
|
||||
let auxc = f.prop(full_box(b"auxC", 0, &[urn.as_bytes(), &[0]].concat()));
|
||||
if let Some(it) = f.items.iter_mut().find(|i| i.id == id) {
|
||||
it.props.push((auxc, true));
|
||||
}
|
||||
f.refs.push((b"auxl", id, vec![primary]));
|
||||
};
|
||||
if let (Some(alpha), n @ 1..) = (spec.alpha, spec.alpha_tile_repeats) {
|
||||
let tile = f.image(TILE, TILE, bd, true, &|x, y| [alpha(x, y), 0, 0]);
|
||||
if let Some(it) = f.items.iter_mut().find(|i| i.id == tile) {
|
||||
it.hidden = true;
|
||||
}
|
||||
let side = u32::from(n) * TILE;
|
||||
let mut g = vec![0u8, 0, n - 1, n - 1];
|
||||
g.extend_from_slice(&(side as u16).to_be_bytes());
|
||||
g.extend_from_slice(&(side as u16).to_be_bytes());
|
||||
let auxc = f.prop(full_box(b"auxC", 0, b"urn:mpeg:hevc:2015:auxid:1\0"));
|
||||
let id = f.add(b"grid", g, vec![(auxc, true)]);
|
||||
f.refs.push((b"dimg", id, vec![tile; usize::from(n) * usize::from(n)]));
|
||||
f.refs.push((b"auxl", id, vec![primary]));
|
||||
} else if let Some(alpha) = spec.alpha {
|
||||
aux(&mut f, "urn:mpeg:hevc:2015:auxid:1", &|x, y| [alpha(x, y), 0, 0]);
|
||||
}
|
||||
for urn in &spec.ignored_aux {
|
||||
aux(&mut f, urn, &|x, y| [((x + y) % 256) as u16, 0, 0]);
|
||||
}
|
||||
if let Some(sample) = spec.thumbnail {
|
||||
// Half the size, with the primary image's colour and orientation (not its crop).
|
||||
let id = f.image(spec.width / 2, spec.height / 2, spec.bit_depth, false, sample);
|
||||
if let Some(it) = f.items.iter_mut().find(|i| i.id == id) {
|
||||
it.props.extend(assoc.iter().filter(|a| !a.2).map(|&(i, e, _)| (i, e)));
|
||||
}
|
||||
f.refs.push((b"thmb", id, vec![primary]));
|
||||
}
|
||||
f.write(primary)
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
//! Decoding lossless synthetic HEIF files ([`crate::testdata`]): every expected sample is known.
|
||||
|
||||
use crate::testdata::{Prop, Spec, build};
|
||||
use crate::{Error, Options, decode, decode_thumbnail, probe};
|
||||
|
||||
/// A luma value unique enough to identify its position; chroma neutral.
|
||||
fn luma(x: u32, y: u32) -> u16 {
|
||||
((x * 7 + y * 13) % 220 + 20) as u16
|
||||
}
|
||||
|
||||
fn grey(x: u32, y: u32) -> [u16; 3] {
|
||||
[luma(x, y), 128, 128]
|
||||
}
|
||||
|
||||
const FULL_601: Prop = Prop::Nclx(1, 13, 6, true);
|
||||
|
||||
/// Decoded red channel at `(x, y)`, back in 8-bit code values.
|
||||
fn at(d: &crate::Decoded, x: u32, y: u32) -> u16 {
|
||||
let ch = if d.has_alpha { 4 } else { 3 };
|
||||
d.data[((y * d.width + x) as usize) * ch] / 257
|
||||
}
|
||||
|
||||
fn decoded(spec: &Spec) -> crate::Decoded {
|
||||
decode(&build(spec), &Options::default()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_reassembles_exactly() {
|
||||
// 4 × 3 tiles of 32, cropped by the grid to 100 × 70.
|
||||
let d = decoded(&Spec { props: vec![FULL_601], ..Spec::new(100, 70, &grey) });
|
||||
assert_eq!((d.width, d.height, d.bit_depth, d.has_alpha), (100, 70, 8, false));
|
||||
for y in 0..70 {
|
||||
for x in 0..100 {
|
||||
let px = &d.data[((y * 100 + x) * 3) as usize..][..3];
|
||||
assert_eq!(px, [luma(x, y) * 257; 3], "({x}, {y})");
|
||||
}
|
||||
}
|
||||
let info = probe(&build(&Spec::new(100, 70, &grey))).unwrap();
|
||||
assert_eq!((info.width, info.height, info.coded_width, info.coded_height, info.bit_depth), (100, 70, 100, 70, 8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colour_follows_the_matrix_and_range() {
|
||||
// BT.601 full range, a saturated orange: within one code value of the exact conversion.
|
||||
let (y, cb, cr) = (150.0f32, 80.0, 190.0);
|
||||
let s = |_: u32, _: u32| [y as u16, cb as u16, cr as u16];
|
||||
let d = decoded(&Spec { props: vec![FULL_601], ..Spec::new(32, 32, &s) });
|
||||
let (u, v) = (cb - 128.0, cr - 128.0);
|
||||
let expected = [y + 1.402 * v, y - 0.344_136 * u - 0.714_136 * v, y + 1.772 * u].map(|c| c.clamp(0.0, 255.0));
|
||||
for (got, want) in d.data[..3].iter().zip(expected) {
|
||||
assert!((f32::from(*got) / 257.0 - want).abs() <= 1.0, "{:?} vs {expected:?}", &d.data[..3]);
|
||||
}
|
||||
assert_eq!(d.colour, crate::Colour { primaries: 1, transfer: 13, matrix: 6, full_range: true });
|
||||
|
||||
// No nclx and no VUI: the H.265 defaults, limited range (16 → black, 235 → white).
|
||||
let ends = |x: u32, _: u32| [if x < 16 { 16 } else { 235 }, 128, 128];
|
||||
let d = decoded(&Spec::new(32, 32, &ends));
|
||||
assert!(!d.colour.full_range);
|
||||
assert_eq!((d.data[0], d.data[20 * 3]), (0, 65535));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ten_bit_samples_keep_their_precision() {
|
||||
let s = |x: u32, y: u32| [(x * 31 + y) as u16 % 1024, 512, 512];
|
||||
let d = decoded(&Spec { bit_depth: 10, props: vec![FULL_601], ..Spec::new(64, 32, &s) });
|
||||
assert_eq!(d.bit_depth, 10);
|
||||
for x in [0, 1, 5, 33, 63] {
|
||||
let want = ((x * 31) % 1024) as f64 / 1023.0 * 65535.0;
|
||||
assert!((f64::from(d.data[(x * 3) as usize]) - want).abs() <= 1.0, "x {x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn container_transforms_are_applied_like_libheif() {
|
||||
let (w, h) = (70u32, 40u32);
|
||||
let spec = |props: Vec<Prop>| Spec { props: [vec![FULL_601], props].concat(), ..Spec::new(w, h, &grey) };
|
||||
// irot: counter-clockwise quarter turns.
|
||||
let d = decoded(&spec(vec![Prop::Irot(1)]));
|
||||
assert_eq!((d.width, d.height), (h, w));
|
||||
assert_eq!(at(&d, 0, 0), luma(w - 1, 0)); // the right column becomes the top row
|
||||
assert_eq!(at(&d, h - 1, w - 1), luma(0, h - 1));
|
||||
let d = decoded(&spec(vec![Prop::Irot(2)]));
|
||||
assert_eq!(at(&d, 0, 0), luma(w - 1, h - 1));
|
||||
let d = decoded(&spec(vec![Prop::Irot(3)]));
|
||||
assert_eq!(at(&d, 0, 0), luma(0, h - 1));
|
||||
// imir: axis 0 exchanges top and bottom, axis 1 left and right (libheif's reading).
|
||||
let d = decoded(&spec(vec![Prop::Imir(0)]));
|
||||
assert_eq!((at(&d, 0, 0), at(&d, 5, 0)), (luma(0, h - 1), luma(5, h - 1)));
|
||||
let d = decoded(&spec(vec![Prop::Imir(1)]));
|
||||
assert_eq!((at(&d, 0, 0), at(&d, 0, 5)), (luma(w - 1, 0), luma(w - 1, 5)));
|
||||
// clap: centred crop moved by its offsets; a half-pixel corner goes left and down.
|
||||
let d = decoded(&spec(vec![Prop::Clap(31, 21, 3, -2)]));
|
||||
assert_eq!((d.width, d.height), (31, 21));
|
||||
// left = (70 - 31 + 6) / 2 = 22.5 → 22, top = (40 - 21 - 4) / 2 = 7.5 → 8
|
||||
assert_eq!(at(&d, 0, 0), luma(22, 8));
|
||||
// In association order: crop, then turn, then mirror.
|
||||
let d = decoded(&spec(vec![Prop::Clap(30, 20, 0, 0), Prop::Irot(1), Prop::Imir(1)]));
|
||||
assert_eq!((d.width, d.height), (20, 30));
|
||||
// The crop is (20, 10) to (49, 29); the turn brings its bottom-right corner to the top-right,
|
||||
// the left-right mirror to the top-left.
|
||||
assert_eq!(at(&d, 0, 0), luma(49, 29));
|
||||
let info = probe(&build(&spec(vec![Prop::Irot(1)]))).unwrap();
|
||||
assert_eq!((info.width, info.height, info.coded_width, info.coded_height), (h, w, w, h));
|
||||
// Transforms off: as coded.
|
||||
let d = decode(&build(&spec(vec![Prop::Irot(1)])), &Options { apply_transforms: false, ..Default::default() }).unwrap();
|
||||
assert_eq!((d.width, d.height, at(&d, 3, 2)), (w, h, luma(3, 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_aux_images_and_thumbnails() {
|
||||
let icc = b"not parsed here: carried verbatim".to_vec();
|
||||
let exif = b"MM\0\x2a\0\0\0\x08\0\0".to_vec();
|
||||
let spec = Spec {
|
||||
props: vec![Prop::Icc(icc.clone()), FULL_601],
|
||||
exif: Some(exif.clone()),
|
||||
thumbnail: Some(&|_, _| [77, 128, 128]),
|
||||
ignored_aux: vec!["urn:com:apple:photo:2020:aux:hdrgainmap", "urn:mpeg:hevc:2015:auxid:2"],
|
||||
..Spec::new(64, 64, &grey)
|
||||
};
|
||||
let bytes = build(&spec);
|
||||
let d = decode(&bytes, &Options::default()).unwrap();
|
||||
assert_eq!((d.width, d.height, d.has_alpha), (64, 64, false));
|
||||
assert_eq!(d.icc.as_deref(), Some(icc.as_slice()));
|
||||
assert_eq!(d.exif.as_deref(), Some(exif.as_slice()));
|
||||
let t = decode_thumbnail(&bytes, 32, &Options::default()).unwrap().unwrap();
|
||||
assert_eq!((t.width, t.height, t.data[0]), (32, 32, 77 * 257));
|
||||
assert_eq!(t.exif.as_deref(), Some(exif.as_slice()));
|
||||
assert_eq!(t.icc.as_deref(), Some(icc.as_slice()));
|
||||
assert!(decode_thumbnail(&bytes, 33, &Options::default()).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alpha_comes_from_its_auxiliary_image() {
|
||||
let alpha = |x: u32, _: u32| (x * 4) as u16;
|
||||
let d = decoded(&Spec { props: vec![FULL_601], alpha: Some(&alpha), ..Spec::new(64, 32, &grey) });
|
||||
assert!(d.has_alpha);
|
||||
assert_eq!(d.data.len(), 64 * 32 * 4);
|
||||
assert_eq!((d.data[3], d.data[10 * 4 + 3]), (0, 40 * 257));
|
||||
assert_eq!(d.data[..3], [luma(0, 0) * 257; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_alpha_grid_decodes_and_its_tile_references_share_the_visit_budget() {
|
||||
let alpha = |x: u32, _: u32| (x * 4) as u16;
|
||||
// a 2 × 2 alpha grid naming one tile four times: a valid file
|
||||
let d = decoded(&Spec { alpha: Some(&alpha), alpha_tile_repeats: 2, ..Spec::new(64, 64, &grey) });
|
||||
assert!(d.has_alpha);
|
||||
assert_eq!((d.data[10 * 4 + 3], d.data[42 * 4 + 3]), (40 * 257, 40 * 257));
|
||||
// 70 × 70 references to that tile: each would be rebuilt and decoded, so it is refused first
|
||||
let bytes = build(&Spec { alpha: Some(&alpha), alpha_tile_repeats: 70, ..Spec::new(32, 32, &grey) });
|
||||
for r in [probe(&bytes).map(|_| ()), decode(&bytes, &Options::default()).map(|_| ())] {
|
||||
assert!(matches!(&r, Err(Error::Limit(m)) if m.contains("extent reads")), "{r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits_are_checked_before_decoding() {
|
||||
let bytes = build(&Spec::new(96, 64, &grey));
|
||||
let r = decode(&bytes, &Options { max_pixels: 96 * 64 - 1, ..Default::default() });
|
||||
assert!(matches!(r, Err(Error::Limit(_))), "{r:?}");
|
||||
}
|
||||
|
||||
/// #1518: a grid's tiles together are held to the pixel budget before any is decoded. A
|
||||
/// 33 × 33 canvas fits 1089 pixels, but its four 32 × 32 tiles hold 4096: over twice the limit.
|
||||
#[test]
|
||||
fn grid_tiles_are_held_to_the_pixel_budget_together() {
|
||||
let bytes = build(&Spec::new(33, 33, &grey));
|
||||
let r = decode(&bytes, &Options { max_pixels: 33 * 33, ..Default::default() });
|
||||
assert!(matches!(r, Err(Error::Limit(_))), "{r:?}");
|
||||
let d = decode(&bytes, &Options { max_pixels: 2 * 32 * 32, ..Default::default() }).unwrap();
|
||||
assert_eq!((d.width, d.height), (33, 33));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_corrupted_files_are_errors_not_panics() {
|
||||
let bytes = build(&Spec { props: vec![FULL_601, Prop::Irot(1)], thumbnail: Some(&grey), ..Spec::new(64, 64, &grey) });
|
||||
let full = decode(&bytes, &Options::default()).unwrap();
|
||||
for cut in (0..bytes.len()).step_by(7) {
|
||||
let b = &bytes[..cut];
|
||||
// Cut inside the photo: an error. Cut in the trailing thumbnail: the whole photo.
|
||||
if let (Ok(_), Ok(d)) = (probe(b), decode(b, &Options::default())) {
|
||||
assert_eq!(d.data, full.data, "cut at {cut} of {}", bytes.len());
|
||||
}
|
||||
let _ = decode_thumbnail(b, 1, &Options::default());
|
||||
}
|
||||
// Flip bits all over the file: any outcome but a panic.
|
||||
let mut state = 0x2545_f491_u32;
|
||||
for _ in 0..400 {
|
||||
let mut b = bytes.clone();
|
||||
for _ in 0..3 {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
let i = state as usize % b.len();
|
||||
b[i] ^= 1 << (state % 8);
|
||||
}
|
||||
let _ = probe(&b);
|
||||
let _ = decode(&b, &Options::default());
|
||||
let _ = decode_thumbnail(&b, 1, &Options::default());
|
||||
}
|
||||
}
|
||||
|
||||
/// CodeRabbit #44: heic-rs keeps every associated transform and each one re-allocates the
|
||||
/// whole picture, so 13 of them are over the [`crate::MAX_TRANSFORMS`] cap and refused.
|
||||
#[test]
|
||||
fn too_many_transform_properties_are_refused() {
|
||||
let bytes = build(&Spec { props: std::iter::repeat_n(Prop::Irot(0), 13).collect(), ..Spec::new(32, 32, &grey) });
|
||||
let r = decode(&bytes, &Options::default());
|
||||
assert!(matches!(r, Err(Error::Limit(ref m)) if m.contains("transform")), "{r:?}");
|
||||
// At the cap they're not: 12 identity rotations decode normally.
|
||||
let bytes = build(&Spec { props: std::iter::repeat_n(Prop::Irot(0), 12).collect(), ..Spec::new(32, 32, &grey) });
|
||||
let d = decode(&bytes, &Options::default()).unwrap();
|
||||
assert_eq!((d.width, d.height), (32, 32));
|
||||
}
|
||||
@@ -1,567 +0,0 @@
|
||||
//! The colour description in an HEVC sequence parameter set's VUI (Rec. ITU-T H.265, 7.3.2.2 and
|
||||
//! Annex E): the fallback a HEIF reader uses when the item carries no `colr` box of type `nclx`.
|
||||
//! iPhone photos are the common case: they label their colour with an ICC profile only and say in
|
||||
//! the VUI that their YCbCr is full range.
|
||||
//!
|
||||
//! Only the syntax up to `matrix_coeffs` is read. Anything this parser can't follow returns `None`
|
||||
//! and the caller falls back to the H.265 defaults; it never fails a decode.
|
||||
|
||||
/// What the VUI's `video_signal_type` says (H.265 E.3.1). Absent fields keep the defaults the
|
||||
/// standard infers: limited range, every code point 2 ("unspecified").
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Signal {
|
||||
pub full_range: bool,
|
||||
pub primaries: u8,
|
||||
pub transfer: u8,
|
||||
pub matrix: u8,
|
||||
}
|
||||
|
||||
impl Default for Signal {
|
||||
fn default() -> Self {
|
||||
Signal { full_range: false, primaries: 2, transfer: 2, matrix: 2 }
|
||||
}
|
||||
}
|
||||
|
||||
/// NAL unit type of a sequence parameter set.
|
||||
const SPS_NUT: u8 = 33;
|
||||
|
||||
/// Reads the signal description from the SPS among `parameter_sets` (NAL units with their
|
||||
/// two-byte header, as an `hvcC` record stores them). `None`: no SPS, or one this reader can't
|
||||
/// follow; `Some(Signal::default())`: an SPS without VUI colour fields.
|
||||
pub fn signal(parameter_sets: &[&[u8]]) -> Option<Signal> {
|
||||
let sps = parameter_sets.iter().find(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == SPS_NUT))?;
|
||||
parse_sps(&unescape(sps.get(2..)?))
|
||||
}
|
||||
|
||||
/// The uncropped picture size (`pic_width/height_in_luma_samples`) of every SPS among
|
||||
/// `parameter_sets`: what the decoder allocates before it applies the conformance window, so the
|
||||
/// pixel budget is checked against it (heic-rs reports only the first SPS, cropped). `None`: an
|
||||
/// SPS this reader can't follow.
|
||||
pub fn coded_sizes(parameter_sets: &[&[u8]]) -> Option<Vec<(u32, u32)>> {
|
||||
parameter_sets
|
||||
.iter()
|
||||
.filter(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == SPS_NUT))
|
||||
.map(|sps| {
|
||||
let rbsp = unescape(sps.get(2..)?);
|
||||
let r = &mut Bits { data: &rbsp, pos: 0 };
|
||||
sps_size(r).map(|(w, h, _)| (w, h))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// NAL unit type of a picture parameter set.
|
||||
const PPS_NUT: u8 = 34;
|
||||
|
||||
/// What [`pps_layouts`] reads of a picture parameter set.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct PpsLayout {
|
||||
/// `pps_pic_parameter_set_id`.
|
||||
pub id: u32,
|
||||
/// `num_tile_columns_minus1 + 1` (1 without tiles).
|
||||
pub tile_cols: u32,
|
||||
/// `num_tile_rows_minus1 + 1` (1 without tiles).
|
||||
pub tile_rows: u32,
|
||||
}
|
||||
|
||||
/// The id and tile layout of every PPS among `parameter_sets`, read up to the tile counts
|
||||
/// (H.265 7.3.2.3.1). `None`: a PPS this reader can't follow.
|
||||
pub fn pps_layouts(parameter_sets: &[&[u8]]) -> Option<Vec<PpsLayout>> {
|
||||
parameter_sets
|
||||
.iter()
|
||||
.filter(|n| n.first().is_some_and(|b| (b >> 1) & 0x3f == PPS_NUT))
|
||||
.map(|pps| {
|
||||
let rbsp = unescape(pps.get(2..)?);
|
||||
pps_layout(&mut Bits { data: &rbsp, pos: 0 })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn pps_layout(r: &mut Bits) -> Option<PpsLayout> {
|
||||
let id = r.ue()?; // pps_pic_parameter_set_id
|
||||
r.ue()?; // pps_seq_parameter_set_id
|
||||
// dependent slices, output flag, 3 extra slice header bits, sign hiding, cabac_init_present
|
||||
r.skip(7)?;
|
||||
r.ue()?; // num_ref_idx_l0_default_active_minus1
|
||||
r.ue()?; // num_ref_idx_l1_default_active_minus1
|
||||
r.se()?; // init_qp_minus26
|
||||
r.skip(2)?; // constrained_intra_pred_flag, transform_skip_enabled_flag
|
||||
if r.flag()? {
|
||||
r.ue()?; // diff_cu_qp_delta_depth
|
||||
}
|
||||
r.se()?; // pps_cb_qp_offset
|
||||
r.se()?; // pps_cr_qp_offset
|
||||
// slice chroma qp offsets present, weighted pred, weighted bipred, transquant bypass
|
||||
r.skip(4)?;
|
||||
let tiles = r.flag()?; // tiles_enabled_flag
|
||||
r.skip(1)?; // entropy_coding_sync_enabled_flag
|
||||
let (tile_cols, tile_rows) = if tiles { (r.ue()?.checked_add(1)?, r.ue()?.checked_add(1)?) } else { (1, 1) };
|
||||
Some(PpsLayout { id, tile_cols, tile_rows })
|
||||
}
|
||||
|
||||
/// Reads an SPS up to and including the picture size, leaving `r` after it: width, height and
|
||||
/// `sps_max_sub_layers_minus1`.
|
||||
fn sps_size(r: &mut Bits) -> Option<(u32, u32, u32)> {
|
||||
r.skip(4)?; // sps_video_parameter_set_id
|
||||
let max_sub_layers_minus1 = r.u(3)?;
|
||||
if max_sub_layers_minus1 > 6 {
|
||||
return None;
|
||||
}
|
||||
r.skip(1)?; // sps_temporal_id_nesting_flag
|
||||
profile_tier_level(r, max_sub_layers_minus1)?;
|
||||
r.ue()?; // sps_seq_parameter_set_id
|
||||
if r.ue()? == 3 {
|
||||
r.skip(1)?; // separate_colour_plane_flag
|
||||
}
|
||||
let width = r.ue()?; // pic_width_in_luma_samples
|
||||
let height = r.ue()?; // pic_height_in_luma_samples
|
||||
Some((width, height, max_sub_layers_minus1))
|
||||
}
|
||||
|
||||
/// Removes emulation prevention bytes (`00 00 03` → `00 00`).
|
||||
fn unescape(nal: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(nal.len());
|
||||
let mut zeros = 0usize;
|
||||
for &b in nal {
|
||||
if zeros >= 2 && b == 3 {
|
||||
zeros = 0;
|
||||
continue;
|
||||
}
|
||||
zeros = if b == 0 { zeros + 1 } else { 0 };
|
||||
out.push(b);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
struct Bits<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl Bits<'_> {
|
||||
fn u(&mut self, n: u32) -> Option<u32> {
|
||||
let mut v = 0u32;
|
||||
for _ in 0..n {
|
||||
let byte = *self.data.get(self.pos / 8)?;
|
||||
v = (v << 1) | u32::from((byte >> (7 - self.pos % 8)) & 1);
|
||||
self.pos += 1;
|
||||
}
|
||||
Some(v)
|
||||
}
|
||||
|
||||
fn flag(&mut self) -> Option<bool> {
|
||||
self.u(1).map(|b| b == 1)
|
||||
}
|
||||
|
||||
fn skip(&mut self, n: usize) -> Option<()> {
|
||||
self.pos = self.pos.checked_add(n)?;
|
||||
(self.pos <= self.data.len().saturating_mul(8)).then_some(())
|
||||
}
|
||||
|
||||
/// `ue(v)`; values past 32 bits are refused (no valid field here needs them).
|
||||
fn ue(&mut self) -> Option<u32> {
|
||||
let mut zeros = 0u32;
|
||||
while !self.flag()? {
|
||||
zeros += 1;
|
||||
if zeros > 31 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let rest = self.u(zeros)?;
|
||||
((1u64 << zeros) - 1 + u64::from(rest)).try_into().ok()
|
||||
}
|
||||
|
||||
fn se(&mut self) -> Option<()> {
|
||||
self.ue().map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
/// `profile_tier_level(1, max_sub_layers_minus1)` (7.3.3): only skipped.
|
||||
fn profile_tier_level(r: &mut Bits, max_sub_layers_minus1: u32) -> Option<()> {
|
||||
r.skip(88)?; // general profile space .. general_inbld/reserved flag
|
||||
r.skip(8)?; // general_level_idc
|
||||
let mut present = [(false, false); 8];
|
||||
for p in present.iter_mut().take(max_sub_layers_minus1 as usize) {
|
||||
*p = (r.flag()?, r.flag()?);
|
||||
}
|
||||
if max_sub_layers_minus1 > 0 {
|
||||
r.skip(2 * (8 - max_sub_layers_minus1 as usize))?; // reserved_zero_2bits
|
||||
}
|
||||
for &(profile, level) in present.iter().take(max_sub_layers_minus1 as usize) {
|
||||
if profile {
|
||||
r.skip(88)?;
|
||||
}
|
||||
if level {
|
||||
r.skip(8)?;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// `scaling_list_data()` (7.3.4): only skipped.
|
||||
fn scaling_list_data(r: &mut Bits) -> Option<()> {
|
||||
for size_id in 0..4u32 {
|
||||
let step = if size_id == 3 { 3 } else { 1 };
|
||||
for _ in (0..6).step_by(step) {
|
||||
if !r.flag()? {
|
||||
r.ue()?; // scaling_list_pred_matrix_id_delta
|
||||
} else {
|
||||
let coefs = 64.min(1 << (4 + (size_id << 1)));
|
||||
if size_id > 1 {
|
||||
r.se()?; // scaling_list_dc_coef_minus8
|
||||
}
|
||||
for _ in 0..coefs {
|
||||
r.se()?; // scaling_list_delta_coef
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// `st_ref_pic_set(idx)` (7.3.7) as it appears in an SPS; returns `NumDeltaPocs[idx]`.
|
||||
fn st_ref_pic_set(r: &mut Bits, idx: usize, num_delta_pocs: &[u32]) -> Option<u32> {
|
||||
if idx != 0 && r.flag()? {
|
||||
// inter_ref_pic_set_prediction_flag: predicted from the previous set (in an SPS,
|
||||
// delta_idx_minus1 is absent and RefRpsIdx = idx - 1).
|
||||
r.skip(1)?; // delta_rps_sign
|
||||
r.ue()?; // abs_delta_rps_minus1
|
||||
let reference = *num_delta_pocs.get(idx - 1)?;
|
||||
let mut count = 0u32;
|
||||
for _ in 0..=reference {
|
||||
let used = r.flag()?;
|
||||
let kept = used || r.flag()?; // use_delta_flag when not used_by_curr_pic_flag
|
||||
count += u32::from(kept);
|
||||
}
|
||||
return Some(count);
|
||||
}
|
||||
let negative = r.ue()?;
|
||||
let positive = r.ue()?;
|
||||
let total = negative.checked_add(positive)?;
|
||||
if total > 32 {
|
||||
return None; // at most 16 + 16 for any level
|
||||
}
|
||||
for _ in 0..total {
|
||||
r.ue()?; // delta_poc_s*_minus1
|
||||
r.skip(1)?; // used_by_curr_pic_s*_flag
|
||||
}
|
||||
Some(total)
|
||||
}
|
||||
|
||||
fn parse_sps(rbsp: &[u8]) -> Option<Signal> {
|
||||
let r = &mut Bits { data: rbsp, pos: 0 };
|
||||
let (_, _, max_sub_layers_minus1) = sps_size(r)?;
|
||||
parse_sps_parameters(r, max_sub_layers_minus1)?;
|
||||
parse_vui(r)
|
||||
}
|
||||
|
||||
fn parse_sps_parameters(r: &mut Bits<'_>, max_sub_layers_minus1: u32) -> Option<()> {
|
||||
if r.flag()? {
|
||||
for _ in 0..4 {
|
||||
r.ue()?; // conf_win_*_offset
|
||||
}
|
||||
}
|
||||
r.ue()?; // bit_depth_luma_minus8
|
||||
r.ue()?; // bit_depth_chroma_minus8
|
||||
let log2_max_poc_lsb = r.ue()?.checked_add(4)?;
|
||||
if log2_max_poc_lsb > 16 {
|
||||
return None;
|
||||
}
|
||||
let first = if r.flag()? { 0 } else { max_sub_layers_minus1 };
|
||||
for _ in first..=max_sub_layers_minus1 {
|
||||
r.ue()?; // sps_max_dec_pic_buffering_minus1
|
||||
r.ue()?; // sps_max_num_reorder_pics
|
||||
r.ue()?; // sps_max_latency_increase_plus1
|
||||
}
|
||||
for _ in 0..6 {
|
||||
r.ue()?; // coding/transform block sizes, transform hierarchy depths
|
||||
}
|
||||
if r.flag()? && r.flag()? {
|
||||
// scaling_list_enabled_flag, sps_scaling_list_data_present_flag
|
||||
scaling_list_data(r)?;
|
||||
}
|
||||
r.skip(2)?; // amp_enabled_flag, sample_adaptive_offset_enabled_flag
|
||||
if r.flag()? {
|
||||
// pcm_enabled_flag
|
||||
r.skip(8)?; // pcm sample bit depths
|
||||
r.ue()?;
|
||||
r.ue()?;
|
||||
r.skip(1)?; // pcm_loop_filter_disabled_flag
|
||||
}
|
||||
let sets = r.ue()? as usize;
|
||||
if sets > 64 {
|
||||
return None;
|
||||
}
|
||||
let mut num_delta_pocs = Vec::with_capacity(sets);
|
||||
for idx in 0..sets {
|
||||
let n = st_ref_pic_set(r, idx, &num_delta_pocs)?;
|
||||
num_delta_pocs.push(n);
|
||||
}
|
||||
if r.flag()? {
|
||||
// long_term_ref_pics_present_flag
|
||||
let n = r.ue()?;
|
||||
if n > 32 {
|
||||
return None;
|
||||
}
|
||||
for _ in 0..n {
|
||||
r.skip(log2_max_poc_lsb as usize + 1)?; // lt_ref_pic_poc_lsb_sps, used_by_curr_pic_lt_sps_flag
|
||||
}
|
||||
}
|
||||
r.skip(2)?; // sps_temporal_mvp_enabled_flag, strong_intra_smoothing_enabled_flag
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn parse_vui(r: &mut Bits<'_>) -> Option<Signal> {
|
||||
let mut signal = Signal::default();
|
||||
if !r.flag()? {
|
||||
return Some(signal); // no VUI
|
||||
}
|
||||
if r.flag()? && r.u(8)? == 255 {
|
||||
// aspect_ratio_info_present_flag, aspect_ratio_idc == EXTENDED_SAR
|
||||
r.skip(32)?;
|
||||
}
|
||||
if r.flag()? {
|
||||
r.skip(1)?; // overscan_appropriate_flag
|
||||
}
|
||||
if r.flag()? {
|
||||
// video_signal_type_present_flag
|
||||
r.skip(3)?; // video_format
|
||||
signal.full_range = r.flag()?;
|
||||
if r.flag()? {
|
||||
signal.primaries = r.u(8)? as u8;
|
||||
signal.transfer = r.u(8)? as u8;
|
||||
signal.matrix = r.u(8)? as u8;
|
||||
}
|
||||
}
|
||||
Some(signal)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A bit writer for building parameter sets in tests.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Writer {
|
||||
pub bits: Vec<bool>,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
pub fn u(&mut self, v: u32, n: u32) {
|
||||
for i in (0..n).rev() {
|
||||
self.bits.push(i < 32 && (v >> i) & 1 == 1);
|
||||
}
|
||||
}
|
||||
pub fn ue(&mut self, v: u32) {
|
||||
let x = u64::from(v) + 1;
|
||||
let len = 64 - x.leading_zeros();
|
||||
self.u(0, len - 1);
|
||||
for i in (0..len).rev() {
|
||||
self.bits.push((x >> i) & 1 == 1);
|
||||
}
|
||||
}
|
||||
pub fn bytes(mut self) -> Vec<u8> {
|
||||
self.bits.push(true); // rbsp_stop_one_bit
|
||||
while !self.bits.len().is_multiple_of(8) {
|
||||
self.bits.push(false);
|
||||
}
|
||||
self.bits.chunks(8).map(|c| c.iter().fold(0u8, |a, &b| (a << 1) | u8::from(b))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn sps(vui: impl FnOnce(&mut Writer), st_sets: impl FnOnce(&mut Writer)) -> Vec<u8> {
|
||||
let mut w = Writer::default();
|
||||
w.u(0, 4);
|
||||
w.u(1, 3); // one sub-layer above the base
|
||||
w.u(1, 1);
|
||||
w.u(0, 88);
|
||||
w.u(93, 8);
|
||||
w.u(0b11, 2); // sub-layer profile and level present
|
||||
w.u(0, 2 * 7);
|
||||
w.u(0, 88);
|
||||
w.u(0, 8);
|
||||
w.ue(0);
|
||||
w.ue(1); // 4:2:0
|
||||
w.ue(4032);
|
||||
w.ue(3024);
|
||||
w.u(1, 1); // conformance window
|
||||
for _ in 0..4 {
|
||||
w.ue(3);
|
||||
}
|
||||
w.ue(0);
|
||||
w.ue(0);
|
||||
w.ue(4);
|
||||
w.u(1, 1);
|
||||
for _ in 0..2 {
|
||||
w.ue(1);
|
||||
w.ue(0);
|
||||
w.ue(0);
|
||||
}
|
||||
for v in [0, 3, 0, 3, 0, 0] {
|
||||
w.ue(v);
|
||||
}
|
||||
w.u(1, 1); // scaling lists, with data
|
||||
w.u(1, 1);
|
||||
for size_id in 0..4u32 {
|
||||
for _ in (0..6).step_by(if size_id == 3 { 3 } else { 1 }) {
|
||||
w.u(1, 1);
|
||||
if size_id > 1 {
|
||||
w.ue(0);
|
||||
}
|
||||
for _ in 0..64.min(1 << (4 + (size_id << 1))) {
|
||||
w.ue(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
w.u(0, 2);
|
||||
w.u(1, 1); // pcm
|
||||
w.u(0x77, 8);
|
||||
w.ue(0);
|
||||
w.ue(1);
|
||||
w.u(1, 1);
|
||||
st_sets(&mut w);
|
||||
w.u(1, 1); // long-term pictures
|
||||
w.ue(1);
|
||||
w.u(0, 8 + 1);
|
||||
w.u(0, 2);
|
||||
vui(&mut w);
|
||||
let mut nal = vec![SPS_NUT << 1, 1];
|
||||
// escape like a real NAL so `signal` has to unescape
|
||||
let mut zeros = 0;
|
||||
for b in w.bytes() {
|
||||
if zeros >= 2 && b <= 3 {
|
||||
nal.push(3);
|
||||
zeros = 0;
|
||||
}
|
||||
zeros = if b == 0 { zeros + 1 } else { 0 };
|
||||
nal.push(b);
|
||||
}
|
||||
nal
|
||||
}
|
||||
|
||||
fn two_rps(w: &mut Writer) {
|
||||
w.ue(2);
|
||||
w.ue(1); // set 0: one negative picture
|
||||
w.ue(0);
|
||||
w.ue(0);
|
||||
w.u(1, 1);
|
||||
w.u(1, 1); // set 1: predicted from set 0
|
||||
w.u(0, 1);
|
||||
w.ue(0);
|
||||
w.u(0, 1); // not used ...
|
||||
w.u(1, 1); // ... but kept
|
||||
w.u(1, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_full_range_and_matrix_from_the_vui() {
|
||||
let nal = sps(
|
||||
|w| {
|
||||
w.u(1, 1); // vui present
|
||||
w.u(1, 1);
|
||||
w.u(255, 8);
|
||||
w.u(0x0001_0001, 32);
|
||||
w.u(1, 1);
|
||||
w.u(0, 1);
|
||||
w.u(1, 1); // video_signal_type_present_flag
|
||||
w.u(5, 3);
|
||||
w.u(1, 1); // full range
|
||||
w.u(1, 1);
|
||||
w.u(12, 8);
|
||||
w.u(13, 8);
|
||||
w.u(6, 8);
|
||||
},
|
||||
two_rps,
|
||||
);
|
||||
let s = signal(&[&[0x40, 1, 0xc], &nal, &[0x44, 1]]);
|
||||
assert_eq!(s, Some(Signal { full_range: true, primaries: 12, transfer: 13, matrix: 6 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absent_fields_take_the_standard_defaults() {
|
||||
let no_vui = sps(|w| w.u(0, 1), |w| w.ue(0));
|
||||
assert_eq!(signal(&[&no_vui]), Some(Signal::default()));
|
||||
let range_only = sps(
|
||||
|w| {
|
||||
w.u(1, 1);
|
||||
w.u(0, 2);
|
||||
w.u(1, 1);
|
||||
w.u(5, 3);
|
||||
w.u(1, 1);
|
||||
w.u(0, 1); // no colour description
|
||||
},
|
||||
|w| w.ue(0),
|
||||
);
|
||||
assert_eq!(signal(&[&range_only]), Some(Signal { full_range: true, ..Signal::default() }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_truncated_sps_is_none() {
|
||||
assert_eq!(signal(&[]), None);
|
||||
assert_eq!(signal(&[&[0x40, 1, 2, 3]]), None);
|
||||
let nal = sps(|w| w.u(0, 1), |w| w.ue(0));
|
||||
for cut in 2..nal.len() - 2 {
|
||||
// never panics; most cuts are None
|
||||
let _ = signal(&[nal.get(..cut).unwrap_or_default()]);
|
||||
}
|
||||
assert_eq!(signal(&[&[SPS_NUT << 1, 1, 0xff, 0xff, 0xff]]), None);
|
||||
}
|
||||
|
||||
/// A PPS NAL as encoders write it, with `tiles` (columns, rows) when tiles are enabled.
|
||||
fn pps(id: u32, cu_qp_delta: bool, tiles: Option<(u32, u32)>) -> Vec<u8> {
|
||||
let mut w = Writer::default();
|
||||
w.ue(id);
|
||||
w.ue(0); // sps id
|
||||
w.u(0, 7);
|
||||
w.ue(0);
|
||||
w.ue(0);
|
||||
w.ue(3); // init_qp_minus26 = -2
|
||||
w.u(0, 2);
|
||||
w.u(u32::from(cu_qp_delta), 1);
|
||||
if cu_qp_delta {
|
||||
w.ue(1);
|
||||
}
|
||||
w.ue(1); // cb offset +1
|
||||
w.ue(2); // cr offset -1
|
||||
w.u(0, 4);
|
||||
w.u(u32::from(tiles.is_some()), 1);
|
||||
w.u(0, 1);
|
||||
if let Some((c, r)) = tiles {
|
||||
w.ue(c - 1);
|
||||
w.ue(r - 1);
|
||||
w.u(1, 1); // uniform spacing
|
||||
w.u(1, 1);
|
||||
}
|
||||
w.u(0, 3);
|
||||
[vec![PPS_NUT << 1, 1], w.bytes()].concat()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_pps_ids_and_tile_counts() {
|
||||
let plain = pps(5, true, None);
|
||||
let tiled = pps(63, false, Some((4, 3)));
|
||||
let sps_nal = sps(|w| w.u(0, 1), |w| w.ue(0));
|
||||
assert_eq!(
|
||||
pps_layouts(&[&sps_nal, &plain, &tiled]),
|
||||
Some(vec![PpsLayout { id: 5, tile_cols: 1, tile_rows: 1 }, PpsLayout { id: 63, tile_cols: 4, tile_rows: 3 }])
|
||||
);
|
||||
assert_eq!(pps_layouts(&[&[PPS_NUT << 1, 1]]), None);
|
||||
assert!(crate::check_parameter_sets(&[&sps_nal, &plain, &tiled]).is_ok());
|
||||
assert!(crate::check_parameter_sets(&[&pps(0, false, Some((20, 22)))]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_parameter_sets_that_multiply_decoder_work() {
|
||||
// a PPS id past 63: heic-rs would keep every distinct one and rescan them all for each
|
||||
let r = crate::check_parameter_sets(&[&pps(64, false, None)]);
|
||||
assert!(matches!(r, Err(crate::Error::Malformed(_))), "{r:?}");
|
||||
// thousands of PPS records (even with valid, repeated ids): quadratic collection
|
||||
let one = pps(1, false, None);
|
||||
let many: Vec<&[u8]> = vec![&one; 5000];
|
||||
assert!(matches!(crate::check_parameter_sets(&many), Err(crate::Error::Limit(_))));
|
||||
// more tiles than any H.265 level allows: tile tables cost blocks × tiles
|
||||
for (c, r) in [(21, 1), (1, 23), (1024, 1024)] {
|
||||
let r = crate::check_parameter_sets(&[&pps(0, false, Some((c, r)))]);
|
||||
assert!(matches!(r, Err(crate::Error::Limit(_))), "{r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,352 +0,0 @@
|
||||
//! YCbCr → RGB for decoded HEVC pictures, done here rather than in heic-rs so the result matches
|
||||
//! libheif (the reference every HEIF tool is checked against) to within one code value:
|
||||
//!
|
||||
//! - **Which matrix and range.** The item's `colr` `nclx` box when there is one; otherwise the
|
||||
//! HEVC VUI ([`crate::vui`]); otherwise the H.265 defaults (limited range). An unspecified matrix
|
||||
//! is BT.601, as libheif reads it. heic-rs 0.1.1 ignores the VUI and assumes BT.709 limited
|
||||
//! range for every file without `nclx`, which shifts every iPhone photo (full range, ICC only)
|
||||
//! by about 8 code values.
|
||||
//! - **Chroma upsampling.** Nearest neighbour (each chroma sample covers its 2×2 or 2×1 luma
|
||||
//! block), as libheif does by default. libheif switches to a centred bilinear filter (weights
|
||||
//! 9/3/3/1 sixteenths, in integers) when a `clap` crop starts at an odd column or row; so does
|
||||
//! [`Upsampling::Bilinear`].
|
||||
//!
|
||||
//! The arithmetic is floating point and the result 16-bit, whatever the coded depth, so the
|
||||
//! develop pipeline gets every bit the conversion produces.
|
||||
|
||||
use heic_rs::grid::Mosaic;
|
||||
use heic_rs::hevc::{ChromaFormat, Frame};
|
||||
|
||||
/// The coded pictures one image is made of.
|
||||
pub enum Planes<'a> {
|
||||
Picture(&'a Frame),
|
||||
Grid(Mosaic<'a>),
|
||||
}
|
||||
|
||||
impl Planes<'_> {
|
||||
pub fn size(&self) -> (usize, usize) {
|
||||
match self {
|
||||
Planes::Picture(f) => (f.width as usize, f.height as usize),
|
||||
Planes::Grid(m) => (m.width() as usize, m.height() as usize),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bit_depth(&self) -> u8 {
|
||||
match self {
|
||||
Planes::Picture(f) => f.bit_depth,
|
||||
Planes::Grid(m) => m.bit_depth(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn chroma(&self) -> ChromaFormat {
|
||||
match self {
|
||||
Planes::Picture(f) => f.chroma,
|
||||
Planes::Grid(m) => m.chroma(),
|
||||
}
|
||||
}
|
||||
|
||||
fn chroma_width(&self) -> usize {
|
||||
let (w, h) = self.size();
|
||||
self.chroma().chroma_size(w as u32, h as u32).0 as usize
|
||||
}
|
||||
|
||||
fn luma_row(&self, y: usize, dst: &mut [u16]) -> Option<()> {
|
||||
match self {
|
||||
Planes::Picture(f) => copy_row(&f.y, f.y_stride as usize, y, dst),
|
||||
Planes::Grid(m) => m.luma_row(y, dst),
|
||||
}
|
||||
}
|
||||
|
||||
fn chroma_row(&self, cr: bool, r: usize, dst: &mut [u16]) -> Option<()> {
|
||||
match self {
|
||||
Planes::Picture(f) => copy_row(if cr { &f.cr } else { &f.cb }, f.c_stride as usize, r, dst),
|
||||
Planes::Grid(m) => m.chroma_row(cr, r, dst),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_row(plane: &[u16], stride: usize, y: usize, dst: &mut [u16]) -> Option<()> {
|
||||
let start = y.checked_mul(stride)?;
|
||||
dst.copy_from_slice(plane.get(start..start.checked_add(dst.len())?)?);
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// How the three coded channels map to R, G, B (H.273 `MatrixCoefficients`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
enum Matrix {
|
||||
/// 0: the channels are G, B, R.
|
||||
Identity,
|
||||
/// 8: YCgCo.
|
||||
YCgCo,
|
||||
/// Every Kr/Kb matrix: R = Y + `cr_r`·Cr, G = Y − `cb_g`·Cb − `cr_g`·Cr, B = Y + `cb_b`·Cb.
|
||||
Kr { cr_r: f32, cb_g: f32, cr_g: f32, cb_b: f32 },
|
||||
}
|
||||
|
||||
impl Matrix {
|
||||
/// Unknown, reserved and unspecified codes are BT.601, like libheif.
|
||||
fn from_code(code: u16) -> Matrix {
|
||||
let (kr, kb) = match code {
|
||||
0 => return Matrix::Identity,
|
||||
8 => return Matrix::YCgCo,
|
||||
1 => (0.2126, 0.0722),
|
||||
4 => (0.30, 0.11),
|
||||
7 => (0.212, 0.087),
|
||||
// 10 (BT.2020 constant luminance) is approximated by its non-constant matrix.
|
||||
9 | 10 => (0.2627, 0.0593),
|
||||
_ => (0.299, 0.114),
|
||||
};
|
||||
let kg = 1.0 - kr - kb;
|
||||
Matrix::Kr { cr_r: 2.0 * (1.0 - kr), cb_g: 2.0 * kb * (1.0 - kb) / kg, cr_g: 2.0 * kr * (1.0 - kr) / kg, cb_b: 2.0 * (1.0 - kb) }
|
||||
}
|
||||
}
|
||||
|
||||
/// How the samples are to be read: the matrix and the range.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Signal {
|
||||
pub matrix: u16,
|
||||
pub full_range: bool,
|
||||
}
|
||||
|
||||
/// How subsampled chroma is brought to the luma resolution.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Upsampling {
|
||||
Nearest,
|
||||
/// Centred bilinear: chroma sits between its two luma columns (and rows for 4:2:0).
|
||||
Bilinear,
|
||||
}
|
||||
|
||||
/// One chroma row brought to the full width `w` of luma row `y`.
|
||||
fn chroma_at(planes: &Planes<'_>, cr: bool, y: usize, w: usize, mode: Upsampling, buf: &mut [u16], next: &mut [u16]) -> Option<Vec<u16>> {
|
||||
let chroma = planes.chroma();
|
||||
let (xs, ys) = (chroma.x_shift(), chroma.y_shift());
|
||||
let (wf, hf) = planes.size();
|
||||
let rows = chroma.chroma_size(wf as u32, hf as u32).1 as usize;
|
||||
let cy = y >> ys;
|
||||
planes.chroma_row(cr, cy, buf)?;
|
||||
let last = buf.len().checked_sub(1)?;
|
||||
if mode == Upsampling::Nearest || xs == 0 {
|
||||
return (0..w).map(|x| buf.get(x >> xs).copied()).collect();
|
||||
}
|
||||
// The nearer neighbour on each axis takes a quarter of the weight.
|
||||
let ny = if ys == 0 {
|
||||
cy
|
||||
} else if y.is_multiple_of(2) {
|
||||
cy.saturating_sub(1)
|
||||
} else {
|
||||
(cy + 1).min(rows.checked_sub(1)?)
|
||||
};
|
||||
planes.chroma_row(cr, ny, next)?;
|
||||
(0..w)
|
||||
.map(|x| {
|
||||
let cx = x >> 1;
|
||||
let nx = if x % 2 == 0 { cx.saturating_sub(1) } else { (cx + 1).min(last) };
|
||||
let (a, an) = (u32::from(*buf.get(cx)?), u32::from(*buf.get(nx)?));
|
||||
let v = if ys == 0 {
|
||||
(3 * a + an + 2) >> 2
|
||||
} else {
|
||||
let (b, bn) = (u32::from(*next.get(cx)?), u32::from(*next.get(nx)?));
|
||||
(9 * a + 3 * b + 3 * an + bn + 8) >> 4
|
||||
};
|
||||
u16::try_from(v).ok()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Converts `planes` to interleaved 16-bit RGB, or RGBA with room left for alpha (filled with
|
||||
/// 65535 here). `None` when the planes can't supply a row they promised (a malformed grid).
|
||||
pub fn to_rgb16(planes: &Planes<'_>, signal: Signal, alpha: bool, mode: Upsampling) -> Option<Vec<u16>> {
|
||||
let (w, h) = planes.size();
|
||||
let ch = if alpha { 4 } else { 3 };
|
||||
let bd = u32::from(planes.bit_depth());
|
||||
if !(8..=16).contains(&bd) || w == 0 || h == 0 {
|
||||
return None;
|
||||
}
|
||||
// The default caller limit is 2²8 pixels, at most four channels per pixel, so the largest
|
||||
// legitimate `w·h·ch` is 2²30 samples. Anything more is a malformed or hostile canvas the
|
||||
// decode path would have refused before calling here (CodeRabbit #48): refuse rather than
|
||||
// ask for a multi-gigabuffer (or worse, over usize).
|
||||
if w.checked_mul(h)?.checked_mul(ch)? > 1 << 30 {
|
||||
return None;
|
||||
}
|
||||
let max = ((1u32 << bd) - 1) as f32;
|
||||
let half = (1u32 << (bd - 1)) as f32;
|
||||
let scale = (1u32 << (bd - 8)) as f32;
|
||||
// Normalised Y = (v − y_off)·y_mul, Cb/Cr = (v − half)·c_mul.
|
||||
let (y_off, y_mul, c_mul) =
|
||||
if signal.full_range { (0.0, 1.0 / max, 1.0 / max) } else { (16.0 * scale, 1.0 / (219.0 * scale), 1.0 / (224.0 * scale)) };
|
||||
let matrix = Matrix::from_code(signal.matrix);
|
||||
let mono = planes.chroma() == ChromaFormat::Monochrome;
|
||||
let cw = planes.chroma_width();
|
||||
|
||||
let mut out = vec![0u16; w.checked_mul(h)?.checked_mul(ch)?];
|
||||
let row = |y: usize, dst: &mut [u16]| -> Option<()> {
|
||||
let mut luma = vec![0u16; w];
|
||||
planes.luma_row(y, &mut luma)?;
|
||||
let (cb, cr) = if mono {
|
||||
(Vec::new(), Vec::new())
|
||||
} else {
|
||||
let (mut buf, mut next) = (vec![0u16; cw], vec![0u16; cw]);
|
||||
(chroma_at(planes, false, y, w, mode, &mut buf, &mut next)?, chroma_at(planes, true, y, w, mode, &mut buf, &mut next)?)
|
||||
};
|
||||
for (x, (px, &yv)) in dst.chunks_exact_mut(ch).zip(&luma).enumerate() {
|
||||
let rgb = if mono {
|
||||
let v = (f32::from(yv) - y_off) * y_mul;
|
||||
[v, v, v]
|
||||
} else {
|
||||
let (u, v) = (f32::from(*cb.get(x)?), f32::from(*cr.get(x)?));
|
||||
match matrix {
|
||||
// G, B, R all read like luma.
|
||||
Matrix::Identity => [(v - y_off) * y_mul, (f32::from(yv) - y_off) * y_mul, (u - y_off) * y_mul],
|
||||
Matrix::YCgCo => {
|
||||
let (yn, cg, co) = ((f32::from(yv) - y_off) * y_mul, (u - half) * c_mul, (v - half) * c_mul);
|
||||
let t = yn - cg;
|
||||
[t + co, yn + cg, t - co]
|
||||
}
|
||||
Matrix::Kr { cr_r, cb_g, cr_g, cb_b } => {
|
||||
let (yn, u, v) = ((f32::from(yv) - y_off) * y_mul, (u - half) * c_mul, (v - half) * c_mul);
|
||||
[yn + cr_r * v, yn - cb_g * u - cr_g * v, yn + cb_b * u]
|
||||
}
|
||||
}
|
||||
};
|
||||
for (o, c) in px.iter_mut().zip(rgb) {
|
||||
*o = (c.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;
|
||||
}
|
||||
if alpha && let Some(a) = px.get_mut(3) {
|
||||
*a = u16::MAX;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
};
|
||||
let row_len = w * ch;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let ok = {
|
||||
use rayon::prelude::*;
|
||||
out.par_chunks_mut(row_len).enumerate().all(|(y, dst)| row(y, dst).is_some())
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let ok = out.chunks_mut(row_len).enumerate().all(|(y, dst)| row(y, dst).is_some());
|
||||
ok.then_some(out)
|
||||
}
|
||||
|
||||
/// Writes an alpha picture's luma, full range, into channel 3 of `rgba`.
|
||||
pub fn put_alpha(planes: &Planes<'_>, rgba: &mut [u16]) -> Option<()> {
|
||||
let (w, h) = planes.size();
|
||||
let max = ((1u32 << u32::from(planes.bit_depth()).clamp(1, 16)) - 1) as f32;
|
||||
let mut luma = vec![0u16; w];
|
||||
for (y, row) in rgba.chunks_exact_mut(w * 4).enumerate().take(h) {
|
||||
planes.luma_row(y, &mut luma)?;
|
||||
for (px, &a) in row.as_chunks_mut::<4>().0.iter_mut().zip(&luma) {
|
||||
let v = (f32::from(a) / max).clamp(0.0, 1.0);
|
||||
px[3] = (v * 65535.0 + 0.5) as u16;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn frame(w: u32, h: u32, bd: u8, chroma: ChromaFormat, y: u16, cb: u16, cr: u16) -> Frame {
|
||||
let (cw, chh) = chroma.chroma_size(w, h);
|
||||
let n = (cw * chh) as usize;
|
||||
Frame {
|
||||
width: w,
|
||||
height: h,
|
||||
bit_depth: bd,
|
||||
chroma,
|
||||
y: vec![y; (w * h) as usize],
|
||||
cb: vec![cb; n],
|
||||
cr: vec![cr; n],
|
||||
y_stride: w,
|
||||
c_stride: cw,
|
||||
}
|
||||
}
|
||||
|
||||
fn rgb(f: &Frame, matrix: u16, full_range: bool) -> [u16; 3] {
|
||||
let v = to_rgb16(&Planes::Picture(f), Signal { matrix, full_range }, false, Upsampling::Nearest).unwrap();
|
||||
[v[0], v[1], v[2]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_and_primaries_convert_exactly() {
|
||||
// Full-range grey stays grey; limited-range black and white reach the ends.
|
||||
assert_eq!(rgb(&frame(4, 4, 8, ChromaFormat::Yuv420, 128, 128, 128), 6, true), [128 * 257; 3]);
|
||||
assert_eq!(rgb(&frame(4, 4, 8, ChromaFormat::Yuv420, 16, 128, 128), 1, false), [0; 3]);
|
||||
assert_eq!(rgb(&frame(4, 4, 8, ChromaFormat::Yuv420, 235, 128, 128), 1, false), [65535; 3]);
|
||||
assert_eq!(rgb(&frame(4, 4, 10, ChromaFormat::Yuv420, 940, 512, 512), 9, false), [65535; 3]);
|
||||
// BT.601 full-range pure red: Y = 76.245, Cb = 84.97, Cr = 255.5 → (255, 0, 0) within rounding.
|
||||
let red = rgb(&frame(2, 2, 8, ChromaFormat::Yuv444, 76, 85, 255), 6, true);
|
||||
assert!(red[0] > 65000 && red[1] < 300 && red[2] < 300, "{red:?}");
|
||||
// Identity: the channels are G, B, R.
|
||||
assert_eq!(rgb(&frame(2, 2, 8, ChromaFormat::Yuv444, 10, 20, 30), 0, true), [30 * 257, 10 * 257, 20 * 257]);
|
||||
// Monochrome.
|
||||
assert_eq!(rgb(&frame(2, 2, 8, ChromaFormat::Monochrome, 51, 0, 0), 6, true), [51 * 257; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chroma_is_nearest_neighbour() {
|
||||
// 4:2:0, 4×2 luma, chroma 2×1: the left chroma sample covers columns 0–1 only.
|
||||
let mut f = frame(4, 2, 8, ChromaFormat::Yuv420, 128, 128, 128);
|
||||
f.cr = vec![200, 128];
|
||||
let v = to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, false, Upsampling::Nearest).unwrap();
|
||||
let red: Vec<u16> = v.chunks(3).map(|p| p[0]).collect();
|
||||
assert!(red[0] == red[1] && red[1] == red[4] && red[0] > red[2] && red[2] == 128 * 257, "{red:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bilinear_chroma_is_centred_9_3_3_1() {
|
||||
// 4:2:0, 4×4 luma, chroma 2×2 with one bright corner sample.
|
||||
let mut f = frame(4, 4, 8, ChromaFormat::Yuv420, 128, 128, 128);
|
||||
f.cr = vec![200, 128, 128, 128];
|
||||
let p = Planes::Picture(&f);
|
||||
let (mut buf, mut next) = (vec![0; 2], vec![0; 2]);
|
||||
let rows: Vec<Vec<u16>> = (0..4).map(|y| chroma_at(&p, true, y, 4, Upsampling::Bilinear, &mut buf, &mut next).unwrap()).collect();
|
||||
// Row 0 sits nearest chroma row 0 (and clamps upward); row 1 blends a quarter of row 1.
|
||||
assert_eq!(rows[0], [200, 182, 146, 128]);
|
||||
assert_eq!(rows[1], [182, 169, 142, 128]);
|
||||
assert_eq!(rows[2], [146, 142, 133, 128]);
|
||||
assert_eq!(rows[3], [128; 4]);
|
||||
assert_eq!(chroma_at(&p, true, 1, 4, Upsampling::Nearest, &mut buf, &mut next).unwrap(), [200, 200, 128, 128]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alpha_and_bad_planes() {
|
||||
let f = frame(2, 2, 8, ChromaFormat::Yuv420, 128, 128, 128);
|
||||
let mut v = to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, true, Upsampling::Nearest).unwrap();
|
||||
assert_eq!(v[3], 65535);
|
||||
put_alpha(&Planes::Picture(&frame(2, 2, 8, ChromaFormat::Monochrome, 51, 0, 0)), &mut v).unwrap();
|
||||
assert_eq!(v[3], 51 * 257);
|
||||
let mut short = frame(4, 4, 8, ChromaFormat::Yuv420, 128, 128, 128);
|
||||
short.y.truncate(5);
|
||||
assert!(to_rgb16(&Planes::Picture(&short), Signal { matrix: 6, full_range: true }, false, Upsampling::Bilinear).is_none());
|
||||
assert!(
|
||||
to_rgb16(
|
||||
&Planes::Picture(&frame(2, 2, 7, ChromaFormat::Yuv420, 0, 0, 0)),
|
||||
Signal { matrix: 6, full_range: true },
|
||||
false,
|
||||
Upsampling::Nearest
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
/// CodeRabbit #48: a plane claiming 500 000 × 500 000 pixels must be refused without ever
|
||||
/// allocating for it (before the cap this vec was never built; upper-bounding allocation
|
||||
/// would have been a 7.5-gibabuffer or a panic instead of an error).
|
||||
#[test]
|
||||
fn an_oversized_canvas_is_refused_without_allocation() {
|
||||
let f = Frame {
|
||||
width: 500_000,
|
||||
height: 500_000,
|
||||
bit_depth: 8,
|
||||
chroma: ChromaFormat::Yuv420,
|
||||
y: vec![128],
|
||||
cb: vec![128; 4],
|
||||
cr: vec![128; 4],
|
||||
y_stride: 0,
|
||||
c_stride: 0,
|
||||
};
|
||||
assert!(to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, false, Upsampling::Nearest).is_none());
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ description = "LightCraft metadata: EXIF, XMP, IPTC (L1)"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
lightcraft-tiff = { workspace = true }
|
||||
craft-tiff = { workspace = true }
|
||||
lightcraft-geom = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
quick-xml = { workspace = true }
|
||||
@@ -17,6 +17,6 @@ chrono = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Lossless synthetic HEIC files: the HEIF item reader is proved against a real container writer.
|
||||
lightcraft-heif = { workspace = true, features = ["testdata"] }
|
||||
craft-heif = { workspace = true, features = ["testdata"] }
|
||||
proptest = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
//! - HEIF/HEIC/AVIF (ISO base media file, see [`crate::heif`]): the `Exif` item's TIFF stream and the XMP
|
||||
//! `mime` item.
|
||||
|
||||
use lightcraft_tiff::{Tiff, tags};
|
||||
use craft_tiff::{Tiff, tags};
|
||||
|
||||
/// Metadata blocks found in a file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
@@ -71,8 +71,8 @@ pub fn embedded(bytes: &[u8]) -> Embedded {
|
||||
xmp_extended: None,
|
||||
icc: ifd0.bytes(tags::ICC_PROFILE).map(|b| b.to_vec()),
|
||||
iptc: ifd0.value(tags::IPTC_NAA).map(|v| match v {
|
||||
lightcraft_tiff::Value::Byte(b) | lightcraft_tiff::Value::Undefined(b) => b.clone(),
|
||||
other => lightcraft_tiff::writer::encode(t.order, other),
|
||||
craft_tiff::Value::Byte(b) | craft_tiff::Value::Undefined(b) => b.clone(),
|
||||
other => craft_tiff::writer::encode(t.order, other),
|
||||
}),
|
||||
}
|
||||
} else {
|
||||
@@ -275,7 +275,7 @@ pub fn webp_chunks(b: &[u8]) -> Embedded {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::exif::tests::sample_exif;
|
||||
use lightcraft_tiff::ByteOrder;
|
||||
use craft_tiff::ByteOrder;
|
||||
|
||||
fn seg(marker: u8, payload: &[u8]) -> Vec<u8> {
|
||||
let mut v = vec![0xff, marker];
|
||||
|
||||
@@ -436,13 +436,13 @@ fn le32(b: &[u8], at: usize) -> Option<u32> {
|
||||
/// 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 lightcraft_tiff::{IfdBuilder, Tiff, TiffWriter, tags as t};
|
||||
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: &lightcraft_tiff::Ifd| {
|
||||
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());
|
||||
@@ -497,14 +497,14 @@ mod tests {
|
||||
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: lightcraft_tiff::Value) -> Vec<u8> {
|
||||
let b = lightcraft_tiff::IfdBuilder::new().with(tag, v);
|
||||
lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[b]).unwrap()
|
||||
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 lightcraft_tiff::{Value, tags as t};
|
||||
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()));
|
||||
@@ -689,7 +689,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn timed_metadata_exposes_the_dynamic_maker_note() {
|
||||
use lightcraft_tiff::{Value, tags as t};
|
||||
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]| {
|
||||
|
||||
+13
-13
@@ -1,7 +1,7 @@
|
||||
//! Exif / TIFF tags → [`Metadata`] (CIPA DC-008 Exif 2.32, TIFF 6.0, DNG 1.7 tag semantics).
|
||||
|
||||
use crate::{DateTime, Flash, Gps, Metadata, Orientation};
|
||||
use lightcraft_tiff::{Ifd, ParseOptions, Tiff, TiffError, tags as t};
|
||||
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] {
|
||||
@@ -129,8 +129,8 @@ pub fn from_tiff(tiff: &Tiff) -> Metadata {
|
||||
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 {
|
||||
lightcraft_tiff::Value::Byte(b) | lightcraft_tiff::Value::Undefined(b) => b.clone(),
|
||||
other => lightcraft_tiff::writer::encode(tiff.order, other),
|
||||
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));
|
||||
}
|
||||
@@ -200,7 +200,7 @@ fn panasonic_lens(data: &[u8], tiff: &Tiff) -> Option<String> {
|
||||
}
|
||||
let e = exif.get(t::MAKER_NOTE)?;
|
||||
let make = tiff.ifds.first().and_then(|i| i.string(t::MAKE)).unwrap_or_default();
|
||||
let mn = lightcraft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?;
|
||||
let mn = craft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?;
|
||||
text(Some(&mn.ifd), PANASONIC_LENS_TYPE)
|
||||
}
|
||||
|
||||
@@ -225,7 +225,7 @@ fn canon_maker_note_lens(data: &[u8], tiff: &Tiff) -> Option<String> {
|
||||
}
|
||||
let exif = tiff.exif()?;
|
||||
let e = exif.get(t::MAKER_NOTE)?;
|
||||
let mn = lightcraft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?;
|
||||
let mn = craft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, &make)?;
|
||||
text(Some(&mn.ifd), CANON_LENS_MODEL)
|
||||
}
|
||||
|
||||
@@ -234,13 +234,13 @@ fn canon_maker_note_lens(data: &[u8], tiff: &Tiff) -> Option<String> {
|
||||
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: lightcraft_tiff::ByteOrder) -> Option<[f64; 4]> {
|
||||
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 = lightcraft_tiff::makernote::parse_makernote(note, 0, note.len() as u64, order, make)?;
|
||||
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;
|
||||
@@ -251,7 +251,7 @@ fn nikon_lens_spec(exif: Option<&Ifd>, make: Option<&str>, order: lightcraft_tif
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
|
||||
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();
|
||||
@@ -602,19 +602,19 @@ pub(crate) mod tests {
|
||||
}
|
||||
|
||||
/// An exact `1/N` rational for a sub-second value whose reciprocal is a whole number (shutter speeds such as
|
||||
/// 1/12800 s, which [`lightcraft_tiff::writer::rational`]'s decimal denominators cannot represent).
|
||||
fn reciprocal(v: Option<f64>) -> Option<lightcraft_tiff::Value> {
|
||||
/// 1/12800 s, which [`craft_tiff::writer::rational`]'s decimal denominators cannot represent).
|
||||
fn reciprocal(v: Option<f64>) -> Option<craft_tiff::Value> {
|
||||
let v = v.filter(|v| v.is_finite() && *v > 0.0 && *v < 1.0)?;
|
||||
let inv = 1.0 / v;
|
||||
((inv - inv.round()).abs() < 1e-6 && inv.round() <= u32::MAX as f64).then(|| lightcraft_tiff::Value::Rational(vec![(1, inv.round() as u32)]))
|
||||
((inv - inv.round()).abs() < 1e-6 && inv.round() <= u32::MAX as f64).then(|| craft_tiff::Value::Rational(vec![(1, inv.round() as u32)]))
|
||||
}
|
||||
|
||||
/// Serialise the interchange subset of `meta` as a TIFF-structured Exif block (little-endian, no
|
||||
/// `Exif\0\0` prefix): IFD0 (make, model, software, artist, copyright, description, orientation,
|
||||
/// date), the Exif IFD (capture settings, lens) and, when present, the GPS IFD.
|
||||
pub fn write_exif(meta: &Metadata) -> Vec<u8> {
|
||||
use lightcraft_tiff::writer::{rational, srational};
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
|
||||
use craft_tiff::writer::{rational, srational};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
|
||||
let ascii = |s: &Option<String>| s.as_ref().filter(|v| !v.is_empty()).map(|v| Value::Ascii(v.clone()));
|
||||
let mut ifd0 = IfdBuilder::new();
|
||||
for (tag, v) in [
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
|
||||
pub use crate::focus_read::{HEADER_PREFIX, HeaderRead, MAX_HEADER_BYTES, read_header};
|
||||
use crate::{Orientation, Rect};
|
||||
use lightcraft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t};
|
||||
use craft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Where the camera focused, on the upright photo.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use lightcraft_tiff::{Entry, IfdBuilder, TiffWriter, Value};
|
||||
use craft_tiff::{Entry, IfdBuilder, TiffWriter, Value};
|
||||
|
||||
fn encipher(p: u8) -> u8 {
|
||||
if p >= 249 { p } else { ((u32::from(p).pow(3)) % 249) as u8 }
|
||||
@@ -206,7 +206,7 @@ fn sony_file_with(make: &str, model: &str, orientation: u16, note_entries: &[(u1
|
||||
let mut outside: Vec<u8> = Vec::new();
|
||||
order.put_u16(&mut note, note_entries.len() as u16);
|
||||
for (tag, v) in note_entries {
|
||||
let raw = lightcraft_tiff::writer::encode(order, v);
|
||||
let raw = craft_tiff::writer::encode(order, v);
|
||||
order.put_u16(&mut note, *tag);
|
||||
order.put_u16(&mut note, v.field_type() as u16);
|
||||
order.put_u32(&mut note, v.count() as u32);
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
use std::io;
|
||||
|
||||
use crate::focus::FocusPoint;
|
||||
use lightcraft_tiff::{ByteOrder, FieldType, Tiff, tags as t};
|
||||
use craft_tiff::{ByteOrder, FieldType, Tiff, tags as t};
|
||||
|
||||
/// Bytes read first: the α1's and A7S III's focus data ends before 16 KB, so one read covers it.
|
||||
pub const HEADER_PREFIX: u64 = 32 * 1024;
|
||||
@@ -176,8 +176,7 @@ fn tiff(r: &mut Reader, head: Vec<u8>) -> io::Result<Option<FocusPoint>> {
|
||||
// file length: only the loaded ranges are data, and an unrelated entry that claims a
|
||||
// huge value must be cut by what leaving it cost, not by what the buffer claims to hold.
|
||||
// The same 8 × / + 1 MiB shape the general TIFF reader uses, over `reader.bytes` instead.
|
||||
let opts =
|
||||
lightcraft_tiff::ParseOptions { value_budget: Some(r.bytes.saturating_mul(8).saturating_add(1 << 20)), ..Default::default() };
|
||||
let opts = craft_tiff::ParseOptions { value_budget: Some(r.bytes.saturating_mul(8).saturating_add(1 << 20)), ..Default::default() };
|
||||
return Ok(crate::try_read_exif_with(&buf, &opts).ok().and_then(|m| m.focus));
|
||||
}
|
||||
Step::Nothing => return Ok(None),
|
||||
@@ -354,7 +353,7 @@ impl Want<'_> {
|
||||
|
||||
/// What of a classic TIFF the focus decoder still needs, given what is `loaded`: IFD0 (Make, Model,
|
||||
/// the Exif pointer), the Exif IFD (the maker-note entry), the maker note's header and IFD as
|
||||
/// `lightcraft_tiff::makernote` locates it, and the focus tags' values.
|
||||
/// `craft_tiff::makernote` locates it, and the focus tags' values.
|
||||
fn plan(buf: &[u8], loaded: &Loaded) -> Step {
|
||||
let Some((order, false)) = Tiff::sniff(buf) else { return Step::Nothing };
|
||||
let mut w = Want { buf, order, loaded, need: Vec::new() };
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! (box structure from ISO/IEC 14496-12, item model from ISO/IEC 23008-12).
|
||||
//!
|
||||
//! HEIC is what iPhones and Macs write. Its pixels need an HEVC decoder (the optional
|
||||
//! `lightcraft-heif` crate), its metadata does not, so this reader is in every build: a HEIC
|
||||
//! `craft-heif` crate), its metadata does not, so this reader is in every build: a HEIC
|
||||
//! imports with its capture time, camera and lens whether or not the build can show the picture.
|
||||
//!
|
||||
//! The `meta` box holds an item information box (`iinf`, one `infe` per item) naming each item's
|
||||
@@ -198,7 +198,7 @@ mod tests {
|
||||
use super::*;
|
||||
// the whole routing, not just this module: a HEIC must reach the HEIF branch of `embedded`
|
||||
use crate::embedded;
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value, tags as t};
|
||||
|
||||
/// One box: its own size, its four-letter kind, then its payload.
|
||||
fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
|
||||
@@ -390,14 +390,14 @@ mod tests {
|
||||
assert!(embedded(&lying).exif.is_none());
|
||||
}
|
||||
|
||||
/// The real container writer of `lightcraft-heif`, so the reader is proved against the layout
|
||||
/// The real container writer of `craft-heif`, so the reader is proved against the layout
|
||||
/// a HEIF encoder produces and not only against this module's own test builder.
|
||||
#[test]
|
||||
fn a_synthetic_heif_file_carries_its_exif() {
|
||||
let tiff = iphone_exif("2026:10:18 13:00:00", "-05:00");
|
||||
let mut spec = lightcraft_heif::testdata::Spec::new(64, 64, &|x, _| [x as u16 * 4, 0, 0]);
|
||||
let mut spec = craft_heif::testdata::Spec::new(64, 64, &|x, _| [x as u16 * 4, 0, 0]);
|
||||
spec.exif = Some(tiff.clone());
|
||||
let file = lightcraft_heif::testdata::build(&spec);
|
||||
let file = craft_heif::testdata::build(&spec);
|
||||
assert!(is_heif(&file));
|
||||
assert_eq!(embedded(&file).exif.as_deref(), Some(tiff.as_slice()));
|
||||
assert_eq!(crate::extract(&file).capture_time.map(|d| d.to_iso()).as_deref(), Some("2026-10-18T13:00:00-05:00"));
|
||||
|
||||
+15
-15
@@ -555,7 +555,7 @@ mod tests {
|
||||
j.extend(payload);
|
||||
};
|
||||
// orientation 6, 6000 × 4000 as stored
|
||||
seg([b"Exif\0\0".as_slice(), &crate::exif::tests::sample_exif(lightcraft_tiff::ByteOrder::Little)].concat());
|
||||
seg([b"Exif\0\0".as_slice(), &crate::exif::tests::sample_exif(craft_tiff::ByteOrder::Little)].concat());
|
||||
seg([b"http://ns.adobe.com/xap/1.0/\0".as_slice(), packet.as_bytes()].concat());
|
||||
j.extend([0xff, 0xd9]);
|
||||
j
|
||||
@@ -600,10 +600,10 @@ mod tests {
|
||||
assert!(near(m.regions[0].rect, DRAWN), "{:?}", m.regions[0].rect);
|
||||
assert_eq!(try_extract(&j).unwrap().regions, m.regions);
|
||||
// a TIFF-based file: the whole file is the Exif block, with the XMP in its first IFD
|
||||
let mut ifd0 = lightcraft_tiff::IfdBuilder::new();
|
||||
ifd0.set(lightcraft_tiff::tags::ORIENTATION, lightcraft_tiff::Value::Short(vec![6]));
|
||||
ifd0.set(lightcraft_tiff::tags::XMP, lightcraft_tiff::Value::Byte(packet.into_bytes()));
|
||||
let m = extract(&lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap());
|
||||
let mut ifd0 = craft_tiff::IfdBuilder::new();
|
||||
ifd0.set(craft_tiff::tags::ORIENTATION, craft_tiff::Value::Short(vec![6]));
|
||||
ifd0.set(craft_tiff::tags::XMP, craft_tiff::Value::Byte(packet.into_bytes()));
|
||||
let m = extract(&craft_tiff::TiffWriter::default().write(&[ifd0]).unwrap());
|
||||
assert_eq!((m.orientation, m.width, m.height), (Some(Orientation::Rotate90), Some(4000), Some(6000)));
|
||||
assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect);
|
||||
}
|
||||
@@ -615,14 +615,14 @@ mod tests {
|
||||
fn an_orientation_only_the_xmp_states_turns_no_regions() {
|
||||
// 6000 × 4000 in the Exif, and no orientation
|
||||
let size_ifd = || {
|
||||
let mut sub = lightcraft_tiff::IfdBuilder::new();
|
||||
sub.set(lightcraft_tiff::tags::PIXEL_X_DIMENSION, lightcraft_tiff::Value::Long(vec![6000]));
|
||||
sub.set(lightcraft_tiff::tags::PIXEL_Y_DIMENSION, lightcraft_tiff::Value::Long(vec![4000]));
|
||||
let mut sub = craft_tiff::IfdBuilder::new();
|
||||
sub.set(craft_tiff::tags::PIXEL_X_DIMENSION, craft_tiff::Value::Long(vec![6000]));
|
||||
sub.set(craft_tiff::tags::PIXEL_Y_DIMENSION, craft_tiff::Value::Long(vec![4000]));
|
||||
sub
|
||||
};
|
||||
let mut exif_ifd0 = lightcraft_tiff::IfdBuilder::new();
|
||||
exif_ifd0.set_child(lightcraft_tiff::tags::EXIF_IFD, size_ifd());
|
||||
let exif = lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[exif_ifd0]).unwrap();
|
||||
let mut exif_ifd0 = craft_tiff::IfdBuilder::new();
|
||||
exif_ifd0.set_child(craft_tiff::tags::EXIF_IFD, size_ifd());
|
||||
let exif = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[exif_ifd0]).unwrap();
|
||||
let packet = regions_packet(6000, 4000, "")
|
||||
.replace(r#"rdf:about="""#, r#"rdf:about="" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" tiff:Orientation="6""#);
|
||||
let mut j = vec![0xff, 0xd8];
|
||||
@@ -641,10 +641,10 @@ mod tests {
|
||||
assert!(near(m.regions[0].rect, DRAWN), "turned by an orientation the Exif doesn't state: {:?}", m.regions[0].rect);
|
||||
assert_eq!(try_extract(&j).unwrap().regions, m.regions);
|
||||
// a TIFF-based file: the first IFD has no orientation, its XMP (tag 700) has
|
||||
let mut ifd0 = lightcraft_tiff::IfdBuilder::new();
|
||||
ifd0.set(lightcraft_tiff::tags::XMP, lightcraft_tiff::Value::Byte(packet.into_bytes()));
|
||||
ifd0.set_child(lightcraft_tiff::tags::EXIF_IFD, size_ifd());
|
||||
let m = extract(&lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap());
|
||||
let mut ifd0 = craft_tiff::IfdBuilder::new();
|
||||
ifd0.set(craft_tiff::tags::XMP, craft_tiff::Value::Byte(packet.into_bytes()));
|
||||
ifd0.set_child(craft_tiff::tags::EXIF_IFD, size_ifd());
|
||||
let m = extract(&craft_tiff::TiffWriter::default().write(&[ifd0]).unwrap());
|
||||
assert_eq!(m.orientation, Some(Orientation::Rotate90));
|
||||
assert!(near(m.regions[0].rect, DRAWN), "TIFF: {:?}", m.regions[0].rect);
|
||||
}
|
||||
|
||||
@@ -177,9 +177,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn try_extract_accepts_unknown_exif_tags_in_psd() {
|
||||
let mut ifd0 = lightcraft_tiff::IfdBuilder::new();
|
||||
ifd0.set(0xc001, lightcraft_tiff::Value::Ascii("vendor metadata".into()));
|
||||
let exif = lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap();
|
||||
let mut ifd0 = craft_tiff::IfdBuilder::new();
|
||||
ifd0.set(0xc001, craft_tiff::Value::Ascii("vendor metadata".into()));
|
||||
let exif = craft_tiff::TiffWriter::default().write(&[ifd0]).unwrap();
|
||||
let file = image(1, &[], &resource(1058, b"", &exif));
|
||||
assert!(crate::try_extract(&file).is_ok());
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! binary blobs are summarised by size; of a maker note only the lens name is listed (the
|
||||
//! Panasonic one, as Panasonic writes no Exif LensModel).
|
||||
|
||||
use lightcraft_tiff::{Ifd, Tiff, Value};
|
||||
use craft_tiff::{Ifd, Tiff, Value};
|
||||
|
||||
/// One metadata row.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -318,7 +318,7 @@ fn nikon_nef_compression(tiff: &Tiff, bytes: &[u8]) -> Option<&'static str> {
|
||||
return None;
|
||||
}
|
||||
let e = ifd0.exif.as_ref()?.get(0x927c)?;
|
||||
let mn = lightcraft_tiff::makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)?;
|
||||
let mn = craft_tiff::makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)?;
|
||||
nef_compression(mn.ifd.u32(0x0093)?)
|
||||
}
|
||||
|
||||
@@ -516,7 +516,7 @@ mod tests {
|
||||
let rw2 = crate::exif::tests::panasonic_rw2("LUMIX S 85/F1.8");
|
||||
assert_eq!(lens(&file_tag_rows(&rw2)), ["LUMIX S 85/F1.8"]);
|
||||
// a JPEG: the note is in its own Exif
|
||||
let exif = crate::exif::tests::panasonic_exif(lightcraft_tiff::ByteOrder::Big, Some("LUMIX G 25/F1.7"), None);
|
||||
let exif = crate::exif::tests::panasonic_exif(craft_tiff::ByteOrder::Big, Some("LUMIX G 25/F1.7"), None);
|
||||
let mut jpg = vec![0xff, 0xd8, 0xff, 0xe1];
|
||||
jpg.extend_from_slice(&((exif.len() + 8) as u16).to_be_bytes());
|
||||
jpg.extend(b"Exif\0\0");
|
||||
|
||||
@@ -656,12 +656,12 @@ fn frac(v: f64) -> String {
|
||||
return format!("1/{}", inv.round() as u64);
|
||||
}
|
||||
}
|
||||
let (n, d) = lightcraft_tiff::writer::rational(v);
|
||||
let (n, d) = craft_tiff::writer::rational(v);
|
||||
format!("{n}/{d}")
|
||||
}
|
||||
|
||||
fn sfrac(v: f64) -> String {
|
||||
let (n, d) = lightcraft_tiff::writer::srational(v);
|
||||
let (n, d) = craft_tiff::writer::srational(v);
|
||||
format!("{n}/{d}")
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ description = "LightCraft RAW decoding, demosaicing and DNG colour model (L1)"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
lightcraft-tiff = { workspace = true }
|
||||
craft-tiff = { workspace = true }
|
||||
lightcraft-meta = { workspace = true }
|
||||
lightcraft-raster = { workspace = true }
|
||||
lightcraft-color = { workspace = true }
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! Prints the TIFF structure (with `--tree`), decode result, timings (MP/s) and basic statistics.
|
||||
//! Exits unsuccessfully if any input cannot be read, decoded or developed, while inspecting the remaining files.
|
||||
|
||||
use craft_tiff::{Ifd, Tiff, Value};
|
||||
use lightcraft_raw::{Method, RawData, decode, embedded_preview, probe};
|
||||
use lightcraft_tiff::{Ifd, Tiff, Value};
|
||||
use std::process::ExitCode;
|
||||
use std::time::Instant;
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
//!
|
||||
//! Quick visual check: develop → as-shot WB + camera matrix → sRGB, oriented, box-downscaled, 8-bit TIFF.
|
||||
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags};
|
||||
use lightcraft_color::{REC2020, SRGB, transfer::encode_srgb8};
|
||||
use lightcraft_raw::{Method, color, decode};
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags};
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! `UniqueCameraModel`, `ProfileName`, the colour/forward matrices and calibration illuminants, the
|
||||
//! hue/saturation map, look table and tone curve. Nothing here ships a profile.
|
||||
|
||||
use lightcraft_tiff::{Ifd, ParseOptions, Tiff, tags as t};
|
||||
use craft_tiff::{Ifd, ParseOptions, Tiff, tags as t};
|
||||
|
||||
use crate::ColorData;
|
||||
use crate::dng::color_data;
|
||||
@@ -118,8 +118,8 @@ pub fn parse_dcp(bytes: &[u8]) -> Result<DcpProfile, DcpError> {
|
||||
/// Write `p` as a `.dcp` file (little-endian): its name, camera, illuminants, matrices, hue/saturation
|
||||
/// map, look table, tone curve and baseline exposure offset.
|
||||
pub fn write_dcp(p: &DcpProfile) -> Result<Vec<u8>, DcpError> {
|
||||
use lightcraft_tiff::writer::srational;
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
|
||||
use craft_tiff::writer::srational;
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
|
||||
let c = &p.color;
|
||||
let mut ifd = IfdBuilder::new();
|
||||
ifd.set(t::UNIQUE_CAMERA_MODEL, Value::Ascii(p.camera_model.clone()));
|
||||
|
||||
@@ -5,10 +5,10 @@ use crate::gaintable::GainTableMap;
|
||||
use crate::profile::{HsvTable, ProfileLook, ToneCurve};
|
||||
use crate::tiffraw::{Packing, read_image_in};
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mat3, Mode, RawData, RawError, RawFormat, RawImage, Rect, Result, opcodes};
|
||||
use craft_tiff::tags::{self as t, photometric};
|
||||
use craft_tiff::{ByteOrder, Ifd, Tiff};
|
||||
use lightcraft_color::Xy;
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::tags::{self as t, photometric};
|
||||
use lightcraft_tiff::{ByteOrder, Ifd, Tiff};
|
||||
|
||||
/// The main raw IFD: full-resolution (NewSubfileType 0) CFA or LinearRaw image with the most pixels.
|
||||
pub(crate) fn raw_ifd(tiff: &Tiff) -> Option<&Ifd> {
|
||||
@@ -183,7 +183,7 @@ pub(crate) fn is_plain_cfa_tiff(tiff: &Tiff, bytes: &[u8]) -> bool {
|
||||
t::compression::JPEG => info
|
||||
.chunks(bytes.len() as u64)
|
||||
.first()
|
||||
.and_then(|c| lightcraft_tiff::image::chunk_bytes(bytes, c))
|
||||
.and_then(|c| craft_tiff::image::chunk_bytes(bytes, c))
|
||||
.is_some_and(|src| crate::ljpeg::frame_info(src).is_ok()),
|
||||
_ => false,
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
//! bit-exact decoder round-trip tests. The raw image is stored in IFD0 (allowed by DNG 1.7 §"File Structure").
|
||||
|
||||
use crate::{RawData, RawError, RawImage, Result, ljpeg, opcodes};
|
||||
use craft_tiff::tags::{self as t, compression, photometric};
|
||||
use craft_tiff::writer::{rational, srational};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use lightcraft_color::Mat3;
|
||||
use lightcraft_tiff::tags::{self as t, compression, photometric};
|
||||
use lightcraft_tiff::writer::{rational, srational};
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use rayon::prelude::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
//! `MapPointsV` / `MapPointsH` is below 256 (their product is at most [`MAX_TABLES`]), so swapped
|
||||
//! it is at least 2^24 and the size checks reject it. We write in the file's byte order.
|
||||
|
||||
use lightcraft_tiff::ByteOrder;
|
||||
use craft_tiff::ByteOrder;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Upper bound on `MapPointsV × MapPointsH` (Apple uses 6 × 8).
|
||||
|
||||
+23
-23
@@ -70,8 +70,8 @@ pub use preview::{
|
||||
};
|
||||
pub use semantic::{SemanticMask, semantic_masks};
|
||||
|
||||
use craft_tiff::{Tiff, TiffError};
|
||||
use lightcraft_color::Xy;
|
||||
use lightcraft_tiff::{Tiff, TiffError};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Upper bound on decoded samples (guards allocations driven by header values).
|
||||
@@ -189,28 +189,28 @@ pub fn probe(bytes: &[u8]) -> Option<RawFormat> {
|
||||
return Some(RawFormat::Cr2);
|
||||
}
|
||||
let (_, _) = Tiff::sniff(bytes)?;
|
||||
let opts = lightcraft_tiff::ParseOptions { max_ifds: 256, ..Default::default() };
|
||||
let opts = craft_tiff::ParseOptions { max_ifds: 256, ..Default::default() };
|
||||
let t = Tiff::parse_with(bytes, &opts).ok()?;
|
||||
let ifd0 = t.ifds.first()?;
|
||||
if ifd0.contains(lightcraft_tiff::tags::DNG_VERSION) {
|
||||
if ifd0.contains(craft_tiff::tags::DNG_VERSION) {
|
||||
return Some(RawFormat::Dng);
|
||||
}
|
||||
let make = t.find(lightcraft_tiff::tags::MAKE).and_then(|e| e.value.as_str()).unwrap_or_default().to_ascii_uppercase();
|
||||
let make = t.find(craft_tiff::tags::MAKE).and_then(|e| e.value.as_str()).unwrap_or_default().to_ascii_uppercase();
|
||||
let has_cfa = has_raw_ifd(&t);
|
||||
// Pentax's reader takes the layout from the Exif `CFAPattern` when no IFD has a CFA photometric (uncompressed
|
||||
// and PackBits PEFs), so for the Pentax family that tag counts as raw evidence too
|
||||
let pentax_raw = has_cfa || t.exif().is_some_and(|e| e.contains(vendor::EXIF_CFA_PATTERN));
|
||||
// Samsung's raw IFD uses private compressions 32769..=32773 (`vendor::srw`), 32773 being PackBits elsewhere
|
||||
let samsung_raw = has_cfa || t.all_ifds().iter().any(|i| i.u16(lightcraft_tiff::tags::COMPRESSION).is_some_and(|c| (32769..=32773).contains(&c)));
|
||||
let samsung_raw = has_cfa || t.all_ifds().iter().any(|i| i.u16(craft_tiff::tags::COMPRESSION).is_some_and(|c| (32769..=32773).contains(&c)));
|
||||
// Sony raws without a CFA IFD (#702): SRF (DSC-F828), whose IFD0 looks like RGB but holds 14-bit samples (12 or
|
||||
// 14 count: raw sensor depths; the raw is in Sony's SRF blocks), and the DSLR-A100, whose IFD0 is an old-style
|
||||
// JPEG thumbnail (compression 6, which today's TIFF writers don't produce) and whose `SubIFDs` tag addresses its
|
||||
// raw data. A camera-authored or exported TIFF has 8- or 16-bit samples, and its SubIFDs hold ordinary images
|
||||
let model = t.find(lightcraft_tiff::tags::MODEL).and_then(|e| e.value.as_str()).unwrap_or_default().trim().to_ascii_uppercase();
|
||||
let model = t.find(craft_tiff::tags::MODEL).and_then(|e| e.value.as_str()).unwrap_or_default().trim().to_ascii_uppercase();
|
||||
let sony_raw = has_cfa
|
||||
|| ifd0.u64s(lightcraft_tiff::tags::BITS_PER_SAMPLE).is_some_and(|b| b.iter().any(|v| matches!(v, 12 | 14)))
|
||||
|| (model == "DSLR-A100" && ifd0.u16(lightcraft_tiff::tags::COMPRESSION) == Some(6) && ifd0.contains(lightcraft_tiff::tags::SUB_IFDS));
|
||||
if make.starts_with("CANON") && t.ifds.len() >= 4 && t.ifds[3].u16(lightcraft_tiff::tags::COMPRESSION) == Some(6) {
|
||||
|| ifd0.u64s(craft_tiff::tags::BITS_PER_SAMPLE).is_some_and(|b| b.iter().any(|v| matches!(v, 12 | 14)))
|
||||
|| (model == "DSLR-A100" && ifd0.u16(craft_tiff::tags::COMPRESSION) == Some(6) && ifd0.contains(craft_tiff::tags::SUB_IFDS));
|
||||
if make.starts_with("CANON") && t.ifds.len() >= 4 && t.ifds[3].u16(craft_tiff::tags::COMPRESSION) == Some(6) {
|
||||
return Some(RawFormat::Cr2);
|
||||
}
|
||||
if make.starts_with("NIKON") && has_cfa {
|
||||
@@ -218,7 +218,7 @@ pub fn probe(bytes: &[u8]) -> Option<RawFormat> {
|
||||
}
|
||||
// Hasselblad's Sony-built bodies (the Lunar is a NEX-7 inside) write a Sony ARW under their own Make. Sony's
|
||||
// raw coding gives them away: compression 32767 or the raw IFD's tone-curve tag 0x7010, which no 3FR / FFF has
|
||||
let sony_coded = || t.all_ifds().iter().any(|i| i.u16(lightcraft_tiff::tags::COMPRESSION) == Some(32767) || i.contains(0x7010));
|
||||
let sony_coded = || t.all_ifds().iter().any(|i| i.u16(craft_tiff::tags::COMPRESSION) == Some(32767) || i.contains(0x7010));
|
||||
if (make.starts_with("SONY") && sony_raw) || (make.starts_with("HASSELBLAD") && sony_coded()) {
|
||||
return Some(RawFormat::Arw);
|
||||
}
|
||||
@@ -257,13 +257,13 @@ const LEAF_DATA: u16 = 0x8606;
|
||||
/// An uncompressed Leaf MOS: IFD0 is the 16-bit mosaic itself (compression 1, BlackIsZero, one sample per pixel),
|
||||
/// with no Make tag and no CFA photometric, so only Leaf's data block marks it as a raw (issue #1275). A rendered
|
||||
/// RGB image that kept the block stays an ordinary image.
|
||||
fn is_leaf_mosaic(ifd0: &lightcraft_tiff::Ifd) -> bool {
|
||||
ifd0.contains(LEAF_DATA) && ifd0.u16(lightcraft_tiff::tags::SAMPLES_PER_PIXEL).unwrap_or(1) == 1
|
||||
fn is_leaf_mosaic(ifd0: &craft_tiff::Ifd) -> bool {
|
||||
ifd0.contains(LEAF_DATA) && ifd0.u16(craft_tiff::tags::SAMPLES_PER_PIXEL).unwrap_or(1) == 1
|
||||
}
|
||||
|
||||
/// Whether the Exif maker note starts with the signature of the Pentax layouts (`AOC\0` or `PENTAX \0`).
|
||||
fn has_pentax_maker_note(t: &Tiff, bytes: &[u8]) -> bool {
|
||||
let Some(e) = t.exif().and_then(|e| e.get(lightcraft_tiff::tags::MAKER_NOTE)) else { return false };
|
||||
let Some(e) = t.exif().and_then(|e| e.get(craft_tiff::tags::MAKER_NOTE)) else { return false };
|
||||
bytes.get(e.offset as usize..).is_some_and(|n| n.starts_with(b"AOC\0") || n.starts_with(b"PENTAX \0"))
|
||||
}
|
||||
|
||||
@@ -272,19 +272,19 @@ fn has_pentax_maker_note(t: &Tiff, bytes: &[u8]) -> bool {
|
||||
/// or vendor-specific raw tags (Sony tone curve, CFA pattern, or Pentax compression 65535).
|
||||
fn has_raw_ifd(t: &Tiff) -> bool {
|
||||
t.all_ifds().iter().any(|i| {
|
||||
i.u16(lightcraft_tiff::tags::PHOTOMETRIC) == Some(lightcraft_tiff::tags::photometric::CFA)
|
||||
|| i.u16(lightcraft_tiff::tags::COMPRESSION).is_some_and(|c| matches!(c, 34713 | 32767 | 32769 | 32770 | 99 | 65535))
|
||||
i.u16(craft_tiff::tags::PHOTOMETRIC) == Some(craft_tiff::tags::photometric::CFA)
|
||||
|| i.u16(craft_tiff::tags::COMPRESSION).is_some_and(|c| matches!(c, 34713 | 32767 | 32769 | 32770 | 99 | 65535))
|
||||
|| i.contains(0x7010)
|
||||
|| i.contains(lightcraft_tiff::tags::CFA_PATTERN_EP)
|
||||
|| i.contains(lightcraft_tiff::tags::CFA_REPEAT_PATTERN_DIM)
|
||||
|| i.contains(craft_tiff::tags::CFA_PATTERN_EP)
|
||||
|| i.contains(craft_tiff::tags::CFA_REPEAT_PATTERN_DIM)
|
||||
})
|
||||
}
|
||||
|
||||
/// IFD0 that is not an image at all: no `ImageWidth` / `ImageLength`, but a JPEG preview pointer or
|
||||
/// `SubIFDs` (the layout of Kodak KDC files, whose pictures sit in private tags). A plain TIFF reader
|
||||
/// rejects such a file as malformed even though it carries a preview.
|
||||
fn is_preview_container(ifd0: &lightcraft_tiff::Ifd) -> bool {
|
||||
use lightcraft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, JPEG_INTERCHANGE_FORMAT, SUB_IFDS};
|
||||
fn is_preview_container(ifd0: &craft_tiff::Ifd) -> bool {
|
||||
use craft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, JPEG_INTERCHANGE_FORMAT, SUB_IFDS};
|
||||
!ifd0.contains(IMAGE_WIDTH) && !ifd0.contains(IMAGE_LENGTH) && (ifd0.contains(JPEG_INTERCHANGE_FORMAT) || ifd0.contains(SUB_IFDS))
|
||||
}
|
||||
|
||||
@@ -309,7 +309,7 @@ pub(crate) struct ThumbnailShell {
|
||||
/// A multi-page TIFF is not caught (its pages are the IFD chain, not `SubIFDs`), nor a pyramid whose
|
||||
/// IFD0 is the full image.
|
||||
fn thumbnail_shell(t: &Tiff, len: usize) -> Option<ThumbnailShell> {
|
||||
use lightcraft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, PIXEL_X_DIMENSION, PIXEL_Y_DIMENSION};
|
||||
use craft_tiff::tags::{IMAGE_LENGTH, IMAGE_WIDTH, PIXEL_X_DIMENSION, PIXEL_Y_DIMENSION};
|
||||
let ifd0 = t.ifds.first()?;
|
||||
let (w0, h0) = (ifd0.u32(IMAGE_WIDTH)?, ifd0.u32(IMAGE_LENGTH)?);
|
||||
if w0 == 0 || h0 == 0 {
|
||||
@@ -352,12 +352,12 @@ fn thumbnail_shell(t: &Tiff, len: usize) -> Option<ThumbnailShell> {
|
||||
|
||||
/// Why [`decode`] gives up on a file [`probe`] called [`RawFormat::OtherTiff`].
|
||||
fn other_tiff_reason(bytes: &[u8]) -> String {
|
||||
let t = Tiff::parse_with(bytes, &lightcraft_tiff::ParseOptions { max_ifds: 256, ..Default::default() }).ok();
|
||||
let t = Tiff::parse_with(bytes, &craft_tiff::ParseOptions { max_ifds: 256, ..Default::default() }).ok();
|
||||
// a DNG-style CFA IFD whose lossless JPEG the lossless decoder rejects: say why
|
||||
if let Some(t) = &t
|
||||
&& let Some(info) = dng::raw_ifd(t).and_then(|i| i.image().ok())
|
||||
&& info.compression == lightcraft_tiff::tags::compression::JPEG
|
||||
&& let Some(src) = info.chunks(bytes.len() as u64).first().and_then(|c| lightcraft_tiff::image::chunk_bytes(bytes, c))
|
||||
&& info.compression == craft_tiff::tags::compression::JPEG
|
||||
&& let Some(src) = info.chunks(bytes.len() as u64).first().and_then(|c| craft_tiff::image::chunk_bytes(bytes, c))
|
||||
&& let Err(e) = ljpeg::frame_info(src)
|
||||
{
|
||||
return format!("raw image coded as lossless JPEG that is not decoded yet ({e})");
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
//! or a DNG 1.7 JPEG XL preview IFD stored as a single tile/strip (a standalone `.jxl` file, as the spec
|
||||
//! recommends for previews).
|
||||
|
||||
use lightcraft_tiff::image::chunk_bytes;
|
||||
use lightcraft_tiff::tags as t;
|
||||
use lightcraft_tiff::{Ifd, Tiff, makernote};
|
||||
use craft_tiff::image::chunk_bytes;
|
||||
use craft_tiff::tags as t;
|
||||
use craft_tiff::{Ifd, Tiff, makernote};
|
||||
|
||||
/// Colour space of an embedded JPEG when the enclosing raw supplies it instead of the JPEG.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -203,7 +203,7 @@ fn jpeg_end(s: &[u8], budget: &mut usize) -> Option<usize> {
|
||||
fn candidates<'a>(data: &'a [u8], ifd: &Ifd, base: u64, out: &mut Vec<&'a [u8]>, budget: &mut usize) {
|
||||
// whole JPEG files stored as an undefined-type tag value (e.g. Panasonic `JpgFromRaw` 0x002e)
|
||||
for e in &ifd.entries {
|
||||
if matches!(e.value, lightcraft_tiff::Value::Undefined(_))
|
||||
if matches!(e.value, craft_tiff::Value::Undefined(_))
|
||||
&& e.count() > 1024
|
||||
&& let Some(s) = file_span(data, e.offset, e.count() as u64, budget)
|
||||
&& s.starts_with(&[0xff, 0xd8])
|
||||
@@ -310,7 +310,7 @@ fn preview_covering(bytes: &[u8], min_edge: Option<u32>) -> Option<Vec<u8>> {
|
||||
if let Some(mn) = makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make) {
|
||||
candidates(bytes, &mn.ifd, mn.base, &mut found, &mut budget);
|
||||
if let Some(off) = mn.ifd.u64(0x0011)
|
||||
&& let Ok((pifd, _)) = lightcraft_tiff::parse_ifd_at(bytes, mn.base + off, mn.order, mn.base, false, &Default::default())
|
||||
&& let Ok((pifd, _)) = craft_tiff::parse_ifd_at(bytes, mn.base + off, mn.order, mn.base, false, &Default::default())
|
||||
{
|
||||
candidates(bytes, &pifd, mn.base, &mut found, &mut budget);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
|
||||
fn fake_jpeg(n: usize) -> Vec<u8> {
|
||||
let mut j = vec![0xff, 0xd8, 0xff, 0xc0, 0x00, 0x0b, 8, 0, 1, 0, 1, 1, 1, 0x11, 0];
|
||||
@@ -394,10 +394,9 @@ fn cr3_with_color_space(exif: Option<u16>, note: Option<u16>) -> Vec<u8> {
|
||||
let block = |tag: u16, v: Option<u16>| {
|
||||
let ifd =
|
||||
v.map_or_else(|| IfdBuilder::new().with(t::ISO_SPEED, Value::Short(vec![100])), |v| IfdBuilder::new().with(tag, Value::Short(vec![v])));
|
||||
TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap()
|
||||
TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd]).unwrap()
|
||||
};
|
||||
let cmt1 =
|
||||
TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[IfdBuilder::new().with(t::MAKE, Value::Ascii("Canon".into()))]).unwrap();
|
||||
let cmt1 = TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[IfdBuilder::new().with(t::MAKE, Value::Ascii("Canon".into()))]).unwrap();
|
||||
let canon_uuid = [0x85, 0xc0, 0xb6, 0x87, 0x82, 0x0f, 0x11, 0xe0, 0x81, 0x11, 0xf4, 0xce, 0x46, 0x2b, 0x6a, 0x48];
|
||||
let boxes = [bx(b"CMT1", &cmt1), bx(b"CMT2", &block(0xA001, exif)), bx(b"CMT3", &block(0x00b4, note))].concat();
|
||||
let mut file = bx(b"ftyp", b"crx \0\0\0\x01crx isom");
|
||||
@@ -444,7 +443,7 @@ fn cr2_preview_colour_space_comes_from_the_canon_maker_note() {
|
||||
}
|
||||
let mut ifd0 = IfdBuilder::new().with(t::MAKE, Value::Ascii(make.into()));
|
||||
ifd0.set_child(t::EXIF_IFD, exif);
|
||||
TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[ifd0]).unwrap()
|
||||
TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[ifd0]).unwrap()
|
||||
};
|
||||
assert_eq!(embedded_preview_color_space(&cr2("Canon", 0xFFFF, Some(2))), Some(AdobeRgb));
|
||||
assert_eq!(embedded_preview_color_space(&cr2("Canon", 1, Some(1))), Some(Srgb));
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
use crate::Rect;
|
||||
use crate::tiffraw::{Packing, read_image};
|
||||
use crate::{RawData, Result};
|
||||
use craft_tiff::Tiff;
|
||||
use craft_tiff::tags::{self as t, photometric};
|
||||
use lightcraft_raster::Image;
|
||||
use lightcraft_tiff::Tiff;
|
||||
use lightcraft_tiff::tags::{self as t, photometric};
|
||||
|
||||
/// At most this many mask IFDs are read from one file.
|
||||
pub const MAX_MASKS: usize = 16;
|
||||
@@ -55,7 +55,7 @@ pub fn semantic_masks(bytes: &[u8]) -> Vec<SemanticMask> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_mask(bytes: &[u8], tiff: &Tiff, ifd: &lightcraft_tiff::Ifd) -> Result<Option<SemanticMask>> {
|
||||
fn read_mask(bytes: &[u8], tiff: &Tiff, ifd: &craft_tiff::Ifd) -> Result<Option<SemanticMask>> {
|
||||
let Some(name) = ifd.string(t::SEMANTIC_NAME).filter(|n| !n.is_empty()) else { return Ok(None) };
|
||||
let info = ifd.image()?;
|
||||
let (w, h) = (info.width as usize, info.height as usize);
|
||||
|
||||
@@ -19,8 +19,8 @@
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use craft_tiff::{ByteOrder, FieldType, Tiff, tags as t};
|
||||
use lightcraft_meta::cr3::{Cr3TrackKind, XMP_UUID, is_cr3, parse_cr3};
|
||||
use lightcraft_tiff::{ByteOrder, FieldType, Tiff, tags as t};
|
||||
|
||||
use crate::RawFormat;
|
||||
|
||||
@@ -29,7 +29,7 @@ use crate::RawFormat;
|
||||
const HEAD: u64 = 64 * 1024;
|
||||
/// An image whose chunks hold fewer bytes than this is read (thumbnails, small previews).
|
||||
const BULK: u64 = 256 * 1024;
|
||||
/// The same bounds as `lightcraft_tiff`'s reader.
|
||||
/// The same bounds as `craft_tiff`'s reader.
|
||||
const MAX_IFDS: usize = 1024;
|
||||
const MAX_ENTRIES: u64 = 8192;
|
||||
const MAX_BOXES: usize = 4096;
|
||||
@@ -301,7 +301,7 @@ fn tiff_plan(bytes: &[u8], loaded: &Ranges, preview: bool) -> HeaderPlan {
|
||||
})
|
||||
}
|
||||
|
||||
/// Walk the IFDs of the TIFF in `data` (which starts at `origin` in the file) as `lightcraft_tiff`'s
|
||||
/// Walk the IFDs of the TIFF in `data` (which starts at `origin` in the file) as `craft_tiff`'s
|
||||
/// reader does — the chain, `SubIFDs`, Exif, GPS and Interop, plus the `extra` pointer tags —
|
||||
/// asking for every IFD table and for the values that locate IFDs and image chunks. Returns the IFD
|
||||
/// tables and out-of-line values found (absolute ranges); incomplete while `w` needs more.
|
||||
|
||||
@@ -120,7 +120,7 @@ fn black_levels() {
|
||||
|
||||
// --- TIFF shells around a private raw block (thumbnail-only IFD0) ---
|
||||
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
|
||||
/// An uncompressed 8-bit RGB image IFD.
|
||||
fn rgb_ifd(w: u32, h: u32) -> IfdBuilder {
|
||||
@@ -408,7 +408,7 @@ fn uncompressed_leaf_mos_is_a_raw() {
|
||||
}
|
||||
ifd
|
||||
};
|
||||
let bytes = TiffWriter::new(lightcraft_tiff::ByteOrder::Big, false).write(&[mosaic(true)]).unwrap();
|
||||
let bytes = TiffWriter::new(craft_tiff::ByteOrder::Big, false).write(&[mosaic(true)]).unwrap();
|
||||
assert_eq!(probe(&bytes), Some(RawFormat::OtherTiff));
|
||||
assert!(matches!(decode(&bytes), Err(RawError::Unsupported(_))));
|
||||
assert!(matches!(probe_info(&bytes), Err(RawError::Unsupported(_))));
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
use crate::unpack::{f16_to_f32, f24_to_f32, inflate, read_u16s, undo_diff_u16, undo_float_predictor, unpack_lsb, unpack_msb, unpack_words32_msb};
|
||||
use crate::{MAX_SAMPLES, RawData, RawError, Result, ljpeg};
|
||||
use lightcraft_tiff::image::{Chunk, ImageInfo, chunk_bytes};
|
||||
use lightcraft_tiff::{ByteOrder, tags::compression as comp};
|
||||
use craft_tiff::image::{Chunk, ImageInfo, chunk_bytes};
|
||||
use craft_tiff::{ByteOrder, tags::compression as comp};
|
||||
use rayon::prelude::*;
|
||||
|
||||
/// Bit packing for uncompressed integer data with bit depths other than 8/16.
|
||||
@@ -51,8 +51,11 @@ pub fn check_image(data: &[u8], info: &ImageInfo) -> Result<usize> {
|
||||
let (across, down) = info.grid();
|
||||
let planes = if info.planar == 2 { cpp } else { 1 };
|
||||
let expected = (across as usize).saturating_mul(down as usize).saturating_mul(planes);
|
||||
if chunks.len() < expected {
|
||||
return Err(RawError::Corrupt(format!("{} image data chunks, expected {expected}", chunks.len())));
|
||||
// the offsets table says how many chunks the image declares: craft-tiff builds at most one
|
||||
// descriptor per byte of file (craft-libs#827), so `chunks` may be shorter on a grid of tiles
|
||||
// sharing one payload, and the bytes behind it are what the bounds below count.
|
||||
if info.offsets.len() < expected {
|
||||
return Err(RawError::Corrupt(format!("{} image data chunks, expected {expected}", info.offsets.len())));
|
||||
}
|
||||
// Tile sizes don't depend on the image size, and every tile is decoded at its nominal size and held until the copy:
|
||||
// a grid of tiles no larger than the image covers less than twice its width and height, so more than four times
|
||||
@@ -461,7 +464,7 @@ fn unpack_chunk(
|
||||
#[cfg(test)]
|
||||
mod lossy_tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::image::Layout;
|
||||
use craft_tiff::image::Layout;
|
||||
|
||||
/// 65 536 tiles all pointing at the same 256 bytes: the image's samples can't come from them,
|
||||
/// and nothing of its size is allocated to find that out.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! predictor), DNG 1.7 (predictors 34892–34895, bit packing, 16/24-bit floats), RFC 1950/1951 (zlib/deflate).
|
||||
|
||||
use crate::{RawError, Result};
|
||||
use lightcraft_tiff::ByteOrder;
|
||||
use craft_tiff::ByteOrder;
|
||||
|
||||
/// Unpack `out.len()` MSB-first packed samples of `bits` (1..=16) from `src` (TIFF bit order).
|
||||
pub fn unpack_msb(src: &[u8], bits: u32, out: &mut [u16]) {
|
||||
|
||||
@@ -30,7 +30,7 @@ mod sr2;
|
||||
pub mod srw;
|
||||
|
||||
use crate::{BlackLevel, Cfa, Rect};
|
||||
use lightcraft_tiff::Tiff;
|
||||
use craft_tiff::Tiff;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Exif `CFAPattern`.
|
||||
@@ -247,7 +247,7 @@ pub(crate) fn declare_strip_len(file: &mut [u8], len: u32, declared: u32) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::tags as t;
|
||||
use craft_tiff::tags as t;
|
||||
|
||||
/// `file`, whose image IFD holds one strip, as two strips at the same offset whose StripByteCounts are LONG8 (which
|
||||
/// classic TIFF readers accept) `[u64::MAX, 1]`: their sum is past `u64::MAX`.
|
||||
|
||||
Vendored
+27
-27
@@ -48,10 +48,10 @@ use super::arw6;
|
||||
use crate::lens_metadata::SonyLensGeometry;
|
||||
use crate::tiffraw::{Packing, check_image, read_image_in};
|
||||
use crate::{BlackLevel, Cfa, ColorData, LensMetadata, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg};
|
||||
use craft_tiff::image::{Chunk, ImageInfo, Layout, chunk_bytes};
|
||||
use craft_tiff::tags::{self as t, photometric};
|
||||
use craft_tiff::{Ifd, Tiff, makernote};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::image::{Chunk, ImageInfo, Layout, chunk_bytes};
|
||||
use lightcraft_tiff::tags::{self as t, photometric};
|
||||
use lightcraft_tiff::{Ifd, Tiff, makernote};
|
||||
use rayon::prelude::*;
|
||||
|
||||
const TONE_CURVE: u16 = 0x7010;
|
||||
@@ -226,7 +226,7 @@ fn sony_body<'a>(make: &str, model: &'a str, mn: Option<&makernote::MakerNote>)
|
||||
/// White balance from the maker note's enciphered `Tag2010` block, the fallback described at [`TAG2010_WB`].
|
||||
/// `model` is the Sony body ([`sony_body`]); Sony appends a regional "V" to some names (SLT-A77V), which the
|
||||
/// documented lists omit.
|
||||
fn tag2010_wb(model: &str, block: &[u8], order: lightcraft_tiff::ByteOrder) -> Option<[f32; 3]> {
|
||||
fn tag2010_wb(model: &str, block: &[u8], order: craft_tiff::ByteOrder) -> Option<[f32; 3]> {
|
||||
let model = model.trim();
|
||||
let &(_, offset) = TAG2010_WB.iter().find(|(models, _)| models.iter().any(|m| model == *m || model.strip_suffix('V') == Some(*m)))?;
|
||||
let bytes: Vec<u8> = block.get(offset..offset + 6)?.iter().map(|&b| DECIPHER[b as usize]).collect();
|
||||
@@ -523,7 +523,7 @@ fn sr2_old_crop(sr2: &super::sr2::SubIfd, w: usize, h: usize) -> Option<Rect> {
|
||||
}
|
||||
|
||||
/// One black level from the four deciphered per-channel levels (their mean), when they are near-equal and plausible.
|
||||
fn sr2_black_levels(plain: &[u8], order: lightcraft_tiff::ByteOrder) -> Option<f32> {
|
||||
fn sr2_black_levels(plain: &[u8], order: craft_tiff::ByteOrder) -> Option<f32> {
|
||||
let levels: Vec<u16> = (0..4).filter_map(|i| order.read_u16(plain, 2 * i)).collect();
|
||||
let (&lo, &hi) = (levels.iter().min()?, levels.iter().max()?);
|
||||
(levels.len() == 4 && (64..=4096).contains(&lo) && hi - lo <= 64).then(|| levels.iter().map(|&v| f32::from(v)).sum::<f32>() / 4.0)
|
||||
@@ -532,8 +532,8 @@ fn sr2_black_levels(plain: &[u8], order: lightcraft_tiff::ByteOrder) -> Option<f
|
||||
/// Byte order of 16-bit-word samples: the file's own order unless the words only fit the sample width in the other
|
||||
/// (see the DSC-R1 note at the top). Sampled across the strip; the order is swapped only when the file order leaves
|
||||
/// more than 1 % of the sampled words at or above `1 << max(bits, 14)` while the other order leaves none.
|
||||
fn word16_order(strip: &[u8], bits: u32, file: lightcraft_tiff::ByteOrder) -> lightcraft_tiff::ByteOrder {
|
||||
use lightcraft_tiff::ByteOrder::{Big, Little};
|
||||
fn word16_order(strip: &[u8], bits: u32, file: craft_tiff::ByteOrder) -> craft_tiff::ByteOrder {
|
||||
use craft_tiff::ByteOrder::{Big, Little};
|
||||
let other = if file == Little { Big } else { Little };
|
||||
let limit = 1u32 << bits.clamp(14, 16);
|
||||
let (mut n, mut over_file, mut over_other) = (0usize, 0usize, 0usize);
|
||||
@@ -836,7 +836,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn downsized_lossless_is_linear_rgb_not_cfa() {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let mut raw = IfdBuilder::new();
|
||||
raw.set(t::MAKE, Value::Ascii("SONY".into()));
|
||||
raw.set(t::MODEL, Value::Ascii("ILCE-7M4".into()));
|
||||
@@ -894,7 +894,7 @@ mod tests {
|
||||
|
||||
/// A 32767-compressed ARW whose single strip is `strip` bytes for a 32 x 4 image.
|
||||
fn arw_with_strip(strip: usize) -> Vec<u8> {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let mut raw = IfdBuilder::new();
|
||||
raw.set(t::MAKE, Value::Ascii("SONY".into()));
|
||||
raw.set(t::MODEL, Value::Ascii("DSLR-A200".into()));
|
||||
@@ -923,7 +923,7 @@ mod tests {
|
||||
/// [`super::super::arw_lens_rm6`]).
|
||||
#[test]
|
||||
fn lens_tables_reach_opcode_list3() {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let file = |model: &str, ca: bool| {
|
||||
let mut raw = IfdBuilder::new();
|
||||
raw.set(t::MAKE, Value::Ascii("SONY".into()));
|
||||
@@ -974,7 +974,7 @@ mod tests {
|
||||
|
||||
/// A 32767-compressed, 12-bit ARW of `w` x `h` whose single strip is `strip`.
|
||||
fn packed_arw(w: u32, h: u32, strip: Vec<u8>) -> Vec<u8> {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let mut raw = IfdBuilder::new();
|
||||
raw.set(t::MAKE, Value::Ascii("SONY".into()));
|
||||
raw.set(t::MODEL, Value::Ascii("DSLR-A900".into()));
|
||||
@@ -1111,7 +1111,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn tag2010_white_balance_by_model() {
|
||||
use lightcraft_tiff::ByteOrder::Little;
|
||||
use craft_tiff::ByteOrder::Little;
|
||||
let mut plain = vec![0u8; 700];
|
||||
for (i, v) in [669u16, 256, 441].iter().enumerate() {
|
||||
plain[612 + 2 * i..614 + 2 * i].copy_from_slice(&v.to_le_bytes());
|
||||
@@ -1134,8 +1134,8 @@ mod tests {
|
||||
|
||||
/// A Sony-style file: IFD0 (`make`) → Exif → maker note `SONY DSC \0\0\0` + an IFD of `entries` (tag, type,
|
||||
/// count, inline value bytes), the layout of the camera's own notes; `count` overrides the entry count.
|
||||
fn sony_file(order: lightcraft_tiff::ByteOrder, make: &str, entries: &[(u16, u16, u32, [u8; 4])], count: Option<u16>) -> Vec<u8> {
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
|
||||
fn sony_file(order: craft_tiff::ByteOrder, make: &str, entries: &[(u16, u16, u32, [u8; 4])], count: Option<u16>) -> Vec<u8> {
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, TiffWriter, Value};
|
||||
let (u16b, u32b) = match order {
|
||||
ByteOrder::Little => (u16::to_le_bytes as fn(u16) -> [u8; 2], u32::to_le_bytes as fn(u32) -> [u8; 4]),
|
||||
ByteOrder::Big => (u16::to_be_bytes as fn(u16) -> [u8; 2], u32::to_be_bytes as fn(u32) -> [u8; 4]),
|
||||
@@ -1160,7 +1160,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn dynamic_range_optimizer_is_read_from_the_sony_note() {
|
||||
use lightcraft_tiff::ByteOrder::{Big, Little};
|
||||
use craft_tiff::ByteOrder::{Big, Little};
|
||||
let long = |order, v: u32| match order {
|
||||
Little => v.to_le_bytes(),
|
||||
Big => v.to_be_bytes(),
|
||||
@@ -1195,7 +1195,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn hostile_sony_notes_are_read_safely() {
|
||||
use lightcraft_tiff::ByteOrder::Little;
|
||||
use craft_tiff::ByteOrder::Little;
|
||||
let entry = [(MN_DYNAMIC_RANGE_OPTIMIZER, 4, 1, 3u32.to_le_bytes())];
|
||||
let good = sony_file(Little, "SONY", &entry, None);
|
||||
assert_eq!(crate::embedded_preview_dynamic_range_optimized(&good), Some(true));
|
||||
@@ -1211,9 +1211,9 @@ mod tests {
|
||||
assert_eq!(crate::embedded_preview_dynamic_range_optimized(b"not a TIFF"), None);
|
||||
assert_eq!(crate::embedded_preview_dynamic_range_optimized(&[]), None);
|
||||
// a Sony file without a maker note
|
||||
let mut ifd0 = lightcraft_tiff::IfdBuilder::new();
|
||||
ifd0.set(t::MAKE, lightcraft_tiff::Value::Ascii("SONY".into()));
|
||||
assert_eq!(crate::embedded_preview_dynamic_range_optimized(&lightcraft_tiff::TiffWriter::new(Little, false).write(&[ifd0]).unwrap()), None);
|
||||
let mut ifd0 = craft_tiff::IfdBuilder::new();
|
||||
ifd0.set(t::MAKE, craft_tiff::Value::Ascii("SONY".into()));
|
||||
assert_eq!(crate::embedded_preview_dynamic_range_optimized(&craft_tiff::TiffWriter::new(Little, false).write(&[ifd0]).unwrap()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1238,7 +1238,7 @@ mod tests {
|
||||
/// (reached through `DNGPrivateData` and the `SR2Private` IFD, as Sony stores it, with `key`; black level 800)
|
||||
/// and a maker note whose `Tag2010` block (RX100 III layout) holds `WB_RGBLevels`.
|
||||
fn arw_with_wb(plain: Option<[u16; 4]>, sr2: Option<[u16; 4]>, tag2010: Option<[u16; 3]>, key: [u8; 4]) -> Vec<u8> {
|
||||
use lightcraft_tiff::{ByteOrder::Little, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{ByteOrder::Little, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let mut tag2010_block = vec![0u8; 700];
|
||||
for (i, v) in tag2010.unwrap_or([0; 3]).iter().enumerate() {
|
||||
tag2010_block[612 + 2 * i..614 + 2 * i].copy_from_slice(&v.to_le_bytes());
|
||||
@@ -1307,7 +1307,7 @@ mod tests {
|
||||
/// balance; without the ID, or with one that isn't listed, there is no layout to read.
|
||||
#[test]
|
||||
fn rebadged_body_takes_its_tag2010_layout_from_the_sony_model_id() {
|
||||
use lightcraft_tiff::{ByteOrder::Little, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{ByteOrder::Little, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let file = |make: &str, model: &str, id: Option<u16>| {
|
||||
let mut block = vec![0u8; 4600];
|
||||
for (i, v) in [639u16, 256, 368].iter().enumerate() {
|
||||
@@ -1371,7 +1371,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn dsc_r1_sr2_subifd_gives_black_wb_and_crop() {
|
||||
use lightcraft_tiff::ByteOrder::Little;
|
||||
use craft_tiff::ByteOrder::Little;
|
||||
let key = [0x63, 0xbe, 0x01, 0x3e];
|
||||
let enc = |crop: [u16; 4], wb: [u16; 4]| {
|
||||
let b = super::super::sr2::tests::block_keyed(
|
||||
@@ -1453,7 +1453,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn sr2_black_level_decodes_and_rejects_garbage() {
|
||||
use lightcraft_tiff::ByteOrder::Little;
|
||||
use craft_tiff::ByteOrder::Little;
|
||||
let plain = |levels: [u16; 4]| -> Vec<u8> { levels.iter().flat_map(|v| v.to_le_bytes()).collect() };
|
||||
assert_eq!(sr2_black_levels(&plain([800; 4]), Little), Some(800.0));
|
||||
assert_eq!(sr2_black_levels(&plain([512, 512, 514, 512]), Little), Some(512.5));
|
||||
@@ -1486,13 +1486,13 @@ mod tests {
|
||||
}
|
||||
|
||||
/// [`sr2_black`] on the encrypted `SR2SubIFD` bytes `block`, which start at file offset `start`.
|
||||
fn sr2_black_in(block: &[u8], start: usize, order: lightcraft_tiff::ByteOrder) -> Option<f32> {
|
||||
fn sr2_black_in(block: &[u8], start: usize, order: craft_tiff::ByteOrder) -> Option<f32> {
|
||||
sr2_black(&super::super::sr2::SubIfd::decrypt(block, start, order))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sr2_black_level_follows_the_first_entry_to_its_layout() {
|
||||
use lightcraft_tiff::ByteOrder::Little;
|
||||
use craft_tiff::ByteOrder::Little;
|
||||
let start = 37584;
|
||||
// the value position of every layout seen, e.g. the DSLR-A700's (62112 bytes, value at 1638) and the
|
||||
// DSLR-A450/A500/A550's (27152 bytes, value at 2166); the first four are those of bodies without a plain 0x7310
|
||||
@@ -1521,7 +1521,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn word16_byte_order_follows_the_sample_range() {
|
||||
use lightcraft_tiff::ByteOrder::{Big, Little};
|
||||
use craft_tiff::ByteOrder::{Big, Little};
|
||||
let be: Vec<u8> = (0..4096u16).flat_map(|i| (512 + i * 3).to_be_bytes()).collect(); // 512..12800 big-endian words
|
||||
assert_eq!(word16_order(&be, 14, Little), Big);
|
||||
let le: Vec<u8> = (0..4096u16).flat_map(|i| (512 + i * 3).to_le_bytes()).collect();
|
||||
@@ -1584,7 +1584,7 @@ mod tests {
|
||||
/// decode allocates the frame.
|
||||
#[test]
|
||||
fn a_strip_cut_short_is_refused_before_allocating() {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let (w, h) = (3000u32, 2000u32);
|
||||
for declared in [w * h, w * h / 2 * 3] {
|
||||
let mut raw = IfdBuilder::new();
|
||||
|
||||
Vendored
+3
-3
@@ -543,9 +543,9 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::vendor::arw6_testenc::*;
|
||||
use crate::vendor::pef::Bits;
|
||||
use lightcraft_tiff::Tiff;
|
||||
use lightcraft_tiff::image::chunk_bytes;
|
||||
use lightcraft_tiff::tags as t;
|
||||
use craft_tiff::Tiff;
|
||||
use craft_tiff::image::chunk_bytes;
|
||||
use craft_tiff::tags as t;
|
||||
|
||||
fn planes(w2: usize, h2: usize, seed: u64) -> (Plane, Plane, Plane, Plane) {
|
||||
let mut x = seed.max(1);
|
||||
|
||||
+2
-2
@@ -2,8 +2,8 @@
|
||||
//! Section names in italics refer to `docs/arw6-compression.md`.
|
||||
|
||||
use crate::llvc::{Bands3, Plane, band_rows};
|
||||
use lightcraft_tiff::tags as t;
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::tags as t;
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
|
||||
/// Exact inverse of `dequant` on representable values: `sign(v) * (|v| >> qi)`.
|
||||
pub(crate) fn quantize(v: i32, qi: u32) -> i32 {
|
||||
|
||||
Vendored
+3
-3
@@ -25,7 +25,7 @@ use crate::lens_metadata::{
|
||||
SonySource,
|
||||
};
|
||||
use crate::{Opcode, Rect};
|
||||
use lightcraft_tiff::{ByteOrder, FieldType, Ifd, Value};
|
||||
use craft_tiff::{ByteOrder, FieldType, Ifd, Value};
|
||||
|
||||
/// Each component's setting and table tags, `(raw IFD, SR2SubIFD)`.
|
||||
const SHADING: Tags = Tags { setting: (0x7031, 0x797c), table: (0x7032, 0x797d) };
|
||||
@@ -545,8 +545,8 @@ mod tests {
|
||||
use crate::lens_metadata::SonyCopy::{Absent, Rejected, Valid};
|
||||
use crate::lens_metadata::SonyFieldError::*;
|
||||
use crate::{LensMetadata, Mode, RawImage};
|
||||
use lightcraft_tiff::ByteOrder::{Big, Little};
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, Tiff, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::ByteOrder::{Big, Little};
|
||||
use craft_tiff::{IfdBuilder, ImageData, Tiff, TiffWriter, Value, tags as t};
|
||||
|
||||
const TELE: [i16; 16] = [-2, 1, 7, 17, 31, 48, 68, 93, 120, 152, 187, 225, 265, 309, 356, 403];
|
||||
const WIDE: [i16; 16] = [14, 0, -27, -59, -106, -158, -223, -291, -367, -440, -519, -593, -667, -731, -792, -839];
|
||||
|
||||
+2
-2
@@ -47,7 +47,7 @@
|
||||
use super::fit_radial_warp;
|
||||
use crate::opcodes::max_radius;
|
||||
use crate::{Opcode, Rect};
|
||||
use lightcraft_tiff::Ifd;
|
||||
use craft_tiff::Ifd;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
pub(crate) const DISTORTION_PARAMS: u16 = 0x7037;
|
||||
@@ -272,7 +272,7 @@ pub(crate) fn lens_opcodes(raw: &Ifd, model: &str, lens: Option<&str>, focal_mm:
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{Entry, Value};
|
||||
use craft_tiff::{Entry, Value};
|
||||
|
||||
/// The FF 16–35 mm example (corpus `arw-sony-ilce7rm6-ff-land-lossless.arw`, docs/sony-ilce7rm6-lens-corrections.md).
|
||||
const FF_DISTORTION: [i16; 17] = [16, 0, 2, 7, 16, 28, 43, 61, 83, 109, 139, 175, 217, 267, 325, 395, 479];
|
||||
|
||||
Vendored
+5
-5
@@ -27,9 +27,9 @@ mod sraw;
|
||||
|
||||
use super::{active_rows, black_from_columns, white_from_data};
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg};
|
||||
use craft_tiff::image::chunk_bytes;
|
||||
use craft_tiff::{ByteOrder, Ifd, Tiff, Value, makernote, tags as t};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::image::chunk_bytes;
|
||||
use lightcraft_tiff::{ByteOrder, Ifd, Tiff, Value, makernote, tags as t};
|
||||
use std::ops::Range;
|
||||
|
||||
const CR2_SLICE: u16 = 0xc640;
|
||||
@@ -192,9 +192,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
Some(v) if v != 1 => return Err(RawError::Unsupported(format!("Canon raw type {v}"))),
|
||||
_ => {}
|
||||
}
|
||||
let off = raw.u64(t::STRIP_OFFSETS).ok_or(RawError::Tiff(lightcraft_tiff::TiffError::MissingTag(t::STRIP_OFFSETS)))?;
|
||||
let off = raw.u64(t::STRIP_OFFSETS).ok_or(RawError::Tiff(craft_tiff::TiffError::MissingTag(t::STRIP_OFFSETS)))?;
|
||||
let len = raw.u64(t::STRIP_BYTE_COUNTS).unwrap_or(bytes.len() as u64 - off.min(bytes.len() as u64));
|
||||
let chunk = lightcraft_tiff::image::Chunk { index: 0, x: 0, y: 0, width: 0, height: 0, plane: 0, offset: off, len };
|
||||
let chunk = craft_tiff::image::Chunk { index: 0, x: 0, y: 0, width: 0, height: 0, plane: 0, offset: off, len };
|
||||
let src = chunk_bytes(bytes, &chunk).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?;
|
||||
let (fw, fh, nc, prec) = ljpeg::frame_info(src)?;
|
||||
let frame = match mode {
|
||||
@@ -306,7 +306,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
|
||||
/// Build a synthetic CR2: IFD0..IFD2 placeholders + IFD3 holding a sliced 2-component LJ92 frame.
|
||||
pub(crate) fn synthetic_cr2(w: usize, h: usize, slices: Option<[u16; 3]>) -> (Vec<u8>, Vec<u16>) {
|
||||
|
||||
Vendored
+4
-4
@@ -28,9 +28,9 @@
|
||||
|
||||
use super::{COLOR_BALANCE, CR2_SLICE, SENSOR_INFO, words};
|
||||
use crate::{BlackLevel, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg};
|
||||
use craft_tiff::image::{Chunk, chunk_bytes};
|
||||
use craft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::image::{Chunk, chunk_bytes};
|
||||
use lightcraft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t};
|
||||
use rayon::prelude::*;
|
||||
|
||||
/// Chroma samples are centred on this value.
|
||||
@@ -335,7 +335,7 @@ fn colour_data_black(words: &[u64]) -> Option<f32> {
|
||||
/// Decode a Canon sRAW / mRAW CR2 into linear white-balanced camera RGB (`cpp` 3).
|
||||
pub(super) fn decode(bytes: &[u8], tiff: &Tiff, raw: &Ifd, mode: Mode) -> Result<RawImage> {
|
||||
let ifd0 = &tiff.ifds[0];
|
||||
let off = raw.u64(t::STRIP_OFFSETS).ok_or(RawError::Tiff(lightcraft_tiff::TiffError::MissingTag(t::STRIP_OFFSETS)))?;
|
||||
let off = raw.u64(t::STRIP_OFFSETS).ok_or(RawError::Tiff(craft_tiff::TiffError::MissingTag(t::STRIP_OFFSETS)))?;
|
||||
let len = raw.u64(t::STRIP_BYTE_COUNTS).unwrap_or(bytes.len() as u64 - off.min(bytes.len() as u64));
|
||||
let chunk = Chunk { index: 0, x: 0, y: 0, width: 0, height: 0, plane: 0, offset: off, len };
|
||||
let src = chunk_bytes(bytes, &chunk).ok_or_else(|| RawError::Corrupt("raw strip outside file".into()))?;
|
||||
@@ -403,7 +403,7 @@ pub(super) fn decode(bytes: &[u8], tiff: &Tiff, raw: &Ifd, mode: Mode) -> Result
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
|
||||
const SRAW_TYPE_TAG: u16 = 0xc6c5;
|
||||
|
||||
|
||||
Vendored
+6
-6
@@ -20,8 +20,8 @@
|
||||
|
||||
use super::{black_from_columns, crx, white_from_data};
|
||||
use crate::{BlackLevel, Cfa, ColorData, MAX_SAMPLES, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};
|
||||
use craft_tiff::{Ifd, Tiff};
|
||||
use lightcraft_meta::cr3::{Cr3ImageArea, Cr3Track, Cr3TrackKind, parse_cr3};
|
||||
use lightcraft_tiff::{Ifd, Tiff};
|
||||
|
||||
const SENSOR_INFO: u16 = 0x00e0;
|
||||
const COLOR_DATA: u16 = 0x4001;
|
||||
@@ -282,7 +282,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{IfdBuilder, Value};
|
||||
use craft_tiff::{IfdBuilder, Value};
|
||||
|
||||
fn maker(version: u16, wb_at: usize, black_at: usize, white_at: usize) -> Ifd {
|
||||
let mut words = vec![0u16; white_at + 1];
|
||||
@@ -291,7 +291,7 @@ mod tests {
|
||||
words[black_at..black_at + 4].copy_from_slice(&[100, 101, 102, 103]);
|
||||
words[white_at] = 15000;
|
||||
let b = IfdBuilder::new().with(COLOR_DATA, Value::Short(words));
|
||||
let bytes = lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[b]).unwrap();
|
||||
let bytes = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[b]).unwrap();
|
||||
Tiff::parse(&bytes).unwrap().ifds.remove(0)
|
||||
}
|
||||
|
||||
@@ -321,7 +321,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn synthetic_header_with(aspect: Option<[u32; 5]>) -> Vec<u8> {
|
||||
use lightcraft_tiff::{ByteOrder, TiffWriter, tags as t};
|
||||
use craft_tiff::{ByteOrder, TiffWriter, tags as t};
|
||||
let tiff = |b: IfdBuilder| TiffWriter::new(ByteOrder::Little, false).write(&[b]).unwrap();
|
||||
let cmt1 = tiff(
|
||||
IfdBuilder::new()
|
||||
@@ -460,8 +460,8 @@ mod tests {
|
||||
/// and `AspectInfo` applies from its origin.
|
||||
#[test]
|
||||
fn aspect_info_needs_a_consistent_recommended_crop() {
|
||||
let aspect = lightcraft_tiff::IfdBuilder::new().with(ASPECT_INFO, Value::Long(vec![13, 5088, 3392, 0, 0]));
|
||||
let bytes = lightcraft_tiff::TiffWriter::new(lightcraft_tiff::ByteOrder::Little, false).write(&[aspect]).unwrap();
|
||||
let aspect = craft_tiff::IfdBuilder::new().with(ASPECT_INFO, Value::Long(vec![13, 5088, 3392, 0, 0]));
|
||||
let bytes = craft_tiff::TiffWriter::new(craft_tiff::ByteOrder::Little, false).write(&[aspect]).unwrap();
|
||||
let maker = Tiff::parse(&bytes).unwrap().ifds.remove(0);
|
||||
let area =
|
||||
|crop| Cr3ImageArea { width: 5376, height: 3574, crop, active: Some([132, 160, 5243, 3567]), masked_left: [0; 4], masked_top: None };
|
||||
|
||||
Vendored
+6
-6
@@ -20,9 +20,9 @@
|
||||
//! - The preview is the maker note's tag `0x0280`, a JPEG whose first byte is stored as `ee` (found by the
|
||||
//! structural scan in `preview::scan_for_jpeg`).
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};
|
||||
use craft_tiff::image::chunk_bytes;
|
||||
use craft_tiff::{Ifd, Tiff, tags as t};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::image::chunk_bytes;
|
||||
use lightcraft_tiff::{Ifd, Tiff, tags as t};
|
||||
|
||||
/// Epson's private compression code for the 16-byte block layout.
|
||||
const BLOCKS16: u16 = 32769;
|
||||
@@ -58,8 +58,8 @@ fn maker_note(bytes: &[u8], tiff: &Tiff) -> Option<Ifd> {
|
||||
if !bytes.get(start..)?.starts_with(b"EPSON\0") {
|
||||
return None;
|
||||
}
|
||||
let opts = lightcraft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() };
|
||||
lightcraft_tiff::parse_ifd_at(bytes, e.offset.checked_add(8)?, tiff.order, 0, false, &opts).ok().map(|(i, _)| i)
|
||||
let opts = craft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() };
|
||||
craft_tiff::parse_ifd_at(bytes, e.offset.checked_add(8)?, tiff.order, 0, false, &opts).ok().map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// Unpack a strip of 16-byte blocks (15 bytes of ten MSB-first 12-bit samples, one pad byte).
|
||||
@@ -137,7 +137,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
|
||||
/// Pack ten-sample groups into 16-byte blocks, MSB first, zero pad.
|
||||
fn pack(px: &[u16]) -> Vec<u8> {
|
||||
@@ -168,7 +168,7 @@ mod tests {
|
||||
ifd0.set(t::MODEL, Value::Ascii("R-D1".into()));
|
||||
ifd0.set(t::ORIENTATION, Value::Short(vec![1]));
|
||||
ifd0.add_sub_ifd(raw);
|
||||
TiffWriter::new(lightcraft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap()
|
||||
TiffWriter::new(craft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Vendored
+3
-3
@@ -25,8 +25,8 @@
|
||||
//! [`rgb_preview`] hands the largest 8-bit one on as a small baseline TIFF.
|
||||
use crate::dng;
|
||||
use crate::{ColorData, Mode, RawFormat, RawImage, Result};
|
||||
use lightcraft_tiff::image::{Layout, chunk_bytes};
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, ParseOptions, Tiff, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::image::{Layout, chunk_bytes};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, ParseOptions, Tiff, TiffWriter, Value, tags as t};
|
||||
|
||||
/// Private IFD0 tag holding the original 3FR header (a complete TIFF) inside an FFF.
|
||||
pub(crate) const ORIGINAL_HEADER: u16 = 0xc51b;
|
||||
@@ -124,7 +124,7 @@ fn adopt_matrices(color: &mut ColorData, from: &ColorData) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{RawData, RawError, decode as decode_file, probe, probe_info};
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
|
||||
const MATRIX: [(i32, i32); 9] =
|
||||
[(686, 1000), (-196, 1000), (-32, 1000), (-437, 1000), (1228, 1000), (235, 1000), (-165, 1000), (317, 1000), (675, 1000)];
|
||||
|
||||
Vendored
+5
-5
@@ -24,9 +24,9 @@
|
||||
//! each other) the raw G/R is 0.94 and G/B 1.96; `0x848` (1913, 1834, 921) gives 0.96 and 1.99, the others
|
||||
//! 0.77..1.25 and 2.08..2.96, so its green over red and over blue are the gains.
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, ljpeg};
|
||||
use craft_tiff::image::chunk_bytes;
|
||||
use craft_tiff::{Ifd, Tiff, tags as t};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::image::chunk_bytes;
|
||||
use lightcraft_tiff::{Ifd, Tiff, tags as t};
|
||||
|
||||
/// The vendor IFD pointer (`KodakIFD`).
|
||||
const KODAK_IFD: u16 = 0x8290;
|
||||
@@ -127,8 +127,8 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
/// The vendor IFD (`KodakIFD`): a plain IFD with absolute value offsets.
|
||||
fn kodak_ifd(bytes: &[u8], tiff: &Tiff, ifd0: &Ifd) -> Option<Ifd> {
|
||||
let off = u64::from(ifd0.u32(KODAK_IFD)?);
|
||||
let opts = lightcraft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() };
|
||||
lightcraft_tiff::parse_ifd_at(bytes, off, tiff.order, 0, false, &opts).ok().map(|(i, _)| i)
|
||||
let opts = craft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() };
|
||||
craft_tiff::parse_ifd_at(bytes, off, tiff.order, 0, false, &opts).ok().map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// Black level per CFA position (the mosaic's first sample is position 0): the value below which only 0.01% of that
|
||||
@@ -167,7 +167,7 @@ fn measured_black(d: &[u16], w: usize) -> BlackLevel {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{decode, probe, probe_info};
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
|
||||
const W: usize = 16;
|
||||
const H: usize = 8;
|
||||
|
||||
Vendored
+3
-3
@@ -16,9 +16,9 @@
|
||||
//! - No white-balance tag was found (the maker note holds an ICC-like profile), so the as-shot gains are measured
|
||||
//! from that preview's neutral pixels ([`crate::wb_estimate`]).
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};
|
||||
use craft_tiff::image::chunk_bytes;
|
||||
use craft_tiff::{Ifd, Tiff, tags as t};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::image::chunk_bytes;
|
||||
use lightcraft_tiff::{Ifd, Tiff, tags as t};
|
||||
|
||||
/// Where the preview's window starts in the sensor frame, and how many sensor pixels one preview pixel covers.
|
||||
const CROP_ORIGIN: (usize, usize) = (24, 12);
|
||||
@@ -142,7 +142,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
|
||||
fn pack(px: &[u16]) -> Vec<u8> {
|
||||
px.chunks(2).flat_map(|p| [(p[0] >> 4) as u8, ((p[0] & 15) << 4) as u8 | (p[1] >> 8) as u8, p[1] as u8]).collect()
|
||||
|
||||
Vendored
+6
-6
@@ -24,8 +24,8 @@
|
||||
//! - `TTW` is a TIFF with IFD0 (orientation), Exif and the maker note; the preview JPEG sits in it with its first
|
||||
//! byte overwritten (see `preview::scan_for_jpeg`).
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result, unpack};
|
||||
use craft_tiff::{Tiff, tags as t};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::{Tiff, tags as t};
|
||||
|
||||
/// Storage method codes in `PRD`.
|
||||
const PACKED_12: u8 = 0x59;
|
||||
@@ -80,7 +80,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode) -> Result<RawImage> {
|
||||
if p.packed {
|
||||
unpack::unpack_msb(src, 12, &mut d);
|
||||
} else {
|
||||
unpack::read_u16s(src, lightcraft_tiff::ByteOrder::Big, &mut d);
|
||||
unpack::read_u16s(src, craft_tiff::ByteOrder::Big, &mut d);
|
||||
for v in &mut d {
|
||||
*v = (*v).min(4095);
|
||||
}
|
||||
@@ -154,10 +154,10 @@ pub(crate) mod tests {
|
||||
for v in wbg {
|
||||
wb.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
let mut ifd0 = lightcraft_tiff::IfdBuilder::new();
|
||||
ifd0.set(t::MAKE, lightcraft_tiff::Value::Ascii("Minolta Co., Ltd.".into()));
|
||||
ifd0.set(t::ORIENTATION, lightcraft_tiff::Value::Short(vec![6]));
|
||||
let ttw = lightcraft_tiff::TiffWriter::default().write(&[ifd0]).unwrap();
|
||||
let mut ifd0 = craft_tiff::IfdBuilder::new();
|
||||
ifd0.set(t::MAKE, craft_tiff::Value::Ascii("Minolta Co., Ltd.".into()));
|
||||
ifd0.set(t::ORIENTATION, craft_tiff::Value::Short(vec![6]));
|
||||
let ttw = craft_tiff::TiffWriter::default().write(&[ifd0]).unwrap();
|
||||
let mut body = Vec::new();
|
||||
for (name, data) in [(b"PRD", &prd), (b"WBG", &wb), (b"TTW", &ttw)] {
|
||||
body.push(0);
|
||||
|
||||
Vendored
+9
-9
@@ -15,10 +15,10 @@
|
||||
use super::{nefc, white_from_data};
|
||||
use crate::tiffraw::{Packing, check_image, read_image};
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};
|
||||
use craft_tiff::image::ImageInfo;
|
||||
use craft_tiff::tags::{self as t, photometric};
|
||||
use craft_tiff::{ByteOrder, Ifd, Tiff, makernote};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::image::ImageInfo;
|
||||
use lightcraft_tiff::tags::{self as t, photometric};
|
||||
use lightcraft_tiff::{ByteOrder, Ifd, Tiff, makernote};
|
||||
|
||||
const WB_RB_LEVELS: u16 = 0x000c;
|
||||
const BLACK_LEVEL: u16 = 0x003d;
|
||||
@@ -500,7 +500,7 @@ fn packed(bytes: &[u8], info: &ImageInfo, rows: usize) -> Result<RawData> {
|
||||
let (Some(layout), [c]) = (layout, chunks.as_slice()) else {
|
||||
return Err(RawError::Unsupported("Nikon compressed NEF without a linearization table (maker note 0x96)".into()));
|
||||
};
|
||||
let src = lightcraft_tiff::image::chunk_bytes(bytes, c)
|
||||
let src = craft_tiff::image::chunk_bytes(bytes, c)
|
||||
.filter(|src| u64::try_from(src.len()).ok() == Some(c.len))
|
||||
.ok_or_else(|| RawError::Corrupt("NEF: incomplete image strip".into()))?;
|
||||
if (w as u64).saturating_mul(h as u64) > crate::MAX_SAMPLES as u64 {
|
||||
@@ -538,7 +538,7 @@ const SMALL_RAW_B_GAIN: f32 = 4.4;
|
||||
|
||||
/// The strip of a small raw: compression 34713, 12 bits, no maker note `0x0096`, one strip of exactly
|
||||
/// `3 * width * height` bytes (even width).
|
||||
fn small_raw_strip(info: &ImageInfo, file_len: usize, mn: Option<&makernote::MakerNote>) -> Option<lightcraft_tiff::image::Chunk> {
|
||||
fn small_raw_strip(info: &ImageInfo, file_len: usize, mn: Option<&makernote::MakerNote>) -> Option<craft_tiff::image::Chunk> {
|
||||
if info.compression != t::compression::NIKON || info.bits() != 12 || info.samples_per_pixel != 1 {
|
||||
return None;
|
||||
}
|
||||
@@ -584,12 +584,12 @@ fn small_raw_row(src: &[u8], w: usize, out: &mut [u16]) {
|
||||
}
|
||||
}
|
||||
|
||||
fn small_raw(bytes: &[u8], tiff: &Tiff, info: &ImageInfo, strip: lightcraft_tiff::image::Chunk, mode: Mode) -> Result<RawImage> {
|
||||
fn small_raw(bytes: &[u8], tiff: &Tiff, info: &ImageInfo, strip: craft_tiff::image::Chunk, mode: Mode) -> Result<RawImage> {
|
||||
use rayon::prelude::*;
|
||||
let (w, h) = (info.width as usize, info.height as usize);
|
||||
let stride = w.checked_mul(3).ok_or(RawError::Limit("image too large"))?;
|
||||
let count = stride.checked_mul(h).filter(|n| *n > 0 && *n <= crate::MAX_SAMPLES).ok_or(RawError::Limit("image too large"))?;
|
||||
let src = lightcraft_tiff::image::chunk_bytes(bytes, &strip)
|
||||
let src = craft_tiff::image::chunk_bytes(bytes, &strip)
|
||||
.filter(|src| u64::try_from(src.len()).ok() == Some(strip.len))
|
||||
.ok_or_else(|| RawError::Corrupt("NEF: incomplete image strip".into()))?;
|
||||
let data = match mode {
|
||||
@@ -634,7 +634,7 @@ fn small_raw(bytes: &[u8], tiff: &Tiff, info: &ImageInfo, strip: lightcraft_tiff
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
|
||||
fn nef(compression: u16, bits: u16, strips: Vec<Vec<u8>>, w: u32, h: u32, rps: u32) -> Vec<u8> {
|
||||
nef_with_note(compression, bits, strips, w, h, rps, None)
|
||||
@@ -1397,7 +1397,7 @@ mod tests {
|
||||
let raw = raw_ifd(&tiff).unwrap();
|
||||
let info = raw.image().unwrap();
|
||||
let chunk = info.chunks(bytes.len() as u64)[0];
|
||||
let data = lightcraft_tiff::image::chunk_bytes(&bytes, &chunk).unwrap().to_vec();
|
||||
let data = craft_tiff::image::chunk_bytes(&bytes, &chunk).unwrap().to_vec();
|
||||
let offset_entry = raw.get(t::STRIP_OFFSETS).unwrap().offset as usize;
|
||||
let start = bytes.len() as u32;
|
||||
bytes[offset_entry..offset_entry + 4].copy_from_slice(&start.to_be_bytes());
|
||||
|
||||
Vendored
+3
-3
@@ -8,7 +8,7 @@
|
||||
//! No lens database or external decoder code.
|
||||
|
||||
use crate::{Opcode, Rect};
|
||||
use lightcraft_tiff::{ByteOrder, Ifd, ParseOptions, parse_ifd_at};
|
||||
use craft_tiff::{ByteOrder, Ifd, ParseOptions, parse_ifd_at};
|
||||
|
||||
const NEF_INFO: u16 = 0xc7d5;
|
||||
const DISTORTION_INFO: u16 = 0x0005;
|
||||
@@ -38,7 +38,7 @@ fn rational(b: &[u8], at: usize, order: ByteOrder) -> Option<f64> {
|
||||
/// The NikonNEFInfo entries: the blob is `"Nikon\0"`, a 4-byte version, then a little TIFF stream.
|
||||
fn nef_info(raw: &Ifd) -> Option<(Ifd, ByteOrder)> {
|
||||
let tiff = raw.bytes(NEF_INFO)?.strip_prefix(b"Nikon\0")?.get(4..)?;
|
||||
let (order, false) = lightcraft_tiff::Tiff::sniff(tiff)? else { return None };
|
||||
let (order, false) = craft_tiff::Tiff::sniff(tiff)? else { return None };
|
||||
let first = order.u32(tiff.get(4..8)?.try_into().ok()?);
|
||||
let opts = ParseOptions { follow_children: false, ..Default::default() };
|
||||
let (ifd, _) = parse_ifd_at(tiff, u64::from(first), order, 0, false, &opts).ok()?;
|
||||
@@ -121,7 +121,7 @@ pub(super) fn distortion(model: &str, raw: &Ifd, active: Rect, crop: Rect) -> Op
|
||||
#[cfg(test)]
|
||||
pub(in crate::vendor) mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{Entry, IfdBuilder, TiffWriter, Value};
|
||||
use craft_tiff::{Entry, IfdBuilder, TiffWriter, Value};
|
||||
|
||||
const AREA: Rect = Rect { x: 0, y: 0, width: 6064, height: 4040 };
|
||||
const CROP: Rect = Rect { x: 8, y: 8, width: 6048, height: 4024 };
|
||||
|
||||
Vendored
+3
-3
@@ -58,7 +58,7 @@
|
||||
|
||||
use super::pef::{Bits, Huffman, diff};
|
||||
use crate::{MAX_SAMPLES, RawError, Result};
|
||||
use lightcraft_tiff::ByteOrder;
|
||||
use craft_tiff::ByteOrder;
|
||||
|
||||
/// A table code word whose symbol was never observed (see the module docs).
|
||||
const UNSEEN: u8 = u8::MAX;
|
||||
@@ -633,8 +633,8 @@ mod tests {
|
||||
/// A minimal NEF: CFA SubIFD with one compressed strip, Exif maker note (`Nikon\0` v2 header + embedded TIFF in
|
||||
/// `mn_order`) holding the linearization table.
|
||||
fn nef_file(strip: Vec<u8>, w: u32, h: u32, bits: u16, table: Vec<u8>, mn_order: ByteOrder) -> Vec<u8> {
|
||||
use lightcraft_tiff::tags::{self as t, photometric};
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::tags::{self as t, photometric};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let mut mn = IfdBuilder::new();
|
||||
mn.set(0x0096, Value::Undefined(table));
|
||||
let mut note = b"Nikon\0\x02\x10\0\0".to_vec();
|
||||
|
||||
Vendored
+6
-6
@@ -40,10 +40,10 @@ use super::{cfa_from_exif, white_from_data};
|
||||
use crate::tiffraw::{Packing, read_image};
|
||||
use crate::unpack::unpack_msb;
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};
|
||||
use craft_tiff::image::chunk_bytes;
|
||||
use craft_tiff::makernote::MakerNote;
|
||||
use craft_tiff::{Ifd, Tiff, Value, makernote, tags as t};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::image::chunk_bytes;
|
||||
use lightcraft_tiff::makernote::MakerNote;
|
||||
use lightcraft_tiff::{Ifd, Tiff, Value, makernote, tags as t};
|
||||
use rayon::prelude::*;
|
||||
|
||||
pub(crate) const CAMERA_SETTINGS: u16 = 0x2020;
|
||||
@@ -73,8 +73,8 @@ pub(crate) fn sub_ifd(bytes: &[u8], mn: &MakerNote, tag: u16) -> Option<Ifd> {
|
||||
Value::Undefined(_) | Value::Byte(_) => e.offset,
|
||||
_ => mn.base.checked_add(mn.ifd.u64(tag)?)?,
|
||||
};
|
||||
let opts = lightcraft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() };
|
||||
lightcraft_tiff::parse_ifd_at(bytes, at, mn.order, mn.base, false, &opts).ok().map(|(i, _)| i)
|
||||
let opts = craft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() };
|
||||
craft_tiff::parse_ifd_at(bytes, at, mn.order, mn.base, false, &opts).ok().map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// Black level of a body without ImageProcessing: the main note's `0x1012` BlackLevel (the mean of its four values)
|
||||
@@ -365,7 +365,7 @@ pub(crate) fn preview(bytes: &[u8]) -> Option<&[u8]> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::vendor::EXIF_CFA_PATTERN;
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter};
|
||||
|
||||
fn orf(w: u32, h: u32, bits: u16, strip: Vec<u8>) -> Vec<u8> {
|
||||
orf_with(w, h, bits, strip, None)
|
||||
|
||||
Vendored
+4
-4
@@ -19,9 +19,9 @@ use super::{black_from_columns, cfa_from_exif, white_from_data};
|
||||
|
||||
use crate::tiffraw::{Packing, read_image_in};
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};
|
||||
use craft_tiff::image::{ImageInfo, chunk_bytes};
|
||||
use craft_tiff::{ByteOrder, Tiff, makernote, tags as t};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::image::{ImageInfo, chunk_bytes};
|
||||
use lightcraft_tiff::{ByteOrder, Tiff, makernote, tags as t};
|
||||
|
||||
const CROP_ORIGIN: u16 = 0x0038;
|
||||
const CROP_SIZE: u16 = 0x0039;
|
||||
@@ -523,7 +523,7 @@ mod tests {
|
||||
/// `CFAPattern` `pattern` and an AOC maker note with the area tags (and, for 65535, a Huffman table). The samples
|
||||
/// are plain 16-bit words (1), packed 12-bit (32773) or Huffman coded (65535).
|
||||
fn pef_with_pattern(compression: u16, pattern: [u8; 4]) -> Vec<u8> {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let (w, h) = (16usize, 8usize);
|
||||
let px: Vec<u16> = (0..w * h).map(|i| ((i * 37) % 900 + 100) as u16).collect();
|
||||
let (tb, codes) = test_table();
|
||||
@@ -589,7 +589,7 @@ mod tests {
|
||||
/// A `w x h` big-endian 14-bit PEF of plain 16-bit words without area tags, whose maker note has only a
|
||||
/// BlackPoint of `black`, with `px(x, y)` as the samples.
|
||||
fn pef_with_black_point(w: usize, h: usize, black: u16, px: impl Fn(usize, usize) -> u16) -> Vec<u8> {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let strip: Vec<u8> = (0..w * h).flat_map(|i| px(i % w, i / w).to_be_bytes()).collect();
|
||||
let build = |levels_at: u32| {
|
||||
let mut ifd = IfdBuilder::new();
|
||||
|
||||
Vendored
+2
-2
@@ -24,8 +24,8 @@
|
||||
use super::white_from_data;
|
||||
use crate::unpack::{unpack_lsb, unpack_words32_msb};
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};
|
||||
use craft_tiff::{ByteOrder, Ifd, Tiff};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::{ByteOrder, Ifd, Tiff};
|
||||
use rayon::prelude::*;
|
||||
|
||||
const CROP_TOP_LEFT: u16 = 0x0110;
|
||||
@@ -88,7 +88,7 @@ fn pair(h: &Header, tag: u16) -> Option<(usize, usize)> {
|
||||
pub(crate) fn raw_ifd(raw: &[u8]) -> Result<Ifd> {
|
||||
let tiff = Tiff::parse(raw).map_err(|_| RawError::Unsupported("RAF without a raw IFD (older FinePix layout)".into()))?;
|
||||
let off = tiff.ifds.first().and_then(|i| i.u64(0xf000)).ok_or_else(|| RawError::Unsupported("RAF without a raw IFD".into()))?;
|
||||
let (ifd, _) = lightcraft_tiff::parse_ifd_at(raw, off, ByteOrder::Little, 0, false, &Default::default())?;
|
||||
let (ifd, _) = craft_tiff::parse_ifd_at(raw, off, ByteOrder::Little, 0, false, &Default::default())?;
|
||||
Ok(ifd)
|
||||
}
|
||||
|
||||
|
||||
Vendored
+2
-2
@@ -18,7 +18,7 @@
|
||||
//! - vignette: relative illumination in percent at the source radius; the correction is the gain `100 / V`.
|
||||
|
||||
use crate::{Opcode, Rect};
|
||||
use lightcraft_tiff::Ifd;
|
||||
use craft_tiff::Ifd;
|
||||
|
||||
const DISTORTION: u16 = 0xf00b;
|
||||
const VIGNETTING: u16 = 0xf010;
|
||||
@@ -334,7 +334,7 @@ pub(super) fn corrections(model: &str, raw: &Ifd, active: Rect) -> Vec<Opcode> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{Entry, Value};
|
||||
use craft_tiff::{Entry, Value};
|
||||
|
||||
pub(crate) const KNOTS9: [f64; 9] = [0.3535211268, 0.5, 0.6126760563, 0.7070422535, 0.7908450704, 0.8661971831, 0.9352112676, 1.0, 1.06056338];
|
||||
/// X-T4 with the XF16-55 at 16 mm (3913): the tables as ExifTool prints them.
|
||||
|
||||
Vendored
+2
-2
@@ -105,8 +105,8 @@
|
||||
use super::pef::{Bits, Huffman, diff};
|
||||
use super::{active_rows, white_from_data};
|
||||
use crate::{BlackLevel, Cfa, ColorData, MAX_SAMPLES, Mode, Opcode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};
|
||||
use craft_tiff::{ByteOrder, Ifd, Tiff, Value, tags as t};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::{ByteOrder, Ifd, Tiff, Value, tags as t};
|
||||
use rayon::prelude::*;
|
||||
|
||||
const SENSOR_WIDTH: u16 = 0x0002;
|
||||
@@ -698,7 +698,7 @@ fn distortion(ifd: &Ifd, active: Rect) -> Option<Opcode> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_tiff::{IfdBuilder, TiffWriter};
|
||||
use craft_tiff::{IfdBuilder, TiffWriter};
|
||||
|
||||
/// Writes bit fields into a 16-byte block from bit 127 down (the inverse of [`Fields`]).
|
||||
struct FieldWriter {
|
||||
|
||||
Vendored
+5
-5
@@ -45,7 +45,7 @@
|
||||
//! of an accident 2⁻⁴⁰⁶⁴). For the DSC-R1's key `63 be 01 3e` the 11932-byte block becomes a well-formed 101-entry
|
||||
//! directory (black `0x7300`, white balance `0x7303`, crop `0x74c3`).
|
||||
|
||||
use lightcraft_tiff::{ByteOrder, EntrySpan, Ifd, ParseOptions, decode_value, directory_entries, entry_span, tags as t};
|
||||
use craft_tiff::{ByteOrder, EntrySpan, Ifd, ParseOptions, decode_value, directory_entries, entry_span, tags as t};
|
||||
|
||||
/// `SR2Private` tags.
|
||||
const SUBIFD_OFFSET: u16 = 0x7200;
|
||||
@@ -260,7 +260,7 @@ pub(crate) mod tests {
|
||||
const LONG: u16 = 4;
|
||||
const UNDEFINED: u16 = 7;
|
||||
const IFD: u16 = 13;
|
||||
use lightcraft_tiff::ByteOrder::{Big, Little};
|
||||
use craft_tiff::ByteOrder::{Big, Little};
|
||||
|
||||
/// An `SR2SubIFD` block for file offset `start`, encrypted: SHORT/SSHORT entries `(tag, type, values)`, values
|
||||
/// of more than two shorts stored after the table at file offsets, as Sony does.
|
||||
@@ -429,8 +429,8 @@ pub(crate) mod tests {
|
||||
/// What `SubIfd::read` on main selects: the TIFF reader's parse of the directory with main's options, then the
|
||||
/// directory's `u64` and `bytes` lookups.
|
||||
fn reader_selects(bytes: &[u8], at: usize, order: ByteOrder) -> Selected {
|
||||
let opts = lightcraft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() };
|
||||
let Ok((private, _)) = lightcraft_tiff::parse_ifd_at(bytes, at as u64, order, 0, false, &opts) else { return (None, None, None) };
|
||||
let opts = craft_tiff::ParseOptions { max_ifds: 1, max_depth: 0, follow_children: false, ..Default::default() };
|
||||
let Ok((private, _)) = craft_tiff::parse_ifd_at(bytes, at as u64, order, 0, false, &opts) else { return (None, None, None) };
|
||||
let n = |tag: u16| private.u64(tag).and_then(|v| usize::try_from(v).ok());
|
||||
(n(SUBIFD_OFFSET), n(SUBIFD_LENGTH), private.bytes(SUBIFD_KEY).and_then(|b| <[u8; 4]>::try_from(b).ok()))
|
||||
}
|
||||
@@ -594,7 +594,7 @@ pub(crate) mod tests {
|
||||
let mut pointer = Vec::new();
|
||||
order.put_u32(&mut pointer, 0);
|
||||
let ifd0 = Ifd {
|
||||
entries: vec![lightcraft_tiff::Entry { tag: t::DNG_PRIVATE_DATA, value: lightcraft_tiff::Value::Byte(pointer), offset: 0 }],
|
||||
entries: vec![craft_tiff::Entry { tag: t::DNG_PRIVATE_DATA, value: craft_tiff::Value::Byte(pointer), offset: 0 }],
|
||||
..Default::default()
|
||||
};
|
||||
let black = SubIfd::read(&file, &ifd0, order).and_then(|s| s.shorts(0x7310));
|
||||
|
||||
Vendored
+6
-6
@@ -36,9 +36,9 @@
|
||||
use super::{black_from_columns, white_from_data};
|
||||
use crate::unpack::{read_u16s, unpack_lsb, unpack_msb};
|
||||
use crate::{BlackLevel, Cfa, ColorData, Mode, OpcodeLists, RawData, RawError, RawFormat, RawImage, Rect, Result};
|
||||
use craft_tiff::image::chunk_bytes;
|
||||
use craft_tiff::{ByteOrder, Ifd, Tiff, tags as t};
|
||||
use lightcraft_geom::Orientation;
|
||||
use lightcraft_tiff::image::chunk_bytes;
|
||||
use lightcraft_tiff::{ByteOrder, Ifd, Tiff, tags as t};
|
||||
use rayon::prelude::*;
|
||||
|
||||
const SENSOR_AREAS: u16 = 0xa010;
|
||||
@@ -53,8 +53,8 @@ const COMPRESSIONS: std::ops::RangeInclusive<u16> = 32769..=32773;
|
||||
/// The maker-note IFD (offsets relative to the note's own start).
|
||||
fn maker_note(bytes: &[u8], tiff: &Tiff) -> Option<Ifd> {
|
||||
let e = tiff.exif()?.get(t::MAKER_NOTE)?;
|
||||
let opts = lightcraft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() };
|
||||
lightcraft_tiff::parse_ifd_at(bytes, e.offset, tiff.order, e.offset, false, &opts).ok().map(|(i, _)| i)
|
||||
let opts = craft_tiff::ParseOptions { max_ifds: 4, max_depth: 1, follow_children: false, ..Default::default() };
|
||||
craft_tiff::parse_ifd_at(bytes, e.offset, tiff.order, e.offset, false, &opts).ok().map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// A key-offset vector: the entries of `tag` shifted by the maker note's key (`sign` is +1 or -1 times the key).
|
||||
@@ -281,7 +281,7 @@ fn masked_black(d: &[u16], w: usize, h: usize, a: Rect, white: f32) -> BlackLeve
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{decode, probe, probe_info};
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
|
||||
const KEY: [u32; 11] = [305, 72, 737, 456, 282, 307, 519, 724, 13, 505, 193];
|
||||
|
||||
@@ -362,7 +362,7 @@ mod tests {
|
||||
}
|
||||
ifd0.set_child(t::EXIF_IFD, exif);
|
||||
ifd0.add_sub_ifd(raw);
|
||||
TiffWriter::new(lightcraft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap()
|
||||
TiffWriter::new(craft_tiff::ByteOrder::Big, false).write(&[ifd0]).unwrap()
|
||||
}
|
||||
|
||||
/// Strip byte counts that add up past `u64::MAX` (LONG8 `[u64::MAX, 1]`) are an error or a picture, not an overflow.
|
||||
|
||||
@@ -1378,7 +1378,7 @@ fn a7cr_enabled_distortion_agrees_in_header_full_and_dng() {
|
||||
let Some(mut bytes) = pinned_sony(&root, name) else { continue };
|
||||
let original = probe_info(&bytes).unwrap();
|
||||
assert!(original.opcodes.list3.is_empty(), "Off files must remain uncorrected");
|
||||
let tiff = lightcraft_tiff::Tiff::parse(&bytes).unwrap();
|
||||
let tiff = craft_tiff::Tiff::parse(&bytes).unwrap();
|
||||
let at = tiff.find(0x7036).unwrap().offset as usize;
|
||||
let mut enabled = Vec::new();
|
||||
tiff.order.put_u16(&mut enabled, 17);
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
//! Synthetic DNG round trips: every storage variant we decode is written with our own TIFF writer (and LJ92
|
||||
//! encoder) and must decode bit-exactly.
|
||||
|
||||
use craft_tiff::tags::{self as t, compression, photometric};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use lightcraft_color::{D65, Mat3, Xy};
|
||||
use lightcraft_raw::opcodes::{Area, Opcode};
|
||||
use lightcraft_raw::{
|
||||
BlackLevel, Cfa, ColorData, DngCompression, DngWriteOptions, Method, OpcodeLists, Orientation, RawData, RawFormat, RawImage, Rect, decode,
|
||||
embedded_preview, probe, write_dng,
|
||||
};
|
||||
use lightcraft_tiff::tags::{self as t, compression, photometric};
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
|
||||
fn scene_value(x: usize, y: usize, c: u8, max: f32) -> f32 {
|
||||
let base = [0.55, 0.8, 0.4][c as usize];
|
||||
@@ -120,7 +120,7 @@ fn writer_camera_identity_tags_roundtrip() {
|
||||
raw.metadata.model = model.map(str::to_owned);
|
||||
for order in [ByteOrder::Little, ByteOrder::Big] {
|
||||
let bytes = write_dng(&raw, &DngWriteOptions { compression: DngCompression::Uncompressed, order, xmp: None }).unwrap();
|
||||
let tiff = lightcraft_tiff::Tiff::parse(&bytes).unwrap();
|
||||
let tiff = craft_tiff::Tiff::parse(&bytes).unwrap();
|
||||
let ifd = &tiff.ifds[0];
|
||||
assert_eq!(ifd.value(t::UNIQUE_CAMERA_MODEL), Some(&Value::Ascii(unique.into())), "{make:?} / {model:?}, {order:?}");
|
||||
for (tag, original) in [(t::MAKE, make), (t::MODEL, model)] {
|
||||
|
||||
@@ -97,8 +97,8 @@ fn truncation_at_every_length() {
|
||||
#[test]
|
||||
fn hostile_dimensions_are_rejected_quickly() {
|
||||
// a DNG claiming a 60000 × 60000 16-bit image with 10 bytes of data
|
||||
use lightcraft_tiff::tags as t;
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::tags as t;
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let mut ifd = IfdBuilder::new();
|
||||
ifd.set(t::DNG_VERSION, Value::Byte(vec![1, 4, 0, 0]));
|
||||
ifd.set(t::IMAGE_WIDTH, Value::Long(vec![60000]));
|
||||
@@ -120,8 +120,8 @@ fn hostile_dimensions_are_rejected_quickly() {
|
||||
/// read as 0 and non-finite samples as black: the photo develops to finite numbers.
|
||||
#[test]
|
||||
fn non_finite_black_levels_and_samples_develop() {
|
||||
use lightcraft_tiff::tags as t;
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::tags as t;
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value};
|
||||
let (w, h) = (32u32, 16u32);
|
||||
for black in [Value::Float(vec![f32::NAN]), Value::Double(vec![f64::INFINITY]), Value::Float(vec![64.0, f32::NAN, 64.0, 64.0])] {
|
||||
let mut ifd = IfdBuilder::new();
|
||||
|
||||
@@ -292,7 +292,7 @@ impl Drop for Scratch {
|
||||
/// A small Sony CFA file with a distortion setting (a lens record), or, `unsupported`, the packed 12-bit ARW variant
|
||||
/// the decoder refuses as unsupported.
|
||||
fn synthetic_arw(unsupported: bool) -> Vec<u8> {
|
||||
use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t};
|
||||
let mut raw = IfdBuilder::new();
|
||||
raw.set(t::MAKE, Value::Ascii("SONY".into()));
|
||||
raw.set(t::MODEL, Value::Ascii("ILCE-7CR".into()));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Malformed vendor raw files (NEF, ARW, PEF, ORF, RW2 of every raw format, CR2, RAF, CRW) must decode to an error, never panic.
|
||||
|
||||
use lightcraft_tiff::tags as t;
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use craft_tiff::tags as t;
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, TiffWriter, Value};
|
||||
use proptest::prelude::*;
|
||||
|
||||
const W: u32 = 32;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! it must not cost memory sized by its other entries: a hostile file can give it fields that each alias most of the
|
||||
//! file. Only the block's offset, length and key may be read. One test per binary (dhat's profiler is global).
|
||||
|
||||
use lightcraft_tiff::{ByteOrder, IfdBuilder, ImageData, Tiff, TiffWriter, Value, tags as t};
|
||||
use craft_tiff::{ByteOrder, IfdBuilder, ImageData, Tiff, TiffWriter, Value, tags as t};
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOC: dhat::Alloc = dhat::Alloc;
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
[package]
|
||||
name = "lightcraft-tiff"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "LightCraft TIFF/IFD reader and writer (L0)"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
@@ -1,45 +0,0 @@
|
||||
# lightcraft-tiff (L0)
|
||||
|
||||
TIFF / IFD reader and writer. Used by `lightcraft-raw` (DNG, CR2, NEF, ARW…), `lightcraft-meta` (Exif) and
|
||||
later the TIFF/DNG exporters.
|
||||
|
||||
## Features
|
||||
|
||||
- Classic TIFF and BigTIFF, little- and big-endian (`II`/`MM`). Also accepts the TIFF-like magic numbers of
|
||||
some raw formats (ORF `IIRO`/`IIRS`, RW2 `IIU`) when `ParseOptions::accept_raw_magic` is set (default).
|
||||
- Every field type: BYTE, ASCII, SHORT, LONG, RATIONAL, SBYTE, UNDEFINED, SSHORT, SLONG, SRATIONAL, FLOAT,
|
||||
DOUBLE, IFD, LONG8, SLONG8, IFD8.
|
||||
- IFD chain + `SubIFDs` (330) + Exif (34665) / GPS (34853) / Interoperability (40965) pointer IFDs, resolved
|
||||
into a tree (`Ifd::sub_ifds`, `exif`, `gps`, `interop`). `Entry::offset` records the absolute position of
|
||||
each value (needed for maker notes and embedded blobs).
|
||||
- `parse_ifd_at(data, offset, order, base, bigtiff, opts)` parses an IFD whose offsets are relative to an
|
||||
arbitrary base; `makernote::parse_makernote` knows the header / byte-order / offset-base conventions of
|
||||
Canon, Nikon (types 1 and 3), Sony, Fujifilm, Olympus (old and new), Panasonic and Pentax notes.
|
||||
- `image::ImageInfo` — width/height, bits, samples, compression, photometric, planar config, predictor,
|
||||
sample format and the strip or tile chunk list (`chunks()`, `chunk_bytes()`); missing byte counts are
|
||||
inferred.
|
||||
- `directory_entries`, `entry_span`, `ParseOptions::budget_for` and `decode_value` are the reader's own rules
|
||||
(directory layout and entry limit, which entries it reads, its value budget, value decoding), for callers that
|
||||
must select entries exactly as `parse_ifd_at` would without decoding the whole directory (`lightcraft-raw`'s
|
||||
Sony `SR2Private` lookup).
|
||||
- `TiffWriter` writes IFD chains with strips or tiles, `SubIFDs` and pointer IFDs, in either byte order,
|
||||
classic or BigTIFF; `writer::rational` / `srational` approximate floats as rationals.
|
||||
|
||||
## Robustness
|
||||
|
||||
The reader never panics on malformed input (proptests feed random and mutated files): offsets are
|
||||
bounds-checked; out-of-range or unknown-type entries are skipped; IFD loops are detected; IFD count,
|
||||
nesting depth and entries per IFD are limited; at most 65,536 directory entry slots
|
||||
(`ParseOptions::max_entries_total`) are accepted across the main IFD chain and all child IFDs, even when tables
|
||||
overlap at distinct offsets, and an IFD past that bound ends the chain or is skipped like any other bad IFD after
|
||||
the first; a next-IFD pointer is followed only when every declared entry was read, with the counts compared as
|
||||
64-bit numbers (a BigTIFF declaring 4,294,967,297 entries but holding one can't pass for a whole directory on a
|
||||
32-bit target); the total bytes of decoded values are capped at
|
||||
`8 × input + 1 MiB` so a file cannot make us allocate far more than its own size.
|
||||
|
||||
## Sources
|
||||
|
||||
Public specifications only: TIFF 6.0 (Adobe, 1992), the TIFF 6.0 supplements (IFD type, SubIFDs), the
|
||||
BigTIFF format description (AWare Systems), Adobe DNG Specification 1.7 (tag numbers), CIPA DC-008 Exif 2.32,
|
||||
and the ExifTool tag-name documentation (maker-note header conventions, prose only). No third-party code
|
||||
was consulted.
|
||||
@@ -1,248 +0,0 @@
|
||||
//! Image layout of an IFD: dimensions, sample format and the strip / tile chunks holding the pixels.
|
||||
|
||||
use crate::{Ifd, Result, TiffError, tags};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How pixel data is split into chunks.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Layout {
|
||||
Strips { rows_per_strip: u32 },
|
||||
Tiles { tile_width: u32, tile_height: u32 },
|
||||
}
|
||||
|
||||
/// Pixel layout description of an IFD (TIFF 6.0 §3–§8, §15).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ImageInfo {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub bits_per_sample: Vec<u16>,
|
||||
pub samples_per_pixel: u16,
|
||||
pub compression: u16,
|
||||
pub photometric: u16,
|
||||
/// 1 = chunky (interleaved), 2 = planar.
|
||||
pub planar: u16,
|
||||
pub predictor: u16,
|
||||
/// 1 = unsigned int, 2 = signed int, 3 = IEEE float.
|
||||
pub sample_format: u16,
|
||||
pub new_subfile_type: u32,
|
||||
pub layout: Layout,
|
||||
pub offsets: Vec<u64>,
|
||||
pub byte_counts: Vec<u64>,
|
||||
}
|
||||
|
||||
/// One strip or tile.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Chunk {
|
||||
pub index: usize,
|
||||
/// Top-left pixel of the chunk.
|
||||
pub x: u32,
|
||||
pub y: u32,
|
||||
/// Nominal chunk size (tiles may extend past the image; strips are clipped to the image height).
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Plane index for planar configuration 2 (else 0).
|
||||
pub plane: u16,
|
||||
pub offset: u64,
|
||||
pub len: u64,
|
||||
}
|
||||
|
||||
impl ImageInfo {
|
||||
pub fn from_ifd(ifd: &Ifd) -> Result<ImageInfo> {
|
||||
let width = ifd.u32(tags::IMAGE_WIDTH).ok_or(TiffError::MissingTag(tags::IMAGE_WIDTH))?;
|
||||
let height = ifd.u32(tags::IMAGE_LENGTH).ok_or(TiffError::MissingTag(tags::IMAGE_LENGTH))?;
|
||||
if width == 0 || height == 0 {
|
||||
return Err(TiffError::Invalid("zero image dimension".into()));
|
||||
}
|
||||
let samples_per_pixel = ifd.u16(tags::SAMPLES_PER_PIXEL).unwrap_or(1).max(1);
|
||||
let bits_per_sample: Vec<u16> =
|
||||
ifd.u64s(tags::BITS_PER_SAMPLE).map(|v| v.into_iter().map(|b| b.min(u16::MAX as u64) as u16).collect()).unwrap_or_else(|| vec![1]);
|
||||
let bits_per_sample = if bits_per_sample.is_empty() { vec![1] } else { bits_per_sample };
|
||||
let planar = ifd.u16(tags::PLANAR_CONFIGURATION).unwrap_or(1);
|
||||
let (layout, offsets, byte_counts) = if let Some(tw) = ifd.u32(tags::TILE_WIDTH) {
|
||||
let th = ifd.u32(tags::TILE_LENGTH).ok_or(TiffError::MissingTag(tags::TILE_LENGTH))?;
|
||||
if tw == 0 || th == 0 {
|
||||
return Err(TiffError::Invalid("zero tile size".into()));
|
||||
}
|
||||
let offs = ifd.u64s(tags::TILE_OFFSETS).or_else(|| ifd.u64s(tags::STRIP_OFFSETS)).ok_or(TiffError::MissingTag(tags::TILE_OFFSETS))?;
|
||||
let cnts = ifd
|
||||
.u64s(tags::TILE_BYTE_COUNTS)
|
||||
.or_else(|| ifd.u64s(tags::STRIP_BYTE_COUNTS))
|
||||
.ok_or(TiffError::MissingTag(tags::TILE_BYTE_COUNTS))?;
|
||||
(Layout::Tiles { tile_width: tw, tile_height: th }, offs, cnts)
|
||||
} else {
|
||||
let offs = ifd.u64s(tags::STRIP_OFFSETS).ok_or(TiffError::MissingTag(tags::STRIP_OFFSETS))?;
|
||||
let cnts = ifd.u64s(tags::STRIP_BYTE_COUNTS).unwrap_or_default();
|
||||
let rps = ifd.u32(tags::ROWS_PER_STRIP).unwrap_or(height).clamp(1, height);
|
||||
(Layout::Strips { rows_per_strip: rps }, offs, cnts)
|
||||
};
|
||||
Ok(ImageInfo {
|
||||
width,
|
||||
height,
|
||||
bits_per_sample,
|
||||
samples_per_pixel,
|
||||
compression: ifd.u16(tags::COMPRESSION).unwrap_or(1),
|
||||
photometric: ifd.u16(tags::PHOTOMETRIC).unwrap_or(1),
|
||||
planar,
|
||||
predictor: ifd.u16(tags::PREDICTOR).unwrap_or(1),
|
||||
sample_format: ifd.u16(tags::SAMPLE_FORMAT).unwrap_or(1),
|
||||
new_subfile_type: ifd.u32(tags::NEW_SUBFILE_TYPE).unwrap_or(0),
|
||||
layout,
|
||||
offsets,
|
||||
byte_counts,
|
||||
})
|
||||
}
|
||||
|
||||
/// Bits of the first sample.
|
||||
pub fn bits(&self) -> u16 {
|
||||
self.bits_per_sample[0]
|
||||
}
|
||||
|
||||
/// Whether this IFD is a reduced-resolution image (NewSubfileType bit 0).
|
||||
pub fn is_reduced(&self) -> bool {
|
||||
self.new_subfile_type & 1 != 0
|
||||
}
|
||||
|
||||
/// Number of chunks across and down per plane.
|
||||
pub fn grid(&self) -> (u32, u32) {
|
||||
match self.layout {
|
||||
Layout::Strips { rows_per_strip } => (1, self.height.div_ceil(rows_per_strip)),
|
||||
Layout::Tiles { tile_width, tile_height } => (self.width.div_ceil(tile_width), self.height.div_ceil(tile_height)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Nominal chunk dimensions.
|
||||
pub fn chunk_size(&self) -> (u32, u32) {
|
||||
match self.layout {
|
||||
Layout::Strips { rows_per_strip } => (self.width, rows_per_strip),
|
||||
Layout::Tiles { tile_width, tile_height } => (tile_width, tile_height),
|
||||
}
|
||||
}
|
||||
|
||||
/// The chunk count the image declares (offsets present, cut to the layout's plane capacity) with the
|
||||
/// geometry `chunks` needs to place each one. No descriptors are built, so a pathological strip array
|
||||
/// costs it a length check.
|
||||
fn chunk_grid(&self) -> (usize, u32, usize) {
|
||||
let (across, down) = self.grid();
|
||||
let per_plane = across as usize * down as usize;
|
||||
let planes = if self.planar == 2 { self.samples_per_pixel as usize } else { 1 };
|
||||
(self.offsets.len().min(per_plane.saturating_mul(planes)), across, per_plane)
|
||||
}
|
||||
|
||||
fn declared_chunk_count(&self) -> usize {
|
||||
self.chunk_grid().0
|
||||
}
|
||||
|
||||
/// The one chunk when the image has exactly one, else `None` — and no descriptor vector beyond it. Preview
|
||||
/// extraction only serves single-chunk images, so it asks here before serving a hostile multi-strip layout.
|
||||
pub fn single_chunk(&self, data_len: u64) -> Option<Chunk> {
|
||||
if self.declared_chunk_count() != 1 {
|
||||
return None;
|
||||
}
|
||||
self.chunks(data_len).into_iter().next()
|
||||
}
|
||||
|
||||
/// All chunks that have an offset. Missing byte counts are inferred as "to the next offset / end of data"
|
||||
/// using `data_len`.
|
||||
pub fn chunks(&self, data_len: u64) -> Vec<Chunk> {
|
||||
let (n, across, per_plane) = self.chunk_grid();
|
||||
let (cw, ch) = self.chunk_size();
|
||||
let mut out = Vec::with_capacity(n);
|
||||
// the distinct offsets in order, for chunks without a byte count (sorted once, not scanned per chunk)
|
||||
let mut sorted: Vec<u64> = Vec::new();
|
||||
if (0..n).any(|i| self.byte_counts.get(i).is_none_or(|&l| l == 0)) {
|
||||
sorted = self.offsets.clone();
|
||||
sorted.sort_unstable();
|
||||
sorted.dedup();
|
||||
}
|
||||
for i in 0..n {
|
||||
let plane = i / per_plane.max(1);
|
||||
let j = i % per_plane.max(1);
|
||||
let (cx, cy) = (j as u32 % across, j as u32 / across);
|
||||
let x = cx * cw;
|
||||
let y = cy * ch;
|
||||
let height = match self.layout {
|
||||
Layout::Strips { .. } => ch.min(self.height - y),
|
||||
Layout::Tiles { .. } => ch,
|
||||
};
|
||||
let offset = self.offsets[i];
|
||||
let len = match self.byte_counts.get(i) {
|
||||
Some(&l) if l > 0 => l,
|
||||
_ => {
|
||||
// infer: up to the next larger offset, else end of data
|
||||
let next = sorted.get(sorted.partition_point(|&o| o <= offset)).copied().unwrap_or(data_len);
|
||||
next.saturating_sub(offset)
|
||||
}
|
||||
};
|
||||
out.push(Chunk { index: i, x, y, width: cw, height, plane: plane as u16, offset, len });
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of a chunk, clipped to the available data (truncated files yield a shorter slice).
|
||||
/// Returns `None` only when the chunk starts past the end of `data`.
|
||||
pub fn chunk_bytes<'a>(data: &'a [u8], c: &Chunk) -> Option<&'a [u8]> {
|
||||
let start = usize::try_from(c.offset).ok()?;
|
||||
if start >= data.len() {
|
||||
return None;
|
||||
}
|
||||
let end = (c.offset.saturating_add(c.len)).min(data.len() as u64) as usize;
|
||||
Some(&data[start..end])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn strips(offsets: Vec<u64>, byte_counts: Vec<u64>) -> ImageInfo {
|
||||
ImageInfo {
|
||||
width: 1,
|
||||
height: offsets.len() as u32,
|
||||
bits_per_sample: vec![8],
|
||||
samples_per_pixel: 1,
|
||||
compression: 1,
|
||||
photometric: 1,
|
||||
planar: 1,
|
||||
predictor: 1,
|
||||
sample_format: 1,
|
||||
new_subfile_type: 0,
|
||||
layout: Layout::Strips { rows_per_strip: 1 },
|
||||
offsets,
|
||||
byte_counts,
|
||||
}
|
||||
}
|
||||
|
||||
/// One offset is one chunk, and `single_chunk` refuses to build descriptors when the image declares more.
|
||||
#[test]
|
||||
fn single_chunk_is_the_only_chunk() {
|
||||
let one = strips(vec![50], vec![10]);
|
||||
assert_eq!(one.single_chunk(100).map(|c| (c.index, c.offset, c.len)), one.chunks(100).first().map(|c| (c.index, c.offset, c.len)));
|
||||
// the inferred length matches too, and never falls back past the data
|
||||
let inferred = strips(vec![70], vec![]);
|
||||
assert_eq!(inferred.single_chunk(100).map(|c| c.len), Some(30));
|
||||
assert!(strips(vec![50, 10], vec![10, 5]).single_chunk(100).is_none(), "a multi-chunk image has no single chunk");
|
||||
assert!(strips(Vec::new(), Vec::new()).single_chunk(100).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_byte_counts_run_to_the_next_larger_offset() {
|
||||
let info = strips(vec![50, 10, 30, 10, 70], vec![0, 0, 5]);
|
||||
let lens: Vec<u64> = info.chunks(100).iter().map(|c| c.len).collect();
|
||||
assert_eq!(lens, vec![20, 20, 5, 20, 30]);
|
||||
}
|
||||
|
||||
/// A million strips without byte counts (offsets in descending order) are measured in one sort, not one
|
||||
/// scan of all offsets per strip.
|
||||
#[test]
|
||||
fn many_strips_without_byte_counts_are_fast() {
|
||||
let n = 1_000_000u64;
|
||||
let info = strips((0..n).rev().map(|i| 1000 + i * 2).collect(), Vec::new());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let chunks = info.chunks(1000 + n * 2);
|
||||
let _ = tx.send(chunks.iter().map(|c| c.len).collect::<Vec<u64>>());
|
||||
});
|
||||
let lens = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("chunks() took longer than 20 s");
|
||||
assert!(lens.iter().all(|&l| l == 2));
|
||||
}
|
||||
}
|
||||
@@ -1,468 +0,0 @@
|
||||
//! TIFF / IFD reading and writing for LightCraft.
|
||||
//!
|
||||
//! - [`Tiff::parse`] reads classic TIFF and BigTIFF in both byte orders, following the IFD chain,
|
||||
//! `SubIFDs`, and the Exif / GPS / Interoperability IFD pointers. All field types of TIFF 6.0,
|
||||
//! the TIFF 6.0 supplement (`IFD`) and BigTIFF (`LONG8`, `SLONG8`, `IFD8`) are decoded.
|
||||
//! - [`parse_ifd_at`] parses a single IFD with an arbitrary offset base — the building block for
|
||||
//! maker-note IFDs ([`makernote`]).
|
||||
//! - [`image::ImageInfo`] describes the pixel layout of an IFD (strips or tiles, planar config,
|
||||
//! compression, predictor) and enumerates its [`image::Chunk`]s.
|
||||
//! - [`writer::TiffWriter`] writes IFD trees (with strips/tiles, `SubIFDs` and pointer IFDs) in
|
||||
//! either byte order, classic or BigTIFF.
|
||||
//!
|
||||
//! The reader never panics on malformed input: every offset is bounds-checked, IFD loops are
|
||||
//! detected, nesting depth / IFD count are limited, at most 65,536 directory entry slots are read
|
||||
//! across the main chain and child IFDs, and decoded value bytes are capped relative to the input
|
||||
//! size (so overlapping tables cannot multiply entry-vector allocations without bound).
|
||||
//!
|
||||
//! Sources: TIFF 6.0 specification (Adobe, 1992), TIFF Technical Note / supplements, the BigTIFF
|
||||
//! design notes (AWare Systems), Adobe DNG specification 1.7 (tag numbers), CIPA DC-008 (Exif 2.32).
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod image;
|
||||
pub mod makernote;
|
||||
mod reader;
|
||||
pub mod tags;
|
||||
pub mod writer;
|
||||
|
||||
pub use reader::{DirectoryEntries, EntrySpan, ParseOptions, decode as decode_value, directory_entries, entry_span, parse_ifd_at};
|
||||
pub use writer::{IfdBuilder, ImageData, TiffWriter};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Errors from TIFF parsing / writing.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum TiffError {
|
||||
#[error("not a TIFF stream (bad header)")]
|
||||
NotTiff,
|
||||
#[error("data truncated at offset {0}")]
|
||||
Truncated(u64),
|
||||
#[error("invalid TIFF structure: {0}")]
|
||||
Invalid(String),
|
||||
#[error("resource limit exceeded: {0}")]
|
||||
Limit(&'static str),
|
||||
#[error("missing required tag {0}")]
|
||||
MissingTag(u16),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, TiffError>;
|
||||
|
||||
/// Byte order of a TIFF stream.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
pub enum ByteOrder {
|
||||
/// `II` — Intel, little-endian.
|
||||
#[default]
|
||||
Little,
|
||||
/// `MM` — Motorola, big-endian.
|
||||
Big,
|
||||
}
|
||||
|
||||
impl ByteOrder {
|
||||
#[inline]
|
||||
pub fn u16(self, b: [u8; 2]) -> u16 {
|
||||
match self {
|
||||
ByteOrder::Little => u16::from_le_bytes(b),
|
||||
ByteOrder::Big => u16::from_be_bytes(b),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn u32(self, b: [u8; 4]) -> u32 {
|
||||
match self {
|
||||
ByteOrder::Little => u32::from_le_bytes(b),
|
||||
ByteOrder::Big => u32::from_be_bytes(b),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn u64(self, b: [u8; 8]) -> u64 {
|
||||
match self {
|
||||
ByteOrder::Little => u64::from_le_bytes(b),
|
||||
ByteOrder::Big => u64::from_be_bytes(b),
|
||||
}
|
||||
}
|
||||
/// Read a `u16` at `off`, or `None` if out of bounds.
|
||||
#[inline]
|
||||
pub fn read_u16(self, data: &[u8], off: usize) -> Option<u16> {
|
||||
data.get(off..off.checked_add(2)?).map(|s| self.u16([s[0], s[1]]))
|
||||
}
|
||||
#[inline]
|
||||
pub fn read_u32(self, data: &[u8], off: usize) -> Option<u32> {
|
||||
data.get(off..off.checked_add(4)?).map(|s| self.u32([s[0], s[1], s[2], s[3]]))
|
||||
}
|
||||
#[inline]
|
||||
pub fn read_u64(self, data: &[u8], off: usize) -> Option<u64> {
|
||||
data.get(off..off.checked_add(8)?).map(|s| self.u64([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]))
|
||||
}
|
||||
pub fn put_u16(self, out: &mut Vec<u8>, v: u16) {
|
||||
out.extend_from_slice(&match self {
|
||||
ByteOrder::Little => v.to_le_bytes(),
|
||||
ByteOrder::Big => v.to_be_bytes(),
|
||||
});
|
||||
}
|
||||
pub fn put_u32(self, out: &mut Vec<u8>, v: u32) {
|
||||
out.extend_from_slice(&match self {
|
||||
ByteOrder::Little => v.to_le_bytes(),
|
||||
ByteOrder::Big => v.to_be_bytes(),
|
||||
});
|
||||
}
|
||||
pub fn put_u64(self, out: &mut Vec<u8>, v: u64) {
|
||||
out.extend_from_slice(&match self {
|
||||
ByteOrder::Little => v.to_le_bytes(),
|
||||
ByteOrder::Big => v.to_be_bytes(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// TIFF field types (TIFF 6.0 §2 + supplements + BigTIFF).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[repr(u16)]
|
||||
pub enum FieldType {
|
||||
Byte = 1,
|
||||
Ascii = 2,
|
||||
Short = 3,
|
||||
Long = 4,
|
||||
Rational = 5,
|
||||
SByte = 6,
|
||||
Undefined = 7,
|
||||
SShort = 8,
|
||||
SLong = 9,
|
||||
SRational = 10,
|
||||
Float = 11,
|
||||
Double = 12,
|
||||
Ifd = 13,
|
||||
Long8 = 16,
|
||||
SLong8 = 17,
|
||||
Ifd8 = 18,
|
||||
}
|
||||
|
||||
impl FieldType {
|
||||
pub fn from_u16(v: u16) -> Option<FieldType> {
|
||||
use FieldType::*;
|
||||
Some(match v {
|
||||
1 => Byte,
|
||||
2 => Ascii,
|
||||
3 => Short,
|
||||
4 => Long,
|
||||
5 => Rational,
|
||||
6 => SByte,
|
||||
7 => Undefined,
|
||||
8 => SShort,
|
||||
9 => SLong,
|
||||
10 => SRational,
|
||||
11 => Float,
|
||||
12 => Double,
|
||||
13 => Ifd,
|
||||
16 => Long8,
|
||||
17 => SLong8,
|
||||
18 => Ifd8,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
/// Size in bytes of one value.
|
||||
pub fn size(self) -> usize {
|
||||
use FieldType::*;
|
||||
match self {
|
||||
Byte | Ascii | SByte | Undefined => 1,
|
||||
Short | SShort => 2,
|
||||
Long | SLong | Float | Ifd => 4,
|
||||
Rational | SRational | Double | Long8 | SLong8 | Ifd8 => 8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A decoded field value. Arrays are stored in their native type.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Value {
|
||||
Byte(Vec<u8>),
|
||||
/// ASCII text (bytes up to the first NUL, decoded lossily as UTF-8).
|
||||
Ascii(String),
|
||||
Short(Vec<u16>),
|
||||
Long(Vec<u32>),
|
||||
Rational(Vec<(u32, u32)>),
|
||||
SByte(Vec<i8>),
|
||||
Undefined(Vec<u8>),
|
||||
SShort(Vec<i16>),
|
||||
SLong(Vec<i32>),
|
||||
SRational(Vec<(i32, i32)>),
|
||||
Float(Vec<f32>),
|
||||
Double(Vec<f64>),
|
||||
Ifd(Vec<u32>),
|
||||
Long8(Vec<u64>),
|
||||
SLong8(Vec<i64>),
|
||||
Ifd8(Vec<u64>),
|
||||
}
|
||||
|
||||
impl Value {
|
||||
pub fn field_type(&self) -> FieldType {
|
||||
match self {
|
||||
Value::Byte(_) => FieldType::Byte,
|
||||
Value::Ascii(_) => FieldType::Ascii,
|
||||
Value::Short(_) => FieldType::Short,
|
||||
Value::Long(_) => FieldType::Long,
|
||||
Value::Rational(_) => FieldType::Rational,
|
||||
Value::SByte(_) => FieldType::SByte,
|
||||
Value::Undefined(_) => FieldType::Undefined,
|
||||
Value::SShort(_) => FieldType::SShort,
|
||||
Value::SLong(_) => FieldType::SLong,
|
||||
Value::SRational(_) => FieldType::SRational,
|
||||
Value::Float(_) => FieldType::Float,
|
||||
Value::Double(_) => FieldType::Double,
|
||||
Value::Ifd(_) => FieldType::Ifd,
|
||||
Value::Long8(_) => FieldType::Long8,
|
||||
Value::SLong8(_) => FieldType::SLong8,
|
||||
Value::Ifd8(_) => FieldType::Ifd8,
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of values (for ASCII: bytes including the terminating NUL).
|
||||
pub fn count(&self) -> usize {
|
||||
match self {
|
||||
Value::Byte(v) | Value::Undefined(v) => v.len(),
|
||||
Value::Ascii(s) => s.len() + 1,
|
||||
Value::Short(v) => v.len(),
|
||||
Value::Long(v) | Value::Ifd(v) => v.len(),
|
||||
Value::Rational(v) => v.len(),
|
||||
Value::SByte(v) => v.len(),
|
||||
Value::SShort(v) => v.len(),
|
||||
Value::SLong(v) => v.len(),
|
||||
Value::SRational(v) => v.len(),
|
||||
Value::Float(v) => v.len(),
|
||||
Value::Double(v) => v.len(),
|
||||
Value::Long8(v) | Value::Ifd8(v) => v.len(),
|
||||
Value::SLong8(v) => v.len(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Value `i` as `f64` (rationals divided; zero denominators give `None`). ASCII has no numbers.
|
||||
pub fn get_f64(&self, i: usize) -> Option<f64> {
|
||||
Some(match self {
|
||||
Value::Byte(v) | Value::Undefined(v) => *v.get(i)? as f64,
|
||||
Value::Ascii(_) => return None,
|
||||
Value::Short(v) => *v.get(i)? as f64,
|
||||
Value::Long(v) | Value::Ifd(v) => *v.get(i)? as f64,
|
||||
Value::Rational(v) => {
|
||||
let (n, d) = *v.get(i)?;
|
||||
if d == 0 {
|
||||
return None;
|
||||
}
|
||||
n as f64 / d as f64
|
||||
}
|
||||
Value::SByte(v) => *v.get(i)? as f64,
|
||||
Value::SShort(v) => *v.get(i)? as f64,
|
||||
Value::SLong(v) => *v.get(i)? as f64,
|
||||
Value::SRational(v) => {
|
||||
let (n, d) = *v.get(i)?;
|
||||
if d == 0 {
|
||||
return None;
|
||||
}
|
||||
n as f64 / d as f64
|
||||
}
|
||||
Value::Float(v) => *v.get(i)? as f64,
|
||||
Value::Double(v) => *v.get(i)?,
|
||||
Value::Long8(v) | Value::Ifd8(v) => *v.get(i)? as f64,
|
||||
Value::SLong8(v) => *v.get(i)? as f64,
|
||||
})
|
||||
}
|
||||
|
||||
/// Value `i` as an unsigned integer (integer types only; negative values give `None`).
|
||||
pub fn get_u64(&self, i: usize) -> Option<u64> {
|
||||
match self {
|
||||
Value::Byte(v) | Value::Undefined(v) => v.get(i).map(|&x| x as u64),
|
||||
Value::Short(v) => v.get(i).map(|&x| x as u64),
|
||||
Value::Long(v) | Value::Ifd(v) => v.get(i).map(|&x| x as u64),
|
||||
Value::Long8(v) | Value::Ifd8(v) => v.get(i).copied(),
|
||||
Value::SByte(v) => v.get(i).and_then(|&x| u64::try_from(x).ok()),
|
||||
Value::SShort(v) => v.get(i).and_then(|&x| u64::try_from(x).ok()),
|
||||
Value::SLong(v) => v.get(i).and_then(|&x| u64::try_from(x).ok()),
|
||||
Value::SLong8(v) => v.get(i).and_then(|&x| u64::try_from(x).ok()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Value `i` as a signed integer (integer types only).
|
||||
pub fn get_i64(&self, i: usize) -> Option<i64> {
|
||||
match self {
|
||||
Value::SByte(v) => v.get(i).map(|&x| x as i64),
|
||||
Value::SShort(v) => v.get(i).map(|&x| x as i64),
|
||||
Value::SLong(v) => v.get(i).map(|&x| x as i64),
|
||||
Value::SLong8(v) => v.get(i).copied(),
|
||||
_ => self.get_u64(i).and_then(|x| i64::try_from(x).ok()),
|
||||
}
|
||||
}
|
||||
|
||||
/// All values as `f64` (missing/invalid entries skipped for rationals with zero denominators → 0).
|
||||
pub fn to_f64_vec(&self) -> Vec<f64> {
|
||||
(0..self.len_values()).map(|i| self.get_f64(i).unwrap_or(0.0)).collect()
|
||||
}
|
||||
|
||||
/// All values as `u64` (integer types only; otherwise empty).
|
||||
pub fn to_u64_vec(&self) -> Vec<u64> {
|
||||
(0..self.len_values()).map_while(|i| self.get_u64(i)).collect()
|
||||
}
|
||||
|
||||
fn len_values(&self) -> usize {
|
||||
match self {
|
||||
Value::Ascii(_) => 0,
|
||||
_ => self.count(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text for ASCII values (trimmed of trailing NULs / spaces); `Byte`/`Undefined` are decoded as UTF-8 (lossy)
|
||||
/// up to the first NUL, which covers XMP packets and UCS-less Exif strings.
|
||||
pub fn as_str(&self) -> Option<String> {
|
||||
match self {
|
||||
Value::Ascii(s) => Some(s.trim_end_matches([' ', '\0']).to_string()),
|
||||
Value::Byte(b) | Value::Undefined(b) => {
|
||||
let end = b.iter().position(|&c| c == 0).unwrap_or(b.len());
|
||||
Some(String::from_utf8_lossy(&b[..end]).trim_end().to_string())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw bytes for `Byte` / `Undefined` / `SByte` / `Ascii`.
|
||||
pub fn as_bytes(&self) -> Option<&[u8]> {
|
||||
match self {
|
||||
Value::Byte(b) | Value::Undefined(b) => Some(b),
|
||||
Value::Ascii(s) => Some(s.as_bytes()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One IFD entry.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Entry {
|
||||
pub tag: u16,
|
||||
pub value: Value,
|
||||
/// Absolute position in the parsed buffer of the value bytes (inline or out-of-line).
|
||||
pub offset: u64,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
pub fn field_type(&self) -> FieldType {
|
||||
self.value.field_type()
|
||||
}
|
||||
pub fn count(&self) -> usize {
|
||||
self.value.count()
|
||||
}
|
||||
}
|
||||
|
||||
/// An Image File Directory with its child IFDs already resolved.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Ifd {
|
||||
/// Absolute offset of the IFD in the buffer.
|
||||
pub offset: u64,
|
||||
/// Entries sorted by tag (duplicate tags: the first occurrence wins).
|
||||
pub entries: Vec<Entry>,
|
||||
/// IFDs referenced by `SubIFDs` (330).
|
||||
pub sub_ifds: Vec<Ifd>,
|
||||
/// Exif private IFD (34665).
|
||||
pub exif: Option<Box<Ifd>>,
|
||||
/// GPS IFD (34853).
|
||||
pub gps: Option<Box<Ifd>>,
|
||||
/// Interoperability IFD (40965).
|
||||
pub interop: Option<Box<Ifd>>,
|
||||
}
|
||||
|
||||
impl Ifd {
|
||||
pub fn get(&self, tag: u16) -> Option<&Entry> {
|
||||
self.entries.binary_search_by_key(&tag, |e| e.tag).ok().map(|i| &self.entries[i])
|
||||
}
|
||||
pub fn contains(&self, tag: u16) -> bool {
|
||||
self.get(tag).is_some()
|
||||
}
|
||||
pub fn value(&self, tag: u16) -> Option<&Value> {
|
||||
self.get(tag).map(|e| &e.value)
|
||||
}
|
||||
/// First value as `u32` (integer types, saturating from wider types).
|
||||
pub fn u32(&self, tag: u16) -> Option<u32> {
|
||||
self.value(tag)?.get_u64(0).map(|v| v.min(u32::MAX as u64) as u32)
|
||||
}
|
||||
pub fn u64(&self, tag: u16) -> Option<u64> {
|
||||
self.value(tag)?.get_u64(0)
|
||||
}
|
||||
pub fn u16(&self, tag: u16) -> Option<u16> {
|
||||
self.value(tag)?.get_u64(0).map(|v| v.min(u16::MAX as u64) as u16)
|
||||
}
|
||||
pub fn i64(&self, tag: u16) -> Option<i64> {
|
||||
self.value(tag)?.get_i64(0)
|
||||
}
|
||||
pub fn f64(&self, tag: u16) -> Option<f64> {
|
||||
self.value(tag)?.get_f64(0)
|
||||
}
|
||||
pub fn f64s(&self, tag: u16) -> Option<Vec<f64>> {
|
||||
self.value(tag).map(|v| v.to_f64_vec())
|
||||
}
|
||||
pub fn u64s(&self, tag: u16) -> Option<Vec<u64>> {
|
||||
self.value(tag).map(|v| v.to_u64_vec())
|
||||
}
|
||||
/// Text value (ASCII, or UTF-8 bytes).
|
||||
pub fn string(&self, tag: u16) -> Option<String> {
|
||||
self.value(tag)?.as_str().filter(|s| !s.is_empty())
|
||||
}
|
||||
pub fn bytes(&self, tag: u16) -> Option<&[u8]> {
|
||||
self.value(tag)?.as_bytes()
|
||||
}
|
||||
|
||||
/// This IFD and all descendants (sub-IFDs, Exif, GPS, Interop), depth-first, pre-order.
|
||||
pub fn walk(&self) -> Vec<&Ifd> {
|
||||
let mut out = vec![self];
|
||||
for s in &self.sub_ifds {
|
||||
out.extend(s.walk());
|
||||
}
|
||||
for c in [&self.exif, &self.gps, &self.interop].into_iter().flatten() {
|
||||
out.extend(c.walk());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Image layout of this IFD, if it describes an image.
|
||||
pub fn image(&self) -> Result<image::ImageInfo> {
|
||||
image::ImageInfo::from_ifd(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// A parsed TIFF stream (IFD chain with resolved children).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Tiff {
|
||||
pub order: ByteOrder,
|
||||
pub bigtiff: bool,
|
||||
/// The main IFD chain (IFD0, IFD1, …).
|
||||
pub ifds: Vec<Ifd>,
|
||||
}
|
||||
|
||||
impl Tiff {
|
||||
/// Parse a TIFF stream (the header must be at offset 0 of `data`).
|
||||
pub fn parse(data: &[u8]) -> Result<Tiff> {
|
||||
reader::parse(data, &ParseOptions::default())
|
||||
}
|
||||
pub fn parse_with(data: &[u8], opts: &ParseOptions) -> Result<Tiff> {
|
||||
reader::parse(data, opts)
|
||||
}
|
||||
/// Header check only: returns the byte order and BigTIFF flag.
|
||||
pub fn sniff(data: &[u8]) -> Option<(ByteOrder, bool)> {
|
||||
reader::header(data).ok().map(|(o, b, _)| (o, b))
|
||||
}
|
||||
/// Every IFD (main chain and all children), depth-first.
|
||||
pub fn all_ifds(&self) -> Vec<&Ifd> {
|
||||
self.ifds.iter().flat_map(|i| i.walk()).collect()
|
||||
}
|
||||
/// The Exif IFD attached to IFD0 (or any IFD).
|
||||
pub fn exif(&self) -> Option<&Ifd> {
|
||||
self.all_ifds().into_iter().find_map(|i| i.exif.as_deref())
|
||||
}
|
||||
pub fn gps(&self) -> Option<&Ifd> {
|
||||
self.all_ifds().into_iter().find_map(|i| i.gps.as_deref())
|
||||
}
|
||||
/// First entry for `tag` in IFD0, then the Exif IFD, then any IFD.
|
||||
pub fn find(&self, tag: u16) -> Option<&Entry> {
|
||||
if let Some(e) = self.ifds.first().and_then(|i| i.get(tag)) {
|
||||
return Some(e);
|
||||
}
|
||||
if let Some(e) = self.exif().and_then(|i| i.get(tag)) {
|
||||
return Some(e);
|
||||
}
|
||||
self.all_ifds().into_iter().find_map(|i| i.get(tag))
|
||||
}
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
//! Maker-note IFD helpers.
|
||||
//!
|
||||
//! Most vendors store their maker note (Exif tag 37500) as a TIFF IFD, but each uses its own header,
|
||||
//! byte order and *offset base* (what stored value offsets are relative to). The header layouts here
|
||||
//! follow the public descriptions in the ExifTool tag documentation (`MakerNotes` table) and the
|
||||
//! vendors' own published notes; no third-party code was consulted.
|
||||
|
||||
use crate::{ByteOrder, Ifd, ParseOptions, parse_ifd_at};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Maker-note dialects we know how to locate.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum MakerNoteKind {
|
||||
/// Plain IFD at the start of the note, offsets relative to the enclosing TIFF header (Canon, many others).
|
||||
Plain,
|
||||
/// `Nikon\0` + version + embedded TIFF header at +10; offsets relative to that header.
|
||||
NikonV3,
|
||||
/// `Nikon\0\x01\0`: IFD at +8, offsets relative to the enclosing TIFF header.
|
||||
NikonV1,
|
||||
/// `SONY DSC `/`SONY CAM `/`SONY MOBILE` etc.: 12-byte header, offsets relative to the TIFF header.
|
||||
Sony,
|
||||
/// `FUJIFILM` + LE u32 IFD offset; little-endian, offsets relative to the note start.
|
||||
Fujifilm,
|
||||
/// `OLYMPUS\0` + byte order + version: IFD at +12, offsets relative to the note start.
|
||||
OlympusNew,
|
||||
/// `OLYMP\0` / `EPSON\0` etc.: IFD at +8, offsets relative to the TIFF header.
|
||||
OlympusOld,
|
||||
/// `Panasonic\0\0\0`: IFD at +12, offsets relative to the TIFF header.
|
||||
Panasonic,
|
||||
/// `AOC\0` + byte order: IFD at +6, offsets relative to the TIFF header.
|
||||
PentaxAoc,
|
||||
/// `PENTAX \0` + byte order: IFD at +10, offsets relative to the note start.
|
||||
Pentax,
|
||||
}
|
||||
|
||||
/// A parsed maker-note IFD.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MakerNote {
|
||||
pub kind: MakerNoteKind,
|
||||
pub order: ByteOrder,
|
||||
/// Absolute offset that stored value offsets are relative to.
|
||||
pub base: u64,
|
||||
pub ifd: Ifd,
|
||||
}
|
||||
|
||||
/// Locate and parse the maker note stored at absolute `offset` (length `len`) inside `data`, the buffer whose
|
||||
/// start is the enclosing TIFF header. `order` is the enclosing stream's byte order. `make` (the Exif Make) is
|
||||
/// used only as a hint for header-less notes. Returns `None` for unknown or unparsable notes.
|
||||
pub fn parse_makernote(data: &[u8], offset: u64, len: u64, order: ByteOrder, make: &str) -> Option<MakerNote> {
|
||||
let start = usize::try_from(offset).ok()?;
|
||||
let end = start.checked_add(usize::try_from(len).ok()?)?.min(data.len());
|
||||
let note = data.get(start..end)?;
|
||||
let order_at = |i: usize| match note.get(i..i + 2) {
|
||||
Some(b"II") => Some(ByteOrder::Little),
|
||||
Some(b"MM") => Some(ByteOrder::Big),
|
||||
_ => None,
|
||||
};
|
||||
// A fixed value budget: a maker note is at most tens of kilobytes of values in any honest file, and
|
||||
// computing the budget from the buffer's length multiplies the file length (a hostile entry in a
|
||||
// sparse header-read buffer, where the buffer holds the file's logical size but only a few
|
||||
// kilobytes are loaded, would decode allocations no actual data backs).
|
||||
let opts = ParseOptions { max_ifds: 64, max_depth: 3, value_budget: Some(1 << 20), ..Default::default() };
|
||||
let try_parse = |kind: MakerNoteKind, ifd_at: u64, base: u64, ord: ByteOrder| -> Option<MakerNote> {
|
||||
let (ifd, _) = parse_ifd_at(data, ifd_at, ord, base, false, &opts).ok()?;
|
||||
(!ifd.entries.is_empty()).then_some(MakerNote { kind, order: ord, base, ifd })
|
||||
};
|
||||
if note.starts_with(b"Nikon\0") {
|
||||
if note.get(6) == Some(&1) {
|
||||
return try_parse(MakerNoteKind::NikonV1, offset + 8, 0, order);
|
||||
}
|
||||
let ord = order_at(10)?;
|
||||
let ifd_rel = ord.read_u32(note, 14)? as u64;
|
||||
let base = offset + 10;
|
||||
return try_parse(MakerNoteKind::NikonV3, base + ifd_rel, base, ord);
|
||||
}
|
||||
if note.starts_with(b"FUJIFILM") || note.starts_with(b"GENERALE") {
|
||||
let rel = ByteOrder::Little.read_u32(note, 8)? as u64;
|
||||
return try_parse(MakerNoteKind::Fujifilm, offset + rel, offset, ByteOrder::Little);
|
||||
}
|
||||
if note.starts_with(b"OLYMPUS\0") || note.starts_with(b"OM SYSTEM\0") {
|
||||
let (ord_at, ifd_at) = if note.starts_with(b"OM SYSTEM\0") { (12, 16) } else { (8, 12) };
|
||||
let ord = order_at(ord_at).unwrap_or(order);
|
||||
return try_parse(MakerNoteKind::OlympusNew, offset + ifd_at, offset, ord);
|
||||
}
|
||||
for p in [b"OLYMP\0", b"EPSON\0", b"MINOL\0", b"CAMER\0", b"SANYO\0"] {
|
||||
if note.starts_with(p) {
|
||||
return try_parse(MakerNoteKind::OlympusOld, offset + 8, 0, order);
|
||||
}
|
||||
}
|
||||
if note.starts_with(b"Panasonic\0") {
|
||||
return try_parse(MakerNoteKind::Panasonic, offset + 12, 0, order);
|
||||
}
|
||||
if note.starts_with(b"AOC\0") {
|
||||
let ord = order_at(4).unwrap_or(order);
|
||||
return try_parse(MakerNoteKind::PentaxAoc, offset + 6, 0, ord);
|
||||
}
|
||||
if note.starts_with(b"PENTAX \0") {
|
||||
let ord = order_at(8).unwrap_or(order);
|
||||
return try_parse(MakerNoteKind::Pentax, offset + 10, offset, ord);
|
||||
}
|
||||
if (note.starts_with(b"SONY") || note.starts_with(b"VHAB \0"))
|
||||
&& let Some(m) = try_parse(MakerNoteKind::Sony, offset + 12, 0, order)
|
||||
{
|
||||
return Some(m);
|
||||
}
|
||||
let _ = make;
|
||||
try_parse(MakerNoteKind::Plain, offset, 0, order)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{IfdBuilder, TiffWriter, Value, tags};
|
||||
|
||||
/// Build a TIFF whose Exif IFD carries `note` as the maker note, return (bytes, note offset, len).
|
||||
fn with_note(order: ByteOrder, note: Vec<u8>) -> (Vec<u8>, u64, u64) {
|
||||
let mut exif = IfdBuilder::new();
|
||||
exif.set(tags::MAKER_NOTE, Value::Undefined(note));
|
||||
let mut ifd0 = IfdBuilder::new();
|
||||
ifd0.set(tags::MAKE, Value::Ascii("Test".into()));
|
||||
ifd0.set_child(tags::EXIF_IFD, exif);
|
||||
let bytes = TiffWriter { order, bigtiff: false }.write(&[ifd0]).unwrap();
|
||||
let t = crate::Tiff::parse(&bytes).unwrap();
|
||||
let e = t.exif().unwrap().get(tags::MAKER_NOTE).unwrap();
|
||||
let (off, len) = (e.offset, e.count() as u64);
|
||||
(bytes, off, len)
|
||||
}
|
||||
|
||||
/// An IFD with one SHORT entry (tag 1, value 7) and one out-of-line LONG[2] entry at `rel` (relative to base).
|
||||
fn tiny_ifd(order: ByteOrder, rel_values: u32) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
order.put_u16(&mut v, 2);
|
||||
order.put_u16(&mut v, 1);
|
||||
order.put_u16(&mut v, 3);
|
||||
order.put_u32(&mut v, 1);
|
||||
order.put_u16(&mut v, 7);
|
||||
order.put_u16(&mut v, 0);
|
||||
order.put_u16(&mut v, 2);
|
||||
order.put_u16(&mut v, 4);
|
||||
order.put_u32(&mut v, 2);
|
||||
order.put_u32(&mut v, rel_values);
|
||||
order.put_u32(&mut v, 0);
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nikon_v3_uses_embedded_header_base() {
|
||||
for order in [ByteOrder::Little, ByteOrder::Big] {
|
||||
let mut note = b"Nikon\0\x02\x10\0\0".to_vec();
|
||||
let hdr_at = note.len();
|
||||
note.extend_from_slice(if order == ByteOrder::Little { b"II" } else { b"MM" });
|
||||
order.put_u16(&mut note, 42);
|
||||
order.put_u32(&mut note, 8);
|
||||
// IFD at +8 (relative to embedded header), values after IFD: 8 + 2 + 24 + 4 = 38
|
||||
note.extend(tiny_ifd(order, 38));
|
||||
order.put_u32(&mut note, 111);
|
||||
order.put_u32(&mut note, 222);
|
||||
let (bytes, off, len) = with_note(order, note);
|
||||
let m = parse_makernote(&bytes, off, len, order, "NIKON CORPORATION").unwrap();
|
||||
assert_eq!(m.kind, MakerNoteKind::NikonV3);
|
||||
assert_eq!(m.base, off + hdr_at as u64);
|
||||
assert_eq!(m.ifd.u32(1), Some(7));
|
||||
assert_eq!(m.ifd.u64s(2).unwrap(), vec![111, 222]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fujifilm_offsets_relative_to_note() {
|
||||
let mut note = b"FUJIFILM".to_vec();
|
||||
ByteOrder::Little.put_u32(&mut note, 12);
|
||||
// IFD at 12 (relative to note), values at 12 + 30 = 42
|
||||
note.extend(tiny_ifd(ByteOrder::Little, 42));
|
||||
ByteOrder::Little.put_u32(&mut note, 5);
|
||||
ByteOrder::Little.put_u32(&mut note, 6);
|
||||
// enclosing file is big-endian: Fuji notes are always little-endian
|
||||
let (bytes, off, len) = with_note(ByteOrder::Big, note);
|
||||
let m = parse_makernote(&bytes, off, len, ByteOrder::Big, "FUJIFILM").unwrap();
|
||||
assert_eq!(m.kind, MakerNoteKind::Fujifilm);
|
||||
assert_eq!(m.order, ByteOrder::Little);
|
||||
assert_eq!(m.ifd.u64s(2).unwrap(), vec![5, 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_canon_style_note() {
|
||||
// Plain IFD whose out-of-line offset is relative to the TIFF header: we need the absolute
|
||||
// position, which we only know after writing. Write once to learn the offset, then patch.
|
||||
let order = ByteOrder::Little;
|
||||
let mut note = tiny_ifd(order, 0);
|
||||
note.extend_from_slice(&[0; 8]);
|
||||
let (mut bytes, off, len) = with_note(order, note);
|
||||
let values_abs = off as u32 + 30;
|
||||
bytes[off as usize + 22..off as usize + 26].copy_from_slice(&values_abs.to_le_bytes());
|
||||
bytes[off as usize + 30..off as usize + 34].copy_from_slice(&9u32.to_le_bytes());
|
||||
let m = parse_makernote(&bytes, off, len, order, "Canon").unwrap();
|
||||
assert_eq!(m.kind, MakerNoteKind::Plain);
|
||||
assert_eq!(m.ifd.u64s(2).unwrap(), vec![9, 0]);
|
||||
}
|
||||
|
||||
/// A maker note's value budget is fixed, not computed from the length of the buffer it sits in:
|
||||
/// an entry claiming more than the note budget (here 2 MB) is dropped, a fitting one is read. In a
|
||||
/// sparse header read the buffer holds the file's logical size while only kilobytes were loaded,
|
||||
/// so a length-scaled budget would let an unrelated entry decode megabytes of zeros (see the focus
|
||||
/// reader, try_read_exif_with).
|
||||
#[test]
|
||||
fn a_note_entry_past_the_fixed_value_budget_is_dropped() {
|
||||
let order = ByteOrder::Little;
|
||||
let mut note = b"SONY DSC \0\0\0".to_vec();
|
||||
// the Sony IFD directly after the 12-byte header, one fitting BYTE entry and a decoy
|
||||
// BYTE[2 MB] entry pointing into the file's own (zero-filled) body
|
||||
order.put_u16(&mut note, 2);
|
||||
order.put_u16(&mut note, 0x201b);
|
||||
order.put_u16(&mut note, 1);
|
||||
order.put_u32(&mut note, 1);
|
||||
note.extend([3, 0, 0, 0]);
|
||||
order.put_u16(&mut note, 0x9900);
|
||||
order.put_u16(&mut note, 1);
|
||||
order.put_u32(&mut note, 2 << 20);
|
||||
order.put_u32(&mut note, 200);
|
||||
order.put_u32(&mut note, 0);
|
||||
let mut bytes = note.clone();
|
||||
bytes.resize(200 + (2 << 20), 0); // the decoy's value range is inside the real bytes
|
||||
let m = parse_makernote(&bytes, 0, note.len() as u64, order, "SONY").unwrap();
|
||||
assert_eq!(m.kind, MakerNoteKind::Sony);
|
||||
assert!(m.ifd.get(0x201b).is_some(), "the fitting entry is read");
|
||||
assert!(m.ifd.get(0x9900).is_none(), "the decoy is dropped by the value budget");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_note_is_none() {
|
||||
let (bytes, off, len) = with_note(ByteOrder::Little, vec![0xff; 40]);
|
||||
assert!(parse_makernote(&bytes, off, len, ByteOrder::Little, "X").is_none());
|
||||
assert!(parse_makernote(&bytes, 1 << 40, 10, ByteOrder::Little, "X").is_none());
|
||||
assert!(parse_makernote(&bytes, off, u64::MAX, ByteOrder::Little, "X").is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,536 +0,0 @@
|
||||
//! Bounds-checked IFD parsing.
|
||||
|
||||
use crate::{ByteOrder, Entry, FieldType, Ifd, Result, Tiff, TiffError, Value, tags};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Limits applied while parsing. The defaults are generous for real files and safe for hostile ones.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ParseOptions {
|
||||
/// Maximum number of IFDs visited in total (chain + children).
|
||||
pub max_ifds: usize,
|
||||
/// Maximum nesting depth of child IFDs.
|
||||
pub max_depth: usize,
|
||||
/// Maximum number of entries read from one IFD.
|
||||
pub max_entries: usize,
|
||||
/// Maximum total number of entries read across all IFDs (chain + children).
|
||||
///
|
||||
/// Hostile files can reuse the same bytes for up to `max_ifds` tables of `max_entries`
|
||||
/// entries each (overlapping IFD tables via SubIFD pointers shifted by one entry), which can
|
||||
/// allocate millions of `Entry`s from a small input (~100 KB → ~400 MB). This hard cap bounds
|
||||
/// that amplification regardless of entry size. 65 536 is generous for real files — a 50 MB
|
||||
/// scanned TIFF with thousands of entries across chain + children stays well under it — yet
|
||||
/// stops a small file from allocating hundreds of megabytes of `Entry`s.
|
||||
pub max_entries_total: usize,
|
||||
/// Maximum total bytes of decoded values; `None` = `8 × input length + 1 MiB`.
|
||||
pub value_budget: Option<u64>,
|
||||
/// Follow `SubIFDs` / Exif / GPS / Interop pointers.
|
||||
pub follow_children: bool,
|
||||
/// Accept the TIFF-like magic numbers used by some raw formats (ORF `IIRO`/`IIRS`, RW2 `IIU`).
|
||||
pub accept_raw_magic: bool,
|
||||
}
|
||||
|
||||
impl Default for ParseOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_ifds: 1024,
|
||||
max_depth: 10,
|
||||
max_entries: 8192,
|
||||
max_entries_total: 65536,
|
||||
value_budget: None,
|
||||
follow_children: true,
|
||||
accept_raw_magic: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ParseOptions {
|
||||
/// The value budget for `data_len` bytes of input: [`Self::value_budget`], else `8 × data_len + 1 MiB`.
|
||||
pub fn budget_for(&self, data_len: usize) -> u64 {
|
||||
self.value_budget.unwrap_or((data_len as u64).saturating_mul(8).saturating_add(1 << 20))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a directory's entries are and how many of them the reader reads, as [`directory_entries`] found them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct DirectoryEntries {
|
||||
/// Position of the first entry.
|
||||
table: usize,
|
||||
/// Entries read: the declared count, cut to the entries the data holds and to the `max_entries` limit.
|
||||
read: usize,
|
||||
/// The declared entry count.
|
||||
declared: u64,
|
||||
/// Bytes per entry: 12, or 20 in BigTIFF.
|
||||
entry_size: usize,
|
||||
}
|
||||
|
||||
impl DirectoryEntries {
|
||||
/// Positions of the entries read, in directory order. Checked arithmetic: the iteration ends rather than
|
||||
/// overflow, whatever the layout.
|
||||
pub fn positions(&self) -> impl Iterator<Item = usize> + use<> {
|
||||
let (table, size) = (self.table, self.entry_size);
|
||||
(0..self.read).map_while(move |i| i.checked_mul(size)?.checked_add(table))
|
||||
}
|
||||
|
||||
/// The number of entries read.
|
||||
pub fn read(&self) -> usize {
|
||||
self.read
|
||||
}
|
||||
|
||||
/// The entry count the directory declares.
|
||||
pub fn declared(&self) -> u64 {
|
||||
self.declared
|
||||
}
|
||||
}
|
||||
|
||||
/// The directory at `offset` as the reader walks it: its entry table and how many entries it reads. The same errors
|
||||
/// as [`parse_ifd_at`] for a directory it can't read: past the data, empty, or without room for one entry.
|
||||
pub fn directory_entries(data: &[u8], offset: u64, order: ByteOrder, bigtiff: bool, max_entries: usize) -> Result<DirectoryEntries> {
|
||||
let pos = usize::try_from(offset).map_err(|_| TiffError::Truncated(offset))?;
|
||||
let (n, head, entry_size) = if bigtiff {
|
||||
(order.read_u64(data, pos).ok_or(TiffError::Truncated(offset))?, 8usize, 20usize)
|
||||
} else {
|
||||
(order.read_u16(data, pos).ok_or(TiffError::Truncated(offset))? as u64, 2, 12)
|
||||
};
|
||||
let table = pos + head;
|
||||
let fit = (data.len().saturating_sub(table) / entry_size) as u64;
|
||||
let read = n.min(fit).min(max_entries as u64) as usize;
|
||||
if n == 0 {
|
||||
return Err(TiffError::Invalid(format!("empty IFD at {offset}")));
|
||||
}
|
||||
if read == 0 {
|
||||
return Err(TiffError::Truncated(offset));
|
||||
}
|
||||
Ok(DirectoryEntries { table, read, declared: n, entry_size })
|
||||
}
|
||||
|
||||
/// A directory entry the reader can read: its tag, type and count, and where its values are.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct EntrySpan {
|
||||
pub tag: u16,
|
||||
pub field_type: FieldType,
|
||||
pub count: u64,
|
||||
/// Position of the values in the data: the entry's own value field when they fit it, else `base` plus the offset
|
||||
/// stored there.
|
||||
pub start: u64,
|
||||
/// `count × size` bytes.
|
||||
pub len: u64,
|
||||
}
|
||||
|
||||
/// The entry at `pos`, when the reader reads it: a known field type, `count × size` without overflow, and values
|
||||
/// inside `data`. Nothing is decoded; [`parse_ifd_at`] also drops an entry whose values exceed what is left of its
|
||||
/// value budget ([`ParseOptions::budget_for`]), which this leaves to the caller.
|
||||
pub fn entry_span(data: &[u8], pos: usize, order: ByteOrder, bigtiff: bool, base: u64) -> Option<EntrySpan> {
|
||||
let tag = order.read_u16(data, pos)?;
|
||||
let field_type = FieldType::from_u16(order.read_u16(data, pos.checked_add(2)?)?)?;
|
||||
let (count, field, inline) = if bigtiff {
|
||||
(order.read_u64(data, pos.checked_add(4)?)?, pos.checked_add(12)?, 8u64)
|
||||
} else {
|
||||
(order.read_u32(data, pos.checked_add(4)?)? as u64, pos.checked_add(8)?, 4)
|
||||
};
|
||||
let len = count.checked_mul(field_type.size() as u64)?;
|
||||
let start = if len <= inline {
|
||||
field as u64
|
||||
} else {
|
||||
let rel = if bigtiff { order.read_u64(data, field)? } else { order.read_u32(data, field)? as u64 };
|
||||
base.checked_add(rel)?
|
||||
};
|
||||
let end = start.checked_add(len)?;
|
||||
(end <= data.len() as u64).then_some(EntrySpan { tag, field_type, count, start, len })
|
||||
}
|
||||
|
||||
/// Whether a directory declaring `declared` entries was read whole (`read` entries), so that its next-IFD pointer
|
||||
/// follows them. The counts compare as 64-bit numbers: narrowing the declared count to `usize` instead would, on a
|
||||
/// 32-bit target, let a BigTIFF declaring 4,294,967,297 entries but holding one pass for a whole directory.
|
||||
fn reads_every_entry(declared: u64, read: usize) -> bool {
|
||||
u64::try_from(read).is_ok_and(|read| read == declared)
|
||||
}
|
||||
|
||||
/// Parse the header: (byte order, bigtiff, first IFD offset).
|
||||
pub(crate) fn header(data: &[u8]) -> Result<(ByteOrder, bool, u64)> {
|
||||
header_with(data, true)
|
||||
}
|
||||
|
||||
fn header_with(data: &[u8], raw_magic: bool) -> Result<(ByteOrder, bool, u64)> {
|
||||
let order = match data.get(0..2) {
|
||||
Some(b"II") => ByteOrder::Little,
|
||||
Some(b"MM") => ByteOrder::Big,
|
||||
_ => return Err(TiffError::NotTiff),
|
||||
};
|
||||
let magic = order.read_u16(data, 2).ok_or(TiffError::NotTiff)?;
|
||||
match magic {
|
||||
42 => Ok((order, false, order.read_u32(data, 4).ok_or(TiffError::Truncated(4))? as u64)),
|
||||
43 => {
|
||||
let bytesize = order.read_u16(data, 4).ok_or(TiffError::Truncated(4))?;
|
||||
let zero = order.read_u16(data, 6).ok_or(TiffError::Truncated(6))?;
|
||||
if bytesize != 8 || zero != 0 {
|
||||
return Err(TiffError::NotTiff);
|
||||
}
|
||||
Ok((order, true, order.read_u64(data, 8).ok_or(TiffError::Truncated(8))?))
|
||||
}
|
||||
0x4f52 | 0x5352 | 0x0055 if raw_magic => Ok((order, false, order.read_u32(data, 4).ok_or(TiffError::Truncated(4))? as u64)),
|
||||
_ => Err(TiffError::NotTiff),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse(data: &[u8], opts: &ParseOptions) -> Result<Tiff> {
|
||||
let (order, big, first) = header_with(data, opts.accept_raw_magic)?;
|
||||
let mut ctx = Ctx::new(data, order, big, opts);
|
||||
let mut ifds = Vec::new();
|
||||
let mut off = first;
|
||||
while off != 0 {
|
||||
match ctx.ifd(off, 0, 0) {
|
||||
Ok((ifd, next)) => {
|
||||
ifds.push(ifd);
|
||||
off = next;
|
||||
}
|
||||
Err(e) => {
|
||||
if ifds.is_empty() {
|
||||
return Err(e);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ifds.is_empty() {
|
||||
return Err(TiffError::Invalid("no IFDs".into()));
|
||||
}
|
||||
Ok(Tiff { order, bigtiff: big, ifds })
|
||||
}
|
||||
|
||||
/// Parse one IFD at absolute `offset` whose value offsets (and child IFD pointers) are relative to
|
||||
/// `base` (absolute position = `base + stored offset`). Returns the IFD and the absolute offset of the
|
||||
/// next IFD (0 when there is none). Used for maker notes, which often use their own offset base.
|
||||
pub fn parse_ifd_at(data: &[u8], offset: u64, order: ByteOrder, base: u64, bigtiff: bool, opts: &ParseOptions) -> Result<(Ifd, u64)> {
|
||||
let mut ctx = Ctx::new(data, order, bigtiff, opts);
|
||||
ctx.ifd(offset, base, 0)
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
data: &'a [u8],
|
||||
order: ByteOrder,
|
||||
big: bool,
|
||||
opts: &'a ParseOptions,
|
||||
visited: HashSet<u64>,
|
||||
budget: u64,
|
||||
entries_total: usize,
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
fn new(data: &'a [u8], order: ByteOrder, big: bool, opts: &'a ParseOptions) -> Self {
|
||||
let budget = opts.budget_for(data.len());
|
||||
Self { data, order, big, opts, visited: HashSet::new(), budget, entries_total: 0 }
|
||||
}
|
||||
|
||||
fn read_off(&self, pos: usize) -> Option<u64> {
|
||||
if self.big { self.order.read_u64(self.data, pos) } else { self.order.read_u32(self.data, pos).map(|v| v as u64) }
|
||||
}
|
||||
|
||||
/// Returns (ifd, absolute next offset or 0).
|
||||
fn ifd(&mut self, offset: u64, base: u64, depth: usize) -> Result<(Ifd, u64)> {
|
||||
if depth > self.opts.max_depth {
|
||||
return Err(TiffError::Limit("IFD nesting depth"));
|
||||
}
|
||||
if self.visited.len() >= self.opts.max_ifds {
|
||||
return Err(TiffError::Limit("IFD count"));
|
||||
}
|
||||
if !self.visited.insert(offset) {
|
||||
return Err(TiffError::Invalid(format!("IFD loop at {offset}")));
|
||||
}
|
||||
let dir = directory_entries(self.data, offset, self.order, self.big, self.opts.max_entries)?;
|
||||
// Bound total entries across the whole parse so overlapping IFD tables (SubIFD pointers
|
||||
// shifted by one entry) cannot allocate millions of `Entry`s from a small input.
|
||||
self.entries_total = self.entries_total.saturating_add(dir.read);
|
||||
if self.entries_total > self.opts.max_entries_total {
|
||||
return Err(TiffError::Limit("entry count"));
|
||||
}
|
||||
let mut entries = Vec::with_capacity(dir.read);
|
||||
for p in dir.positions() {
|
||||
if let Some(e) = self.entry(p, base) {
|
||||
entries.push(e);
|
||||
}
|
||||
}
|
||||
entries.sort_by_key(|e| e.tag);
|
||||
entries.dedup_by_key(|e| e.tag);
|
||||
// the next-IFD pointer follows the last entry, read only when every declared entry was (checked: a BigTIFF
|
||||
// count can be anything up to u64::MAX)
|
||||
let next = if reads_every_entry(dir.declared, dir.read) {
|
||||
match dir.read.checked_mul(dir.entry_size).and_then(|n| n.checked_add(dir.table)).and_then(|p| self.read_off(p)) {
|
||||
Some(0) | None => 0,
|
||||
Some(v) => base.checked_add(v).unwrap_or(0),
|
||||
}
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut ifd = Ifd { offset, entries, ..Default::default() };
|
||||
if self.opts.follow_children {
|
||||
self.children(&mut ifd, base, depth);
|
||||
}
|
||||
Ok((ifd, next))
|
||||
}
|
||||
|
||||
fn children(&mut self, ifd: &mut Ifd, base: u64, depth: usize) {
|
||||
if let Some(v) = ifd.value(tags::SUB_IFDS) {
|
||||
let offs = v.to_u64_vec();
|
||||
for o in offs {
|
||||
if let Some(abs) = base.checked_add(o)
|
||||
&& let Ok((sub, _)) = self.ifd(abs, base, depth + 1)
|
||||
{
|
||||
ifd.sub_ifds.push(sub);
|
||||
}
|
||||
}
|
||||
}
|
||||
let child = |tag: u16, ctx: &mut Self| -> Option<Box<Ifd>> {
|
||||
let o = ifd.value(tag)?.get_u64(0)?;
|
||||
let abs = base.checked_add(o)?;
|
||||
ctx.ifd(abs, base, depth + 1).ok().map(|(i, _)| Box::new(i))
|
||||
};
|
||||
let exif = child(tags::EXIF_IFD, self);
|
||||
let gps = child(tags::GPS_IFD, self);
|
||||
let interop = child(tags::INTEROP_IFD, self);
|
||||
ifd.exif = exif;
|
||||
ifd.gps = gps;
|
||||
ifd.interop = interop;
|
||||
}
|
||||
|
||||
fn entry(&mut self, p: usize, base: u64) -> Option<Entry> {
|
||||
let span = entry_span(self.data, p, self.order, self.big, base)?;
|
||||
if span.len > self.budget {
|
||||
return None;
|
||||
}
|
||||
self.budget -= span.len;
|
||||
let bytes = self.data.get(usize::try_from(span.start).ok()?..usize::try_from(span.start + span.len).ok()?)?;
|
||||
Some(Entry { tag: span.tag, value: decode(self.order, span.field_type, bytes), offset: span.start })
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode `bytes` (exactly `count × size` long, or the first values of an entry) as values of type `typ`.
|
||||
pub fn decode(o: ByteOrder, typ: FieldType, b: &[u8]) -> Value {
|
||||
fn arr<const N: usize>(c: &[u8]) -> [u8; N] {
|
||||
let mut a = [0u8; N];
|
||||
a.copy_from_slice(c);
|
||||
a
|
||||
}
|
||||
match typ {
|
||||
FieldType::Byte => Value::Byte(b.to_vec()),
|
||||
FieldType::Undefined => Value::Undefined(b.to_vec()),
|
||||
FieldType::Ascii => {
|
||||
let end = b.iter().position(|&c| c == 0).unwrap_or(b.len());
|
||||
Value::Ascii(String::from_utf8_lossy(&b[..end]).into_owned())
|
||||
}
|
||||
FieldType::SByte => Value::SByte(b.iter().map(|&x| x as i8).collect()),
|
||||
FieldType::Short => Value::Short(b.as_chunks::<2>().0.iter().map(|c| o.u16(arr(c))).collect()),
|
||||
FieldType::SShort => Value::SShort(b.as_chunks::<2>().0.iter().map(|c| o.u16(arr(c)) as i16).collect()),
|
||||
FieldType::Long => Value::Long(b.as_chunks::<4>().0.iter().map(|c| o.u32(arr(c))).collect()),
|
||||
FieldType::Ifd => Value::Ifd(b.as_chunks::<4>().0.iter().map(|c| o.u32(arr(c))).collect()),
|
||||
FieldType::SLong => Value::SLong(b.as_chunks::<4>().0.iter().map(|c| o.u32(arr(c)) as i32).collect()),
|
||||
FieldType::Float => Value::Float(b.as_chunks::<4>().0.iter().map(|c| f32::from_bits(o.u32(arr(c)))).collect()),
|
||||
FieldType::Rational => Value::Rational(b.as_chunks::<8>().0.iter().map(|c| (o.u32(arr(&c[..4])), o.u32(arr(&c[4..])))).collect()),
|
||||
FieldType::SRational => {
|
||||
Value::SRational(b.as_chunks::<8>().0.iter().map(|c| (o.u32(arr(&c[..4])) as i32, o.u32(arr(&c[4..])) as i32)).collect())
|
||||
}
|
||||
FieldType::Double => Value::Double(b.as_chunks::<8>().0.iter().map(|c| f64::from_bits(o.u64(arr(c)))).collect()),
|
||||
FieldType::Long8 => Value::Long8(b.as_chunks::<8>().0.iter().map(|c| o.u64(arr(c))).collect()),
|
||||
FieldType::Ifd8 => Value::Ifd8(b.as_chunks::<8>().0.iter().map(|c| o.u64(arr(c))).collect()),
|
||||
FieldType::SLong8 => Value::SLong8(b.as_chunks::<8>().0.iter().map(|c| o.u64(arr(c)) as i64).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Value;
|
||||
use crate::tags as t;
|
||||
use crate::writer::{IfdBuilder, TiffWriter};
|
||||
|
||||
/// A value budget the caller sets bounds what is decoded: an entry claiming more value bytes than
|
||||
/// the budget allows is dropped, entries that fit are read (the sparse header-read path, where the
|
||||
/// buffer holds the file's logical size but only a few kilobytes were ever loaded, sizes its
|
||||
/// budget from what was fetched, not from whatever length the file claims).
|
||||
#[test]
|
||||
fn the_value_budget_drops_over_budget_entries_and_keeps_the_rest() {
|
||||
let mut ifd0 = IfdBuilder::new();
|
||||
ifd0.set(t::MAKE, Value::Ascii("Keep".into()));
|
||||
ifd0.set(0x9000, Value::Byte(vec![0; 2 << 20]));
|
||||
let file = TiffWriter { order: ByteOrder::Little, bigtiff: false }.write(&[ifd0]).unwrap();
|
||||
let opts = ParseOptions { value_budget: Some(1 << 20), ..Default::default() };
|
||||
let tiff = Tiff::parse_with(&file, &opts).unwrap();
|
||||
assert_eq!(tiff.ifds[0].string(t::MAKE), Some("Keep".to_string()), "a fitting entry is read");
|
||||
assert!(tiff.ifds[0].get(0x9000).is_none(), "the over-budget entry is dropped");
|
||||
}
|
||||
|
||||
/// A BigTIFF whose first IFD, at 80, declares `declared` entries but holds one, followed by a next-IFD pointer
|
||||
/// `next`; a valid one-entry IFD sits at 16.
|
||||
fn bigtiff_chain(order: ByteOrder, declared: u64, next: u64) -> Vec<u8> {
|
||||
let ifd = |d: &mut Vec<u8>, count: u64, tag: u16, next: u64| {
|
||||
order.put_u64(d, count);
|
||||
order.put_u16(d, tag);
|
||||
order.put_u16(d, 3);
|
||||
order.put_u64(d, 1);
|
||||
order.put_u16(d, 8);
|
||||
d.extend([0; 6]);
|
||||
order.put_u64(d, next);
|
||||
};
|
||||
let mut d = if order == ByteOrder::Little { b"II".to_vec() } else { b"MM".to_vec() };
|
||||
order.put_u16(&mut d, 43);
|
||||
order.put_u16(&mut d, 8);
|
||||
order.put_u16(&mut d, 0);
|
||||
order.put_u64(&mut d, 80);
|
||||
ifd(&mut d, 1, 0x0101, 0);
|
||||
d.resize(80, 0);
|
||||
ifd(&mut d, declared, 0x0100, next);
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_directory_read_whole_has_a_next_pointer() {
|
||||
// the comparison itself, on every target: a declared count past u32::MAX never matches a small read count
|
||||
for (declared, read, whole) in [
|
||||
(0, 0, true),
|
||||
(1, 1, true),
|
||||
(8192, 8192, true),
|
||||
(8193, 8192, false),
|
||||
(1, 0, false),
|
||||
((1 << 32) + 1, 1, false),
|
||||
((2 << 32) + 1, 1, false),
|
||||
((1 << 63) + 1, 1, false),
|
||||
(u64::MAX, 1, false),
|
||||
] {
|
||||
assert_eq!(reads_every_entry(declared, read), whole, "{declared} declared, {read} read");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bigtiff_count_past_u32_max_never_follows_the_next_pointer() {
|
||||
// the whole chain: on 32-bit targets (wasm32) the old cast truncated these counts to 1 and followed the pointer
|
||||
for order in [ByteOrder::Little, ByteOrder::Big] {
|
||||
for declared in [(1u64 << 32) + 1, (2u64 << 32) + 1, (1u64 << 63) + 1] {
|
||||
let d = bigtiff_chain(order, declared, 16);
|
||||
let tiff = Tiff::parse(&d).unwrap();
|
||||
assert_eq!(tiff.ifds.len(), 1, "{order:?} {declared}");
|
||||
assert_eq!(tiff.ifds[0].u64(0x0100), Some(8));
|
||||
assert_eq!(parse_ifd_at(&d, 80, order, 0, true, &ParseOptions::default()).unwrap().1, 0, "{order:?} {declared}");
|
||||
}
|
||||
// control: the same file declaring its one entry follows the pointer to the IFD at 16
|
||||
let whole = Tiff::parse(&bigtiff_chain(order, 1, 16)).unwrap();
|
||||
assert_eq!(whole.ifds.len(), 2, "{order:?}");
|
||||
assert_eq!(whole.ifds[1].u64(0x0101), Some(8));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_positions_never_overflow() {
|
||||
// a hand-built layout the reader never produces: the iterator stops instead of overflowing
|
||||
let hostile = DirectoryEntries { table: usize::MAX, read: 2, declared: 2, entry_size: 12 };
|
||||
assert_eq!(hostile.positions().collect::<Vec<_>>(), vec![usize::MAX]);
|
||||
assert_eq!(hostile.positions().nth(1), None);
|
||||
let wide = DirectoryEntries { table: usize::MAX - 30, read: 4, declared: 4, entry_size: 12 };
|
||||
assert_eq!(wide.positions().collect::<Vec<_>>(), vec![usize::MAX - 30, usize::MAX - 18, usize::MAX - 6]);
|
||||
// a directory read from data lists its entries
|
||||
let mut data = Vec::new();
|
||||
ByteOrder::Little.put_u16(&mut data, 2);
|
||||
data.extend([0; 24]);
|
||||
let dir = directory_entries(&data, 0, ByteOrder::Little, false, 8192).unwrap();
|
||||
assert_eq!(dir.positions().collect::<Vec<_>>(), vec![2, 14]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bigtiff_directory_declaring_u64_max_entries_parses_without_overflow() {
|
||||
// 44 bytes: BigTIFF header (first IFD at 16), an entry count of u64::MAX, one 20-byte entry
|
||||
let mut data = b"II\x2b\x00\x08\x00\x00\x00".to_vec();
|
||||
data.extend(16u64.to_le_bytes());
|
||||
data.extend(u64::MAX.to_le_bytes());
|
||||
data.extend(0x0100u16.to_le_bytes());
|
||||
data.extend(3u16.to_le_bytes());
|
||||
data.extend(1u64.to_le_bytes());
|
||||
data.extend([8, 0, 0, 0, 0, 0, 0, 0]);
|
||||
assert_eq!(data.len(), 44);
|
||||
let tiff = Tiff::parse(&data).unwrap();
|
||||
assert_eq!(tiff.ifds.len(), 1);
|
||||
assert_eq!(tiff.ifds[0].u64(0x0100), Some(8));
|
||||
}
|
||||
#[test]
|
||||
fn overlapping_ifd_tables_hit_entry_cap_instead_of_amplifying() {
|
||||
// classic TIFF; IFDs at 8, 20, 32, ... each declaring 8192 entries whose tables overlap
|
||||
// (next table starts one entry after the previous table's start). Without the cap, a single
|
||||
// `Tiff::parse` would run `Vec::with_capacity(8192)` per IFD inside one `Ctx`, amplifying a
|
||||
// small file into millions of `Entry`s; the per-`Ctx` `max_entries_total` cap rejects the
|
||||
// 9th IFD before any allocation.
|
||||
let mut data = vec![0u8; 200_000];
|
||||
data[0..2].copy_from_slice(b"II");
|
||||
data[2..4].copy_from_slice(&42u16.to_le_bytes());
|
||||
data[4..8].copy_from_slice(&8u32.to_le_bytes()); // first IFD at 8
|
||||
|
||||
for k in 0..9u64 {
|
||||
let ifd_off = (8 + 12 * k) as usize;
|
||||
data[ifd_off..ifd_off + 2].copy_from_slice(&8192u16.to_le_bytes()); // count
|
||||
let table = ifd_off + 2;
|
||||
let ptr = table + 8192 * 12; // next-IFD pointer lives right after the entries
|
||||
let next = if k + 1 < 9 { (8 + 12 * (k + 1)) as u32 } else { 0 };
|
||||
data[ptr..ptr + 4].copy_from_slice(&next.to_le_bytes());
|
||||
}
|
||||
|
||||
let tiff = Tiff::parse(&data).unwrap();
|
||||
assert_eq!(tiff.ifds.len(), 8, "8 IFDs parsed, 9th rejected by max_entries_total before allocation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legitimate_multi_ifd_file_still_parses_under_the_entry_cap() {
|
||||
// classic TIFF: IFD0 @8 (3 entries: value + Exif + GPS child pointers) -> IFD1 @58 chain,
|
||||
// plus Exif child @60 and GPS child @90. Total entries = 6, far under max_entries_total.
|
||||
let mut data = vec![0u8; 128];
|
||||
data[0..2].copy_from_slice(b"II");
|
||||
data[2..4].copy_from_slice(&42u16.to_le_bytes());
|
||||
data[4..8].copy_from_slice(&8u32.to_le_bytes()); // first IFD at 8
|
||||
|
||||
// IFD0 @8: count 3, table @10, next-IFD @46 -> IFD1 @58
|
||||
data[8..10].copy_from_slice(&3u16.to_le_bytes());
|
||||
// entry0 @10: tag 0x0100, SHORT, count 1, value 8 (inline @18..22)
|
||||
data[10..12].copy_from_slice(&0x0100u16.to_le_bytes());
|
||||
data[12..14].copy_from_slice(&3u16.to_le_bytes());
|
||||
data[14..18].copy_from_slice(&1u32.to_le_bytes());
|
||||
data[18..22].copy_from_slice(&8u32.to_le_bytes());
|
||||
// entry1 @22: tag 0x8769 ExifIFD, LONG, count 1, value 60 (inline @30..34)
|
||||
data[22..24].copy_from_slice(&0x8769u16.to_le_bytes());
|
||||
data[24..26].copy_from_slice(&4u16.to_le_bytes());
|
||||
data[26..30].copy_from_slice(&1u32.to_le_bytes());
|
||||
data[30..34].copy_from_slice(&60u32.to_le_bytes());
|
||||
// entry2 @34: tag 0x8825 GPSIFD, LONG, count 1, value 90 (inline @42..46)
|
||||
data[34..36].copy_from_slice(&0x8825u16.to_le_bytes());
|
||||
data[36..38].copy_from_slice(&4u16.to_le_bytes());
|
||||
data[38..42].copy_from_slice(&1u32.to_le_bytes());
|
||||
data[42..46].copy_from_slice(&90u32.to_le_bytes());
|
||||
data[46..50].copy_from_slice(&58u32.to_le_bytes()); // next IFD
|
||||
|
||||
// IFD1 @58: count 1, table @60, next 0
|
||||
data[58..60].copy_from_slice(&1u16.to_le_bytes());
|
||||
data[60..62].copy_from_slice(&0x0100u16.to_le_bytes());
|
||||
data[62..64].copy_from_slice(&3u16.to_le_bytes());
|
||||
data[64..68].copy_from_slice(&1u32.to_le_bytes());
|
||||
data[68..72].copy_from_slice(&8u32.to_le_bytes());
|
||||
data[72..76].copy_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
// Exif child IFD @60: count 1, entry tag 0x9000 value 1, next 0
|
||||
data[60..62].copy_from_slice(&1u16.to_le_bytes());
|
||||
data[62..64].copy_from_slice(&0x9000u16.to_le_bytes());
|
||||
data[64..66].copy_from_slice(&3u16.to_le_bytes());
|
||||
data[66..70].copy_from_slice(&1u32.to_le_bytes());
|
||||
data[70..74].copy_from_slice(&1u32.to_le_bytes());
|
||||
data[74..78].copy_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
// GPS child IFD @90: count 1, entry tag 0 value 1, next 0
|
||||
data[90..92].copy_from_slice(&1u16.to_le_bytes());
|
||||
data[92..94].copy_from_slice(&0u16.to_le_bytes());
|
||||
data[94..96].copy_from_slice(&3u16.to_le_bytes());
|
||||
data[96..100].copy_from_slice(&1u32.to_le_bytes());
|
||||
data[100..104].copy_from_slice(&1u32.to_le_bytes());
|
||||
data[104..108].copy_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
let tiff = Tiff::parse(&data).unwrap();
|
||||
assert_eq!(tiff.ifds.len(), 2, "chain IFDs parse fully");
|
||||
assert_eq!(tiff.ifds[0].u64(0x0100), Some(8));
|
||||
let exif = tiff.ifds[0].exif.as_ref().expect("Exif child present");
|
||||
assert_eq!(exif.u64(0x9000), Some(1));
|
||||
let gps = tiff.ifds[0].gps.as_ref().expect("GPS child present");
|
||||
assert_eq!(gps.u64(0x0000), Some(1));
|
||||
}
|
||||
}
|
||||
@@ -1,226 +0,0 @@
|
||||
//! Tag numbers (TIFF 6.0, TIFF/EP, Exif 2.32, GPS, DNG 1.7). Public specification constants.
|
||||
|
||||
// --- TIFF baseline / extensions
|
||||
pub const NEW_SUBFILE_TYPE: u16 = 254;
|
||||
pub const SUBFILE_TYPE: u16 = 255;
|
||||
pub const IMAGE_WIDTH: u16 = 256;
|
||||
pub const IMAGE_LENGTH: u16 = 257;
|
||||
pub const BITS_PER_SAMPLE: u16 = 258;
|
||||
pub const COMPRESSION: u16 = 259;
|
||||
pub const PHOTOMETRIC: u16 = 262;
|
||||
pub const FILL_ORDER: u16 = 266;
|
||||
pub const DOCUMENT_NAME: u16 = 269;
|
||||
pub const IMAGE_DESCRIPTION: u16 = 270;
|
||||
pub const MAKE: u16 = 271;
|
||||
pub const MODEL: u16 = 272;
|
||||
pub const STRIP_OFFSETS: u16 = 273;
|
||||
pub const ORIENTATION: u16 = 274;
|
||||
pub const SAMPLES_PER_PIXEL: u16 = 277;
|
||||
pub const ROWS_PER_STRIP: u16 = 278;
|
||||
pub const STRIP_BYTE_COUNTS: u16 = 279;
|
||||
pub const X_RESOLUTION: u16 = 282;
|
||||
pub const Y_RESOLUTION: u16 = 283;
|
||||
pub const PLANAR_CONFIGURATION: u16 = 284;
|
||||
pub const RESOLUTION_UNIT: u16 = 296;
|
||||
pub const SOFTWARE: u16 = 305;
|
||||
pub const DATE_TIME: u16 = 306;
|
||||
pub const ARTIST: u16 = 315;
|
||||
pub const PREDICTOR: u16 = 317;
|
||||
pub const TILE_WIDTH: u16 = 322;
|
||||
pub const TILE_LENGTH: u16 = 323;
|
||||
pub const TILE_OFFSETS: u16 = 324;
|
||||
pub const TILE_BYTE_COUNTS: u16 = 325;
|
||||
pub const SUB_IFDS: u16 = 330;
|
||||
pub const EXTRA_SAMPLES: u16 = 338;
|
||||
pub const SAMPLE_FORMAT: u16 = 339;
|
||||
pub const JPEG_INTERCHANGE_FORMAT: u16 = 513;
|
||||
pub const JPEG_INTERCHANGE_FORMAT_LENGTH: u16 = 514;
|
||||
pub const YCBCR_SUBSAMPLING: u16 = 530;
|
||||
pub const XMP: u16 = 700;
|
||||
pub const RATING: u16 = 18246;
|
||||
pub const RATING_PERCENT: u16 = 18249;
|
||||
pub const CFA_REPEAT_PATTERN_DIM: u16 = 33421;
|
||||
pub const CFA_PATTERN_EP: u16 = 33422;
|
||||
pub const COPYRIGHT: u16 = 33432;
|
||||
pub const EXPOSURE_TIME_EP: u16 = 33434;
|
||||
pub const IPTC_NAA: u16 = 33723;
|
||||
pub const EXIF_IFD: u16 = 34665;
|
||||
pub const ICC_PROFILE: u16 = 34675;
|
||||
pub const GPS_IFD: u16 = 34853;
|
||||
pub const INTEROP_IFD: u16 = 40965;
|
||||
|
||||
// --- Exif private IFD
|
||||
pub const EXPOSURE_TIME: u16 = 33434;
|
||||
pub const F_NUMBER: u16 = 33437;
|
||||
pub const EXPOSURE_PROGRAM: u16 = 34850;
|
||||
pub const ISO_SPEED: u16 = 34855;
|
||||
pub const SENSITIVITY_TYPE: u16 = 34864;
|
||||
pub const RECOMMENDED_EXPOSURE_INDEX: u16 = 34866;
|
||||
pub const ISO_SPEED_RATINGS_EXT: u16 = 34867;
|
||||
pub const EXIF_VERSION: u16 = 36864;
|
||||
pub const DATE_TIME_ORIGINAL: u16 = 36867;
|
||||
pub const DATE_TIME_DIGITIZED: u16 = 36868;
|
||||
pub const OFFSET_TIME: u16 = 36880;
|
||||
pub const OFFSET_TIME_ORIGINAL: u16 = 36881;
|
||||
pub const OFFSET_TIME_DIGITIZED: u16 = 36882;
|
||||
pub const SHUTTER_SPEED_VALUE: u16 = 37377;
|
||||
pub const APERTURE_VALUE: u16 = 37378;
|
||||
pub const EXPOSURE_BIAS: u16 = 37380;
|
||||
pub const MAX_APERTURE: u16 = 37381;
|
||||
pub const METERING_MODE: u16 = 37383;
|
||||
pub const LIGHT_SOURCE: u16 = 37384;
|
||||
pub const FLASH: u16 = 37385;
|
||||
pub const FOCAL_LENGTH: u16 = 37386;
|
||||
pub const MAKER_NOTE: u16 = 37500;
|
||||
pub const USER_COMMENT: u16 = 37510;
|
||||
pub const SUBSEC_TIME: u16 = 37520;
|
||||
pub const SUBSEC_TIME_ORIGINAL: u16 = 37521;
|
||||
pub const SUBSEC_TIME_DIGITIZED: u16 = 37522;
|
||||
pub const PIXEL_X_DIMENSION: u16 = 40962;
|
||||
pub const PIXEL_Y_DIMENSION: u16 = 40963;
|
||||
pub const FOCAL_PLANE_X_RESOLUTION: u16 = 41486;
|
||||
pub const EXPOSURE_MODE: u16 = 41986;
|
||||
pub const WHITE_BALANCE: u16 = 41987;
|
||||
pub const FOCAL_LENGTH_35MM: u16 = 41989;
|
||||
pub const SCENE_CAPTURE_TYPE: u16 = 41990;
|
||||
pub const BODY_SERIAL_NUMBER: u16 = 42033;
|
||||
pub const LENS_SPECIFICATION: u16 = 42034;
|
||||
pub const LENS_MAKE: u16 = 42035;
|
||||
pub const LENS_MODEL: u16 = 42036;
|
||||
pub const LENS_SERIAL_NUMBER: u16 = 42037;
|
||||
|
||||
// --- GPS IFD
|
||||
pub const GPS_VERSION_ID: u16 = 0;
|
||||
pub const GPS_LATITUDE_REF: u16 = 1;
|
||||
pub const GPS_LATITUDE: u16 = 2;
|
||||
pub const GPS_LONGITUDE_REF: u16 = 3;
|
||||
pub const GPS_LONGITUDE: u16 = 4;
|
||||
pub const GPS_ALTITUDE_REF: u16 = 5;
|
||||
pub const GPS_ALTITUDE: u16 = 6;
|
||||
pub const GPS_TIME_STAMP: u16 = 7;
|
||||
pub const GPS_IMG_DIRECTION_REF: u16 = 16;
|
||||
pub const GPS_IMG_DIRECTION: u16 = 17;
|
||||
pub const GPS_DATE_STAMP: u16 = 29;
|
||||
|
||||
// --- DNG
|
||||
pub const DNG_VERSION: u16 = 50706;
|
||||
pub const DNG_BACKWARD_VERSION: u16 = 50707;
|
||||
pub const UNIQUE_CAMERA_MODEL: u16 = 50708;
|
||||
pub const LOCALIZED_CAMERA_MODEL: u16 = 50709;
|
||||
pub const CFA_PLANE_COLOR: u16 = 50710;
|
||||
pub const CFA_LAYOUT: u16 = 50711;
|
||||
pub const LINEARIZATION_TABLE: u16 = 50712;
|
||||
pub const BLACK_LEVEL_REPEAT_DIM: u16 = 50713;
|
||||
pub const BLACK_LEVEL: u16 = 50714;
|
||||
pub const BLACK_LEVEL_DELTA_H: u16 = 50715;
|
||||
pub const BLACK_LEVEL_DELTA_V: u16 = 50716;
|
||||
pub const WHITE_LEVEL: u16 = 50717;
|
||||
pub const DEFAULT_SCALE: u16 = 50718;
|
||||
pub const DEFAULT_CROP_ORIGIN: u16 = 50719;
|
||||
pub const DEFAULT_CROP_SIZE: u16 = 50720;
|
||||
pub const COLOR_MATRIX_1: u16 = 50721;
|
||||
pub const COLOR_MATRIX_2: u16 = 50722;
|
||||
pub const CAMERA_CALIBRATION_1: u16 = 50723;
|
||||
pub const CAMERA_CALIBRATION_2: u16 = 50724;
|
||||
pub const REDUCTION_MATRIX_1: u16 = 50725;
|
||||
pub const REDUCTION_MATRIX_2: u16 = 50726;
|
||||
pub const ANALOG_BALANCE: u16 = 50727;
|
||||
pub const AS_SHOT_NEUTRAL: u16 = 50728;
|
||||
pub const AS_SHOT_WHITE_XY: u16 = 50729;
|
||||
pub const BASELINE_EXPOSURE: u16 = 50730;
|
||||
pub const BASELINE_NOISE: u16 = 50731;
|
||||
pub const BASELINE_SHARPNESS: u16 = 50732;
|
||||
pub const BAYER_GREEN_SPLIT: u16 = 50733;
|
||||
pub const LINEAR_RESPONSE_LIMIT: u16 = 50734;
|
||||
pub const CAMERA_SERIAL_NUMBER: u16 = 50735;
|
||||
pub const LENS_INFO: u16 = 50736;
|
||||
pub const CHROMA_BLUR_RADIUS: u16 = 50737;
|
||||
pub const ANTI_ALIAS_STRENGTH: u16 = 50738;
|
||||
pub const SHADOW_SCALE: u16 = 50739;
|
||||
pub const DNG_PRIVATE_DATA: u16 = 50740;
|
||||
pub const MAKER_NOTE_SAFETY: u16 = 50741;
|
||||
pub const CALIBRATION_ILLUMINANT_1: u16 = 50778;
|
||||
pub const CALIBRATION_ILLUMINANT_2: u16 = 50779;
|
||||
pub const BEST_QUALITY_SCALE: u16 = 50780;
|
||||
pub const RAW_DATA_UNIQUE_ID: u16 = 50781;
|
||||
pub const ORIGINAL_RAW_FILE_NAME: u16 = 50827;
|
||||
pub const ACTIVE_AREA: u16 = 50829;
|
||||
pub const MASKED_AREAS: u16 = 50830;
|
||||
pub const AS_SHOT_ICC_PROFILE: u16 = 50831;
|
||||
pub const COLORIMETRIC_REFERENCE: u16 = 50879;
|
||||
pub const CAMERA_CALIBRATION_SIGNATURE: u16 = 50931;
|
||||
pub const PROFILE_CALIBRATION_SIGNATURE: u16 = 50932;
|
||||
pub const AS_SHOT_PROFILE_NAME: u16 = 50934;
|
||||
pub const PROFILE_NAME: u16 = 50936;
|
||||
pub const PROFILE_HUE_SAT_MAP_DIMS: u16 = 50937;
|
||||
pub const PROFILE_HUE_SAT_MAP_DATA_1: u16 = 50938;
|
||||
pub const PROFILE_HUE_SAT_MAP_DATA_2: u16 = 50939;
|
||||
pub const PROFILE_TONE_CURVE: u16 = 50940;
|
||||
pub const PROFILE_EMBED_POLICY: u16 = 50941;
|
||||
pub const PROFILE_LOOK_TABLE_DIMS: u16 = 50981;
|
||||
pub const PROFILE_LOOK_TABLE_DATA: u16 = 50982;
|
||||
pub const PROFILE_HUE_SAT_MAP_ENCODING: u16 = 51107;
|
||||
pub const PROFILE_LOOK_TABLE_ENCODING: u16 = 51108;
|
||||
pub const BASELINE_EXPOSURE_OFFSET: u16 = 51109;
|
||||
pub const DEFAULT_BLACK_RENDER: u16 = 51110;
|
||||
pub const FORWARD_MATRIX_1: u16 = 50964;
|
||||
pub const FORWARD_MATRIX_2: u16 = 50965;
|
||||
pub const PREVIEW_COLOR_SPACE: u16 = 50970;
|
||||
pub const CURRENT_PREVIEW_DATE_TIME: u16 = 50971;
|
||||
pub const OPCODE_LIST_1: u16 = 51008;
|
||||
pub const OPCODE_LIST_2: u16 = 51009;
|
||||
pub const OPCODE_LIST_3: u16 = 51022;
|
||||
pub const NOISE_PROFILE: u16 = 51041;
|
||||
pub const DEFAULT_USER_CROP: u16 = 51125;
|
||||
pub const PROFILE_GAIN_TABLE_MAP: u16 = 52525;
|
||||
/// DNG 1.7 row interleave: the stored raster holds this many interleaved row groups (each group is
|
||||
/// every `n`-th row of the image), so it must be un-interleaved before the data is a mosaic.
|
||||
pub const ROW_INTERLEAVE_FACTOR: u16 = 50975;
|
||||
/// DNG 1.7 column interleave, the column-wise counterpart of [`ROW_INTERLEAVE_FACTOR`].
|
||||
pub const COLUMN_INTERLEAVE_FACTOR: u16 = 52547;
|
||||
pub const CALIBRATION_ILLUMINANT_3: u16 = 52529;
|
||||
pub const CAMERA_CALIBRATION_3: u16 = 52530;
|
||||
pub const COLOR_MATRIX_3: u16 = 52531;
|
||||
pub const FORWARD_MATRIX_3: u16 = 52532;
|
||||
pub const ILLUMINANT_DATA_1: u16 = 52533;
|
||||
pub const ILLUMINANT_DATA_2: u16 = 52534;
|
||||
pub const ILLUMINANT_DATA_3: u16 = 52535;
|
||||
// DNG 1.6 semantic masks (spec chapter 4, "Semantic Masks")
|
||||
pub const SEMANTIC_NAME: u16 = 52526;
|
||||
pub const SEMANTIC_INSTANCE_ID: u16 = 52528;
|
||||
pub const MASK_SUB_AREA: u16 = 52536;
|
||||
/// NewSubFileType of a semantic mask IFD.
|
||||
pub const SUBFILE_SEMANTIC_MASK: u32 = 0x10004;
|
||||
pub const PROFILE_GAIN_TABLE_MAP_2: u16 = 52544;
|
||||
|
||||
// --- Compression codes (TIFF 6.0, DNG, and widely used registrations)
|
||||
pub mod compression {
|
||||
pub const NONE: u16 = 1;
|
||||
pub const LZW: u16 = 5;
|
||||
pub const OLD_JPEG: u16 = 6;
|
||||
pub const JPEG: u16 = 7;
|
||||
pub const ADOBE_DEFLATE: u16 = 8;
|
||||
pub const DEFLATE: u16 = 32946;
|
||||
pub const PACKBITS: u16 = 32773;
|
||||
/// DNG lossy JPEG (baseline DCT, 8-bit).
|
||||
pub const LOSSY_JPEG: u16 = 34892;
|
||||
pub const JPEG_XL: u16 = 52546;
|
||||
/// SMPTE ST 2073 (VC-5) as written by GoPro's GPR files (the value measured in them).
|
||||
pub const VC5: u16 = 9;
|
||||
/// Nikon NEF Huffman compression.
|
||||
pub const NIKON: u16 = 34713;
|
||||
/// Sony ARW compressed (the value used by ARW files).
|
||||
pub const SONY_ARW: u16 = 32767;
|
||||
}
|
||||
|
||||
// --- PhotometricInterpretation
|
||||
pub mod photometric {
|
||||
pub const WHITE_IS_ZERO: u16 = 0;
|
||||
pub const BLACK_IS_ZERO: u16 = 1;
|
||||
pub const RGB: u16 = 2;
|
||||
pub const YCBCR: u16 = 6;
|
||||
pub const CFA: u16 = 32803;
|
||||
pub const LINEAR_RAW: u16 = 34892;
|
||||
/// DNG 1.6 semantic mask.
|
||||
pub const MASK: u16 = 52527;
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
//! TIFF writer: IFD trees with strips / tiles, `SubIFDs` and pointer IFDs (Exif, GPS, Interop, …).
|
||||
//!
|
||||
//! Layout: header, then for each IFD of the main chain its image chunks, child IFDs, out-of-line values
|
||||
//! and finally the IFD itself (all word-aligned). Children are written before their parent so every
|
||||
//! pointer is known when the parent's entries are emitted; only the chain's next-IFD pointers are patched.
|
||||
|
||||
use crate::{ByteOrder, Result, TiffError, Value, tags};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Pixel data attached to an IFD. The writer fills in the offset / byte-count tags.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ImageData {
|
||||
/// Strips (each already compressed as the IFD's `Compression` says). Sets `RowsPerStrip`.
|
||||
Strips { rows_per_strip: u32, strips: Vec<Vec<u8>> },
|
||||
/// Tiles in row-major tile order. Sets `TileWidth` / `TileLength`.
|
||||
Tiles { tile_width: u32, tile_height: u32, tiles: Vec<Vec<u8>> },
|
||||
}
|
||||
|
||||
/// An IFD to be written.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct IfdBuilder {
|
||||
pub entries: BTreeMap<u16, Value>,
|
||||
/// Written and referenced through the `SubIFDs` (330) tag.
|
||||
pub sub_ifds: Vec<IfdBuilder>,
|
||||
/// Pointer IFDs keyed by the pointer tag (e.g. [`tags::EXIF_IFD`], [`tags::GPS_IFD`], [`tags::INTEROP_IFD`]).
|
||||
pub children: BTreeMap<u16, IfdBuilder>,
|
||||
pub image: Option<ImageData>,
|
||||
}
|
||||
|
||||
impl IfdBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
pub fn set(&mut self, tag: u16, value: Value) -> &mut Self {
|
||||
self.entries.insert(tag, value);
|
||||
self
|
||||
}
|
||||
/// Builder-style [`IfdBuilder::set`].
|
||||
pub fn with(mut self, tag: u16, value: Value) -> Self {
|
||||
self.entries.insert(tag, value);
|
||||
self
|
||||
}
|
||||
pub fn set_child(&mut self, tag: u16, child: IfdBuilder) -> &mut Self {
|
||||
self.children.insert(tag, child);
|
||||
self
|
||||
}
|
||||
pub fn add_sub_ifd(&mut self, sub: IfdBuilder) -> &mut Self {
|
||||
self.sub_ifds.push(sub);
|
||||
self
|
||||
}
|
||||
pub fn set_image(&mut self, image: ImageData) -> &mut Self {
|
||||
self.image = Some(image);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialises IFD chains.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TiffWriter {
|
||||
pub order: ByteOrder,
|
||||
pub bigtiff: bool,
|
||||
}
|
||||
|
||||
impl TiffWriter {
|
||||
pub fn new(order: ByteOrder, bigtiff: bool) -> Self {
|
||||
Self { order, bigtiff }
|
||||
}
|
||||
|
||||
/// Write `chain` (IFD0, IFD1, …) as a complete TIFF stream.
|
||||
pub fn write(&self, chain: &[IfdBuilder]) -> Result<Vec<u8>> {
|
||||
if chain.is_empty() {
|
||||
return Err(TiffError::Invalid("no IFDs to write".into()));
|
||||
}
|
||||
let o = self.order;
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(match o {
|
||||
ByteOrder::Little => b"II",
|
||||
ByteOrder::Big => b"MM",
|
||||
});
|
||||
let mut patch = if self.bigtiff {
|
||||
o.put_u16(&mut buf, 43);
|
||||
o.put_u16(&mut buf, 8);
|
||||
o.put_u16(&mut buf, 0);
|
||||
let p = buf.len();
|
||||
o.put_u64(&mut buf, 0);
|
||||
p
|
||||
} else {
|
||||
o.put_u16(&mut buf, 42);
|
||||
let p = buf.len();
|
||||
o.put_u32(&mut buf, 0);
|
||||
p
|
||||
};
|
||||
for ifd in chain {
|
||||
let (off, next_pos) = self.write_ifd(&mut buf, ifd, 0)?;
|
||||
self.patch_offset(&mut buf, patch, off)?;
|
||||
patch = next_pos;
|
||||
}
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
fn patch_offset(&self, buf: &mut [u8], pos: usize, v: u64) -> Result<()> {
|
||||
let mut tmp = Vec::with_capacity(8);
|
||||
if self.bigtiff {
|
||||
self.order.put_u64(&mut tmp, v);
|
||||
} else {
|
||||
self.order.put_u32(&mut tmp, u32::try_from(v).map_err(|_| TiffError::Limit("classic TIFF larger than 4 GiB"))?);
|
||||
}
|
||||
buf[pos..pos + tmp.len()].copy_from_slice(&tmp);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn offset_value(&self, v: Vec<u64>) -> Result<Value> {
|
||||
if self.bigtiff {
|
||||
Ok(Value::Long8(v))
|
||||
} else {
|
||||
Ok(Value::Long(
|
||||
v.into_iter().map(|x| u32::try_from(x).map_err(|_| TiffError::Limit("classic TIFF larger than 4 GiB"))).collect::<Result<_>>()?,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the IFD (and everything it references); returns (IFD offset, position of its next-IFD pointer).
|
||||
fn write_ifd(&self, buf: &mut Vec<u8>, ifd: &IfdBuilder, depth: usize) -> Result<(u64, usize)> {
|
||||
if depth > 16 {
|
||||
return Err(TiffError::Limit("IFD nesting depth"));
|
||||
}
|
||||
let o = self.order;
|
||||
let mut entries = ifd.entries.clone();
|
||||
if let Some(img) = &ifd.image {
|
||||
let chunks = match img {
|
||||
ImageData::Strips { rows_per_strip, strips } => {
|
||||
entries.insert(tags::ROWS_PER_STRIP, Value::Long(vec![*rows_per_strip]));
|
||||
strips
|
||||
}
|
||||
ImageData::Tiles { tile_width, tile_height, tiles } => {
|
||||
entries.insert(tags::TILE_WIDTH, Value::Long(vec![*tile_width]));
|
||||
entries.insert(tags::TILE_LENGTH, Value::Long(vec![*tile_height]));
|
||||
tiles
|
||||
}
|
||||
};
|
||||
let mut offs = Vec::with_capacity(chunks.len());
|
||||
let mut counts = Vec::with_capacity(chunks.len());
|
||||
for c in chunks {
|
||||
align(buf);
|
||||
offs.push(buf.len() as u64);
|
||||
counts.push(c.len() as u64);
|
||||
buf.extend_from_slice(c);
|
||||
}
|
||||
let (ot, ct) = match img {
|
||||
ImageData::Strips { .. } => (tags::STRIP_OFFSETS, tags::STRIP_BYTE_COUNTS),
|
||||
ImageData::Tiles { .. } => (tags::TILE_OFFSETS, tags::TILE_BYTE_COUNTS),
|
||||
};
|
||||
entries.insert(ot, self.offset_value(offs)?);
|
||||
entries.insert(ct, self.offset_value(counts)?);
|
||||
}
|
||||
if !ifd.sub_ifds.is_empty() {
|
||||
let mut offs = Vec::new();
|
||||
for s in &ifd.sub_ifds {
|
||||
offs.push(self.write_ifd(buf, s, depth + 1)?.0);
|
||||
}
|
||||
entries.insert(tags::SUB_IFDS, self.offset_value(offs)?);
|
||||
}
|
||||
for (&tag, child) in &ifd.children {
|
||||
let off = self.write_ifd(buf, child, depth + 1)?.0;
|
||||
entries.insert(tag, self.offset_value(vec![off])?);
|
||||
}
|
||||
let inline = if self.bigtiff { 8 } else { 4 };
|
||||
// out-of-line values
|
||||
let mut encoded: Vec<(u16, &Value, Vec<u8>, Option<u64>)> = Vec::with_capacity(entries.len());
|
||||
for (&tag, v) in &entries {
|
||||
let bytes = encode(o, v);
|
||||
let pos = if bytes.len() > inline {
|
||||
align(buf);
|
||||
let p = buf.len() as u64;
|
||||
buf.extend_from_slice(&bytes);
|
||||
Some(p)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
encoded.push((tag, v, bytes, pos));
|
||||
}
|
||||
align(buf);
|
||||
let ifd_off = buf.len() as u64;
|
||||
if !self.bigtiff && ifd_off > u32::MAX as u64 {
|
||||
return Err(TiffError::Limit("classic TIFF larger than 4 GiB"));
|
||||
}
|
||||
if self.bigtiff {
|
||||
o.put_u64(buf, encoded.len() as u64);
|
||||
} else {
|
||||
o.put_u16(buf, u16::try_from(encoded.len()).map_err(|_| TiffError::Limit("more than 65535 entries"))?);
|
||||
}
|
||||
for (tag, v, bytes, pos) in &encoded {
|
||||
o.put_u16(buf, *tag);
|
||||
o.put_u16(buf, v.field_type() as u16);
|
||||
if self.bigtiff {
|
||||
o.put_u64(buf, v.count() as u64);
|
||||
} else {
|
||||
o.put_u32(buf, u32::try_from(v.count()).map_err(|_| TiffError::Limit("value count"))?);
|
||||
}
|
||||
match pos {
|
||||
Some(p) => {
|
||||
if self.bigtiff {
|
||||
o.put_u64(buf, *p);
|
||||
} else {
|
||||
o.put_u32(buf, u32::try_from(*p).map_err(|_| TiffError::Limit("classic TIFF larger than 4 GiB"))?);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
buf.extend_from_slice(bytes);
|
||||
buf.extend(std::iter::repeat_n(0u8, inline - bytes.len()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let next_pos = buf.len();
|
||||
if self.bigtiff {
|
||||
o.put_u64(buf, 0);
|
||||
} else {
|
||||
o.put_u32(buf, 0);
|
||||
}
|
||||
Ok((ifd_off, next_pos))
|
||||
}
|
||||
}
|
||||
|
||||
fn align(buf: &mut Vec<u8>) {
|
||||
if buf.len() % 2 == 1 {
|
||||
buf.push(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialise a value's bytes in `o` order.
|
||||
pub fn encode(o: ByteOrder, v: &Value) -> Vec<u8> {
|
||||
let mut b = Vec::new();
|
||||
match v {
|
||||
Value::Byte(x) | Value::Undefined(x) => b.extend_from_slice(x),
|
||||
Value::Ascii(s) => {
|
||||
b.extend_from_slice(s.as_bytes());
|
||||
b.push(0);
|
||||
}
|
||||
Value::SByte(x) => b.extend(x.iter().map(|&c| c as u8)),
|
||||
Value::Short(x) => x.iter().for_each(|&c| o.put_u16(&mut b, c)),
|
||||
Value::SShort(x) => x.iter().for_each(|&c| o.put_u16(&mut b, c as u16)),
|
||||
Value::Long(x) | Value::Ifd(x) => x.iter().for_each(|&c| o.put_u32(&mut b, c)),
|
||||
Value::SLong(x) => x.iter().for_each(|&c| o.put_u32(&mut b, c as u32)),
|
||||
Value::Float(x) => x.iter().for_each(|&c| o.put_u32(&mut b, c.to_bits())),
|
||||
Value::Rational(x) => x.iter().for_each(|&(n, d)| {
|
||||
o.put_u32(&mut b, n);
|
||||
o.put_u32(&mut b, d);
|
||||
}),
|
||||
Value::SRational(x) => x.iter().for_each(|&(n, d)| {
|
||||
o.put_u32(&mut b, n as u32);
|
||||
o.put_u32(&mut b, d as u32);
|
||||
}),
|
||||
Value::Double(x) => x.iter().for_each(|&c| o.put_u64(&mut b, c.to_bits())),
|
||||
Value::Long8(x) | Value::Ifd8(x) => x.iter().for_each(|&c| o.put_u64(&mut b, c)),
|
||||
Value::SLong8(x) => x.iter().for_each(|&c| o.put_u64(&mut b, c as u64)),
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Convenience: approximate `v` by an unsigned rational with denominator up to 1e6 (for writing Exif rationals).
|
||||
pub fn rational(v: f64) -> (u32, u32) {
|
||||
if !v.is_finite() || v <= 0.0 {
|
||||
return (0, 1);
|
||||
}
|
||||
for d in [1u32, 10, 100, 1000, 10_000, 100_000, 1_000_000] {
|
||||
let n = v * d as f64;
|
||||
if n > u32::MAX as f64 {
|
||||
return ((v * (d / 10).max(1) as f64).round().min(u32::MAX as f64) as u32, (d / 10).max(1));
|
||||
}
|
||||
if (n - n.round()).abs() < 1e-9 * d as f64 || d == 1_000_000 {
|
||||
return (n.round() as u32, d);
|
||||
}
|
||||
}
|
||||
(0, 1)
|
||||
}
|
||||
|
||||
/// Signed variant of [`rational`].
|
||||
pub fn srational(v: f64) -> (i32, i32) {
|
||||
if !v.is_finite() {
|
||||
return (0, 1);
|
||||
}
|
||||
for d in [1i32, 10, 100, 1000, 10_000, 100_000, 1_000_000] {
|
||||
let n = v * d as f64;
|
||||
if n.abs() > i32::MAX as f64 {
|
||||
let d = (d / 10).max(1);
|
||||
return ((v * d as f64).round().clamp(i32::MIN as f64, i32::MAX as f64) as i32, d);
|
||||
}
|
||||
if (n - n.round()).abs() < 1e-9 * d as f64 || d == 1_000_000 {
|
||||
return (n.round() as i32, d);
|
||||
}
|
||||
}
|
||||
(0, 1)
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
//! The integration tests, one module per file, linked into one test binary.
|
||||
|
||||
mod roundtrip;
|
||||
@@ -1,429 +0,0 @@
|
||||
use lightcraft_tiff::image::{Layout, chunk_bytes};
|
||||
use lightcraft_tiff::writer::{rational, srational};
|
||||
use lightcraft_tiff::{ByteOrder, FieldType, IfdBuilder, ImageData, ParseOptions, Tiff, TiffError, TiffWriter, Value, parse_ifd_at, tags};
|
||||
use proptest::prelude::*;
|
||||
|
||||
const ORDERS: [ByteOrder; 2] = [ByteOrder::Little, ByteOrder::Big];
|
||||
|
||||
fn all_values() -> Vec<(u16, Value)> {
|
||||
vec![
|
||||
(1000, Value::Byte(vec![1, 2, 3, 255])),
|
||||
(1001, Value::Ascii("hello tiff".into())),
|
||||
(1002, Value::Short(vec![1, 65535, 3])),
|
||||
(1003, Value::Long(vec![7])),
|
||||
(1004, Value::Rational(vec![(1, 3), (22, 7)])),
|
||||
(1005, Value::SByte(vec![-1, 0, 127, -128])),
|
||||
(1006, Value::Undefined(vec![9; 17])),
|
||||
(1007, Value::SShort(vec![-32768, 32767])),
|
||||
(1008, Value::SLong(vec![-5, i32::MAX])),
|
||||
(1009, Value::SRational(vec![(-1, 3), (5, -2)])),
|
||||
(1010, Value::Float(vec![1.5, -0.25, f32::MAX])),
|
||||
(1011, Value::Double(vec![std::f64::consts::PI])),
|
||||
(1012, Value::Ifd(vec![0])),
|
||||
(1013, Value::Short(vec![42])),
|
||||
(1014, Value::Ascii(String::new())),
|
||||
]
|
||||
}
|
||||
|
||||
fn big_values() -> Vec<(u16, Value)> {
|
||||
vec![(1020, Value::Long8(vec![1 << 40, 3])), (1021, Value::SLong8(vec![-(1 << 50)])), (1022, Value::Ifd8(vec![0]))]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_field_types_roundtrip_every_variant() {
|
||||
for order in ORDERS {
|
||||
for big in [false, true] {
|
||||
let mut ifd = IfdBuilder::new();
|
||||
for (t, v) in all_values() {
|
||||
ifd.set(t, v);
|
||||
}
|
||||
if big {
|
||||
for (t, v) in big_values() {
|
||||
ifd.set(t, v);
|
||||
}
|
||||
}
|
||||
let bytes = TiffWriter::new(order, big).write(&[ifd]).unwrap();
|
||||
let t = Tiff::parse(&bytes).unwrap();
|
||||
assert_eq!(t.order, order);
|
||||
assert_eq!(t.bigtiff, big);
|
||||
assert_eq!(Tiff::sniff(&bytes), Some((order, big)));
|
||||
let ifd0 = &t.ifds[0];
|
||||
for (tag, v) in all_values().into_iter().chain(if big { big_values() } else { vec![] }) {
|
||||
assert_eq!(ifd0.value(tag), Some(&v), "tag {tag} order {order:?} big {big}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accessors() {
|
||||
let mut ifd = IfdBuilder::new();
|
||||
ifd.set(1, Value::Rational(vec![(28, 10), (0, 0)]));
|
||||
ifd.set(2, Value::Short(vec![5, 6]));
|
||||
ifd.set(3, Value::SLong(vec![-3]));
|
||||
ifd.set(4, Value::Ascii("Canon ".into()));
|
||||
ifd.set(5, Value::Byte(b"<x:xmpmeta/>\0junk".to_vec()));
|
||||
let bytes = TiffWriter::default().write(&[ifd]).unwrap();
|
||||
let t = Tiff::parse(&bytes).unwrap();
|
||||
let i = &t.ifds[0];
|
||||
assert_eq!(i.f64(1), Some(2.8));
|
||||
assert_eq!(i.f64s(1).unwrap(), vec![2.8, 0.0]);
|
||||
assert_eq!(i.u32(2), Some(5));
|
||||
assert_eq!(i.u64s(2).unwrap(), vec![5, 6]);
|
||||
assert_eq!(i.u32(3), None);
|
||||
assert_eq!(i.i64(3), Some(-3));
|
||||
assert_eq!(i.string(4).as_deref(), Some("Canon"));
|
||||
assert_eq!(i.string(5).as_deref(), Some("<x:xmpmeta/>"));
|
||||
assert_eq!(i.get(4).unwrap().field_type(), FieldType::Ascii);
|
||||
assert!(i.u32(999).is_none());
|
||||
assert_eq!(t.find(2).map(|e| e.tag), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chain_subifds_and_pointer_ifds() {
|
||||
for order in ORDERS {
|
||||
for big in [false, true] {
|
||||
let mut interop = IfdBuilder::new();
|
||||
interop.set(1, Value::Ascii("R98".into()));
|
||||
let mut exif = IfdBuilder::new();
|
||||
exif.set(tags::F_NUMBER, Value::Rational(vec![(56, 10)]));
|
||||
exif.set_child(tags::INTEROP_IFD, interop);
|
||||
let mut gps = IfdBuilder::new();
|
||||
gps.set(tags::GPS_LATITUDE_REF, Value::Ascii("N".into()));
|
||||
let mut ifd0 = IfdBuilder::new();
|
||||
ifd0.set(tags::MAKE, Value::Ascii("Maker".into()));
|
||||
ifd0.set_child(tags::EXIF_IFD, exif);
|
||||
ifd0.set_child(tags::GPS_IFD, gps);
|
||||
let mut raw = IfdBuilder::new();
|
||||
raw.set(tags::IMAGE_WIDTH, Value::Long(vec![4]));
|
||||
let mut nested = IfdBuilder::new();
|
||||
nested.set(tags::IMAGE_WIDTH, Value::Long(vec![2]));
|
||||
raw.add_sub_ifd(nested);
|
||||
ifd0.add_sub_ifd(raw);
|
||||
ifd0.add_sub_ifd(IfdBuilder::new().with(tags::IMAGE_WIDTH, Value::Short(vec![3])));
|
||||
let ifd1 = IfdBuilder::new().with(tags::IMAGE_WIDTH, Value::Short(vec![160]));
|
||||
let ifd2 = IfdBuilder::new().with(tags::IMAGE_WIDTH, Value::Short(vec![80]));
|
||||
let bytes = TiffWriter::new(order, big).write(&[ifd0, ifd1, ifd2]).unwrap();
|
||||
let t = Tiff::parse(&bytes).unwrap();
|
||||
assert_eq!(t.ifds.len(), 3);
|
||||
assert_eq!(t.ifds[1].u32(tags::IMAGE_WIDTH), Some(160));
|
||||
assert_eq!(t.ifds[2].u32(tags::IMAGE_WIDTH), Some(80));
|
||||
let i0 = &t.ifds[0];
|
||||
assert_eq!(i0.sub_ifds.len(), 2);
|
||||
assert_eq!(i0.sub_ifds[0].u32(tags::IMAGE_WIDTH), Some(4));
|
||||
assert_eq!(i0.sub_ifds[0].sub_ifds[0].u32(tags::IMAGE_WIDTH), Some(2));
|
||||
assert_eq!(i0.sub_ifds[1].u32(tags::IMAGE_WIDTH), Some(3));
|
||||
let exif = t.exif().unwrap();
|
||||
assert_eq!(exif.f64(tags::F_NUMBER), Some(5.6));
|
||||
assert_eq!(exif.interop.as_ref().unwrap().string(1).as_deref(), Some("R98"));
|
||||
assert_eq!(t.gps().unwrap().string(tags::GPS_LATITUDE_REF).as_deref(), Some("N"));
|
||||
// IFD0, sub0, sub0.sub, sub1, exif, interop, gps, ifd1, ifd2
|
||||
assert_eq!(t.all_ifds().len(), 9);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gradient(w: usize, h: usize) -> Vec<u8> {
|
||||
(0..w * h).map(|i| (i * 7 % 251) as u8).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_layout_and_bytes() {
|
||||
let (w, h) = (10usize, 7usize);
|
||||
let px = gradient(w, h);
|
||||
let rps = 3;
|
||||
let strips: Vec<Vec<u8>> = px.chunks(w * rps).map(|c| c.to_vec()).collect();
|
||||
let mut ifd = IfdBuilder::new();
|
||||
ifd.set(tags::IMAGE_WIDTH, Value::Long(vec![w as u32]));
|
||||
ifd.set(tags::IMAGE_LENGTH, Value::Long(vec![h as u32]));
|
||||
ifd.set(tags::BITS_PER_SAMPLE, Value::Short(vec![8]));
|
||||
ifd.set(tags::COMPRESSION, Value::Short(vec![1]));
|
||||
ifd.set_image(ImageData::Strips { rows_per_strip: rps as u32, strips });
|
||||
for order in ORDERS {
|
||||
for big in [false, true] {
|
||||
let bytes = TiffWriter::new(order, big).write(std::slice::from_ref(&ifd)).unwrap();
|
||||
let t = Tiff::parse(&bytes).unwrap();
|
||||
let info = t.ifds[0].image().unwrap();
|
||||
assert_eq!(info.layout, Layout::Strips { rows_per_strip: 3 });
|
||||
assert_eq!(info.grid(), (1, 3));
|
||||
let chunks = info.chunks(bytes.len() as u64);
|
||||
assert_eq!(chunks.len(), 3);
|
||||
assert_eq!(chunks[2].height, 1);
|
||||
let mut out = Vec::new();
|
||||
for c in &chunks {
|
||||
out.extend_from_slice(chunk_bytes(&bytes, c).unwrap());
|
||||
}
|
||||
assert_eq!(out, px);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_layout_and_bytes() {
|
||||
let (w, h, tw, th) = (20usize, 13usize, 16usize, 8usize);
|
||||
let px = gradient(w, h);
|
||||
let (ta, td) = (w.div_ceil(tw), h.div_ceil(th));
|
||||
let mut tiles = Vec::new();
|
||||
for ty in 0..td {
|
||||
for tx in 0..ta {
|
||||
let mut t = vec![0u8; tw * th];
|
||||
for y in 0..th {
|
||||
for x in 0..tw {
|
||||
let (sx, sy) = (tx * tw + x, ty * th + y);
|
||||
if sx < w && sy < h {
|
||||
t[y * tw + x] = px[sy * w + sx];
|
||||
}
|
||||
}
|
||||
}
|
||||
tiles.push(t);
|
||||
}
|
||||
}
|
||||
let mut ifd = IfdBuilder::new();
|
||||
ifd.set(tags::IMAGE_WIDTH, Value::Short(vec![w as u16]));
|
||||
ifd.set(tags::IMAGE_LENGTH, Value::Short(vec![h as u16]));
|
||||
ifd.set_image(ImageData::Tiles { tile_width: tw as u32, tile_height: th as u32, tiles });
|
||||
let bytes = TiffWriter::new(ByteOrder::Big, false).write(&[ifd]).unwrap();
|
||||
let t = Tiff::parse(&bytes).unwrap();
|
||||
let info = t.ifds[0].image().unwrap();
|
||||
assert_eq!(info.grid(), (2, 2));
|
||||
let chunks = info.chunks(bytes.len() as u64);
|
||||
assert_eq!(chunks.len(), 4);
|
||||
let mut out = vec![0u8; w * h];
|
||||
for c in &chunks {
|
||||
let b = chunk_bytes(&bytes, c).unwrap();
|
||||
for y in 0..c.height as usize {
|
||||
for x in 0..c.width as usize {
|
||||
let (sx, sy) = (c.x as usize + x, c.y as usize + y);
|
||||
if sx < w && sy < h {
|
||||
out[sy * w + sx] = b[y * tw + x];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(out, px);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_byte_counts_are_inferred() {
|
||||
let mut ifd = IfdBuilder::new();
|
||||
ifd.set(tags::IMAGE_WIDTH, Value::Long(vec![4]));
|
||||
ifd.set(tags::IMAGE_LENGTH, Value::Long(vec![2]));
|
||||
ifd.set_image(ImageData::Strips { rows_per_strip: 1, strips: vec![vec![1; 4], vec![2; 4]] });
|
||||
let bytes = TiffWriter::default().write(&[ifd]).unwrap();
|
||||
let t = Tiff::parse(&bytes).unwrap();
|
||||
let mut info = t.ifds[0].image().unwrap();
|
||||
info.byte_counts.clear();
|
||||
let c = info.chunks(bytes.len() as u64);
|
||||
assert_eq!(c[0].len, 4);
|
||||
assert_eq!(&chunk_bytes(&bytes, &c[0]).unwrap()[..4], &[1; 4]);
|
||||
assert!(c[1].len >= 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_headers() {
|
||||
assert_eq!(Tiff::parse(b""), Err(TiffError::NotTiff));
|
||||
assert_eq!(Tiff::parse(b"XX*\0\0\0\0\0"), Err(TiffError::NotTiff));
|
||||
assert_eq!(Tiff::parse(b"II\x2b\0\x04\0\0\0"), Err(TiffError::NotTiff));
|
||||
assert!(Tiff::parse(b"II*\0").is_err());
|
||||
assert!(Tiff::parse(b"II*\0\x08\0\0\0").is_err());
|
||||
assert!(Tiff::parse(b"II*\0\x08\0\0\0\0\0").is_err());
|
||||
assert!(Tiff::sniff(b"MM\0*\0\0\0\x08").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ifd_loops_are_detected() {
|
||||
// IFD0 at 8 whose next pointer points back to itself, and whose SubIFDs point to itself too.
|
||||
let mut b = b"II*\0\x08\0\0\0".to_vec();
|
||||
b.extend_from_slice(&1u16.to_le_bytes());
|
||||
b.extend_from_slice(&330u16.to_le_bytes());
|
||||
b.extend_from_slice(&4u16.to_le_bytes());
|
||||
b.extend_from_slice(&1u32.to_le_bytes());
|
||||
b.extend_from_slice(&8u32.to_le_bytes());
|
||||
b.extend_from_slice(&8u32.to_le_bytes());
|
||||
let t = Tiff::parse(&b).unwrap();
|
||||
assert_eq!(t.ifds.len(), 1);
|
||||
assert!(t.ifds[0].sub_ifds.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_range_entries_are_skipped() {
|
||||
let mut ifd = IfdBuilder::new();
|
||||
ifd.set(1, Value::Long(vec![1, 2, 3]));
|
||||
ifd.set(2, Value::Short(vec![5]));
|
||||
let mut bytes = TiffWriter::default().write(&[ifd]).unwrap();
|
||||
let t = Tiff::parse(&bytes).unwrap();
|
||||
let e = t.ifds[0].get(1).unwrap().clone();
|
||||
// point tag 1's value offset past EOF
|
||||
let ifd_off = t.ifds[0].offset as usize;
|
||||
let field = ifd_off + 2 + 8;
|
||||
assert_eq!(u32::from_le_bytes(bytes[field..field + 4].try_into().unwrap()) as u64, e.offset);
|
||||
bytes[field..field + 4].copy_from_slice(&0xffff_fff0u32.to_le_bytes());
|
||||
let t = Tiff::parse(&bytes).unwrap();
|
||||
assert!(t.ifds[0].get(1).is_none());
|
||||
assert_eq!(t.ifds[0].u32(2), Some(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_budget_limits_allocation() {
|
||||
// 50 entries all pointing at the same 1000-byte blob.
|
||||
let mut ifd = IfdBuilder::new();
|
||||
ifd.set(1, Value::Undefined(vec![7; 1000]));
|
||||
let bytes = TiffWriter::default().write(&[ifd]).unwrap();
|
||||
let t = Tiff::parse(&bytes).unwrap();
|
||||
let blob = t.ifds[0].get(1).unwrap().offset as u32;
|
||||
let mut b = b"II*\0".to_vec();
|
||||
b.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
|
||||
let mut file = bytes.clone();
|
||||
file[..8].copy_from_slice(&b);
|
||||
file.extend_from_slice(&50u16.to_le_bytes());
|
||||
for i in 0..50u16 {
|
||||
file.extend_from_slice(&i.to_le_bytes());
|
||||
file.extend_from_slice(&7u16.to_le_bytes());
|
||||
file.extend_from_slice(&1000u32.to_le_bytes());
|
||||
file.extend_from_slice(&blob.to_le_bytes());
|
||||
}
|
||||
file.extend_from_slice(&0u32.to_le_bytes());
|
||||
let opts = ParseOptions { value_budget: Some(10_000), ..Default::default() };
|
||||
let t = Tiff::parse_with(&file, &opts).unwrap();
|
||||
assert_eq!(t.ifds[0].entries.len(), 10);
|
||||
let t = Tiff::parse(&file).unwrap();
|
||||
assert_eq!(t.ifds[0].entries.len(), 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_ifd_with_base() {
|
||||
// an IFD blob embedded at 100 whose offsets are relative to 100
|
||||
let mut blob = Vec::new();
|
||||
let o = ByteOrder::Big;
|
||||
o.put_u16(&mut blob, 1);
|
||||
o.put_u16(&mut blob, 5);
|
||||
o.put_u16(&mut blob, 4);
|
||||
o.put_u32(&mut blob, 3);
|
||||
o.put_u32(&mut blob, 18);
|
||||
o.put_u32(&mut blob, 0);
|
||||
for v in [10u32, 20, 30] {
|
||||
o.put_u32(&mut blob, v);
|
||||
}
|
||||
let mut data = vec![0u8; 100];
|
||||
data.extend(blob);
|
||||
let (ifd, next) = parse_ifd_at(&data, 100, o, 100, false, &ParseOptions::default()).unwrap();
|
||||
assert_eq!(next, 0);
|
||||
assert_eq!(ifd.u64s(5).unwrap(), vec![10, 20, 30]);
|
||||
assert_eq!(ifd.get(5).unwrap().offset, 118);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rationals() {
|
||||
assert_eq!(rational(2.8), (28, 10));
|
||||
assert_eq!(rational(0.004), (4, 1000));
|
||||
assert_eq!(rational(-1.0), (0, 1));
|
||||
assert_eq!(srational(-0.333), (-333, 1000));
|
||||
assert_eq!(srational(7.0), (7, 1));
|
||||
let (n, d) = rational(1.0 / 3.0);
|
||||
assert!((n as f64 / d as f64 - 1.0 / 3.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
fn sample_file() -> Vec<u8> {
|
||||
let mut exif = IfdBuilder::new();
|
||||
exif.set(tags::F_NUMBER, Value::Rational(vec![(4, 1)]));
|
||||
exif.set(tags::MAKER_NOTE, Value::Undefined(b"Nikon\0\x02\x10\0\0II*\0\x08\0\0\0\x01\0\x01\0\x03\0\x01\0\0\0\x05\0\0\0\0\0\0\0".to_vec()));
|
||||
let mut ifd0 = IfdBuilder::new();
|
||||
ifd0.set(tags::IMAGE_WIDTH, Value::Long(vec![8]));
|
||||
ifd0.set(tags::IMAGE_LENGTH, Value::Long(vec![4]));
|
||||
ifd0.set(tags::MAKE, Value::Ascii("NIKON".into()));
|
||||
ifd0.set_child(tags::EXIF_IFD, exif);
|
||||
ifd0.set_image(ImageData::Strips { rows_per_strip: 2, strips: vec![vec![1; 16], vec![2; 16]] });
|
||||
ifd0.add_sub_ifd(IfdBuilder::new().with(tags::IMAGE_WIDTH, Value::Long(vec![2])));
|
||||
TiffWriter::default().write(&[ifd0, IfdBuilder::new().with(1, Value::Short(vec![1]))]).unwrap()
|
||||
}
|
||||
|
||||
fn exercise(t: &Tiff, data: &[u8]) {
|
||||
for ifd in t.all_ifds() {
|
||||
if let Ok(info) = ifd.image() {
|
||||
for c in info.chunks(data.len() as u64).iter().take(64) {
|
||||
let _ = chunk_bytes(data, c);
|
||||
}
|
||||
}
|
||||
for e in &ifd.entries {
|
||||
let _ = e.value.to_f64_vec();
|
||||
let _ = e.value.as_str();
|
||||
}
|
||||
}
|
||||
if let Some(e) = t.exif().and_then(|x| x.get(tags::MAKER_NOTE)) {
|
||||
let _ = lightcraft_tiff::makernote::parse_makernote(data, e.offset, e.count() as u64, t.order, "NIKON");
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 2000, .. ProptestConfig::default() })]
|
||||
|
||||
#[test]
|
||||
fn random_bytes_never_panic(mut data in proptest::collection::vec(any::<u8>(), 0..512), hdr in 0usize..4) {
|
||||
let heads: [&[u8]; 4] = [b"II*\0", b"MM\0*", b"II+\0\x08\0\0\0", b"MM\0+\0\x08\0\0"];
|
||||
let h = heads[hdr];
|
||||
if data.len() >= h.len() {
|
||||
data[..h.len()].copy_from_slice(h);
|
||||
}
|
||||
if let Ok(t) = Tiff::parse(&data) {
|
||||
exercise(&t, &data);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mutated_files_never_panic(flips in proptest::collection::vec((any::<usize>(), any::<u8>()), 1..16), cut in any::<usize>()) {
|
||||
let mut data = sample_file();
|
||||
for (i, v) in flips {
|
||||
let n = data.len();
|
||||
data[i % n] = v;
|
||||
}
|
||||
let keep = if cut % 4 == 0 { cut % data.len() } else { data.len() };
|
||||
let data = &data[..keep];
|
||||
if let Ok(t) = Tiff::parse(data) {
|
||||
exercise(&t, data);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_short_arrays_roundtrip(v in proptest::collection::vec(any::<u16>(), 1..300), big in any::<bool>(), le in any::<bool>()) {
|
||||
let order = if le { ByteOrder::Little } else { ByteOrder::Big };
|
||||
let ifd = IfdBuilder::new().with(500, Value::Short(v.clone())).with(501, Value::Double(v.iter().map(|&x| x as f64 / 3.0).collect()));
|
||||
let bytes = TiffWriter::new(order, big).write(&[ifd]).unwrap();
|
||||
let t = Tiff::parse(&bytes).unwrap();
|
||||
prop_assert_eq!(t.ifds[0].value(500), Some(&Value::Short(v.clone())));
|
||||
prop_assert_eq!(t.ifds[0].f64s(501).unwrap().len(), v.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// A BigTIFF whose IFD says it has an enormous number of entries, with one readable, computed where the next-IFD
|
||||
/// offset would be from the advertised count: an add overflow, a panic in builds with overflow checks (issue
|
||||
/// #1516). The readable entry is kept and there is no next IFD; complete chains still link.
|
||||
#[test]
|
||||
fn bigtiff_with_an_enormous_entry_count_does_not_panic() {
|
||||
for order in ORDERS {
|
||||
for count in [u64::MAX, 1 << 62, 2] {
|
||||
// little-endian bytes, reversed for big-endian files
|
||||
let e = |le: &[u8]| -> Vec<u8> { if order == ByteOrder::Little { le.to_vec() } else { le.iter().rev().copied().collect() } };
|
||||
let mut f = if order == ByteOrder::Little { b"II".to_vec() } else { b"MM".to_vec() };
|
||||
for part in [e(&43u16.to_le_bytes()), e(&8u16.to_le_bytes()), e(&0u16.to_le_bytes()), e(&16u64.to_le_bytes()), e(&count.to_le_bytes())] {
|
||||
f.extend(part);
|
||||
}
|
||||
// one entry: ImageWidth, LONG, 1 value (inline in the 8-byte field)
|
||||
for part in [e(&tags::IMAGE_WIDTH.to_le_bytes()), e(&4u16.to_le_bytes()), e(&1u64.to_le_bytes()), e(&640u32.to_le_bytes())] {
|
||||
f.extend(part);
|
||||
}
|
||||
f.extend([0; 4]);
|
||||
let (ifd, next) = parse_ifd_at(&f, 16, order, 0, true, &ParseOptions::default()).unwrap();
|
||||
assert_eq!(ifd.value(tags::IMAGE_WIDTH), Some(&Value::Long(vec![640])), "{order:?} {count}");
|
||||
assert_eq!(next, 0, "{order:?} {count}");
|
||||
let t = Tiff::parse(&f).unwrap();
|
||||
assert_eq!(t.ifds.len(), 1);
|
||||
}
|
||||
// a complete chain of two IFDs still links
|
||||
let mut a = IfdBuilder::new();
|
||||
a.set(1000, Value::Short(vec![1]));
|
||||
let mut b = IfdBuilder::new();
|
||||
b.set(1000, Value::Short(vec![2]));
|
||||
let t = Tiff::parse(&TiffWriter::new(order, true).write(&[a, b]).unwrap()).unwrap();
|
||||
assert_eq!(t.ifds.len(), 2, "{order:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! Release and source Flatpaks must allow release checks and host update helpers.
|
||||
fn finish_args(manifest: &str) -> Vec<&str> {
|
||||
manifest
|
||||
.split("finish-args:")
|
||||
.nth(1)
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#'))
|
||||
.filter_map(|line| line.trim().strip_prefix("- "))
|
||||
.map(|arg| arg.trim_matches(['\'', '"']))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatpak_update_permissions() {
|
||||
let manifests = [
|
||||
include_str!("../../../packaging/linux/flatpak/ai.storyteller.lightcraft.bundle.yml"),
|
||||
include_str!("../../../packaging/linux/flatpak/ai.storyteller.lightcraft.yml"),
|
||||
];
|
||||
let args = manifests.map(finish_args);
|
||||
assert_eq!(args[0], args[1], "source and release permissions must agree");
|
||||
for permissions in args {
|
||||
for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak"] {
|
||||
assert!(permissions.contains(&required), "missing update permission: {required}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ import and export formats. Ours come from `crates/codecs/src/sniff.rs`, `crates/
|
||||
| TIFF | ✅ 8/16/32-bit | ✅ 8/16-bit, LZW/ZIP | ✅ 1–64-bit integer, 16–64-bit float, bilevel, CCITT fax, WhiteIsZero | ✅ 8/16-bit, 32-bit float linear, none / LZW / ZIP | `crates/tiff`, `crates/codecs/src/tiff_codec.rs` |
|
||||
| PNG | ✅ | ✅ | ✅ | ✅ | |
|
||||
| PSD / PSB | ✅ (maximized-compatibility composite) | ✅ (Classic: PSD export, edit-in round trip) | ✅ merged composite | ⬜ (external-editor round trip writes 16-bit TIFF) | `crates/codecs/src/psd.rs` |
|
||||
| HEIC / HEIF | ✅ | ⬜ (Classic) / HDR only | ✅ in every release build (`crates/heif`, heic-rs) | ⬜ | `heif` feature on by packaging scripts |
|
||||
| HEIC / HEIF | ✅ | ⬜ (Classic) / HDR only | ✅ in every release build (`craft-heif` from craft-libs, heic-rs) | ⬜ | `heif` feature on by packaging scripts |
|
||||
| AVIF | ✅ | ✅ (HDR) | ⬜ recognised, not decoded (no permissive pure-Rust AV1 decoder) | ✅ 8/10-bit, PQ HDR | |
|
||||
| JPEG XL | ✅ | ✅ | ✅ (`jxl-oxide`) incl. DNG 1.7 JXL tiles | ✅ lossy / lossless, 8/16-bit, PQ HDR (`jixel`, native only; ⬜ web) | `crates/engine/src/tests/export.rs` |
|
||||
| WebP | not in its document types | ⬜ | ✅ | ✅ | beyond target |
|
||||
@@ -27,7 +27,7 @@ import and export formats. Ours come from `crates/codecs/src/sniff.rs`, `crates/
|
||||
| DNG (from raw) | ✅ | ✅ incl. lossy, embedded original | ✅ | ✅ uncompressed, LJ92, Deflate or lossy (JPEG tiles, optional long edge); ⬜ embedded original | `crates/raw/src/dngwrite.rs` |
|
||||
| Render to DNG (15.5) | — | ✅ | — | 🟡 export format "Rendered DNG" (linear float DNG, edit baked in); not yet added to the catalog | `crates/raw/src/dngwrite.rs` (`write_rendered_dng`) |
|
||||
| Original + sidecar | — | ✅ | — | ✅ | |
|
||||
| HDR gain map JPEG (ISO 21496-1) | ✅ | ✅ | ✅ (gain map read) | ✅ | `crates/codecs/src/gainmap.rs` |
|
||||
| HDR gain map JPEG (ISO 21496-1) | ✅ | ✅ | ✅ (gain map read) | ✅ | `crates/codecs/src/gainmap.rs` (JPEG layout), `craft-gainmap` (metadata, compute, apply) |
|
||||
| PQ / HLG HDR | ✅ | ✅ AVIF, JXL, TIFF | — | 🟡 PQ AVIF, PQ JPEG XL, float TIFF; no HLG | |
|
||||
| Contact sheet / print PDF | — | ✅ (Print module: PDF / JPEG / printer) | — | 🟡 paginated contact-sheet PDF (A4 / Letter, 150 dpi, sRGB) | `crates/engine/src/contact_sheet.rs` |
|
||||
| Video (MP4, MOV, AVCHD…) | ✅ playback, trim, edit | ✅ export | 🟡 catalogued (kind, duration) | ⬜ | see video gap |
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -7,6 +7,17 @@
|
||||
three quarters, where it used to cover 90 % and more, and a slow stroke covers the same as a fast one (issue #4045).
|
||||
New photos (and Reset) get it; photos you already edited keep their brushes until Photo ▸ Update to Current Process.
|
||||
|
||||
### Flatpak updates
|
||||
- Help ▸ Check for Updates can now reach the release service and update standalone Flatpak bundles.
|
||||
This permissions repair must first arrive through your existing host-side update method. Flatpaks
|
||||
managed by a software repository continue to use its package manager, and launcher-pinned versions
|
||||
keep their selected version.
|
||||
|
||||
### Export Effect Presets leaves your originals alone
|
||||
- Export Effect Presets… (`mask.exportEffects`) now refuses a path that is a photo's original or its XMP sidecar, as
|
||||
the other exports do, and writes the file atomically. It used to write the presets over whatever file it was given,
|
||||
and a failed write (a full disk) could leave a cut-off file where an earlier export was.
|
||||
|
||||
### Film grain that looks like film (process V7)
|
||||
- Grain now comes from a simulated emulsion of crystal layers (after Aurélien Pierre's model): dense, soft and cloudy
|
||||
rather than dots on top of the photo. It fades out towards black and white as on a print, so shadows keep their depth
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user