Debian Codegraph @

src/decoder/image.rs

raw symbols SCIP
1 use super::ifd::Value;
2 use super::stream::PackBitsReader;
3 use super::tag_reader::TagReader;
4 use super::ChunkType;
5 use super::{predict_f16, predict_f32, predict_f64, ValueReader};
6 use crate::tags::{
7 CompressionMethod, ExtraSamples, PhotometricInterpretation, PlanarConfiguration, Predictor,
8 SampleFormat, Tag,
9 };
10 use crate::{
11 ColorType, Directory, TiffError, TiffFormatError, TiffResult, TiffUnsupportedError, UsageError,
12 };
13
14 use std::io::{self, Cursor, Read, Seek};
15 use std::sync::Arc;
16
17 #[derive(Debug)]
18 pub(crate) struct StripDecodeState {
19 pub rows_per_strip: u32,
20 }
21
22 #[derive(Debug)]
23 /// Computed values useful for tile decoding
24 pub(crate) struct TileAttributes {
25 pub image_width: usize,
26 pub image_height: usize,
27
28 pub tile_width: usize,
29 pub tile_length: usize,
30 }
31
32 impl TileAttributes {
33 pub fn tiles_across(&self) -> usize {
34 self.image_width.div_ceil(self.tile_width)
35 }
36 pub fn tiles_down(&self) -> usize {
37 self.image_height.div_ceil(self.tile_length)
38 }
39 fn padding_right(&self) -> usize {
40 (self.tile_width - self.image_width % self.tile_width) % self.tile_width
41 }
42 fn padding_down(&self) -> usize {
43 (self.tile_length - self.image_height % self.tile_length) % self.tile_length
44 }
45 pub fn get_padding(&self, tile: usize) -> (usize, usize) {
46 let row = tile / self.tiles_across();
47 let column = tile % self.tiles_across();
48
49 let padding_right = if column == self.tiles_across() - 1 {
50 self.padding_right()
51 } else {
52 0
53 };
54
55 let padding_down = if row == self.tiles_down() - 1 {
56 self.padding_down()
57 } else {
58 0
59 };
60
61 (padding_right, padding_down)
62 }
63 }
64
65 #[derive(Debug)]
66 pub(crate) struct Image {
67 pub ifd: Option<Directory>,
68 pub width: u32,
69 pub height: u32,
70 pub bits_per_sample: u8,
71 pub samples: u16,
72 /// The `ExtraSamples`, defaulting to empty if not given.
73 pub extra_samples: Vec<ExtraSamples>,
74 /// Number of samples that belong to the photometric interpretation, samples except
75 /// `ExtraSamples` (338, 0x0152) tag.
76 pub photometric_samples: u16,
77 pub sample_format: SampleFormat,
78 pub photometric_interpretation: PhotometricInterpretation,
79 pub compression_method: CompressionMethod,
80 pub predictor: Predictor,
81 pub jpeg_tables: Option<Arc<Vec<u8>>>,
82 pub chunk_type: ChunkType,
83 pub planar_config: PlanarConfiguration,
84 pub strip_decoder: Option<StripDecodeState>,
85 pub tile_attributes: Option<TileAttributes>,
86 pub chunk_offsets: Vec<u64>,
87 pub chunk_bytes: Vec<u64>,
88 pub chroma_subsampling: (u16, u16),
89 }
90
91 /// Describes how to read a tile-aligned portion of the image.
92 #[derive(Clone)]
93 pub(crate) struct ReadoutLayout {
94 /// The planar configuration, which applies to both the underlying image and the output buffer.
95 /// This may be relaxed if we find a clean enough way to provide it.
96 pub planar_config: PlanarConfiguration,
97
98 /// The sample interpretation (interpret with planar_config).
99 ///
100 /// FIXME: we should not require this here. The ability to turn out the raw bytes from the
101 /// sample arrays is very different from turning out interpretable color. Firstly we can always
102 /// readout `Multiband` but currently only use that ColorType in special circumstances (it must
103 /// not overlap cases where actually want to use a ColorType).
104 ///
105 /// And then we have CIE Lab, which uses a tuple of `(u8, i8, i8)`, that is still filterable
106 /// but still not represented by any of our `DecoderResult` variants. Other color variants
107 /// depend on extra tags (YCbCrCoefficients/0x0211) and we don't have a good side channel to
108 /// tag the output with all that TIFF specific information, so arguably we should process and
109 /// apply those to the data so it becomes a self-contained representation.
110 ///
111 /// This should be computed at a higher level, in `Decoder`, instead.
112 pub color: ColorType,
113 /// The number of bytes from one row to another.
114 pub minimum_row_stride: usize,
115 /// The format of samples (assumed uniform for now, same with depth of `ColorType`).
116 pub sample_format: SampleFormat,
117
118 /// Number of bytes to advance in output per row.
119 pub row_stride: usize,
120 /// Number of bytes to advance in output per chunk in width.
121 pub chunk_row_stride: usize,
122 /// Number of bytes to advance in output per chunk in height.
123 pub chunk_col_stride: usize,
124 /// Number of bytes in output from one plane to another.
125 pub plane_stride: usize,
126
127 /// Bits per sample in the encoded data.
128 pub tiff_bits_per_sample: u8,
129 /// Number of samples in the encoded data.
130 pub tiff_samples: u16,
131 /// Dimensions of the underlying rectangular chunks (tile or strips).
132 pub tiff_chunk_dimensions: (u32, u32),
133 /// Number of bytes in the underlying data with all samples per row of chunks.
134 pub tiff_row_bytes: usize,
135
136 /// Chunks until wrapping to the next row of chunks.
137 pub chunks_across: u32,
138 /// Chunks to advance to get to the next plane of chunks.
139 pub chunks_per_plane: u32,
140 }
141
142 impl Image {
143 pub fn from_reader<R: Read + Seek>(
144 decoder: &mut ValueReader<R>,
145 ifd: Directory,
146 ) -> TiffResult<Image> {
147 let mut tag_reader = TagReader { decoder, ifd: &ifd };
148
149 let width = tag_reader.require_tag(Tag::ImageWidth)?.into_u32()?;
150 let height = tag_reader.require_tag(Tag::ImageLength)?.into_u32()?;
151 if width == 0 || height == 0 {
152 return Err(TiffError::FormatError(TiffFormatError::InvalidDimensions(
153 width, height,
154 )));
155 }
156
157 let photometric_interpretation = tag_reader
158 .find_tag(Tag::PhotometricInterpretation)?
159 .map(Value::into_u16)
160 .transpose()?
161 .and_then(PhotometricInterpretation::from_u16)
162 .ok_or(TiffUnsupportedError::UnknownInterpretation)?;
163
164 // Try to parse both the compression method and the number, format, and bits of the included samples.
165 // If they are not explicitly specified, those tags are reset to their default values and not carried from previous images.
166 let compression_method = match tag_reader.find_tag(Tag::Compression)? {
167 Some(val) => CompressionMethod::from_u16_exhaustive(val.into_u16()?),
168 None => CompressionMethod::None,
169 };
170
171 let jpeg_tables = if compression_method == CompressionMethod::ModernJPEG
172 && ifd.contains(Tag::JPEGTables)
173 {
174 let vec = tag_reader
175 .find_tag(Tag::JPEGTables)?
176 .unwrap()
177 .into_u8_vec()?;
178 if vec.len() < 2 {
179 return Err(TiffError::FormatError(
180 TiffFormatError::InvalidTagValueType(Tag::JPEGTables),
181 ));
182 }
183
184 Some(Arc::new(vec))
185 } else {
186 None
187 };
188
189 let samples: u16 = tag_reader
190 .find_tag(Tag::SamplesPerPixel)?
191 .map(Value::into_u16)
192 .transpose()?
193 .unwrap_or(1);
194
195 if samples == 0 {
196 return Err(TiffFormatError::SamplesPerPixelIsZero.into());
197 }
198
199 let extra_samples = match tag_reader.find_tag(Tag::ExtraSamples)? {
200 Some(n) => n.into_u16_vec()?,
201 None => vec![],
202 };
203
204 let extra_samples = extra_samples
205 .into_iter()
206 .map(|x| ExtraSamples::from_u16(x).unwrap_or(ExtraSamples::Unspecified))
207 .collect::<Vec<_>>();
208
209 let photometric_samples = match usize::from(samples).checked_sub(extra_samples.len()) {
210 None => {
211 return Err(TiffError::FormatError(
212 TiffFormatError::InconsistentSizesEncountered,
213 ));
214 }
215 Some(n) => n as u16,
216 };
217
218 let sample_format = match tag_reader.find_tag_uint_vec(Tag::SampleFormat)? {
219 Some(vals) => {
220 let sample_format: Vec<_> = vals
221 .into_iter()
222 .map(SampleFormat::from_u16_exhaustive)
223 .collect();
224
225 let Some(format) = sample_format.first().copied() else {
226 // Reject empty sample formats
227 return Err(TiffFormatError::InvalidTagValueType(Tag::SampleFormat).into());
228 };
229 // TODO: for now, only homogenous formats across samples are supported.
230 if !sample_format.iter().all(|&s| s == format) {
231 return Err(TiffUnsupportedError::UnsupportedSampleFormat(sample_format).into());
232 }
233 format
234 }
235 None => SampleFormat::Uint,
236 };
237
238 let bits_per_sample: Vec<u8> = tag_reader
239 .find_tag_uint_vec(Tag::BitsPerSample)?
240 .unwrap_or_else(|| vec![1]);
241
242 // Technically bits_per_sample.len() should be *equal* to samples, but libtiff also allows
243 // it to be a single value that applies to all samples.
244 if bits_per_sample.len() != usize::from(samples) && bits_per_sample.len() != 1 {
245 return Err(TiffError::FormatError(
246 TiffFormatError::InconsistentSizesEncountered,
247 ));
248 }
249
250 // This library (and libtiff) do not support mixed sample formats and zero bits per sample
251 // doesn't make sense.
252 if bits_per_sample.iter().any(|&b| b != bits_per_sample[0]) || bits_per_sample[0] == 0 {
253 return Err(TiffUnsupportedError::InconsistentBitsPerSample(bits_per_sample).into());
254 }
255
256 let predictor = tag_reader
257 .find_tag(Tag::Predictor)?
258 .map(Value::into_u16)
259 .transpose()?
260 .map(|p| {
261 Predictor::from_u16(p)
262 .ok_or(TiffError::FormatError(TiffFormatError::UnknownPredictor(p)))
263 })
264 .transpose()?
265 .unwrap_or(Predictor::None);
266
267 let planar_config = tag_reader
268 .find_tag(Tag::PlanarConfiguration)?
269 .map(Value::into_u16)
270 .transpose()?
271 .map(|p| {
272 PlanarConfiguration::from_u16(p).ok_or(TiffError::FormatError(
273 TiffFormatError::UnknownPlanarConfiguration(p),
274 ))
275 })
276 .transpose()?
277 .unwrap_or(PlanarConfiguration::Chunky);
278
279 let ycbcr_subsampling = tag_reader.find_tag_uint_vec::<u16>(Tag::ChromaSubsampling)?;
280
281 let chroma_subsampling = if let Some(subsamples) = &ycbcr_subsampling {
282 let [a, b] = subsamples.as_slice() else {
283 return Err(TiffError::FormatError(TiffFormatError::InvalidCountForTag(
284 Tag::ChromaSubsampling,
285 subsamples.len(),
286 )));
287 };
288
289 // ImageWidth and ImageLength are constrained to be integer multiples of
290 // YCbCrSubsampleHoriz and YCbCrSubsampleVert respectively. TileWidth and TileLength
291 // have the same constraints. RowsPerStrip must be an integer multiple of
292 // YCbCrSubsampleVert.
293 (*a, *b)
294 } else {
295 (2, 2)
296 };
297
298 let planes = match planar_config {
299 PlanarConfiguration::Chunky => 1,
300 PlanarConfiguration::Planar => samples,
301 };
302
303 let chunk_type;
304 let chunk_offsets;
305 let chunk_bytes;
306 let strip_decoder;
307 let tile_attributes;
308 match (
309 ifd.contains(Tag::StripByteCounts),
310 ifd.contains(Tag::StripOffsets),
311 ifd.contains(Tag::TileByteCounts),
312 ifd.contains(Tag::TileOffsets),
313 ) {
314 (true, true, false, false) => {
315 chunk_type = ChunkType::Strip;
316
317 chunk_offsets = tag_reader
318 .find_tag(Tag::StripOffsets)?
319 .unwrap()
320 .into_u64_vec()?;
321 chunk_bytes = tag_reader
322 .find_tag(Tag::StripByteCounts)?
323 .unwrap()
324 .into_u64_vec()?;
325 let rows_per_strip = tag_reader
326 .find_tag(Tag::RowsPerStrip)?
327 .map(Value::into_u32)
328 .transpose()?
329 .unwrap_or(height);
330 strip_decoder = Some(StripDecodeState { rows_per_strip });
331 tile_attributes = None;
332
333 if chunk_offsets.len() != chunk_bytes.len()
334 || rows_per_strip == 0
335 || u32::try_from(chunk_offsets.len())?
336 != (height.saturating_sub(1) / rows_per_strip + 1) * planes as u32
337 {
338 return Err(TiffError::FormatError(
339 TiffFormatError::InconsistentSizesEncountered,
340 ));
341 }
342 }
343 (false, false, true, true) => {
344 chunk_type = ChunkType::Tile;
345
346 let tile_width =
347 usize::try_from(tag_reader.require_tag(Tag::TileWidth)?.into_u32()?)?;
348 let tile_length =
349 usize::try_from(tag_reader.require_tag(Tag::TileLength)?.into_u32()?)?;
350
351 if tile_width == 0 {
352 return Err(TiffFormatError::InvalidTagValueType(Tag::TileWidth).into());
353 } else if tile_length == 0 {
354 return Err(TiffFormatError::InvalidTagValueType(Tag::TileLength).into());
355 }
356
357 strip_decoder = None;
358 tile_attributes = Some(TileAttributes {
359 image_width: usize::try_from(width)?,
360 image_height: usize::try_from(height)?,
361 tile_width,
362 tile_length,
363 });
364 chunk_offsets = tag_reader
365 .find_tag(Tag::TileOffsets)?
366 .unwrap()
367 .into_u64_vec()?;
368 chunk_bytes = tag_reader
369 .find_tag(Tag::TileByteCounts)?
370 .unwrap()
371 .into_u64_vec()?;
372
373 let tile = tile_attributes.as_ref().unwrap();
374 if chunk_offsets.len() != chunk_bytes.len()
375 || chunk_offsets.len()
376 != tile.tiles_down() * tile.tiles_across() * planes as usize
377 {
378 return Err(TiffError::FormatError(
379 TiffFormatError::InconsistentSizesEncountered,
380 ));
381 }
382 }
383 (_, _, _, _) => {
384 return Err(TiffError::FormatError(
385 TiffFormatError::StripTileTagConflict,
386 ))
387 }
388 };
389
390 Ok(Image {
391 ifd: Some(ifd),
392 width,
393 height,
394 bits_per_sample: bits_per_sample[0],
395 samples,
396 extra_samples,
397 photometric_samples,
398 sample_format,
399 photometric_interpretation,
400 compression_method,
401 jpeg_tables,
402 predictor,
403 chunk_type,
404 planar_config,
405 strip_decoder,
406 tile_attributes,
407 chunk_offsets,
408 chunk_bytes,
409 chroma_subsampling,
410 })
411 }
412
413 pub(crate) fn colortype(&self) -> TiffResult<ColorType> {
414 let is_alpha_extra_samples = matches!(
415 self.extra_samples.as_slice(),
416 [ExtraSamples::AssociatedAlpha, ..] | [ExtraSamples::UnassociatedAlpha, ..]
417 );
418
419 match self.photometric_interpretation {
420 PhotometricInterpretation::RGB => match self.photometric_samples {
421 3 => Ok(if is_alpha_extra_samples {
422 ColorType::RGBA(self.bits_per_sample)
423 } else {
424 ColorType::RGB(self.bits_per_sample)
425 }),
426 4 => Ok(ColorType::RGBA(self.bits_per_sample)),
427 _ => Err(TiffError::UnsupportedError(
428 TiffUnsupportedError::InterpretationWithBits(
429 self.photometric_interpretation,
430 vec![self.bits_per_sample; self.samples as usize],
431 ),
432 )),
433 },
434 PhotometricInterpretation::CMYK => match self.photometric_samples {
435 4 => Ok(if is_alpha_extra_samples {
436 ColorType::CMYKA(self.bits_per_sample)
437 } else {
438 ColorType::CMYK(self.bits_per_sample)
439 }),
440 5 => Ok(ColorType::CMYKA(self.bits_per_sample)),
441 _ => Err(TiffError::UnsupportedError(
442 TiffUnsupportedError::InterpretationWithBits(
443 self.photometric_interpretation,
444 vec![self.bits_per_sample; self.samples as usize],
445 ),
446 )),
447 },
448 PhotometricInterpretation::YCbCr => match self.photometric_samples {
449 3 => Ok(ColorType::YCbCr(self.bits_per_sample)),
450 _ => Err(TiffError::UnsupportedError(
451 TiffUnsupportedError::InterpretationWithBits(
452 self.photometric_interpretation,
453 vec![self.bits_per_sample; self.samples as usize],
454 ),
455 )),
456 },
457 // TODO: treatment of WhiteIsZero is not quite consistent with `invert_colors` that is
458 // later called when that interpretation is read. That function does not support
459 // Multiband as a color type and will error. It's unclear how to resolve that exactly.
460 PhotometricInterpretation::BlackIsZero | PhotometricInterpretation::WhiteIsZero => {
461 // Note: compatibility with previous implementation requires us to return extra
462 // samples as `Multiband`. For gray images however the better choice would be
463 // returning a `Gray` color, i.e. matching on `photometric_samples` instead.
464 match self.samples {
465 1 => Ok(ColorType::Gray(self.bits_per_sample)),
466 _ => Ok(ColorType::Multiband {
467 bit_depth: self.bits_per_sample,
468 num_samples: self.samples,
469 }),
470 }
471 }
472 // ```
473 // struct IccLab /* Interpretation 9* {
474 // pub L: u8, // SampleFormat::Uint
475 // pub a: u8, // SampleFormat::Uint, defined as TiffLab::a + 128
476 // pub b: u8, // SampleFormat::Uint, defined as TiffLab::b + 128
477 // }
478 // ```
479 PhotometricInterpretation::IccLab => match self.photometric_samples {
480 3 if matches!(self.sample_format, SampleFormat::Uint) => {
481 Ok(ColorType::Lab(self.bits_per_sample))
482 }
483 _ => Err(TiffError::UnsupportedError(
484 TiffUnsupportedError::InterpretationWithBits(
485 self.photometric_interpretation,
486 vec![self.bits_per_sample; self.samples as usize],
487 ),
488 )),
489 },
490 // Unsupported due to inherently heterogeneous sample types. This is represented as:
491 // ```
492 // struct TiffLab /* Interpretation 8* {
493 // pub L: u8, // SampleFormat::Uint
494 // pub a: i8, // SampleFormat::Int
495 // pub b: i8, // SampleFormat::Int
496 // }
497 // ```
498 PhotometricInterpretation::CIELab => Err(TiffError::UnsupportedError(
499 TiffUnsupportedError::InterpretationWithBits(
500 PhotometricInterpretation::CIELab,
501 vec![self.bits_per_sample; self.samples as usize],
502 ),
503 )),
504 // Unsupported due to extra unfiltering and conversion steps. We need to find the
505 // Decode tag (SRATIONAL; 2 * SamplesPerPixel) and apply the following conversion:
506 //
507 // L* = Decode[0] + Lsample x (Decode[1] - Decode[0]) / (2^n -1)
508 // …
509 //
510 // So we'll have a larger depth in the output and either worry about reducing fractions
511 // or turn everything into floats. That's a lot of decisions.
512 PhotometricInterpretation::ItuLab => Err(TiffError::UnsupportedError(
513 TiffUnsupportedError::InterpretationWithBits(
514 PhotometricInterpretation::CIELab,
515 vec![self.bits_per_sample; self.samples as usize],
516 ),
517 )),
518 PhotometricInterpretation::RGBPalette | PhotometricInterpretation::TransparencyMask => {
519 Err(TiffError::UnsupportedError(
520 TiffUnsupportedError::InterpretationWithBits(
521 self.photometric_interpretation,
522 vec![self.bits_per_sample; self.samples as usize],
523 ),
524 ))
525 }
526 }
527 }
528
529 fn create_reader<'r, R: 'r + Read + Seek>(
530 reader: R,
531 compression_method: CompressionMethod,
532 compressed_length: u64,
533 // FIXME: these should be `expect` attributes or we choose another way of passing them.
534 #[cfg_attr(not(feature = "jpeg"), allow(unused_variables))] jpeg_tables: Option<&[u8]>,
535 #[cfg_attr(not(feature = "fax"), allow(unused_variables))] dimensions: (u32, u32),
536 #[cfg_attr(not(feature = "webp"), allow(unused_variables))] samples: u16,
537 ) -> TiffResult<Box<dyn Read + 'r>> {
538 Ok(match compression_method {
539 CompressionMethod::None => Box::new(reader),
540 #[cfg(feature = "lzw")]
541 CompressionMethod::LZW => Box::new(super::stream::LZWReader::new(
542 reader,
543 usize::try_from(compressed_length)?,
544 )),
545 #[cfg(feature = "zstd")]
546 CompressionMethod::ZSTD => Box::new(zstd::Decoder::new(reader)?),
547 CompressionMethod::PackBits => Box::new(PackBitsReader::new(reader, compressed_length)),
548 #[cfg(feature = "deflate")]
549 CompressionMethod::Deflate | CompressionMethod::OldDeflate => {
550 Box::new(super::stream::DeflateReader::new(reader))
551 }
552 #[cfg(feature = "jpeg")]
553 CompressionMethod::ModernJPEG => {
554 use zune_jpeg::zune_core;
555
556 if jpeg_tables.is_some() && compressed_length < 2 {
557 return Err(TiffError::FormatError(
558 TiffFormatError::InvalidTagValueType(Tag::JPEGTables),
559 ));
560 }
561
562 // Construct new jpeg_reader wrapping a SmartReader.
563 //
564 // JPEG compression in TIFF allows saving quantization and/or huffman tables in one
565 // central location. These `jpeg_tables` are simply prepended to the remaining jpeg image data.
566 // Because these `jpeg_tables` start with a `SOI` (HEX: `0xFFD8`) or __start of image__ marker
567 // which is also at the beginning of the remaining JPEG image data and would
568 // confuse the JPEG renderer, one of these has to be taken off. In this case the first two
569 // bytes of the remaining JPEG data is removed because it follows `jpeg_tables`.
570 // Similary, `jpeg_tables` ends with a `EOI` (HEX: `0xFFD9`) or __end of image__ marker,
571 // this has to be removed as well (last two bytes of `jpeg_tables`).
572 let mut jpeg_reader = match jpeg_tables {
573 Some(jpeg_tables) => {
574 let mut reader = reader.take(compressed_length);
575 reader.read_exact(&mut [0; 2])?;
576
577 Box::new(
578 Cursor::new(&jpeg_tables[..jpeg_tables.len() - 2])
579 .chain(reader.take(compressed_length)),
580 ) as Box<dyn Read>
581 }
582 None => Box::new(reader.take(compressed_length)),
583 };
584
585 let mut jpeg_data = Vec::new();
586 jpeg_reader.read_to_end(&mut jpeg_data)?;
587
588 let mut decoder =
589 zune_jpeg::JpegDecoder::new(zune_core::bytestream::ZCursor::new(jpeg_data));
590 let mut options: zune_core::options::DecoderOptions = Default::default();
591
592 // Disable color conversion by setting the output colorspace to the input
593 // colorspace.
594 decoder.decode_headers()?;
595 if let Some(colorspace) = decoder.input_colorspace() {
596 options = options.jpeg_set_out_colorspace(colorspace);
597 }
598
599 decoder.set_options(options);
600
601 let data = decoder.decode()?;
602
603 Box::new(Cursor::new(data))
604 }
605 #[cfg(feature = "fax")]
606 CompressionMethod::Fax4 => Box::new(super::stream::Group4Reader::new(
607 dimensions,
608 reader,
609 compressed_length,
610 )?),
611 #[cfg(feature = "webp")]
612 CompressionMethod::WebP => Box::new(super::stream::WebPReader::new(
613 reader,
614 compressed_length,
615 samples,
616 )?),
617
618 method => {
619 return Err(TiffError::UnsupportedError(
620 TiffUnsupportedError::UnsupportedCompressionMethod(method),
621 ))
622 }
623 })
624 }
625
626 /// Samples per pixel within chunk.
627 ///
628 /// In planar config, samples are stored in separate strips/chunks, also called bands.
629 ///
630 /// Example with `bits_per_sample = [8, 8, 8]` and `PhotometricInterpretation::RGB`:
631 /// * `PlanarConfiguration::Chunky` -> 3 (RGBRGBRGB...)
632 /// * `PlanarConfiguration::Planar` -> 1 (RRR...) (GGG...) (BBB...)
633 pub(crate) fn samples_per_pixel(&self) -> u16 {
634 match self.planar_config {
635 PlanarConfiguration::Chunky => self.samples,
636 PlanarConfiguration::Planar => 1,
637 }
638 }
639
640 pub(crate) fn samples_per_out_texel(&self, color: ColorType) -> u16 {
641 match self.planar_config {
642 PlanarConfiguration::Chunky => color.num_samples(),
643 PlanarConfiguration::Planar => 1,
644 }
645 }
646
647 /// Number of strips per pixel.
648 pub(crate) fn strips_per_pixel(&self) -> u16 {
649 match self.planar_config {
650 PlanarConfiguration::Chunky => 1,
651 PlanarConfiguration::Planar => self.samples,
652 }
653 }
654
655 pub(crate) fn chunk_file_range(&self, chunk: u32) -> TiffResult<(u64, u64)> {
656 let file_offset = self
657 .chunk_offsets
658 .get(chunk as usize)
659 .ok_or(TiffError::FormatError(
660 TiffFormatError::InconsistentSizesEncountered,
661 ))?;
662
663 let compressed_bytes =
664 self.chunk_bytes
665 .get(chunk as usize)
666 .ok_or(TiffError::FormatError(
667 TiffFormatError::InconsistentSizesEncountered,
668 ))?;
669
670 Ok((*file_offset, *compressed_bytes))
671 }
672
673 pub(crate) fn chunk_dimensions(&self) -> TiffResult<(u32, u32)> {
674 match self.chunk_type {
675 ChunkType::Strip => {
676 let strip_attrs = self.strip_decoder.as_ref().unwrap();
677 Ok((self.width, strip_attrs.rows_per_strip))
678 }
679 ChunkType::Tile => {
680 let tile_attrs = self.tile_attributes.as_ref().unwrap();
681 Ok((
682 u32::try_from(tile_attrs.tile_width)?,
683 u32::try_from(tile_attrs.tile_length)?,
684 ))
685 }
686 }
687 }
688
689 pub(crate) fn readout_for_image(&self) -> TiffResult<ReadoutLayout> {
690 let Image { width, height, .. } = *self;
691 self.readout_for_size(width, height)
692 }
693
694 /// Get the layout for reading out a tile-aligned portion of the image.
695 ///
696 /// The provided width and height should be less than or equal to the image dimensions.
697 pub(crate) fn readout_for_size(&self, width: u32, height: u32) -> TiffResult<ReadoutLayout> {
698 let color = self.colortype()?;
699
700 let tiff_samples = self.samples_per_pixel();
701 let tiff_bits_per_sample = self.bits_per_sample;
702 let data_samples = self.samples_per_out_texel(color);
703 let tiff_chunk_dimensions = self.chunk_dimensions()?;
704 let strips_per_pixel = self.strips_per_pixel();
705
706 let data_dimensions = (width, height);
707
708 let tiff_row_bits = (u64::from(tiff_chunk_dimensions.0) * u64::from(tiff_bits_per_sample))
709 .checked_mul(u64::from(tiff_samples))
710 .ok_or(TiffError::LimitsExceeded)?;
711 let tiff_row_bytes: usize = tiff_row_bits.div_ceil(8).try_into()?;
712
713 let chunk_row_bits = (u64::from(tiff_chunk_dimensions.0) * u64::from(tiff_bits_per_sample))
714 .checked_mul(u64::from(data_samples))
715 .ok_or(TiffError::LimitsExceeded)?;
716 let chunk_row_bytes: usize = chunk_row_bits.div_ceil(8).try_into()?;
717
718 let data_row_bits = (u64::from(data_dimensions.0) * u64::from(tiff_bits_per_sample))
719 .checked_mul(u64::from(data_samples))
720 .ok_or(TiffError::LimitsExceeded)?;
721 let data_row_bytes: usize = data_row_bits.div_ceil(8).try_into()?;
722
723 let chunk_col_stride: usize = data_row_bits
724 .div_ceil(8)
725 .checked_mul(u64::from(tiff_chunk_dimensions.1))
726 .ok_or(TiffError::LimitsExceeded)?
727 .try_into()?;
728
729 let plane_stride: usize = data_row_bits
730 .div_ceil(8)
731 .checked_mul(u64::from(data_dimensions.1))
732 .ok_or(TiffError::LimitsExceeded)?
733 .try_into()?;
734
735 let minimum_row_stride = data_row_bytes;
736
737 let chunks_across: u32 = data_dimensions.0.div_ceil(tiff_chunk_dimensions.0);
738 let chunks_per_plane = (self.chunk_offsets.len() as u32) / u32::from(strips_per_pixel);
739
740 // We would not get an offset in byte units, sorry, no bit interleaving in the output.
741 if chunks_across > 1 && chunk_row_bits % 8 != 0 {
742 return Err(TiffError::UnsupportedError(
743 TiffUnsupportedError::MisalignedTileBoundaries,
744 ));
745 }
746
747 // Only this color type interprets the tag, which is defined with a default of (2, 2)
748 if matches!(color, ColorType::YCbCr(_)) && self.chroma_subsampling != (1, 1) {
749 // The JPEG library does upsampling for us and defines its buffers correctly
750 // (presumably). All other compression schemes are not supported..
751 //
752 // NOTE: as explained in <fa225e820b96bef35f01bf4685654beeb4a8df0c> we may be better
753 // off supporting this tag by consistently upsampling, not by adjusting the buffer
754 // size. At least as a default this makes more sense and is much more permissive in
755 // case the compression stream disagrees with the tags (we would not have enough / or
756 // the wrong buffer layout if we only asked for subsampled planes in a planar layout).
757 if !matches!(self.compression_method, CompressionMethod::ModernJPEG) {
758 return Err(TiffError::UnsupportedError(
759 TiffUnsupportedError::ChromaSubsampling,
760 ));
761 }
762 }
763
764 Ok(ReadoutLayout {
765 planar_config: self.planar_config,
766 color,
767 minimum_row_stride,
768 sample_format: self.sample_format,
769 row_stride: data_row_bytes,
770 chunk_row_stride: chunk_row_bytes,
771 chunk_col_stride,
772 plane_stride,
773 tiff_bits_per_sample,
774 tiff_samples,
775 tiff_chunk_dimensions,
776 tiff_row_bytes,
777 chunks_across,
778 chunks_per_plane,
779 })
780 }
781
782 pub(crate) fn chunk_data_dimensions(&self, chunk_index: u32) -> TiffResult<(u32, u32)> {
783 let dims = self.chunk_dimensions()?;
784
785 match self.chunk_type {
786 ChunkType::Strip => {
787 let rows_per_strip = dims.1;
788 let strips_per_band = self.height.div_ceil(rows_per_strip);
789
790 let strip_height_without_padding = (chunk_index % strips_per_band)
791 .checked_mul(dims.1)
792 .and_then(|x| self.height.checked_sub(x))
793 .ok_or(TiffError::UsageError(UsageError::InvalidChunkIndex(
794 chunk_index,
795 )))?;
796
797 // Ignore potential vertical padding on the bottommost strip
798 let strip_height = dims.1.min(strip_height_without_padding);
799
800 Ok((dims.0, strip_height))
801 }
802 ChunkType::Tile => {
803 let tile_attrs = self.tile_attributes.as_ref().unwrap();
804 let (padding_right, padding_down) = tile_attrs.get_padding(chunk_index as usize);
805
806 let tile_width = tile_attrs.tile_width - padding_right;
807 let tile_length = tile_attrs.tile_length - padding_down;
808
809 Ok((u32::try_from(tile_width)?, u32::try_from(tile_length)?))
810 }
811 }
812 }
813
814 pub(crate) fn expand_chunk(
815 &self,
816 reader: &mut ValueReader<impl Read + Seek>,
817 buf: &mut [u8],
818 layout: &ReadoutLayout,
819 chunk_index: u32,
820 ) -> TiffResult<()> {
821 let ValueReader {
822 reader,
823 bigtiff: _,
824 limits,
825 } = reader;
826
827 let byte_order = reader.byte_order;
828
829 // Validate that the color type is supported.
830 let color_type = layout.color;
831
832 match color_type {
833 ColorType::RGB(n)
834 | ColorType::RGBA(n)
835 | ColorType::CMYK(n)
836 | ColorType::CMYKA(n)
837 | ColorType::YCbCr(n)
838 | ColorType::Gray(n)
839 | ColorType::Multiband {
840 bit_depth: n,
841 num_samples: _,
842 } if n == 8 || n == 16 || n == 32 || n == 64 => {}
843 ColorType::Gray(n)
844 | ColorType::Multiband {
845 bit_depth: n,
846 num_samples: _,
847 } if n < 8 => match self.predictor {
848 Predictor::None => {}
849 Predictor::Horizontal => {
850 return Err(TiffError::UnsupportedError(
851 TiffUnsupportedError::HorizontalPredictor(color_type),
852 ));
853 }
854 Predictor::FloatingPoint => {
855 return Err(TiffError::UnsupportedError(
856 TiffUnsupportedError::FloatingPointPredictor(color_type),
857 ));
858 }
859 },
860 type_ => {
861 return Err(TiffError::UnsupportedError(
862 TiffUnsupportedError::UnsupportedColorType(type_),
863 ));
864 }
865 }
866
867 // Validate that the predictor is supported for the sample type.
868 match (self.predictor, self.sample_format) {
869 (
870 Predictor::Horizontal,
871 SampleFormat::Int | SampleFormat::Uint | SampleFormat::IEEEFP,
872 ) => {}
873 (Predictor::Horizontal, _) => {
874 return Err(TiffError::UnsupportedError(
875 TiffUnsupportedError::HorizontalPredictor(color_type),
876 ));
877 }
878 (Predictor::FloatingPoint, SampleFormat::IEEEFP) => {}
879 (Predictor::FloatingPoint, _) => {
880 return Err(TiffError::UnsupportedError(
881 TiffUnsupportedError::FloatingPointPredictor(color_type),
882 ));
883 }
884 _ => {}
885 }
886
887 let compressed_bytes =
888 self.chunk_bytes
889 .get(chunk_index as usize)
890 .ok_or(TiffError::FormatError(
891 TiffFormatError::InconsistentSizesEncountered,
892 ))?;
893
894 if *compressed_bytes > limits.intermediate_buffer_size as u64 {
895 return Err(TiffError::LimitsExceeded);
896 }
897
898 let compression_method = self.compression_method;
899 let photometric_interpretation = self.photometric_interpretation;
900 let predictor = self.predictor;
901
902 let samples = layout.tiff_samples;
903 let data_samples = layout.samples_per_out_texel();
904
905 // We have two dimensions: the 2d rectangle of encoded data and the 2d rectangle this
906 // takes up in the output. Each has an associated count of bits per pixel. The first
907 // dimension, i.e. a ''row'', is the number of pixels that are encoded with bit packing
908 // while the second is the byte-padded array of each so encoded slices.
909 //
910 // During decoding we map the relevant bits from one to the other.
911 let chunk_dims = self.chunk_dimensions()?;
912 let data_dims = self.chunk_data_dimensions(chunk_index)?;
913
914 let chunk_row_bytes: usize = layout.tiff_row_bytes;
915 let data_row_bytes: usize = layout.chunk_row_bytes(data_dims.0)?;
916
917 // TODO: Should these return errors instead?
918 assert!(layout.minimum_row_stride >= data_row_bytes);
919 assert!(buf.len() >= layout.row_stride * (data_dims.1 as usize - 1) + data_row_bytes);
920
921 let is_all_bits = samples == data_samples;
922 let is_output_chunk_rows = layout.row_stride == chunk_row_bytes;
923
924 let mut reader = Self::create_reader(
925 reader.inner(),
926 compression_method,
927 *compressed_bytes,
928 self.jpeg_tables.as_deref().map(|a| &**a),
929 chunk_dims,
930 self.samples,
931 )?;
932
933 if is_output_chunk_rows && is_all_bits {
934 // Here we can read directly into the output buffer itself.
935 let tile = &mut buf[..chunk_row_bytes * data_dims.1 as usize];
936 reader.read_exact(tile)?;
937
938 for row in tile.chunks_mut(chunk_row_bytes) {
939 super::fix_endianness_and_predict(
940 row,
941 color_type.bit_depth(),
942 samples,
943 byte_order,
944 predictor,
945 );
946 }
947
948 if photometric_interpretation == PhotometricInterpretation::WhiteIsZero {
949 super::invert_colors(tile, color_type, self.sample_format)?;
950 }
951 } else if chunk_row_bytes > data_row_bytes && self.predictor == Predictor::FloatingPoint {
952 // The floating point predictor shuffles the padding bytes into the encoded output, so
953 // this case is handled specially when needed.
954 let mut encoded = vec![0u8; chunk_row_bytes];
955 for row in buf.chunks_mut(layout.row_stride).take(data_dims.1 as usize) {
956 reader.read_exact(&mut encoded)?;
957
958 let row = &mut row[..data_row_bytes];
959 match color_type.bit_depth() {
960 16 => predict_f16(&mut encoded, row, samples),
961 32 => predict_f32(&mut encoded, row, samples),
962 64 => predict_f64(&mut encoded, row, samples),
963 _ => unreachable!(),
964 }
965 if photometric_interpretation == PhotometricInterpretation::WhiteIsZero {
966 super::invert_colors(row, color_type, self.sample_format)?;
967 }
968 }
969 } else if is_all_bits {
970 // We read row-by-row but each row fits in its output buffer.
971 for row in buf.chunks_mut(layout.row_stride).take(data_dims.1 as usize) {
972 let row = &mut row[..data_row_bytes];
973 let used = data_row_bytes.min(chunk_row_bytes);
974
975 // Two ways how we get here: we have more bytes in our chunk data than in the image
976 // we are to read. Then we need to skip the rest of the data. Or we have a bigger
977 // row stride than the chunk contains data, then we need to fill only the front.
978 reader.read_exact(&mut row[..used])?;
979 // Skip horizontal padding
980 if chunk_row_bytes > data_row_bytes {
981 let len = u64::try_from(chunk_row_bytes - data_row_bytes)?;
982 io::copy(&mut reader.by_ref().take(len), &mut io::sink())?;
983 }
984
985 super::fix_endianness_and_predict(
986 row,
987 color_type.bit_depth(),
988 samples,
989 byte_order,
990 predictor,
991 );
992
993 if photometric_interpretation == PhotometricInterpretation::WhiteIsZero {
994 super::invert_colors(row, color_type, self.sample_format)?;
995 }
996 }
997 } else {
998 // The encoded data potentially takes up more space than the output data so we must be
999 // prepared to discard some of it. That decision is bit-by-bit.
1000 let bits_per_pixel = u32::from(self.bits_per_sample) * u32::from(self.samples);
1001 // Assumes the photometric samples are always the start.. This is slightly problematic.
1002 // To expand spport we should instead have different methods of transforming the read
1003 // buffer data, not only the `compact_photometric_bytes` method below and then choose
1004 // from the right one with supplied parameters. Then we can also bit-for-bit copy with
1005 // a selection for better performance.
1006 let photometric_bit_end = u32::from(self.bits_per_sample) * data_samples as u32;
1007
1008 debug_assert!(bits_per_pixel >= photometric_bit_end);
1009
1010 if bits_per_pixel % 8 != 0 || photometric_bit_end % 8 != 0 {
1011 return Err(TiffError::UnsupportedError(
1012 TiffUnsupportedError::InterpretationWithBits(
1013 self.photometric_interpretation,
1014 vec![self.bits_per_sample; self.samples as usize],
1015 ),
1016 ));
1017 }
1018
1019 let photo_range = photometric_bit_end / 8..bits_per_pixel / 8;
1020 let mut encoded = vec![0u8; chunk_row_bytes];
1021 for row in buf.chunks_mut(layout.row_stride).take(data_dims.1 as usize) {
1022 reader.read_exact(&mut encoded)?;
1023
1024 Self::compact_photometric_bytes(&mut encoded, row, &photo_range);
1025
1026 super::fix_endianness_and_predict(
1027 row,
1028 color_type.bit_depth(),
1029 samples,
1030 byte_order,
1031 predictor,
1032 );
1033
1034 if photometric_interpretation == PhotometricInterpretation::WhiteIsZero {
1035 super::invert_colors(row, color_type, self.sample_format)?;
1036 }
1037 }
1038 }
1039
1040 Ok(())
1041 }
1042
1043 /// Turn a contiguous buffer of a whole number of raw sample arrays into a whole number of
1044 /// photometric sample arrays by removing the extra samples in-between.
1045 fn compact_photometric_bytes(
1046 raw: &mut [u8],
1047 row: &mut [u8],
1048 photo_range: &std::ops::Range<u32>,
1049 ) {
1050 raw.chunks_exact_mut(photo_range.end as usize)
1051 .zip(row.chunks_exact_mut(photo_range.start as usize))
1052 .for_each(|(src, dst)| {
1053 dst.copy_from_slice(&src[..photo_range.start as usize]);
1054 });
1055 }
1056 }
1057
1058 impl ReadoutLayout {
1059 pub(crate) fn samples_per_out_texel(&self) -> u16 {
1060 match self.planar_config {
1061 PlanarConfiguration::Chunky => self.color.num_samples(),
1062 PlanarConfiguration::Planar => 1,
1063 }
1064 }
1065
1066 // For a concrete chunk, which may be a partial border chunk, the byte length of one row of its
1067 // pixel data.
1068 pub(crate) fn chunk_row_bytes(&self, width: u32) -> TiffResult<usize> {
1069 let data_samples = self.samples_per_out_texel();
1070 let data_row_bits = (u64::from(width) * u64::from(self.tiff_bits_per_sample))
1071 .checked_mul(u64::from(data_samples))
1072 .ok_or(TiffError::LimitsExceeded)?;
1073 Ok(data_row_bits.div_ceil(8).try_into()?)
1074 }
1075
1076 pub(crate) fn set_row_stride(&mut self, row_stride: usize) -> Result<(), TiffError> {
1077 if row_stride < self.minimum_row_stride {
1078 return Err(TiffError::UsageError(
1079 UsageError::InsufficientOutputRowStride {
1080 needed: self.minimum_row_stride,
1081 requested: row_stride,
1082 },
1083 ));
1084 }
1085
1086 let data_row_bytes = u64::try_from(row_stride)?;
1087
1088 let chunk_col_stride = data_row_bytes
1089 .checked_mul(u64::from(self.tiff_chunk_dimensions.1))
1090 .ok_or(TiffError::LimitsExceeded)?
1091 .try_into()?;
1092
1093 let height = self.plane_stride.checked_div(self.row_stride);
1094
1095 let plane_stride = height
1096 .and_then(|h| data_row_bytes.checked_mul(h as u64))
1097 // If height was zero, or the previous stride was zero, there are no bytes in a plane
1098 .unwrap_or(0)
1099 .try_into()?;
1100
1101 self.row_stride = row_stride;
1102 self.chunk_col_stride = chunk_col_stride;
1103 self.plane_stride = plane_stride;
1104
1105 Ok(())
1106 }
1107
1108 /// Reduce this down to the layout of the output planes.
1109 pub(crate) fn to_plane_layout(&self) -> Result<PlaneLayout, TiffError> {
1110 let num_planes = self.color.num_samples() / self.samples_per_out_texel();
1111
1112 // Using the standard range iterator as checked_add on steroids.
1113 //
1114 // Note: for supporting subsampling, adjust as required.
1115 let mut offset = (0..=usize::MAX).step_by(self.plane_stride);
1116
1117 let plane_offsets = offset.by_ref().take(usize::from(num_planes)).collect();
1118
1119 // Get the past-the-end of the last plane.
1120 //
1121 // This also verifies the `take` above was not short.
1122 let Some(total_bytes) = offset.next() else {
1123 return Err(TiffError::LimitsExceeded);
1124 };
1125
1126 Ok(PlaneLayout {
1127 plane_offsets,
1128 total_bytes,
1129 readout: self.clone(),
1130 })
1131 }
1132 }
1133
1134 /// A `ReadoutLayout` with pre-calculated plane information.
1135 pub(crate) struct PlaneLayout {
1136 /// The underlying readout layout.
1137 pub readout: ReadoutLayout,
1138 /// Buffer offset from one plane of output to the next.
1139 pub plane_offsets: Vec<usize>,
1140 /// Total number of bytes for all planes in given order.
1141 pub total_bytes: usize,
1142 }
1143
1144 impl PlaneLayout {
1145 /// Return the number of planes to extract into the provided buffer.
1146 pub(crate) fn used_planes(&self, buffer: &[impl Sized]) -> TiffResult<u16> {
1147 self.readout.assert_min_layout(buffer)?;
1148 let buffer_len = core::mem::size_of_val(buffer);
1149
1150 // Note: with differently sized planes this is dependent on the plane.
1151 let last_plane_start = buffer_len.checked_sub(self.readout.plane_stride);
1152
1153 // Find how many planes fit into the output buffer.
1154 let used_plane_offsets = self
1155 .plane_offsets
1156 .iter()
1157 .enumerate()
1158 // Find the first plane that would not fit completely at its offset.
1159 .skip_while(|(_, &offset)| last_plane_start >= Some(offset))
1160 .nth(0)
1161 // If all planes fit, use all of them.
1162 .map_or(self.plane_offsets.len(), |(idx, _)| idx);
1163
1164 debug_assert!(
1165 used_plane_offsets <= usize::from(u16::MAX),
1166 "Planes limited by number of samples, which is encoded as u16"
1167 );
1168
1169 Ok(used_plane_offsets as u16)
1170 }
1171 }