forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-image-tiff': a TIFF decoder for the gpui surface

Browse files at this commit

43209384e10377364189cc722dc39deb66f024afAhmet Kaan GümüşParent: 810888755b1d36
crates/ec-image/src/lib.rsmodified+31 -13
@@ -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.
2 //!2 //!
3 //! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the3 //! One entry point — [`decode`] over bytes, [`open`] over a path — guesses the
4 //! format from the leading bytes and hands back an [`Image`]: dimensions, a4 //! format from the leading bytes and hands back an [`Image`]: dimensions, a
@@ -35,6 +35,7 @@ pub mod bmp;
35 pub mod gif;35 pub mod gif;
36 pub mod jpeg;36 pub mod jpeg;
37 pub mod png;37 pub mod png;
38+pub mod tiff;
38 mod upsample;39 mod upsample;
39 pub mod webp;40 pub mod webp;
40 41
@@ -57,6 +58,8 @@ pub enum ImageFormat {
57 Gif,58 Gif,
58 /// Windows BMP (device-independent bitmap).59 /// Windows BMP (device-independent bitmap).
59 Bmp,60 Bmp,
61+ /// TIFF, the tag-directory format.
62+ Tiff,
60 }63 }
61 64
62 impl ImageFormat {65 impl ImageFormat {
@@ -74,6 +77,15 @@ impl ImageFormat {
74 Some(ImageFormat::Gif)77 Some(ImageFormat::Gif)
75 } else if is_bmp(data) {78 } else if is_bmp(data) {
76 Some(ImageFormat::Bmp)79 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)
77 } else {89 } else {
78 None90 None
79 }91 }
@@ -87,6 +99,7 @@ impl ImageFormat {
87 ImageFormat::WebP => "webp",99 ImageFormat::WebP => "webp",
88 ImageFormat::Gif => "gif",100 ImageFormat::Gif => "gif",
89 ImageFormat::Bmp => "bmp",101 ImageFormat::Bmp => "bmp",
102+ ImageFormat::Tiff => "tiff",
90 }103 }
91 }104 }
92 }105 }
@@ -123,10 +136,12 @@ pub struct Limits {
123 /// Largest total bytes accepted across every frame of one decode call.136 /// Largest total bytes accepted across every frame of one decode call.
124 ///137 ///
125 /// A single frame can pass [`Limits::check_bytes`] on its own and still138 /// A single frame can pass [`Limits::check_bytes`] on its own and still
126- /// be a bomb once an animation's frame count multiplies it — GIF and139+ /// be a bomb once a frame or segment count multiplies it — GIF and WebP
127- /// WebP both composite onto a full canvas per frame, so a file with many140+ /// both composite onto a full canvas per frame, and a stripped or tiled
128- /// small-looking frames can retain gigabytes nothing ever checked one141+ /// TIFF decompresses many segments per call, so a file whose parts each
129- /// buffer at a time. [`AllocBudget`] enforces this across a decode call.142+ /// look small on their own can still retain gigabytes nothing ever
143+ /// checked one buffer at a time. [`AllocBudget`] enforces this across a
144+ /// decode call.
130 pub max_total_alloc: usize,145 pub max_total_alloc: usize,
131 }146 }
132 147
@@ -156,8 +171,8 @@ impl Limits {
156 Ok(())171 Ok(())
157 }172 }
158 173
159- /// Check a byte count computed from header-declared fields (a frame's174+ /// Check a byte count computed from header-declared fields (a frame's or
160- /// `width * height * bpp`, a palette size, a chunk length) before it175+ /// strip's `width * height * bpp`, a palette size, a chunk length) before it
161 /// sizes a single allocation. `what` names the buffer for the error.176 /// sizes a single allocation. `what` names the buffer for the error.
162 pub fn check_bytes(&self, what: &str, bytes: Option<usize>) -> Result<usize> {177 pub fn check_bytes(&self, what: &str, bytes: Option<usize>) -> Result<usize> {
163 let bytes =178 let bytes =
@@ -172,10 +187,11 @@ impl Limits {
172 }187 }
173 }188 }
174 189
175-/// Accumulates bytes spent across every frame of one decode call and refuses190+/// Accumulates bytes spent across every frame or segment of one decode call
176-/// once the running total crosses [`Limits::max_total_alloc`] — the guard191+/// and refuses once the running total crosses [`Limits::max_total_alloc`] —
177-/// for `frame_count x canvas`, which [`Limits::check_bytes`] alone never192+/// the guard for `frame_count x canvas` or `segment_count x segment_size`,
178-/// sees since it only ever looks at one buffer at a time.193+/// which [`Limits::check_bytes`] alone never sees since it only ever looks
194+/// at one buffer at a time.
179 #[derive(Debug, Default)]195 #[derive(Debug, Default)]
180 pub struct AllocBudget(usize);196 pub struct AllocBudget(usize);
181 197
@@ -425,9 +441,10 @@ pub fn decode_with_limits(data: &[u8], limits: Limits) -> Result<Image> {
425 Some(ImageFormat::WebP) => webp::decode(data, limits),441 Some(ImageFormat::WebP) => webp::decode(data, limits),
426 Some(ImageFormat::Gif) => gif::decode(data, limits),442 Some(ImageFormat::Gif) => gif::decode(data, limits),
427 Some(ImageFormat::Bmp) => bmp::decode(data, limits),443 Some(ImageFormat::Bmp) => bmp::decode(data, limits),
444+ Some(ImageFormat::Tiff) => tiff::decode(data, limits),
428 None => Err(Error::unsupported(445 None => Err(Error::unsupported(
429 "image",446 "image",
430- "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data",447+ "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data",
431 )),448 )),
432 }449 }
433 }450 }
@@ -440,9 +457,10 @@ pub fn info(data: &[u8]) -> Result<Info> {
440 Some(ImageFormat::WebP) => webp::info(data),457 Some(ImageFormat::WebP) => webp::info(data),
441 Some(ImageFormat::Gif) => gif::info(data),458 Some(ImageFormat::Gif) => gif::info(data),
442 Some(ImageFormat::Bmp) => bmp::info(data),459 Some(ImageFormat::Bmp) => bmp::info(data),
460+ Some(ImageFormat::Tiff) => tiff::info(data),
443 None => Err(Error::unsupported(461 None => Err(Error::unsupported(
444 "image",462 "image",
445- "no PNG, JPEG, WebP, GIF or BMP signature at the start of the data",463+ "no PNG, JPEG, WebP, GIF, BMP or TIFF signature at the start of the data",
446 )),464 )),
447 }465 }
448 }466 }
crates/ec-image/src/tiff.rsadded+757 -0
@@ -0,0 +1,757 @@
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::{AllocBudget, 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+ if out.len() >= hint {
367+ // The declared strip is already full. A bomb-style stream keeps
368+ // emitting codes past this point (the dictionary just keeps
369+ // growing); stopping here is what keeps a KB-sized input from
370+ // expanding into hundreds of megabytes.
371+ return Ok(out);
372+ }
373+ while have < width {
374+ let Some(&byte) = input.get(bit) else {
375+ return Ok(out);
376+ };
377+ bit += 1;
378+ acc = (acc << 8) | u32::from(byte);
379+ have += 8;
380+ }
381+ let code = ((acc >> (have - width)) & ((1 << width) - 1)) as u16;
382+ have -= width;
383+ match code {
384+ CLEAR => {
385+ next = 258;
386+ width = 9;
387+ previous = None;
388+ continue;
389+ }
390+ END => return Ok(out),
391+ _ => {}
392+ }
393+ stack.clear();
394+ let first_byte = if (code as usize) < next {
395+ let mut walk = code;
396+ while walk >= 258 {
397+ stack.push(suffix[walk as usize]);
398+ walk = prefix[walk as usize];
399+ }
400+ if walk > 255 {
401+ return Err(Error::corrupt("TIFF: an LZW code with no string"));
402+ }
403+ stack.push(walk as u8);
404+ *stack.last().unwrap()
405+ } else if code as usize == next {
406+ // The KwKwK case: the code being emitted is exactly the one this
407+ // step is about to define. A code greater than `next` is not a
408+ // KwKwK case at all -- it names a dictionary entry that does not
409+ // exist yet -- and accepting it here would let `previous` (set
410+ // below to this out-of-range `code`) get written into a future
411+ // `prefix` slot, breaking the invariant that every prefix chain
412+ // strictly decreases and turning the walk above into a cycle
413+ // that grows `stack` without bound.
414+ let previous = previous
415+ .ok_or_else(|| Error::corrupt("TIFF: an LZW stream opening with a new code"))?;
416+ let mut walk = previous;
417+ while walk >= 258 {
418+ stack.push(suffix[walk as usize]);
419+ walk = prefix[walk as usize];
420+ }
421+ stack.push(walk as u8);
422+ let first = *stack.last().unwrap();
423+ stack.insert(0, first);
424+ first
425+ } else {
426+ // code as usize > next: a reference to a dictionary entry that
427+ // does not exist yet, neither an ordinary code nor a valid KwKwK.
428+ return Err(Error::corrupt("TIFF: an LZW code past the dictionary"));
429+ };
430+ out.extend(stack.iter().rev());
431+ if let Some(previous) = previous {
432+ if next < 4096 {
433+ prefix[next] = previous;
434+ suffix[next] = first_byte;
435+ next += 1;
436+ }
437+ }
438+ previous = Some(code);
439+ // One code early: 511, not 512, is where nine bits stop being enough.
440+ if next + 1 >= (1 << width) && width < 12 {
441+ width += 1;
442+ }
443+ }
444+}
445+
446+/// PackBits: a run-length coder whose control byte is signed.
447+fn packbits(input: &[u8], hint: usize) -> Vec<u8> {
448+ let mut out = Vec::with_capacity(hint);
449+ let mut at = 0usize;
450+ while at < input.len() {
451+ if out.len() >= hint {
452+ // Same bomb shape as LZW: a run byte expands to up to 128 bytes
453+ // of output, so a small strip can otherwise inflate far past
454+ // what the declared geometry says it should hold.
455+ break;
456+ }
457+ let control = input[at] as i8;
458+ at += 1;
459+ if control >= 0 {
460+ let run = control as usize + 1;
461+ let end = (at + run).min(input.len());
462+ out.extend_from_slice(&input[at..end]);
463+ at = end;
464+ } else if control != -128 {
465+ let run = (-i32::from(control)) as usize + 1;
466+ let Some(&byte) = input.get(at) else { break };
467+ at += 1;
468+ out.extend(std::iter::repeat_n(byte, run));
469+ } else {
470+ // -128 is a no-op the format reserves.
471+ }
472+ }
473+ out
474+}
475+
476+/// One strip or tile, decompressed.
477+fn segment(layout: &Layout, data: &[u8], index: usize, expect: usize) -> Result<Vec<u8>> {
478+ let at = layout.offsets[index] as usize;
479+ let len = layout.counts[index] as usize;
480+ let body = data
481+ .get(at..at.saturating_add(len))
482+ .ok_or_else(|| Error::corrupt("TIFF: a strip reaching past the end of the file"))?;
483+ Ok(match layout.compression {
484+ COMPRESSION_NONE => body.to_vec(),
485+ COMPRESSION_LZW => lzw(body, expect)?,
486+ COMPRESSION_PACKBITS => packbits(body, expect),
487+ _ => ec_inflate::inflate_zlib(body, expect.saturating_mul(2).max(1024))
488+ .map_err(|e| Error::corrupt(format!("TIFF: a Deflate strip: {e}")))?,
489+ })
490+}
491+
492+/// Undo horizontal differencing across one row of `channels` interleaved samples.
493+/// Horizontal differencing runs at the sample's own width, so the sum wraps at
494+/// `mask + 1` -- an 8-bit file wraps at 256, not at the u16 these are held in.
495+fn undo_predictor(row: &mut [u16], channels: usize, mask: u16) {
496+ for i in channels..row.len() {
497+ row[i] = row[i].wrapping_add(row[i - channels]) & mask;
498+ }
499+}
500+
501+/// Read `count` samples of `bits` width from `bytes`, MSB-first.
502+fn unpack(bytes: &[u8], bits: u16, count: usize, out: &mut Vec<u16>, big_endian: bool) {
503+ match bits {
504+ 16 => {
505+ for i in 0..count {
506+ let (a, b) = (
507+ bytes.get(i * 2).copied().unwrap_or(0),
508+ bytes.get(i * 2 + 1).copied().unwrap_or(0),
509+ );
510+ out.push(if big_endian {
511+ u16::from_be_bytes([a, b])
512+ } else {
513+ u16::from_le_bytes([a, b])
514+ });
515+ }
516+ }
517+ 8 => out.extend(
518+ (0..count).map(|i| u16::from(bytes.get(i).copied().unwrap_or(0))),
519+ ),
520+ _ => {
521+ let per_byte = 8 / bits as usize;
522+ let mask = (1u16 << bits) - 1;
523+ for i in 0..count {
524+ let byte = bytes.get(i / per_byte).copied().unwrap_or(0);
525+ let shift = 8 - bits as usize * (i % per_byte + 1);
526+ out.push((u16::from(byte) >> shift) & mask);
527+ }
528+ }
529+ }
530+}
531+
532+/// Decode the first image in the file.
533+pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
534+ let layout = layout(data)?;
535+ limits.check(layout.width, layout.height)?;
536+ let (width, height) = (layout.width as usize, layout.height as usize);
537+ if width == 0 || height == 0 {
538+ return Err(Error::corrupt("TIFF: a zero-sized picture"));
539+ }
540+ let big_endian = data.starts_with(b"MM");
541+ let bits = layout.bits[0];
542+ let samples = layout.samples;
543+ let planar = layout.planar == 2;
544+ let planes = if planar { samples } else { 1 };
545+ let per_plane = if planar { 1 } else { samples };
546+
547+ // Samples land here interleaved, whatever the file's own arrangement was.
548+ // `width`/`height` already passed `limits.check`, but that only bounds
549+ // pixel count -- a 4-sample 16-bit picture is 8 bytes/pixel, which can
550+ // still cross the allocation limit even inside the pixel limit.
551+ let raw_len = width
552+ .checked_mul(height)
553+ .and_then(|v| v.checked_mul(samples))
554+ .ok_or_else(|| Error::corrupt("TIFF: sample count overflows"))?;
555+ let mut budget = AllocBudget::default();
556+ // A decompression-bomb guard on top of `max_alloc`: no legitimate encoder
557+ // writes a file whose declared pixel count decompresses to thousands of
558+ // times the bytes actually on disk (uncompressed is 1x, and LZW/Deflate
559+ // only improve on that). A tag claiming otherwise is sized past the file
560+ // that would have to contain it, not a picture this decoder should spend
561+ // possibly-seconds unpacking one strip of.
562+ let bomb_cap = data.len().saturating_mul(4096).max(1 << 20);
563+ let raw_bytes = limits.check_bytes("TIFF raw samples", raw_len.checked_mul(2))?;
564+ if raw_bytes > bomb_cap {
565+ return Err(Error::unsupported(
566+ "TIFF: a picture out of proportion to its file size",
567+ format!("{raw_bytes} raw bytes claimed from a {}-byte file", data.len()),
568+ ));
569+ }
570+ budget.spend(&limits, "TIFF raw samples", raw_bytes)?;
571+ let mut raw = vec![0u16; raw_len];
572+
573+ // Strips and tiles differ only in the rectangle one segment covers. Tile
574+ // and rows-per-strip dimensions are header fields too, unconstrained by
575+ // the picture's own width/height, so a segment's decompressed size is
576+ // budgeted before anything is sized from it.
577+ let (seg_w, seg_h) = match layout.tile {
578+ Some((w, h)) if w > 0 && h > 0 => (w as usize, h as usize),
579+ Some(_) => return Err(Error::corrupt("TIFF: a zero-sized tile")),
580+ None => (width, layout.rows_per_strip.max(1) as usize),
581+ };
582+ let across = width.div_ceil(seg_w);
583+ let down = height.div_ceil(seg_h);
584+ let per_plane_segments = across * down;
585+ if layout.offsets.len() < per_plane_segments * planes {
586+ return Err(Error::corrupt(
587+ "TIFF: fewer strips than the geometry needs",
588+ ));
589+ }
590+
591+ // A tile is always its full width; a strip is only as wide as the picture,
592+ // and its last one only as tall as the rows that remain.
593+ let row_samples = seg_w
594+ .checked_mul(per_plane)
595+ .ok_or_else(|| Error::corrupt("TIFF: a row wider than usize"))?;
596+ let row_bytes = limits.check_bytes(
597+ "TIFF row",
598+ row_samples
599+ .checked_mul(bits as usize)
600+ .map(|bits| bits.div_ceil(8)),
601+ )?;
602+ // `row` holds one `u16` per *sample*, not per packed byte -- for anything
603+ // under 16 bits that is a bigger allocation than `row_bytes` (up to 16x
604+ // for a 1-bit picture), so it needs its own check rather than trusting
605+ // the packed size to stand in for it.
606+ limits.check_bytes("TIFF row samples", row_samples.checked_mul(2))?;
607+ if row_samples.saturating_mul(2) > bomb_cap {
608+ return Err(Error::unsupported(
609+ "TIFF: a row out of proportion to its file size",
610+ format!("{row_samples} samples/row claimed from a {}-byte file", data.len()),
611+ ));
612+ }
613+ let mut row = Vec::with_capacity(row_samples);
614+ let full = ((1u32 << bits) - 1) as u16;
615+ // `bomb_cap` alone bounds one strip; nothing bounded the strip *count*
616+ // yet, and that is attacker-controlled up to the number of offsets a
617+ // small file can list. A few thousand small-looking strips can still add
618+ // up to gigabytes of real decompression work, so the running total is
619+ // held to the same file-size-proportional ceiling as a single strip.
620+ let mut segment_bytes_total = 0usize;
621+ for index in 0..per_plane_segments * planes {
622+ let plane = index / per_plane_segments;
623+ let within = index % per_plane_segments;
624+ let (col, band) = (within % across, within / across);
625+ // The declared strip/tile height is a header field like any other:
626+ // nothing stops RowsPerStrip or TileLength from claiming far more
627+ // rows than the picture has, which would otherwise size an LZW or
628+ // Deflate hint (and the compute behind it) off a number with no
629+ // relationship to the real image -- a small file claiming a
630+ // billion-row strip decodes only as many rows as `height` actually
631+ // has, never the declared height.
632+ let rows_used = seg_h.min(height.saturating_sub(band * seg_h));
633+ let expect = limits.check_bytes("TIFF strip", row_bytes.checked_mul(rows_used))?;
634+ segment_bytes_total = segment_bytes_total.saturating_add(expect);
635+ if expect > bomb_cap || segment_bytes_total > bomb_cap {
636+ return Err(Error::unsupported(
637+ "TIFF: strips claim more decompressed data than the file could hold",
638+ format!(
639+ "{segment_bytes_total} bytes claimed across strips from a {}-byte file",
640+ data.len()
641+ ),
642+ ));
643+ }
644+ budget.spend(&limits, "TIFF strip", expect)?;
645+ let body = segment(&layout, data, index, expect)?;
646+ for r in 0..seg_h {
647+ let y = band * seg_h + r;
648+ if y >= height {
649+ break;
650+ }
651+ let at = r * row_bytes;
652+ let Some(bytes) = body.get(at..(at + row_bytes).min(body.len())) else {
653+ break;
654+ };
655+ row.clear();
656+ unpack(bytes, bits, row_samples, &mut row, big_endian);
657+ if layout.predictor == 2 {
658+ undo_predictor(&mut row, per_plane, full);
659+ }
660+ for x in 0..seg_w {
661+ let px = col * seg_w + x;
662+ if px >= width {
663+ break;
664+ }
665+ for s in 0..per_plane {
666+ let channel = if planar { plane } else { s };
667+ raw[(y * width + px) * samples + channel] = row[x * per_plane + s];
668+ }
669+ }
670+ }
671+ }
672+
673+ // Widths below 8 bits are stretched to full scale so that a bilevel file's
674+ // 1 becomes white rather than one two-hundred-and-fifty-fifth of it.
675+ let pixels = build(&layout, &raw, width * height, bits, full)?;
676+ Ok(Image {
677+ width: layout.width,
678+ height: layout.height,
679+ pixels,
680+ meta: Metadata {
681+ orientation: layout.orientation,
682+ ..Metadata::default()
683+ },
684+ })
685+}
686+
687+/// Turn raw samples into the crate's colour form.
688+fn build(layout: &Layout, raw: &[u16], count: usize, bits: u16, full: u16) -> Result<Pixels> {
689+ let samples = layout.samples;
690+ let alpha = samples == 2 || samples == 4;
691+ // Extra sample type 1 is straight alpha and 2 is associated -- the colour
692+ // channels already multiplied by it. This crate carries straight alpha, so
693+ // an associated file is divided back out; where alpha is full, which is
694+ // what ImageMagick writes for an opaque picture, that is the identity.
695+ let associated = alpha && layout.extra_samples.first() == Some(&2);
696+ // 8-bit output for everything but a 16-bit file, whose depth survives.
697+ let widen = |v: u16| -> u16 {
698+ if bits == 16 {
699+ v
700+ } else {
701+ // round(v * 65535 / full)
702+ ((u32::from(v) * 65535 + u32::from(full) / 2) / u32::from(full)) as u16
703+ }
704+ };
705+ let narrow = |v: u16| -> u8 { ((u32::from(v) * 255 + 32767) / 65535) as u8 };
706+
707+ if layout.photometric == 3 {
708+ // A palette: three ranges of 16-bit values, one per channel, in a
709+ // single tag.
710+ let entries = layout.colour_map.len() / 3;
711+ if entries == 0 {
712+ return Err(Error::corrupt("TIFF: a palette picture with no colour map"));
713+ }
714+ let mut out = Vec::with_capacity(count * 3);
715+ for &index in raw.iter().take(count) {
716+ let index = index as usize;
717+ if index >= entries {
718+ return Err(Error::corrupt("TIFF: a palette index past the colour map"));
719+ }
720+ for c in 0..3 {
721+ out.push(narrow(layout.colour_map[c * entries + index] as u16));
722+ }
723+ }
724+ return Ok(Pixels::Rgb8(out));
725+ }
726+
727+ let invert = layout.photometric == 0;
728+ let mut wide: Vec<u16> = Vec::with_capacity(raw.len());
729+ for (i, &v) in raw.iter().enumerate() {
730+ let is_alpha = alpha && (i % samples) == samples - 1;
731+ let v = widen(v);
732+ wide.push(if invert && !is_alpha { 65535 - v } else { v });
733+ }
734+ if associated {
735+ for pixel in wide.chunks_mut(samples) {
736+ let a = u32::from(pixel[samples - 1]);
737+ for channel in &mut pixel[..samples - 1] {
738+ *channel = if a == 0 {
739+ 0
740+ } else {
741+ (((u32::from(*channel) * 65535 + a / 2) / a).min(65535)) as u16
742+ };
743+ }
744+ }
745+ }
746+
747+ Ok(match (samples, bits) {
748+ (1, 16) => Pixels::L16(wide),
749+ (2, 16) => Pixels::La16(wide),
750+ (3, 16) => Pixels::Rgb16(wide),
751+ (4, 16) => Pixels::Rgba16(wide),
752+ (1, _) => Pixels::L8(wide.iter().map(|&v| narrow(v)).collect()),
753+ (2, _) => Pixels::La8(wide.iter().map(|&v| narrow(v)).collect()),
754+ (3, _) => Pixels::Rgb8(wide.iter().map(|&v| narrow(v)).collect()),
755+ _ => Pixels::Rgba8(wide.iter().map(|&v| narrow(v)).collect()),
756+ })
757+}
crates/ec-image/tests/differential.rsmodified+99 -0
@@ -630,3 +630,102 @@ fn an_os2_v2_header_reads_as_the_same_picture() {
630 "os2v2.bmp: samples differ from the same picture in a v1 header"630 "os2v2.bmp: samples differ from the same picture in a v1 header"
631 );631 );
632 }632 }
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() {
212 sweep("bmp-rle", "rle8.bmp");212 sweep("bmp-rle", "rle8.bmp");
213 }213 }
214 214
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+
215 #[test]229 #[test]
216 fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() {230 fn arbitrary_bytes_behind_a_signature_are_refused_not_believed() {
217- let signatures: [&[u8]; 5] = [231+ let signatures: [&[u8]; 6] = [
218 &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],232 &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
219 &[0xff, 0xd8, 0xff, 0xe0],233 &[0xff, 0xd8, 0xff, 0xe0],
220 b"RIFF\x40\x00\x00\x00WEBPVP8 ",234 b"RIFF\x40\x00\x00\x00WEBPVP8 ",
221 b"GIF89a",235 b"GIF89a",
236+ // A TIFF header whose directory offset is inside the header itself.
237+ b"II\x2a\x00\x04\x00\x00\x00",
222 // "BM" alone is two bytes anything could start with, so the guess also238 // "BM" alone is two bytes anything could start with, so the guess also
223 // asks the file header to agree with itself: this prefix declares a239 // asks the file header to agree with itself: this prefix declares a
224 // 40-byte info header and pixels at 54, which is what makes the bytes240 // 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
163 rm -f "$out/bmp-source.png" "$out/bmp-source-alpha.png" "$out/bmp-source.rgba" \163 rm -f "$out/bmp-source.png" "$out/bmp-source-alpha.png" "$out/bmp-source.rgba" \
164 "$out/bmp-source-alpha.rgba" "$out/bmp-embed.png" "$out/bmp-embed.jpg"164 "$out/bmp-source-alpha.rgba" "$out/bmp-embed.png" "$out/bmp-embed.jpg"
165 165
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+
166 # Small versions of each format, for the fuzz sweep: ten thousand mutations213 # Small versions of each format, for the fuzz sweep: ten thousand mutations
167 # per format is only affordable on a picture that decodes in microseconds.214 # per format is only affordable on a picture that decodes in microseconds.
168 magick "$out/source.png" -resize 32x24! "$out/tiny.png"215 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
172 ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 1 "$out/tiny-lossless.webp"219 ffmpeg -loglevel error -y -i "$out/tiny.png" -c:v libwebp -lossless 1 "$out/tiny-lossless.webp"
173 magick "$out/tiny.png" -colors 64 "$out/tiny.gif"220 magick "$out/tiny.png" -colors 64 "$out/tiny.gif"
174 magick "$out/tiny.png" -colors 64 -type palette -compress None BMP3:"$out/tiny.bmp"221 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"
175 223
176 echo "wrote $(ls "$out" | wc -l) files to $out"224 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> {
392 ec_image::ImageFormat::Bmp => Some(ImageFormat::Bmp),392 ec_image::ImageFormat::Bmp => Some(ImageFormat::Bmp),
393 #[cfg(not(feature = "gpui"))]393 #[cfg(not(feature = "gpui"))]
394 ec_image::ImageFormat::Bmp => None,394 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,
395 }399 }
396 }400 }
397 401