/
encoder.rs
2301 lines (2022 loc) · 81.6 KB
/
encoder.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
use borrow::Cow;
use io::{Read, Write};
use ops::{Deref, DerefMut};
use std::{borrow, error, fmt, io, mem, ops, result};
use crc32fast::Hasher as Crc32;
use deflate::write::ZlibEncoder;
use crate::chunk::{self, ChunkType};
use crate::common::{
AnimationControl, BitDepth, BlendOp, BytesPerPixel, ColorType, Compression, DisposeOp,
FrameControl, Info, ParameterError, ParameterErrorKind, ScaledFloat,
};
use crate::filter::{filter, AdaptiveFilterType, FilterType};
use crate::text_metadata::{
EncodableTextChunk, ITXtChunk, TEXtChunk, TextEncodingError, ZTXtChunk,
};
use crate::traits::WriteBytesExt;
pub type Result<T> = result::Result<T, EncodingError>;
#[derive(Debug)]
pub enum EncodingError {
IoError(io::Error),
Format(FormatError),
Parameter(ParameterError),
LimitsExceeded,
}
#[derive(Debug)]
pub struct FormatError {
inner: FormatErrorKind,
}
#[derive(Debug)]
enum FormatErrorKind {
ZeroWidth,
ZeroHeight,
InvalidColorCombination(BitDepth, ColorType),
NoPalette,
// TODO: wait, what?
WrittenTooMuch(usize),
NotAnimated,
OutOfBounds,
EndReached,
ZeroFrames,
MissingFrames,
MissingData(usize),
Unrecoverable,
BadTextEncoding(TextEncodingError),
}
impl error::Error for EncodingError {
fn cause(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
EncodingError::IoError(err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for EncodingError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
use self::EncodingError::*;
match self {
IoError(err) => write!(fmt, "{}", err),
Format(desc) => write!(fmt, "{}", desc),
Parameter(desc) => write!(fmt, "{}", desc),
LimitsExceeded => write!(fmt, "Limits are exceeded."),
}
}
}
impl fmt::Display for FormatError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
use FormatErrorKind::*;
match self.inner {
ZeroWidth => write!(fmt, "Zero width not allowed"),
ZeroHeight => write!(fmt, "Zero height not allowed"),
ZeroFrames => write!(fmt, "Zero frames not allowed"),
InvalidColorCombination(depth, color) => write!(
fmt,
"Invalid combination of bit-depth '{:?}' and color-type '{:?}'",
depth, color
),
NoPalette => write!(fmt, "can't write indexed image without palette"),
WrittenTooMuch(index) => write!(fmt, "wrong data size, got {} bytes too many", index),
NotAnimated => write!(fmt, "not an animation"),
OutOfBounds => write!(
fmt,
"the dimension and position go over the frame boundaries"
),
EndReached => write!(fmt, "all the frames have been already written"),
MissingFrames => write!(fmt, "there are still frames to be written"),
MissingData(n) => write!(fmt, "there are still {} bytes to be written", n),
Unrecoverable => write!(
fmt,
"a previous error put the writer into an unrecoverable state"
),
BadTextEncoding(tee) => match tee {
TextEncodingError::Unrepresentable => write!(
fmt,
"The text metadata cannot be encoded into valid ISO 8859-1"
),
TextEncodingError::InvalidKeywordSize => write!(fmt, "Invalid keyword size"),
TextEncodingError::CompressionError => {
write!(fmt, "Unable to compress text metadata")
}
},
}
}
}
impl From<io::Error> for EncodingError {
fn from(err: io::Error) -> EncodingError {
EncodingError::IoError(err)
}
}
impl From<EncodingError> for io::Error {
fn from(err: EncodingError) -> io::Error {
io::Error::new(io::ErrorKind::Other, err.to_string())
}
}
// Private impl.
impl From<FormatErrorKind> for FormatError {
fn from(kind: FormatErrorKind) -> Self {
FormatError { inner: kind }
}
}
impl From<TextEncodingError> for EncodingError {
fn from(tee: TextEncodingError) -> Self {
EncodingError::Format(FormatError {
inner: FormatErrorKind::BadTextEncoding(tee),
})
}
}
/// PNG Encoder.
///
/// This configures the PNG format options such as animation chunks, palette use, color types,
/// auxiliary chunks etc.
///
/// FIXME: Configuring APNG might be easier (less individual errors) if we had an _adapter_ which
/// borrows this mutably but guarantees that `info.frame_control` is not `None`.
pub struct Encoder<'a, W: Write> {
w: W,
info: Info<'a>,
options: Options,
}
/// Decoding options, internal type, forwarded to the Writer.
#[derive(Default)]
struct Options {
filter: FilterType,
adaptive_filter: AdaptiveFilterType,
sep_def_img: bool,
validate_sequence: bool,
}
impl<'a, W: Write> Encoder<'a, W> {
pub fn new(w: W, width: u32, height: u32) -> Encoder<'static, W> {
Encoder {
w,
info: Info::with_size(width, height),
options: Options::default(),
}
}
/// Specify that the image is animated.
///
/// `num_frames` controls how many frames the animation has, while
/// `num_plays` controls how many times the animation should be
/// repeated until it stops, if it's zero then it will repeat
/// infinitely.
///
/// When this method is returns successfully then the images written will be encoded as fdAT
/// chunks, except for the first image that is still encoded as `IDAT`. You can control if the
/// first frame should be treated as an animation frame with [`Encoder::set_sep_def_img()`].
///
/// This method returns an error if `num_frames` is 0.
pub fn set_animated(&mut self, num_frames: u32, num_plays: u32) -> Result<()> {
if num_frames == 0 {
return Err(EncodingError::Format(FormatErrorKind::ZeroFrames.into()));
}
let actl = AnimationControl {
num_frames,
num_plays,
};
let fctl = FrameControl {
sequence_number: 0,
width: self.info.width,
height: self.info.height,
..Default::default()
};
self.info.animation_control = Some(actl);
self.info.frame_control = Some(fctl);
Ok(())
}
/// Mark the first animated frame as a 'separate default image'.
///
/// In APNG each animated frame is preceded by a special control chunk, `fcTL`. It's up to the
/// encoder to decide if the first image, the standard `IDAT` data, should be part of the
/// animation by emitting this chunk or by not doing so. A default image that is _not_ part of
/// the animation is often interpreted as a thumbnail.
///
/// This method will return an error when animation control was not configured
/// (which is done by calling [`Encoder::set_animated`]).
pub fn set_sep_def_img(&mut self, sep_def_img: bool) -> Result<()> {
if self.info.animation_control.is_some() {
self.options.sep_def_img = sep_def_img;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Sets the raw byte contents of the PLTE chunk. This method accepts
/// both borrowed and owned byte data.
pub fn set_palette<T: Into<Cow<'a, [u8]>>>(&mut self, palette: T) {
self.info.palette = Some(palette.into());
}
/// Sets the raw byte contents of the tRNS chunk. This method accepts
/// both borrowed and owned byte data.
pub fn set_trns<T: Into<Cow<'a, [u8]>>>(&mut self, trns: T) {
self.info.trns = Some(trns.into());
}
/// Set the display gamma of the source system on which the image was generated or last edited.
pub fn set_source_gamma(&mut self, source_gamma: ScaledFloat) {
self.info.source_gamma = Some(source_gamma);
}
/// Set the chromaticities for the source system's display channels (red, green, blue) and the whitepoint
/// of the source system on which the image was generated or last edited.
pub fn set_source_chromaticities(
&mut self,
source_chromaticities: super::SourceChromaticities,
) {
self.info.source_chromaticities = Some(source_chromaticities);
}
/// Mark the image data as conforming to the SRGB color space with the specified rendering intent.
///
/// Matching source gamma and chromaticities chunks are added automatically.
/// Any manually specified source gamma or chromaticities will be ignored.
pub fn set_srgb(&mut self, rendering_intent: super::SrgbRenderingIntent) {
self.info.srgb = Some(rendering_intent);
}
/// Start encoding by writing the header data.
///
/// The remaining data can be supplied by methods on the returned [`Writer`].
pub fn write_header(self) -> Result<Writer<W>> {
Writer::new(self.w, PartialInfo::new(&self.info), self.options).init(&self.info)
}
/// Set the color of the encoded image.
///
/// These correspond to the color types in the png IHDR data that will be written. The length
/// of the image data that is later supplied must match the color type, otherwise an error will
/// be emitted.
pub fn set_color(&mut self, color: ColorType) {
self.info.color_type = color;
}
/// Set the indicated depth of the image data.
pub fn set_depth(&mut self, depth: BitDepth) {
self.info.bit_depth = depth;
}
/// Set compression parameters.
///
/// Accepts a `Compression` or any type that can transform into a `Compression`. Notably `deflate::Compression` and
/// `deflate::CompressionOptions` which "just work".
pub fn set_compression(&mut self, compression: Compression) {
self.info.compression = compression;
}
/// Set the used filter type.
///
/// The default filter is [`FilterType::Sub`] which provides a basic prediction algorithm for
/// sample values based on the previous. For a potentially better compression ratio, at the
/// cost of more complex processing, try out [`FilterType::Paeth`].
///
/// [`FilterType::Sub`]: enum.FilterType.html#variant.Sub
/// [`FilterType::Paeth`]: enum.FilterType.html#variant.Paeth
pub fn set_filter(&mut self, filter: FilterType) {
self.options.filter = filter;
}
/// Set the adaptive filter type.
///
/// Adaptive filtering attempts to select the best filter for each line
/// based on heuristics which minimize the file size for compression rather
/// than use a single filter for the entire image. The default method is
/// [`AdaptiveFilterType::NonAdaptive`].
///
/// [`AdaptiveFilterType::NonAdaptive`]: enum.AdaptiveFilterType.html
pub fn set_adaptive_filter(&mut self, adaptive_filter: AdaptiveFilterType) {
self.options.adaptive_filter = adaptive_filter;
}
/// Set the fraction of time every frame is going to be displayed, in seconds.
///
/// *Note that this parameter can be set for each individual frame after
/// [`Encoder::write_header`] is called. (see [`Writer::set_frame_delay`])*
///
/// If the denominator is 0, it is to be treated as if it were 100
/// (that is, the numerator then specifies 1/100ths of a second).
/// If the the value of the numerator is 0 the decoder should render the next frame
/// as quickly as possible, though viewers may impose a reasonable lower bound.
///
/// The default value is 0 for both the numerator and denominator.
///
/// This method will return an error if the image is not animated.
/// (see [`set_animated`])
///
/// [`write_header`]: struct.Encoder.html#method.write_header
/// [`set_animated`]: struct.Encoder.html#method.set_animated
/// [`Writer::set_frame_delay`]: struct.Writer#method.set_frame_delay
pub fn set_frame_delay(&mut self, numerator: u16, denominator: u16) -> Result<()> {
if let Some(ref mut fctl) = self.info.frame_control {
fctl.delay_den = denominator;
fctl.delay_num = numerator;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Set the blend operation for every frame.
///
/// The blend operation specifies whether the frame is to be alpha blended
/// into the current output buffer content, or whether it should completely
/// replace its region in the output buffer.
///
/// *Note that this parameter can be set for each individual frame after
/// [`write_header`] is called. (see [`Writer::set_blend_op`])*
///
/// See the [`BlendOp`] documentation for the possible values and their effects.
///
/// *Note that for the first frame the two blend modes are functionally
/// equivalent due to the clearing of the output buffer at the beginning
/// of each play.*
///
/// The default value is [`BlendOp::Source`].
///
/// This method will return an error if the image is not animated.
/// (see [`set_animated`])
///
/// [`BlendOP`]: enum.BlendOp.html
/// [`BlendOP::Source`]: enum.BlendOp.html#variant.Source
/// [`write_header`]: struct.Encoder.html#method.write_header
/// [`set_animated`]: struct.Encoder.html#method.set_animated
/// [`Writer::set_blend_op`]: struct.Writer#method.set_blend_op
pub fn set_blend_op(&mut self, op: BlendOp) -> Result<()> {
if let Some(ref mut fctl) = self.info.frame_control {
fctl.blend_op = op;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Set the dispose operation for every frame.
///
/// The dispose operation specifies how the output buffer should be changed
/// at the end of the delay (before rendering the next frame)
///
/// *Note that this parameter can be set for each individual frame after
/// [`write_header`] is called (see [`Writer::set_dispose_op`])*
///
/// See the [`DisposeOp`] documentation for the possible values and their effects.
///
/// *Note that if the first frame uses [`DisposeOp::Previous`]
/// it will be treated as [`DisposeOp::Background`].*
///
/// The default value is [`DisposeOp::None`].
///
/// This method will return an error if the image is not animated.
/// (see [`set_animated`])
///
/// [`DisposeOp`]: ../common/enum.BlendOp.html
/// [`DisposeOp::Previous`]: ../common/enum.BlendOp.html#variant.Previous
/// [`DisposeOp::Background`]: ../common/enum.BlendOp.html#variant.Background
/// [`DisposeOp::None`]: ../common/enum.BlendOp.html#variant.None
/// [`write_header`]: struct.Encoder.html#method.write_header
/// [`set_animated`]: struct.Encoder.html#method.set_animated
/// [`Writer::set_dispose_op`]: struct.Writer#method.set_dispose_op
pub fn set_dispose_op(&mut self, op: DisposeOp) -> Result<()> {
if let Some(ref mut fctl) = self.info.frame_control {
fctl.dispose_op = op;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Convenience function to add tEXt chunks to [`Info`] struct
pub fn add_text_chunk(&mut self, keyword: String, text: String) -> Result<()> {
let text_chunk = TEXtChunk::new(keyword, text);
self.info.uncompressed_latin1_text.push(text_chunk);
Ok(())
}
/// Convenience function to add zTXt chunks to [`Info`] struct
pub fn add_ztxt_chunk(&mut self, keyword: String, text: String) -> Result<()> {
let text_chunk = ZTXtChunk::new(keyword, text);
self.info.compressed_latin1_text.push(text_chunk);
Ok(())
}
/// Convenience function to add iTXt chunks to [`Info`] struct
///
/// This function only sets the `keyword` and `text` field of the iTXt chunk.
/// To set the other fields, create a [`ITXtChunk`] directly, and then encode it to the output stream.
pub fn add_itxt_chunk(&mut self, keyword: String, text: String) -> Result<()> {
let text_chunk = ITXtChunk::new(keyword, text);
self.info.utf8_text.push(text_chunk);
Ok(())
}
/// Validate the written image sequence.
///
/// When validation is turned on (it's turned off by default) then attempts to write more than
/// one `IDAT` image or images beyond the number of frames indicated in the animation control
/// chunk will fail and return an error result instead. Attempts to [finish][finish] the image
/// with missing frames will also return an error.
///
/// [finish]: StreamWriter::finish
///
/// (It's possible to circumvent these checks by writing raw chunks instead.)
pub fn validate_sequence(&mut self, validate: bool) {
self.options.validate_sequence = validate;
}
}
/// PNG writer
///
/// Progresses through the image by writing images, frames, or raw individual chunks. This is
/// constructed through [`Encoder::write_header()`].
///
/// FIXME: Writing of animated chunks might be clearer if we had an _adapter_ that you would call
/// to guarantee the next image to be prefaced with a fcTL-chunk, and all other chunks would be
/// guaranteed to be `IDAT`/not affected by APNG's frame control.
pub struct Writer<W: Write> {
/// The underlying writer.
w: W,
/// The local version of the `Info` struct.
info: PartialInfo,
/// Global encoding options.
options: Options,
/// The total number of image frames, counting all consecutive IDAT and fdAT chunks.
images_written: u64,
/// The total number of animation frames, that is equivalent to counting fcTL chunks.
animation_written: u32,
/// A flag to note when the IEND chunk was already added.
/// This is only set on code paths that drop `Self` to control the destructor.
iend_written: bool,
}
/// Contains the subset of attributes of [Info] needed for [Writer] to function
struct PartialInfo {
width: u32,
height: u32,
bit_depth: BitDepth,
color_type: ColorType,
frame_control: Option<FrameControl>,
animation_control: Option<AnimationControl>,
compression: Compression,
has_palette: bool,
}
impl PartialInfo {
fn new(info: &Info) -> Self {
PartialInfo {
width: info.width,
height: info.height,
bit_depth: info.bit_depth,
color_type: info.color_type,
frame_control: info.frame_control,
animation_control: info.animation_control,
compression: info.compression,
has_palette: info.palette.is_some(),
}
}
fn bpp_in_prediction(&self) -> BytesPerPixel {
// Passthrough
self.to_info().bpp_in_prediction()
}
fn raw_row_length(&self) -> usize {
// Passthrough
self.to_info().raw_row_length()
}
fn raw_row_length_from_width(&self, width: u32) -> usize {
// Passthrough
self.to_info().raw_row_length_from_width(width)
}
/// Converts this partial info to an owned Info struct,
/// setting missing values to their defaults
fn to_info(&self) -> Info<'static> {
Info {
width: self.width,
height: self.height,
bit_depth: self.bit_depth,
color_type: self.color_type,
frame_control: self.frame_control,
animation_control: self.animation_control,
compression: self.compression,
..Default::default()
}
}
}
const DEFAULT_BUFFER_LENGTH: usize = 4 * 1024;
pub(crate) fn write_chunk<W: Write>(mut w: W, name: chunk::ChunkType, data: &[u8]) -> Result<()> {
w.write_be(data.len() as u32)?;
w.write_all(&name.0)?;
w.write_all(data)?;
let mut crc = Crc32::new();
crc.update(&name.0);
crc.update(data);
w.write_be(crc.finalize())?;
Ok(())
}
impl<W: Write> Writer<W> {
fn new(w: W, info: PartialInfo, options: Options) -> Writer<W> {
Writer {
w,
info,
options,
images_written: 0,
animation_written: 0,
iend_written: false,
}
}
fn init(mut self, info: &Info<'_>) -> Result<Self> {
if self.info.width == 0 {
return Err(EncodingError::Format(FormatErrorKind::ZeroWidth.into()));
}
if self.info.height == 0 {
return Err(EncodingError::Format(FormatErrorKind::ZeroHeight.into()));
}
if self
.info
.color_type
.is_combination_invalid(self.info.bit_depth)
{
return Err(EncodingError::Format(
FormatErrorKind::InvalidColorCombination(self.info.bit_depth, self.info.color_type)
.into(),
));
}
self.w.write_all(&[137, 80, 78, 71, 13, 10, 26, 10])?; // PNG signature
info.encode(&mut self.w)?;
Ok(self)
}
/// Write a raw chunk of PNG data.
///
/// The chunk will have its CRC calculated and correctly. The data is not filtered in any way,
/// but the chunk needs to be short enough to have its length encoded correctly.
pub fn write_chunk(&mut self, name: ChunkType, data: &[u8]) -> Result<()> {
use std::convert::TryFrom;
if u32::try_from(data.len()).map_or(true, |length| length > i32::MAX as u32) {
let kind = FormatErrorKind::WrittenTooMuch(data.len() - i32::MAX as usize);
return Err(EncodingError::Format(kind.into()));
}
write_chunk(&mut self.w, name, data)
}
pub fn write_text_chunk<T: EncodableTextChunk>(&mut self, text_chunk: &T) -> Result<()> {
text_chunk.encode(&mut self.w)
}
/// Check if we should allow writing another image.
fn validate_new_image(&self) -> Result<()> {
if !self.options.validate_sequence {
return Ok(());
}
match self.info.animation_control {
None => {
if self.images_written == 0 {
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::EndReached.into()))
}
}
Some(_) => {
if self.info.frame_control.is_some() {
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::EndReached.into()))
}
}
}
}
fn validate_sequence_done(&self) -> Result<()> {
if !self.options.validate_sequence {
return Ok(());
}
if (self.info.animation_control.is_some() && self.info.frame_control.is_some())
|| self.images_written == 0
{
Err(EncodingError::Format(FormatErrorKind::MissingFrames.into()))
} else {
Ok(())
}
}
const MAX_IDAT_CHUNK_LEN: u32 = std::u32::MAX >> 1;
#[allow(non_upper_case_globals)]
const MAX_fdAT_CHUNK_LEN: u32 = (std::u32::MAX >> 1) - 4;
/// Writes the next image data.
pub fn write_image_data(&mut self, data: &[u8]) -> Result<()> {
if self.info.color_type == ColorType::Indexed && !self.info.has_palette {
return Err(EncodingError::Format(FormatErrorKind::NoPalette.into()));
}
self.validate_new_image()?;
let width: usize;
let height: usize;
if let Some(ref mut fctl) = self.info.frame_control {
width = fctl.width as usize;
height = fctl.height as usize;
} else {
width = self.info.width as usize;
height = self.info.height as usize;
}
let in_len = self.info.raw_row_length_from_width(width as u32) - 1;
let data_size = in_len * height;
if data_size != data.len() {
return Err(EncodingError::Parameter(
ParameterErrorKind::ImageBufferSize {
expected: data_size,
actual: data.len(),
}
.into(),
));
}
let prev = vec![0; in_len];
let mut prev = prev.as_slice();
let mut current = vec![0; in_len];
let mut zlib =
deflate::write::ZlibEncoder::new(Vec::new(), self.info.compression.to_options());
let bpp = self.info.bpp_in_prediction();
let filter_method = self.options.filter;
let adaptive_method = self.options.adaptive_filter;
for line in data.chunks(in_len) {
current.copy_from_slice(line);
let filter_type = filter(filter_method, adaptive_method, bpp, prev, &mut current);
zlib.write_all(&[filter_type as u8])?;
zlib.write_all(¤t)?;
prev = line;
}
let zlib_encoded = zlib.finish()?;
match self.info.frame_control {
None => {
self.write_zlib_encoded_idat(&zlib_encoded)?;
}
Some(_) if self.should_skip_frame_control_on_default_image() => {
self.write_zlib_encoded_idat(&zlib_encoded)?;
}
Some(ref mut fctl) => {
fctl.encode(&mut self.w)?;
fctl.sequence_number = fctl.sequence_number.wrapping_add(1);
self.animation_written += 1;
// If the default image is the first frame of an animation, it's still an IDAT.
if self.images_written == 0 {
self.write_zlib_encoded_idat(&zlib_encoded)?;
} else {
let buff_size = zlib_encoded.len().min(Self::MAX_fdAT_CHUNK_LEN as usize);
let mut alldata = vec![0u8; 4 + buff_size];
for chunk in zlib_encoded.chunks(Self::MAX_fdAT_CHUNK_LEN as usize) {
alldata[..4].copy_from_slice(&fctl.sequence_number.to_be_bytes());
alldata[4..][..chunk.len()].copy_from_slice(chunk);
write_chunk(&mut self.w, chunk::fdAT, &alldata[..4 + chunk.len()])?;
fctl.sequence_number = fctl.sequence_number.wrapping_add(1);
}
}
}
}
self.increment_images_written();
Ok(())
}
fn increment_images_written(&mut self) {
self.images_written = self.images_written.saturating_add(1);
if let Some(actl) = self.info.animation_control {
if actl.num_frames <= self.animation_written {
// If we've written all animation frames, all following will be normal image chunks.
self.info.frame_control = None;
}
}
}
fn write_iend(&mut self) -> Result<()> {
self.iend_written = true;
self.write_chunk(chunk::IEND, &[])
}
fn should_skip_frame_control_on_default_image(&self) -> bool {
self.options.sep_def_img && self.images_written == 0
}
fn write_zlib_encoded_idat(&mut self, zlib_encoded: &[u8]) -> Result<()> {
for chunk in zlib_encoded.chunks(Self::MAX_IDAT_CHUNK_LEN as usize) {
self.write_chunk(chunk::IDAT, chunk)?;
}
Ok(())
}
/// Set the used filter type for the following frames.
///
/// The default filter is [`FilterType::Sub`] which provides a basic prediction algorithm for
/// sample values based on the previous. For a potentially better compression ratio, at the
/// cost of more complex processing, try out [`FilterType::Paeth`].
///
/// [`FilterType::Sub`]: enum.FilterType.html#variant.Sub
/// [`FilterType::Paeth`]: enum.FilterType.html#variant.Paeth
pub fn set_filter(&mut self, filter: FilterType) {
self.options.filter = filter;
}
/// Set the adaptive filter type for the following frames.
///
/// Adaptive filtering attempts to select the best filter for each line
/// based on heuristics which minimize the file size for compression rather
/// than use a single filter for the entire image. The default method is
/// [`AdaptiveFilterType::NonAdaptive`].
///
/// [`AdaptiveFilterType::NonAdaptive`]: enum.AdaptiveFilterType.html
pub fn set_adaptive_filter(&mut self, adaptive_filter: AdaptiveFilterType) {
self.options.adaptive_filter = adaptive_filter;
}
/// Set the fraction of time the following frames are going to be displayed,
/// in seconds
///
/// If the denominator is 0, it is to be treated as if it were 100
/// (that is, the numerator then specifies 1/100ths of a second).
/// If the the value of the numerator is 0 the decoder should render the next frame
/// as quickly as possible, though viewers may impose a reasonable lower bound.
///
/// This method will return an error if the image is not animated.
pub fn set_frame_delay(&mut self, numerator: u16, denominator: u16) -> Result<()> {
if let Some(ref mut fctl) = self.info.frame_control {
fctl.delay_den = denominator;
fctl.delay_num = numerator;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Set the dimension of the following frames.
///
/// This function will return an error when:
/// - The image is not an animated;
///
/// - The selected dimension, considering also the current frame position,
/// goes outside the image boundaries;
///
/// - One or both the width and height are 0;
///
// ??? TODO ???
// - The next frame is the default image
pub fn set_frame_dimension(&mut self, width: u32, height: u32) -> Result<()> {
if let Some(ref mut fctl) = self.info.frame_control {
if Some(width) > self.info.width.checked_sub(fctl.x_offset)
|| Some(height) > self.info.height.checked_sub(fctl.y_offset)
{
return Err(EncodingError::Format(FormatErrorKind::OutOfBounds.into()));
} else if width == 0 {
return Err(EncodingError::Format(FormatErrorKind::ZeroWidth.into()));
} else if height == 0 {
return Err(EncodingError::Format(FormatErrorKind::ZeroHeight.into()));
}
fctl.width = width;
fctl.height = height;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Set the position of the following frames.
///
/// An error will be returned if:
/// - The image is not animated;
///
/// - The selected position, considering also the current frame dimension,
/// goes outside the image boundaries;
///
// ??? TODO ???
// - The next frame is the default image
pub fn set_frame_position(&mut self, x: u32, y: u32) -> Result<()> {
if let Some(ref mut fctl) = self.info.frame_control {
if Some(x) > self.info.width.checked_sub(fctl.width)
|| Some(y) > self.info.height.checked_sub(fctl.height)
{
return Err(EncodingError::Format(FormatErrorKind::OutOfBounds.into()));
}
fctl.x_offset = x;
fctl.y_offset = y;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Set the frame dimension to occupy all the image, starting from
/// the current position.
///
/// To reset the frame to the full image size [`reset_frame_position`]
/// should be called first.
///
/// This method will return an error if the image is not animated.
///
/// [`reset_frame_position`]: struct.Writer.html#method.reset_frame_position
pub fn reset_frame_dimension(&mut self) -> Result<()> {
if let Some(ref mut fctl) = self.info.frame_control {
fctl.width = self.info.width - fctl.x_offset;
fctl.height = self.info.height - fctl.y_offset;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Set the frame position to (0, 0).
///
/// Equivalent to calling [`set_frame_position(0, 0)`].
///
/// This method will return an error if the image is not animated.
///
/// [`set_frame_position(0, 0)`]: struct.Writer.html#method.set_frame_position
pub fn reset_frame_position(&mut self) -> Result<()> {
if let Some(ref mut fctl) = self.info.frame_control {
fctl.x_offset = 0;
fctl.y_offset = 0;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Set the blend operation for the following frames.
///
/// The blend operation specifies whether the frame is to be alpha blended
/// into the current output buffer content, or whether it should completely
/// replace its region in the output buffer.
///
/// See the [`BlendOp`] documentation for the possible values and their effects.
///
/// *Note that for the first frame the two blend modes are functionally
/// equivalent due to the clearing of the output buffer at the beginning
/// of each play.*
///
/// This method will return an error if the image is not animated.
///
/// [`BlendOP`]: enum.BlendOp.html
pub fn set_blend_op(&mut self, op: BlendOp) -> Result<()> {
if let Some(ref mut fctl) = self.info.frame_control {
fctl.blend_op = op;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Set the dispose operation for the following frames.
///
/// The dispose operation specifies how the output buffer should be changed
/// at the end of the delay (before rendering the next frame)
///
/// See the [`DisposeOp`] documentation for the possible values and their effects.
///
/// *Note that if the first frame uses [`DisposeOp::Previous`]
/// it will be treated as [`DisposeOp::Background`].*
///
/// This method will return an error if the image is not animated.
///
/// [`DisposeOp`]: ../common/enum.BlendOp.html
/// [`DisposeOp::Previous`]: ../common/enum.BlendOp.html#variant.Previous
/// [`DisposeOp::Background`]: ../common/enum.BlendOp.html#variant.Background
pub fn set_dispose_op(&mut self, op: DisposeOp) -> Result<()> {
if let Some(ref mut fctl) = self.info.frame_control {
fctl.dispose_op = op;
Ok(())
} else {
Err(EncodingError::Format(FormatErrorKind::NotAnimated.into()))
}
}
/// Create a stream writer.
///
/// This allows you to create images that do not fit in memory. The default
/// chunk size is 4K, use `stream_writer_with_size` to set another chunk
/// size.
///
/// This borrows the writer which allows for manually appending additional
/// chunks after the image data has been written.
pub fn stream_writer(&mut self) -> Result<StreamWriter<W>> {
self.stream_writer_with_size(DEFAULT_BUFFER_LENGTH)
}
/// Create a stream writer with custom buffer size.
///
/// See [`stream_writer`].
///
/// [`stream_writer`]: #fn.stream_writer
pub fn stream_writer_with_size(&mut self, size: usize) -> Result<StreamWriter<W>> {
StreamWriter::new(ChunkOutput::Borrowed(self), size)
}
/// Turn this into a stream writer for image data.
///
/// This allows you to create images that do not fit in memory. The default
/// chunk size is 4K, use `stream_writer_with_size` to set another chunk
/// size.
pub fn into_stream_writer(self) -> Result<StreamWriter<'static, W>> {
self.into_stream_writer_with_size(DEFAULT_BUFFER_LENGTH)
}
/// Turn this into a stream writer with custom buffer size.
///
/// See [`into_stream_writer`].
///
/// [`into_stream_writer`]: #fn.into_stream_writer
pub fn into_stream_writer_with_size(self, size: usize) -> Result<StreamWriter<'static, W>> {
StreamWriter::new(ChunkOutput::Owned(self), size)
}
/// Consume the stream writer with validation.
///
/// Unlike a simple drop this ensures that the final chunk was written correctly. When other
/// validation options (chunk sequencing) had been turned on in the configuration then it will
/// also do a check on their correctness _before_ writing the final chunk.
pub fn finish(mut self) -> Result<()> {
self.validate_sequence_done()?;
self.write_iend()?;
self.w.flush()?;
// Explicitly drop `self` just for clarity.
drop(self);
Ok(())
}
}
impl<W: Write> Drop for Writer<W> {
fn drop(&mut self) {
if !self.iend_written {
let _ = self.write_iend();
}
}
}
enum ChunkOutput<'a, W: Write> {
Borrowed(&'a mut Writer<W>),
Owned(Writer<W>),
}
// opted for deref for practical reasons
impl<'a, W: Write> Deref for ChunkOutput<'a, W> {