mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge PR #7415: codecs: read and write TIFF extra samples (spot and alpha channels)
This commit is contained in:
commit
5939e12dfb
4 files changed
+83
-13
No files matched your search
@@ -228,8 +228,10 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them
|
||||
* Extra samples: the first alpha sample (ExtraSamples 1 or 2, wherever it sits) is the image's
|
||||
alpha. Every other extra sample, such as a spot colour or a further alpha channel
|
||||
(ExtraSamples 0), comes back in `Metadata::extra_samples`: one plane per sample in the
|
||||
image's sample type, with its ExtraSamples value as `kind`. At most `MAX_EXTRA_SAMPLES` (16)
|
||||
are kept, and they count against `Limits::max_alloc` with the image.
|
||||
image's sample type, with its ExtraSamples value as `kind` (a reserved value above 2 reads as
|
||||
0). At most `MAX_EXTRA_SAMPLES` (16) are kept, and they count against `Limits::max_alloc` with
|
||||
the image: when the image fits but its extra samples don't, it opens without them and carries
|
||||
`DecodeWarning::ExtraSamplesDropped`.
|
||||
* Every directory is reachable: `tiff_info` lists the main IFD chain and its SubIFDs (tag 330)
|
||||
with each page's size, kind (page, reduced-resolution copy, mask) and storage, walked with a
|
||||
seen-set, a depth limit and a 10 000-directory cap; `decode_tiff_page` opens any of them.
|
||||
@@ -244,7 +246,8 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them
|
||||
JPEG-in-TIFF) return `Unsupported`.
|
||||
* **TIFF encode** writes classic TIFF, or BigTIFF when `EncodeOptions::tiff_bigtiff` is set or
|
||||
the file could pass 4 GiB. `Metadata::extra_samples` (up to 16) are written after the colour
|
||||
and alpha samples, with their `kind` in the ExtraSamples tag. Each plane must be exactly
|
||||
and alpha samples, with their `kind` in the ExtraSamples tag (a reserved `kind` above 2 is
|
||||
written as 0). Each plane must be exactly
|
||||
`width × height × sample.bytes()` bytes; a plane of any other length, and more than 16 planes,
|
||||
are encode errors rather than silently truncated or reinterpreted.
|
||||
* **EXR**
|
||||
|
||||
@@ -696,7 +696,7 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
|
||||
.ok_or_else(|| CodecError::LimitExceeded("tile size".into()))?;
|
||||
let scratch_cap = chunk_bytes.saturating_mul(2).max(64 << 20).min(limits.alloc_usize());
|
||||
let extra_at = extra_sample_indices(spp as usize, color, alpha_at, out_layout.has_alpha());
|
||||
let lay = Layout {
|
||||
let mut lay = Layout {
|
||||
w: wu,
|
||||
src,
|
||||
out,
|
||||
@@ -715,10 +715,15 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
|
||||
extra_at,
|
||||
};
|
||||
// Extra samples share the allocation budget with the image: their interleaved buffer and the
|
||||
// planes split from it are held next to the image, so both count against `max_alloc`.
|
||||
// planes split from it are held next to the image, so both count against `max_alloc`. When
|
||||
// they don't fit, the image still opens (it passed its own check above) without them.
|
||||
let mut extras_dropped = 0;
|
||||
if !lay.extra_at.is_empty() {
|
||||
let per_pixel = out_layout.channels().saturating_add(lay.extra_at.len().saturating_mul(2)).saturating_mul(out.bytes());
|
||||
limits.check_bytes(w, h, per_pixel as u64)?;
|
||||
if limits.check_bytes(w, h, per_pixel as u64).is_err() {
|
||||
extras_dropped = u32::try_from(lay.extra_at.len()).unwrap_or(u32::MAX);
|
||||
lay.extra_at.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// The output, allocated once and fallibly.
|
||||
@@ -740,9 +745,17 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
|
||||
}
|
||||
let mut img = Image::from_raw(w, h, out_layout, out, data)?;
|
||||
if !lay.extra_at.is_empty() {
|
||||
let kind_of = |si: usize| si.checked_sub(color).and_then(|k| extra.get(k)).copied().unwrap_or(0) as u16;
|
||||
// TIFF 6.0 defines ExtraSamples 0, 1 and 2 only; a reserved value reads as unspecified,
|
||||
// so a save never writes it back.
|
||||
let kind_of = |si: usize| match si.checked_sub(color).and_then(|k| extra.get(k)).copied() {
|
||||
Some(v @ 0..=2) => v as u16,
|
||||
_ => 0,
|
||||
};
|
||||
img.meta.extra_samples = split_extra_samples(&extra_data, wu, hu, &lay.extra_at, out, kind_of)?;
|
||||
}
|
||||
if extras_dropped > 0 {
|
||||
img.warnings.push(DecodeWarning::ExtraSamplesDropped { format: F, count: extras_dropped });
|
||||
}
|
||||
if tally.missing > 0 {
|
||||
img.warnings.push(DecodeWarning::Truncated { format: F });
|
||||
}
|
||||
@@ -1728,8 +1741,9 @@ fn encode_ready(img: &Image, opts: &EncodeOptions) -> Result<Vec<u8>, CodecError
|
||||
if img.layout().has_alpha() {
|
||||
kinds.push(2);
|
||||
}
|
||||
// TIFF 6.0 reserves ExtraSamples values above 2: those are written as 0 (unspecified).
|
||||
for e in &img.meta.extra_samples {
|
||||
kinds.push(e.kind);
|
||||
kinds.push(if e.kind <= 2 { e.kind } else { 0 });
|
||||
}
|
||||
let tags = TagSet {
|
||||
icc: if opts.embed_icc { img.icc.as_deref() } else { None },
|
||||
|
||||
@@ -200,6 +200,9 @@ pub enum DecodeWarning {
|
||||
/// A DPX element's transfer characteristic and colorimetric specification (SMPTE 268M codes,
|
||||
/// 255 when undefined). The code values are imported as stored, without a colour transform.
|
||||
DpxEncoding { transfer: u8, colorimetric: u8 },
|
||||
/// The file's `count` extra samples (spot or extra alpha channels) did not fit the allocation
|
||||
/// limit next to the image, so only the image was decoded.
|
||||
ExtraSamplesDropped { format: Format, count: u32 },
|
||||
}
|
||||
|
||||
/// The SMPTE 268M name of a transfer characteristic or colorimetric code.
|
||||
@@ -250,6 +253,13 @@ impl fmt::Display for DecodeWarning {
|
||||
dpx_code_name(*transfer),
|
||||
dpx_code_name(*colorimetric)
|
||||
),
|
||||
DecodeWarning::ExtraSamplesDropped { format, count } => write!(
|
||||
f,
|
||||
"{count} extra {} file channel{} (spot or alpha) did not fit in memory and {} not imported",
|
||||
format.name(),
|
||||
if *count == 1 { "" } else { "s" },
|
||||
if *count == 1 { "was" } else { "were" }
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,11 +218,13 @@ fn a_wrong_sized_plane_is_refused_before_a_sample_type_conversion() {
|
||||
}
|
||||
|
||||
/// Extra samples count against `max_alloc` with the image (their interleaved buffer and the
|
||||
/// planes split from it): a budget that holds the RGB image but not sixteen extra planes refuses
|
||||
/// the file instead of allocating past it.
|
||||
/// planes split from it): a budget that holds the RGB image but not sixteen extra planes opens
|
||||
/// the image without them, with a warning, instead of allocating past it.
|
||||
#[test]
|
||||
fn extra_samples_count_against_the_allocation_limit() {
|
||||
let (w, h) = (64u32, 64u32);
|
||||
// Big enough for several strips (about 1 MB each): one strip of all 19 samples fits the budget
|
||||
// of the image alone, as in real files.
|
||||
let (w, h) = (1024u32, 1024u32);
|
||||
let n = (w * h) as usize;
|
||||
let mut img = synth(w, h, ChannelLayout::Rgb, SampleType::U8, 1, 0.0);
|
||||
img.meta.extra_samples = (0..MAX_EXTRA_SAMPLES).map(|k| ExtraSample { kind: 0, data: vec![k as u8; n] }).collect();
|
||||
@@ -231,10 +233,51 @@ fn extra_samples_count_against_the_allocation_limit() {
|
||||
// RGB is 3 bytes a pixel; the extra samples add 2 x 16 more.
|
||||
let image_only = 3 * n as u64;
|
||||
let with_extras = (3 + 2 * MAX_EXTRA_SAMPLES as u64) * n as u64;
|
||||
assert!(matches!(with(image_only), Err(CodecError::LimitExceeded(_))), "the image fits, the extra samples don't");
|
||||
assert!(matches!(with(with_extras - 1), Err(CodecError::LimitExceeded(_))));
|
||||
let back = with(with_extras).expect("everything fits");
|
||||
assert_eq!(back.meta.extra_samples.len(), MAX_EXTRA_SAMPLES);
|
||||
assert!(back.warnings.is_empty());
|
||||
// The image fits, its extra samples don't: it opens as before they were read, with a warning.
|
||||
for max_alloc in [image_only, with_extras - 1] {
|
||||
let only = with(max_alloc).expect("the image alone fits");
|
||||
assert!(only.meta.extra_samples.is_empty());
|
||||
assert_eq!(only.warnings, vec![DecodeWarning::ExtraSamplesDropped { format: Format::Tiff, count: MAX_EXTRA_SAMPLES as u32 }]);
|
||||
assert_eq!(only.data(), back.data());
|
||||
}
|
||||
assert!(matches!(with(image_only - 1), Err(CodecError::LimitExceeded(_))), "the image itself must still fit");
|
||||
}
|
||||
|
||||
/// The value field of a little-endian classic TIFF's ExtraSamples entry (tag 338, SHORT) holding
|
||||
/// two values, so they sit in the entry itself.
|
||||
fn extra_samples_values(bytes: &mut [u8]) -> &mut [u8] {
|
||||
assert_eq!(&bytes[..4], b"II*\0");
|
||||
let entry = [0x52, 0x01, 3, 0, 2, 0, 0, 0];
|
||||
let at = bytes.windows(8).position(|w| w == entry).expect("an ExtraSamples entry with two values");
|
||||
&mut bytes[at + 8..at + 12]
|
||||
}
|
||||
|
||||
/// ExtraSamples values above 2 are reserved (TIFF 6.0, p. 31): they read as 0 (unspecified) and
|
||||
/// are written as 0, so a save never carries a reserved value.
|
||||
#[test]
|
||||
fn reserved_extra_sample_kinds_read_as_unspecified() {
|
||||
let n = 4 * 4;
|
||||
let mut img = synth(4, 4, ChannelLayout::Rgb, SampleType::U8, 1, 0.0);
|
||||
img.meta.extra_samples = vec![ExtraSample { kind: 0, data: vec![7; n] }, ExtraSample { kind: 0, data: vec![9; n] }];
|
||||
let mut bytes = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
|
||||
// A file from another writer with reserved values 3 and 65535.
|
||||
let values = extra_samples_values(&mut bytes);
|
||||
assert_eq!(values, [0, 0, 0, 0]);
|
||||
values.copy_from_slice(&[3, 0, 0xFF, 0xFF]);
|
||||
let back = decode(&bytes).unwrap();
|
||||
assert_eq!(back.meta.extra_samples.iter().map(|e| e.kind).collect::<Vec<_>>(), [0, 0]);
|
||||
assert_eq!(back.layout(), ChannelLayout::Rgb, "a reserved value is no alpha");
|
||||
assert_eq!(back.meta.extra_samples[0].data, vec![7; n]);
|
||||
assert_eq!(back.meta.extra_samples[1].data, vec![9; n]);
|
||||
|
||||
// An image that carries a reserved kind saves it as 0.
|
||||
img.meta.extra_samples[0].kind = 3;
|
||||
img.meta.extra_samples[1].kind = u16::MAX;
|
||||
let mut bytes = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
|
||||
assert_eq!(extra_samples_values(&mut bytes), [0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
/// Converting an image's sample type converts its extra samples with it, so they keep matching
|
||||
|
||||
Reference in new issue
Block a user