-
Notifications
You must be signed in to change notification settings - Fork 715
Expand file tree
/
Copy pathdecoder.rs
More file actions
3157 lines (2850 loc) · 121 KB
/
Copy pathdecoder.rs
File metadata and controls
3157 lines (2850 loc) · 121 KB
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 crate::io::DecoderPreparedImage;
use crate::utils::vec_try_with_capacity;
use std::cmp::{self, Ordering};
use std::io::{self, BufRead, Seek, SeekFrom};
use std::iter::{repeat, Rev};
use std::slice::ChunksExactMut;
use std::{error, fmt};
use crate::color::ColorType;
use crate::error::{
DecodingError, ImageError, ImageResult, UnsupportedError, UnsupportedErrorKind,
};
use crate::io::{image_reader_type::SpecCompliance, DecodedImageAttributes};
use crate::{ImageDecoder, ImageFormat};
const BITMAPCOREHEADER_SIZE: u32 = 12;
const BITMAPINFOHEADER_SIZE: u32 = 40;
const BITMAPV2HEADER_SIZE: u32 = 52;
const BITMAPV3HEADER_SIZE: u32 = 56;
const BITMAPV4HEADER_SIZE: u32 = 108;
const BITMAPV5HEADER_SIZE: u32 = 124;
const FILE_HEADER_SIZE: u64 = 14;
const OS2_V2_MAX_HEADER_SIZE: u32 = 64;
const OS2_V2_MIN_HEADER_SIZE: u32 = 16;
// Compression method constants
const BI_RGB: u32 = 0;
const BI_RLE8: u32 = 1;
const BI_RLE4: u32 = 2;
const BI_BITFIELDS: u32 = 3;
const BI_JPEG: u32 = 4; // Used in legacy Windows pass-through printing path (not supported) and for RLE24
const BI_PNG: u32 = 5; // Used in legacy Windows pass-through printing path - not supported
const BI_ALPHABITFIELDS: u32 = 6;
const BI_CMYK: u32 = 11;
const BI_CMYKRLE8: u32 = 12;
const BI_CMYKRLE4: u32 = 13;
static R5_G5_B5_COLOR_MASK: Bitfields = Bitfields {
r: Bitfield::from_len_shift(5, 10),
g: Bitfield::from_len_shift(5, 5),
b: Bitfield::from_len_shift(5, 0),
a: Bitfield::from_len_shift(0, 0),
};
const R8_G8_B8_COLOR_MASK: Bitfields = Bitfields {
r: Bitfield::from_len_shift(8, 24),
g: Bitfield::from_len_shift(8, 16),
b: Bitfield::from_len_shift(8, 8),
a: Bitfield::from_len_shift(0, 0),
};
const R8_G8_B8_A8_COLOR_MASK: Bitfields = Bitfields {
r: Bitfield::from_len_shift(8, 16),
g: Bitfield::from_len_shift(8, 8),
b: Bitfield::from_len_shift(8, 0),
a: Bitfield::from_len_shift(8, 24),
};
const RLE_ESCAPE: u8 = 0;
const RLE_ESCAPE_EOL: u8 = 0;
const RLE_ESCAPE_EOF: u8 = 1;
const RLE_ESCAPE_DELTA: u8 = 2;
/// Opaque alpha channel value (fully opaque)
const ALPHA_OPAQUE: u8 = 0xFF;
/// The maximum width/height the decoder will process.
const MAX_WIDTH_HEIGHT: i32 = 0xFFFF;
/// The value of the V5 header field indicating an embedded ICC profile.
const PROFILE_EMBEDDED: u32 = u32::from_be_bytes(*b"MBED");
// BMP color space type constants (bV4CSType / bV5CSType).
const LCS_CALIBRATED_RGB: u32 = 0x00000000;
const LCS_SRGB: u32 = u32::from_be_bytes(*b"sRGB");
const LCS_WINDOWS_COLOR_SPACE: u32 = u32::from_be_bytes(*b"Win ");
/// During progressive decoding, the decoder applies transforms (e.g. a vertical
/// flip for bottom-up BMP files) as it writes rows into the output buffer.
/// This enum describes which rows contain valid pixel data by indicating the
/// transform that was applied.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RowsDecoded {
/// Rows were decoded sequentially from the top of the image.
TopDown {
/// Number of top rows decoded so far.
rows: u32,
},
/// Rows were decoded from the bottom of the image (vertical flip).
BottomUp {
/// Number of bottom rows decoded so far.
rows: u32,
},
}
impl RowsDecoded {
/// Returns the number of decoded rows.
#[inline]
pub fn rows(&self) -> u32 {
match *self {
RowsDecoded::TopDown { rows } | RowsDecoded::BottomUp { rows } => rows,
}
}
}
/// Parsed BITMAPCOREHEADER fields (excludes 4-byte size field).
struct ParsedCoreHeader {
width: i32,
height: i32,
bit_count: u16,
image_type: ImageType,
}
impl ParsedCoreHeader {
/// Parse BITMAPCOREHEADER fields from an 8-byte buffer.
fn parse(buffer: &[u8; 8], spec_strictness: SpecCompliance) -> ImageResult<Self> {
let width = i32::from(u16::from_le_bytes(buffer[0..2].try_into().unwrap()));
let height = i32::from(u16::from_le_bytes(buffer[2..4].try_into().unwrap()));
let planes = u16::from_le_bytes(buffer[4..6].try_into().unwrap());
if spec_strictness == SpecCompliance::Strict && planes != 1 {
return Err(DecoderError::MoreThanOnePlane.into());
}
let bit_count = u16::from_le_bytes(buffer[6..8].try_into().unwrap());
let image_type = match bit_count {
1 | 4 | 8 => ImageType::Palette,
24 => ImageType::RGB24,
_ => {
return Err(
DecoderError::InvalidChannelWidth(ChannelWidthError::Rgb, bit_count).into(),
)
}
};
Ok(ParsedCoreHeader {
width,
height,
bit_count,
image_type,
})
}
}
/// Parsed BITMAPINFOHEADER fields (excludes 4-byte size field).
struct ParsedInfoHeader {
width: i32,
height: i32,
top_down: bool,
bit_count: u16,
compression: u32,
colors_used: u32,
}
impl ParsedInfoHeader {
/// Parse BITMAPINFOHEADER fields from a 36-byte buffer.
fn parse(buffer: &[u8; 36], spec_strictness: SpecCompliance) -> ImageResult<Self> {
let width = i32::from_le_bytes(buffer[0..4].try_into().unwrap());
let mut height = i32::from_le_bytes(buffer[4..8].try_into().unwrap());
// Width cannot be negative
if width < 0 {
return Err(DecoderError::NegativeWidth(width).into());
} else if width > MAX_WIDTH_HEIGHT || height > MAX_WIDTH_HEIGHT {
return Err(DecoderError::ImageTooLarge(width, height).into());
}
if height == i32::MIN {
return Err(DecoderError::InvalidHeight.into());
}
// A negative height indicates a top-down DIB
let top_down = if height < 0 {
height = -height;
true
} else {
false
};
let planes = u16::from_le_bytes(buffer[8..10].try_into().unwrap());
if spec_strictness == SpecCompliance::Strict && planes != 1 {
return Err(DecoderError::MoreThanOnePlane.into());
}
let bit_count = u16::from_le_bytes(buffer[10..12].try_into().unwrap());
let compression = u32::from_le_bytes(buffer[12..16].try_into().unwrap());
// Top-down DIBs cannot be compressed (per BMP specification).
// In lenient mode, we allow this for compatibility with other decoders.
if spec_strictness == SpecCompliance::Strict
&& top_down
&& compression != BI_RGB
&& compression != BI_BITFIELDS
&& compression != BI_ALPHABITFIELDS
{
return Err(DecoderError::ImageTypeInvalidForTopDown(compression).into());
}
// Skip size_image (16-19), x_pix_permeter (20-23), y_pix_permeter (24-27)
let colors_used = u32::from_le_bytes(buffer[28..32].try_into().unwrap());
// Skip important_colors (32-35)
Ok(ParsedInfoHeader {
width,
height,
top_down,
bit_count,
compression,
colors_used,
})
}
}
/// Parsed bitfield masks from DIB header.
struct ParsedBitfields {
r_mask: u32,
g_mask: u32,
b_mask: u32,
a_mask: u32,
}
impl ParsedBitfields {
/// Parse bitfield masks from buffer.
/// Caller must ensure buffer has sufficient length; this method does not validate.
/// Note: Caller must ensure buffer has 12 (V2/Core) or 16 (V3/V4/V5) bytes length; this method does not validate.
#[track_caller]
fn parse(buffer: &[u8], has_alpha: bool) -> Self {
let r_mask = u32::from_le_bytes(buffer[0..4].try_into().unwrap());
let g_mask = u32::from_le_bytes(buffer[4..8].try_into().unwrap());
let b_mask = u32::from_le_bytes(buffer[8..12].try_into().unwrap());
let a_mask = if has_alpha {
u32::from_le_bytes(buffer[12..16].try_into().unwrap())
} else {
0
};
ParsedBitfields {
r_mask,
g_mask,
b_mask,
a_mask,
}
}
}
/// Parsed ICC profile metadata from V5 header.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ParsedIccProfile {
/// Absolute file offset where the ICC profile data starts.
profile_offset: u64,
profile_size: u32,
}
impl ParsedIccProfile {
/// Parse ICC profile metadata from V5 header buffer.
/// Returns None if no embedded ICC profile is present.
/// Note: Caller must ensure buffer has 116 bytes length; this method does not validate.
#[track_caller]
fn parse(buffer: &[u8], bmp_header_offset: u64) -> Option<Self> {
// bV5CSType is at offset 56 from header start, which is offset 52 from after the size field
let cs_type = u32::from_le_bytes(buffer[52..56].try_into().unwrap());
// Only embedded profiles are supported
if cs_type != PROFILE_EMBEDDED {
return None;
}
// bV5ProfileData is at offset 112 from header start, which is offset 108 from after size field
let profile_offset_from_header = u32::from_le_bytes(buffer[108..112].try_into().unwrap());
// bV5ProfileSize is at offset 116 from header start, which is offset 112 from after size field
let profile_size = u32::from_le_bytes(buffer[112..116].try_into().unwrap());
if profile_size == 0 || profile_offset_from_header == 0 {
return None;
}
// Compute the absolute file offset by adding the header's position to the relative offset
let profile_offset = bmp_header_offset + u64::from(profile_offset_from_header);
Some(ParsedIccProfile {
profile_offset,
profile_size,
})
}
}
/// Color space data parsed from V4/V5 BMP headers.
#[derive(Debug, Clone)]
enum ColorSpaceInfo {
/// LCS_CALIBRATED_RGB: endpoint and gamma values specified in the header.
CalibratedRgb(CalibratedRgb),
/// LCS_sRGB or LCS_WINDOWS_COLOR_SPACE: sRGB color space.
Srgb,
/// PROFILE_EMBEDDED: ICC profile data embedded in the file.
EmbeddedIcc(ParsedIccProfile),
}
impl ColorSpaceInfo {
/// Parse color space information from a V4/V5 header buffer.
/// The buffer should start after the 4-byte size field.
/// Note: Caller must ensure buffer has at least 104 bytes (V4 header minus size field);
/// this method does not validate.
#[track_caller]
fn parse(buffer: &[u8], bmp_header_size: u32, bmp_header_offset: u64) -> Option<Self> {
// bV4CSType at offset 56 from header start = offset 52 from after size field.
let cs_type = u32::from_le_bytes(buffer[52..56].try_into().unwrap());
match cs_type {
LCS_CALIBRATED_RGB => {
let read_u32 = |offset: usize| -> u32 {
u32::from_le_bytes(buffer[offset..offset + 4].try_into().unwrap())
};
// FXPT2DOT30 (2.30 fixed-point) → f32.
let fxpt2dot30 = |val: u32| -> f32 { val as f32 * (1.0 / (1u64 << 30) as f32) };
// FXPT16DOT16 (16.16 fixed-point) → f32.
let fxpt16dot16 = |val: u32| -> f32 { val as f32 / 65536.0 };
// CIEXYZTRIPLE: 9 FXPT2DOT30 values at offsets 60-95 from header
// start (56-91 from after size field). Layout:
// RedX, RedY, RedZ, GreenX, GreenY, GreenZ, BlueX, BlueY, BlueZ
// We read only X and Y per primary (Z is implicit: Z = 1 - X - Y
// for chromaticity, but BMP stores raw CIE XYZ values).
let rx = fxpt2dot30(read_u32(56));
let ry = fxpt2dot30(read_u32(60));
let gx = fxpt2dot30(read_u32(68));
let gy = fxpt2dot30(read_u32(72));
let bx = fxpt2dot30(read_u32(80));
let by = fxpt2dot30(read_u32(84));
// Gamma values at offsets 96-107 from header start (92-103 from after size).
let gamma_r = fxpt16dot16(read_u32(92));
let gamma_g = fxpt16dot16(read_u32(96));
let gamma_b = fxpt16dot16(read_u32(100));
// Validate: Y values must be non-zero (used as denominators in
// XYZ→chromaticity conversion by color management libraries).
if ry == 0.0 || gy == 0.0 || by == 0.0 {
return None;
}
Some(ColorSpaceInfo::CalibratedRgb(CalibratedRgb {
rx,
ry,
gx,
gy,
bx,
by,
gamma_r,
gamma_g,
gamma_b,
}))
}
LCS_SRGB | LCS_WINDOWS_COLOR_SPACE => Some(ColorSpaceInfo::Srgb),
PROFILE_EMBEDDED if bmp_header_size >= BITMAPV5HEADER_SIZE => {
ParsedIccProfile::parse(buffer, bmp_header_offset).map(ColorSpaceInfo::EmbeddedIcc)
}
_ => None,
}
}
}
/// Calibrated RGB color space parameters from a BMP V4/V5 header.
///
/// When the header's `bV4CSType` is `LCS_CALIBRATED_RGB`, these fields
/// carry the CIE XYZ endpoint coordinates for the RGB primaries and
/// per-channel gamma values, parsed from the FXPT2DOT30 / FXPT16DOT16
/// fixed-point fields in the header.
#[derive(Debug, Clone, Copy, PartialEq)]
struct CalibratedRgb {
/// Red primary CIE X coordinate (FXPT2DOT30).
rx: f32,
/// Red primary CIE Y coordinate (FXPT2DOT30).
ry: f32,
/// Green primary CIE X coordinate (FXPT2DOT30).
gx: f32,
/// Green primary CIE Y coordinate (FXPT2DOT30).
gy: f32,
/// Blue primary CIE X coordinate (FXPT2DOT30).
bx: f32,
/// Blue primary CIE Y coordinate (FXPT2DOT30).
by: f32,
/// Red channel gamma (FXPT16DOT16).
gamma_r: f32,
/// Green channel gamma (FXPT16DOT16).
gamma_g: f32,
/// Blue channel gamma (FXPT16DOT16).
gamma_b: f32,
}
impl CalibratedRgb {
/// Build a moxcms `ColorProfile` from the calibrated RGB primaries and gamma.
fn to_color_profile(self) -> moxcms::ColorProfile {
let primaries = moxcms::ColorPrimaries {
red: moxcms::Chromaticity::new(self.rx, self.ry),
green: moxcms::Chromaticity::new(self.gx, self.gy),
blue: moxcms::Chromaticity::new(self.bx, self.by),
};
let mut profile = moxcms::ColorProfile::new_srgb();
profile.update_rgb_colorimetry(moxcms::WHITE_POINT_D65, primaries);
// Clear inherited CICP metadata from the sRGB base profile.
profile.cicp = None;
// Use gamma directly as the TRC exponent via a parametric curve
// (ICC type 0: Y = X^gamma). This preserves full s15Fixed16 precision
// when serialised to ICC bytes.
let safe_gamma = |g: f32| if g > 0.0 { g } else { 1.0 };
let parametric_trc = |g: f32| moxcms::ToneReprCurve::Parametric(vec![safe_gamma(g)]);
profile.red_trc = Some(parametric_trc(self.gamma_r));
profile.green_trc = Some(parametric_trc(self.gamma_g));
profile.blue_trc = Some(parametric_trc(self.gamma_b));
profile
}
}
#[derive(PartialEq, Copy, Clone)]
enum ImageType {
Palette,
RGB16,
RGB24,
RGB32,
RGBA32,
RLE8,
RLE4,
RLE24,
Bitfields16,
Bitfields32,
}
/// Progress within the metadata reading phase.
///
/// The metadata is split into phases:
/// 1. Headers: File header, DIB header, and bitmasks (~30-150 bytes total).
/// These are always re-read together on retry since they're small.
/// 2. Optional data: Palette (up to 1KB) and ICC profile (variable, can be several KB).
/// These are tracked separately since they can be larger.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum MetadataProgress {
/// Initial state, nothing read yet.
#[default]
NotStarted,
/// Reading main headers (file header, DIB header, bitmasks).
/// Stores the start offset for seeking on retry.
ReadingMainHeader { start_offset: u64 },
/// Headers have been read; now reading palette.
/// Stores header offsets for subsequent phases.
ReadingPalette { offsets: HeaderOffsets },
/// Headers and palette (if any) have been read; now reading ICC profile.
/// Stores header offsets for the ICC profile read.
ReadingIccProfile { offsets: HeaderOffsets },
/// All metadata has been read successfully.
Complete,
}
/// Offsets and sizes discovered during header parsing.
/// Carried through metadata phases to avoid redundant state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct HeaderOffsets {
/// Absolute file offset where the DIB header ends (before any extra
/// bitmask bytes or palette). This is the minimum valid data_offset.
bmp_header_end: u64,
/// Offset where palette data starts (after headers).
palette_offset: u64,
/// ICC profile metadata if present.
icc_profile: Option<ParsedIccProfile>,
}
/// Progress within the RLE decoding phase.
///
/// RLE decoding checkpoints at row boundaries (after EndOfRow markers) and
/// after Delta instructions to avoid quadratic time with malformed files.
/// On UnexpectedEof, decoding resumes from the last stored checkpoint.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
enum RleProgress {
/// Not started yet.
#[default]
NotStarted,
/// Checkpoint at position (row, x) with stream at stream_pos.
/// On resume, decoding continues from this exact pixel position.
Checkpoint { row: u32, x: u32, stream_pos: u64 },
}
/// Decoder state for resumable decoding.
///
/// This allows the decoder to recover from `UnexpectedEof` errors.
/// Decoding can resume from the last successfully decoded row or RLE symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DecoderState {
/// Currently reading metadata (headers, palette, ICC profile).
ReadingMetadata { progress: MetadataProgress },
/// Currently reading row-based (non-RLE) image data.
/// Stores the number of rows successfully decoded.
ReadingRowData { rows_decoded: u32 },
/// Currently reading RLE-compressed data.
/// Tracks progress at symbol boundaries for resumability.
ReadingRleData { progress: RleProgress },
/// Image data has been fully decoded.
ImageDecoded,
}
impl Default for DecoderState {
fn default() -> Self {
DecoderState::ReadingMetadata {
progress: MetadataProgress::default(),
}
}
}
#[derive(PartialEq)]
enum BMPHeaderType {
Core,
Info,
V2,
V3,
V4,
V5,
Os2V2,
}
#[derive(PartialEq)]
enum FormatFullBytes {
RGB24,
RGB32,
RGBA32,
Format888,
}
/// Compression type for bitfield-based formats.
#[derive(PartialEq, Copy, Clone)]
enum BitfieldCompression {
/// BI_BITFIELDS: RGB masks only (3 masks, 12 bytes after header).
Rgb,
/// BI_ALPHABITFIELDS: RGBA masks (4 masks, 16 bytes after header).
Rgba,
}
enum Chunker<'a> {
FromTop(ChunksExactMut<'a, u8>),
FromBottom(Rev<ChunksExactMut<'a, u8>>),
}
pub(crate) struct RowIterator<'a> {
chunks: Chunker<'a>,
}
impl<'a> Iterator for RowIterator<'a> {
type Item = &'a mut [u8];
#[inline(always)]
fn next(&mut self) -> Option<&'a mut [u8]> {
match self.chunks {
Chunker::FromTop(ref mut chunks) => chunks.next(),
Chunker::FromBottom(ref mut chunks) => chunks.next(),
}
}
}
/// All errors that can occur when attempting to parse a BMP
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
enum DecoderError {
/// The bitfield mask interleaves set and unset bits
BitfieldMaskNonContiguous,
/// Bitfield mask invalid (e.g. too long for specified type)
BitfieldMaskInvalid,
/// Bitfield (of the specified width – 16- or 32-bit) mask not present
BitfieldMaskMissing(u32),
/// Bitfield (of the specified width – 16- or 32-bit) masks not present
BitfieldMasksMissing(u32),
/// BMP's "BM" signature wrong or missing
BmpSignatureInvalid,
/// More than the exactly one allowed plane specified by the format
MoreThanOnePlane,
/// Invalid amount of bits per channel for the specified image type
InvalidChannelWidth(ChannelWidthError, u16),
/// The width is negative
NegativeWidth(i32),
/// One of the dimensions is larger than a soft limit
ImageTooLarge(i32, i32),
/// The height is `i32::min_value()`
///
/// General negative heights specify top-down DIBs
InvalidHeight,
/// Specified image type is invalid for top-down BMPs (i.e. is compressed)
ImageTypeInvalidForTopDown(u32),
/// Image type not currently recognized by the decoder
ImageTypeUnknown(u32),
/// Bitmap header smaller than the core header
HeaderTooSmall(u32),
/// The palette is bigger than allowed by the bit count of the BMP
PaletteSizeExceeded { colors_used: u32, bit_count: u16 },
/// read_image_data was called before read_metadata completed
MetadataNotRead,
/// Corrupt RLE data
CorruptRleData,
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DecoderError::CorruptRleData => f.write_str("Corrupt RLE data"),
DecoderError::BitfieldMaskNonContiguous => f.write_str("Non-contiguous bitfield mask"),
DecoderError::BitfieldMaskInvalid => f.write_str("Invalid bitfield mask"),
DecoderError::BitfieldMaskMissing(bb) => {
f.write_fmt(format_args!("Missing {bb}-bit bitfield mask"))
}
DecoderError::BitfieldMasksMissing(bb) => {
f.write_fmt(format_args!("Missing {bb}-bit bitfield masks"))
}
DecoderError::BmpSignatureInvalid => f.write_str("BMP signature not found"),
DecoderError::MoreThanOnePlane => f.write_str("More than one plane"),
DecoderError::InvalidChannelWidth(tp, n) => {
f.write_fmt(format_args!("Invalid channel bit count for {tp}: {n}"))
}
DecoderError::NegativeWidth(w) => f.write_fmt(format_args!("Negative width ({w})")),
DecoderError::ImageTooLarge(w, h) => f.write_fmt(format_args!(
"Image too large (one of ({w}, {h}) > soft limit of {MAX_WIDTH_HEIGHT})"
)),
DecoderError::InvalidHeight => f.write_str("Invalid height"),
DecoderError::ImageTypeInvalidForTopDown(tp) => f.write_fmt(format_args!(
"Invalid image type {tp} for top-down image."
)),
DecoderError::ImageTypeUnknown(tp) => {
f.write_fmt(format_args!("Unknown image compression type {tp}"))
}
DecoderError::HeaderTooSmall(s) => {
f.write_fmt(format_args!("Bitmap header too small ({s} bytes)"))
}
DecoderError::PaletteSizeExceeded {
colors_used,
bit_count,
} => f.write_fmt(format_args!(
"Palette size {colors_used} exceeds maximum size for BMP with bit count of {bit_count}"
)),
DecoderError::MetadataNotRead => {
f.write_str("read_image_data called before read_metadata completed")
}
}
}
}
impl From<DecoderError> for ImageError {
fn from(e: DecoderError) -> ImageError {
ImageError::Decoding(DecodingError::new(ImageFormat::Bmp.into(), e))
}
}
impl error::Error for DecoderError {}
/// Distinct image types whose saved channel width can be invalid
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
enum ChannelWidthError {
/// RGB
Rgb,
/// 8-bit run length encoding
Rle8,
/// 4-bit run length encoding
Rle4,
/// 24-bit run length encoding (OS/2)
Rle24,
/// Bitfields (16- or 32-bit)
Bitfields,
}
impl fmt::Display for ChannelWidthError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
ChannelWidthError::Rgb => "RGB",
ChannelWidthError::Rle8 => "RLE8",
ChannelWidthError::Rle4 => "RLE4",
ChannelWidthError::Rle24 => "RLE24",
ChannelWidthError::Bitfields => "bitfields",
})
}
}
/// BMP rows must be padded to a multiple of 4 bytes.
#[inline]
fn calculate_row_padding(bytes_per_row: usize) -> usize {
(4 - (bytes_per_row % 4)) % 4
}
/// Allocate a row buffer with OOM protection.
fn allocate_row_buffer(size: usize) -> ImageResult<Vec<u8>> {
let mut buffer = vec_try_with_capacity(size).map_err(|_| {
ImageError::Unsupported(UnsupportedError::from_format_and_kind(
ImageFormat::Bmp.into(),
UnsupportedErrorKind::GenericFeature(format!(
"Row buffer allocation ({} bytes) too large",
size
)),
))
})?;
buffer.resize(size, 0);
Ok(buffer)
}
/// Checks if the current scanline is the last one or not. If it is not the
/// last one, it performs a normal read. Otherwise, the special case applies:
/// Apparently many BMPs are missing the final byte at the end of the file.
/// This function checks if the stream is exactly one byte short of the
/// required final scanline length. If so, it reads the available bytes and
/// explicitly zeroes the missing trailing byte. Otherwise, it performs a normal `read_exact`.
fn read_scanline(
reader: &mut (impl io::Read + Seek),
buf: &mut [u8],
current_file_row: &mut u32,
last_row: u32,
spec_strictness: SpecCompliance,
) -> io::Result<()> {
let is_last_row = *current_file_row == last_row;
*current_file_row += 1;
if is_last_row && spec_strictness == SpecCompliance::Lenient {
let current_pos = reader.stream_position()?;
let end_pos = reader.seek(SeekFrom::End(0))?;
reader.seek(SeekFrom::Start(current_pos))?;
let Some((last, head)) = buf.split_last_mut() else {
// Empty row, nothing to read.
return Ok(());
};
if Ok(head.len()) == usize::try_from(end_pos - current_pos) {
reader.read_exact(head)?;
*last = b'\0';
return Ok(());
}
}
reader.read_exact(buf)
}
/// Convenience function to check if the combination of width, length and number of
/// channels would result in a buffer that would overflow.
fn check_for_overflow(width: i32, length: i32, channels: usize) -> ImageResult<()> {
num_bytes(width, length, channels)
.map(|_| ())
.ok_or_else(|| {
ImageError::Unsupported(UnsupportedError::from_format_and_kind(
ImageFormat::Bmp.into(),
UnsupportedErrorKind::GenericFeature(format!(
"Image dimensions ({width}x{length} w/{channels} channels) are too large"
)),
))
})
}
/// Calculate how many many bytes a buffer holding a decoded image with these properties would
/// require. Returns `None` if the buffer size would overflow or if one of the sizes are negative.
fn num_bytes(width: i32, length: i32, channels: usize) -> Option<usize> {
if width <= 0 || length <= 0 {
None
} else {
match channels.checked_mul(width as usize) {
Some(n) => n.checked_mul(length as usize),
None => None,
}
}
}
/// Process rows with resumability support.
///
/// Calls `func` for each row from `start_row` to `height`, passing the output row slice.
/// On success, returns the total number of rows (height).
/// On error, returns the number of rows successfully completed before the error.
///
/// The caller is responsible for seeking to the correct file position before calling.
fn with_rows_resumable<F>(
buffer: &mut [u8],
width: i32,
height: i32,
channels: usize,
top_down: bool,
start_row: u32,
mut func: F,
) -> Result<u32, (u32, io::Error)>
where
F: FnMut(&mut [u8]) -> io::Result<()>,
{
// An overflow should already have been checked for when this is called,
// though we check anyhow, as it somehow seems to increase performance slightly.
let row_width = channels.checked_mul(width as usize).unwrap();
let height = height as u32;
/// Get the index of a row in the output buffer given the file row index.
/// For top-down images, row 0 in the file is row 0 in the buffer.
/// For bottom-up images, row 0 in the file is the last row in the buffer.
#[inline]
fn output_row_index(file_row: u32, height: u32, top_down: bool) -> usize {
if top_down {
file_row as usize
} else {
(height - 1 - file_row) as usize
}
}
/// Get a mutable reference to a specific row in the output buffer.
#[inline]
fn get_row_mut(buf: &mut [u8], row_index: usize, row_stride: usize) -> &mut [u8] {
let start = row_index * row_stride;
&mut buf[start..][..row_stride]
}
for file_row in start_row..height {
let out_row_idx = output_row_index(file_row, height, top_down);
let row = get_row_mut(buffer, out_row_idx, row_width);
if let Err(e) = func(row) {
return Err((file_row, e));
}
}
Ok(height)
}
fn set_8bit_pixel_run<'a, T: Iterator<Item = &'a u8>>(
pixel_iter: &mut ChunksExactMut<u8>,
palette: &[[u8; 3]],
indices: T,
n_pixels: usize,
) -> bool {
for idx in indices.take(n_pixels) {
if let Some(pixel) = pixel_iter.next() {
let rgb = palette[*idx as usize];
pixel[0] = rgb[0];
pixel[1] = rgb[1];
pixel[2] = rgb[2];
} else {
return false;
}
}
true
}
fn set_4bit_pixel_run<'a, T: Iterator<Item = &'a u8>>(
pixel_iter: &mut ChunksExactMut<u8>,
palette: &[[u8; 3]],
indices: T,
mut n_pixels: usize,
) -> bool {
for idx in indices {
macro_rules! set_pixel {
($i:expr) => {
if n_pixels == 0 {
break;
}
if let Some(pixel) = pixel_iter.next() {
let rgb = palette[$i as usize];
pixel[0] = rgb[0];
pixel[1] = rgb[1];
pixel[2] = rgb[2];
} else {
return false;
}
n_pixels -= 1;
};
}
set_pixel!(idx >> 4);
set_pixel!(idx & 0xf);
}
true
}
#[rustfmt::skip]
fn set_2bit_pixel_run<'a, T: Iterator<Item = &'a u8>>(
pixel_iter: &mut ChunksExactMut<u8>,
palette: &[[u8; 3]],
indices: T,
mut n_pixels: usize,
) -> bool {
for idx in indices {
macro_rules! set_pixel {
($i:expr) => {
if n_pixels == 0 {
break;
}
if let Some(pixel) = pixel_iter.next() {
let rgb = palette[$i as usize];
pixel[0] = rgb[0];
pixel[1] = rgb[1];
pixel[2] = rgb[2];
} else {
return false;
}
n_pixels -= 1;
};
}
set_pixel!((idx >> 6) & 0x3u8);
set_pixel!((idx >> 4) & 0x3u8);
set_pixel!((idx >> 2) & 0x3u8);
set_pixel!( idx & 0x3u8);
}
true
}
fn set_1bit_pixel_run<'a, T: Iterator<Item = &'a u8>>(
pixel_iter: &mut ChunksExactMut<u8>,
palette: &[[u8; 3]],
indices: T,
) {
for idx in indices {
let mut bit = 0x80;
loop {
if let Some(pixel) = pixel_iter.next() {
let rgb = palette[usize::from((idx & bit) != 0)];
pixel[0] = rgb[0];
pixel[1] = rgb[1];
pixel[2] = rgb[2];
} else {
return;
}
bit >>= 1;
if bit == 0 {
break;
}
}
}
}
#[derive(PartialEq, Eq)]
struct Bitfield {
shift: u32,
len: u32,
factor_addend: (u32, u32),
}
impl Bitfield {
/// Factors and addends such that `((data * factor + addend) >> 8) as u8`
/// maps the `data` value to the nearest value in the full 0-255 range.
///
/// All constants come from the following site and were adjusted to use a
/// shift of 8: https://rundevelopment.github.io/blog/fast-unorm-conversions#constants
const FACTOR_ADDEND: [(u32, u32); 8] = [
(0x01_00, 0), // len=8: round(x * 255 / 255) = (x * 256 + 0) >> 8
(0xff_00, 0), // len=1: round(x * 255 / 1) = (x * 65280 + 0) >> 8
(0x55_00, 0), // len=2: round(x * 255 / 3) = (x * 21760 + 0) >> 8
(0x24_80, 0), // len=3: round(x * 255 / 7) = (x * 9344 + 0) >> 8
(0x11_00, 0), // len=4: round(x * 255 / 15) = (x * 4352 + 0) >> 8
(0x08_3c, 0x5C), // len=5: round(x * 255 / 31) = (x * 2108 + 92) >> 8
(0x04_0c, 0x84), // len=6: round(x * 255 / 63) = (x * 1036 + 132) >> 8
(0x02_04, 0), // len=7: round(x * 255 / 127) = (x * 516 + 0) >> 8
];
const fn from_len_shift(len: u32, shift: u32) -> Self {
debug_assert!(len <= 8);
debug_assert!(shift + len <= 32);
Bitfield {
shift,
len,
factor_addend: Self::FACTOR_ADDEND[(len % 8) as usize],
}
}
fn from_mask(mask: u32, max_len: u32) -> ImageResult<Bitfield> {
if mask == 0 {
return Ok(Bitfield::from_len_shift(0, 0));
}
let mut shift = mask.trailing_zeros();
let mut len = (!(mask >> shift)).trailing_zeros();
if len != mask.count_ones() {
return Err(DecoderError::BitfieldMaskNonContiguous.into());
}
if len + shift > max_len {
return Err(DecoderError::BitfieldMaskInvalid.into());
}
if len > 8 {
shift += len - 8;
len = 8;
}
Ok(Bitfield::from_len_shift(len, shift))
}
#[inline]
fn read(&self, data: u32) -> u8 {
debug_assert!(self.len <= 8);
// This performs branch-less UNORM conversion using the multiply-add
// method. See `FACTOR_ADDEND` above for more information.
let (factor, addend) = self.factor_addend;
let mask = (1 << self.len) - 1;
let data = (data >> self.shift) & mask;
((data * factor + addend) >> 8) as u8
}
}
#[derive(PartialEq, Eq)]
struct Bitfields {
r: Bitfield,
g: Bitfield,
b: Bitfield,
a: Bitfield,
}