Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_graphics/src/tiff.rs

20.0 KiB, 1 run

created by r1870400018:75664, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! TIFF, page by page.
2//!
3//! A TIFF is a chain of directories, one a page, each a list of tagged values saying how the page's
4//! pixels are cut into strips or tiles, how each is compressed and what its samples mean. What is
5//! read here is what scanners, fax software and photograph tools write: uncompressed, PackBits,
6//! LZW (with or without the horizontal predictor), Deflate, JPEG, and the three CCITT fax codings;
7//! one to sixteen bits a sample; bilevel, greyscale, palette, RGB, CMYK, and JPEG's YCbCr; an alpha
8//! channel associated or not; strips or tiles; chunky or planar samples; either fill order.
9//!
10//! A directory marked as a reduced-resolution copy of another -- the thumbnail a scanner puts
11//! beside the page -- is not a page and is passed over.
12//!
13//! BigTIFF, floating-point samples, the old (pre-6.0) JPEG coding and the old LZW bit order are
14//! refused by name.
15//!
16//! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\
17//! Anthropic Claude
18
19use crate::{
20 ccitt::{
21 self,
22 Coding,
23 },
24 jpeg,
25 lzw::{
26 self,
27 BitOrder,
28 },
29 pixmap::Pixmap,
30};
31
32use oxedyne_fe2o3_core::prelude::*;
33
34use std::io::Read;
35
36use flate2::read::ZlibDecoder;
37
38// The most pages read from one file, a ceiling against a directory chain that loops or an attack.
39pub const MAX_PAGES: usize = 1000;
40
41// Tags.
42const NEW_SUBFILE: u16 = 254;
43const WIDTH: u16 = 256;
44const HEIGHT: u16 = 257;
45const BITS: u16 = 258;
46const COMPRESSION: u16 = 259;
47const PHOTOMETRIC: u16 = 262;
48const FILL_ORDER: u16 = 266;
49const STRIP_OFFSETS: u16 = 273;
50const SAMPLES: u16 = 277;
51const ROWS_PER_STRIP: u16 = 278;
52const STRIP_COUNTS: u16 = 279;
53const PLANAR: u16 = 284;
54const T4_OPTIONS: u16 = 292;
55const PREDICTOR: u16 = 317;
56const COLOUR_MAP: u16 = 320;
57const TILE_WIDTH: u16 = 322;
58const TILE_LENGTH: u16 = 323;
59const TILE_OFFSETS: u16 = 324;
60const TILE_COUNTS: u16 = 325;
61const INK_SET: u16 = 332;
62const EXTRA: u16 = 338;
63const SAMPLE_FORMAT: u16 = 339;
64const JPEG_TABLES: u16 = 347;
65
66/// The byte order a file declares.
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68enum Order {
69 Le,
70 Be,
71}
72
73struct File<'a> {
74 b: &'a [u8],
75 order: Order,
76}
77
78impl<'a> File<'a> {
79
80 fn u16(&self, at: usize) -> Outcome<u16> {
81 match self.b.get(at..at + 2) {
82 Some(s) => Ok(match self.order {
83 Order::Le => u16::from_le_bytes([s[0], s[1]]),
84 Order::Be => u16::from_be_bytes([s[0], s[1]]),
85 }),
86 None => Err(err!(
87 "A TIFF needs two bytes at offset {}, but holds {}.", at, self.b.len();
88 Invalid, Input, Decode)),
89 }
90 }
91
92 fn u32(&self, at: usize) -> Outcome<u32> {
93 match self.b.get(at..at + 4) {
94 Some(s) => Ok(match self.order {
95 Order::Le => u32::from_le_bytes([s[0], s[1], s[2], s[3]]),
96 Order::Be => u32::from_be_bytes([s[0], s[1], s[2], s[3]]),
97 }),
98 None => Err(err!(
99 "A TIFF needs four bytes at offset {}, but holds {}.", at, self.b.len();
100 Invalid, Input, Decode)),
101 }
102 }
103}
104
105/// One directory's tags, each as the integers or the bytes it holds.
106struct Ifd {
107 tags: Vec<(u16, Vec<u32>)>,
108 tables: Option<Vec<u8>>, // JPEGTables, kept as bytes
109 next: usize,
110}
111
112impl Ifd {
113
114 fn get(&self, tag: u16) -> Option<&[u32]> {
115 self.tags.iter().find(|t| t.0 == tag).map(|t| &t.1[..])
116 }
117
118 fn one(&self, tag: u16, default: u32) -> u32 {
119 match self.get(tag) {
120 Some(v) if !v.is_empty() => v[0],
121 _ => default,
122 }
123 }
124
125 fn need(&self, tag: u16, name: &str) -> Outcome<&[u32]> {
126 match self.get(tag) {
127 Some(v) if !v.is_empty() => Ok(v),
128 _ => Err(err!("A TIFF page has no {} tag ({}).", name, tag; Invalid, Input, Decode)),
129 }
130 }
131}
132
133fn read_ifd(f: &File, at: usize) -> Outcome<Ifd> {
134 let n = res!(f.u16(at)) as usize;
135 let mut tags = Vec::with_capacity(n);
136 let mut tables = None;
137 for i in 0..n {
138 let e = at + 2 + i * 12;
139 let tag = res!(f.u16(e));
140 let kind = res!(f.u16(e + 2));
141 let count = res!(f.u32(e + 4)) as usize;
142 let size = match kind {
143 1 | 2 | 6 | 7 => 1,
144 3 | 8 => 2,
145 4 | 9 | 11 | 13 => 4,
146 5 | 10 | 12 => 8,
147 _ => continue, // a type this does not know is a tag this does not need
148 };
149 let bytes = match count.checked_mul(size) {
150 Some(b) if b <= f.b.len() => b,
151 _ => return Err(err!(
152 "A TIFF tag {} claims {} values, more than the file holds.", tag, count;
153 Invalid, Input, Decode)),
154 };
155 let base = if bytes <= 4 { e + 8 } else { res!(f.u32(e + 8)) as usize };
156 if tag == JPEG_TABLES {
157 match f.b.get(base..base + bytes) {
158 Some(s) => tables = Some(s.to_vec()),
159 None => return Err(err!(
160 "A TIFF's JPEG tables at offset {} pass the end of the file.", base;
161 Invalid, Input, Decode)),
162 }
163 continue;
164 }
165 let mut v = Vec::with_capacity(count);
166 for k in 0..count {
167 let p = base + k * size;
168 let x = match kind {
169 1 | 2 | 6 | 7 => match f.b.get(p) {
170 Some(b) => *b as u32,
171 None => return Err(err!(
172 "A TIFF tag {}'s values pass the end of the file.", tag;
173 Invalid, Input, Decode)),
174 },
175 3 | 8 => res!(f.u16(p)) as u32,
176 4 | 9 | 13 => res!(f.u32(p)),
177 _ => res!(f.u32(p)), // a rational's numerator, or a float's bits; unused
178 };
179 v.push(x);
180 }
181 tags.push((tag, v));
182 }
183 let next = res!(f.u32(at + 2 + n * 12)) as usize;
184 Ok(Ifd { tags, tables, next })
185}
186
187fn header(buf: &[u8]) -> Outcome<(File<'_>, usize)> {
188 let order = match buf.get(..4) {
189 Some(b"II*\0") => Order::Le,
190 Some(b"MM\0*") => Order::Be,
191 Some(b"II+\0") | Some(b"MM\0+") => return Err(err!(
192 "The file is a BigTIFF, which this does not read."; Invalid, Input, Decode, Unimplemented)),
193 _ => return Err(err!("The bytes do not begin with a TIFF header."; Invalid, Input, Decode)),
194 };
195 let f = File { b: buf, order };
196 let first = res!(f.u32(4)) as usize;
197 Ok((f, first))
198}
199
200/// Every page's directory, thumbnails passed over.
201fn pages_of<'a>(buf: &'a [u8]) -> Outcome<(File<'a>, Vec<Ifd>)> {
202 let (f, mut at) = res!(header(buf));
203 let mut seen = Vec::new();
204 let mut out = Vec::new();
205 while at != 0 {
206 if seen.contains(&at) || seen.len() >= MAX_PAGES {
207 break;
208 }
209 seen.push(at);
210 let ifd = res!(read_ifd(&f, at));
211 at = ifd.next;
212 if ifd.one(NEW_SUBFILE, 0) & 1 == 0 {
213 out.push(ifd);
214 }
215 }
216 if out.is_empty() {
217 return Err(err!("A TIFF holds no page."; Invalid, Input, Decode));
218 }
219 Ok((f, out))
220}
221
222/// How many pages a TIFF holds, thumbnails not counted.
223pub fn page_count(buf: &[u8]) -> Outcome<usize> {
224 Ok(res!(pages_of(buf)).1.len())
225}
226
227/// The first page's width and height.
228pub fn dimensions(buf: &[u8]) -> Outcome<(usize, usize)> {
229 let (_, pages) = res!(pages_of(buf));
230 let p = &pages[0];
231 Ok((res!(p.need(WIDTH, "ImageWidth"))[0] as usize, res!(p.need(HEIGHT, "ImageLength"))[0] as usize))
232}
233
234/// Decodes the first page.
235pub fn decode(buf: &[u8]) -> Outcome<Pixmap> {
236 let (f, pages) = res!(pages_of(buf));
237 page(&f, &pages[0])
238}
239
240/// Decodes every page, in order.
241pub fn decode_pages(buf: &[u8]) -> Outcome<Vec<Pixmap>> {
242 let (f, pages) = res!(pages_of(buf));
243 let mut out = Vec::with_capacity(pages.len());
244 for (i, p) in pages.iter().enumerate() {
245 out.push(res!(page(&f, p).map_err(|e| err!(e,
246 "Decoding page {} of {} of a TIFF.", i + 1, pages.len(); Decode))));
247 }
248 Ok(out)
249}
250
251/// PackBits: a signed count byte, then either that many plus one literal bytes or one byte
252/// repeated one minus that many times.
253fn packbits(data: &[u8], limit: usize) -> Outcome<Vec<u8>> {
254 let mut out = Vec::with_capacity(limit);
255 let mut i = 0;
256 while i < data.len() && out.len() < limit {
257 let n = data[i] as i8;
258 i += 1;
259 if n >= 0 {
260 let k = n as usize + 1;
261 let end = (i + k).min(data.len());
262 out.extend_from_slice(&data[i..end]);
263 i += k;
264 } else if n != -128 {
265 let k = 1 - n as isize;
266 if let Some(b) = data.get(i) {
267 for _ in 0..k {
268 out.push(*b);
269 }
270 }
271 i += 1;
272 }
273 }
274 out.truncate(limit);
275 Ok(out)
276}
277
278/// What one page's samples mean.
279#[derive(Clone, Copy, Debug, PartialEq, Eq)]
280enum Photo {
281 WhiteIsZero,
282 BlackIsZero,
283 Rgb,
284 Palette,
285 Cmyk,
286 YCbCr,
287}
288
289struct Page<'a> {
290 w: usize,
291 h: usize,
292 spp: usize, // samples a pixel
293 bps: usize, // bits a sample
294 photo: Photo,
295 planar: bool,
296 alpha: Option<(usize, bool)>, // which sample, and whether it is premultiplied
297 map: Option<&'a [u32]>,
298 be: bool, // sixteen-bit samples are big-endian
299}
300
301fn page(f: &File, ifd: &Ifd) -> Outcome<Pixmap> {
302 let w = res!(ifd.need(WIDTH, "ImageWidth"))[0] as usize;
303 let h = res!(ifd.need(HEIGHT, "ImageLength"))[0] as usize;
304 let spp = ifd.one(SAMPLES, 1) as usize;
305 let bps = ifd.one(BITS, 1) as usize;
306 if let Some(v) = ifd.get(BITS) {
307 if v.iter().any(|b| *b as usize != bps) {
308 return Err(err!(
309 "A TIFF page mixes sample depths {:?}, which this does not read.", v;
310 Invalid, Input, Decode, Unimplemented));
311 }
312 }
313 if !(1..=16).contains(&bps) || spp == 0 || spp > 8 {
314 return Err(err!(
315 "A TIFF page of {} samples of {} bits is not one this reads.", spp, bps;
316 Invalid, Input, Decode, Unimplemented));
317 }
318 if ifd.one(SAMPLE_FORMAT, 1) == 3 {
319 return Err(err!(
320 "A TIFF page of floating-point samples is not one this reads.";
321 Invalid, Input, Decode, Unimplemented));
322 }
323 let comp = ifd.one(COMPRESSION, 1);
324 let photo = match ifd.get(PHOTOMETRIC).and_then(|v| v.first().copied()) {
325 Some(0) => Photo::WhiteIsZero,
326 Some(1) => Photo::BlackIsZero,
327 Some(2) => Photo::Rgb,
328 Some(3) => Photo::Palette,
329 Some(5) => {
330 if ifd.one(INK_SET, 1) != 1 || spp < 4 {
331 return Err(err!(
332 "A separated TIFF page that is not CMYK is not one this reads.";
333 Invalid, Input, Decode, Unimplemented));
334 }
335 Photo::Cmyk
336 }
337 Some(6) => Photo::YCbCr,
338 Some(p) => return Err(err!(
339 "A TIFF page's photometric interpretation {} is not one this reads.", p;
340 Invalid, Input, Decode, Unimplemented)),
341 // Missing, which the specification forbids; guess as most readers do.
342 None => if matches!(comp, 2 | 3 | 4) { Photo::WhiteIsZero }
343 else if spp >= 3 { Photo::Rgb } else { Photo::BlackIsZero },
344 };
345 if photo == Photo::YCbCr && comp != 7 {
346 return Err(err!(
347 "A TIFF page of YCbCr samples outside JPEG coding is not one this reads.";
348 Invalid, Input, Decode, Unimplemented));
349 }
350 let base = match photo {
351 Photo::Rgb | Photo::YCbCr => 3,
352 Photo::Cmyk => 4,
353 _ => 1,
354 };
355 if spp < base {
356 return Err(err!(
357 "A TIFF page of {} samples a pixel is too few for its colour interpretation.", spp;
358 Invalid, Input, Decode));
359 }
360 let alpha = match ifd.get(EXTRA) {
361 Some(v) if spp > base => match v.first() {
362 Some(1) => Some((base, true)),
363 Some(2) => Some((base, false)),
364 _ => None,
365 },
366 _ => None,
367 };
368 let map = match photo {
369 Photo::Palette => {
370 let m = res!(ifd.need(COLOUR_MAP, "ColorMap"));
371 if m.len() < 3 << bps {
372 return Err(err!(
373 "A TIFF palette of {} values is short of the {} its depth needs.",
374 m.len(), 3 << bps;
375 Invalid, Input, Decode));
376 }
377 Some(m)
378 }
379 _ => None,
380 };
381 let pg = Page {
382 w, h, spp, bps, photo,
383 planar: ifd.one(PLANAR, 1) == 2 && spp > 1,
384 alpha, map,
385 be: f.order == Order::Be,
386 };
387 let mut pm = res!(Pixmap::new(w, h));
388
389 // The chunks: strips are tiles as wide as the page.
390 let tiled = ifd.get(TILE_OFFSETS).is_some();
391 let (cw, ch, offs, counts) = if tiled {
392 let tw = res!(ifd.need(TILE_WIDTH, "TileWidth"))[0] as usize;
393 let tl = res!(ifd.need(TILE_LENGTH, "TileLength"))[0] as usize;
394 (tw, tl, res!(ifd.need(TILE_OFFSETS, "TileOffsets")), ifd.get(TILE_COUNTS))
395 } else {
396 let rps = (ifd.one(ROWS_PER_STRIP, h as u32) as usize).clamp(1, h.max(1));
397 (w, rps, res!(ifd.need(STRIP_OFFSETS, "StripOffsets")), ifd.get(STRIP_COUNTS))
398 };
399 if cw == 0 || ch == 0 {
400 return Err(err!("A TIFF page's tiles are {} by {}.", cw, ch; Invalid, Input, Decode));
401 }
402 let across = (w + cw - 1) / cw;
403 let down = (h + ch - 1) / ch;
404 let planes = if pg.planar { spp } else { 1 };
405 let per = across * down;
406 if offs.len() < per * planes {
407 return Err(err!(
408 "A TIFF page of {} chunks lists only {} offsets.", per * planes, offs.len();
409 Invalid, Input, Decode));
410 }
411 let fill_reversed = ifd.one(FILL_ORDER, 1) == 2;
412 let predictor = ifd.one(PREDICTOR, 1);
413 if predictor == 3 {
414 return Err(err!(
415 "A TIFF page uses the floating-point predictor, which this does not read.";
416 Invalid, Input, Decode, Unimplemented));
417 }
418 let t4 = ifd.one(T4_OPTIONS, 0);
419 // The planar case gathers every plane of a chunk before converting it.
420 let chunk_spp = if pg.planar { 1 } else { spp };
421 for cy in 0..down {
422 for cx in 0..across {
423 let x0 = cx * cw;
424 let y0 = cy * ch;
425 // A strip's last chunk is short; a tile is always whole.
426 let rows = if tiled { ch } else { ch.min(h - y0) };
427 let stride = (cw * chunk_spp * bps + 7) / 8;
428 let size = stride * rows;
429 let mut planes_px: Vec<Vec<u8>> = Vec::with_capacity(planes);
430 for p in 0..planes {
431 let k = p * per + cy * across + cx;
432 let off = offs[k] as usize;
433 let len = match counts {
434 Some(c) if k < c.len() => c[k] as usize,
435 _ => f.b.len().saturating_sub(off),
436 };
437 let end = off.saturating_add(len).min(f.b.len());
438 let raw = match f.b.get(off..end) {
439 Some(s) => s,
440 None => return Err(err!(
441 "A TIFF chunk at offset {} passes the end of the file at {}.", off, f.b.len();
442 Invalid, Input, Decode)),
443 };
444 let owned;
445 let raw = if fill_reversed {
446 owned = raw.iter().map(|b| b.reverse_bits()).collect::<Vec<u8>>();
447 &owned[..]
448 } else {
449 raw
450 };
451 if comp == 7 {
452 // A JPEG chunk decodes straight to colour.
453 let jp = res!(jpeg_chunk(raw, ifd.tables.as_deref()));
454 blit(&mut pm, &jp, x0, y0);
455 continue;
456 }
457 let mut px = match comp {
458 1 => raw.to_vec(),
459 32773 => res!(packbits(raw, size)),
460 5 => {
461 if raw.len() >= 2 && raw[0] == 0 && raw[1] & 1 == 1 {
462 return Err(err!(
463 "A TIFF chunk is in the pre-6.0 LZW bit order, which this does \
464 not read."; Invalid, Input, Decode, Unimplemented));
465 }
466 res!(lzw::decode(raw, 8, BitOrder::Msb, true, size))
467 }
468 8 | 32946 => {
469 let mut v = Vec::with_capacity(size);
470 let mut z = ZlibDecoder::new(raw).take(size as u64);
471 res!(z.read_to_end(&mut v).map_err(|e| err!(e,
472 "A TIFF chunk's Deflate stream at offset {} is damaged.", off;
473 Invalid, Input, Decode)));
474 v
475 }
476 2 | 3 | 4 => {
477 if bps != 1 || chunk_spp != 1 {
478 return Err(err!(
479 "A fax-coded TIFF page must be one bit of one sample, not {} of {}.",
480 bps, chunk_spp; Invalid, Input, Decode));
481 }
482 let coding = match comp {
483 2 => Coding::Mh,
484 3 => Coding::T4 { two_d: t4 & 1 == 1, aligned: t4 & 4 == 4 },
485 _ => Coding::T6,
486 };
487 res!(ccitt::decode(raw, cw, rows, coding).map_err(|e| err!(e,
488 "Decoding the fax-coded TIFF chunk at offset {}.", off; Decode)))
489 }
490 6 => return Err(err!(
491 "A TIFF page uses the pre-6.0 JPEG coding, which this does not read.";
492 Invalid, Input, Decode, Unimplemented)),
493 c => return Err(err!(
494 "A TIFF page uses compression {}, which this does not read.", c;
495 Invalid, Input, Decode, Unimplemented)),
496 };
497 px.resize(size, 0); // a short chunk reads as zeros rather than out of bounds
498 if predictor == 2 {
499 undo_predictor(&mut px, cw, rows, stride, chunk_spp, bps, pg.be);
500 }
501 planes_px.push(px);
502 }
503 if comp == 7 {
504 continue;
505 }
506 res!(convert(&pg, &planes_px, stride, x0, y0, cw, rows, &mut pm));
507 }
508 }
509 Ok(pm)
510}
511
512/// Joins a JPEG chunk to the page's shared tables and decodes it.
513fn jpeg_chunk(raw: &[u8], tables: Option<&[u8]>) -> Outcome<Pixmap> {
514 match tables {
515 Some(t) if t.len() > 4 && raw.len() > 2 => {
516 // The tables are a stream of their own, SOI to EOI; the chunk starts with its own SOI.
517 let mut j = Vec::with_capacity(t.len() + raw.len());
518 j.extend_from_slice(&t[..t.len() - 2]);
519 j.extend_from_slice(&raw[2..]);
520 jpeg::decode(&j)
521 }
522 _ => jpeg::decode(raw),
523 }
524}
525
526fn blit(pm: &mut Pixmap, src: &Pixmap, x0: usize, y0: usize) {
527 let (w, h) = (pm.width(), pm.height());
528 let sw = src.width();
529 let sd = src.data();
530 let dd = pm.data_mut();
531 for y in 0..src.height() {
532 if y0 + y >= h {
533 break;
534 }
535 for x in 0..sw {
536 if x0 + x >= w {
537 break;
538 }
539 let s = (y * sw + x) * 4;
540 let d = ((y0 + y) * w + x0 + x) * 4;
541 dd[d..d + 4].copy_from_slice(&sd[s..s + 4]);
542 }
543 }
544}
545
546/// Undoes horizontal differencing, sample by sample along each row.
547fn undo_predictor(px: &mut [u8], w: usize, rows: usize, stride: usize, spp: usize, bps: usize, be: bool) {
548 for r in 0..rows {
549 let row = &mut px[r * stride..(r + 1) * stride];
550 match bps {
551 8 => {
552 for i in spp..w * spp {
553 row[i] = row[i].wrapping_add(row[i - spp]);
554 }
555 }
556 16 => {
557 let get = |row: &[u8], i: usize| -> u16 {
558 if be { u16::from_be_bytes([row[2 * i], row[2 * i + 1]]) }
559 else { u16::from_le_bytes([row[2 * i], row[2 * i + 1]]) }
560 };
561 for i in spp..w * spp {
562 let v = get(row, i).wrapping_add(get(row, i - spp));
563 let b = if be { v.to_be_bytes() } else { v.to_le_bytes() };
564 row[2 * i] = b[0];
565 row[2 * i + 1] = b[1];
566 }
567 }
568 _ => (), // the predictor is defined for whole bytes only
569 }
570 }
571}
572
573/// Sample `i` of a row, scaled to eight bits.
574fn sample(row: &[u8], i: usize, bps: usize, be: bool) -> u8 {
575 match bps {
576 8 => row[i],
577 16 => if be { row[2 * i] } else { row[2 * i + 1] },
578 _ => {
579 let max = (1u32 << bps) - 1;
580 let mut v = 0u32;
581 let bit = i * bps;
582 for k in 0..bps {
583 let p = bit + k;
584 v = (v << 1) | ((row[p >> 3] >> (7 - (p & 7))) & 1) as u32;
585 }
586 if bps < 8 {
587 ((v * 255 + max / 2) / max) as u8
588 } else {
589 (v >> (bps - 8)) as u8
590 }
591 }
592 }
593}
594
595/// The palette index of sample `i`, unscaled.
596fn index(row: &[u8], i: usize, bps: usize, be: bool) -> usize {
597 match bps {
598 8 => row[i] as usize,
599 16 => (if be { u16::from_be_bytes([row[2 * i], row[2 * i + 1]]) }
600 else { u16::from_le_bytes([row[2 * i], row[2 * i + 1]]) }) as usize,
601 _ => {
602 let mut v = 0usize;
603 let bit = i * bps;
604 for k in 0..bps {
605 let p = bit + k;
606 v = (v << 1) | ((row[p >> 3] >> (7 - (p & 7))) & 1) as usize;
607 }
608 v
609 }
610 }
611}
612
613/// Turns a chunk's samples into the page's pixels.
614fn convert(pg: &Page, planes: &[Vec<u8>], stride: usize, x0: usize, y0: usize, cw: usize,
615 rows: usize, pm: &mut Pixmap) -> Outcome<()>
616{
617 let w = pg.w;
618 let n = 1usize << pg.bps;
619 let data = pm.data_mut();
620 let mut s = [0u8; 8];
621 for r in 0..rows {
622 let y = y0 + r;
623 if y >= pg.h {
624 break;
625 }
626 for x in 0..cw {
627 if x0 + x >= w {
628 break;
629 }
630 // The pixel's samples, from one chunk or one from each plane.
631 let mut pal = 0usize;
632 for k in 0..pg.spp {
633 let (row, i) = if pg.planar {
634 (&planes[k][r * stride..(r + 1) * stride], x)
635 } else {
636 (&planes[0][r * stride..(r + 1) * stride], x * pg.spp + k)
637 };
638 if k == 0 && pg.photo == Photo::Palette {
639 pal = index(row, i, pg.bps, pg.be);
640 }
641 s[k] = sample(row, i, pg.bps, pg.be);
642 }
643 let mut c = match pg.photo {
644 Photo::WhiteIsZero => [255 - s[0], 255 - s[0], 255 - s[0], 255],
645 Photo::BlackIsZero => [s[0], s[0], s[0], 255],
646 Photo::Rgb | Photo::YCbCr => [s[0], s[1], s[2], 255],
647 Photo::Palette => match pg.map {
648 Some(m) if pal < n => [
649 (m[pal] >> 8) as u8,
650 (m[n + pal] >> 8) as u8,
651 (m[2 * n + pal] >> 8) as u8,
652 255,
653 ],
654 _ => [0, 0, 0, 255],
655 },
656 Photo::Cmyk => {
657 let k = 255 - s[3] as u32;
658 let ink = |v: u8| ((255 - v as u32) * k / 255) as u8;
659 [ink(s[0]), ink(s[1]), ink(s[2]), 255]
660 }
661 };
662 if let Some((a, pre)) = pg.alpha {
663 let al = s[a];
664 c[3] = al;
665 if pre && al > 0 && al < 255 {
666 for v in c.iter_mut().take(3) {
667 *v = ((*v as u32 * 255 + al as u32 / 2) / al as u32).min(255) as u8;
668 }
669 }
670 }
671 let d = (y * w + x0 + x) * 4;
672 data[d..d + 4].copy_from_slice(&c);
673 }
674 }
675 Ok(())
676}
677
678#[cfg(test)]
679mod tests {
680 use super::*;
681
682 #[test]
683 fn test_packbits_literal_and_repeat_runs_00() -> Outcome<()> {
684 // The example in the TIFF 6.0 specification.
685 let packed = [
686 0xfe, 0xaa, 0x02, 0x80, 0x00, 0x2a, 0xfd, 0xaa, 0x03, 0x80, 0x00, 0x2a, 0x22, 0xf7, 0xaa,
687 ];
688 let want = [
689 0xaa, 0xaa, 0xaa, 0x80, 0x00, 0x2a, 0xaa, 0xaa, 0xaa, 0xaa, 0x80, 0x00, 0x2a, 0x22,
690 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
691 ];
692 assert_eq!(res!(packbits(&packed, 64)), want.to_vec());
693 Ok(())
694 }
695
696 #[test]
697 fn test_a_bigtiff_is_refused_by_name_00() {
698 let got = decode(b"II+\0\x08\0\0\0");
699 assert!(matches!(&got, Err(e) if fmt!("{}", e).contains("BigTIFF")));
700 }
701}