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

Switch to miniz_oxide #218

Merged
merged 5 commits into from
Jun 13, 2020
Merged
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ include = [
]

[dependencies]
inflate = "0.4.2"
miniz_oxide = "0.3.5"
deflate = { version = "0.8.2", optional = true }
bitflags = "1.0"
crc32fast = "1.2.0"
Expand Down
26 changes: 21 additions & 5 deletions src/decoder/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod stream;
mod zlib;

use self::stream::{get_info, CHUNCK_BUFFER_SIZE};
pub use self::stream::{Decoded, DecodingError, StreamingDecoder};
Expand Down Expand Up @@ -170,21 +171,22 @@ impl<R: Read> ReadDecoder<R> {
while !self.at_eof {
let buf = self.reader.fill_buf()?;
if buf.is_empty() {
return Err(DecodingError::Format("unexpected EOF".into()));
return Err(DecodingError::Format("unexpected EOF after image".into()));
}
let (consumed, event) = self.decoder.update(buf, &mut vec![])?;
self.reader.consume(consumed);
match event {
Decoded::Nothing => (),
Decoded::ImageEnd => self.at_eof = true,
Decoded::ChunkComplete(_, _) => return Ok(()),
Decoded::ImageData => { /*ignore more data*/ }
// ignore more data
Decoded::ChunkComplete(_, _) | Decoded::ChunkBegin(_, _) | Decoded::ImageData => {}
Decoded::ImageDataFlushed => return Ok(()),
Decoded::PartialChunk(_) => {}
new => unreachable!("{:?}", new),
}
}

Err(DecodingError::Format("unexpected EOF".into()))
Err(DecodingError::Format("unexpected EOF after image".into()))
}

fn info(&self) -> Option<&Info> {
Expand Down Expand Up @@ -227,6 +229,7 @@ struct SubframeInfo {
width: u32,
rowlen: usize,
interlace: InterlaceIter,
consumed_and_flushed: bool,
}

#[derive(Clone)]
Expand Down Expand Up @@ -409,7 +412,9 @@ impl<R: Read> Reader<R> {
}
}
// Advance over the rest of data for this (sub-)frame.
self.decoder.finished_decoding()?;
if !self.subframe.consumed_and_flushed {
self.decoder.finished_decoding()?;
}
// Advance our state to expect the next frame.
self.finished_frame();
Ok(())
Expand Down Expand Up @@ -657,6 +662,12 @@ impl<R: Read> Reader<R> {
interlace: passdata,
}));
} else {
if self.subframe.consumed_and_flushed {
return Err(DecodingError::Format(
format!("not enough data for image").into(),
));
}

// Clear the current buffer before appending more data.
if self.scan_start > 0 {
self.current.drain(..self.scan_start).for_each(drop);
Expand All @@ -666,6 +677,9 @@ impl<R: Read> Reader<R> {
let val = self.decoder.decode_next(&mut self.current)?;
match val {
Some(Decoded::ImageData) => {}
Some(Decoded::ImageDataFlushed) => {
self.subframe.consumed_and_flushed = true;
}
None => {
if !self.current.is_empty() {
return Err(DecodingError::Format("file truncated".into()));
Expand All @@ -686,6 +700,7 @@ impl SubframeInfo {
width: 0,
rowlen: 0,
interlace: InterlaceIter::None(0..0),
consumed_and_flushed: false,
}
}

Expand All @@ -708,6 +723,7 @@ impl SubframeInfo {
width,
rowlen: info.raw_row_length_from_width(width),
interlace,
consumed_and_flushed: false,
}
}
}
Expand Down
54 changes: 37 additions & 17 deletions src/decoder/stream.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
extern crate crc32fast;
extern crate inflate;

use std::borrow::Cow;
use std::cmp::min;
Expand All @@ -11,7 +10,7 @@ use std::io;

use crc32fast::Hasher as Crc32;

use self::inflate::InflateStream;
use super::zlib::ZlibStream;
use crate::chunk::{self, ChunkType, IDAT, IEND, IHDR};
use crate::common::{
AnimationControl, BitDepth, BlendOp, ColorType, DisposeOp, FrameControl, Info, PixelDimensions,
Expand All @@ -28,14 +27,6 @@ pub const CHUNCK_BUFFER_SIZE: usize = 32 * 1024;
/// be used to detect that build.
const CHECKSUM_DISABLED: bool = cfg!(fuzzing);

fn zlib_stream() -> InflateStream {
if CHECKSUM_DISABLED {
InflateStream::from_zlib_no_checksum()
} else {
InflateStream::from_zlib()
}
}

#[derive(Debug)]
enum U32Value {
// CHUNKS
Expand Down Expand Up @@ -69,6 +60,10 @@ pub enum Decoded {
FrameControl(FrameControl),
/// Decoded raw image data.
ImageData,
/// The last of a consecutive chunk of IDAT was done.
/// This is distinct from ChunkComplete which only marks that some IDAT chunk was completed but
/// not that no additional IDAT chunk follows.
ImageDataFlushed,
PartialChunk(ChunkType),
ImageEnd,
}
Expand Down Expand Up @@ -141,7 +136,7 @@ pub struct StreamingDecoder {
state: Option<State>,
current_chunk: ChunkState,
/// The inflater state handling consecutive `IDAT` and `fdAT` chunks.
inflater: InflateStream,
inflater: ZlibStream,
/// The complete image info read from all prior chunks.
info: Option<Info>,
/// The animation chunk sequence number.
Expand All @@ -152,6 +147,10 @@ pub struct StreamingDecoder {
}

struct ChunkState {
/// The type of the current chunk.
/// Relevant for `IDAT` and `fdAT` which aggregate consecutive chunks of their own type.
type_: ChunkType,

/// Partial crc until now.
crc: Crc32,

Expand All @@ -170,7 +169,7 @@ impl StreamingDecoder {
StreamingDecoder {
state: Some(State::Signature(0, [0; 7])),
current_chunk: ChunkState::default(),
inflater: zlib_stream(),
inflater: ZlibStream::new(),
info: None,
current_seq_no: None,
apng_seq_handled: false,
Expand All @@ -184,7 +183,7 @@ impl StreamingDecoder {
self.current_chunk.crc = Crc32::new();
self.current_chunk.remaining = 0;
self.current_chunk.raw_bytes.clear();
self.inflater = zlib_stream();
self.inflater = ZlibStream::new();
self.info = None;
self.current_seq_no = None;
self.apng_seq_handled = false;
Expand Down Expand Up @@ -269,6 +268,20 @@ impl StreamingDecoder {
(val >> 8) as u8,
val as u8,
];
if type_str != self.current_chunk.type_
&& (self.current_chunk.type_ == IDAT
|| self.current_chunk.type_ == chunk::fdAT)
{
self.current_chunk.type_ = type_str;
self.inflater.finish_compressed_chunks(image_data)?;
self.inflater.reset();
return goto!(
0,
U32Byte3(Type(length), val & !0xff),
emit Decoded::ImageDataFlushed
);
}
self.current_chunk.type_ = type_str;
self.current_chunk.crc.reset();
self.current_chunk.crc.update(&type_str);
self.current_chunk.remaining = length;
Expand Down Expand Up @@ -369,6 +382,7 @@ impl StreamingDecoder {
crc,
remaining,
raw_bytes,
type_: _,
} = &mut self.current_chunk;
let buf_avail = raw_bytes.capacity() - raw_bytes.len();
let bytes_avail = min(buf.len(), buf_avail);
Expand All @@ -393,10 +407,9 @@ impl StreamingDecoder {
DecodeData(type_str, mut n) => {
let chunk_len = self.current_chunk.raw_bytes.len();
let chunk_data = &self.current_chunk.raw_bytes[n..];
let (c, data) = self.inflater.update(chunk_data)?;
image_data.extend_from_slice(data);
let c = self.inflater.decompress(chunk_data, image_data)?;
n += c;
if n == chunk_len && data.is_empty() && c == 0 {
if n == chunk_len && c == 0 {
goto!(
0,
ReadChunk(type_str, true),
Expand Down Expand Up @@ -477,7 +490,7 @@ impl StreamingDecoder {
}
0
});
self.inflater = zlib_stream();
self.inflater = ZlibStream::new();
let fc = FrameControl {
sequence_number: next_seq_no,
width: buf.read_be()?,
Expand Down Expand Up @@ -679,9 +692,16 @@ impl Info {
}
}

impl Default for StreamingDecoder {
fn default() -> Self {
Self::new()
}
}

impl Default for ChunkState {
fn default() -> Self {
ChunkState {
type_: [0; 4],
crc: Crc32::new(),
remaining: 0,
raw_bytes: Vec::with_capacity(CHUNCK_BUFFER_SIZE),
Expand Down
Loading