forge
Explore
Log in

Don't you dare go Hollow

wip(image): TIFF decoder lane snapshot before finish charter

Browse files at this commit

b4d23d9008a018664a27651e66ed5ed94c212bf0Ahmet Kaan GümüşParent: 463079b
crates/ec-image/src/lib.rsmodified+18 -3
@@ -1,4 +1,4 @@
1-//! Still-image decoding: PNG, JPEG, WebP, GIF and BMP.
1+//! Still-image decoding: PNG, JPEG, WebP, GIF, BMP and TIFF.
22 //!
33 //! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the
44 //! format from the leading bytes and hands back an [`Image`]: dimensions, a
@@ -35,6 +35,7 @@ pub mod bmp;
3535 pub mod gif;
3636 pub mod jpeg;
3737 pub mod png;
38+pub mod tiff;
3839 mod upsample;
3940 pub mod webp;
4041
@@ -57,6 +58,8 @@ pub enum ImageFormat {
5758 Gif,
5859 /// Windows BMP (device-independent bitmap).
5960 Bmp,
61+ /// TIFF, the tag-directory format.
62+ Tiff,
6063 }
6164
6265 impl ImageFormat {
@@ -74,6 +77,15 @@ impl ImageFormat {
7477 Some(ImageFormat::Gif)
7578 } else if is_bmp(data) {
7679 Some(ImageFormat::Bmp)
80+ } else if data.starts_with(b"II\x2a\x00")
81+ || data.starts_with(b"MM\x00\x2a")
82+ || data.starts_with(b"II\x2b\x00")
83+ || data.starts_with(b"MM\x00\x2b")
84+ {
85+ // 42 is classic TIFF and 43 is BigTIFF; the second is recognised
86+ // here so that the decoder can refuse it by name rather than
87+ // leaving the file unidentified.
88+ Some(ImageFormat::Tiff)
7789 } else {
7890 None
7991 }
@@ -87,6 +99,7 @@ impl ImageFormat {
8799 ImageFormat::WebP => "webp",
88100 ImageFormat::Gif => "gif",
89101 ImageFormat::Bmp => "bmp",
102+ ImageFormat::Tiff => "tiff",
90103 }
91104 }
92105 }
@@ -373,9 +386,10 @@ pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> {
373386 Some(ImageFormat::WebP) => webp::decode(data, limits),
374387 Some(ImageFormat::Gif) => gif::decode(data, limits),
375388 Some(ImageFormat::Bmp) => bmp::decode(data, limits),
389+ Some(ImageFormat::Tiff) => tiff::decode(data, limits),
376390 None => Err(Error::unsupported(
377391 "image",
378- "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data",
392+ "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data",
379393 )),
380394 }
381395 }
@@ -388,9 +402,10 @@ pub fn info(data: &[u8]) -> Result<Info> {
388402 Some(ImageFormat::WebP) => webp::info(data),
389403 Some(ImageFormat::Gif) => gif::info(data),
390404 Some(ImageFormat::Bmp) => bmp::info(data),
405+ Some(ImageFormat::Tiff) => tiff::info(data),
391406 None => Err(Error::unsupported(
392407 "image",
393- "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data",
408+ "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data",
394409 )),
395410 }
396411 }
crates/ec-image/src/tiff.rsadded+665 -0
@@ -0,0 +1,665 @@
1+//! TIFF: the tag-directory format scanners, cameras and every "save as
2+//! uncompressed" dialog write.
3+//!
4+//! A TIFF is a header pointing at a directory of tags, and the tags say where
5+//! the pixels are and how they were packed. Almost nothing about the layout is
6+//! fixed: rows may be grouped into strips or into tiles, samples may be
7+//! interleaved or stored one plane at a time, a sample may be 1, 2, 4, 8 or 16
8+//! bits wide, and the bytes may be little- or big-endian. This reads all of
9+//! those, with the compressions in general use -- none, LZW, PackBits and
10+//! Deflate -- and the horizontal-differencing predictor that usually
11+//! accompanies the last two.
12+//!
13+//! Refused by name, because the capability is genuinely absent rather than
14+//! merely unwritten: the CCITT fax compressions (2, 3, 4), which are a
15+//! different coder altogether, JPEG-in-TIFF (7), and BigTIFF, whose header is
16+//! a different format that happens to share a signature byte. The incumbent
17+//! `image` crate refuses all three as well.
18+
19+use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels};
20+use ec_core::{Error, Result};
21+
22+const TAG_WIDTH: u16 = 256;
23+const TAG_HEIGHT: u16 = 257;
24+const TAG_BITS: u16 = 258;
25+const TAG_COMPRESSION: u16 = 259;
26+const TAG_PHOTOMETRIC: u16 = 262;
27+const TAG_STRIP_OFFSETS: u16 = 273;
28+const TAG_ORIENTATION: u16 = 274;
29+const TAG_SAMPLES: u16 = 277;
30+const TAG_ROWS_PER_STRIP: u16 = 278;
31+const TAG_STRIP_COUNTS: u16 = 279;
32+const TAG_PLANAR: u16 = 284;
33+const TAG_PREDICTOR: u16 = 317;
34+const TAG_COLOR_MAP: u16 = 320;
35+const TAG_TILE_WIDTH: u16 = 322;
36+const TAG_TILE_HEIGHT: u16 = 323;
37+const TAG_TILE_OFFSETS: u16 = 324;
38+const TAG_TILE_COUNTS: u16 = 325;
39+const TAG_EXTRA_SAMPLES: u16 = 338;
40+const TAG_SAMPLE_FORMAT: u16 = 339;
41+
42+const COMPRESSION_NONE: u64 = 1;
43+const COMPRESSION_LZW: u64 = 5;
44+const COMPRESSION_DEFLATE: u64 = 8;
45+const COMPRESSION_PACKBITS: u64 = 32773;
46+const COMPRESSION_DEFLATE_OLD: u64 = 32946;
47+
48+/// The endianness the file declared, and the bytes it declared it about.
49+struct Reader<'a> {
50+ data: &'a [u8],
51+ big_endian: bool,
52+}
53+
54+impl<'a> Reader<'a> {
55+ fn u16_at(&self, at: usize) -> Result<u16> {
56+ let bytes = self
57+ .data
58+ .get(at..at + 2)
59+ .ok_or_else(|| Error::corrupt("TIFF: a field past the end of the file"))?;
60+ Ok(if self.big_endian {
61+ u16::from_be_bytes([bytes[0], bytes[1]])
62+ } else {
63+ u16::from_le_bytes([bytes[0], bytes[1]])
64+ })
65+ }
66+
67+ fn u32_at(&self, at: usize) -> Result<u32> {
68+ let bytes = self
69+ .data
70+ .get(at..at + 4)
71+ .ok_or_else(|| Error::corrupt("TIFF: a field past the end of the file"))?;
72+ Ok(if self.big_endian {
73+ u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
74+ } else {
75+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
76+ })
77+ }
78+}
79+
80+/// One directory entry, with its values already read.
81+struct Entry {
82+ tag: u16,
83+ values: Vec<u64>,
84+}
85+
86+/// Bytes one value of each TIFF type occupies.
87+fn type_size(kind: u16) -> Option<usize> {
88+ Some(match kind {
89+ 1 | 2 | 6 | 7 => 1,
90+ 3 | 8 => 2,
91+ 4 | 9 | 11 => 4,
92+ 5 | 10 | 12 => 8,
93+ _ => return None,
94+ })
95+}
96+
97+/// The image file directory at `offset`, as entries whose integer values are
98+/// already resolved.
99+///
100+/// Values of four bytes or fewer live in the entry itself; anything longer is
101+/// at an offset the entry holds. Non-integer types (rationals, floats, ASCII)
102+/// are read as raw words and ignored by every caller here, which only asks for
103+/// the geometry tags.
104+fn directory(reader: &Reader, offset: usize) -> Result<Vec<Entry>> {
105+ let count = reader.u16_at(offset)? as usize;
106+ let mut entries = Vec::with_capacity(count);
107+ for i in 0..count {
108+ let at = offset + 2 + i * 12;
109+ let tag = reader.u16_at(at)?;
110+ let kind = reader.u16_at(at + 2)?;
111+ let n = reader.u32_at(at + 4)? as usize;
112+ let Some(size) = type_size(kind) else {
113+ continue; // a type this decoder has no use for
114+ };
115+ // A count large enough to overflow the file is corrupt, and a count
116+ // large enough to exhaust memory is corrupt too: the biggest legitimate
117+ // value list is one offset per strip.
118+ if n > reader.data.len() {
119+ return Err(Error::corrupt("TIFF: a tag claiming more values than bytes"));
120+ }
121+ let total = n * size;
122+ let base = if total <= 4 {
123+ at + 8
124+ } else {
125+ reader.u32_at(at + 8)? as usize
126+ };
127+ let mut values = Vec::with_capacity(n);
128+ for v in 0..n {
129+ let at = base + v * size;
130+ values.push(match size {
131+ 1 => u64::from(
132+ *reader
133+ .data
134+ .get(at)
135+ .ok_or_else(|| Error::corrupt("TIFF: a value past the end of the file"))?,
136+ ),
137+ 2 => u64::from(reader.u16_at(at)?),
138+ 4 => u64::from(reader.u32_at(at)?),
139+ // Rationals and doubles: the numerator is the only half any
140+ // tag read here would want, and none of them do.
141+ _ => u64::from(reader.u32_at(at)?),
142+ });
143+ }
144+ entries.push(Entry { tag, values });
145+ }
146+ Ok(entries)
147+}
148+
149+/// Everything the tags say about the pixels.
150+struct Layout {
151+ width: u32,
152+ height: u32,
153+ bits: Vec<u16>,
154+ samples: usize,
155+ photometric: u64,
156+ compression: u64,
157+ planar: u64,
158+ predictor: u64,
159+ /// Strip or tile data offsets, in the order the file lists them.
160+ offsets: Vec<u64>,
161+ counts: Vec<u64>,
162+ /// `None` for a stripped file; the tile size for a tiled one.
163+ tile: Option<(u32, u32)>,
164+ rows_per_strip: u32,
165+ colour_map: Vec<u64>,
166+ /// Tag 338: whether the extra sample is alpha, and whether it is premultiplied.
167+ extra_samples: Vec<u64>,
168+ orientation: Option<u8>,
169+}
170+
171+fn tag<'e>(entries: &'e [Entry], tag: u16) -> Option<&'e Entry> {
172+ entries.iter().find(|e| e.tag == tag)
173+}
174+
175+fn first(entries: &[Entry], want: u16, default: u64) -> u64 {
176+ tag(entries, want)
177+ .and_then(|e| e.values.first().copied())
178+ .unwrap_or(default)
179+}
180+
181+fn layout(data: &[u8]) -> Result<Layout> {
182+ if data.len() < 8 {
183+ return Err(Error::corrupt("TIFF: a file too short to hold a header"));
184+ }
185+ let big_endian = match &data[0..2] {
186+ b"II" => false,
187+ b"MM" => true,
188+ _ => return Err(Error::corrupt("TIFF: no II or MM byte order mark")),
189+ };
190+ let reader = Reader { data, big_endian };
191+ match reader.u16_at(2)? {
192+ 42 => {}
193+ 43 => {
194+ return Err(Error::unsupported(
195+ "TIFF: a BigTIFF file (version 43)",
196+ "BigTIFF replaces every offset and count with a 64-bit one; \
197+ it shares the byte order mark but not the directory format",
198+ ));
199+ }
200+ other => {
201+ return Err(Error::corrupt(format!("TIFF: version {other}")));
202+ }
203+ }
204+ let entries = directory(&reader, reader.u32_at(4)? as usize)?;
205+
206+ let compression = first(&entries, TAG_COMPRESSION, COMPRESSION_NONE);
207+ match compression {
208+ COMPRESSION_NONE
209+ | COMPRESSION_LZW
210+ | COMPRESSION_DEFLATE
211+ | COMPRESSION_PACKBITS
212+ | COMPRESSION_DEFLATE_OLD => {}
213+ 2 | 3 | 4 => {
214+ return Err(Error::unsupported(
215+ format!("TIFF: CCITT compression {compression}"),
216+ "the fax coders are a separate format with their own \
217+ two-dimensional coding modes",
218+ ));
219+ }
220+ 6 | 7 => {
221+ return Err(Error::unsupported(
222+ "TIFF: a JPEG-compressed strip",
223+ "the strips hold JPEG scans with the tables in a separate tag; \
224+ decode such a file with the JPEG decoder once it is assembled",
225+ ));
226+ }
227+ other => return Err(Error::corrupt(format!("TIFF: compression {other}"))),
228+ }
229+
230+ let samples = first(&entries, TAG_SAMPLES, 1) as usize;
231+ if samples == 0 || samples > 4 {
232+ return Err(Error::corrupt(format!(
233+ "TIFF: {samples} samples per pixel"
234+ )));
235+ }
236+ let bits: Vec<u16> = tag(&entries, TAG_BITS)
237+ .map(|e| e.values.iter().map(|&v| v as u16).collect())
238+ .unwrap_or_else(|| vec![1; samples]);
239+ if bits.len() != samples {
240+ return Err(Error::corrupt(
241+ "TIFF: a bit-depth list that does not match the sample count",
242+ ));
243+ }
244+ if bits.iter().any(|b| *b != bits[0]) {
245+ return Err(Error::unsupported(
246+ "TIFF: channels of different depths",
247+ "every channel is unpacked with one width; a file mixing them \
248+ would need a per-channel unpacker",
249+ ));
250+ }
251+ if !matches!(bits[0], 1 | 2 | 4 | 8 | 16) {
252+ return Err(Error::unsupported(
253+ format!("TIFF: {}-bit samples", bits[0]),
254+ "1, 2, 4, 8 and 16 are the widths this decoder unpacks",
255+ ));
256+ }
257+ if first(&entries, TAG_SAMPLE_FORMAT, 1) == 3 {
258+ return Err(Error::unsupported(
259+ "TIFF: floating-point samples",
260+ "sample format 3 stores IEEE floats, which have no fixed range to \
261+ map onto an integer picture",
262+ ));
263+ }
264+
265+ let photometric = first(&entries, TAG_PHOTOMETRIC, 1);
266+ if !matches!(photometric, 0 | 1 | 2 | 3) {
267+ return Err(Error::unsupported(
268+ format!("TIFF: photometric interpretation {photometric}"),
269+ "white-is-zero, black-is-zero, RGB and palette are the colour \
270+ models this decoder converts",
271+ ));
272+ }
273+
274+ let predictor = first(&entries, TAG_PREDICTOR, 1);
275+ if !matches!(predictor, 1 | 2) {
276+ return Err(Error::unsupported(
277+ format!("TIFF: predictor {predictor}"),
278+ "1 (none) and 2 (horizontal differencing) are the integer \
279+ predictors; 3 is the floating-point one",
280+ ));
281+ }
282+
283+ let tile = match (tag(&entries, TAG_TILE_WIDTH), tag(&entries, TAG_TILE_HEIGHT)) {
284+ (Some(w), Some(h)) => Some((
285+ *w.values.first().unwrap_or(&0) as u32,
286+ *h.values.first().unwrap_or(&0) as u32,
287+ )),
288+ _ => None,
289+ };
290+ let (offsets_tag, counts_tag) = if tile.is_some() {
291+ (TAG_TILE_OFFSETS, TAG_TILE_COUNTS)
292+ } else {
293+ (TAG_STRIP_OFFSETS, TAG_STRIP_COUNTS)
294+ };
295+ let offsets = tag(&entries, offsets_tag)
296+ .map(|e| e.values.clone())
297+ .ok_or_else(|| Error::corrupt("TIFF: no strip or tile offsets"))?;
298+ let counts = tag(&entries, counts_tag)
299+ .map(|e| e.values.clone())
300+ .ok_or_else(|| Error::corrupt("TIFF: no strip or tile byte counts"))?;
301+ if offsets.len() != counts.len() {
302+ return Err(Error::corrupt(
303+ "TIFF: as many offsets as byte counts is the one thing the format promises",
304+ ));
305+ }
306+
307+ let orientation = match first(&entries, TAG_ORIENTATION, 0) {
308+ v @ 1..=8 => Some(v as u8),
309+ _ => None,
310+ };
311+
312+ Ok(Layout {
313+ width: first(&entries, TAG_WIDTH, 0) as u32,
314+ height: first(&entries, TAG_HEIGHT, 0) as u32,
315+ bits,
316+ samples,
317+ photometric,
318+ compression,
319+ planar: first(&entries, TAG_PLANAR, 1),
320+ predictor,
321+ offsets,
322+ counts,
323+ tile,
324+ rows_per_strip: first(&entries, TAG_ROWS_PER_STRIP, u64::from(u32::MAX)).min(u64::from(u32::MAX))
325+ as u32,
326+ colour_map: tag(&entries, TAG_COLOR_MAP)
327+ .map(|e| e.values.clone())
328+ .unwrap_or_default(),
329+ extra_samples: tag(&entries, TAG_EXTRA_SAMPLES)
330+ .map(|e| e.values.clone())
331+ .unwrap_or_default(),
332+ orientation,
333+ })
334+}
335+
336+/// Dimensions from the first directory, without decoding the pixels.
337+pub fn info(data: &[u8]) -> Result<Info> {
338+ let layout = layout(data)?;
339+ Ok(Info {
340+ format: ImageFormat::Tiff,
341+ width: layout.width,
342+ height: layout.height,
343+ })
344+}
345+
346+/// TIFF's LZW: MSB-first codes, and the width grows one code early.
347+///
348+/// The "one code early" is the difference from the GIF variant: a TIFF encoder
349+/// switches to the next width when the *next* code to be assigned would not
350+/// fit, so a decoder that waits for the code itself desynchronises a byte into
351+/// every image.
352+fn lzw(input: &[u8], hint: usize) -> Result<Vec<u8>> {
353+ const CLEAR: u16 = 256;
354+ const END: u16 = 257;
355+ let mut out = Vec::with_capacity(hint);
356+ // Each entry is a previous code plus one byte, walked backwards on emit,
357+ // which keeps the table one allocation instead of one per string.
358+ let mut prefix = vec![0u16; 4096];
359+ let mut suffix = vec![0u8; 4096];
360+ let mut next = 258usize;
361+ let mut width = 9u32;
362+ let mut previous: Option<u16> = None;
363+ let (mut bit, mut acc, mut have) = (0usize, 0u32, 0u32);
364+ let mut stack = Vec::with_capacity(4096);
365+ loop {
366+ while have < width {
367+ let Some(&byte) = input.get(bit) else {
368+ return Ok(out);
369+ };
370+ bit += 1;
371+ acc = (acc << 8) | u32::from(byte);
372+ have += 8;
373+ }
374+ let code = ((acc >> (have - width)) & ((1 << width) - 1)) as u16;
375+ have -= width;
376+ match code {
377+ CLEAR => {
378+ next = 258;
379+ width = 9;
380+ previous = None;
381+ continue;
382+ }
383+ END => return Ok(out),
384+ _ => {}
385+ }
386+ stack.clear();
387+ let first_byte = if (code as usize) < next {
388+ let mut walk = code;
389+ while walk >= 258 {
390+ stack.push(suffix[walk as usize]);
391+ walk = prefix[walk as usize];
392+ }
393+ if walk > 255 {
394+ return Err(Error::corrupt("TIFF: an LZW code with no string"));
395+ }
396+ stack.push(walk as u8);
397+ *stack.last().unwrap()
398+ } else if let Some(previous) = previous {
399+ // The KwKwK case: the code being emitted is the one this step is
400+ // about to define.
401+ let mut walk = previous;
402+ while walk >= 258 {
403+ stack.push(suffix[walk as usize]);
404+ walk = prefix[walk as usize];
405+ }
406+ stack.push(walk as u8);
407+ let first = *stack.last().unwrap();
408+ stack.insert(0, first);
409+ first
410+ } else {
411+ return Err(Error::corrupt("TIFF: an LZW stream opening with a new code"));
412+ };
413+ out.extend(stack.iter().rev());
414+ if let Some(previous) = previous {
415+ if next < 4096 {
416+ prefix[next] = previous;
417+ suffix[next] = first_byte;
418+ next += 1;
419+ }
420+ }
421+ previous = Some(code);
422+ // One code early: 511, not 512, is where nine bits stop being enough.
423+ if next + 1 >= (1 << width) && width < 12 {
424+ width += 1;
425+ }
426+ }
427+}
428+
429+/// PackBits: a run-length coder whose control byte is signed.
430+fn packbits(input: &[u8], hint: usize) -> Vec<u8> {
431+ let mut out = Vec::with_capacity(hint);
432+ let mut at = 0usize;
433+ while at < input.len() {
434+ let control = input[at] as i8;
435+ at += 1;
436+ if control >= 0 {
437+ let run = control as usize + 1;
438+ let end = (at + run).min(input.len());
439+ out.extend_from_slice(&input[at..end]);
440+ at = end;
441+ } else if control != -128 {
442+ let run = (-i32::from(control)) as usize + 1;
443+ let Some(&byte) = input.get(at) else { break };
444+ at += 1;
445+ out.extend(std::iter::repeat_n(byte, run));
446+ } else {
447+ // -128 is a no-op the format reserves.
448+ }
449+ }
450+ out
451+}
452+
453+/// One strip or tile, decompressed.
454+fn segment(layout: &Layout, data: &[u8], index: usize, expect: usize) -> Result<Vec<u8>> {
455+ let at = layout.offsets[index] as usize;
456+ let len = layout.counts[index] as usize;
457+ let body = data
458+ .get(at..at.saturating_add(len))
459+ .ok_or_else(|| Error::corrupt("TIFF: a strip reaching past the end of the file"))?;
460+ Ok(match layout.compression {
461+ COMPRESSION_NONE => body.to_vec(),
462+ COMPRESSION_LZW => lzw(body, expect)?,
463+ COMPRESSION_PACKBITS => packbits(body, expect),
464+ _ => ec_inflate::inflate_zlib(body, expect.saturating_mul(2).max(1024))
465+ .map_err(|e| Error::corrupt(format!("TIFF: a Deflate strip: {e}")))?,
466+ })
467+}
468+
469+/// Undo horizontal differencing across one row of `channels` interleaved samples.
470+/// Horizontal differencing runs at the sample's own width, so the sum wraps at
471+/// `mask + 1` -- an 8-bit file wraps at 256, not at the u16 these are held in.
472+fn undo_predictor(row: &mut [u16], channels: usize, mask: u16) {
473+ for i in channels..row.len() {
474+ row[i] = row[i].wrapping_add(row[i - channels]) & mask;
475+ }
476+}
477+
478+/// Read `count` samples of `bits` width from `bytes`, MSB-first.
479+fn unpack(bytes: &[u8], bits: u16, count: usize, out: &mut Vec<u16>, big_endian: bool) {
480+ match bits {
481+ 16 => {
482+ for i in 0..count {
483+ let (a, b) = (
484+ bytes.get(i * 2).copied().unwrap_or(0),
485+ bytes.get(i * 2 + 1).copied().unwrap_or(0),
486+ );
487+ out.push(if big_endian {
488+ u16::from_be_bytes([a, b])
489+ } else {
490+ u16::from_le_bytes([a, b])
491+ });
492+ }
493+ }
494+ 8 => out.extend(
495+ (0..count).map(|i| u16::from(bytes.get(i).copied().unwrap_or(0))),
496+ ),
497+ _ => {
498+ let per_byte = 8 / bits as usize;
499+ let mask = (1u16 << bits) - 1;
500+ for i in 0..count {
501+ let byte = bytes.get(i / per_byte).copied().unwrap_or(0);
502+ let shift = 8 - bits as usize * (i % per_byte + 1);
503+ out.push((u16::from(byte) >> shift) & mask);
504+ }
505+ }
506+ }
507+}
508+
509+/// Decode the first image in the file.
510+pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
511+ let layout = layout(data)?;
512+ limits.check(layout.width, layout.height)?;
513+ let (width, height) = (layout.width as usize, layout.height as usize);
514+ if width == 0 || height == 0 {
515+ return Err(Error::corrupt("TIFF: a zero-sized picture"));
516+ }
517+ let big_endian = data.starts_with(b"MM");
518+ let bits = layout.bits[0];
519+ let samples = layout.samples;
520+ let planar = layout.planar == 2;
521+ let planes = if planar { samples } else { 1 };
522+ let per_plane = if planar { 1 } else { samples };
523+
524+ // Samples land here interleaved, whatever the file's own arrangement was.
525+ let mut raw = vec![0u16; width * height * samples];
526+
527+ // Strips and tiles differ only in the rectangle one segment covers.
528+ let (seg_w, seg_h) = match layout.tile {
529+ Some((w, h)) if w > 0 && h > 0 => (w as usize, h as usize),
530+ Some(_) => return Err(Error::corrupt("TIFF: a zero-sized tile")),
531+ None => (width, layout.rows_per_strip.max(1) as usize),
532+ };
533+ let across = width.div_ceil(seg_w);
534+ let down = height.div_ceil(seg_h);
535+ let per_plane_segments = across * down;
536+ if layout.offsets.len() < per_plane_segments * planes {
537+ return Err(Error::corrupt(
538+ "TIFF: fewer strips than the geometry needs",
539+ ));
540+ }
541+
542+ // A tile is always its full width; a strip is only as wide as the picture,
543+ // and its last one only as tall as the rows that remain.
544+ let row_samples = seg_w * per_plane;
545+ let row_bytes = (row_samples * bits as usize).div_ceil(8);
546+ let mut row = Vec::with_capacity(row_samples);
547+ let full = ((1u32 << bits) - 1) as u16;
548+ for index in 0..per_plane_segments * planes {
549+ let plane = index / per_plane_segments;
550+ let within = index % per_plane_segments;
551+ let (col, band) = (within % across, within / across);
552+ let expect = row_bytes * seg_h;
553+ let body = segment(&layout, data, index, expect)?;
554+ for r in 0..seg_h {
555+ let y = band * seg_h + r;
556+ if y >= height {
557+ break;
558+ }
559+ let at = r * row_bytes;
560+ let Some(bytes) = body.get(at..(at + row_bytes).min(body.len())) else {
561+ break;
562+ };
563+ row.clear();
564+ unpack(bytes, bits, row_samples, &mut row, big_endian);
565+ if layout.predictor == 2 {
566+ undo_predictor(&mut row, per_plane, full);
567+ }
568+ for x in 0..seg_w {
569+ let px = col * seg_w + x;
570+ if px >= width {
571+ break;
572+ }
573+ for s in 0..per_plane {
574+ let channel = if planar { plane } else { s };
575+ raw[(y * width + px) * samples + channel] = row[x * per_plane + s];
576+ }
577+ }
578+ }
579+ }
580+
581+ // Widths below 8 bits are stretched to full scale so that a bilevel file's
582+ // 1 becomes white rather than one two-hundred-and-fifty-fifth of it.
583+ let pixels = build(&layout, &raw, width * height, bits, full)?;
584+ Ok(Image {
585+ width: layout.width,
586+ height: layout.height,
587+ pixels,
588+ meta: Metadata {
589+ orientation: layout.orientation,
590+ ..Metadata::default()
591+ },
592+ })
593+}
594+
595+/// Turn raw samples into the crate's colour form.
596+fn build(layout: &Layout, raw: &[u16], count: usize, bits: u16, full: u16) -> Result<Pixels> {
597+ let samples = layout.samples;
598+ let alpha = samples == 2 || samples == 4;
599+ // Extra sample type 1 is straight alpha and 2 is associated -- the colour
600+ // channels already multiplied by it. This crate carries straight alpha, so
601+ // an associated file is divided back out; where alpha is full, which is
602+ // what ImageMagick writes for an opaque picture, that is the identity.
603+ let associated = alpha && layout.extra_samples.first() == Some(&2);
604+ // 8-bit output for everything but a 16-bit file, whose depth survives.
605+ let widen = |v: u16| -> u16 {
606+ if bits == 16 {
607+ v
608+ } else {
609+ // round(v * 65535 / full)
610+ ((u32::from(v) * 65535 + u32::from(full) / 2) / u32::from(full)) as u16
611+ }
612+ };
613+ let narrow = |v: u16| -> u8 { ((u32::from(v) * 255 + 32767) / 65535) as u8 };
614+
615+ if layout.photometric == 3 {
616+ // A palette: three ranges of 16-bit values, one per channel, in a
617+ // single tag.
618+ let entries = layout.colour_map.len() / 3;
619+ if entries == 0 {
620+ return Err(Error::corrupt("TIFF: a palette picture with no colour map"));
621+ }
622+ let mut out = Vec::with_capacity(count * 3);
623+ for &index in raw.iter().take(count) {
624+ let index = index as usize;
625+ if index >= entries {
626+ return Err(Error::corrupt("TIFF: a palette index past the colour map"));
627+ }
628+ for c in 0..3 {
629+ out.push(narrow(layout.colour_map[c * entries + index] as u16));
630+ }
631+ }
632+ return Ok(Pixels::Rgb8(out));
633+ }
634+
635+ let invert = layout.photometric == 0;
636+ let mut wide: Vec<u16> = Vec::with_capacity(raw.len());
637+ for (i, &v) in raw.iter().enumerate() {
638+ let is_alpha = alpha && (i % samples) == samples - 1;
639+ let v = widen(v);
640+ wide.push(if invert && !is_alpha { 65535 - v } else { v });
641+ }
642+ if associated {
643+ for pixel in wide.chunks_mut(samples) {
644+ let a = u32::from(pixel[samples - 1]);
645+ for channel in &mut pixel[..samples - 1] {
646+ *channel = if a == 0 {
647+ 0
648+ } else {
649+ (((u32::from(*channel) * 65535 + a / 2) / a).min(65535)) as u16
650+ };
651+ }
652+ }
653+ }
654+
655+ Ok(match (samples, bits) {
656+ (1, 16) => Pixels::L16(wide),
657+ (2, 16) => Pixels::La16(wide),
658+ (3, 16) => Pixels::Rgb16(wide),
659+ (4, 16) => Pixels::Rgba16(wide),
660+ (1, _) => Pixels::L8(wide.iter().map(|&v| narrow(v)).collect()),
661+ (2, _) => Pixels::La8(wide.iter().map(|&v| narrow(v)).collect()),
662+ (3, _) => Pixels::Rgb8(wide.iter().map(|&v| narrow(v)).collect()),
663+ _ => Pixels::Rgba8(wide.iter().map(|&v| narrow(v)).collect()),
664+ })
665+}
crates/ec-image/tests/differential.rsmodified+99 -0
@@ -630,3 +630,102 @@ fn an_os2_v2_header_reads_as_the_same_picture() {
630630 "os2v2.bmp: samples differ from the same picture in a v1 header"
631631 );
632632 }
633+
634+/// TIFF stores raw samples, so like BMP the only question is whether the two
635+/// decoders read the same tags the same way. The corpus crosses every
636+/// compression with both byte orders, strips against tiles, interleaved
637+/// samples against planes, and five sample depths.
638+#[test]
639+fn tiff_decodes_pixel_exactly() {
640+ let mut files = corpus("tiff");
641+ files.extend(corpus("tif"));
642+ files.sort();
643+ if files.is_empty() && skip("tiff") {
644+ return;
645+ }
646+ for path in files {
647+ let name = path.file_name().unwrap().to_string_lossy().to_string();
648+ if name == "palette4.tiff" {
649+ continue; // the incumbent refuses a 4-bit palette; its own test covers it
650+ }
651+ if name == "rgba8-assoc.tiff" {
652+ continue; // the incumbent ignores ExtraSamples; its own test covers it
653+ }
654+ let data = std::fs::read(&path).unwrap();
655+ let ours = ec_image::decode(&data).unwrap_or_else(|e| panic!("{name}: {e}"));
656+ let theirs = image::load_from_memory(&data).unwrap_or_else(|e| panic!("{name}: {e}"));
657+ assert_eq!(
658+ (ours.width, ours.height),
659+ theirs.dimensions(),
660+ "{name}: dimensions differ"
661+ );
662+ let (max, corr) = compare(&ours.to_rgba8(), &theirs.to_rgba8().into_raw());
663+ println!("{name:>20} max {max} corr {corr:.6}");
664+ assert_eq!(max, 0, "{name}: samples differ from the incumbent");
665+ }
666+}
667+
668+/// TIFF tags its alpha as either straight (ExtraSamples 1) or associated
669+/// (ExtraSamples 2, premultiplied). The incumbent hands back the file's raw
670+/// samples either way, so it cannot arbitrate the premultiplied one; the two
671+/// fixtures carry the same picture at alpha 0 or 255, where premultiplying is
672+/// lossless, so the associated file must decode to the straight one exactly.
673+#[test]
674+fn an_associated_alpha_tiff_reads_unpremultiplied() {
675+ let (Ok(assoc), Ok(straight)) = (
676+ std::fs::read(fixtures().join("rgba8-assoc.tiff")),
677+ std::fs::read(fixtures().join("rgba8.tiff")),
678+ ) else {
679+ skip("rgba8-assoc.tiff");
680+ return;
681+ };
682+ let ours = ec_image::decode(&assoc).expect("rgba8-assoc.tiff");
683+ let reference = ec_image::decode(&straight).expect("rgba8.tiff");
684+ // Under a zero alpha the colour is gone for good -- premultiplying by zero
685+ // is not invertible -- so those pixels are compared on their alpha alone.
686+ let (ours, reference) = (ours.to_rgba8(), reference.to_rgba8());
687+ for (i, (a, b)) in ours.chunks(4).zip(reference.chunks(4)).enumerate() {
688+ assert_eq!(a[3], b[3], "rgba8-assoc.tiff: alpha differs at pixel {i}");
689+ if b[3] != 0 {
690+ assert_eq!(
691+ a[..3],
692+ b[..3],
693+ "rgba8-assoc.tiff: the premultiplication was not undone at pixel {i}"
694+ );
695+ }
696+ }
697+
698+ // The incumbent ignores the tag, so its two decodes differ: were that to
699+ // change, this test would be comparing against nothing.
700+ let a = image::load_from_memory(&assoc).expect("incumbent rgba8-assoc.tiff");
701+ let b = image::load_from_memory(&straight).expect("incumbent rgba8.tiff");
702+ assert_ne!(
703+ a.to_rgba8().into_raw(),
704+ b.to_rgba8().into_raw(),
705+ "the incumbent now honours ExtraSamples; use it as the oracle instead"
706+ );
707+}
708+
709+/// A 4-bit palette, which the incumbent refuses ("Photometric interpretation
710+/// RGBPalette with bits per sample [4] is unsupported") and ffmpeg reads. The
711+/// oracle is therefore ffmpeg's own decode of the same file, written to a PNG
712+/// when the corpus was generated.
713+#[test]
714+fn a_four_bit_tiff_palette_reads_as_ffmpeg_reads_it() {
715+ let (Ok(narrow), Ok(wide)) = (
716+ std::fs::read(fixtures().join("palette4.tiff")),
717+ std::fs::read(fixtures().join("palette4-golden.png")),
718+ ) else {
719+ skip("palette4.tiff");
720+ return;
721+ };
722+ assert!(
723+ image::load_from_memory(&narrow).is_err(),
724+ "the incumbent now reads a 4-bit palette; this test's premise is stale"
725+ );
726+ let ours = ec_image::decode(&narrow).unwrap();
727+ let reference = image::load_from_memory(&wide).unwrap();
728+ assert_eq!((ours.width, ours.height), reference.dimensions());
729+ let (max, _) = compare(&ours.to_rgba8(), &reference.to_rgba8().into_raw());
730+ assert_eq!(max, 0, "palette4.tiff: samples differ from the same palette at 8 bits");
731+}
crates/ec-image/tests/fuzz.rsmodified+17 -1
@@ -212,13 +212,29 @@ fn a_run_length_bmp_survives_mutation() {
212212 sweep("bmp-rle", "rle8.bmp");
213213 }
214214
215+/// TIFF is a directory of offsets into itself: a mutation can point a strip,
216+/// a palette or the directory's own continuation anywhere in the file.
217+#[test]
218+fn tiff_survives_mutation() {
219+ sweep("tiff", "tiny.tiff");
220+}
221+
222+/// The compressed, predicted path decodes into a row buffer whose length comes
223+/// from tags the mutation is free to disagree about, so it gets its own seed.
224+#[test]
225+fn a_compressed_tiff_survives_mutation() {
226+ sweep("tiff-lzw", "rgb8-lzw-pred.tiff");
227+}
228+
215229 #[test]
216230 fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() {
217- let signatures: [&[u8]; 5] = [
231+ let signatures: [&[u8]; 6] = [
218232 &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
219233 &[0xff, 0xd8, 0xff, 0xe0],
220234 b"RIFF\x40\x00\x00\x00WEBPVP8 ",
221235 b"GIF89a",
236+ // A TIFF header whose directory offset is inside the header itself.
237+ b"II\x2a\x00\x04\x00\x00\x00",
222238 // "BM" alone is two bytes anything could start with, so the guess also
223239 // asks the file header to agree with itself: this prefix declares a
224240 // 40-byte info header and pixels at 54, which is what makes the bytes
scripts/gen-still-fixtures.shmodified+48 -0
@@ -163,6 +163,53 @@ python3 "$(dirname "$0")/lib/gen-bmp-shapes.py" "$out" "$out/bmp-source.rgba" 64
163163 rm -f "$out/bmp-source.png" "$out/bmp-source-alpha.png" "$out/bmp-source.rgba" \
164164 "$out/bmp-source-alpha.rgba" "$out/bmp-embed.png" "$out/bmp-embed.jpg"
165165
166+# --- TIFF: both byte orders, four compressions, strips and tiles -----------
167+# TIFF fixes almost nothing about its layout, so the corpus is a cross-product:
168+# each compression, each sample depth, both byte orders, strips and tiles, and
169+# both plane arrangements. ImageMagick writes all of them.
170+magick "$out/source.png" -resize 64x48! "$out/tiff-source.png"
171+magick "$out/source-alpha.png" -resize 64x48! "$out/tiff-source-alpha.png"
172+magick "$out/tiff-source.png" -depth 8 -compress None "$out/rgb8.tiff"
173+magick "$out/tiff-source.png" -depth 8 -compress LZW "$out/rgb8-lzw.tiff"
174+magick "$out/tiff-source.png" -depth 8 -compress RLE "$out/rgb8-packbits.tiff"
175+magick "$out/tiff-source.png" -depth 8 -compress Zip "$out/rgb8-zip.tiff"
176+# The horizontal-differencing predictor, which is what an encoder reaches for
177+# when the compression is LZW or Deflate.
178+magick "$out/tiff-source.png" -depth 8 -compress LZW -define tiff:predictor=2 \
179+ "$out/rgb8-lzw-pred.tiff"
180+magick "$out/tiff-source.png" -depth 8 -compress Zip -define tiff:predictor=2 \
181+ "$out/rgb8-zip-pred.tiff"
182+# Big-endian: the same picture with every field byte-swapped.
183+magick "$out/tiff-source.png" -depth 8 -compress None -define tiff:endian=msb \
184+ "$out/rgb8-be.tiff"
185+# Tiles rather than strips, and planes rather than interleaved samples.
186+magick "$out/tiff-source.png" -depth 8 -compress LZW \
187+ -define tiff:tile-geometry=32x32 "$out/rgb8-tiled.tiff"
188+magick "$out/tiff-source.png" -depth 8 -compress None -interlace Plane \
189+ "$out/rgb8-planar.tiff"
190+# Depths: bilevel, 4-bit palette, 8-bit grey, 16-bit grey and 16-bit colour.
191+magick "$out/tiff-source.png" -monochrome -type bilevel -compress None \
192+ "$out/bilevel.tiff"
193+magick "$out/tiff-source.png" -colors 16 -type palette -depth 4 -compress None \
194+ "$out/palette4.tiff"
195+# The incumbent refuses a 4-bit palette outright, so ffmpeg -- which reads it --
196+# writes the reference picture for that one fixture.
197+ffmpeg -loglevel error -y -i "$out/palette4.tiff" "$out/palette4-golden.png"
198+# -alpha off, or ImageMagick attaches an alpha channel to a grey picture that
199+# has none, and a two-sample grey file is a shape the incumbent refuses.
200+magick "$out/tiff-source.png" -colorspace gray -alpha off -depth 8 -compress None \
201+ "$out/gray8.tiff"
202+magick "$out/tiff-source.png" -colorspace gray -alpha off -depth 16 -compress None \
203+ "$out/gray16.tiff"
204+magick "$out/tiff-source.png" -depth 16 -compress Zip "$out/rgb16.tiff"
205+# Alpha, which TIFF carries as a fourth sample plus an ExtraSamples tag: both
206+# the straight and the premultiplied tagging, neither of which ImageMagick will
207+# write on request.
208+magick "$out/tiff-source-alpha.png" rgba:"$out/tiff-source-alpha.rgba"
209+python3 "$(dirname "$0")/lib/gen-tiff-shapes.py" "$out" "$out/tiff-source-alpha.rgba" 64 48
210+rm -f "$out/tiff-source.png" "$out/tiff-source-alpha.png" \
211+ "$out/tiff-source-alpha.rgba"
212+
166213 # Small versions of each format, for the fuzz sweep: ten thousand mutations
167214 # per format is only affordable on a picture that decodes in microseconds.
168215 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
172219 ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 1 "$out/tiny-lossless.webp"
173220 magick "$out/tiny.png" -colors 64 "$out/tiny.gif"
174221 magick "$out/tiny.png" -colors 64 -type palette -compress None BMP3:"$out/tiny.bmp"
222+magick "$out/tiny.png" -depth 8 -compress LZW "$out/tiny.tiff"
175223
176224 echo "wrote $(ls "$out" | wc -l) files to $out"
scripts/lib/gen-tiff-shapes.pyadded+66 -0
@@ -0,0 +1,66 @@
1+"""Write the TIFF alpha shapes ImageMagick will not emit.
2+
3+ImageMagick always tags a TIFF's alpha channel as associated (ExtraSamples 2,
4+premultiplied) and ignores ``-define tiff:alpha=unassociated``, so the ordinary
5+straight-alpha file -- the common one -- has to be written here. Both files
6+carry the same picture with the alpha flattened to 0 or 255, which makes the
7+premultiplication lossless and so lets the two decode to identical pixels.
8+"""
9+
10+import struct
11+import sys
12+
13+out, raw, width, height = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])
14+rgba = open(raw, "rb").read()
15+
16+# Flatten alpha to fully transparent or fully opaque: premultiplying by 0 or 1
17+# loses nothing, so the associated file is recoverable exactly.
18+body = bytearray()
19+for i in range(0, width * height * 4, 4):
20+ r, g, b, a = rgba[i : i + 4]
21+ body += bytes((r, g, b, 255 if a >= 128 else 0))
22+
23+
24+def tiff(path, extra_samples):
25+ """A little-endian, uncompressed, single-strip RGBA file."""
26+ pixels = bytearray(body)
27+ if extra_samples == 2:
28+ for i in range(0, len(pixels), 4):
29+ if pixels[i + 3] == 0:
30+ pixels[i : i + 3] = b"\x00\x00\x00"
31+
32+ # The header is 8 bytes, then the strip, then the directory: writing the
33+ # pixels first keeps every out-of-line value at a known offset behind it.
34+ strip = 8
35+ ifd = strip + len(pixels)
36+ entries = [
37+ (256, 3, 1, width), # ImageWidth
38+ (257, 3, 1, height), # ImageLength
39+ (258, 3, 4, None), # BitsPerSample, four shorts, out of line
40+ (259, 3, 1, 1), # Compression: none
41+ (262, 3, 1, 2), # PhotometricInterpretation: RGB
42+ (273, 4, 1, strip), # StripOffsets
43+ (277, 3, 1, 4), # SamplesPerPixel
44+ (278, 3, 1, height), # RowsPerStrip
45+ (279, 4, 1, len(pixels)), # StripByteCounts
46+ (284, 3, 1, 1), # PlanarConfiguration: chunky
47+ (338, 3, 1, extra_samples), # ExtraSamples
48+ ]
49+ trailing = ifd + 2 + 12 * len(entries) + 4
50+
51+ directory = struct.pack("<H", len(entries))
52+ for tag, kind, count, value in entries:
53+ if value is None:
54+ directory += struct.pack("<HHII", tag, kind, count, trailing)
55+ elif kind == 3:
56+ directory += struct.pack("<HHIHH", tag, kind, count, value, 0)
57+ else:
58+ directory += struct.pack("<HHII", tag, kind, count, value)
59+ directory += struct.pack("<I", 0)
60+ directory += struct.pack("<4H", 8, 8, 8, 8)
61+
62+ open(path, "wb").write(b"II\x2a\x00" + struct.pack("<I", ifd) + pixels + directory)
63+
64+
65+tiff(f"{out}/rgba8.tiff", 1)
66+tiff(f"{out}/rgba8-assoc.tiff", 2)
shims/image/src/lib.rsmodified+4 -0
@@ -392,6 +392,10 @@ fn format_of(data: &[u8]) -> Option<ImageFormat> {
392392 ec_image::ImageFormat::Bmp => Some(ImageFormat::Bmp),
393393 #[cfg(not(feature = "gpui"))]
394394 ec_image::ImageFormat::Bmp => None,
395+ #[cfg(feature = "gpui")]
396+ ec_image::ImageFormat::Tiff => Some(ImageFormat::Tiff),
397+ #[cfg(not(feature = "gpui"))]
398+ ec_image::ImageFormat::Tiff => None,
395399 }
396400 }
397401