diff --git a/crates/ec-image/src/lib.rs b/crates/ec-image/src/lib.rs index 014ebaf3..04d75d00 100644 --- a/crates/ec-image/src/lib.rs +++ b/crates/ec-image/src/lib.rs @@ -1,4 +1,4 @@ -//! Still-image decoding: PNG, JPEG, WebP, GIF and BMP. +//! Still-image decoding: PNG, JPEG, WebP, GIF, BMP and TIFF. //! //! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the //! format from the leading bytes and hands back an [`Image`]: dimensions, a @@ -35,6 +35,7 @@ pub mod bmp; pub mod gif; pub mod jpeg; pub mod png; +pub mod tiff; mod upsample; pub mod webp; @@ -57,6 +58,8 @@ pub enum ImageFormat { Gif, /// Windows BMP (device-independent bitmap). Bmp, + /// TIFF, the tag-directory format. + Tiff, } impl ImageFormat { @@ -74,6 +77,15 @@ impl ImageFormat { Some(ImageFormat::Gif) } else if is_bmp(data) { Some(ImageFormat::Bmp) + } else if data.starts_with(b"II\x2a\x00") + || data.starts_with(b"MM\x00\x2a") + || data.starts_with(b"II\x2b\x00") + || data.starts_with(b"MM\x00\x2b") + { + // 42 is classic TIFF and 43 is BigTIFF; the second is recognised + // here so that the decoder can refuse it by name rather than + // leaving the file unidentified. + Some(ImageFormat::Tiff) } else { None } @@ -87,6 +99,7 @@ impl ImageFormat { ImageFormat::WebP => "webp", ImageFormat::Gif => "gif", ImageFormat::Bmp => "bmp", + ImageFormat::Tiff => "tiff", } } } @@ -123,10 +136,12 @@ pub struct Limits { /// Largest total bytes accepted across every frame of one decode call. /// /// A single frame can pass [`Limits::check_bytes`] on its own and still - /// be a bomb once an animation's frame count multiplies it — GIF and - /// WebP both composite onto a full canvas per frame, so a file with many - /// small-looking frames can retain gigabytes nothing ever checked one - /// buffer at a time. [`AllocBudget`] enforces this across a decode call. + /// be a bomb once a frame or segment count multiplies it — GIF and WebP + /// both composite onto a full canvas per frame, and a stripped or tiled + /// TIFF decompresses many segments per call, so a file whose parts each + /// look small on their own can still retain gigabytes nothing ever + /// checked one buffer at a time. [`AllocBudget`] enforces this across a + /// decode call. pub max_total_alloc: usize, } @@ -156,8 +171,8 @@ impl Limits { Ok(()) } - /// Check a byte count computed from header-declared fields (a frame's - /// `width * height * bpp`, a palette size, a chunk length) before it + /// Check a byte count computed from header-declared fields (a frame's or + /// strip's `width * height * bpp`, a palette size, a chunk length) before it /// sizes a single allocation. `what` names the buffer for the error. pub fn check_bytes(&self, what: &str, bytes: Option) -> Result { let bytes = @@ -172,10 +187,11 @@ impl Limits { } } -/// Accumulates bytes spent across every frame of one decode call and refuses -/// once the running total crosses [`Limits::max_total_alloc`] — the guard -/// for `frame_count x canvas`, which [`Limits::check_bytes`] alone never -/// sees since it only ever looks at one buffer at a time. +/// Accumulates bytes spent across every frame or segment of one decode call +/// and refuses once the running total crosses [`Limits::max_total_alloc`] — +/// the guard for `frame_count x canvas` or `segment_count x segment_size`, +/// which [`Limits::check_bytes`] alone never sees since it only ever looks +/// at one buffer at a time. #[derive(Debug, Default)] pub struct AllocBudget(usize); @@ -425,9 +441,10 @@ pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result { Some(ImageFormat::WebP) => webp::decode(data, limits), Some(ImageFormat::Gif) => gif::decode(data, limits), Some(ImageFormat::Bmp) => bmp::decode(data, limits), + Some(ImageFormat::Tiff) => tiff::decode(data, limits), None => Err(Error::unsupported( "image", - "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data", + "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data", )), } } @@ -440,9 +457,10 @@ pub fn info(data: &[u8]) -> Result { Some(ImageFormat::WebP) => webp::info(data), Some(ImageFormat::Gif) => gif::info(data), Some(ImageFormat::Bmp) => bmp::info(data), + Some(ImageFormat::Tiff) => tiff::info(data), None => Err(Error::unsupported( "image", - "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data", + "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data", )), } } diff --git a/crates/ec-image/src/tiff.rs b/crates/ec-image/src/tiff.rs new file mode 100644 index 00000000..b1a75f60 --- /dev/null +++ b/crates/ec-image/src/tiff.rs @@ -0,0 +1,757 @@ +//! TIFF: the tag-directory format scanners, cameras and every "save as +//! uncompressed" dialog write. +//! +//! A TIFF is a header pointing at a directory of tags, and the tags say where +//! the pixels are and how they were packed. Almost nothing about the layout is +//! fixed: rows may be grouped into strips or into tiles, samples may be +//! interleaved or stored one plane at a time, a sample may be 1, 2, 4, 8 or 16 +//! bits wide, and the bytes may be little- or big-endian. This reads all of +//! those, with the compressions in general use -- none, LZW, PackBits and +//! Deflate -- and the horizontal-differencing predictor that usually +//! accompanies the last two. +//! +//! Refused by name, because the capability is genuinely absent rather than +//! merely unwritten: the CCITT fax compressions (2, 3, 4), which are a +//! different coder altogether, JPEG-in-TIFF (7), and BigTIFF, whose header is +//! a different format that happens to share a signature byte. The incumbent +//! `image` crate refuses all three as well. + +use crate::{AllocBudget, Image, ImageFormat, Info, Limits, Metadata, Pixels}; +use ec_core::{Error, Result}; + +const TAG_WIDTH: u16 = 256; +const TAG_HEIGHT: u16 = 257; +const TAG_BITS: u16 = 258; +const TAG_COMPRESSION: u16 = 259; +const TAG_PHOTOMETRIC: u16 = 262; +const TAG_STRIP_OFFSETS: u16 = 273; +const TAG_ORIENTATION: u16 = 274; +const TAG_SAMPLES: u16 = 277; +const TAG_ROWS_PER_STRIP: u16 = 278; +const TAG_STRIP_COUNTS: u16 = 279; +const TAG_PLANAR: u16 = 284; +const TAG_PREDICTOR: u16 = 317; +const TAG_COLOR_MAP: u16 = 320; +const TAG_TILE_WIDTH: u16 = 322; +const TAG_TILE_HEIGHT: u16 = 323; +const TAG_TILE_OFFSETS: u16 = 324; +const TAG_TILE_COUNTS: u16 = 325; +const TAG_EXTRA_SAMPLES: u16 = 338; +const TAG_SAMPLE_FORMAT: u16 = 339; + +const COMPRESSION_NONE: u64 = 1; +const COMPRESSION_LZW: u64 = 5; +const COMPRESSION_DEFLATE: u64 = 8; +const COMPRESSION_PACKBITS: u64 = 32773; +const COMPRESSION_DEFLATE_OLD: u64 = 32946; + +/// The endianness the file declared, and the bytes it declared it about. +struct Reader<'a> { + data: &'a [u8], + big_endian: bool, +} + +impl<'a> Reader<'a> { + fn u16_at(&self, at: usize) -> Result { + let bytes = self + .data + .get(at..at + 2) + .ok_or_else(|| Error::corrupt("TIFF: a field past the end of the file"))?; + Ok(if self.big_endian { + u16::from_be_bytes([bytes[0], bytes[1]]) + } else { + u16::from_le_bytes([bytes[0], bytes[1]]) + }) + } + + fn u32_at(&self, at: usize) -> Result { + let bytes = self + .data + .get(at..at + 4) + .ok_or_else(|| Error::corrupt("TIFF: a field past the end of the file"))?; + Ok(if self.big_endian { + u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) + } else { + u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) + }) + } +} + +/// One directory entry, with its values already read. +struct Entry { + tag: u16, + values: Vec, +} + +/// Bytes one value of each TIFF type occupies. +fn type_size(kind: u16) -> Option { + Some(match kind { + 1 | 2 | 6 | 7 => 1, + 3 | 8 => 2, + 4 | 9 | 11 => 4, + 5 | 10 | 12 => 8, + _ => return None, + }) +} + +/// The image file directory at `offset`, as entries whose integer values are +/// already resolved. +/// +/// Values of four bytes or fewer live in the entry itself; anything longer is +/// at an offset the entry holds. Non-integer types (rationals, floats, ASCII) +/// are read as raw words and ignored by every caller here, which only asks for +/// the geometry tags. +fn directory(reader: &Reader, offset: usize) -> Result> { + let count = reader.u16_at(offset)? as usize; + let mut entries = Vec::with_capacity(count); + for i in 0..count { + let at = offset + 2 + i * 12; + let tag = reader.u16_at(at)?; + let kind = reader.u16_at(at + 2)?; + let n = reader.u32_at(at + 4)? as usize; + let Some(size) = type_size(kind) else { + continue; // a type this decoder has no use for + }; + // A count large enough to overflow the file is corrupt, and a count + // large enough to exhaust memory is corrupt too: the biggest legitimate + // value list is one offset per strip. + if n > reader.data.len() { + return Err(Error::corrupt("TIFF: a tag claiming more values than bytes")); + } + let total = n * size; + let base = if total <= 4 { + at + 8 + } else { + reader.u32_at(at + 8)? as usize + }; + let mut values = Vec::with_capacity(n); + for v in 0..n { + let at = base + v * size; + values.push(match size { + 1 => u64::from( + *reader + .data + .get(at) + .ok_or_else(|| Error::corrupt("TIFF: a value past the end of the file"))?, + ), + 2 => u64::from(reader.u16_at(at)?), + 4 => u64::from(reader.u32_at(at)?), + // Rationals and doubles: the numerator is the only half any + // tag read here would want, and none of them do. + _ => u64::from(reader.u32_at(at)?), + }); + } + entries.push(Entry { tag, values }); + } + Ok(entries) +} + +/// Everything the tags say about the pixels. +struct Layout { + width: u32, + height: u32, + bits: Vec, + samples: usize, + photometric: u64, + compression: u64, + planar: u64, + predictor: u64, + /// Strip or tile data offsets, in the order the file lists them. + offsets: Vec, + counts: Vec, + /// `None` for a stripped file; the tile size for a tiled one. + tile: Option<(u32, u32)>, + rows_per_strip: u32, + colour_map: Vec, + /// Tag 338: whether the extra sample is alpha, and whether it is premultiplied. + extra_samples: Vec, + orientation: Option, +} + +fn tag<'e>(entries: &'e [Entry], tag: u16) -> Option<&'e Entry> { + entries.iter().find(|e| e.tag == tag) +} + +fn first(entries: &[Entry], want: u16, default: u64) -> u64 { + tag(entries, want) + .and_then(|e| e.values.first().copied()) + .unwrap_or(default) +} + +fn layout(data: &[u8]) -> Result { + if data.len() < 8 { + return Err(Error::corrupt("TIFF: a file too short to hold a header")); + } + let big_endian = match &data[0..2] { + b"II" => false, + b"MM" => true, + _ => return Err(Error::corrupt("TIFF: no II or MM byte order mark")), + }; + let reader = Reader { data, big_endian }; + match reader.u16_at(2)? { + 42 => {} + 43 => { + return Err(Error::unsupported( + "TIFF: a BigTIFF file (version 43)", + "BigTIFF replaces every offset and count with a 64-bit one; \ + it shares the byte order mark but not the directory format", + )); + } + other => { + return Err(Error::corrupt(format!("TIFF: version {other}"))); + } + } + let entries = directory(&reader, reader.u32_at(4)? as usize)?; + + let compression = first(&entries, TAG_COMPRESSION, COMPRESSION_NONE); + match compression { + COMPRESSION_NONE + | COMPRESSION_LZW + | COMPRESSION_DEFLATE + | COMPRESSION_PACKBITS + | COMPRESSION_DEFLATE_OLD => {} + 2 | 3 | 4 => { + return Err(Error::unsupported( + format!("TIFF: CCITT compression {compression}"), + "the fax coders are a separate format with their own \ + two-dimensional coding modes", + )); + } + 6 | 7 => { + return Err(Error::unsupported( + "TIFF: a JPEG-compressed strip", + "the strips hold JPEG scans with the tables in a separate tag; \ + decode such a file with the JPEG decoder once it is assembled", + )); + } + other => return Err(Error::corrupt(format!("TIFF: compression {other}"))), + } + + let samples = first(&entries, TAG_SAMPLES, 1) as usize; + if samples == 0 || samples > 4 { + return Err(Error::corrupt(format!( + "TIFF: {samples} samples per pixel" + ))); + } + let bits: Vec = tag(&entries, TAG_BITS) + .map(|e| e.values.iter().map(|&v| v as u16).collect()) + .unwrap_or_else(|| vec![1; samples]); + if bits.len() != samples { + return Err(Error::corrupt( + "TIFF: a bit-depth list that does not match the sample count", + )); + } + if bits.iter().any(|b| *b != bits[0]) { + return Err(Error::unsupported( + "TIFF: channels of different depths", + "every channel is unpacked with one width; a file mixing them \ + would need a per-channel unpacker", + )); + } + if !matches!(bits[0], 1 | 2 | 4 | 8 | 16) { + return Err(Error::unsupported( + format!("TIFF: {}-bit samples", bits[0]), + "1, 2, 4, 8 and 16 are the widths this decoder unpacks", + )); + } + if first(&entries, TAG_SAMPLE_FORMAT, 1) == 3 { + return Err(Error::unsupported( + "TIFF: floating-point samples", + "sample format 3 stores IEEE floats, which have no fixed range to \ + map onto an integer picture", + )); + } + + let photometric = first(&entries, TAG_PHOTOMETRIC, 1); + if !matches!(photometric, 0 | 1 | 2 | 3) { + return Err(Error::unsupported( + format!("TIFF: photometric interpretation {photometric}"), + "white-is-zero, black-is-zero, RGB and palette are the colour \ + models this decoder converts", + )); + } + + let predictor = first(&entries, TAG_PREDICTOR, 1); + if !matches!(predictor, 1 | 2) { + return Err(Error::unsupported( + format!("TIFF: predictor {predictor}"), + "1 (none) and 2 (horizontal differencing) are the integer \ + predictors; 3 is the floating-point one", + )); + } + + let tile = match (tag(&entries, TAG_TILE_WIDTH), tag(&entries, TAG_TILE_HEIGHT)) { + (Some(w), Some(h)) => Some(( + *w.values.first().unwrap_or(&0) as u32, + *h.values.first().unwrap_or(&0) as u32, + )), + _ => None, + }; + let (offsets_tag, counts_tag) = if tile.is_some() { + (TAG_TILE_OFFSETS, TAG_TILE_COUNTS) + } else { + (TAG_STRIP_OFFSETS, TAG_STRIP_COUNTS) + }; + let offsets = tag(&entries, offsets_tag) + .map(|e| e.values.clone()) + .ok_or_else(|| Error::corrupt("TIFF: no strip or tile offsets"))?; + let counts = tag(&entries, counts_tag) + .map(|e| e.values.clone()) + .ok_or_else(|| Error::corrupt("TIFF: no strip or tile byte counts"))?; + if offsets.len() != counts.len() { + return Err(Error::corrupt( + "TIFF: as many offsets as byte counts is the one thing the format promises", + )); + } + + let orientation = match first(&entries, TAG_ORIENTATION, 0) { + v @ 1..=8 => Some(v as u8), + _ => None, + }; + + Ok(Layout { + width: first(&entries, TAG_WIDTH, 0) as u32, + height: first(&entries, TAG_HEIGHT, 0) as u32, + bits, + samples, + photometric, + compression, + planar: first(&entries, TAG_PLANAR, 1), + predictor, + offsets, + counts, + tile, + rows_per_strip: first(&entries, TAG_ROWS_PER_STRIP, u64::from(u32::MAX)).min(u64::from(u32::MAX)) + as u32, + colour_map: tag(&entries, TAG_COLOR_MAP) + .map(|e| e.values.clone()) + .unwrap_or_default(), + extra_samples: tag(&entries, TAG_EXTRA_SAMPLES) + .map(|e| e.values.clone()) + .unwrap_or_default(), + orientation, + }) +} + +/// Dimensions from the first directory, without decoding the pixels. +pub fn info(data: &[u8]) -> Result { + let layout = layout(data)?; + Ok(Info { + format: ImageFormat::Tiff, + width: layout.width, + height: layout.height, + }) +} + +/// TIFF's LZW: MSB-first codes, and the width grows one code early. +/// +/// The "one code early" is the difference from the GIF variant: a TIFF encoder +/// switches to the next width when the *next* code to be assigned would not +/// fit, so a decoder that waits for the code itself desynchronises a byte into +/// every image. +fn lzw(input: &[u8], hint: usize) -> Result> { + const CLEAR: u16 = 256; + const END: u16 = 257; + let mut out = Vec::with_capacity(hint); + // Each entry is a previous code plus one byte, walked backwards on emit, + // which keeps the table one allocation instead of one per string. + let mut prefix = vec![0u16; 4096]; + let mut suffix = vec![0u8; 4096]; + let mut next = 258usize; + let mut width = 9u32; + let mut previous: Option = None; + let (mut bit, mut acc, mut have) = (0usize, 0u32, 0u32); + let mut stack = Vec::with_capacity(4096); + loop { + if out.len() >= hint { + // The declared strip is already full. A bomb-style stream keeps + // emitting codes past this point (the dictionary just keeps + // growing); stopping here is what keeps a KB-sized input from + // expanding into hundreds of megabytes. + return Ok(out); + } + while have < width { + let Some(&byte) = input.get(bit) else { + return Ok(out); + }; + bit += 1; + acc = (acc << 8) | u32::from(byte); + have += 8; + } + let code = ((acc >> (have - width)) & ((1 << width) - 1)) as u16; + have -= width; + match code { + CLEAR => { + next = 258; + width = 9; + previous = None; + continue; + } + END => return Ok(out), + _ => {} + } + stack.clear(); + let first_byte = if (code as usize) < next { + let mut walk = code; + while walk >= 258 { + stack.push(suffix[walk as usize]); + walk = prefix[walk as usize]; + } + if walk > 255 { + return Err(Error::corrupt("TIFF: an LZW code with no string")); + } + stack.push(walk as u8); + *stack.last().unwrap() + } else if code as usize == next { + // The KwKwK case: the code being emitted is exactly the one this + // step is about to define. A code greater than `next` is not a + // KwKwK case at all -- it names a dictionary entry that does not + // exist yet -- and accepting it here would let `previous` (set + // below to this out-of-range `code`) get written into a future + // `prefix` slot, breaking the invariant that every prefix chain + // strictly decreases and turning the walk above into a cycle + // that grows `stack` without bound. + let previous = previous + .ok_or_else(|| Error::corrupt("TIFF: an LZW stream opening with a new code"))?; + let mut walk = previous; + while walk >= 258 { + stack.push(suffix[walk as usize]); + walk = prefix[walk as usize]; + } + stack.push(walk as u8); + let first = *stack.last().unwrap(); + stack.insert(0, first); + first + } else { + // code as usize > next: a reference to a dictionary entry that + // does not exist yet, neither an ordinary code nor a valid KwKwK. + return Err(Error::corrupt("TIFF: an LZW code past the dictionary")); + }; + out.extend(stack.iter().rev()); + if let Some(previous) = previous { + if next < 4096 { + prefix[next] = previous; + suffix[next] = first_byte; + next += 1; + } + } + previous = Some(code); + // One code early: 511, not 512, is where nine bits stop being enough. + if next + 1 >= (1 << width) && width < 12 { + width += 1; + } + } +} + +/// PackBits: a run-length coder whose control byte is signed. +fn packbits(input: &[u8], hint: usize) -> Vec { + let mut out = Vec::with_capacity(hint); + let mut at = 0usize; + while at < input.len() { + if out.len() >= hint { + // Same bomb shape as LZW: a run byte expands to up to 128 bytes + // of output, so a small strip can otherwise inflate far past + // what the declared geometry says it should hold. + break; + } + let control = input[at] as i8; + at += 1; + if control >= 0 { + let run = control as usize + 1; + let end = (at + run).min(input.len()); + out.extend_from_slice(&input[at..end]); + at = end; + } else if control != -128 { + let run = (-i32::from(control)) as usize + 1; + let Some(&byte) = input.get(at) else { break }; + at += 1; + out.extend(std::iter::repeat_n(byte, run)); + } else { + // -128 is a no-op the format reserves. + } + } + out +} + +/// One strip or tile, decompressed. +fn segment(layout: &Layout, data: &[u8], index: usize, expect: usize) -> Result> { + let at = layout.offsets[index] as usize; + let len = layout.counts[index] as usize; + let body = data + .get(at..at.saturating_add(len)) + .ok_or_else(|| Error::corrupt("TIFF: a strip reaching past the end of the file"))?; + Ok(match layout.compression { + COMPRESSION_NONE => body.to_vec(), + COMPRESSION_LZW => lzw(body, expect)?, + COMPRESSION_PACKBITS => packbits(body, expect), + _ => ec_inflate::inflate_zlib(body, expect.saturating_mul(2).max(1024)) + .map_err(|e| Error::corrupt(format!("TIFF: a Deflate strip: {e}")))?, + }) +} + +/// Undo horizontal differencing across one row of `channels` interleaved samples. +/// Horizontal differencing runs at the sample's own width, so the sum wraps at +/// `mask + 1` -- an 8-bit file wraps at 256, not at the u16 these are held in. +fn undo_predictor(row: &mut [u16], channels: usize, mask: u16) { + for i in channels..row.len() { + row[i] = row[i].wrapping_add(row[i - channels]) & mask; + } +} + +/// Read `count` samples of `bits` width from `bytes`, MSB-first. +fn unpack(bytes: &[u8], bits: u16, count: usize, out: &mut Vec, big_endian: bool) { + match bits { + 16 => { + for i in 0..count { + let (a, b) = ( + bytes.get(i * 2).copied().unwrap_or(0), + bytes.get(i * 2 + 1).copied().unwrap_or(0), + ); + out.push(if big_endian { + u16::from_be_bytes([a, b]) + } else { + u16::from_le_bytes([a, b]) + }); + } + } + 8 => out.extend( + (0..count).map(|i| u16::from(bytes.get(i).copied().unwrap_or(0))), + ), + _ => { + let per_byte = 8 / bits as usize; + let mask = (1u16 << bits) - 1; + for i in 0..count { + let byte = bytes.get(i / per_byte).copied().unwrap_or(0); + let shift = 8 - bits as usize * (i % per_byte + 1); + out.push((u16::from(byte) >> shift) & mask); + } + } + } +} + +/// Decode the first image in the file. +pub fn decode(data: &[u8], limits: Limits) -> Result { + let layout = layout(data)?; + limits.check(layout.width, layout.height)?; + let (width, height) = (layout.width as usize, layout.height as usize); + if width == 0 || height == 0 { + return Err(Error::corrupt("TIFF: a zero-sized picture")); + } + let big_endian = data.starts_with(b"MM"); + let bits = layout.bits[0]; + let samples = layout.samples; + let planar = layout.planar == 2; + let planes = if planar { samples } else { 1 }; + let per_plane = if planar { 1 } else { samples }; + + // Samples land here interleaved, whatever the file's own arrangement was. + // `width`/`height` already passed `limits.check`, but that only bounds + // pixel count -- a 4-sample 16-bit picture is 8 bytes/pixel, which can + // still cross the allocation limit even inside the pixel limit. + let raw_len = width + .checked_mul(height) + .and_then(|v| v.checked_mul(samples)) + .ok_or_else(|| Error::corrupt("TIFF: sample count overflows"))?; + let mut budget = AllocBudget::default(); + // A decompression-bomb guard on top of `max_alloc`: no legitimate encoder + // writes a file whose declared pixel count decompresses to thousands of + // times the bytes actually on disk (uncompressed is 1x, and LZW/Deflate + // only improve on that). A tag claiming otherwise is sized past the file + // that would have to contain it, not a picture this decoder should spend + // possibly-seconds unpacking one strip of. + let bomb_cap = data.len().saturating_mul(4096).max(1 << 20); + let raw_bytes = limits.check_bytes("TIFF raw samples", raw_len.checked_mul(2))?; + if raw_bytes > bomb_cap { + return Err(Error::unsupported( + "TIFF: a picture out of proportion to its file size", + format!("{raw_bytes} raw bytes claimed from a {}-byte file", data.len()), + )); + } + budget.spend(&limits, "TIFF raw samples", raw_bytes)?; + let mut raw = vec![0u16; raw_len]; + + // Strips and tiles differ only in the rectangle one segment covers. Tile + // and rows-per-strip dimensions are header fields too, unconstrained by + // the picture's own width/height, so a segment's decompressed size is + // budgeted before anything is sized from it. + let (seg_w, seg_h) = match layout.tile { + Some((w, h)) if w > 0 && h > 0 => (w as usize, h as usize), + Some(_) => return Err(Error::corrupt("TIFF: a zero-sized tile")), + None => (width, layout.rows_per_strip.max(1) as usize), + }; + let across = width.div_ceil(seg_w); + let down = height.div_ceil(seg_h); + let per_plane_segments = across * down; + if layout.offsets.len() < per_plane_segments * planes { + return Err(Error::corrupt( + "TIFF: fewer strips than the geometry needs", + )); + } + + // A tile is always its full width; a strip is only as wide as the picture, + // and its last one only as tall as the rows that remain. + let row_samples = seg_w + .checked_mul(per_plane) + .ok_or_else(|| Error::corrupt("TIFF: a row wider than usize"))?; + let row_bytes = limits.check_bytes( + "TIFF row", + row_samples + .checked_mul(bits as usize) + .map(|bits| bits.div_ceil(8)), + )?; + // `row` holds one `u16` per *sample*, not per packed byte -- for anything + // under 16 bits that is a bigger allocation than `row_bytes` (up to 16x + // for a 1-bit picture), so it needs its own check rather than trusting + // the packed size to stand in for it. + limits.check_bytes("TIFF row samples", row_samples.checked_mul(2))?; + if row_samples.saturating_mul(2) > bomb_cap { + return Err(Error::unsupported( + "TIFF: a row out of proportion to its file size", + format!("{row_samples} samples/row claimed from a {}-byte file", data.len()), + )); + } + let mut row = Vec::with_capacity(row_samples); + let full = ((1u32 << bits) - 1) as u16; + // `bomb_cap` alone bounds one strip; nothing bounded the strip *count* + // yet, and that is attacker-controlled up to the number of offsets a + // small file can list. A few thousand small-looking strips can still add + // up to gigabytes of real decompression work, so the running total is + // held to the same file-size-proportional ceiling as a single strip. + let mut segment_bytes_total = 0usize; + for index in 0..per_plane_segments * planes { + let plane = index / per_plane_segments; + let within = index % per_plane_segments; + let (col, band) = (within % across, within / across); + // The declared strip/tile height is a header field like any other: + // nothing stops RowsPerStrip or TileLength from claiming far more + // rows than the picture has, which would otherwise size an LZW or + // Deflate hint (and the compute behind it) off a number with no + // relationship to the real image -- a small file claiming a + // billion-row strip decodes only as many rows as `height` actually + // has, never the declared height. + let rows_used = seg_h.min(height.saturating_sub(band * seg_h)); + let expect = limits.check_bytes("TIFF strip", row_bytes.checked_mul(rows_used))?; + segment_bytes_total = segment_bytes_total.saturating_add(expect); + if expect > bomb_cap || segment_bytes_total > bomb_cap { + return Err(Error::unsupported( + "TIFF: strips claim more decompressed data than the file could hold", + format!( + "{segment_bytes_total} bytes claimed across strips from a {}-byte file", + data.len() + ), + )); + } + budget.spend(&limits, "TIFF strip", expect)?; + let body = segment(&layout, data, index, expect)?; + for r in 0..seg_h { + let y = band * seg_h + r; + if y >= height { + break; + } + let at = r * row_bytes; + let Some(bytes) = body.get(at..(at + row_bytes).min(body.len())) else { + break; + }; + row.clear(); + unpack(bytes, bits, row_samples, &mut row, big_endian); + if layout.predictor == 2 { + undo_predictor(&mut row, per_plane, full); + } + for x in 0..seg_w { + let px = col * seg_w + x; + if px >= width { + break; + } + for s in 0..per_plane { + let channel = if planar { plane } else { s }; + raw[(y * width + px) * samples + channel] = row[x * per_plane + s]; + } + } + } + } + + // Widths below 8 bits are stretched to full scale so that a bilevel file's + // 1 becomes white rather than one two-hundred-and-fifty-fifth of it. + let pixels = build(&layout, &raw, width * height, bits, full)?; + Ok(Image { + width: layout.width, + height: layout.height, + pixels, + meta: Metadata { + orientation: layout.orientation, + ..Metadata::default() + }, + }) +} + +/// Turn raw samples into the crate's colour form. +fn build(layout: &Layout, raw: &[u16], count: usize, bits: u16, full: u16) -> Result { + let samples = layout.samples; + let alpha = samples == 2 || samples == 4; + // Extra sample type 1 is straight alpha and 2 is associated -- the colour + // channels already multiplied by it. This crate carries straight alpha, so + // an associated file is divided back out; where alpha is full, which is + // what ImageMagick writes for an opaque picture, that is the identity. + let associated = alpha && layout.extra_samples.first() == Some(&2); + // 8-bit output for everything but a 16-bit file, whose depth survives. + let widen = |v: u16| -> u16 { + if bits == 16 { + v + } else { + // round(v * 65535 / full) + ((u32::from(v) * 65535 + u32::from(full) / 2) / u32::from(full)) as u16 + } + }; + let narrow = |v: u16| -> u8 { ((u32::from(v) * 255 + 32767) / 65535) as u8 }; + + if layout.photometric == 3 { + // A palette: three ranges of 16-bit values, one per channel, in a + // single tag. + let entries = layout.colour_map.len() / 3; + if entries == 0 { + return Err(Error::corrupt("TIFF: a palette picture with no colour map")); + } + let mut out = Vec::with_capacity(count * 3); + for &index in raw.iter().take(count) { + let index = index as usize; + if index >= entries { + return Err(Error::corrupt("TIFF: a palette index past the colour map")); + } + for c in 0..3 { + out.push(narrow(layout.colour_map[c * entries + index] as u16)); + } + } + return Ok(Pixels::Rgb8(out)); + } + + let invert = layout.photometric == 0; + let mut wide: Vec = Vec::with_capacity(raw.len()); + for (i, &v) in raw.iter().enumerate() { + let is_alpha = alpha && (i % samples) == samples - 1; + let v = widen(v); + wide.push(if invert && !is_alpha { 65535 - v } else { v }); + } + if associated { + for pixel in wide.chunks_mut(samples) { + let a = u32::from(pixel[samples - 1]); + for channel in &mut pixel[..samples - 1] { + *channel = if a == 0 { + 0 + } else { + (((u32::from(*channel) * 65535 + a / 2) / a).min(65535)) as u16 + }; + } + } + } + + Ok(match (samples, bits) { + (1, 16) => Pixels::L16(wide), + (2, 16) => Pixels::La16(wide), + (3, 16) => Pixels::Rgb16(wide), + (4, 16) => Pixels::Rgba16(wide), + (1, _) => Pixels::L8(wide.iter().map(|&v| narrow(v)).collect()), + (2, _) => Pixels::La8(wide.iter().map(|&v| narrow(v)).collect()), + (3, _) => Pixels::Rgb8(wide.iter().map(|&v| narrow(v)).collect()), + _ => Pixels::Rgba8(wide.iter().map(|&v| narrow(v)).collect()), + }) +} diff --git a/crates/ec-image/tests/differential.rs b/crates/ec-image/tests/differential.rs index 4b8d6a63..9b7cd6ed 100644 --- a/crates/ec-image/tests/differential.rs +++ b/crates/ec-image/tests/differential.rs @@ -630,3 +630,102 @@ fn an_os2_v2_header_reads_as_the_same_picture() { "os2v2.bmp: samples differ from the same picture in a v1 header" ); } + +/// TIFF stores raw samples, so like BMP the only question is whether the two +/// decoders read the same tags the same way. The corpus crosses every +/// compression with both byte orders, strips against tiles, interleaved +/// samples against planes, and five sample depths. +#[test] +fn tiff_decodes_pixel_exactly() { + let mut files = corpus("tiff"); + files.extend(corpus("tif")); + files.sort(); + if files.is_empty() && skip("tiff") { + return; + } + for path in files { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + if name == "palette4.tiff" { + continue; // the incumbent refuses a 4-bit palette; its own test covers it + } + if name == "rgba8-assoc.tiff" { + continue; // the incumbent ignores ExtraSamples; its own test covers it + } + let data = std::fs::read(&path).unwrap(); + let ours = ec_image::decode(&data).unwrap_or_else(|e| panic!("{name}: {e}")); + let theirs = image::load_from_memory(&data).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!( + (ours.width, ours.height), + theirs.dimensions(), + "{name}: dimensions differ" + ); + let (max, corr) = compare(&ours.to_rgba8(), &theirs.to_rgba8().into_raw()); + println!("{name:>20} max {max} corr {corr:.6}"); + assert_eq!(max, 0, "{name}: samples differ from the incumbent"); + } +} + +/// TIFF tags its alpha as either straight (ExtraSamples 1) or associated +/// (ExtraSamples 2, premultiplied). The incumbent hands back the file's raw +/// samples either way, so it cannot arbitrate the premultiplied one; the two +/// fixtures carry the same picture at alpha 0 or 255, where premultiplying is +/// lossless, so the associated file must decode to the straight one exactly. +#[test] +fn an_associated_alpha_tiff_reads_unpremultiplied() { + let (Ok(assoc), Ok(straight)) = ( + std::fs::read(fixtures().join("rgba8-assoc.tiff")), + std::fs::read(fixtures().join("rgba8.tiff")), + ) else { + skip("rgba8-assoc.tiff"); + return; + }; + let ours = ec_image::decode(&assoc).expect("rgba8-assoc.tiff"); + let reference = ec_image::decode(&straight).expect("rgba8.tiff"); + // Under a zero alpha the colour is gone for good -- premultiplying by zero + // is not invertible -- so those pixels are compared on their alpha alone. + let (ours, reference) = (ours.to_rgba8(), reference.to_rgba8()); + for (i, (a, b)) in ours.chunks(4).zip(reference.chunks(4)).enumerate() { + assert_eq!(a[3], b[3], "rgba8-assoc.tiff: alpha differs at pixel {i}"); + if b[3] != 0 { + assert_eq!( + a[..3], + b[..3], + "rgba8-assoc.tiff: the premultiplication was not undone at pixel {i}" + ); + } + } + + // The incumbent ignores the tag, so its two decodes differ: were that to + // change, this test would be comparing against nothing. + let a = image::load_from_memory(&assoc).expect("incumbent rgba8-assoc.tiff"); + let b = image::load_from_memory(&straight).expect("incumbent rgba8.tiff"); + assert_ne!( + a.to_rgba8().into_raw(), + b.to_rgba8().into_raw(), + "the incumbent now honours ExtraSamples; use it as the oracle instead" + ); +} + +/// A 4-bit palette, which the incumbent refuses ("Photometric interpretation +/// RGBPalette with bits per sample [4] is unsupported") and ffmpeg reads. The +/// oracle is therefore ffmpeg's own decode of the same file, written to a PNG +/// when the corpus was generated. +#[test] +fn a_four_bit_tiff_palette_reads_as_ffmpeg_reads_it() { + let (Ok(narrow), Ok(wide)) = ( + std::fs::read(fixtures().join("palette4.tiff")), + std::fs::read(fixtures().join("palette4-golden.png")), + ) else { + skip("palette4.tiff"); + return; + }; + assert!( + image::load_from_memory(&narrow).is_err(), + "the incumbent now reads a 4-bit palette; this test's premise is stale" + ); + let ours = ec_image::decode(&narrow).unwrap(); + let reference = image::load_from_memory(&wide).unwrap(); + assert_eq!((ours.width, ours.height), reference.dimensions()); + let (max, _) = compare(&ours.to_rgba8(), &reference.to_rgba8().into_raw()); + assert_eq!(max, 0, "palette4.tiff: samples differ from the same palette at 8 bits"); +} diff --git a/crates/ec-image/tests/fuzz.rs b/crates/ec-image/tests/fuzz.rs index 22036382..faec11fd 100644 --- a/crates/ec-image/tests/fuzz.rs +++ b/crates/ec-image/tests/fuzz.rs @@ -212,13 +212,29 @@ fn a_run_length_bmp_survives_mutation() { sweep("bmp-rle", "rle8.bmp"); } +/// TIFF is a directory of offsets into itself: a mutation can point a strip, +/// a palette or the directory's own continuation anywhere in the file. +#[test] +fn tiff_survives_mutation() { + sweep("tiff", "tiny.tiff"); +} + +/// The compressed, predicted path decodes into a row buffer whose length comes +/// from tags the mutation is free to disagree about, so it gets its own seed. +#[test] +fn a_compressed_tiff_survives_mutation() { + sweep("tiff-lzw", "rgb8-lzw-pred.tiff"); +} + #[test] fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() { - let signatures: [&[u8]; 5] = [ + let signatures: [&[u8]; 6] = [ &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a], &[0xff, 0xd8, 0xff, 0xe0], b"RIFF\x40\x00\x00\x00WEBPVP8 ", b"GIF89a", + // A TIFF header whose directory offset is inside the header itself. + b"II\x2a\x00\x04\x00\x00\x00", // "BM" alone is two bytes anything could start with, so the guess also // asks the file header to agree with itself: this prefix declares a // 40-byte info header and pixels at 54, which is what makes the bytes diff --git a/scripts/gen-still-fixtures.sh b/scripts/gen-still-fixtures.sh index ec9b76aa..c710c860 100755 --- a/scripts/gen-still-fixtures.sh +++ b/scripts/gen-still-fixtures.sh @@ -163,6 +163,53 @@ python3 "$(dirname "$0")/lib/gen-bmp-shapes.py" "$out" "$out/bmp-source.rgba" 64 rm -f "$out/bmp-source.png" "$out/bmp-source-alpha.png" "$out/bmp-source.rgba" \ "$out/bmp-source-alpha.rgba" "$out/bmp-embed.png" "$out/bmp-embed.jpg" +# --- TIFF: both byte orders, four compressions, strips and tiles ----------- +# TIFF fixes almost nothing about its layout, so the corpus is a cross-product: +# each compression, each sample depth, both byte orders, strips and tiles, and +# both plane arrangements. ImageMagick writes all of them. +magick "$out/source.png" -resize 64x48! "$out/tiff-source.png" +magick "$out/source-alpha.png" -resize 64x48! "$out/tiff-source-alpha.png" +magick "$out/tiff-source.png" -depth 8 -compress None "$out/rgb8.tiff" +magick "$out/tiff-source.png" -depth 8 -compress LZW "$out/rgb8-lzw.tiff" +magick "$out/tiff-source.png" -depth 8 -compress RLE "$out/rgb8-packbits.tiff" +magick "$out/tiff-source.png" -depth 8 -compress Zip "$out/rgb8-zip.tiff" +# The horizontal-differencing predictor, which is what an encoder reaches for +# when the compression is LZW or Deflate. +magick "$out/tiff-source.png" -depth 8 -compress LZW -define tiff:predictor=2 \ + "$out/rgb8-lzw-pred.tiff" +magick "$out/tiff-source.png" -depth 8 -compress Zip -define tiff:predictor=2 \ + "$out/rgb8-zip-pred.tiff" +# Big-endian: the same picture with every field byte-swapped. +magick "$out/tiff-source.png" -depth 8 -compress None -define tiff:endian=msb \ + "$out/rgb8-be.tiff" +# Tiles rather than strips, and planes rather than interleaved samples. +magick "$out/tiff-source.png" -depth 8 -compress LZW \ + -define tiff:tile-geometry=32x32 "$out/rgb8-tiled.tiff" +magick "$out/tiff-source.png" -depth 8 -compress None -interlace Plane \ + "$out/rgb8-planar.tiff" +# Depths: bilevel, 4-bit palette, 8-bit grey, 16-bit grey and 16-bit colour. +magick "$out/tiff-source.png" -monochrome -type bilevel -compress None \ + "$out/bilevel.tiff" +magick "$out/tiff-source.png" -colors 16 -type palette -depth 4 -compress None \ + "$out/palette4.tiff" +# The incumbent refuses a 4-bit palette outright, so ffmpeg -- which reads it -- +# writes the reference picture for that one fixture. +ffmpeg -loglevel error -y -i "$out/palette4.tiff" "$out/palette4-golden.png" +# -alpha off, or ImageMagick attaches an alpha channel to a grey picture that +# has none, and a two-sample grey file is a shape the incumbent refuses. +magick "$out/tiff-source.png" -colorspace gray -alpha off -depth 8 -compress None \ + "$out/gray8.tiff" +magick "$out/tiff-source.png" -colorspace gray -alpha off -depth 16 -compress None \ + "$out/gray16.tiff" +magick "$out/tiff-source.png" -depth 16 -compress Zip "$out/rgb16.tiff" +# Alpha, which TIFF carries as a fourth sample plus an ExtraSamples tag: both +# the straight and the premultiplied tagging, neither of which ImageMagick will +# write on request. +magick "$out/tiff-source-alpha.png" rgba:"$out/tiff-source-alpha.rgba" +python3 "$(dirname "$0")/lib/gen-tiff-shapes.py" "$out" "$out/tiff-source-alpha.rgba" 64 48 +rm -f "$out/tiff-source.png" "$out/tiff-source-alpha.png" \ + "$out/tiff-source-alpha.rgba" + # Small versions of each format, for the fuzz sweep: ten thousand mutations # per format is only affordable on a picture that decodes in microseconds. magick "$out/source.png" -resize 32x24! "$out/tiny.png" @@ -172,5 +219,6 @@ ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 0 -quality 7 ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 1 "$out/tiny-lossless.webp" magick "$out/tiny.png" -colors 64 "$out/tiny.gif" magick "$out/tiny.png" -colors 64 -type palette -compress None BMP3:"$out/tiny.bmp" +magick "$out/tiny.png" -depth 8 -compress LZW "$out/tiny.tiff" echo "wrote $(ls "$out" | wc -l) files to $out" diff --git a/scripts/lib/gen-tiff-shapes.py b/scripts/lib/gen-tiff-shapes.py new file mode 100644 index 00000000..fb6996be --- /dev/null +++ b/scripts/lib/gen-tiff-shapes.py @@ -0,0 +1,66 @@ +"""Write the TIFF alpha shapes ImageMagick will not emit. + +ImageMagick always tags a TIFF's alpha channel as associated (ExtraSamples 2, +premultiplied) and ignores ``-define tiff:alpha=unassociated``, so the ordinary +straight-alpha file -- the common one -- has to be written here. Both files +carry the same picture with the alpha flattened to 0 or 255, which makes the +premultiplication lossless and so lets the two decode to identical pixels. +""" + +import struct +import sys + +out, raw, width, height = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4]) +rgba = open(raw, "rb").read() + +# Flatten alpha to fully transparent or fully opaque: premultiplying by 0 or 1 +# loses nothing, so the associated file is recoverable exactly. +body = bytearray() +for i in range(0, width * height * 4, 4): + r, g, b, a = rgba[i : i + 4] + body += bytes((r, g, b, 255 if a >= 128 else 0)) + + +def tiff(path, extra_samples): + """A little-endian, uncompressed, single-strip RGBA file.""" + pixels = bytearray(body) + if extra_samples == 2: + for i in range(0, len(pixels), 4): + if pixels[i + 3] == 0: + pixels[i : i + 3] = b"\x00\x00\x00" + + # The header is 8 bytes, then the strip, then the directory: writing the + # pixels first keeps every out-of-line value at a known offset behind it. + strip = 8 + ifd = strip + len(pixels) + entries = [ + (256, 3, 1, width), # ImageWidth + (257, 3, 1, height), # ImageLength + (258, 3, 4, None), # BitsPerSample, four shorts, out of line + (259, 3, 1, 1), # Compression: none + (262, 3, 1, 2), # PhotometricInterpretation: RGB + (273, 4, 1, strip), # StripOffsets + (277, 3, 1, 4), # SamplesPerPixel + (278, 3, 1, height), # RowsPerStrip + (279, 4, 1, len(pixels)), # StripByteCounts + (284, 3, 1, 1), # PlanarConfiguration: chunky + (338, 3, 1, extra_samples), # ExtraSamples + ] + trailing = ifd + 2 + 12 * len(entries) + 4 + + directory = struct.pack(" Option { ec_image::ImageFormat::Bmp => Some(ImageFormat::Bmp), #[cfg(not(feature = "gpui"))] ec_image::ImageFormat::Bmp => None, + #[cfg(feature = "gpui")] + ec_image::ImageFormat::Tiff => Some(ImageFormat::Tiff), + #[cfg(not(feature = "gpui"))] + ec_image::ImageFormat::Tiff => None, } }