Removed ChunkInfo and added additional functions on decoder

This commit is contained in:
Alan Race committed 2022-07-18 17:15:44 +02:00
1 parent 5cadbffebf
commit 802949f6e1
7 files changed
+69 -108

No files matched your search

+2 -2
View File
@@ -451,8 +451,8 @@ impl Entry {
// Case 3: There is more than one value, but it fits in the offset field.
if value_bytes <= 4 || bigtiff && value_bytes <= 8 {
match self.type_ {
Type::BYTE => return Ok(offset_to_bytes(self.count as usize, self)?),
Type::SBYTE => return Ok(offset_to_sbytes(self.count as usize, self)?),
Type::BYTE => return offset_to_bytes(self.count as usize, self),
Type::SBYTE => return offset_to_sbytes(self.count as usize, self),
Type::ASCII => {
let mut buf = vec![0; self.count as usize];
self.r(bo).read_exact(&mut buf)?;
+34 -74
View File
@@ -61,39 +61,6 @@ impl TileAttributes {
}
}
#[derive(Debug)]
#[non_exhaustive]
/// ChunkInfo describes the properties of a chunk (either tile or strip).
pub struct ChunkInfo {
/// Width of the chunk as specified (includes potential padding). This has the same
/// value for all chunks in the image.
pub chunk_width: u32,
/// Height/Length of the chunk as specified (includes potential padding). This has
/// the same value for all chunks in the image.
pub chunk_height: u32,
/// Width of the data (excluding potential padding). This can take different values
/// on the right column of the image due to padding.
pub data_width: u32,
/// Height/Length of the data (excluding potential padding). This can take different values
/// on the bottom row of the image due to padding.
pub data_height: u32,
}
impl ChunkInfo {
#[inline]
/// Returns the amount of padding (pixles) on the right-side of the chunk.
pub fn padding_right(&self) -> u32 {
self.chunk_width - self.data_width
}
#[inline]
/// Returns the amount of padding (pixles) on the bottom-side of the chunk.
pub fn padding_down(&self) -> u32 {
self.chunk_height - self.data_height
}
}
#[derive(Debug)]
pub(crate) struct Image {
pub ifd: Option<Directory>,
@@ -408,39 +375,38 @@ impl Image {
Ok((*file_offset, *compressed_bytes))
}
pub(crate) fn chunk_dimensions(&self) -> TiffResult<(usize, usize)> {
pub(crate) fn chunk_dimensions(&self) -> TiffResult<(u32, u32)> {
match self.chunk_type {
ChunkType::Strip => {
let width = usize::try_from(self.width)?;
let strip_attrs = self.strip_decoder.as_ref().unwrap();
Ok((width, usize::try_from(strip_attrs.rows_per_strip)?))
Ok((self.width, strip_attrs.rows_per_strip))
}
ChunkType::Tile => {
let tile_attrs = self.tile_attributes.as_ref().unwrap();
Ok((tile_attrs.tile_width, tile_attrs.tile_length))
Ok((
u32::try_from(tile_attrs.tile_width)?,
u32::try_from(tile_attrs.tile_length)?,
))
}
}
}
pub(crate) fn chunk_info(&self, chunk_index: u32) -> Option<ChunkInfo> {
match &self.chunk_type {
ChunkType::Strip => {
let rows_per_strip = self.strip_decoder.as_ref().unwrap().rows_per_strip;
pub(crate) fn chunk_data_dimensions(&self, chunk_index: u32) -> TiffResult<(u32, u32)> {
let dims = self.chunk_dimensions()?;
match self.chunk_type {
ChunkType::Strip => {
let strip_height_without_padding = chunk_index
.checked_mul(rows_per_strip)
.and_then(|x| self.height.checked_sub(x))?;
.checked_mul(dims.1)
.and_then(|x| self.height.checked_sub(x))
.ok_or(TiffError::UsageError(UsageError::InvalidChunkIndex(
chunk_index,
)))?;
// Ignore potential vertical padding on the bottommost strip
let strip_height = rows_per_strip.min(strip_height_without_padding);
let strip_height = dims.1.min(strip_height_without_padding);
Some(ChunkInfo {
chunk_width: self.width,
chunk_height: rows_per_strip,
data_width: self.width,
data_height: strip_height,
})
Ok((dims.0, strip_height))
}
ChunkType::Tile => {
let tile_attrs = self.tile_attributes.as_ref().unwrap();
@@ -449,13 +415,7 @@ impl Image {
let tile_width = tile_attrs.tile_width - padding_right;
let tile_length = tile_attrs.tile_length - padding_down;
Some(ChunkInfo {
chunk_width: tile_attrs.tile_width as u32,
chunk_height: tile_attrs.tile_length as u32,
data_width: tile_width as u32,
data_height: tile_length as u32,
})
Ok((u32::try_from(tile_width)?, u32::try_from(tile_length)?))
}
}
}
@@ -528,21 +488,21 @@ impl Image {
let predictor = self.predictor;
let samples = self.bits_per_sample.len();
let chunk_info = self.chunk_info(chunk_index).ok_or(TiffError::UsageError(
UsageError::InvalidChunkIndex(chunk_index),
))?;
let chunk_dims = self.chunk_dimensions()?;
let data_dims = self.chunk_data_dimensions(chunk_index)?;
let padding_right = chunk_dims.0 - data_dims.0;
let jpeg_tables = self.jpeg_tables.clone();
let mut reader =
Self::create_reader(reader, compression_method, *compressed_bytes, jpeg_tables)?;
if output_width == chunk_info.data_width as usize && chunk_info.padding_right() == 0 {
let total_samples =
chunk_info.data_width as usize * chunk_info.data_height as usize * samples;
if output_width == data_dims.0 as usize && padding_right == 0 {
let total_samples = data_dims.0 as usize * data_dims.1 as usize * samples;
let tile = &mut buffer.as_bytes_mut()[..total_samples * byte_len];
reader.read_exact(tile)?;
for row in 0..chunk_info.data_height as usize {
for row in 0..data_dims.1 as usize {
let row_start = row as usize * output_width as usize * samples;
let row_end = (row + 1) * output_width as usize * samples;
let row = buffer.subrange(row_start..row_end);
@@ -551,13 +511,14 @@ impl Image {
if photometric_interpretation == PhotometricInterpretation::WhiteIsZero {
super::invert_colors(&mut buffer.subrange(0..total_samples), color_type);
}
} else if chunk_info.padding_right() > 0 && self.predictor == Predictor::FloatingPoint {
} else if padding_right > 0 && self.predictor == Predictor::FloatingPoint {
// The floating point predictor shuffles the padding bytes into the encoded output, so
// this case is handled specially when needed.
let mut encoded = vec![0u8; chunk_info.chunk_width as usize * samples * byte_len];
for row in 0..chunk_info.data_height as usize {
let mut encoded = vec![0u8; chunk_dims.0 as usize * samples * byte_len];
for row in 0..data_dims.1 as usize {
let row_start = row * output_width as usize * samples;
let row_end = row_start + chunk_info.data_width as usize * samples;
let row_end = row_start + data_dims.0 as usize * samples;
reader.read_exact(&mut encoded)?;
match buffer.subrange(row_start..row_end) {
@@ -570,17 +531,16 @@ impl Image {
}
}
} else {
for row in 0..chunk_info.data_height as usize {
for row in 0..data_dims.1 as usize {
let row_start = row * output_width as usize * samples;
let row_end = row_start + chunk_info.data_width as usize * samples;
let row_end = row_start + data_dims.0 as usize * samples;
let row = &mut buffer.as_bytes_mut()[(row_start * byte_len)..(row_end * byte_len)];
reader.read_exact(row)?;
// Skip horizontal padding
if chunk_info.padding_right() > 0 {
let len =
u64::try_from(chunk_info.padding_right() as usize * samples * byte_len)?;
if padding_right > 0 {
let len = u64::try_from(padding_right as usize * samples * byte_len)?;
io::copy(&mut reader.by_ref().take(len), &mut io::sink())?;
}
+28 -27
View File
@@ -8,7 +8,7 @@ use crate::{
};
use self::ifd::Directory;
use self::image::{ChunkInfo, Image};
use self::image::Image;
use crate::tags::{
CompressionMethod, PhotometricInterpretation, Predictor, SampleFormat, Tag, Type,
};
@@ -1147,7 +1147,7 @@ impl<R: Read + Seek> Decoder<R> {
pub fn read_strip(&mut self) -> TiffResult<DecodingResult> {
let result = self.read_chunk(self.current_chunk)?;
Ok(result.0)
Ok(result)
}
/// Read a single tile from the image and return it as a Vector. This method does not return
@@ -1160,36 +1160,37 @@ impl<R: Read + Seek> Decoder<R> {
self.current_chunk += 1;
Ok(result.0)
Ok(result)
}
/// Read the specified chunk (at index `chunk_index`) and return the binary data as a Vector and
/// `ChunkInfo` describing the size of the chunk.
pub fn read_chunk(&mut self, chunk_index: u32) -> TiffResult<(DecodingResult, ChunkInfo)> {
let chunk_info = self
.image()
.chunk_info(chunk_index)
.ok_or(UsageError::InvalidChunkIndex(chunk_index))?;
/// Read the specified chunk (at index `chunk_index`) and return the binary data as a Vector.
pub fn read_chunk(&mut self, chunk_index: u32) -> TiffResult<DecodingResult> {
let data_dims = self.image().chunk_data_dimensions(chunk_index)?;
let mut result = self.result_buffer(
chunk_info.data_width as usize,
chunk_info.data_height as usize,
)?;
let mut result = self.result_buffer(data_dims.0 as usize, data_dims.1 as usize)?;
self.read_chunk_to_buffer(
result.as_buffer(0),
chunk_index,
chunk_info.data_width as usize,
)?;
self.read_chunk_to_buffer(result.as_buffer(0), chunk_index, data_dims.0 as usize)?;
Ok((result, chunk_info))
Ok(result)
}
/// Returns the default chunk size for the current image. Any given chunk in the image is at most as large as
/// the value returned here. For the size of the data (chunk minus padding), use `chunk_data_dimensions`.
pub fn chunk_dimensions(&self) -> TiffResult<(u32, u32)> {
self.image().chunk_dimensions()
}
/// Returns the size of the data in the chunk with the specified index. This is the default size of the chunk,
/// minus any padding.
pub fn chunk_data_dimensions(&self, chunk_index: u32) -> TiffResult<(u32, u32)> {
self.image().chunk_data_dimensions(chunk_index)
}
/// Decodes the entire image and return it as a Vector
pub fn read_image(&mut self) -> TiffResult<DecodingResult> {
let width = usize::try_from(self.image().width)?;
let height = usize::try_from(self.image().height)?;
let mut result = self.result_buffer(width, height)?;
let width = self.image().width;
let height = self.image().height;
let mut result = self.result_buffer(width as usize, height as usize)?;
if width == 0 || height == 0 {
return Ok(result);
}
@@ -1212,20 +1213,20 @@ impl<R: Read + Seek> Decoder<R> {
));
}
let chunks_across = (width - 1) / chunk_dimensions.0 + 1;
let strip_samples = width * chunk_dimensions.1 * samples;
let chunks_across = ((width - 1) / chunk_dimensions.0 + 1) as usize;
let strip_samples = width as usize * chunk_dimensions.1 as usize * samples;
for chunk in 0..self.image().chunk_offsets.len() {
self.goto_offset_u64(self.image().chunk_offsets[chunk])?;
let x = chunk % chunks_across;
let y = chunk / chunks_across;
let buffer_offset = y * strip_samples + x * chunk_dimensions.0 * samples;
let buffer_offset = y * strip_samples + x * chunk_dimensions.0 as usize * samples;
let byte_order = self.reader.byte_order;
self.image.expand_chunk(
&mut self.reader,
result.as_buffer(buffer_offset).copy(),
width,
width as usize,
byte_order,
chunk as u32,
)?;
+1 -1
View File
@@ -53,7 +53,7 @@ impl Compression for Deflate {
impl CompressionAlgorithm for Deflate {
fn write_to<W: Write>(&mut self, writer: &mut W, bytes: &[u8]) -> Result<u64, io::Error> {
let mut encoder = ZlibEncoder::new(writer, self.level);
encoder.write_all(&bytes)?;
encoder.write_all(bytes)?;
encoder.try_finish()?;
Ok(encoder.total_out())
}
+2 -2
View File
@@ -157,7 +157,7 @@ mod tests {
let mut compressed_data = Vec::<u8>::new();
let mut writer = Cursor::new(&mut compressed_data);
Packbits::default()
.write_to(&mut writer, &UNCOMPRESSED_DATA)
.write_to(&mut writer, UNCOMPRESSED_DATA)
.unwrap();
assert_eq!(compressed_data, EXPECTED_COMPRESSED_DATA);
}
@@ -207,7 +207,7 @@ mod tests {
let mut compressed_data = Vec::<u8>::new();
let mut writer = Cursor::new(&mut compressed_data);
Packbits::default()
.write_to(&mut writer, &TEST_DATA)
.write_to(&mut writer, TEST_DATA)
.unwrap();
assert_eq!(compressed_data, EXPECTED_COMPRESSED_DATA);
}
+1 -1
View File
@@ -276,7 +276,7 @@ fn test_tiled_incremental() {
for tile in 0..tiles {
match decoder.read_chunk(tile).unwrap() {
(DecodingResult::U8(res), _) => {
DecodingResult::U8(res) => {
let sum: u64 = res.into_iter().map(<u64>::from).sum();
assert_eq!(sum, sums[tile as usize]);
}
+1 -1
View File
@@ -513,7 +513,7 @@ fn test_rows_per_strip() {
for i in 0..50 {
let img2 = [i; 2 * 100];
match decoder.read_chunk(i as u32).unwrap() {
(DecodingResult::U8(data), _) => assert_eq!(&img2[..], &data[..]),
DecodingResult::U8(data) => assert_eq!(&img2[..], &data[..]),
other => panic!("Incorrect strip type {:?}", other),
}
}