Make TIFF pixel codecs optional while retaining metadata readers

This commit is contained in:
Codex committed 2026-11-29 23:23:14 +01:00
1 parent dd491ec0b6
commit 379a2b30e7
19 files changed
+100 -12

No files matched your search

+1
View File
@@ -607,6 +607,7 @@ image-codecs-pnm = ["image-codecs", "craft-image-codecs/pnm"]
image-codecs-sgi = ["image-codecs", "craft-image-codecs/sgi"]
image-codecs-sunraster = ["image-codecs", "craft-image-codecs/sunraster"]
image-codecs-tga = ["image-codecs", "craft-image-codecs/tga"]
image-codecs-tiff = ["image-codecs", "craft-image-codecs/tiff"]
image-codecs-threads = ["image-codecs", "craft-image-codecs/threads"]
image-codecs-webp = ["image-codecs", "craft-image-codecs/webp"]
image-codecs-xpm = ["image-codecs", "craft-image-codecs/xpm"]
+3 -2
View File
@@ -15,7 +15,7 @@ corpus = []
# Every codec below is on by default; a build that never reads or writes a format can turn
# `default-features` off and list the ones it needs. A format left out is still detected, and
# reading or writing it returns `CodecError::Unsupported` naming the feature.
default = ["dds", "dicom", "dpx", "exr", "fits", "iff", "jp2", "jpegls", "jxl-encode", "pnm", "tga", "webp", "xpm"]
default = ["dds", "dicom", "dpx", "exr", "fits", "iff", "jp2", "jpegls", "jxl-encode", "pnm", "tga", "tiff", "webp", "xpm"]
dds = []
dicom = []
# DPX and Cineon.
@@ -29,6 +29,7 @@ jpegls = []
jxl-encode = ["dep:zune-jpegxl"]
pnm = []
tga = ["image/tga"]
tiff = ["image/tiff"]
webp = ["dep:image-webp"]
xpm = []
# Opt in to threaded AVIF encoding without enabling AVIF (or assembly) by itself.
@@ -53,7 +54,7 @@ jp2 = ["dep:hayro-jpeg2000"]
craft-dds = { workspace = true }
crc32fast = "1.5"
thiserror = { workspace = true }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "gif", "bmp", "ico", "qoi", "hdr"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "bmp", "ico", "qoi", "hdr"] }
png = "0.18"
tiff = { version = "0.11", default-features = false, features = ["deflate", "fax", "jpeg", "lzw"] }
exr = { version = "1.73", default-features = false, optional = true }
+4 -2
View File
@@ -69,7 +69,8 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "<
Each codec below sits behind a Cargo feature that is on by default, preserving the default read
and write capabilities shown in the matrix. A build that never handles some formats turns `default-features`
off and lists the ones it needs; the codecs left out, and their dependencies, are not compiled in.
off and lists the ones it needs; unused codec backends are removed from optimized builds.
TIFF metadata readers and EXIF writing remain available without TIFF pixel support.
For a minimal build, depend directly on `craft-image-codecs` with `default-features = false`.
The `craft` facade's generated codec selectors are additive: its base `image-codecs` feature
@@ -88,10 +89,11 @@ retains the default codec set for existing facade consumers.
| `jxl-encode` | JPEG XL export (the `zune-jpegxl` dependency); decode is the separate `jxl` feature |
| `pnm` | Netpbm |
| `tga` | TGA (the `image` crate's TGA decoder) |
| `tiff` | TIFF and BigTIFF pixel decoding and encoding |
| `webp` | WebP, with the VP8 encoder (the `image-webp` dependency) |
| `xpm` | XPM |
PNG, JPEG, TIFF, GIF, BMP, ICO, QOI, Radiance HDR and PCX are always built. A format left
PNG, JPEG, GIF, BMP, ICO, QOI, Radiance HDR and PCX are always built. A format left
out is still detected; reading or writing it returns `CodecError::Unsupported` naming the feature,
and its `caps` say it can be neither read nor written. The functions specific to a left-out format
(`exr_info`, `decode_webp_frames`, `webp_encoding`, `xpm_named_color_rgb`...) are not compiled in.
+3
View File
@@ -259,6 +259,9 @@ use PhotometricInterpretation as PI;
/// Encode plain classic RGBA16 TIFF for callers that need the legacy file layout.
pub fn encode_plain_rgba16(width: u32, height: u32, samples: &[u16]) -> Result<Vec<u8>, CodecError> {
if !cfg!(feature = "tiff") {
return Err(CodecError::feature_missing(F, "tiff"));
}
craft_tiff::plain::encode_rgba16(width, height, samples).map_err(|error| CodecError::encode(F, error))
}
@@ -28,6 +28,9 @@ pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32, u16), Co
/// carries the page's metadata, a [`DecodeWarning::MorePages`] when the file holds more
/// full-resolution pages, and a [`DecodeWarning::Truncated`] when image data is cut off.
pub(crate) fn decode_page(bytes: &[u8], page: Option<usize>, limits: &Limits) -> Result<Image, CodecError> {
if !cfg!(feature = "tiff") {
return Err(CodecError::feature_missing(F, "tiff"));
}
let (file, dir, more) = open_page(bytes, page)?;
let mut img = decode_ifd(&file, &dir, limits)?;
let extra_samples = std::mem::take(&mut img.meta.extra_samples);
@@ -107,6 +110,9 @@ impl<'a> TiffBands<'a> {
/// against `limits`; on 64-bit targets its `max_alloc` bounds each group of bands, not the
/// whole image.
pub fn open(bytes: &'a [u8], page: Option<usize>, limits: &Limits) -> Result<Self, CodecError> {
if !cfg!(feature = "tiff") {
return Err(CodecError::feature_missing(F, "tiff"));
}
let (file, dir, more) = open_page(bytes, page)?;
// On 32-bit targets the whole image must still fit `max_alloc`, as it did before: the
// document holding it shares the same small address space (wasm32: 4 GiB).
@@ -911,7 +917,7 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result<Prep
})
}
#[cfg(test)]
#[cfg(all(test, feature = "tiff"))]
mod tests {
use super::*;
use crate::{EncodeOptions, ExtraSample, Format};
@@ -539,6 +539,9 @@ fn check_extra_planes(img: &Image) -> Result<(), CodecError> {
}
pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Vec<u8>, CodecError> {
if !cfg!(feature = "tiff") {
return Err(CodecError::feature_missing(F, "tiff"));
}
// Check the source planes before `converted`, which brings them to the plan's sample type
// with the image but deliberately leaves a wrong-sized plane alone: past that point a bad
// plane would be reinterpreted in the new width rather than rejected.
+1
View File
@@ -292,6 +292,7 @@ pub(crate) fn missing_feature(format: Format) -> Option<&'static str> {
Format::Sgi => ("sgi", cfg!(feature = "sgi")),
Format::SunRaster => ("sunraster", cfg!(feature = "sunraster")),
Format::Tga => ("tga", cfg!(feature = "tga")),
Format::Tiff => ("tiff", cfg!(feature = "tiff")),
Format::WebP => ("webp", cfg!(feature = "webp")),
Format::Xpm => ("xpm", cfg!(feature = "xpm")),
_ => return None,
+3 -2
View File
@@ -89,8 +89,9 @@ mod tests {
use super::*;
#[test]
fn reads_first_directory_and_enforces_limits_and_bounds() {
let image = crate::Image::from_u8(2, 3, crate::ChannelLayout::Rgb, vec![42; 18]).unwrap();
let bytes = crate::encode(&image, crate::Format::Tiff, &crate::EncodeOptions::default()).unwrap();
let mut out = std::io::Cursor::new(Vec::new());
tiff::encoder::TiffEncoder::new(&mut out).unwrap().write_image::<tiff::encoder::colortype::RGB8>(2, 3, &[42; 18]).unwrap();
let bytes = out.into_inner();
assert_eq!(header(&bytes, 6).unwrap(), (2, 3, 1));
let info = decode_info(&bytes, 6).unwrap();
assert_eq!((info.width, info.height, info.bit_depth), (2, 3, 8));
@@ -244,6 +244,7 @@ fn animated_webp_warns_and_keeps_the_first_frame() {
}
/// A TIFF with one IFD per entry: `(NewSubfileType, sample type)`.
#[cfg(feature = "tiff")]
fn tiff(ifds: &[(u32, SampleType)]) -> Vec<u8> {
use tiff::encoder::{TiffEncoder, colortype};
use tiff::tags::Tag;
@@ -272,6 +273,7 @@ fn tiff(ifds: &[(u32, SampleType)]) -> Vec<u8> {
}
#[test]
#[cfg(feature = "tiff")]
fn multi_page_tiff_warns_and_keeps_the_first_page() {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
let one = decode(&tiff(&[(0, sample)])).unwrap();
@@ -286,6 +288,7 @@ fn multi_page_tiff_warns_and_keeps_the_first_page() {
}
#[test]
#[cfg(feature = "tiff")]
fn tiff_thumbnails_and_masks_are_not_pages() {
let u8 = SampleType::U8;
// A reduced-resolution copy (bit 0) or a transparency mask (bit 2) is part of the page.
@@ -354,12 +357,19 @@ fn additional_images_probe_uses_container_structure_without_decoding_pixels() {
(animated_webp(&frames[..1]), false),
#[cfg(feature = "webp")]
(animated_webp(&frames), true),
#[cfg(feature = "tiff")]
(tiff(&[(0, SampleType::U8)]), false),
#[cfg(feature = "tiff")]
(tiff(&[(0, SampleType::U8), (2, SampleType::U8)]), true),
#[cfg(feature = "tiff")]
(tiff(&[(0, SampleType::U8), (1, SampleType::U8)]), false),
#[cfg(feature = "tiff")]
(tiff(&[(4, SampleType::U8)]), false),
#[cfg(feature = "tiff")]
(tiff(&[(0, SampleType::U8), (4, SampleType::U8)]), true),
#[cfg(feature = "tiff")]
(tiff(&[(4, SampleType::U8), (0, SampleType::U8)]), true),
#[cfg(feature = "tiff")]
(tiff(&[(0, SampleType::U8), (1, SampleType::U8), (4, SampleType::U8)]), true),
] {
assert_eq!(has_unretained_source_data(&bytes).unwrap(), multiple);
@@ -48,6 +48,7 @@ fn feature_config_default_build_formats_all_symmetric() {
let expected = [
Format::Png,
Format::Jpeg,
#[cfg(feature = "tiff")]
Format::Tiff,
#[cfg(feature = "webp")]
Format::WebP,
+1
View File
@@ -18,6 +18,7 @@ fn png_u16_rgba_is_clean() {
assert!(warns(&test_image(ChannelLayout::Rgba, SampleType::U16), Format::Png).is_empty());
}
#[test]
#[cfg(feature = "tiff")]
fn tiff_is_clean_for_all_integer_and_f32_layouts() {
for l in ChannelLayout::ALL {
for s in [SampleType::U8, SampleType::U16, SampleType::F32, SampleType::F16] {
+1
View File
@@ -462,6 +462,7 @@ fn jpeg_bomb_header_rejected() {
}
#[test]
#[cfg(feature = "tiff")]
fn tiff_bomb_header_rejected() {
// Minimal little-endian TIFF claiming 1_000_000 x 1_000_000 8-bit gray.
let mut b = b"II*\0\x08\0\0\0".to_vec();
+11
View File
@@ -1,6 +1,7 @@
//! The crate's integration tests, linked into one test binary.
mod bmp_resolution;
#[cfg(feature = "tiff")]
mod camera_raw;
mod common;
#[cfg(feature = "dds")]
@@ -43,14 +44,24 @@ mod roundtrip;
mod source_settings;
#[cfg(feature = "tga")]
mod tga;
#[cfg(feature = "tiff")]
mod tiff_bands;
#[cfg(feature = "tiff")]
mod tiff_bench;
#[cfg(feature = "tiff")]
mod tiff_exif;
mod tiff_feature;
#[cfg(feature = "tiff")]
mod tiff_lab;
#[cfg(feature = "tiff")]
mod tiff_pages;
#[cfg(feature = "tiff")]
mod tiff_photoshop;
#[cfg(feature = "tiff")]
mod tiff_pyramid;
#[cfg(feature = "tiff")]
mod tiff_regressions;
#[cfg(feature = "tiff")]
mod tiff_ycbcr;
#[cfg(feature = "webp")]
mod webp_frames;
@@ -264,6 +264,7 @@ fn tiny_tiff(extra: &[(u16, u16, u32, u32)]) -> Vec<u8> {
}
#[test]
#[cfg(feature = "tiff")]
fn tiff_fixture_decodes() {
let img = decode_as_with(Format::Tiff, &tiny_tiff(&[]), &tight()).unwrap();
assert_eq!((img.width(), img.height()), (1, 1));
+4 -2
View File
@@ -126,7 +126,7 @@ fn hdr_metadata() {
#[test]
fn metadata_on_16bit_png_and_tiff() {
for f in [Format::Png, Format::Tiff] {
for f in [Format::Png, Format::Tiff].into_iter().filter(|f| caps(*f).write) {
let mut img = test_image(ChannelLayout::Rgba, SampleType::U16);
img.icc = Some(sample_icc(512));
img.meta.dpi = Some((72.0, 72.0));
@@ -138,7 +138,7 @@ fn metadata_on_16bit_png_and_tiff() {
#[test]
fn icc_on_cmyk_tiff_and_jpeg() {
for f in [Format::Tiff, Format::Jpeg] {
for f in [Format::Tiff, Format::Jpeg].into_iter().filter(|f| caps(*f).write) {
let img = test_image(ChannelLayout::Cmyk, SampleType::U8).with_icc(Some(sample_icc(900)));
let back = decode(&encode(&img, f, &EncodeOptions::default()).unwrap()).unwrap();
assert_eq!(back.layout(), ChannelLayout::Cmyk, "{f:?}");
@@ -220,6 +220,7 @@ fn embed_flags_disable_metadata() {
for f in [
Format::Png,
Format::Jpeg,
#[cfg(feature = "tiff")]
Format::Tiff,
#[cfg(feature = "webp")]
Format::WebP,
@@ -288,6 +289,7 @@ fn jpeg_dpi_in_jfif() {
}
#[test]
#[cfg(feature = "tiff")]
fn tiff_icc_readable_by_oracle() {
let img = test_image(ChannelLayout::Rgb, SampleType::U16).with_icc(Some(sample_icc(1234)));
let bytes = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
+10 -3
View File
@@ -91,6 +91,7 @@ fn png_with_exif(png: &[u8], exif: &[u8]) -> Vec<u8> {
out
}
#[cfg(feature = "tiff")]
fn tiff_with_orientation(data: &[u8], w: u32, h: u32, o: u16) -> Vec<u8> {
use tiff::encoder::{TiffEncoder, colortype::Gray8};
let mut cursor = std::io::Cursor::new(Vec::new());
@@ -305,6 +306,7 @@ fn extra_samples_turn_with_the_image() {
}
#[test]
#[cfg(feature = "tiff")]
fn tiff_opens_upright_for_every_orientation() {
let (w, h) = (4, 7);
let up = exact_scene(w, h);
@@ -396,6 +398,7 @@ fn export_writes_orientation_1_and_keeps_pixels() {
Format::Jpeg,
#[cfg(feature = "webp")]
Format::WebP,
#[cfg(feature = "tiff")]
Format::Tiff,
] {
let bytes = encode(&stale, format, &EncodeOptions { jpeg_quality: 100, ..Default::default() }).unwrap();
@@ -633,9 +636,12 @@ fn limits_apply_to_the_upright_size() {
let flipped = decode_with(&jpeg_with_exif(&jpeg, &exif(3, false, false)), &opts).unwrap();
assert_eq!(flipped.dimensions(), (32, 16));
// The same holds for a TIFF, whose orientation lives in its own IFD0.
let tiff = tiff_with_orientation(&[7; 32 * 16], 32, 16, 8);
assert!(matches!(decode_with(&tiff, &opts), Err(CodecError::LimitExceeded(_))));
assert_eq!(decode_with(&tiff, &DecodeOptions::default()).unwrap().dimensions(), (16, 32));
#[cfg(feature = "tiff")]
{
let tiff = tiff_with_orientation(&[7; 32 * 16], 32, 16, 8);
assert!(matches!(decode_with(&tiff, &opts), Err(CodecError::LimitExceeded(_))));
assert_eq!(decode_with(&tiff, &DecodeOptions::default()).unwrap().dimensions(), (16, 32));
}
}
#[test]
@@ -673,6 +679,7 @@ fn feature_config_probe_size_matches_decode() {
let probed = [
Format::Png,
Format::Jpeg,
#[cfg(feature = "tiff")]
Format::Tiff,
#[cfg(feature = "webp")]
Format::WebP,
+2
View File
@@ -229,6 +229,7 @@ fn png_output_matches_oracle_all_layouts() {
}
#[test]
#[cfg(feature = "tiff")]
fn tiff_output_matches_oracle() {
for l in [ChannelLayout::Gray, ChannelLayout::Rgb, ChannelLayout::Rgba] {
for s in [SampleType::U8, SampleType::U16] {
@@ -241,6 +242,7 @@ fn tiff_output_matches_oracle() {
}
#[test]
#[cfg(feature = "tiff")]
fn tiff_f32_output_matches_oracle() {
let img = test_image(ChannelLayout::Rgba, SampleType::F32);
let b = encode(&img, Format::Tiff, &EncodeOptions { tiff_compression: TiffCompression::None, ..Default::default() }).unwrap();
@@ -160,6 +160,7 @@ fn hdr_values_survive_float_formats() {
let vals: Vec<f32> = (0..16 * 8 * 3).map(|i| (i as f32 - 40.0) * 0.37).collect();
let img = Image::from_f32(16, 8, ChannelLayout::Rgb, &vals).unwrap();
let formats = [
#[cfg(feature = "tiff")]
Format::Tiff,
#[cfg(feature = "exr")]
Format::OpenExr,
@@ -200,6 +201,7 @@ fn f16_exr_is_bit_exact() {
}
#[test]
#[cfg(feature = "tiff")]
fn tiff_all_compressions_lossless() {
for layout in ChannelLayout::ALL {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
@@ -222,6 +224,7 @@ fn tiff_all_compressions_lossless() {
}
#[test]
#[cfg(feature = "tiff")]
fn compressed_tiff_does_not_keep_the_uncompressed_reservation() {
// The encoder reserves the uncompressed size up front for an uncompressed file (#6607). A
// smooth image compresses to a fraction of it, and no returned file holds much spare room.
@@ -358,6 +361,7 @@ fn larger_image_png_tiff_exact() {
let img = synth(513, 257, ChannelLayout::Rgba, SampleType::U16, 99, 1.0);
for f in [
Format::Png,
#[cfg(feature = "tiff")]
Format::Tiff,
#[cfg(feature = "pnm")]
Format::Pnm,
@@ -0,0 +1,30 @@
//! Original synthetic fixture: one RGBA pixel, written by the independent TIFF structure crate.
#[cfg(not(feature = "tiff"))]
use craft_image_codecs::*;
#[cfg(not(feature = "tiff"))]
#[test]
fn omitted_tiff_pixels_are_refused_but_metadata_remains_readable() {
let bytes = craft_tiff::plain::encode_rgba16(1, 1, &[1, 2, 3, u16::MAX]).unwrap();
assert_eq!(detect(&bytes), Some(Format::Tiff));
assert!(!caps(Format::Tiff).read && !caps(Format::Tiff).write);
assert!(tiff_info(&bytes).is_ok());
assert_eq!(tiff_probe::header(&bytes, 1).unwrap(), (1, 1, 1));
let image = Image::from_u8(1, 1, ChannelLayout::Rgba, vec![1, 2, 3, 255]).unwrap();
let errors = [
decode(&bytes).err(),
decode_tiff_page(&bytes, 0, &DecodeOptions::default()).err(),
TiffBands::open(&bytes, None, &Limits::default()).err(),
encode(&image, Format::Tiff, &EncodeOptions::default()).err(),
encode_tiff_plain_rgba16(1, 1, &[1, 2, 3, u16::MAX]).err(),
];
for error in errors {
match error.unwrap() {
CodecError::Unsupported { format, reason } => {
assert_eq!(format, Format::Tiff);
assert!(reason.contains("tiff feature"), "{reason}");
}
other => panic!("expected a named feature error, got {other:?}"),
}
}
}