diff --git a/Cargo.lock b/Cargo.lock index ee31aa401..70a520379 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3464,9 +3464,11 @@ dependencies = [ name = "craft-tiff" version = "0.1.0" dependencies = [ + "image", "proptest", "serde", "thiserror 2.0.21", + "tiff", ] [[package]] diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 46d510342..bab74d286 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -43,7 +43,7 @@ zune-core = "0.5" jpeg-encoder = "0.6" craft-jpeg = { workspace = true } craft-metadata = { workspace = true } -craft-tiff = { workspace = true } +craft-tiff = { workspace = true, features = ["plain-rgba16"] } zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] } craft-heif = { workspace = true, optional = true } craft-jxl = { workspace = true, optional = true, features = ["decode"] } diff --git a/crates/image-codecs/src/codecs/tiff.rs b/crates/image-codecs/src/codecs/tiff.rs index 1856ae0d4..dc537d2fd 100644 --- a/crates/image-codecs/src/codecs/tiff.rs +++ b/crates/image-codecs/src/codecs/tiff.rs @@ -29,7 +29,7 @@ //! (see [`writes_little_endian`]), which the layer data must match. use std::borrow::Cow; -use std::io::{self, Cursor, Read, Seek, SeekFrom}; +use std::io::{self, Read, Seek, SeekFrom}; use half::f16; use tiff::decoder::{ChunkType, Decoder}; @@ -257,52 +257,9 @@ macro_rules! custom_colortype { use PhotometricInterpretation as PI; -/// Encode straight, native-endian RGBA16 samples as an uncompressed classic TIFF, with the -/// underlying encoder's default strip layout and no extra tags such as ICC or ExtraSamples. -/// This preserves the plain legacy TIFF representation; use the general encoder for new files -/// that need an explicit unassociated-alpha tag, metadata or BigTIFF. +/// 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, CodecError> { - let expected = u64::from(width).checked_mul(u64::from(height)).and_then(|n| n.checked_mul(4)).and_then(|n| usize::try_from(n).ok()); - if width == 0 || height == 0 || expected != Some(samples.len()) { - return Err(CodecError::encode(F, "invalid dimensions or RGBA16 sample count")); - } - let mut out = Cursor::new(Vec::new()); - TiffEncoder::new(&mut out) - .and_then(|mut encoder| encoder.write_image::(width, height, samples)) - .map_err(|error| CodecError::encode(F, error))?; - Ok(out.into_inner()) -} - -#[cfg(test)] -mod plain_rgba16_tests { - use super::*; - - #[test] - fn plain_rgba16_keeps_uncompressed_legacy_strips_and_rgba_samples() { - // Self-generated straight RGBA data; tall enough for the encoder's second strip. - let (width, height) = (4, 31_253); - let samples: Vec = std::iter::repeat_n([0x12ab, 0xcdef, 0x3142, 0x8000], (width * height) as usize).flatten().collect(); - let bytes = encode_plain_rgba16(width, height, &samples).unwrap(); - let mut reader = tiff::decoder::Decoder::new(Cursor::new(bytes)).unwrap(); - use tiff::tags::Tag; - assert_eq!(reader.dimensions().unwrap(), (width, height)); - assert_eq!(reader.get_tag_u32(Tag::Compression).unwrap(), 1); - assert_eq!(reader.get_tag_u32_vec(Tag::StripByteCounts).unwrap(), [1_000_000, 96]); - assert!(reader.find_tag(Tag::ExtraSamples).unwrap().is_none()); - assert!(reader.find_tag(Tag::IccProfile).unwrap().is_none()); - let tiff::decoder::DecodingResult::U16(decoded) = reader.read_image().unwrap() else { - panic!("expected native 16-bit samples"); - }; - assert_eq!(decoded, samples); - } - - #[test] - fn plain_rgba16_rejects_malformed_sample_count_and_dimensions() { - assert!(encode_plain_rgba16(0, 1, &[]).is_err()); - assert!(encode_plain_rgba16(1, 1, &[0; 3]).is_err()); - assert!(encode_plain_rgba16(1, 1, &[0; 5]).is_err()); - assert!(encode_plain_rgba16(u32::MAX, u32::MAX, &[]).is_err()); - } + craft_tiff::plain::encode_rgba16(width, height, samples).map_err(|error| CodecError::encode(F, error)) } mod bands; diff --git a/crates/tiff/Cargo.toml b/crates/tiff/Cargo.toml index 8b5c49b01..42f71a571 100644 --- a/crates/tiff/Cargo.toml +++ b/crates/tiff/Cargo.toml @@ -10,9 +10,14 @@ repository.workspace = true [lints] workspace = true +[features] +plain-rgba16 = ["dep:tiff"] + [dependencies] serde = { workspace = true } thiserror = { workspace = true } +tiff = { version = "0.11", default-features = false, optional = true } [dev-dependencies] +image = { version = "0.25", default-features = false, features = ["tiff"] } proptest = { workspace = true } diff --git a/crates/tiff/src/lib.rs b/crates/tiff/src/lib.rs index 5d6d78a21..1a618f39f 100644 --- a/crates/tiff/src/lib.rs +++ b/crates/tiff/src/lib.rs @@ -28,6 +28,9 @@ pub mod classic; pub mod image; pub mod makernote; pub mod packbits; +/// Plain, uncompressed classic TIFF writing for existing RGBA16 callers. +#[cfg(feature = "plain-rgba16")] +pub mod plain; pub mod probe; mod reader; pub mod tags; diff --git a/crates/tiff/src/plain.rs b/crates/tiff/src/plain.rs new file mode 100644 index 000000000..ffb664d4e --- /dev/null +++ b/crates/tiff/src/plain.rs @@ -0,0 +1,71 @@ +//! The uncompressed, metadata-free compatibility representation for RGBA16 stills. + +use std::io::Cursor; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid dimensions or RGBA16 sample count")] + InvalidInput, + #[error(transparent)] + Tiff(#[from] tiff::TiffError), +} + +/// Encode straight, native-endian RGBA16 samples as an uncompressed classic TIFF with the +/// encoder's default strip layout and no extra tags such as ICC or ExtraSamples. +pub fn encode_rgba16(width: u32, height: u32, samples: &[u16]) -> Result, Error> { + let expected = u64::from(width).checked_mul(u64::from(height)).and_then(|n| n.checked_mul(4)).and_then(|n| usize::try_from(n).ok()); + if width == 0 || height == 0 || expected != Some(samples.len()) { + return Err(Error::InvalidInput); + } + let mut out = Cursor::new(Vec::new()); + tiff::encoder::TiffEncoder::new(&mut out)?.write_image::(width, height, samples)?; + Ok(out.into_inner()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_rgba16_keeps_uncompressed_legacy_strips_and_rgba_samples() { + // Self-generated straight RGBA data; tall enough for the encoder's second strip. + let (width, height) = (4, 31_253); + let samples: Vec = std::iter::repeat_n([0x12ab, 0xcdef, 0x3142, 0x8000], (width * height) as usize).flatten().collect(); + let bytes = encode_rgba16(width, height, &samples).unwrap(); + let mut reader = tiff::decoder::Decoder::new(Cursor::new(bytes)).unwrap(); + use tiff::tags::Tag; + assert_eq!(reader.dimensions().unwrap(), (width, height)); + assert_eq!(reader.get_tag_u32(Tag::Compression).unwrap(), 1); + assert_eq!(reader.get_tag_u32_vec(Tag::StripByteCounts).unwrap(), [1_000_000, 96]); + assert!(reader.find_tag(Tag::ExtraSamples).unwrap().is_none()); + assert!(reader.find_tag(Tag::IccProfile).unwrap().is_none()); + let tiff::decoder::DecodingResult::U16(decoded) = reader.read_image().unwrap() else { + panic!("expected native 16-bit samples"); + }; + assert_eq!(decoded, samples); + } + + #[test] + fn plain_rgba16_rejects_malformed_sample_count_and_dimensions() { + assert!(encode_rgba16(0, 1, &[]).is_err()); + assert!(encode_rgba16(1, 1, &[0; 3]).is_err()); + assert!(encode_rgba16(1, 1, &[0; 5]).is_err()); + assert!(encode_rgba16(u32::MAX, u32::MAX, &[]).is_err()); + } + + #[test] + fn plain_rgba16_matches_legacy_writer_bytes() -> Result<(), Box> { + use image::{ExtendedColorType, ImageEncoder, codecs::tiff::TiffEncoder}; + + // Original, generated pixels with distinct channels and alpha. Tall and wide cases + // both exceed one strip and stress the compatibility encoder's strip decisions. + for (w, h) in [(1, 1), (5, 3), (4, 31_253), (5_123, 25)] { + let samples: Vec<_> = (0..w * h * 4).map(|i: u32| i.wrapping_mul(7919).wrapping_add(0x1234) as u16).collect(); + let mut legacy = Cursor::new(Vec::new()); + let packed: Vec = samples.iter().flat_map(|v| v.to_ne_bytes()).collect(); + TiffEncoder::new(&mut legacy).write_image(&packed, w, h, ExtendedColorType::Rgba16)?; + assert!(encode_rgba16(w, h, &samples)? == legacy.into_inner(), "{w}×{h}: TIFF bytes changed"); + } + Ok(()) + } +}