diff --git a/crates/codecs/README.md b/crates/codecs/README.md index 539365c95b..e3799d357b 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -187,8 +187,12 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them planar configuration 1 or 2. * Supports 1, 2 and 4-bit gray, 8/16/32/64-bit integers (32 and 64-bit are reduced to U16), F16, F32 and F64 (converted to F32), WhiteIsZero (#691: the tones are no longer inverted), - palette images (opened as RGB), associated alpha (made straight) and extra samples (dropped - unless the first is alpha). + palette images (opened as RGB) and associated alpha (made straight). + * 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. * 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. @@ -202,7 +206,8 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them * YCbCr, CIE Lab, signed integers and compressions that the `tiff` crate lacks (CCITT, 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. + 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; more than 16 is an error. * **EXR** * Multi-part files (a Maya/Arnold render writes one part per AOV) open the part that looks most like a colour image — RGBA beats RGB beats YA beats a single channel, so a diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rs index 9528fec9c8..1cfa38bc10 100644 --- a/crates/codecs/src/codecs/tiff.rs +++ b/crates/codecs/src/codecs/tiff.rs @@ -249,7 +249,9 @@ pub(crate) fn decode_page(bytes: &[u8], page: Option, limits: &Limits) -> .ok_or_else(|| CodecError::InvalidImage(format!("TIFF page {index} does not exist (the file has {} directories)", info.pages.len())))?; let dir = file.ifd(p.ifd_offset).ok_or_else(|| err("image directory cut off"))?; let mut img = decode_ifd(&file, &dir, limits)?; + let extra_samples = std::mem::take(&mut img.meta.extra_samples); img.meta = metadata(&file, &dir, &mut img.icc); + img.meta.extra_samples = extra_samples; let pages = info.page_count(); if pages > 1 { img.warnings.push(DecodeWarning::MorePages { total: info.complete.then_some(u32::try_from(pages).unwrap_or(u32::MAX)) }); @@ -423,6 +425,8 @@ struct Layout { palette: Option>, /// Upper bound for one chunk's scratch buffer. scratch_cap: usize, + /// File sample indices that are neither colour nor the chosen alpha (spot / extra alpha). + extra_at: Vec, } impl Layout { @@ -436,6 +440,9 @@ impl Layout { fn out_row(&self) -> usize { self.w * self.out_channels() * self.out.bytes() } + fn extra_row(&self) -> usize { + self.w.saturating_mul(self.extra_at.len()).saturating_mul(self.out.bytes()) + } /// A chunky strip already in the output's layout: decoded in place. fn direct(&self) -> bool { self.copyable() && self.across == 1 @@ -543,13 +550,16 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result 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 | 8 | 9) && alpha_at.is_some_and(|a| a > 0); + let alpha_at = extra.iter().position(|&e| e == 1 || e == 2).filter(|&a| (color as u64).saturating_add(a as u64) < spp); + // Samples the colour model does not keep. RGB, CMYK and Lab only hand back every sample when + // asked (photometric patched to black-is-zero below); gray already comes back as multiband. + let unused = !extra.is_empty() && (spp as usize) > color.saturating_add(usize::from(alpha_at.is_some())); + let all_samples = palette.is_none() && matches!(photometric, 2 | 5 | 8 | 9) && (alpha_at.is_some_and(|a| a > 0) || (!planar && unused)); let mut patches: Vec<(u64, Vec)> = Vec::new(); let encode_u = |v: u64, len: usize| -> Vec { let b = if f.le { v.to_le_bytes() } else { v.to_be_bytes() }; @@ -592,7 +602,31 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result (ChannelLayout::Rgb, 1), tiff::ColorType::Gray(_) => (ChannelLayout::Gray, 1), tiff::ColorType::Multiband { num_samples, .. } if all_samples => { - (if photometric == 5 { ChannelLayout::CmykA } else { ChannelLayout::Rgba }, usize::from(num_samples)) + // Lab reads as RGB here and is relabelled below. + let layout = match photometric { + 2 | 8 | 9 => { + if alpha_at.is_some() { + ChannelLayout::Rgba + } else { + ChannelLayout::Rgb + } + } + 5 => { + if alpha_at.is_some() { + ChannelLayout::CmykA + } else { + ChannelLayout::Cmyk + } + } + _ => { + if gray_alpha { + ChannelLayout::GrayA + } else { + ChannelLayout::Gray + } + } + }; + (layout, usize::from(num_samples)) } tiff::ColorType::Multiband { num_samples, .. } if photometric <= 1 => { (if gray_alpha { ChannelLayout::GrayA } else { ChannelLayout::Gray }, usize::from(num_samples)) @@ -661,6 +695,7 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result, dir: &Ifd, limits: &Limits) -> Result, dir: &Ifd, limits: &Limits) -> Result 0 { return Err(err("the image data is missing (cut off or past the end of the file)")); } @@ -693,6 +739,10 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result 0 { img.warnings.push(DecodeWarning::Truncated { format: F }); } @@ -728,6 +778,52 @@ fn convert_ab(data: &mut [u8], channels: usize, sample: SampleType, signed: bool } } +/// File sample indices that are not a colour channel and not the one alpha sample, capped at +/// [`crate::MAX_EXTRA_SAMPLES`]. +fn extra_sample_indices(spp: usize, color: usize, alpha_at: Option, has_alpha: bool) -> Vec { + let mut used = vec![false; spp]; + for i in 0..color.min(spp) { + if let Some(slot) = used.get_mut(i) { + *slot = true; + } + } + if has_alpha { + let a = alpha_at.map(|k| color.saturating_add(k)).unwrap_or(color); + if let Some(slot) = used.get_mut(a) { + *slot = true; + } + } + used.into_iter().enumerate().filter(|(_, on)| !*on).map(|(i, _)| i).take(crate::MAX_EXTRA_SAMPLES).collect() +} + +/// Interleaved extra samples (`extra_at.len()` per pixel) → one plane per sample. Each plane is +/// allocated fallibly (the caller has checked their total against the limits). +fn split_extra_samples( + buf: &[u8], + w: usize, + h: usize, + at: &[usize], + sample: SampleType, + mut kind_of: impl FnMut(usize) -> u16, +) -> Result, CodecError> { + let b = sample.bytes(); + let n = w.saturating_mul(h); + let spp = at.len(); + let mut out = Vec::with_capacity(spp); + for (ei, &si) in at.iter().enumerate() { + let mut data = zeroed(n.saturating_mul(b))?; + for i in 0..n { + let src = (i.saturating_mul(spp).saturating_add(ei)).saturating_mul(b); + let dst = i.saturating_mul(b); + if let (Some(s), Some(d)) = (buf.get(src..src.saturating_add(b)), data.get_mut(dst..dst.saturating_add(b))) { + d.copy_from_slice(s); + } + } + out.push(crate::ExtraSample { kind: kind_of(si), data }); + } + Ok(out) +} + /// A zero-filled buffer, allocated fallibly. On native targets the zeroing (and the first /// touch of every page, which dominates on a fresh multi-hundred-megabyte buffer) is spread over /// all cores. @@ -760,20 +856,43 @@ impl std::ops::Add for Tally { } /// Decodes every band into `data`, in parallel on native targets (one decoder and scratch -/// buffer per worker). +/// buffer per worker). `extra` receives samples that are not part of the colour image, one +/// band of rows at a time, when it is non-empty. #[cfg(not(target_arch = "wasm32"))] -fn decode_bands<'a, O>(lay: &Layout, data: &mut [u8], band_bytes: usize, _first: &mut Decoder>, open: &O) -> Result +fn decode_bands<'a, O>( + lay: &Layout, + data: &mut [u8], + band_bytes: usize, + extra: &mut [u8], + extra_band: usize, + _first: &mut Decoder>, + open: &O, +) -> Result where O: Fn() -> Result>, CodecError> + Sync, { use rayon::prelude::*; + if extra.is_empty() { + return data + .par_chunks_mut(band_bytes.max(1)) + .enumerate() + .map_init( + || open().map(|d| (d, Vec::new())).map_err(|e| e.to_string()), + |worker, (b, band)| { + let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?; + decode_band(lay, dec, scratch, b, band, None) + }, + ) + .try_reduce(Tally::default, |a, b| Ok(a + b)); + } data.par_chunks_mut(band_bytes.max(1)) + .zip(extra.par_chunks_mut(extra_band.max(1))) .enumerate() .map_init( || open().map(|d| (d, Vec::new())).map_err(|e| e.to_string()), - |worker, (b, band)| { + |worker, (b, (band, extra_band))| { let (dec, scratch) = worker.as_mut().map_err(|e| err(e.clone()))?; - decode_band(lay, dec, scratch, b, band) + decode_band(lay, dec, scratch, b, band, Some(extra_band)) }, ) .try_reduce(Tally::default, |a, b| Ok(a + b)) @@ -781,20 +900,41 @@ where /// Decodes every band into `data`, one after the other. #[cfg(target_arch = "wasm32")] -fn decode_bands<'a, O>(lay: &Layout, data: &mut [u8], band_bytes: usize, first: &mut Decoder>, _open: &O) -> Result +fn decode_bands<'a, O>( + lay: &Layout, + data: &mut [u8], + band_bytes: usize, + extra: &mut [u8], + extra_band: usize, + first: &mut Decoder>, + _open: &O, +) -> Result where O: Fn() -> Result>, CodecError> + Sync, { let mut scratch = Vec::new(); let mut tally = Tally::default(); - for (b, band) in data.chunks_mut(band_bytes.max(1)).enumerate() { - tally = tally + decode_band(lay, first, &mut scratch, b, band)?; + if extra.is_empty() { + for (b, band) in data.chunks_mut(band_bytes.max(1)).enumerate() { + tally = tally + decode_band(lay, first, &mut scratch, b, band, None)?; + } + return Ok(tally); + } + for (b, (band, extra_band)) in data.chunks_mut(band_bytes.max(1)).zip(extra.chunks_mut(extra_band.max(1))).enumerate() { + tally = tally + decode_band(lay, first, &mut scratch, b, band, Some(extra_band))?; } Ok(tally) } /// Decodes band `b` (one strip, or one row of tiles, in every plane) into its output rows. -fn decode_band(lay: &Layout, dec: &mut Decoder>, scratch: &mut Vec, b: usize, band: &mut [u8]) -> Result { +fn decode_band( + lay: &Layout, + dec: &mut Decoder>, + scratch: &mut Vec, + b: usize, + band: &mut [u8], + mut extra: Option<&mut [u8]>, +) -> Result { let out_row = lay.out_row(); let rows = band.len() / out_row.max(1); let px = lay.out_channels() * lay.out.bytes(); @@ -836,16 +976,95 @@ fn decode_band(lay: &Layout, dec: &mut Decoder>, scratch: &mut Vec>, + scratch: &mut Vec, + b: usize, + rows: usize, + extra: Option<&mut [u8]>, + tally: &mut Tally, +) -> Result<(), CodecError> { + let Some(extra) = extra else { return Ok(()) }; + let ech = lay.extra_at.len(); + let erow = lay.extra_row(); + if ech == 0 || erow == 0 { + return Ok(()); + } + for (ei, &file_plane) in lay.extra_at.iter().enumerate() { + for col in 0..lay.across { + 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)) + .and_then(|c| u32::try_from(c).ok()) + .ok_or_else(|| err("chunk index out of range"))?; + let pref = dec.image_chunk_buffer_layout(chunk).map_err(map_err)?; + let stride = pref.row_stride.map(|s| s.get()).ok_or_else(|| err("empty chunk row"))?; + if pref.len > lay.scratch_cap { + return Err(CodecError::LimitExceeded(format!("a {} byte strip or tile", pref.len))); + } + if scratch.len() < pref.len { + scratch.resize(pref.len, 0); + } + let buf = scratch.get_mut(..pref.len).ok_or_else(|| err("scratch buffer"))?; + match dec.read_chunk_bytes(chunk, buf) { + Ok(()) => tally.decoded += 1, + Err(e) if is_eof(&e) => { + tally.missing += 1; + continue; + } + Err(e) => return Err(map_err(e)), + } + let x0 = col * lay.cw; + let n = lay.cw.min(lay.w.saturating_sub(x0)); + for (ri, src_row) in buf.chunks_exact(stride).take(rows).enumerate() { + let start = ri.saturating_mul(erow); + let Some(er) = extra.get_mut(start..start.saturating_add(erow)) else { continue }; + let px = ech * lay.out.bytes(); + let Some(dst) = er.get_mut(x0.saturating_mul(px)..(x0.saturating_add(n)).saturating_mul(px)) else { continue }; + transfer(lay.src, src_row, 1, 0, dst, lay.out, ech, ei, n); + } + } + } + Ok(()) +} + /// Converts `n` pixels of one decoded chunk row into output pixels (`plane` for planar data). fn convert_row(lay: &Layout, src: &[u8], dst: &mut [u8], n: usize, plane: usize) { let och = lay.out_channels(); @@ -1072,6 +1291,214 @@ custom_colortype!(Lab16, u16, PI::CIELab, &[16; 3], &[SampleFormat::Uint; 3], in custom_colortype!(LabA8, u8, PI::CIELab, &[8; 4], &[SampleFormat::Uint; 4], int); custom_colortype!(LabA16, u16, PI::CIELab, &[16; 4], &[SampleFormat::Uint; 4], int); +// Colour types with 1..=MAX_EXTRA_SAMPLES trailing extra samples (spot channels, extra alpha). +// One generic type per (sample, photometric, bit depth, total sample count) instead of a +// hand-written type for every layout. `N` is the total sample count, not the extra count. +const fn extra_photo(v: u16) -> PhotometricInterpretation { + match v { + 1 => PhotometricInterpretation::BlackIsZero, + 2 => PhotometricInterpretation::RGB, + 5 => PhotometricInterpretation::CMYK, + 8 => PhotometricInterpretation::CIELab, + _ => PhotometricInterpretation::RGB, + } +} + +trait ExtraKind: Copy + TiffValue + 'static { + const FORMAT: SampleFormat; + fn predict(row: &[Self], out: &mut Vec, samples: usize); +} + +impl ExtraKind for u8 { + const FORMAT: SampleFormat = SampleFormat::Uint; + fn predict(row: &[Self], out: &mut Vec, samples: usize) { + let n = samples.min(row.len()); + out.extend_from_slice(&row[..n]); + out.extend(row.iter().zip(&row[n..]).map(|(prev, current)| current.wrapping_sub(*prev))); + } +} + +impl ExtraKind for u16 { + const FORMAT: SampleFormat = SampleFormat::Uint; + fn predict(row: &[Self], out: &mut Vec, samples: usize) { + let n = samples.min(row.len()); + out.extend_from_slice(&row[..n]); + out.extend(row.iter().zip(&row[n..]).map(|(prev, current)| current.wrapping_sub(*prev))); + } +} + +impl ExtraKind for f32 { + const FORMAT: SampleFormat = SampleFormat::IEEEFP; + fn predict(row: &[Self], out: &mut Vec, _samples: usize) { + out.extend_from_slice(row); + } +} + +struct Extras(std::marker::PhantomData); + +impl TiffColorType for Extras +where + T: ExtraKind, +{ + type Inner = T; + const TIFF_VALUE: PhotometricInterpretation = extra_photo(PHOTO); + const BITS_PER_SAMPLE: &'static [u16] = &[BITS; N]; + const SAMPLE_FORMAT: &'static [SampleFormat] = &[T::FORMAT; N]; + fn horizontal_predict(row: &[Self::Inner], result: &mut Vec) { + T::predict(row, result, N); + } +} + +macro_rules! write_extras { + ($n:expr, $enc:expr, $w:expr, $h:expr, $data:expr, $tags:expr, $sample:ty, $photo:literal, $bits:literal, $base:literal) => { + match $n { + 1 => write_one::, K>($enc, $w, $h, $data, $tags), + 2 => write_one::, K>($enc, $w, $h, $data, $tags), + 3 => write_one::, K>($enc, $w, $h, $data, $tags), + 4 => write_one::, K>($enc, $w, $h, $data, $tags), + 5 => write_one::, K>($enc, $w, $h, $data, $tags), + 6 => write_one::, K>($enc, $w, $h, $data, $tags), + 7 => write_one::, K>($enc, $w, $h, $data, $tags), + 8 => write_one::, K>($enc, $w, $h, $data, $tags), + 9 => write_one::, K>($enc, $w, $h, $data, $tags), + 10 => write_one::, K>($enc, $w, $h, $data, $tags), + 11 => write_one::, K>($enc, $w, $h, $data, $tags), + 12 => write_one::, K>($enc, $w, $h, $data, $tags), + 13 => write_one::, K>($enc, $w, $h, $data, $tags), + 14 => write_one::, K>($enc, $w, $h, $data, $tags), + 15 => write_one::, K>($enc, $w, $h, $data, $tags), + 16 => write_one::, K>($enc, $w, $h, $data, $tags), + other => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported extra samples ({other})")).into()), + } + }; +} + +fn bytes_as_u16(b: &[u8]) -> Vec { + b.as_chunks::<2>().0.iter().map(|c| u16::from_ne_bytes(*c)).collect() +} + +fn bytes_as_f32(b: &[u8]) -> Vec { + b.as_chunks::<4>().0.iter().map(|c| f32::from_ne_bytes(*c)).collect() +} + +/// Interleaves colour (and alpha) samples with [`Metadata::extra_samples`]. +fn interleave_extras(img: &Image) -> Result, String> { + let (w, h) = img.dimensions(); + let n = (w as usize).checked_mul(h as usize).ok_or_else(|| "image size overflows".to_string())?; + let sb = img.sample_type().bytes(); + let ch = img.layout().channels(); + let extras = &img.meta.extra_samples; + let total = ch.checked_add(extras.len()).ok_or_else(|| "too many samples".to_string())?; + let px = total.checked_mul(sb).ok_or_else(|| "sample size overflows".to_string())?; + let mut out = vec![0u8; n.checked_mul(px).ok_or_else(|| "image size overflows".to_string())?]; + let base = img.data(); + let base_px = ch.saturating_mul(sb); + for i in 0..n { + let src = i.saturating_mul(base_px); + let dst = i.saturating_mul(px); + let Some(s) = base.get(src..src.saturating_add(base_px)) else { + return Err("image buffer is shorter than its dimensions".into()); + }; + let Some(d) = out.get_mut(dst..dst.saturating_add(base_px)) else { + return Err("extra-sample buffer is short".into()); + }; + d.copy_from_slice(s); + for (k, e) in extras.iter().enumerate() { + let es = i.saturating_mul(sb); + let ed = dst.saturating_add(base_px).saturating_add(k.saturating_mul(sb)); + let Some(s) = e.data.get(es..es.saturating_add(sb)) else { + return Err(format!("extra sample {k} is shorter than the image")); + }; + let Some(d) = out.get_mut(ed..ed.saturating_add(sb)) else { + return Err("extra-sample buffer is short".into()); + }; + d.copy_from_slice(s); + } + } + Ok(out) +} + +fn write_with_extras(enc: &mut TiffEncoder<&mut Cursor>, K>, img: &Image, tags: &TagSet<'_>) -> tiff::TiffResult<()> { + use ChannelLayout as L; + use SampleType as S; + let (w, h) = img.dimensions(); + let n = img.meta.extra_samples.len(); + if img.layout().is_lab() { + let file = lab_file(img); + let bytes = interleave_extras(&file).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + return match (file.layout(), file.sample_type()) { + (L::Lab, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 8, 8, 3), + (L::Lab, _) => { + let v = bytes_as_u16(&bytes); + write_extras!(n, enc, w, h, &v, tags, u16, 8, 16, 3) + } + (_, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 8, 8, 4), + _ => { + let v = bytes_as_u16(&bytes); + write_extras!(n, enc, w, h, &v, tags, u16, 8, 16, 4) + } + }; + } + let bytes = interleave_extras(img).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + match (img.layout(), img.sample_type()) { + (L::Gray, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 1, 8, 1), + (L::Gray, S::U16) => { + let v = bytes_as_u16(&bytes); + write_extras!(n, enc, w, h, &v, tags, u16, 1, 16, 1) + } + (L::Gray, S::F32) => { + let v = bytes_as_f32(&bytes); + write_extras!(n, enc, w, h, &v, tags, f32, 1, 32, 1) + } + (L::GrayA, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 1, 8, 2), + (L::GrayA, S::U16) => { + let v = bytes_as_u16(&bytes); + write_extras!(n, enc, w, h, &v, tags, u16, 1, 16, 2) + } + (L::GrayA, S::F32) => { + let v = bytes_as_f32(&bytes); + write_extras!(n, enc, w, h, &v, tags, f32, 1, 32, 2) + } + (L::Rgb, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 2, 8, 3), + (L::Rgb, S::U16) => { + let v = bytes_as_u16(&bytes); + write_extras!(n, enc, w, h, &v, tags, u16, 2, 16, 3) + } + (L::Rgb, S::F32) => { + let v = bytes_as_f32(&bytes); + write_extras!(n, enc, w, h, &v, tags, f32, 2, 32, 3) + } + (L::Rgba, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 2, 8, 4), + (L::Rgba, S::U16) => { + let v = bytes_as_u16(&bytes); + write_extras!(n, enc, w, h, &v, tags, u16, 2, 16, 4) + } + (L::Rgba, S::F32) => { + let v = bytes_as_f32(&bytes); + write_extras!(n, enc, w, h, &v, tags, f32, 2, 32, 4) + } + (L::Cmyk, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 5, 8, 4), + (L::Cmyk, S::U16) => { + let v = bytes_as_u16(&bytes); + write_extras!(n, enc, w, h, &v, tags, u16, 5, 16, 4) + } + (L::Cmyk, S::F32) => { + let v = bytes_as_f32(&bytes); + write_extras!(n, enc, w, h, &v, tags, f32, 5, 32, 4) + } + (L::CmykA, S::U8) => write_extras!(n, enc, w, h, &bytes, tags, u8, 5, 8, 5), + (L::CmykA, S::U16) => { + let v = bytes_as_u16(&bytes); + write_extras!(n, enc, w, h, &v, tags, u16, 5, 16, 5) + } + (L::CmykA, S::F32) => { + let v = bytes_as_f32(&bytes); + write_extras!(n, enc, w, h, &v, tags, f32, 5, 32, 5) + } + _ => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported extra samples ({n})")).into()), + } +} + struct TagSet<'a> { icc: Option<&'a [u8]>, /// The EXIF block's directories and IFD0 tags, written as the TIFF's own. @@ -1079,7 +1506,8 @@ struct TagSet<'a> { xmp: Option<&'a [u8]>, dpi: Option<(f32, f32)>, text: Vec<(Tag, &'a str)>, - alpha: bool, + /// ExtraSamples tag, including the unassociated-alpha marker when the image has alpha. + extra_samples: &'a [u16], photoshop_resources: Option<&'a [u8]>, photoshop_layers: Option<&'a [u8]>, } @@ -1109,9 +1537,8 @@ where im.y_resolution(Rational { n: (y * 1000.0).round() as u32, d: 1000 }); } let d = im.encoder(); - if tags.alpha { - // 2 = unassociated alpha - d.write_tag(Tag::ExtraSamples, &[2u16][..])?; + if !tags.extra_samples.is_empty() { + d.write_tag(Tag::ExtraSamples, tags.extra_samples)?; } if let Some(icc) = tags.icc { d.write_tag(Tag::IccProfile, Undefined(icc))?; @@ -1142,10 +1569,24 @@ where im.write_data(data) } +/// A Lab image as CIELab stores it: a* and b* signed, 8 or 16 bits (CIELab has no float form: +/// 32-bit Lab is written with 16 bits). Extra samples follow the new sample type. +fn lab_file(img: &Image) -> Image { + let sample = if img.sample_type() == SampleType::U8 { SampleType::U8 } else { SampleType::U16 }; + // `convert` brings the extra samples to the new sample type with the image. + let mut file = img.convert(img.layout(), sample); + let channels = file.layout().channels(); + convert_ab(file.data_mut(), channels, sample, true, true); + file +} + /// Writes the image with the colour type matching its layout and sample type. fn write_image(enc: &mut TiffEncoder<&mut Cursor>, K>, img: &Image, tags: &TagSet<'_>) -> tiff::TiffResult<()> { use ChannelLayout as L; use SampleType as S; + if !img.meta.extra_samples.is_empty() { + return write_with_extras::(enc, img, tags); + } let (w, h) = img.dimensions(); let u16s = || img.to_u16_samples().unwrap_or_default(); let f32s = || img.to_f32_samples().unwrap_or_default(); @@ -1170,13 +1611,9 @@ fn write_image(enc: &mut TiffEncoder<&mut Cursor>, K>, img: (L::CmykA, S::U16) => write_one::(enc, w, h, &u16s(), tags), (L::CmykA, S::F32) => write_one::(enc, w, h, &f32s(), tags), (L::Lab | L::LabA, _) => { - // CIELab has no float form: 32-bit Lab is written with 16 bits. - let sample = if img.sample_type() == S::U8 { S::U8 } else { S::U16 }; - let mut file = img.convert(img.layout(), sample); - let channels = file.layout().channels(); - convert_ab(file.data_mut(), channels, sample, true, true); + let file = lab_file(img); let u16s = || file.to_u16_samples().unwrap_or_default(); - match (file.layout(), sample) { + match (file.layout(), file.sample_type()) { (L::Lab, S::U8) => write_one::(enc, w, h, file.data(), tags), (L::Lab, _) => write_one::(enc, w, h, &u16s(), tags), (_, S::U8) => write_one::(enc, w, h, file.data(), tags), @@ -1198,11 +1635,16 @@ fn estimated_size(img: &Image, tags: &TagSet<'_>) -> u64 { + tags.exif.iter().flat_map(|e| e.ifd0.iter().chain(&e.exif).chain(&e.gps)).map(|f| f.value.len() as u64 + 12).sum::(); // Strip tables: one offset and one count per strip of about 1 MB. let tables = (img.data().len() as u64 / (1 << 20) + 1) * 16; - (img.data().len() as u64).saturating_add(payloads).saturating_add(text).saturating_add(tables).saturating_add(1 << 20) + let extras: u64 = img.meta.extra_samples.iter().map(|e| e.data.len() as u64).sum(); + (img.data().len() as u64).saturating_add(extras).saturating_add(payloads).saturating_add(text).saturating_add(tables).saturating_add(1 << 20) } pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { - let img = src.converted(plan.layout, plan.sample); + // `converted` brings the extra samples to the plan's sample type with the image. + encode_ready(&src.converted(plan.layout, plan.sample), opts) +} + +fn encode_ready(img: &Image, opts: &EncodeOptions) -> Result, CodecError> { let compression = match opts.tiff_compression { TiffCompression::None => tiff::encoder::Compression::Uncompressed, TiffCompression::Lzw => tiff::encoder::Compression::Lzw, @@ -1226,13 +1668,23 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result crate::MAX_EXTRA_SAMPLES { + return Err(CodecError::encode(F, format!("TIFF stores at most {} extra samples", crate::MAX_EXTRA_SAMPLES))); + } + let mut kinds = Vec::with_capacity(img.meta.extra_samples.len().saturating_add(1)); + if img.layout().has_alpha() { + kinds.push(2); + } + for e in &img.meta.extra_samples { + kinds.push(e.kind); + } let tags = TagSet { icc: if opts.embed_icc { img.icc.as_deref() } else { None }, exif: if opts.embed_metadata { img.meta.exif.as_deref().and_then(|e| tiff_exif::read(crate::orientation::tiff_body(e))) } else { None }, xmp: xmp.as_deref().map(str::as_bytes), dpi: if opts.embed_metadata { img.meta.dpi.filter(|d| d.0 > 0.0 && d.1 > 0.0) } else { None }, text, - alpha: img.layout().has_alpha(), + extra_samples: &kinds, // Document content, not metadata: written whenever present. photoshop_resources: img.meta.photoshop_resources.as_deref().filter(|r| !r.is_empty()), photoshop_layers: img.meta.photoshop_layers.as_deref().filter(|l| !l.is_empty()), @@ -1245,17 +1697,33 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result(&mut enc, &img, &tags)?; + write_image::(&mut enc, img, &tags)?; } else { let mut enc = TiffEncoder::new(&mut cursor)?.with_compression(compression).with_predictor(predictor); - write_image::(&mut enc, &img, &tags)?; + write_image::(&mut enc, img, &tags)?; } Ok(cursor.into_inner()) }; - let big = opts.tiff_bigtiff || estimated_size(&img, &tags) > CLASSIC_LIMIT; + let big = opts.tiff_bigtiff || estimated_size(img, &tags) > CLASSIC_LIMIT; match write(big) { Ok(v) => Ok(v), Err(tiff::TiffError::IntSizeError) if !big => write(true).map_err(|e| CodecError::encode(F, e)), Err(e) => Err(CodecError::encode(F, e)), } } + +#[cfg(test)] +mod bits_len { + use super::Extras; + use tiff::encoder::colortype::ColorType as TiffColorType; + + #[test] + fn const_generic_sample_tables_have_one_entry_per_sample() { + // A repeat expression in an associated const (`&[BITS; N]`) has, on some compilers, + // promoted to a slice shorter than `N`. The encoder sizes every strip from that length. + assert_eq!( as TiffColorType>::BITS_PER_SAMPLE.len(), 4, "{:?}", as TiffColorType>::BITS_PER_SAMPLE); + assert_eq!( as TiffColorType>::BITS_PER_SAMPLE.len(), 5); + assert_eq!( as TiffColorType>::BITS_PER_SAMPLE.len(), 19); + assert_eq!( as TiffColorType>::SAMPLE_FORMAT.len(), 6); + } +} diff --git a/crates/codecs/src/image.rs b/crates/codecs/src/image.rs index 5a03e7d283..a15ab72779 100644 --- a/crates/codecs/src/image.rs +++ b/crates/codecs/src/image.rs @@ -145,6 +145,24 @@ pub struct Metadata { /// Photoshop layer data (TIFF tag 37724 `ImageSourceData`): a layered TIFF's layers. Kept /// opaque here; `photocraft-io` reads and writes it through `photocraft-psd`. pub photoshop_layers: Option>, + /// Samples per pixel beyond the colour channels and the one alpha sample. TIFF extra + /// samples (spot colours, extra alpha channels) the pixel layout does not hold. Each entry + /// is one sample per pixel, native endian, in the image's [`SampleType`], row-major. + pub extra_samples: Vec, +} + +/// How many extra TIFF samples an encoded file may carry. Decoders keep at most this many. +/// Sixteen covers a UV-DTF stack (white, varnish, gloss, primer, and further spots) without +/// approaching the PSD 56-channel limit. +pub const MAX_EXTRA_SAMPLES: usize = 16; + +/// One TIFF extra sample (a spot channel or an alpha channel that is not the image alpha). +#[derive(Debug, Clone, PartialEq)] +pub struct ExtraSample { + /// TIFF ExtraSamples value: 0 unspecified, 1 associated alpha, 2 unassociated alpha. + pub kind: u16, + /// One sample per pixel, native endian, same sample type as the image. + pub data: Vec, } impl Metadata { @@ -155,6 +173,7 @@ impl Metadata { && self.text.is_empty() && self.photoshop_resources.is_none() && self.photoshop_layers.is_none() + && self.extra_samples.is_empty() } } @@ -639,6 +658,17 @@ impl Image { let values = convert_layout(&src, self.layout, layout); quantize(&values, sample) }; + let mut meta = self.meta.clone(); + if sample != self.sample { + // Extra samples are stored in the image's sample type, so they convert with it. A + // plane of the wrong size is left as it is: importers drop it with a warning. + let plane_len = (self.width as usize).saturating_mul(self.height as usize).saturating_mul(self.sample.bytes()); + for e in meta.extra_samples.iter_mut().filter(|e| e.data.len() == plane_len) { + if let Ok(plane) = Image::from_raw(self.width, self.height, ChannelLayout::Gray, self.sample, std::mem::take(&mut e.data)) { + e.data = plane.convert(ChannelLayout::Gray, sample).data; + } + } + } Image { width: self.width, height: self.height, @@ -646,7 +676,7 @@ impl Image { sample, data, icc: if layout.same_model(self.layout) { self.icc.clone() } else { None }, - meta: self.meta.clone(), + meta, warnings: self.warnings.clone(), } } diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 8c06694b9a..5c0e37b0db 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -36,7 +36,8 @@ pub use crate::exif_color::{EXIF_COLOR_SPACE_SRGB, exif_color_space}; pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_with}; pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect, from_extension}; pub use crate::image::{ - ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, Image, Metadata, SampleType, + ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, ExtraSample, Image, + MAX_EXTRA_SAMPLES, Metadata, SampleType, }; pub use crate::options::{ DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, Limits, PngCompression, PngStereo, TiffCompression, diff --git a/crates/codecs/src/orientation.rs b/crates/codecs/src/orientation.rs index 3d10d5ddea..7f31a6b271 100644 --- a/crates/codecs/src/orientation.rs +++ b/crates/codecs/src/orientation.rs @@ -331,6 +331,12 @@ impl Image { } let data = orient_bytes(self.data(), bpp, o, (w, h), ow)?; let mut meta = self.meta.clone(); + // Extra samples (a TIFF's alpha and spot planes, one sample a pixel) turn with the image. + // A plane of the wrong size is left as it is: importers drop it with a warning. + let plane_len = w.saturating_mul(h).saturating_mul(sample.bytes()); + for e in meta.extra_samples.iter_mut().filter(|e| e.data.len() == plane_len) { + e.data = orient_bytes(&e.data, sample.bytes(), o, (w, h), ow)?; + } if let Some(e) = &mut meta.exif && let Cow::Owned(fixed) = upright_exif(e) { diff --git a/crates/codecs/tests/orientation.rs b/crates/codecs/tests/orientation.rs index c1f176b87c..0532b44066 100644 --- a/crates/codecs/tests/orientation.rs +++ b/crates/codecs/tests/orientation.rs @@ -211,6 +211,25 @@ fn png_opens_upright_for_every_orientation() { } } +/// Extra samples (a TIFF's alpha and spot planes) turn with the image, so a channel stays +/// aligned with the pixels for every orientation. +#[test] +fn extra_samples_turn_with_the_image() { + let (w, h) = (4, 7); + let up = exact_scene(w, h); + let up_extra: Vec = up.iter().map(|v| 255 - v).collect(); + for o in 1..=8u16 { + let (s, sw, sh) = stored(&up, w, h, o); + let (s_extra, _, _) = stored(&up_extra, w, h, o); + let mut img = gray(sw, sh, s); + img.meta.extra_samples = vec![ExtraSample { kind: 0, data: s_extra }]; + let turned = img.oriented(o).unwrap(); + assert_eq!(turned.data(), &up[..], "o={o}"); + assert_eq!(turned.meta.extra_samples.len(), 1, "o={o}"); + assert_eq!(turned.meta.extra_samples[0].data, up_extra, "o={o}"); + } +} + #[test] fn tiff_opens_upright_for_every_orientation() { let (w, h) = (4, 7); diff --git a/crates/codecs/tests/tiff_lab.rs b/crates/codecs/tests/tiff_lab.rs index 7076633ef5..9e41ef80b2 100644 --- a/crates/codecs/tests/tiff_lab.rs +++ b/crates/codecs/tests/tiff_lab.rs @@ -74,3 +74,36 @@ fn lab_converts_to_rgb_for_other_formats() { assert_eq!(&p[4..7], &[255, 255, 255], "white"); assert!(p[0] > 180 && p[1] < 120 && p[2] > 140, "L 50, a 50, b −30 is a magenta-ish purple: {:?}", &p[..3]); } + +#[test] +fn lab_keeps_extra_samples() { + // A spot plate next to Lab: written as CIELab plus one unspecified extra sample, and read + // back as Lab with the spot (not as LabA). + for (layout, sample) in [(ChannelLayout::Lab, SampleType::U8), (ChannelLayout::LabA, SampleType::U16)] { + let px: Vec = + [lab(50.0, 50.0, -30.0), lab(100.0, 0.0, 0.0)].iter().flat_map(|p| p.iter().copied().chain(layout.has_alpha().then_some(0.5))).collect(); + let mut img = Image::from_normalized(2, 1, layout, sample, &px).unwrap(); + let spot: Vec = (0..2 * sample.bytes()).map(|i| (i * 37 + 5) as u8).collect(); + img.meta.extra_samples = vec![ExtraSample { kind: 0, data: spot.clone() }]; + let file = uncompressed(&img); + if layout == ChannelLayout::Lab { + assert!(find(&file, &[128, 50, (-30i8) as u8, spot[0], 255, 0, 0, spot[1]]).is_some(), "CIELab samples with the spot"); + } + let back = decode(&file).unwrap(); + assert_eq!((back.layout(), back.sample_type()), (layout, sample)); + let (a, b) = (img.to_normalized(), back.to_normalized()); + assert!(a.iter().zip(&b).all(|(x, y)| (x - y).abs() <= 1.5 / 65535.0), "{layout:?}: {a:?} {b:?}"); + assert_eq!(back.meta.extra_samples, vec![ExtraSample { kind: 0, data: spot }], "{layout:?}"); + } +} + +#[test] +fn float_lab_writes_its_extra_samples_with_16_bits() { + let px: Vec = [lab(50.0, 50.0, -30.0), lab(100.0, 0.0, 0.0)].concat(); + let mut img = Image::from_normalized(2, 1, ChannelLayout::Lab, SampleType::F32, &px).unwrap(); + img.meta.extra_samples = vec![ExtraSample { kind: 0, data: [0.25f32, 1.0].iter().flat_map(|v| v.to_ne_bytes()).collect() }]; + let back = decode(&uncompressed(&img)).unwrap(); + assert_eq!((back.layout(), back.sample_type()), (ChannelLayout::Lab, SampleType::U16)); + let spot: Vec = [16384u16, 65535].iter().flat_map(|v| v.to_ne_bytes()).collect(); + assert_eq!(back.meta.extra_samples, vec![ExtraSample { kind: 0, data: spot }]); +} diff --git a/crates/codecs/tests/tiff_pages.rs b/crates/codecs/tests/tiff_pages.rs index 60885e527d..dce4317a8c 100644 --- a/crates/codecs/tests/tiff_pages.rs +++ b/crates/codecs/tests/tiff_pages.rs @@ -128,13 +128,16 @@ fn planar_strips_at_every_depth() { } } +/// Extra samples that are not the alpha (ExtraSamples 0: a spot colour or an extra channel) are +/// not part of the image: they come back in `meta.extra_samples`, one plane each. #[test] -fn extra_samples_that_are_not_alpha_are_dropped() { +fn extra_samples_that_are_not_alpha_are_kept_apart() { let (w, h) = (5usize, 3usize); let t = truth(w * h * 5, 4); let rgb_of = |spp: usize, keep: usize| -> Vec { t.u8s[..w * h * spp].chunks(spp).flat_map(|p| p[..keep].to_vec()).collect() }; + let extra = |spp: usize, at: usize| vec![ExtraSample { kind: 0, data: t.u8s[..w * h * spp].chunks(spp).map(|p| p[at]).collect() }]; for planar in [false, true] { - // RGB + one unspecified extra sample: RGB. + // RGB + one unspecified extra sample: RGB, and the sample as an extra plane. let px = &t.u8s[..w * h * 4]; let chunks = if planar { planar_strips(px, w, h, 4, 1, 2) } else { px.chunks(w * 4 * 2).map(<[u8]>::to_vec).collect() }; let mut d = Dir { entries: base(w as u32, h as u32, 8, 4, 2), chunks, tiled: false }.tag(278, LONG, &[2]).tag(338, SHORT, &[0]); @@ -144,7 +147,8 @@ fn extra_samples_that_are_not_alpha_are_dropped() { let img = decode_ok(&build(true, false, &[d], &[0]).bytes); assert_eq!(img.layout(), ChannelLayout::Rgb); assert_eq!(img.data(), &rgb_of(4, 3)[..], "planar {planar}"); - // RGB + alpha + an unspecified extra sample: RGBA. + assert_eq!(img.meta.extra_samples, extra(4, 3), "planar {planar}"); + // RGB + alpha + an unspecified extra sample: RGBA and one extra plane. let px = &t.u8s[..w * h * 5]; let chunks = if planar { planar_strips(px, w, h, 5, 1, 2) } else { px.chunks(w * 5 * 2).map(<[u8]>::to_vec).collect() }; let mut d = Dir { entries: base(w as u32, h as u32, 8, 5, 2), chunks, tiled: false }.tag(278, LONG, &[2]).tag(338, SHORT, &[2, 0]); @@ -154,18 +158,22 @@ fn extra_samples_that_are_not_alpha_are_dropped() { let img = decode_ok(&build(false, true, &[d], &[0]).bytes); assert_eq!(img.layout(), ChannelLayout::Rgba); assert_eq!(img.data(), &rgb_of(5, 4)[..], "planar {planar}"); + assert_eq!(img.meta.extra_samples, extra(5, 4), "planar {planar}"); } - // Gray + alpha + extra: gray and alpha; gray + an unspecified extra: gray. + // Gray + alpha + extra: gray and alpha; gray + an unspecified extra: gray. Each keeps the + // extra sample as a plane. let px = &t.u8s[..w * h * 3]; let d = strips(w as u32, h as u32, 8, 3, 1, 3, px).tag(338, SHORT, &[2, 0]); let img = decode_ok(&build(true, false, &[d], &[0]).bytes); assert_eq!(img.layout(), ChannelLayout::GrayA); assert_eq!(img.data(), &rgb_of(3, 2)[..]); + assert_eq!(img.meta.extra_samples, extra(3, 2)); let px = &t.u8s[..w * h * 2]; let d = strips(w as u32, h as u32, 8, 2, 1, 3, px).tag(338, SHORT, &[0]); let img = decode_ok(&build(true, false, &[d], &[0]).bytes); assert_eq!(img.layout(), ChannelLayout::Gray); assert_eq!(img.data(), &rgb_of(2, 1)[..]); + assert_eq!(img.meta.extra_samples, extra(2, 1)); } #[test] diff --git a/crates/codecs/tests/tiff_photoshop.rs b/crates/codecs/tests/tiff_photoshop.rs index 400b72eb0c..82f4b74e7d 100644 --- a/crates/codecs/tests/tiff_photoshop.rs +++ b/crates/codecs/tests/tiff_photoshop.rs @@ -41,6 +41,187 @@ fn tags_round_trip_through_the_encoder() { } } +#[test] +fn extra_samples_round_trip() { + for (layout, sample) in [ + (ChannelLayout::Rgb, SampleType::U8), + (ChannelLayout::Rgba, SampleType::U8), + (ChannelLayout::Gray, SampleType::U16), + (ChannelLayout::Cmyk, SampleType::F32), + ] { + let mut img = synth(4, 3, layout, sample, 2, 0.4); + let n = 4 * 3; + let b = sample.bytes(); + let data: Vec = (0..n * b).map(|i| (i * 17) as u8).collect(); + img.meta.extra_samples = vec![ExtraSample { kind: 0, data: data.clone() }]; + let bytes = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap(); + let back = decode(&bytes).unwrap(); + assert_eq!(back.layout(), layout, "{layout:?} {sample:?}"); + assert_eq!(back.data(), img.data(), "{layout:?} {sample:?}"); + assert_eq!(back.meta.extra_samples.len(), 1, "{layout:?} {sample:?}"); + assert_eq!(back.meta.extra_samples[0].kind, 0, "{layout:?} {sample:?}"); + assert_eq!(back.meta.extra_samples[0].data, data, "{layout:?} {sample:?}"); + } +} + +/// Tall enough that the default strip size (about 1 MB) cannot hold every row, so a writer +/// that only fills the first strip, or predicts across the wrong sample count, cannot hide. +/// The spot plane is checked with the `tiff` crate, not PhotoCraft's decoder. +#[test] +fn multi_strip_spot_round_trip_and_dump() { + let w = 800u32; + let h = 400u32; + let n = (w as usize) * (h as usize); + for (layout, channels) in [(ChannelLayout::Rgb, 3usize), (ChannelLayout::Rgba, 4usize)] { + let mut px = vec![0u8; n * channels]; + let mut spot = vec![0u8; n]; + for y in 0..h as usize { + for x in 0..w as usize { + let i = y * w as usize + x; + px[i * channels] = (x % 251) as u8; + px[i * channels + 1] = (y % 251) as u8; + px[i * channels + 2] = 40; + if channels == 4 { + px[i * channels + 3] = if x > 20 && x < 780 && y > 10 && y + 10 < h as usize { 255 } else { 0 }; + } + spot[i] = ((x * 3 + y * 17) % 251) as u8; + } + } + let mut img = Image::from_u8(w, h, layout, px).unwrap(); + img.meta.extra_samples = vec![ExtraSample { kind: 0, data: spot.clone() }]; + for compression in [TiffCompression::None, TiffCompression::Deflate, TiffCompression::Lzw, TiffCompression::PackBits] { + let bytes = encode(&img, Format::Tiff, &EncodeOptions { tiff_compression: compression, ..Default::default() }).unwrap(); + let label = format!("{layout:?} {compression:?}"); + let back = decode(&bytes).unwrap(); + assert_eq!(back.meta.extra_samples.len(), 1, "{label}"); + assert_eq!(back.meta.extra_samples[0].data, spot, "own decoder {label}"); + assert_eq!(back.data(), img.data(), "own decoder rgb {label}"); + let mut dec = tiff::decoder::Decoder::new(std::io::Cursor::new(bytes.as_slice())).unwrap(); + let spp: u16 = dec.get_tag_unsigned(tiff::tags::Tag::SamplesPerPixel).unwrap(); + let bps = dec.get_tag_u16_vec(tiff::tags::Tag::BitsPerSample).unwrap(); + let extra = dec.get_tag_u16_vec(tiff::tags::Tag::ExtraSamples).unwrap(); + let rows = dec.find_tag_unsigned::(tiff::tags::Tag::RowsPerStrip).unwrap(); + assert_eq!(bps.len(), spp as usize, "{label}"); + assert_eq!(spp as usize, channels + 1, "{label}"); + assert_eq!(*extra.last().unwrap(), 0, "{label} spot ExtraSamples {extra:?}"); + assert!(rows.is_some_and(|r| r < h) || compression == TiffCompression::PackBits, "{label} rows {rows:?}"); + let patched = min_is_black(&bytes); + let mut indep = tiff::decoder::Decoder::new(std::io::Cursor::new(patched.as_slice())).unwrap(); + let tiff::decoder::DecodingResult::U8(samples) = indep.read_image().unwrap() else { panic!("{label} not u8") }; + let spp = spp as usize; + assert_eq!(samples.len(), n * spp, "{label}"); + let mut bad = 0usize; + let mut first = None; + for (i, want) in spot.iter().enumerate() { + let got = samples.get(i * spp + spp - 1).copied(); + if got != Some(*want) { + bad += 1; + first.get_or_insert((i, got)); + } + } + assert_eq!(bad, 0, "{label} independent reader, first {first:?}"); + } + } +} + +/// Retag photometric interpretation 262 as MinIsBlack so `tiff`'s decoder returns every sample. +fn min_is_black(src: &[u8]) -> Vec { + let mut bytes = src.to_vec(); + let le = bytes.first().copied() == Some(b'I'); + let ru16 = |b: &[u8], i: usize| -> Option { + let s = b.get(i..i + 2)?; + Some(if le { u16::from_le_bytes([s[0], s[1]]) } else { u16::from_be_bytes([s[0], s[1]]) }) + }; + let ru32 = |b: &[u8], i: usize| -> Option { + let s = b.get(i..i + 4)?; + Some(if le { u32::from_le_bytes(s.try_into().ok()?) } else { u32::from_be_bytes(s.try_into().ok()?) }) + }; + let Some(ifd) = ru32(&bytes, 4) else { return bytes }; + let Some(n) = ru16(&bytes, ifd as usize) else { return bytes }; + for e in 0..n as usize { + let at = ifd as usize + 2 + e * 12; + if ru16(&bytes, at) == Some(262) { + let value = if le { 1u16.to_le_bytes() } else { 1u16.to_be_bytes() }; + if let Some(slot) = bytes.get_mut(at + 8..at + 10) { + slot.copy_from_slice(&value); + } + break; + } + } + bytes +} + +#[test] +fn more_than_sixteen_extra_samples_is_refused() { + let mut img = synth(2, 2, ChannelLayout::Rgb, SampleType::U8, 1, 0.0); + img.meta.extra_samples = (0..MAX_EXTRA_SAMPLES + 1).map(|_| ExtraSample { kind: 0, data: vec![0; 4] }).collect(); + assert!(encode(&img, Format::Tiff, &EncodeOptions::default()).is_err()); +} + +#[test] +fn sixteen_extra_samples_round_trip() { + for (layout, sample, base) in [ + (ChannelLayout::Rgb, SampleType::U8, 3usize), + (ChannelLayout::Rgba, SampleType::U8, 4), + (ChannelLayout::Gray, SampleType::U16, 1), + (ChannelLayout::Cmyk, SampleType::F32, 4), + ] { + let mut img = synth(2, 2, layout, sample, 1, 0.0); + let n = 2 * 2 * sample.bytes(); + img.meta.extra_samples = (0..MAX_EXTRA_SAMPLES).map(|k| ExtraSample { kind: 0, data: vec![k as u8; n] }).collect(); + let bytes = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap(); + let back = decode(&bytes).unwrap(); + assert_eq!(back.layout(), layout, "{layout:?} {sample:?} base {base}"); + assert_eq!(back.data(), img.data(), "{layout:?}"); + assert_eq!(back.meta.extra_samples.len(), MAX_EXTRA_SAMPLES, "{layout:?}"); + assert_eq!(back.meta.extra_samples[7].kind, 0, "{layout:?}"); + assert_eq!(back.meta.extra_samples[15].data, vec![15; n], "{layout:?}"); + } +} + +/// 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. +#[test] +fn extra_samples_count_against_the_allocation_limit() { + let (w, h) = (64u32, 64u32); + 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(); + let bytes = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap(); + let with = |max_alloc: u64| decode_with(&bytes, &DecodeOptions { limits: Limits { max_alloc, ..Limits::default() }, ..DecodeOptions::default() }); + // 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); +} + +/// Converting an image's sample type converts its extra samples with it, so they keep matching +/// the image: a 16-bit float TIFF's spot planes survive the 32-bit float a layered import uses. +#[test] +fn extra_samples_follow_a_sample_type_conversion() { + let (w, h) = (3u32, 2u32); + let n = (w * h) as usize; + let values = [0.0f32, 0.25, 0.5, 0.75, 1.0, 0.125]; + let half = |v: f32| f16::from_f32(v).to_bits().to_ne_bytes(); + let rgb: Vec = (0..n * 3).flat_map(|_| half(0.5)).collect(); + let mut img = Image::from_raw(w, h, ChannelLayout::Rgb, SampleType::F16, rgb).unwrap(); + img.meta.extra_samples = vec![ExtraSample { kind: 0, data: values.iter().flat_map(|v| half(*v)).collect() }]; + + let wide = img.convert(ChannelLayout::Rgb, SampleType::F32); + let plane: Vec = wide.meta.extra_samples[0].data.as_chunks::<4>().0.iter().map(|c| f32::from_ne_bytes(*c)).collect(); + assert_eq!(plane, values); + + // To 8 bits, the plane quantizes exactly as a gray image of the same values does. + let narrow = wide.convert(ChannelLayout::Rgb, SampleType::U8); + let gray = Image::from_raw(w, h, ChannelLayout::Gray, SampleType::F32, wide.meta.extra_samples[0].data.clone()).unwrap(); + assert_eq!(narrow.meta.extra_samples[0].data, gray.convert(ChannelLayout::Gray, SampleType::U8).data()); + assert_eq!(narrow.meta.extra_samples[0].data.len(), n); +} + #[test] fn absent_and_empty_tags_are_not_written() { let mut img = synth(4, 4, ChannelLayout::Rgb, SampleType::U8, 1, 0.0);