-
Notifications
You must be signed in to change notification settings - Fork 143
/
stream.rs
1604 lines (1494 loc) · 61.7 KB
/
stream.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
extern crate crc32fast;
use std::convert::From;
use std::default::Default;
use std::error;
use std::fmt;
use std::io;
use std::{borrow::Cow, cmp::min};
use crc32fast::Hasher as Crc32;
use super::zlib::ZlibStream;
use crate::chunk::{self, ChunkType, IDAT, IEND, IHDR};
use crate::common::{
AnimationControl, BitDepth, BlendOp, ColorType, DisposeOp, FrameControl, Info, ParameterError,
PixelDimensions, ScaledFloat, SourceChromaticities, Unit,
};
use crate::text_metadata::{ITXtChunk, TEXtChunk, TextDecodingError, ZTXtChunk};
use crate::traits::ReadBytesExt;
/// TODO check if these size are reasonable
pub const CHUNCK_BUFFER_SIZE: usize = 32 * 1024;
/// Determines if checksum checks should be disabled globally.
///
/// This is used only in fuzzing. `afl` automatically adds `--cfg fuzzing` to RUSTFLAGS which can
/// be used to detect that build.
const CHECKSUM_DISABLED: bool = cfg!(fuzzing);
#[derive(Debug)]
enum U32Value {
// CHUNKS
Length,
Type(u32),
Crc(ChunkType),
}
#[derive(Debug)]
enum State {
Signature(u8, [u8; 7]),
U32Byte3(U32Value, u32),
U32Byte2(U32Value, u32),
U32Byte1(U32Value, u32),
U32(U32Value),
ReadChunk(ChunkType),
PartialChunk(ChunkType),
DecodeData(ChunkType, usize),
}
#[derive(Debug)]
/// Result of the decoding process
pub enum Decoded {
/// Nothing decoded yet
Nothing,
Header(u32, u32, BitDepth, ColorType, bool),
ChunkBegin(u32, ChunkType),
ChunkComplete(u32, ChunkType),
PixelDimensions(PixelDimensions),
AnimationControl(AnimationControl),
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,
}
/// Any kind of error during PNG decoding.
///
/// This enumeration provides a very rough analysis on the origin of the failure. That is, each
/// variant corresponds to one kind of actor causing the error. It should not be understood as a
/// direct blame but can inform the search for a root cause or if such a search is required.
#[derive(Debug)]
pub enum DecodingError {
/// An error in IO of the underlying reader.
IoError(io::Error),
/// The input image was not a valid PNG.
///
/// There isn't a lot that can be done here, except if the program itself was responsible for
/// creating this image then investigate the generator. This is internally implemented with a
/// large Enum. If You are interested in accessing some of the more exact information on the
/// variant then we can discuss in an issue.
Format(FormatError),
/// An interface was used incorrectly.
///
/// This is used in cases where it's expected that the programmer might trip up and stability
/// could be affected. For example when:
///
/// * The decoder is polled for more animation frames despite being done (or not being animated
/// in the first place).
/// * The output buffer does not have the required size.
///
/// As a rough guideline for introducing new variants parts of the requirements are dynamically
/// derived from the (untrusted) input data while the other half is from the caller. In the
/// above cases the number of frames respectively the size is determined by the file while the
/// number of calls
///
/// If you're an application you might want to signal that a bug report is appreciated.
Parameter(ParameterError),
/// The image would have required exceeding the limits configured with the decoder.
///
/// Note that Your allocations, e.g. when reading into a pre-allocated buffer, is __NOT__
/// considered part of the limits. Nevertheless, required intermediate buffers such as for
/// singular lines is checked against the limit.
///
/// Note that this is a best-effort basis.
LimitsExceeded,
}
#[derive(Debug)]
pub struct FormatError {
inner: FormatErrorInner,
}
#[derive(Debug)]
pub(crate) enum FormatErrorInner {
/// Bad framing.
CrcMismatch {
/// Stored CRC32 value
crc_val: u32,
/// Calculated CRC32 sum
crc_sum: u32,
/// The chunk type that has the CRC mismatch.
chunk: ChunkType,
},
/// Not a PNG, the magic signature is missing.
InvalidSignature,
/// End of file, within a chunk event.
UnexpectedEof,
/// End of file, while expecting more image data.
UnexpectedEndOfChunk,
// Errors of chunk level ordering, missing etc.
/// Ihdr must occur.
MissingIhdr,
/// Fctl must occur if an animated chunk occurs.
MissingFctl,
/// Image data that was indicated in IHDR or acTL is missing.
MissingImageData,
/// 4.3., Must be first.
ChunkBeforeIhdr {
kind: ChunkType,
},
/// 4.3., some chunks must be before IDAT.
AfterIdat {
kind: ChunkType,
},
/// 4.3., some chunks must be before PLTE.
AfterPlte {
kind: ChunkType,
},
/// 4.3., some chunks must be between PLTE and IDAT.
OutsidePlteIdat {
kind: ChunkType,
},
/// 4.3., some chunks must be unique.
DuplicateChunk {
kind: ChunkType,
},
/// Specifically for fdat there is an embedded sequence number for chunks.
ApngOrder {
/// The sequence number in the chunk.
present: u32,
/// The one that should have been present.
expected: u32,
},
// Errors specific to particular chunk data to be validated.
/// The palette did not even contain a single pixel data.
ShortPalette {
expected: usize,
len: usize,
},
/// A palletized image did not have a palette.
PaletteRequired,
/// The color-depth combination is not valid according to Table 11.1.
InvalidColorBitDepth {
color_type: ColorType,
bit_depth: BitDepth,
},
ColorWithBadTrns(ColorType),
InvalidBitDepth(u8),
InvalidColorType(u8),
InvalidDisposeOp(u8),
InvalidBlendOp(u8),
InvalidUnit(u8),
/// The rendering intent of the sRGB chunk is invalid.
InvalidSrgbRenderingIntent(u8),
UnknownCompressionMethod(u8),
UnknownFilterMethod(u8),
UnknownInterlaceMethod(u8),
/// The subframe is not in bounds of the image.
/// TODO: fields with relevant data.
BadSubFrameBounds {},
// Errors specific to the IDAT/fDAT chunks.
/// The compression of the data stream was faulty.
CorruptFlateStream {
err: fdeflate::DecompressionError,
},
/// The image data chunk was too short for the expected pixel count.
NoMoreImageData,
/// Bad text encoding
BadTextEncoding(TextDecodingError),
}
impl error::Error for DecodingError {
fn cause(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
DecodingError::IoError(err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for DecodingError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
use self::DecodingError::*;
match self {
IoError(err) => write!(fmt, "{}", err),
Parameter(desc) => write!(fmt, "{}", &desc),
Format(desc) => write!(fmt, "{}", desc),
LimitsExceeded => write!(fmt, "limits are exceeded"),
}
}
}
impl fmt::Display for FormatError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use FormatErrorInner::*;
match &self.inner {
CrcMismatch {
crc_val,
crc_sum,
chunk,
..
} => write!(
fmt,
"CRC error: expected 0x{:x} have 0x{:x} while decoding {:?} chunk.",
crc_val, crc_sum, chunk
),
MissingIhdr => write!(fmt, "IHDR chunk missing"),
MissingFctl => write!(fmt, "fcTL chunk missing before fdAT chunk."),
MissingImageData => write!(fmt, "IDAT or fDAT chunk is missing."),
ChunkBeforeIhdr { kind } => write!(fmt, "{:?} chunk appeared before IHDR chunk", kind),
AfterIdat { kind } => write!(fmt, "Chunk {:?} is invalid after IDAT chunk.", kind),
AfterPlte { kind } => write!(fmt, "Chunk {:?} is invalid after PLTE chunk.", kind),
OutsidePlteIdat { kind } => write!(
fmt,
"Chunk {:?} must appear between PLTE and IDAT chunks.",
kind
),
DuplicateChunk { kind } => write!(fmt, "Chunk {:?} must appear at most once.", kind),
ApngOrder { present, expected } => write!(
fmt,
"Sequence is not in order, expected #{} got #{}.",
expected, present,
),
ShortPalette { expected, len } => write!(
fmt,
"Not enough palette entries, expect {} got {}.",
expected, len
),
PaletteRequired => write!(fmt, "Missing palette of indexed image."),
InvalidColorBitDepth {
color_type,
bit_depth,
} => write!(
fmt,
"Invalid color/depth combination in header: {:?}/{:?}",
color_type, bit_depth,
),
ColorWithBadTrns(color_type) => write!(
fmt,
"Transparency chunk found for color type {:?}.",
color_type
),
InvalidBitDepth(nr) => write!(fmt, "Invalid dispose operation {}.", nr),
InvalidColorType(nr) => write!(fmt, "Invalid color type {}.", nr),
InvalidDisposeOp(nr) => write!(fmt, "Invalid dispose op {}.", nr),
InvalidBlendOp(nr) => write!(fmt, "Invalid blend op {}.", nr),
InvalidUnit(nr) => write!(fmt, "Invalid physical pixel size unit {}.", nr),
InvalidSrgbRenderingIntent(nr) => write!(fmt, "Invalid sRGB rendering intent {}.", nr),
UnknownCompressionMethod(nr) => write!(fmt, "Unknown compression method {}.", nr),
UnknownFilterMethod(nr) => write!(fmt, "Unknown filter method {}.", nr),
UnknownInterlaceMethod(nr) => write!(fmt, "Unknown interlace method {}.", nr),
BadSubFrameBounds {} => write!(fmt, "Sub frame is out-of-bounds."),
InvalidSignature => write!(fmt, "Invalid PNG signature."),
UnexpectedEof => write!(fmt, "Unexpected end of data before image end."),
UnexpectedEndOfChunk => write!(fmt, "Unexpected end of data within a chunk."),
NoMoreImageData => write!(fmt, "IDAT or fDAT chunk is has not enough data for image."),
CorruptFlateStream { err } => {
write!(fmt, "Corrupt deflate stream. ")?;
write!(fmt, "{:?}", err)
}
// TODO: Wrap more info in the enum variant
BadTextEncoding(tde) => {
match tde {
TextDecodingError::Unrepresentable => {
write!(fmt, "Unrepresentable data in tEXt chunk.")
}
TextDecodingError::InvalidKeywordSize => {
write!(fmt, "Keyword empty or longer than 79 bytes.")
}
TextDecodingError::MissingNullSeparator => {
write!(fmt, "No null separator in tEXt chunk.")
}
TextDecodingError::InflationError => {
write!(fmt, "Invalid compressed text data.")
}
TextDecodingError::OutOfDecompressionSpace => {
write!(fmt, "Out of decompression space. Try with a larger limit.")
}
TextDecodingError::InvalidCompressionMethod => {
write!(fmt, "Using an unrecognized byte as compression method.")
}
TextDecodingError::InvalidCompressionFlag => {
write!(fmt, "Using a flag that is not 0 or 255 as a compression flag for iTXt chunk.")
}
TextDecodingError::MissingCompressionFlag => {
write!(fmt, "No compression flag in the iTXt chunk.")
}
}
}
}
}
}
impl From<io::Error> for DecodingError {
fn from(err: io::Error) -> DecodingError {
DecodingError::IoError(err)
}
}
impl From<FormatError> for DecodingError {
fn from(err: FormatError) -> DecodingError {
DecodingError::Format(err)
}
}
impl From<FormatErrorInner> for FormatError {
fn from(inner: FormatErrorInner) -> Self {
FormatError { inner }
}
}
impl From<DecodingError> for io::Error {
fn from(err: DecodingError) -> io::Error {
match err {
DecodingError::IoError(err) => err,
err => io::Error::new(io::ErrorKind::Other, err.to_string()),
}
}
}
impl From<TextDecodingError> for DecodingError {
fn from(tbe: TextDecodingError) -> Self {
DecodingError::Format(FormatError {
inner: FormatErrorInner::BadTextEncoding(tbe),
})
}
}
/// Decoder configuration options
#[derive(Clone)]
pub struct DecodeOptions {
ignore_adler32: bool,
ignore_crc: bool,
ignore_text_chunk: bool,
}
impl Default for DecodeOptions {
fn default() -> Self {
Self {
ignore_adler32: true,
ignore_crc: false,
ignore_text_chunk: false,
}
}
}
impl DecodeOptions {
/// When set, the decoder will not compute and verify the Adler-32 checksum.
///
/// Defaults to `true`.
pub fn set_ignore_adler32(&mut self, ignore_adler32: bool) {
self.ignore_adler32 = ignore_adler32;
}
/// When set, the decoder will not compute and verify the CRC code.
///
/// Defaults to `false`.
pub fn set_ignore_crc(&mut self, ignore_crc: bool) {
self.ignore_crc = ignore_crc;
}
/// Flag to ignore computing and verifying the Adler-32 checksum and CRC
/// code.
pub fn set_ignore_checksums(&mut self, ignore_checksums: bool) {
self.ignore_adler32 = ignore_checksums;
self.ignore_crc = ignore_checksums;
}
/// Ignore text chunks while decoding.
///
/// Defaults to `false`.
pub fn set_ignore_text_chunk(&mut self, ignore_text_chunk: bool) {
self.ignore_text_chunk = ignore_text_chunk;
}
}
/// PNG StreamingDecoder (low-level interface)
///
/// By default, the decoder does not verify Adler-32 checksum computation. To
/// enable checksum verification, set it with [`StreamingDecoder::set_ignore_adler32`]
/// before starting decompression.
pub struct StreamingDecoder {
state: Option<State>,
current_chunk: ChunkState,
/// The inflater state handling consecutive `IDAT` and `fdAT` chunks.
inflater: ZlibStream,
/// The complete image info read from all prior chunks.
pub(crate) info: Option<Info<'static>>,
/// The animation chunk sequence number.
current_seq_no: Option<u32>,
/// Stores where in decoding an `fdAT` chunk we are.
apng_seq_handled: bool,
have_idat: bool,
decode_options: DecodeOptions,
}
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,
/// Remaining bytes to be read.
remaining: u32,
/// Non-decoded bytes in the chunk.
raw_bytes: Vec<u8>,
}
impl StreamingDecoder {
/// Creates a new StreamingDecoder
///
/// Allocates the internal buffers.
pub fn new() -> StreamingDecoder {
StreamingDecoder::new_with_options(DecodeOptions::default())
}
pub fn new_with_options(decode_options: DecodeOptions) -> StreamingDecoder {
let mut inflater = ZlibStream::new();
inflater.set_ignore_adler32(decode_options.ignore_adler32);
StreamingDecoder {
state: Some(State::Signature(0, [0; 7])),
current_chunk: ChunkState::default(),
inflater,
info: None,
current_seq_no: None,
apng_seq_handled: false,
have_idat: false,
decode_options,
}
}
/// Resets the StreamingDecoder
pub fn reset(&mut self) {
self.state = Some(State::Signature(0, [0; 7]));
self.current_chunk.crc = Crc32::new();
self.current_chunk.remaining = 0;
self.current_chunk.raw_bytes.clear();
self.inflater.reset();
self.info = None;
self.current_seq_no = None;
self.apng_seq_handled = false;
self.have_idat = false;
}
/// Provides access to the inner `info` field
pub fn info(&self) -> Option<&Info<'static>> {
self.info.as_ref()
}
pub fn set_ignore_text_chunk(&mut self, ignore_text_chunk: bool) {
self.decode_options.set_ignore_text_chunk(ignore_text_chunk);
}
/// Return whether the decoder is set to ignore the Adler-32 checksum.
pub fn ignore_adler32(&self) -> bool {
self.inflater.ignore_adler32()
}
/// Set whether to compute and verify the Adler-32 checksum during
/// decompression. Return `true` if the flag was successfully set.
///
/// The decoder defaults to `true`.
///
/// This flag cannot be modified after decompression has started until the
/// [`StreamingDecoder`] is reset.
pub fn set_ignore_adler32(&mut self, ignore_adler32: bool) -> bool {
self.inflater.set_ignore_adler32(ignore_adler32)
}
/// Set whether to compute and verify the Adler-32 checksum during
/// decompression.
///
/// The decoder defaults to `false`.
pub fn set_ignore_crc(&mut self, ignore_crc: bool) {
self.decode_options.set_ignore_crc(ignore_crc)
}
/// Low level StreamingDecoder interface.
///
/// Allows to stream partial data to the encoder. Returns a tuple containing the bytes that have
/// been consumed from the input buffer and the current decoding result. If the decoded chunk
/// was an image data chunk, it also appends the read data to `image_data`.
pub fn update(
&mut self,
mut buf: &[u8],
image_data: &mut Vec<u8>,
) -> Result<(usize, Decoded), DecodingError> {
let len = buf.len();
while !buf.is_empty() && self.state.is_some() {
match self.next_state(buf, image_data) {
Ok((bytes, Decoded::Nothing)) => buf = &buf[bytes..],
Ok((bytes, result)) => {
buf = &buf[bytes..];
return Ok((len - buf.len(), result));
}
Err(err) => return Err(err),
}
}
Ok((len - buf.len(), Decoded::Nothing))
}
fn next_state<'a>(
&'a mut self,
buf: &[u8],
image_data: &mut Vec<u8>,
) -> Result<(usize, Decoded), DecodingError> {
use self::State::*;
let current_byte = buf[0];
// Driver should ensure that state is never None
let state = self.state.take().unwrap();
match state {
Signature(i, mut signature) if i < 7 => {
signature[i as usize] = current_byte;
self.state = Some(Signature(i + 1, signature));
Ok((1, Decoded::Nothing))
}
Signature(_, signature)
if signature == [137, 80, 78, 71, 13, 10, 26] && current_byte == 10 =>
{
self.state = Some(U32(U32Value::Length));
Ok((1, Decoded::Nothing))
}
Signature(..) => Err(DecodingError::Format(
FormatErrorInner::InvalidSignature.into(),
)),
U32Byte3(type_, mut val) => {
use self::U32Value::*;
val |= u32::from(current_byte);
match type_ {
Length => {
self.state = Some(U32(Type(val)));
Ok((1, Decoded::Nothing))
}
Type(length) => {
let type_str = ChunkType([
(val >> 24) as u8,
(val >> 16) as u8,
(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();
self.state = Some(U32Byte3(Type(length), val & !0xff));
return Ok((0, Decoded::ImageDataFlushed));
}
self.current_chunk.type_ = type_str;
if !self.decode_options.ignore_crc {
self.current_chunk.crc.reset();
self.current_chunk.crc.update(&type_str.0);
}
self.current_chunk.remaining = length;
self.apng_seq_handled = false;
self.current_chunk.raw_bytes.clear();
self.state = Some(ReadChunk(type_str));
Ok((1, Decoded::ChunkBegin(length, type_str)))
}
Crc(type_str) => {
// If ignore_crc is set, do not calculate CRC. We set
// sum=val so that it short-circuits to true in the next
// if-statement block
let sum = if self.decode_options.ignore_crc {
val
} else {
self.current_chunk.crc.clone().finalize()
};
if val == sum || CHECKSUM_DISABLED {
self.state = Some(State::U32(U32Value::Length));
if type_str == IEND {
Ok((1, Decoded::ImageEnd))
} else {
Ok((1, Decoded::ChunkComplete(val, type_str)))
}
} else {
Err(DecodingError::Format(
FormatErrorInner::CrcMismatch {
crc_val: val,
crc_sum: sum,
chunk: type_str,
}
.into(),
))
}
}
}
}
U32Byte2(type_, val) => {
self.state = Some(U32Byte3(type_, val | u32::from(current_byte) << 8));
Ok((1, Decoded::Nothing))
}
U32Byte1(type_, val) => {
self.state = Some(U32Byte2(type_, val | u32::from(current_byte) << 16));
Ok((1, Decoded::Nothing))
}
U32(type_) => {
self.state = Some(U32Byte1(type_, u32::from(current_byte) << 24));
Ok((1, Decoded::Nothing))
}
PartialChunk(type_str) => {
match type_str {
IDAT => {
self.have_idat = true;
self.state = Some(DecodeData(type_str, 0));
Ok((0, Decoded::PartialChunk(type_str)))
}
chunk::fdAT => {
let data_start;
if let Some(seq_no) = self.current_seq_no {
if !self.apng_seq_handled {
data_start = 4;
let mut buf = &self.current_chunk.raw_bytes[..];
let next_seq_no = buf.read_be()?;
if next_seq_no != seq_no + 1 {
return Err(DecodingError::Format(
FormatErrorInner::ApngOrder {
present: next_seq_no,
expected: seq_no + 1,
}
.into(),
));
}
self.current_seq_no = Some(next_seq_no);
self.apng_seq_handled = true;
} else {
data_start = 0;
}
} else {
return Err(DecodingError::Format(
FormatErrorInner::MissingFctl.into(),
));
}
self.state = Some(DecodeData(type_str, data_start));
Ok((0, Decoded::PartialChunk(type_str)))
}
// Handle other chunks
_ => {
if self.current_chunk.remaining == 0 {
// complete chunk
Ok((0, self.parse_chunk(type_str)?))
} else {
// Make sure we have room to read more of the chunk.
// We need it fully before parsing.
self.reserve_current_chunk()?;
self.state = Some(ReadChunk(type_str));
Ok((0, Decoded::PartialChunk(type_str)))
}
}
}
}
ReadChunk(type_str) => {
// The _previous_ event wanted to return the contents of raw_bytes, and let the
// caller consume it,
if self.current_chunk.remaining == 0 {
self.state = Some(U32(U32Value::Crc(type_str)));
Ok((0, Decoded::Nothing))
} else {
let ChunkState {
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);
let n = min(*remaining, bytes_avail as u32);
if buf_avail == 0 {
self.state = Some(PartialChunk(type_str));
Ok((0, Decoded::Nothing))
} else {
let buf = &buf[..n as usize];
if !self.decode_options.ignore_crc {
crc.update(buf);
}
raw_bytes.extend_from_slice(buf);
*remaining -= n;
if *remaining == 0 {
self.state = Some(PartialChunk(type_str));
} else {
self.state = Some(ReadChunk(type_str));
}
Ok((n as usize, Decoded::Nothing))
}
}
}
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 = self.inflater.decompress(chunk_data, image_data)?;
n += c;
if n == chunk_len && c == 0 {
self.current_chunk.raw_bytes.clear();
self.state = Some(ReadChunk(type_str));
Ok((0, Decoded::ImageData))
} else {
self.state = Some(DecodeData(type_str, n));
Ok((0, Decoded::ImageData))
}
}
}
}
fn reserve_current_chunk(&mut self) -> Result<(), DecodingError> {
// FIXME: use limits, also do so in iccp/zlib decompression.
const MAX: usize = 0x10_0000;
let buffer = &mut self.current_chunk.raw_bytes;
// Double if necessary, but no more than until the limit is reached.
let reserve_size = MAX.saturating_sub(buffer.capacity()).min(buffer.len());
buffer.reserve_exact(reserve_size);
if buffer.capacity() == buffer.len() {
Err(DecodingError::LimitsExceeded)
} else {
Ok(())
}
}
fn parse_chunk(&mut self, type_str: ChunkType) -> Result<Decoded, DecodingError> {
self.state = Some(State::U32(U32Value::Crc(type_str)));
if self.info.is_none() && type_str != IHDR {
return Err(DecodingError::Format(
FormatErrorInner::ChunkBeforeIhdr { kind: type_str }.into(),
));
}
match match type_str {
IHDR => self.parse_ihdr(),
chunk::PLTE => self.parse_plte(),
chunk::tRNS => self.parse_trns(),
chunk::pHYs => self.parse_phys(),
chunk::gAMA => self.parse_gama(),
chunk::acTL => self.parse_actl(),
chunk::fcTL => self.parse_fctl(),
chunk::cHRM => self.parse_chrm(),
chunk::sRGB => self.parse_srgb(),
chunk::iCCP => self.parse_iccp(),
chunk::tEXt if !self.decode_options.ignore_text_chunk => self.parse_text(),
chunk::zTXt if !self.decode_options.ignore_text_chunk => self.parse_ztxt(),
chunk::iTXt if !self.decode_options.ignore_text_chunk => self.parse_itxt(),
_ => Ok(Decoded::PartialChunk(type_str)),
} {
Err(err) => {
// Borrow of self ends here, because Decoding error does not borrow self.
self.state = None;
Err(err)
}
ok => ok,
}
}
fn parse_fctl(&mut self) -> Result<Decoded, DecodingError> {
let mut buf = &self.current_chunk.raw_bytes[..];
let next_seq_no = buf.read_be()?;
// Assuming that fcTL is required before *every* fdAT-sequence
self.current_seq_no = Some(if let Some(seq_no) = self.current_seq_no {
if next_seq_no != seq_no + 1 {
return Err(DecodingError::Format(
FormatErrorInner::ApngOrder {
expected: seq_no + 1,
present: next_seq_no,
}
.into(),
));
}
next_seq_no
} else {
if next_seq_no != 0 {
return Err(DecodingError::Format(
FormatErrorInner::ApngOrder {
expected: 0,
present: next_seq_no,
}
.into(),
));
}
0
});
self.inflater.reset();
let fc = FrameControl {
sequence_number: next_seq_no,
width: buf.read_be()?,
height: buf.read_be()?,
x_offset: buf.read_be()?,
y_offset: buf.read_be()?,
delay_num: buf.read_be()?,
delay_den: buf.read_be()?,
dispose_op: {
let dispose_op = buf.read_be()?;
match DisposeOp::from_u8(dispose_op) {
Some(dispose_op) => dispose_op,
None => {
return Err(DecodingError::Format(
FormatErrorInner::InvalidDisposeOp(dispose_op).into(),
))
}
}
},
blend_op: {
let blend_op = buf.read_be()?;
match BlendOp::from_u8(blend_op) {
Some(blend_op) => blend_op,
None => {
return Err(DecodingError::Format(
FormatErrorInner::InvalidBlendOp(blend_op).into(),
))
}
}
},
};
self.info.as_ref().unwrap().validate(&fc)?;
self.info.as_mut().unwrap().frame_control = Some(fc);
Ok(Decoded::FrameControl(fc))
}
fn parse_actl(&mut self) -> Result<Decoded, DecodingError> {
if self.have_idat {
Err(DecodingError::Format(
FormatErrorInner::AfterIdat { kind: chunk::acTL }.into(),
))
} else {
let mut buf = &self.current_chunk.raw_bytes[..];
let actl = AnimationControl {
num_frames: buf.read_be()?,
num_plays: buf.read_be()?,
};
self.info.as_mut().unwrap().animation_control = Some(actl);
Ok(Decoded::AnimationControl(actl))
}
}
fn parse_plte(&mut self) -> Result<Decoded, DecodingError> {
let info = self.info.as_mut().unwrap();
if info.palette.is_some() {
// Only one palette is allowed
Err(DecodingError::Format(
FormatErrorInner::DuplicateChunk { kind: chunk::PLTE }.into(),
))
} else {
info.palette = Some(Cow::Owned(self.current_chunk.raw_bytes.clone()));
Ok(Decoded::Nothing)
}
}
fn parse_trns(&mut self) -> Result<Decoded, DecodingError> {
let info = self.info.as_mut().unwrap();
if info.trns.is_some() {
return Err(DecodingError::Format(
FormatErrorInner::DuplicateChunk { kind: chunk::PLTE }.into(),
));
}
let (color_type, bit_depth) = { (info.color_type, info.bit_depth as u8) };
let mut vec = self.current_chunk.raw_bytes.clone();
let len = vec.len();
match color_type {
ColorType::Grayscale => {
if len < 2 {
return Err(DecodingError::Format(
FormatErrorInner::ShortPalette { expected: 2, len }.into(),
));
}
if bit_depth < 16 {
vec[0] = vec[1];
vec.truncate(1);
}
info.trns = Some(Cow::Owned(vec));
Ok(Decoded::Nothing)
}
ColorType::Rgb => {
if len < 6 {
return Err(DecodingError::Format(
FormatErrorInner::ShortPalette { expected: 6, len }.into(),
));
}
if bit_depth < 16 {
vec[0] = vec[1];
vec[1] = vec[3];
vec[2] = vec[5];
vec.truncate(3);
}
info.trns = Some(Cow::Owned(vec));
Ok(Decoded::Nothing)
}
ColorType::Indexed => {
// The transparency chunk must be after the palette chunk and
// before the data chunk.
if info.palette.is_none() {
return Err(DecodingError::Format(
FormatErrorInner::AfterPlte { kind: chunk::tRNS }.into(),
));
} else if self.have_idat {
return Err(DecodingError::Format(
FormatErrorInner::OutsidePlteIdat { kind: chunk::tRNS }.into(),
));
}
info.trns = Some(Cow::Owned(vec));
Ok(Decoded::Nothing)
}
c => Err(DecodingError::Format(
FormatErrorInner::ColorWithBadTrns(c).into(),
)),
}
}
fn parse_phys(&mut self) -> Result<Decoded, DecodingError> {
let info = self.info.as_mut().unwrap();
if self.have_idat {
Err(DecodingError::Format(
FormatErrorInner::AfterIdat { kind: chunk::pHYs }.into(),
))
} else if info.pixel_dims.is_some() {
Err(DecodingError::Format(
FormatErrorInner::DuplicateChunk { kind: chunk::pHYs }.into(),
))
} else {
let mut buf = &self.current_chunk.raw_bytes[..];
let xppu = buf.read_be()?;
let yppu = buf.read_be()?;
let unit = buf.read_be()?;
let unit = match Unit::from_u8(unit) {
Some(unit) => unit,
None => {
return Err(DecodingError::Format(
FormatErrorInner::InvalidUnit(unit).into(),
))
}
};
let pixel_dims = PixelDimensions { xppu, yppu, unit };
info.pixel_dims = Some(pixel_dims);
Ok(Decoded::PixelDimensions(pixel_dims))
}
}
fn parse_chrm(&mut self) -> Result<Decoded, DecodingError> {
let info = self.info.as_mut().unwrap();
if self.have_idat {
Err(DecodingError::Format(
FormatErrorInner::AfterIdat { kind: chunk::cHRM }.into(),
))
} else if info.chrm_chunk.is_some() {
Err(DecodingError::Format(
FormatErrorInner::DuplicateChunk { kind: chunk::cHRM }.into(),
))
} else {
let mut buf = &self.current_chunk.raw_bytes[..];
let white_x: u32 = buf.read_be()?;
let white_y: u32 = buf.read_be()?;
let red_x: u32 = buf.read_be()?;
let red_y: u32 = buf.read_be()?;
let green_x: u32 = buf.read_be()?;