| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 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 | |
| 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 | |
| 81 | struct Entry { |
| 82 | tag: u16, |
| 83 | values: Vec<u64>, |
| 84 | } |
| 85 | |
| 86 | |
| 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 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 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; |
| 114 | }; |
| 115 | |
| 116 | |
| 117 | |
| 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 | |
| 140 | |
| 141 | _ => u64::from(reader.u32_at(at)?), |
| 142 | }); |
| 143 | } |
| 144 | entries.push(Entry { tag, values }); |
| 145 | } |
| 146 | Ok(entries) |
| 147 | } |
| 148 | |
| 149 | |
| 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 | |
| 160 | offsets: Vec<u64>, |
| 161 | counts: Vec<u64>, |
| 162 | |
| 163 | tile: Option<(u32, u32)>, |
| 164 | rows_per_strip: u32, |
| 165 | colour_map: Vec<u64>, |
| 166 | |
| 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 | |
| 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 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 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 | |
| 357 | |
| 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 | |
| 368 | |
| 369 | |
| 370 | |
| 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 | |
| 407 | |
| 408 | |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | |
| 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 | |
| 427 | |
| 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 | |
| 440 | if next + 1 >= (1 << width) && width < 12 { |
| 441 | width += 1; |
| 442 | } |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | |
| 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 | |
| 453 | |
| 454 | |
| 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 | |
| 471 | } |
| 472 | } |
| 473 | out |
| 474 | } |
| 475 | |
| 476 | |
| 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 | |
| 493 | |
| 494 | |
| 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 | |
| 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 | |
| 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 | |
| 548 | |
| 549 | |
| 550 | |
| 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 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | |
| 561 | |
| 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 | |
| 574 | |
| 575 | |
| 576 | |
| 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 | |
| 592 | |
| 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 | |
| 603 | |
| 604 | |
| 605 | |
| 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 | |
| 616 | |
| 617 | |
| 618 | |
| 619 | |
| 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 | |
| 626 | |
| 627 | |
| 628 | |
| 629 | |
| 630 | |
| 631 | |
| 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 | |
| 674 | |
| 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 | |
| 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 | |
| 692 | |
| 693 | |
| 694 | |
| 695 | let associated = alpha && layout.extra_samples.first() == Some(&2); |
| 696 | |
| 697 | let widen = |v: u16| -> u16 { |
| 698 | if bits == 16 { |
| 699 | v |
| 700 | } else { |
| 701 | |
| 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 | |
| 709 | |
| 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 | } |