forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

tiff.rs763 lines, 29.5 KiBHistoryRawDownload
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
19use crate::{AllocBudget, Image, ImageFormat, Info, Limits, Metadata, Pixels};
20use ec_core::{Error, Result};
21
22const TAG_WIDTH: u16 = 256;
23const TAG_HEIGHT: u16 = 257;
24const TAG_BITS: u16 = 258;
25const TAG_COMPRESSION: u16 = 259;
26const TAG_PHOTOMETRIC: u16 = 262;
27const TAG_STRIP_OFFSETS: u16 = 273;
28const TAG_ORIENTATION: u16 = 274;
29const TAG_SAMPLES: u16 = 277;
30const TAG_ROWS_PER_STRIP: u16 = 278;
31const TAG_STRIP_COUNTS: u16 = 279;
32const TAG_PLANAR: u16 = 284;
33const TAG_PREDICTOR: u16 = 317;
34const TAG_COLOR_MAP: u16 = 320;
35const TAG_TILE_WIDTH: u16 = 322;
36const TAG_TILE_HEIGHT: u16 = 323;
37const TAG_TILE_OFFSETS: u16 = 324;
38const TAG_TILE_COUNTS: u16 = 325;
39const TAG_EXTRA_SAMPLES: u16 = 338;
40const TAG_SAMPLE_FORMAT: u16 = 339;
41
42const COMPRESSION_NONE: u64 = 1;
43const COMPRESSION_LZW: u64 = 5;
44const COMPRESSION_DEFLATE: u64 = 8;
45const COMPRESSION_PACKBITS: u64 = 32773;
46const COMPRESSION_DEFLATE_OLD: u64 = 32946;
47
48/// The endianness the file declared, and the bytes it declared it about.
49struct Reader<'a> {
50 data: &'a [u8],
51 big_endian: bool,
52}
53
54impl<'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.
81struct Entry {
82 tag: u16,
83 values: Vec<u64>,
84}
85
86/// Bytes one value of each TIFF type occupies.
87fn 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.
104fn 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.
150struct 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
171fn tag(entries: &[Entry], tag: u16) -> Option<&Entry> {
172 entries.iter().find(|e| e.tag == tag)
173}
174
175fn 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
181fn 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..=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..=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.
337pub 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 // Not read: TIFF orientation lives in the first directory, which `layout` does not keep.
344 orientation: 1,
345 })
346}
347
348/// TIFF's LZW: MSB-first codes, and the width grows one code early.
349///
350/// The "one code early" is the difference from the GIF variant: a TIFF encoder
351/// switches to the next width when the *next* code to be assigned would not
352/// fit, so a decoder that waits for the code itself desynchronises a byte into
353/// every image.
354fn lzw(input: &[u8], hint: usize) -> Result<Vec<u8>> {
355 const CLEAR: u16 = 256;
356 const END: u16 = 257;
357 let mut out = Vec::with_capacity(hint);
358 // Each entry is a previous code plus one byte, walked backwards on emit,
359 // which keeps the table one allocation instead of one per string.
360 let mut prefix = vec![0u16; 4096];
361 let mut suffix = vec![0u8; 4096];
362 let mut next = 258usize;
363 let mut width = 9u32;
364 let mut previous: Option<u16> = None;
365 let (mut bit, mut acc, mut have) = (0usize, 0u32, 0u32);
366 let mut stack = Vec::with_capacity(4096);
367 loop {
368 if out.len() >= hint {
369 // The declared strip is already full. A bomb-style stream keeps
370 // emitting codes past this point (the dictionary just keeps
371 // growing); stopping here is what keeps a KB-sized input from
372 // expanding into hundreds of megabytes.
373 return Ok(out);
374 }
375 while have < width {
376 let Some(&byte) = input.get(bit) else {
377 return Ok(out);
378 };
379 bit += 1;
380 acc = (acc << 8) | u32::from(byte);
381 have += 8;
382 }
383 let code = ((acc >> (have - width)) & ((1 << width) - 1)) as u16;
384 have -= width;
385 match code {
386 CLEAR => {
387 next = 258;
388 width = 9;
389 previous = None;
390 continue;
391 }
392 END => return Ok(out),
393 _ => {}
394 }
395 stack.clear();
396 let first_byte = if (code as usize) < next {
397 let mut walk = code;
398 while walk >= 258 {
399 stack.push(suffix[walk as usize]);
400 walk = prefix[walk as usize];
401 }
402 if walk > 255 {
403 return Err(Error::corrupt("TIFF: an LZW code with no string"));
404 }
405 stack.push(walk as u8);
406 *stack.last().unwrap()
407 } else if code as usize == next {
408 // The KwKwK case: the code being emitted is exactly the one this
409 // step is about to define. A code greater than `next` is not a
410 // KwKwK case at all -- it names a dictionary entry that does not
411 // exist yet -- and accepting it here would let `previous` (set
412 // below to this out-of-range `code`) get written into a future
413 // `prefix` slot, breaking the invariant that every prefix chain
414 // strictly decreases and turning the walk above into a cycle
415 // that grows `stack` without bound.
416 let previous = previous
417 .ok_or_else(|| Error::corrupt("TIFF: an LZW stream opening with a new code"))?;
418 let mut walk = previous;
419 while walk >= 258 {
420 stack.push(suffix[walk as usize]);
421 walk = prefix[walk as usize];
422 }
423 stack.push(walk as u8);
424 let first = *stack.last().unwrap();
425 stack.insert(0, first);
426 first
427 } else {
428 // code as usize > next: a reference to a dictionary entry that
429 // does not exist yet, neither an ordinary code nor a valid KwKwK.
430 return Err(Error::corrupt("TIFF: an LZW code past the dictionary"));
431 };
432 out.extend(stack.iter().rev());
433 if let Some(previous) = previous
434 && next < 4096
435 {
436 prefix[next] = previous;
437 suffix[next] = first_byte;
438 next += 1;
439 }
440 previous = Some(code);
441 // One code early: 511, not 512, is where nine bits stop being enough.
442 if next + 1 >= (1 << width) && width < 12 {
443 width += 1;
444 }
445 }
446}
447
448/// PackBits: a run-length coder whose control byte is signed.
449fn packbits(input: &[u8], hint: usize) -> Vec<u8> {
450 let mut out = Vec::with_capacity(hint);
451 let mut at = 0usize;
452 while at < input.len() {
453 if out.len() >= hint {
454 // Same bomb shape as LZW: a run byte expands to up to 128 bytes
455 // of output, so a small strip can otherwise inflate far past
456 // what the declared geometry says it should hold.
457 break;
458 }
459 let control = input[at] as i8;
460 at += 1;
461 if control >= 0 {
462 let run = control as usize + 1;
463 let end = (at + run).min(input.len());
464 out.extend_from_slice(&input[at..end]);
465 at = end;
466 } else if control != -128 {
467 let run = (-i32::from(control)) as usize + 1;
468 let Some(&byte) = input.get(at) else { break };
469 at += 1;
470 out.extend(std::iter::repeat_n(byte, run));
471 } else {
472 // -128 is a no-op the format reserves.
473 }
474 }
475 out
476}
477
478/// One strip or tile, decompressed.
479fn segment(layout: &Layout, data: &[u8], index: usize, expect: usize) -> Result<Vec<u8>> {
480 let at = layout.offsets[index] as usize;
481 let len = layout.counts[index] as usize;
482 let body = data
483 .get(at..at.saturating_add(len))
484 .ok_or_else(|| Error::corrupt("TIFF: a strip reaching past the end of the file"))?;
485 Ok(match layout.compression {
486 COMPRESSION_NONE => body.to_vec(),
487 COMPRESSION_LZW => lzw(body, expect)?,
488 COMPRESSION_PACKBITS => packbits(body, expect),
489 _ => ec_inflate::inflate_zlib(body, expect.saturating_mul(2).max(1024))
490 .map_err(|e| Error::corrupt(format!("TIFF: a Deflate strip: {e}")))?,
491 })
492}
493
494/// Undo horizontal differencing across one row of `channels` interleaved samples.
495/// Horizontal differencing runs at the sample's own width, so the sum wraps at
496/// `mask + 1` -- an 8-bit file wraps at 256, not at the u16 these are held in.
497fn undo_predictor(row: &mut [u16], channels: usize, mask: u16) {
498 for i in channels..row.len() {
499 row[i] = row[i].wrapping_add(row[i - channels]) & mask;
500 }
501}
502
503/// Read `count` samples of `bits` width from `bytes`, MSB-first.
504fn unpack(bytes: &[u8], bits: u16, count: usize, out: &mut Vec<u16>, big_endian: bool) {
505 match bits {
506 16 => {
507 for i in 0..count {
508 let (a, b) = (
509 bytes.get(i * 2).copied().unwrap_or(0),
510 bytes.get(i * 2 + 1).copied().unwrap_or(0),
511 );
512 out.push(if big_endian {
513 u16::from_be_bytes([a, b])
514 } else {
515 u16::from_le_bytes([a, b])
516 });
517 }
518 }
519 8 => out.extend(
520 (0..count).map(|i| u16::from(bytes.get(i).copied().unwrap_or(0))),
521 ),
522 _ => {
523 let per_byte = 8 / bits as usize;
524 let mask = (1u16 << bits) - 1;
525 for i in 0..count {
526 let byte = bytes.get(i / per_byte).copied().unwrap_or(0);
527 let shift = 8 - bits as usize * (i % per_byte + 1);
528 out.push((u16::from(byte) >> shift) & mask);
529 }
530 }
531 }
532}
533
534/// Decode the first image in the file.
535pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
536 let layout = layout(data)?;
537 // The decoded picture is refused by name before any raw sample is sized: a palette file
538 // comes out as RGB, anything else keeps its samples, and each sample is 16 bits only for a
539 // 16-bit file.
540 let out_samples = if layout.photometric == 3 { 3 } else { layout.samples };
541 let out_depth = if layout.bits.first() == Some(&16) { 2 } else { 1 };
542 limits.check_output(layout.width, layout.height, out_samples * out_depth)?;
543 let (width, height) = (layout.width as usize, layout.height as usize);
544 if width == 0 || height == 0 {
545 return Err(Error::corrupt("TIFF: a zero-sized picture"));
546 }
547 let big_endian = data.starts_with(b"MM");
548 let bits = layout.bits[0];
549 let samples = layout.samples;
550 let planar = layout.planar == 2;
551 let planes = if planar { samples } else { 1 };
552 let per_plane = if planar { 1 } else { samples };
553
554 // Samples land here interleaved, whatever the file's own arrangement was.
555 // `width`/`height` already passed `limits.check`, but that only bounds
556 // pixel count -- a 4-sample 16-bit picture is 8 bytes/pixel, which can
557 // still cross the allocation limit even inside the pixel limit.
558 let raw_len = width
559 .checked_mul(height)
560 .and_then(|v| v.checked_mul(samples))
561 .ok_or_else(|| Error::corrupt("TIFF: sample count overflows"))?;
562 let mut budget = AllocBudget::default();
563 // A decompression-bomb guard on top of `max_alloc`: no legitimate encoder
564 // writes a file whose declared pixel count decompresses to thousands of
565 // times the bytes actually on disk (uncompressed is 1x, and LZW/Deflate
566 // only improve on that). A tag claiming otherwise is sized past the file
567 // that would have to contain it, not a picture this decoder should spend
568 // possibly-seconds unpacking one strip of.
569 let bomb_cap = data.len().saturating_mul(4096).max(1 << 20);
570 let raw_bytes = limits.check_bytes("TIFF raw samples", raw_len.checked_mul(2))?;
571 if raw_bytes > bomb_cap {
572 return Err(Error::unsupported(
573 "TIFF: a picture out of proportion to its file size",
574 format!("{raw_bytes} raw bytes claimed from a {}-byte file", data.len()),
575 ));
576 }
577 budget.spend(&limits, "TIFF raw samples", raw_bytes)?;
578 let mut raw = vec![0u16; raw_len];
579
580 // Strips and tiles differ only in the rectangle one segment covers. Tile
581 // and rows-per-strip dimensions are header fields too, unconstrained by
582 // the picture's own width/height, so a segment's decompressed size is
583 // budgeted before anything is sized from it.
584 let (seg_w, seg_h) = match layout.tile {
585 Some((w, h)) if w > 0 && h > 0 => (w as usize, h as usize),
586 Some(_) => return Err(Error::corrupt("TIFF: a zero-sized tile")),
587 None => (width, layout.rows_per_strip.max(1) as usize),
588 };
589 let across = width.div_ceil(seg_w);
590 let down = height.div_ceil(seg_h);
591 let per_plane_segments = across * down;
592 if layout.offsets.len() < per_plane_segments * planes {
593 return Err(Error::corrupt(
594 "TIFF: fewer strips than the geometry needs",
595 ));
596 }
597
598 // A tile is always its full width; a strip is only as wide as the picture,
599 // and its last one only as tall as the rows that remain.
600 let row_samples = seg_w
601 .checked_mul(per_plane)
602 .ok_or_else(|| Error::corrupt("TIFF: a row wider than usize"))?;
603 let row_bytes = limits.check_bytes(
604 "TIFF row",
605 row_samples
606 .checked_mul(bits as usize)
607 .map(|bits| bits.div_ceil(8)),
608 )?;
609 // `row` holds one `u16` per *sample*, not per packed byte -- for anything
610 // under 16 bits that is a bigger allocation than `row_bytes` (up to 16x
611 // for a 1-bit picture), so it needs its own check rather than trusting
612 // the packed size to stand in for it.
613 limits.check_bytes("TIFF row samples", row_samples.checked_mul(2))?;
614 if row_samples.saturating_mul(2) > bomb_cap {
615 return Err(Error::unsupported(
616 "TIFF: a row out of proportion to its file size",
617 format!("{row_samples} samples/row claimed from a {}-byte file", data.len()),
618 ));
619 }
620 let mut row = Vec::with_capacity(row_samples);
621 let full = ((1u32 << bits) - 1) as u16;
622 // `bomb_cap` alone bounds one strip; nothing bounded the strip *count*
623 // yet, and that is attacker-controlled up to the number of offsets a
624 // small file can list. A few thousand small-looking strips can still add
625 // up to gigabytes of real decompression work, so the running total is
626 // held to the same file-size-proportional ceiling as a single strip.
627 let mut segment_bytes_total = 0usize;
628 for index in 0..per_plane_segments * planes {
629 let plane = index / per_plane_segments;
630 let within = index % per_plane_segments;
631 let (col, band) = (within % across, within / across);
632 // The declared strip/tile height is a header field like any other:
633 // nothing stops RowsPerStrip or TileLength from claiming far more
634 // rows than the picture has, which would otherwise size an LZW or
635 // Deflate hint (and the compute behind it) off a number with no
636 // relationship to the real image -- a small file claiming a
637 // billion-row strip decodes only as many rows as `height` actually
638 // has, never the declared height.
639 let rows_used = seg_h.min(height.saturating_sub(band * seg_h));
640 let expect = limits.check_bytes("TIFF strip", row_bytes.checked_mul(rows_used))?;
641 segment_bytes_total = segment_bytes_total.saturating_add(expect);
642 if expect > bomb_cap || segment_bytes_total > bomb_cap {
643 return Err(Error::unsupported(
644 "TIFF: strips claim more decompressed data than the file could hold",
645 format!(
646 "{segment_bytes_total} bytes claimed across strips from a {}-byte file",
647 data.len()
648 ),
649 ));
650 }
651 budget.spend(&limits, "TIFF strip", expect)?;
652 let body = segment(&layout, data, index, expect)?;
653 for r in 0..seg_h {
654 let y = band * seg_h + r;
655 if y >= height {
656 break;
657 }
658 let at = r * row_bytes;
659 let Some(bytes) = body.get(at..(at + row_bytes).min(body.len())) else {
660 break;
661 };
662 row.clear();
663 unpack(bytes, bits, row_samples, &mut row, big_endian);
664 if layout.predictor == 2 {
665 undo_predictor(&mut row, per_plane, full);
666 }
667 for x in 0..seg_w {
668 let px = col * seg_w + x;
669 if px >= width {
670 break;
671 }
672 for s in 0..per_plane {
673 let channel = if planar { plane } else { s };
674 raw[(y * width + px) * samples + channel] = row[x * per_plane + s];
675 }
676 }
677 }
678 }
679
680 // Widths below 8 bits are stretched to full scale so that a bilevel file's
681 // 1 becomes white rather than one two-hundred-and-fifty-fifth of it.
682 let pixels = build(&layout, &raw, width * height, bits, full)?;
683 Ok(Image {
684 width: layout.width,
685 height: layout.height,
686 pixels,
687 meta: Metadata {
688 orientation: layout.orientation,
689 ..Metadata::default()
690 },
691 })
692}
693
694/// Turn raw samples into the crate's colour form.
695fn build(layout: &Layout, raw: &[u16], count: usize, bits: u16, full: u16) -> Result<Pixels> {
696 let samples = layout.samples;
697 let alpha = samples == 2 || samples == 4;
698 // Extra sample type 1 is straight alpha and 2 is associated -- the colour
699 // channels already multiplied by it. This crate carries straight alpha, so
700 // an associated file is divided back out; where alpha is full, which is
701 // what ImageMagick writes for an opaque picture, that is the identity.
702 let associated = alpha && layout.extra_samples.first() == Some(&2);
703 // 8-bit output for everything but a 16-bit file, whose depth survives.
704 let widen = |v: u16| -> u16 {
705 if bits == 16 {
706 v
707 } else {
708 // round(v * 65535 / full)
709 ((u32::from(v) * 65535 + u32::from(full) / 2) / u32::from(full)) as u16
710 }
711 };
712 let narrow = |v: u16| -> u8 { ((u32::from(v) * 255 + 32767) / 65535) as u8 };
713
714 if layout.photometric == 3 {
715 // A palette: three ranges of 16-bit values, one per channel, in a
716 // single tag.
717 let entries = layout.colour_map.len() / 3;
718 if entries == 0 {
719 return Err(Error::corrupt("TIFF: a palette picture with no colour map"));
720 }
721 let mut out = Vec::with_capacity(count * 3);
722 for &index in raw.iter().take(count) {
723 let index = index as usize;
724 if index >= entries {
725 return Err(Error::corrupt("TIFF: a palette index past the colour map"));
726 }
727 for c in 0..3 {
728 out.push(narrow(layout.colour_map[c * entries + index] as u16));
729 }
730 }
731 return Ok(Pixels::Rgb8(out));
732 }
733
734 let invert = layout.photometric == 0;
735 let mut wide: Vec<u16> = Vec::with_capacity(raw.len());
736 for (i, &v) in raw.iter().enumerate() {
737 let is_alpha = alpha && (i % samples) == samples - 1;
738 let v = widen(v);
739 wide.push(if invert && !is_alpha { 65535 - v } else { v });
740 }
741 if associated {
742 for pixel in wide.chunks_mut(samples) {
743 let a = u32::from(pixel[samples - 1]);
744 for channel in &mut pixel[..samples - 1] {
745 // a == 0 means the pixel is fully transparent: its colour is zero.
746 *channel = (u32::from(*channel) * 65535 + a / 2)
747 .checked_div(a)
748 .map_or(0, |v| v.min(65535)) as u16;
749 }
750 }
751 }
752
753 Ok(match (samples, bits) {
754 (1, 16) => Pixels::L16(wide),
755 (2, 16) => Pixels::La16(wide),
756 (3, 16) => Pixels::Rgb16(wide),
757 (4, 16) => Pixels::Rgba16(wide),
758 (1, _) => Pixels::L8(wide.iter().map(|&v| narrow(v)).collect()),
759 (2, _) => Pixels::La8(wide.iter().map(|&v| narrow(v)).collect()),
760 (3, _) => Pixels::Rgb8(wide.iter().map(|&v| narrow(v)).collect()),
761 _ => Pixels::Rgba8(wide.iter().map(|&v| narrow(v)).collect()),
762 })
763}