forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBa5441e8Tahinli3 months ago1014 commits

tiff.rs757 lines, 29.0 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<'e>(entries: &'e [Entry], tag: u16) -> Option<&'e 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 | 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.
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 })
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.
352fn 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.
447fn 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.
477fn 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.
495fn 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.
502fn 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.
533pub 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.
688fn 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}