diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rs index 1cfa38bc10..7fef6f17b2 100644 --- a/crates/codecs/src/codecs/tiff.rs +++ b/crates/codecs/src/codecs/tiff.rs @@ -1373,12 +1373,26 @@ macro_rules! write_extras { }; } -fn bytes_as_u16(b: &[u8]) -> Vec { - b.as_chunks::<2>().0.iter().map(|c| u16::from_ne_bytes(*c)).collect() +/// An empty buffer with room for `len` elements, allocated fallibly: a save too large for memory +/// is an error, not an abort. +fn try_with_capacity(len: usize) -> io::Result> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| io::Error::new(io::ErrorKind::OutOfMemory, format!("cannot allocate {len} samples for the extra samples")))?; + Ok(v) } -fn bytes_as_f32(b: &[u8]) -> Vec { - b.as_chunks::<4>().0.iter().map(|c| f32::from_ne_bytes(*c)).collect() +fn bytes_as_u16(b: &[u8]) -> io::Result> { + let chunks = b.as_chunks::<2>().0; + let mut v = try_with_capacity(chunks.len())?; + v.extend(chunks.iter().map(|c| u16::from_ne_bytes(*c))); + Ok(v) +} + +fn bytes_as_f32(b: &[u8]) -> io::Result> { + let chunks = b.as_chunks::<4>().0; + let mut v = try_with_capacity(chunks.len())?; + v.extend(chunks.iter().map(|c| f32::from_ne_bytes(*c))); + Ok(v) } /// Interleaves colour (and alpha) samples with [`Metadata::extra_samples`]. @@ -1390,7 +1404,9 @@ fn interleave_extras(img: &Image) -> Result, String> { 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 len = n.checked_mul(px).ok_or_else(|| "image size overflows".to_string())?; + let mut out = try_with_capacity::(len).map_err(|e| e.to_string())?; + out.resize(len, 0); let base = img.data(); let base_px = ch.saturating_mul(sb); for i in 0..n { @@ -1429,12 +1445,12 @@ fn write_with_extras(enc: &mut TiffEncoder<&mut Cursor>, K> 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); + 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); + let v = bytes_as_u16(&bytes)?; write_extras!(n, enc, w, h, &v, tags, u16, 8, 16, 4) } }; @@ -1443,56 +1459,56 @@ fn write_with_extras(enc: &mut TiffEncoder<&mut Cursor>, K> 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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); + 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()), @@ -1727,3 +1743,18 @@ mod bits_len { assert_eq!( as TiffColorType>::SAMPLE_FORMAT.len(), 6); } } + +#[cfg(test)] +mod extra_sample_buffers { + use super::try_with_capacity; + + /// The extra-sample writer's buffers are allocated fallibly: a size no allocation can serve + /// is an out-of-memory error the save reports, not an abort. + #[test] + fn an_impossible_buffer_is_an_error() { + let err = try_with_capacity::(usize::MAX).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::OutOfMemory); + assert!(try_with_capacity::(usize::MAX / 2).is_err()); + assert!(try_with_capacity::(64).is_ok_and(|v| v.is_empty() && v.capacity() >= 64)); + } +} diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 20bee05515..1d47eb9a31 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -321,6 +321,11 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr if has_alpha && !write_alpha { drop_merged_transparency(&mut resources); } + // Past MAX_EXTRA_SAMPLES the TIFF stores only the first `kept` channels: the name and + // DisplayInfo resources describe just those, and a Quick Mask among the rest is dropped. + if extra_n > kept { + keep_first_channels(&mut resources, kept, cc); + } let resources = resources_to_bytes(&resources)?; let ifd_channels = cc + usize::from(write_alpha); let sample = csample(fmt.sample); @@ -424,6 +429,48 @@ fn drop_first_unicode(data: &[u8]) -> Vec { data.get(end..).unwrap_or(data).to_vec() } +/// Trims the channel-name resources (1006, 1045) and DisplayInfo (1077) to their first `kept` +/// entries, and drops Quick Mask info (1022) when its channel is not one of the `kept` extra +/// samples, which start at sample `first_extra`. A resource too short for `kept` entries is +/// left as it is. +fn keep_first_channels(resources: &mut Vec, kept: usize, first_extra: usize) { + for r in resources.iter_mut() { + r.data = match r.id { + 1006 => first_pascal_names(&r.data, kept), + 1045 => first_unicode_names(&r.data, kept), + id if id == crate::channel_map::DISPLAY_INFO => first_display_records(&r.data, kept), + _ => continue, + }; + } + let end = first_extra.saturating_add(kept); + resources.retain(|r| r.id != crate::channel_map::QUICK_MASK_INFO || r.data.get(..2).is_none_or(|b| usize::from(u16::from_be_bytes([b[0], b[1]])) < end)); +} + +fn first_pascal_names(data: &[u8], n: usize) -> Vec { + let mut at = 0usize; + for _ in 0..n { + let Some(&len) = data.get(at) else { return data.to_vec() }; + at = at.saturating_add(1).saturating_add(usize::from(len)); + } + data.get(..at).unwrap_or(data).to_vec() +} + +fn first_unicode_names(data: &[u8], n: usize) -> Vec { + let mut at = 0usize; + for _ in 0..n { + let Some(b) = data.get(at..at.saturating_add(4)) else { return data.to_vec() }; + let len = u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize; + at = at.saturating_add(4).saturating_add(len.saturating_mul(2)); + } + data.get(..at).unwrap_or(data).to_vec() +} + +/// Resource 1077: a 4-byte version, then 13-byte records. Keeps the first `n` records. +fn first_display_records(data: &[u8], n: usize) -> Vec { + let end = 4usize.saturating_add(n.saturating_mul(13)); + data.get(..end).unwrap_or(data).to_vec() +} + /// Resource 1077: a 4-byte version, then 13-byte records. Drops the first record. fn drop_first_display_record(data: &[u8]) -> Vec { const RECORD: usize = 13; diff --git a/crates/io/tests/it/tiff_layers.rs b/crates/io/tests/it/tiff_layers.rs index f1d8f7dc46..4f2a627d07 100644 --- a/crates/io/tests/it/tiff_layers.rs +++ b/crates/io/tests/it/tiff_layers.rs @@ -1047,3 +1047,56 @@ fn layered_tiff_nested_past_the_cap_is_rejected() { let r = import("hundred.tif", &tiff_nested(100)).unwrap(); assert_eq!(r.document.max_group_depth(), 100); } + +/// Past MAX_EXTRA_SAMPLES (16), a layered TIFF stores the first 16 extra channels. Its channel +/// resources must describe those 16 and no more: 16 names in 1006 and 1045, 16 DisplayInfo +/// records and 16 identifiers, and no Quick Mask record for a Quick Mask that wasn't stored. +#[test] +fn channels_past_sixteen_leave_no_resources_behind() { + use photocraft_color::PixelFormat; + use photocraft_doc::{AlphaChannel, Layer}; + use photocraft_geom::{Rect, Size}; + use photocraft_raster::Surface; + + let mut doc = Document::new("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let fmt = doc.pixel_format(); + let mut art = Surface::new(fmt); + art.fill_rect(Rect::new(0, 0, 8, 8), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + doc.layers.push(Layer::new("Art", LayerContent::Raster(art))); + let gray = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false); + for i in 1..=18 { + doc.channels.push(AlphaChannel::new(format!("Alpha {i}"), Surface::new(gray))); + } + doc.quick_mask = Some(AlphaChannel::new("Quick Mask", Surface::new(gray))); + + let r = tiff(&doc, true); + assert!(r.warnings.iter().any(|w| w.contains("19 extra channels") && w.contains("first 16")), "{:?}", r.warnings); + let (resources, _) = tags(&r.bytes); + let (resources, _) = photocraft_psd::tiff::resources_from_bytes(&resources.expect("resources")).expect("parse resources"); + let data = |id: u16| resources.iter().find(|r| r.id == id).map(|r| r.data.clone()).unwrap_or_default(); + let pascal = data(1006); + let (mut at, mut names) = (0usize, 0usize); + while let Some(&len) = pascal.get(at) { + at += 1 + usize::from(len); + names += 1; + } + assert_eq!(names, 16, "1006"); + let unicode = data(1045); + let (mut at, mut names) = (0usize, 0usize); + while let Some(b) = unicode.get(at..at + 4) { + at += 4 + 2 * u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize; + names += 1; + } + assert_eq!(names, 16, "1045"); + assert_eq!(data(1077).len(), 4 + 16 * 13, "1077"); + assert_eq!(data(1053).len(), 16 * 4, "1053"); + assert!(resources.iter().all(|r| r.id != 1022), "the Quick Mask was not stored, so its record goes"); + + let flat = photocraft_codecs::decode(&r.bytes).expect("decode"); + assert_eq!(flat.meta.extra_samples.len(), 16); + let back = import("x.tif", &r.bytes).expect("import").document; + let names: Vec<&str> = back.channels.iter().map(|c| c.name.as_str()).collect(); + let want: Vec = (1..=16).map(|i| format!("Alpha {i}")).collect(); + assert_eq!(names, want.iter().map(String::as_str).collect::>()); + assert!(back.quick_mask.is_none()); +}