Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lazy parse sBIT #556

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 41 additions & 2 deletions src/common.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Common types shared between the encoder and decoder
use crate::decoder::stream::{FormatError, FormatErrorInner};
use crate::text_metadata::{ITXtChunk, TEXtChunk, ZTXtChunk};
use crate::{chunk, encoder};
use crate::{chunk, encoder, DecodingError};
use io::Write;
use std::{borrow::Cow, convert::TryFrom, fmt, io};

Expand Down Expand Up @@ -580,7 +581,7 @@ pub struct Info<'a> {
pub color_type: ColorType,
pub interlaced: bool,
/// The image's `sBIT` chunk, if present; contains significant bits of the sample.
pub sbit: Option<Cow<'a, [u8]>>,
pub(crate) sbit: Option<Result<[u8; 4], FormatErrorInner>>,
/// The image's `tRNS` chunk, if present; contains the alpha channel of the image's palette, 1 byte per entry.
pub trns: Option<Cow<'a, [u8]>>,
pub pixel_dims: Option<PixelDimensions>,
Expand Down Expand Up @@ -759,6 +760,44 @@ impl Info<'_> {
self.srgb = Some(rendering_intent);
self.icc_profile = None;
}

/// Number of significant bits per channel, according to sBIT chunk
pub fn sbit(&self) -> Result<Option<&[u8]>, DecodingError> {
let sbit = match self.sbit.as_ref() {
None => return Ok(None),
Some(Ok(sbit)) => sbit,
Some(Err(e)) => return Err(FormatError::from(e.clone()).into()),
};

let len = match self.color_type {
ColorType::Grayscale => 1,
ColorType::Rgb | ColorType::Indexed => 3,
ColorType::GrayscaleAlpha => 2,
ColorType::Rgba => 4,
};

let sbit = &sbit[..len];

// The sample depth for color type 3 is fixed at eight bits.
let sample_depth = if self.color_type == ColorType::Indexed {
BitDepth::Eight
} else {
self.bit_depth
};

for &depth in sbit {
if depth < 1 || depth > sample_depth as u8 {
return Err(DecodingError::Format(
FormatErrorInner::InvalidSbit {
sample_depth,
sbit: depth,
}
.into(),
));
}
}
Ok(Some(sbit))
}
}

impl BytesPerPixel {
Expand Down
161 changes: 86 additions & 75 deletions src/decoder/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ pub struct FormatError {
inner: FormatErrorInner,
}

#[derive(Debug)]
#[derive(Debug, Clone)]
pub(crate) enum FormatErrorInner {
/// Bad framing.
CrcMismatch {
Expand Down Expand Up @@ -205,14 +205,14 @@ pub(crate) enum FormatErrorInner {
// Errors specific to particular chunk data to be validated.
/// The palette did not even contain a single pixel data.
ShortPalette {
expected: usize,
len: usize,
expected: u32,
len: u32,
},
/// sBIT chunk size based on color type.
InvalidSbitChunkSize {
color_type: ColorType,
expected: usize,
len: usize,
expected: u32,
len: u32,
},
InvalidSbit {
sample_depth: BitDepth,
Expand Down Expand Up @@ -244,7 +244,7 @@ pub(crate) enum FormatErrorInner {
// Errors specific to the IDAT/fdAT chunks.
/// The compression of the data stream was faulty.
CorruptFlateStream {
err: fdeflate::DecompressionError,
err: CloneDecompressionError,
},
/// The image data chunk was too short for the expected pixel count.
NoMoreImageData,
Expand All @@ -269,6 +269,42 @@ pub(crate) enum FormatErrorInner {
},
}

impl From<fdeflate::DecompressionError> for FormatErrorInner {
fn from(err: fdeflate::DecompressionError) -> Self {
Self::CorruptFlateStream {
err: CloneDecompressionError(err),
}
}
}

#[repr(transparent)]
#[derive(Debug)]
pub(crate) struct CloneDecompressionError(pub fdeflate::DecompressionError);

impl Clone for CloneDecompressionError {
fn clone(&self) -> Self {
use fdeflate::DecompressionError::*;
Self(match self.0 {
BadZlibHeader => BadZlibHeader,
InsufficientInput => InsufficientInput,
InvalidBlockType => InvalidBlockType,
InvalidUncompressedBlockLength => InvalidUncompressedBlockLength,
InvalidHlit => InvalidHlit,
InvalidHdist => InvalidHdist,
InvalidCodeLengthRepeat => InvalidCodeLengthRepeat,
BadCodeLengthHuffmanTree => BadCodeLengthHuffmanTree,
BadLiteralLengthHuffmanTree => BadLiteralLengthHuffmanTree,
BadDistanceHuffmanTree => BadDistanceHuffmanTree,
InvalidLiteralLengthCode => InvalidLiteralLengthCode,
InvalidDistanceCode => InvalidDistanceCode,
InputStartsWithRun => InputStartsWithRun,
DistanceTooFarBack => DistanceTooFarBack,
WrongChecksum => WrongChecksum,
ExtraInput => ExtraInput,
})
}
}

impl error::Error for DecodingError {
fn cause(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Expand Down Expand Up @@ -976,7 +1012,10 @@ impl StreamingDecoder {
self.state = Some(State::new_u32(U32ValueKind::Crc(type_str)));
let parse_result = match type_str {
IHDR => self.parse_ihdr(),
chunk::sBIT => self.parse_sbit(),
chunk::sBIT => {
self.parse_sbit();
Ok(Decoded::Nothing)
}
chunk::PLTE => self.parse_plte(),
chunk::tRNS => self.parse_trns(),
chunk::pHYs => self.parse_phys(),
Expand Down Expand Up @@ -1110,76 +1149,49 @@ impl StreamingDecoder {
}
}

fn parse_sbit(&mut self) -> Result<Decoded, DecodingError> {
let mut parse = || {
let info = self.info.as_mut().unwrap();
fn parse_sbit(&mut self) {
let info = self.info.as_mut().unwrap();
let raw_bytes = &self.current_chunk.raw_bytes[..];
let have_idat = self.have_idat;
let parse = || {
if info.palette.is_some() {
return Err(DecodingError::Format(
FormatErrorInner::AfterPlte { kind: chunk::sBIT }.into(),
));
return Err(FormatErrorInner::AfterPlte { kind: chunk::sBIT }.into());
}

if self.have_idat {
return Err(DecodingError::Format(
FormatErrorInner::AfterIdat { kind: chunk::sBIT }.into(),
));
if have_idat {
return Err(FormatErrorInner::AfterIdat { kind: chunk::sBIT }.into());
}

if info.sbit.is_some() {
return Err(DecodingError::Format(
FormatErrorInner::DuplicateChunk { kind: chunk::sBIT }.into(),
));
return Err(FormatErrorInner::DuplicateChunk { kind: chunk::sBIT }.into());
}

let (color_type, bit_depth) = { (info.color_type, info.bit_depth) };
// The sample depth for color type 3 is fixed at eight bits.
let sample_depth = if color_type == ColorType::Indexed {
BitDepth::Eight
} else {
bit_depth
};
self.limits
.reserve_bytes(self.current_chunk.raw_bytes.len())?;
let vec = self.current_chunk.raw_bytes.clone();
let len = vec.len();
let len = raw_bytes.len();

// expected lenth of the chunk
let expected = match color_type {
let expected = match info.color_type {
ColorType::Grayscale => 1,
ColorType::Rgb | ColorType::Indexed => 3,
ColorType::GrayscaleAlpha => 2,
ColorType::Rgba => 4,
};

// Check if the sbit chunk size is valid.
if expected != len {
return Err(DecodingError::Format(
FormatErrorInner::InvalidSbitChunkSize {
color_type,
expected,
len,
}
.into(),
));
}

for sbit in &vec {
if *sbit < 1 || *sbit > sample_depth as u8 {
return Err(DecodingError::Format(
FormatErrorInner::InvalidSbit {
sample_depth,
sbit: *sbit,
}
.into(),
));
if expected as usize != len {
return Err(FormatErrorInner::InvalidSbitChunkSize {
color_type: info.color_type,
expected,
len: len as _,
}
.into());
}
info.sbit = Some(Cow::Owned(vec));
Ok(Decoded::Nothing)

let mut sbit = [0; 4];
sbit[..len].copy_from_slice(&raw_bytes[..len]);
Ok(sbit)
};

parse().ok();
Ok(Decoded::Nothing)
info.sbit = Some(parse());
}

fn parse_trns(&mut self) -> Result<Decoded, DecodingError> {
Expand All @@ -1198,7 +1210,11 @@ impl StreamingDecoder {
ColorType::Grayscale => {
if len < 2 {
return Err(DecodingError::Format(
FormatErrorInner::ShortPalette { expected: 2, len }.into(),
FormatErrorInner::ShortPalette {
expected: 2,
len: len as _,
}
.into(),
));
}
if bit_depth < 16 {
Expand All @@ -1211,7 +1227,11 @@ impl StreamingDecoder {
ColorType::Rgb => {
if len < 6 {
return Err(DecodingError::Format(
FormatErrorInner::ShortPalette { expected: 6, len }.into(),
FormatErrorInner::ShortPalette {
expected: 6,
len: len as _,
}
.into(),
));
}
if bit_depth < 16 {
Expand Down Expand Up @@ -1542,9 +1562,7 @@ impl StreamingDecoder {
info.icc_profile = Some(Cow::Owned(profile));
}
Err(fdeflate::BoundedDecompressionError::DecompressionError { inner: err }) => {
return Err(DecodingError::Format(
FormatErrorInner::CorruptFlateStream { err }.into(),
))
return Err(DecodingError::Format(FormatErrorInner::from(err).into()))
}
Err(fdeflate::BoundedDecompressionError::OutputTooLarge { .. }) => {
return Err(DecodingError::LimitsExceeded);
Expand Down Expand Up @@ -1822,7 +1840,6 @@ mod tests {
use crate::{Decoder, DecodingError, Reader};
use approx::assert_relative_eq;
use byteorder::WriteBytesExt;
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::fs::File;
Expand Down Expand Up @@ -2059,24 +2076,18 @@ mod tests {

#[test]
fn image_source_sbit() {
fn trial(path: &str, expected: Option<Cow<[u8]>>) {
fn trial(path: &str, expected: Option<&[u8]>) {
let decoder = crate::Decoder::new(File::open(path).unwrap());
let reader = decoder.read_info().unwrap();
let actual: Option<Cow<[u8]>> = reader.info().sbit.clone();
let actual = reader.info().sbit().ok().flatten();
assert!(actual == expected);
}

trial("tests/sbit/g.png", Some(Cow::Owned(vec![5u8])));
trial("tests/sbit/ga.png", Some(Cow::Owned(vec![5u8, 3u8])));
trial(
"tests/sbit/indexed.png",
Some(Cow::Owned(vec![5u8, 6u8, 5u8])),
);
trial("tests/sbit/rgb.png", Some(Cow::Owned(vec![5u8, 6u8, 5u8])));
trial(
"tests/sbit/rgba.png",
Some(Cow::Owned(vec![5u8, 6u8, 5u8, 8u8])),
);
trial("tests/sbit/g.png", Some(&[5u8]));
trial("tests/sbit/ga.png", Some(&[5u8, 3u8]));
trial("tests/sbit/indexed.png", Some(&[5u8, 6u8, 5u8]));
trial("tests/sbit/rgb.png", Some(&[5u8, 6u8, 5u8]));
trial("tests/sbit/rgba.png", Some(&[5u8, 6u8, 5u8, 8u8]));
}

/// Test handling of a PNG file that contains *two* iCCP chunks.
Expand Down
8 changes: 2 additions & 6 deletions src/decoder/zlib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,7 @@ impl ZlibStream {
let (in_consumed, out_consumed) = self
.state
.read(data, self.out_buffer.as_mut_slice(), self.out_pos, false)
.map_err(|err| {
DecodingError::Format(FormatErrorInner::CorruptFlateStream { err }.into())
})?;
.map_err(|err| DecodingError::Format(FormatErrorInner::from(err).into()))?;

self.started = true;
self.out_pos += out_consumed;
Expand Down Expand Up @@ -130,9 +128,7 @@ impl ZlibStream {
let (_in_consumed, out_consumed) = self
.state
.read(&[], self.out_buffer.as_mut_slice(), self.out_pos, true)
.map_err(|err| {
DecodingError::Format(FormatErrorInner::CorruptFlateStream { err }.into())
})?;
.map_err(|err| DecodingError::Format(FormatErrorInner::from(err).into()))?;

self.out_pos += out_consumed;

Expand Down
Loading