| 1 |
//! All IO functionality needed for TIFF decoding |
| 2 |
use std::io::{self, BufRead, BufReader, Read, Seek, Take}; |
| 3 |
|
| 4 |
/// Byte order of the TIFF file. |
| 5 |
#[derive(Clone, Copy, Debug)] |
| 6 |
pub enum ByteOrder { |
| 7 |
/// little endian byte order |
| 8 |
LittleEndian, |
| 9 |
/// big endian byte order |
| 10 |
BigEndian, |
| 11 |
} |
| 12 |
|
| 13 |
/// Reader that is aware of the byte order. |
| 14 |
#[derive(Debug)] |
| 15 |
pub struct EndianReader<R> { |
| 16 |
reader: R, |
| 17 |
pub(crate) byte_order: ByteOrder, |
| 18 |
} |
| 19 |
|
| 20 |
impl<R: Read> EndianReader<R> { |
| 21 |
pub fn new(reader: R, byte_order: ByteOrder) -> Self { |
| 22 |
Self { reader, byte_order } |
| 23 |
} |
| 24 |
|
| 25 |
pub fn inner(&mut self) -> &mut R { |
| 26 |
&mut self.reader |
| 27 |
} |
| 28 |
|
| 29 |
pub fn goto_offset(&mut self, offset: u64) -> io::Result<()> |
| 30 |
where |
| 31 |
R: Seek, |
| 32 |
{ |
| 33 |
self.reader.seek(io::SeekFrom::Start(offset))?; |
| 34 |
Ok(()) |
| 35 |
} |
| 36 |
|
| 37 |
/// Reads an u16 |
| 38 |
#[inline(always)] |
| 39 |
pub fn read_u16(&mut self) -> Result<u16, io::Error> { |
| 40 |
let mut n = [0u8; 2]; |
| 41 |
self.reader.read_exact(&mut n)?; |
| 42 |
Ok(match self.byte_order { |
| 43 |
ByteOrder::LittleEndian => u16::from_le_bytes(n), |
| 44 |
ByteOrder::BigEndian => u16::from_be_bytes(n), |
| 45 |
}) |
| 46 |
} |
| 47 |
|
| 48 |
/// Reads an i8 |
| 49 |
#[inline(always)] |
| 50 |
pub fn read_i8(&mut self) -> Result<i8, io::Error> { |
| 51 |
let mut n = [0u8; 1]; |
| 52 |
self.reader.read_exact(&mut n)?; |
| 53 |
Ok(match self.byte_order { |
| 54 |
ByteOrder::LittleEndian => i8::from_le_bytes(n), |
| 55 |
ByteOrder::BigEndian => i8::from_be_bytes(n), |
| 56 |
}) |
| 57 |
} |
| 58 |
|
| 59 |
/// Reads an i16 |
| 60 |
#[inline(always)] |
| 61 |
pub fn read_i16(&mut self) -> Result<i16, io::Error> { |
| 62 |
let mut n = [0u8; 2]; |
| 63 |
self.reader.read_exact(&mut n)?; |
| 64 |
Ok(match self.byte_order { |
| 65 |
ByteOrder::LittleEndian => i16::from_le_bytes(n), |
| 66 |
ByteOrder::BigEndian => i16::from_be_bytes(n), |
| 67 |
}) |
| 68 |
} |
| 69 |
|
| 70 |
/// Reads an u32 |
| 71 |
#[inline(always)] |
| 72 |
pub fn read_u32(&mut self) -> Result<u32, io::Error> { |
| 73 |
let mut n = [0u8; 4]; |
| 74 |
self.reader.read_exact(&mut n)?; |
| 75 |
Ok(match self.byte_order { |
| 76 |
ByteOrder::LittleEndian => u32::from_le_bytes(n), |
| 77 |
ByteOrder::BigEndian => u32::from_be_bytes(n), |
| 78 |
}) |
| 79 |
} |
| 80 |
|
| 81 |
/// Reads an i32 |
| 82 |
#[inline(always)] |
| 83 |
pub fn read_i32(&mut self) -> Result<i32, io::Error> { |
| 84 |
let mut n = [0u8; 4]; |
| 85 |
self.reader.read_exact(&mut n)?; |
| 86 |
Ok(match self.byte_order { |
| 87 |
ByteOrder::LittleEndian => i32::from_le_bytes(n), |
| 88 |
ByteOrder::BigEndian => i32::from_be_bytes(n), |
| 89 |
}) |
| 90 |
} |
| 91 |
|
| 92 |
/// Reads an u64 |
| 93 |
#[inline(always)] |
| 94 |
pub fn read_u64(&mut self) -> Result<u64, io::Error> { |
| 95 |
let mut n = [0u8; 8]; |
| 96 |
self.reader.read_exact(&mut n)?; |
| 97 |
Ok(match self.byte_order { |
| 98 |
ByteOrder::LittleEndian => u64::from_le_bytes(n), |
| 99 |
ByteOrder::BigEndian => u64::from_be_bytes(n), |
| 100 |
}) |
| 101 |
} |
| 102 |
|
| 103 |
/// Reads an i64 |
| 104 |
#[inline(always)] |
| 105 |
pub fn read_i64(&mut self) -> Result<i64, io::Error> { |
| 106 |
let mut n = [0u8; 8]; |
| 107 |
self.reader.read_exact(&mut n)?; |
| 108 |
Ok(match self.byte_order { |
| 109 |
ByteOrder::LittleEndian => i64::from_le_bytes(n), |
| 110 |
ByteOrder::BigEndian => i64::from_be_bytes(n), |
| 111 |
}) |
| 112 |
} |
| 113 |
|
| 114 |
/// Reads an f32 |
| 115 |
#[inline(always)] |
| 116 |
pub fn read_f32(&mut self) -> Result<f32, io::Error> { |
| 117 |
let mut n = [0u8; 4]; |
| 118 |
self.reader.read_exact(&mut n)?; |
| 119 |
Ok(f32::from_bits(match self.byte_order { |
| 120 |
ByteOrder::LittleEndian => u32::from_le_bytes(n), |
| 121 |
ByteOrder::BigEndian => u32::from_be_bytes(n), |
| 122 |
})) |
| 123 |
} |
| 124 |
|
| 125 |
/// Reads an f64 |
| 126 |
#[inline(always)] |
| 127 |
pub fn read_f64(&mut self) -> Result<f64, io::Error> { |
| 128 |
let mut n = [0u8; 8]; |
| 129 |
self.reader.read_exact(&mut n)?; |
| 130 |
Ok(f64::from_bits(match self.byte_order { |
| 131 |
ByteOrder::LittleEndian => u64::from_le_bytes(n), |
| 132 |
ByteOrder::BigEndian => u64::from_be_bytes(n), |
| 133 |
})) |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
// |
| 138 |
// # READERS |
| 139 |
// |
| 140 |
|
| 141 |
/// Type alias for the deflate Reader |
| 142 |
#[cfg(feature = "deflate")] |
| 143 |
pub type DeflateReader<R> = flate2::read::ZlibDecoder<R>; |
| 144 |
|
| 145 |
// |
| 146 |
// ## LZW Reader |
| 147 |
// |
| 148 |
|
| 149 |
/// Reader that decompresses LZW streams |
| 150 |
#[cfg(feature = "lzw")] |
| 151 |
pub struct LZWReader<R: Read> { |
| 152 |
reader: BufReader<Take<R>>, |
| 153 |
decoder: weezl::decode::Decoder, |
| 154 |
} |
| 155 |
|
| 156 |
#[cfg(feature = "lzw")] |
| 157 |
impl<R: Read> LZWReader<R> { |
| 158 |
/// Wraps a reader |
| 159 |
pub fn new(reader: R, compressed_length: usize) -> LZWReader<R> { |
| 160 |
let configuration = |
| 161 |
weezl::decode::Configuration::with_tiff_size_switch(weezl::BitOrder::Msb, 8) |
| 162 |
.with_yield_on_full_buffer(true); |
| 163 |
Self { |
| 164 |
reader: BufReader::with_capacity( |
| 165 |
(32 * 1024).min(compressed_length), |
| 166 |
reader.take(u64::try_from(compressed_length).unwrap()), |
| 167 |
), |
| 168 |
decoder: configuration.build(), |
| 169 |
} |
| 170 |
} |
| 171 |
} |
| 172 |
|
| 173 |
#[cfg(feature = "lzw")] |
| 174 |
impl<R: Read> Read for LZWReader<R> { |
| 175 |
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 176 |
loop { |
| 177 |
let result = self.decoder.decode_bytes(self.reader.fill_buf()?, buf); |
| 178 |
self.reader.consume(result.consumed_in); |
| 179 |
|
| 180 |
match result.status { |
| 181 |
Ok(weezl::LzwStatus::Ok) => { |
| 182 |
if result.consumed_out == 0 { |
| 183 |
continue; |
| 184 |
} else { |
| 185 |
return Ok(result.consumed_out); |
| 186 |
} |
| 187 |
} |
| 188 |
Ok(weezl::LzwStatus::NoProgress) => { |
| 189 |
assert_eq!(result.consumed_in, 0); |
| 190 |
assert_eq!(result.consumed_out, 0); |
| 191 |
assert!(self.reader.buffer().is_empty()); |
| 192 |
return Err(io::Error::new( |
| 193 |
io::ErrorKind::UnexpectedEof, |
| 194 |
"no lzw end code found", |
| 195 |
)); |
| 196 |
} |
| 197 |
Ok(weezl::LzwStatus::Done) => { |
| 198 |
return Ok(result.consumed_out); |
| 199 |
} |
| 200 |
Err(err) => return Err(io::Error::new(io::ErrorKind::InvalidData, err)), |
| 201 |
} |
| 202 |
} |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
// |
| 207 |
// ## PackBits Reader |
| 208 |
// |
| 209 |
|
| 210 |
/// Internal state machine for the PackBitsReader. |
| 211 |
enum PackBitsReaderState { |
| 212 |
Header, |
| 213 |
Literal, |
| 214 |
Repeat { value: u8 }, |
| 215 |
} |
| 216 |
|
| 217 |
/// Reader that unpacks Apple's `PackBits` format |
| 218 |
pub struct PackBitsReader<R: Read> { |
| 219 |
reader: Take<R>, |
| 220 |
state: PackBitsReaderState, |
| 221 |
count: usize, |
| 222 |
} |
| 223 |
|
| 224 |
impl<R: Read> PackBitsReader<R> { |
| 225 |
/// Wraps a reader |
| 226 |
pub fn new(reader: R, length: u64) -> Self { |
| 227 |
Self { |
| 228 |
reader: reader.take(length), |
| 229 |
state: PackBitsReaderState::Header, |
| 230 |
count: 0, |
| 231 |
} |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
impl<R: Read> Read for PackBitsReader<R> { |
| 236 |
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 237 |
while let PackBitsReaderState::Header = self.state { |
| 238 |
if self.reader.limit() == 0 { |
| 239 |
return Ok(0); |
| 240 |
} |
| 241 |
let mut header: [u8; 1] = [0]; |
| 242 |
self.reader.read_exact(&mut header)?; |
| 243 |
let h = header[0] as i8; |
| 244 |
if (-127..=-1).contains(&h) { |
| 245 |
let mut data: [u8; 1] = [0]; |
| 246 |
self.reader.read_exact(&mut data)?; |
| 247 |
self.state = PackBitsReaderState::Repeat { value: data[0] }; |
| 248 |
self.count = (1 - h as isize) as usize; |
| 249 |
} else if h >= 0 { |
| 250 |
self.state = PackBitsReaderState::Literal; |
| 251 |
self.count = h as usize + 1; |
| 252 |
} else { |
| 253 |
// h = -128 is a no-op. |
| 254 |
} |
| 255 |
} |
| 256 |
|
| 257 |
let length = buf.len().min(self.count); |
| 258 |
let actual = match self.state { |
| 259 |
PackBitsReaderState::Literal => self.reader.read(&mut buf[..length])?, |
| 260 |
PackBitsReaderState::Repeat { value } => { |
| 261 |
for b in &mut buf[..length] { |
| 262 |
*b = value; |
| 263 |
} |
| 264 |
|
| 265 |
length |
| 266 |
} |
| 267 |
PackBitsReaderState::Header => unreachable!(), |
| 268 |
}; |
| 269 |
|
| 270 |
self.count -= actual; |
| 271 |
if self.count == 0 { |
| 272 |
self.state = PackBitsReaderState::Header; |
| 273 |
} |
| 274 |
Ok(actual) |
| 275 |
} |
| 276 |
} |
| 277 |
|
| 278 |
#[cfg(feature = "fax")] |
| 279 |
pub struct Group4Reader<R: Read> { |
| 280 |
decoder: fax34::decoder::Group4Decoder<io::Bytes<io::BufReader<io::Take<R>>>>, |
| 281 |
line_buf: io::Cursor<Vec<u8>>, |
| 282 |
height: u16, |
| 283 |
width: u16, |
| 284 |
y: u16, |
| 285 |
} |
| 286 |
|
| 287 |
#[cfg(feature = "fax")] |
| 288 |
impl<R: Read> Group4Reader<R> { |
| 289 |
pub fn new( |
| 290 |
dimensions: (u32, u32), |
| 291 |
reader: R, |
| 292 |
compressed_length: u64, |
| 293 |
) -> crate::TiffResult<Self> { |
| 294 |
let width = u16::try_from(dimensions.0)?; |
| 295 |
let height = u16::try_from(dimensions.1)?; |
| 296 |
|
| 297 |
Ok(Self { |
| 298 |
decoder: fax34::decoder::Group4Decoder::new( |
| 299 |
io::BufReader::new(reader.take(compressed_length)).bytes(), |
| 300 |
width, |
| 301 |
)?, |
| 302 |
line_buf: io::Cursor::new(Vec::with_capacity(width.into())), |
| 303 |
width, |
| 304 |
height, |
| 305 |
y: 0, |
| 306 |
}) |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
#[cfg(feature = "fax")] |
| 311 |
impl<R: Read> Read for Group4Reader<R> { |
| 312 |
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 313 |
// Either we have not read any line or we are at the end of a line. |
| 314 |
if self.line_buf.position() as usize == self.line_buf.get_ref().len() |
| 315 |
&& self.y < self.height |
| 316 |
{ |
| 317 |
let next = self.decoder.advance().map_err(std::io::Error::other)?; |
| 318 |
|
| 319 |
match next { |
| 320 |
fax34::decoder::DecodeStatus::End => (), |
| 321 |
fax34::decoder::DecodeStatus::Incomplete => { |
| 322 |
self.y += 1; |
| 323 |
|
| 324 |
// We known `transitions` yields exactly `self.width` items (per doc). |
| 325 |
// FIXME: performance. We do not need an individual pixel iterator, filling |
| 326 |
// memory especially for long runs can be much quicker. The `transitions` are |
| 327 |
// the positions at which each run-length ends, i.e. the prefix sum of run |
| 328 |
// lengths. Runs in fax4 start with white. |
| 329 |
let transitions = fax34::decoder::pels(self.decoder.transition(), self.width); |
| 330 |
|
| 331 |
let buffer = self.line_buf.get_mut(); |
| 332 |
buffer.resize(usize::from(self.width).div_ceil(8), 0u8); |
| 333 |
|
| 334 |
let target = &mut buffer[..]; |
| 335 |
|
| 336 |
// Note: it may seem strange to treat black as 0b1 and white as 0b0 despite all |
| 337 |
// our streams by default decoding as-if PhotometricInterpretation::BlackIsMin. |
| 338 |
// This is however consistent with libtiff. It seems that fax4's "White" |
| 339 |
// differs from what libtiff thinks of as "White". For content, a line of data |
| 340 |
// is in runlength encoding of white-black-white-black always starting with |
| 341 |
// white. In libtiff, the loop always does both colors in one go and the |
| 342 |
// structure is: |
| 343 |
// |
| 344 |
// ``` |
| 345 |
// for (; runs < erun; runs += 2) |
| 346 |
// // white run |
| 347 |
// do { *lp++ = 0L; } while (…) |
| 348 |
// // black run |
| 349 |
// do { *lp++ = -1L; } while (…) |
| 350 |
// ``` |
| 351 |
// |
| 352 |
// So indeed the Fax4::White run is implemented by filling with zeros. |
| 353 |
let mut bits = transitions.map(|c| match c { |
| 354 |
fax34::Color::Black => true, |
| 355 |
fax34::Color::White => false, |
| 356 |
}); |
| 357 |
|
| 358 |
// Assemble bits in MSB as per our library representation for buffer. |
| 359 |
for byte in target { |
| 360 |
let mut val = 0; |
| 361 |
|
| 362 |
for (idx, bit) in bits.by_ref().take(8).enumerate() { |
| 363 |
val |= u8::from(bit) << (7 - idx % 8); |
| 364 |
} |
| 365 |
|
| 366 |
*byte = val; |
| 367 |
} |
| 368 |
|
| 369 |
self.line_buf.set_position(0); |
| 370 |
} |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
self.line_buf.read(buf) |
| 375 |
} |
| 376 |
} |
| 377 |
|
| 378 |
#[cfg(test)] |
| 379 |
mod test { |
| 380 |
use super::*; |
| 381 |
|
| 382 |
#[test] |
| 383 |
fn test_packbits() { |
| 384 |
let encoded = vec![ |
| 385 |
0xFE, 0xAA, 0x02, 0x80, 0x00, 0x2A, 0xFD, 0xAA, 0x03, 0x80, 0x00, 0x2A, 0x22, 0xF7, |
| 386 |
0xAA, |
| 387 |
]; |
| 388 |
let encoded_len = encoded.len(); |
| 389 |
|
| 390 |
let buff = io::Cursor::new(encoded); |
| 391 |
let mut decoder = PackBitsReader::new(buff, encoded_len as u64); |
| 392 |
|
| 393 |
let mut decoded = Vec::new(); |
| 394 |
decoder.read_to_end(&mut decoded).unwrap(); |
| 395 |
|
| 396 |
let expected = vec![ |
| 397 |
0xAA, 0xAA, 0xAA, 0x80, 0x00, 0x2A, 0xAA, 0xAA, 0xAA, 0xAA, 0x80, 0x00, 0x2A, 0x22, |
| 398 |
0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, |
| 399 |
]; |
| 400 |
assert_eq!(decoded, expected); |
| 401 |
} |
| 402 |
} |