Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

TIFF: alpha after an unspecified extra sample opens transparent (#1349) (#1513)

David Mann284724af377f
diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rs
index 4a8846365..9069f166e 100644
--- a/crates/codecs/src/codecs/tiff.rs
+++ b/crates/codecs/src/codecs/tiff.rs
@@ -407,6 +407,8 @@ struct Layout {
chunks_per_plane: usize,
/// WhiteIsZero: invert the gray channel.
invert: bool,
+ /// The decoded sample (chunky) or file plane (planar) of the alpha channel (when there is one).
+ alpha_sample: usize,
/// Associated (premultiplied) alpha to turn straight.
premultiplied: bool,
/// Palette images: the colour map (16-bit RGB per index).
@@ -419,6 +421,10 @@ impl Layout {
fn out_channels(&self) -> usize {
self.out_layout.channels()
}
+ /// The decoded sample (chunky) or file plane (planar) of output channel `k`.
+ fn source_sample(&self, k: usize) -> usize {
+ if self.out_layout.has_alpha() && k + 1 == self.out_channels() { self.alpha_sample } else { k }
+ }
fn out_row(&self) -> usize {
self.w * self.out_channels() * self.out.bytes()
}
@@ -518,6 +524,17 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
} else {
None
};
+ // TIFF 6.0 lets any extra sample be the alpha (#1349). For RGB and CMYK the `tiff` crate
+ // returns the alpha only when it is the first extra sample: otherwise it is asked for every
+ // sample (as multiband gray) and the colour and alpha samples are picked here. An alpha
+ // position past the samples the file has is ignored.
+ let color = match photometric {
+ 2 => 3,
+ 5 => 4,
+ _ => 1,
+ };
+ let alpha_at = extra.iter().position(|&e| e == 1 || e == 2).filter(|&a| (color + a as u64) < spp);
+ let all_samples = palette.is_none() && matches!(photometric, 2 | 5) && alpha_at.is_some_and(|a| a > 0);
let mut patches: Vec<(u64, Vec<u8>)> = Vec::new();
let encode_u = |v: u64, len: usize| -> Vec<u8> {
let b = if f.le { v.to_le_bytes() } else { v.to_be_bytes() };
@@ -532,7 +549,7 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
// The directory is seen as the last of its chain: the chain was walked already, and a
// cycle through it must not fail this page.
patches.push((dir.next_at, vec![0; if f.big { 8 } else { 4 }]));
- if invert || palette.is_some() {
+ if invert || palette.is_some() || all_samples {
let e = photometric_entry.ok_or_else(|| err("missing PhotometricInterpretation"))?;
let len = match e.ty {
3 if e.count == 1 => 2,
@@ -555,11 +572,13 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
return Err(err("inconsistent image directory"));
}
let ct = dec.colortype().map_err(map_err)?;
- let alpha_first = matches!(extra.first(), Some(1 | 2));
- let gray_alpha = alpha_first || (extra.is_empty() && spp == 2);
+ let gray_alpha = alpha_at.is_some() || (extra.is_empty() && spp == 2);
let (out_layout, chunk_spp) = match ct {
_ if palette.is_some() => (ChannelLayout::Rgb, 1),
tiff::ColorType::Gray(_) => (ChannelLayout::Gray, 1),
+ tiff::ColorType::Multiband { num_samples, .. } if all_samples => {
+ (if photometric == 2 { ChannelLayout::Rgba } else { ChannelLayout::CmykA }, usize::from(num_samples))
+ }
tiff::ColorType::Multiband { num_samples, .. } if photometric <= 1 => {
(if gray_alpha { ChannelLayout::GrayA } else { ChannelLayout::Gray }, usize::from(num_samples))
}
@@ -570,6 +589,11 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
other => return Err(CodecError::unsupported(F, format!("colour type {other:?}"))),
};
let chunk_spp = if planar { 1 } else { chunk_spp };
+ // The sample (chunky) or plane (planar) that holds the alpha: the colour samples come first.
+ let alpha_sample = out_layout.color_channels() + alpha_at.unwrap_or(0);
+ if out_layout.has_alpha() && (alpha_sample as u64 >= spp || (!planar && alpha_sample >= chunk_spp)) {
+ return Err(err("the alpha sample is past the samples of a pixel"));
+ }
if matches!(src, Src::Bits(_)) && (out_layout.channels() > 1 || spp != 1) && palette.is_none() {
return Err(CodecError::unsupported(F, format!("{bits}-bit samples with {spp} samples per pixel")));
}
@@ -628,7 +652,8 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr
across,
chunks_per_plane,
invert: invert && palette.is_none(),
- premultiplied: out_layout.has_alpha() && extra.first() == Some(&1),
+ alpha_sample,
+ premultiplied: out_layout.has_alpha() && alpha_at.and_then(|a| extra.get(a)) == Some(&1),
palette,
scratch_cap,
};
@@ -722,8 +747,9 @@ fn decode_band(lay: &Layout, dec: &mut Decoder<Patched<'_>>, scratch: &mut Vec<u
let px = lay.out_channels() * lay.out.bytes();
let mut tally = Tally::default();
for plane in 0..lay.planes {
+ let file_plane = lay.source_sample(plane);
for col in 0..lay.across {
- let chunk = plane
+ let chunk = file_plane
.checked_mul(lay.chunks_per_plane)
.and_then(|c| c.checked_add(b.checked_mul(lay.across)?))
.and_then(|c| c.checked_add(col))
@@ -795,7 +821,7 @@ fn convert_row(lay: &Layout, src: &[u8], dst: &mut [u8], n: usize, plane: usize)
transfer(lay.src, src, 1, 0, dst, lay.out, och, plane, n);
} else {
for k in 0..och {
- transfer(lay.src, src, lay.chunk_spp, k, dst, lay.out, och, k, n);
+ transfer(lay.src, src, lay.chunk_spp, lay.source_sample(k), dst, lay.out, och, k, n);
}
}
}
diff --git a/crates/codecs/tests/tiff_pages.rs b/crates/codecs/tests/tiff_pages.rs
index e297416eb..60885e527 100644
--- a/crates/codecs/tests/tiff_pages.rs
+++ b/crates/codecs/tests/tiff_pages.rs
@@ -168,6 +168,48 @@ fn extra_samples_that_are_not_alpha_are_dropped() {
assert_eq!(img.data(), &rgb_of(2, 1)[..]);
}
+#[test]
+fn alpha_after_an_unspecified_extra_sample_is_kept() {
+ // #1349: TIFF 6.0 lets alpha be any extra sample; ExtraSamples [0, 2] puts it second.
+ let (w, h) = (5usize, 3usize);
+ for (photometric, color, layout) in [(2u16, 3usize, ChannelLayout::Rgba), (5, 4, ChannelLayout::CmykA), (1, 1, ChannelLayout::GrayA)] {
+ let spp = color + 2;
+ let t = truth(w * h * spp, 13 + spp as u64);
+ for (little, big) in ORDERS {
+ for (bits, format, file, want_all, sample) in depths(&t, little) {
+ let bps = bits as usize / 8;
+ // The colour samples, then the second extra sample (the alpha).
+ let want: Vec<u8> = want_all.chunks(spp * bps).flat_map(|p| [&p[..color * bps], &p[(color + 1) * bps..]].concat()).collect();
+ for planar in [false, true] {
+ let chunks = if planar { planar_strips(&file, w, h, spp, bps, 2) } else { file.chunks(w * spp * bps * 2).map(<[u8]>::to_vec).collect() };
+ let mut d = Dir { entries: base(w as u32, h as u32, bits, spp as u16, photometric), chunks, tiled: false }
+ .tag(278, LONG, &[2])
+ .tag(339, SHORT, &vec![u64::from(format); spp])
+ .tag(338, SHORT, &[0, 2]);
+ if planar {
+ d = d.tag(284, SHORT, &[2]);
+ }
+ let img = decode_ok(&build(little, big, &[d], &[0]).bytes);
+ let what = format!("photometric {photometric} little {little} big {big} bits {bits} planar {planar}");
+ assert_eq!((img.layout(), img.sample_type()), (layout, sample), "{what}");
+ assert_eq!(img.data(), &want[..], "{what}");
+ assert_eq!(img.warnings, [], "{what}");
+ }
+ }
+ }
+ }
+ // The issue's file: 2x2 RGB, every pixel 200 100 50, then 17 (unspecified), then alpha 128.
+ let px: Vec<u8> = [200u8, 100, 50, 17, 128].repeat(4);
+ let d = strips(2, 2, 8, 5, 2, 2, &px).tag(338, SHORT, &[0, 2]);
+ let img = decode_ok(&build(true, false, &[d], &[0]).bytes);
+ assert_eq!(img.data(), &[200u8, 100, 50, 128].repeat(4)[..]);
+ // Associated alpha in the same position is made straight.
+ let px: Vec<u8> = [100u8, 50, 25, 17, 128].repeat(4);
+ let d = strips(2, 2, 8, 5, 2, 2, &px).tag(338, SHORT, &[0, 1]);
+ let img = decode_ok(&build(true, false, &[d], &[0]).bytes);
+ assert_eq!(img.data(), &[199u8, 100, 50, 128].repeat(4)[..]);
+}
+
#[test]
fn associated_alpha_is_made_straight() {
// Premultiplied: half-transparent mid gray is stored as 64 with alpha 128.