pdfluent-jbig2 0.2.0

A memory-safe, pure-Rust JBIG2 decoder.
Documentation
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
/*!
A memory-safe, pure-Rust JBIG2 decoder.

`hayro-jbig2` decodes JBIG2 images as specified in ITU-T T.88 (also known as
ISO/IEC 14492). JBIG2 is a bi-level image compression standard commonly used
in PDF documents for compressing scanned text documents.

The crate is `no_std` compatible but requires an allocator to be available.

# Safety
This crate forbids unsafe code via a crate-level attribute.
*/

#![cfg_attr(not(feature = "std"), no_std)]
#![forbid(unsafe_code)]
#![allow(missing_docs)]

extern crate alloc;

use alloc::vec::Vec;

/// A decoder for JBIG2 images.
pub trait Decoder {
    /// Push a single pixel to the output.
    fn push_pixel(&mut self, black: bool);
    /// Push multiple chunks of 8 pixels of the same color.
    ///
    /// The `chunk_count` parameter indicates how many 8-pixel chunks to push.
    /// For example, if this method is called with `white = true` and
    /// `chunk_count = 10`, 80 white pixels are pushed (10 × 8 = 80).
    ///
    /// You can assume that this method is only called if the number of already
    /// pushed pixels is a multiple of 8 (i.e. byte-aligned).
    fn push_pixel_chunk(&mut self, black: bool, chunk_count: u32);
    /// Called when a row has been completed.
    fn next_line(&mut self);
}

mod arithmetic_decoder;
mod bitmap;
mod decode;
mod error;
mod file;
mod gray_scale;
mod huffman_table;
mod integer_decoder;
mod lazy;
mod page_info;
mod reader;
mod segment;
mod symbol_id_decoder;

use error::bail;
pub use error::{
    DecodeError, FormatError, HuffmanError, ParseError, RegionError, Result, SegmentError,
    SymbolError, TemplateError,
};

use crate::file::parse_segments_sequential;
use bitmap::Bitmap;
use decode::CombinationOperator;
use decode::generic;
use decode::generic_refinement;
use decode::halftone;
use decode::pattern;
use decode::pattern::PatternDictionary;
use decode::symbol;
use decode::symbol::SymbolDictionary;
use decode::text;
use file::parse_file;
use huffman_table::{HuffmanTable, StandardHuffmanTables};
use page_info::{PageInformation, parse_page_information};
use reader::Reader;
use segment::SegmentType;

/// A decoded JBIG2 image.
#[derive(Debug, Clone)]
pub struct Image {
    /// The width of the image in pixels.
    pub width: u32,
    /// The height of the image in pixels.
    pub height: u32,
    /// Number of u32 words per row.
    stride: u32,
    /// The packed pixel data.
    data: Vec<u32>,
}

impl Image {
    /// Decode the image data into the decoder.
    pub fn decode<D: Decoder>(&self, decoder: &mut D) {
        let bytes_per_row = self.width.div_ceil(8) as usize;

        for row in self.data.chunks_exact(self.stride as usize) {
            let mut x = 0_u32;
            let mut chunk_byte: Option<u8> = None;
            let mut chunk_count = 0_u32;

            let bytes = row.iter().flat_map(|w| w.to_be_bytes()).take(bytes_per_row);

            for byte in bytes {
                let remaining = self.width - x;

                if remaining >= 8 && (byte == 0x00 || byte == 0xFF) {
                    // Continue the previous chunk.
                    if chunk_byte == Some(byte) {
                        chunk_count += 1;
                        x += 8;
                        continue;
                    }

                    // Flush previous chunk if any, then start new one.
                    if let Some(b) = chunk_byte {
                        decoder.push_pixel_chunk(b == 0xFF, chunk_count);
                    }

                    chunk_byte = Some(byte);
                    chunk_count = 1;
                    x += 8;

                    continue;
                }

                // Can't continue/start chunk, flush any existing chunk first.
                if let Some(b) = chunk_byte.take() {
                    decoder.push_pixel_chunk(b == 0xFF, chunk_count);
                    chunk_count = 0;
                }

                // Emit individual pixels.
                let count = remaining.min(8);
                for i in 0..count {
                    decoder.push_pixel((byte >> (7 - i)) & 1 != 0);
                }
                x += count;
            }

            // Flush any remaining chunk at end of row.
            if let Some(b) = chunk_byte {
                decoder.push_pixel_chunk(b == 0xFF, chunk_count);
            }

            decoder.next_line();
        }
    }
}

/// Decode a JBIG2 file from the given data.
///
/// The file is expected to use the sequential or random-access organization,
/// as defined in Annex D.1 and D.2.
pub fn decode(data: &[u8]) -> Result<Image> {
    let file = parse_file(data)?;
    decode_with_segments(&file.segments)
}

/// Decode an embedded JBIG2 image. with the given global segments.
///
/// The file is expected to use the embedded organization defined in
/// Annex D.3.
pub fn decode_embedded(data: &[u8], globals: Option<&[u8]>) -> Result<Image> {
    let mut segments = Vec::new();
    if let Some(globals_data) = globals {
        let mut reader = Reader::new(globals_data);
        parse_segments_sequential(&mut reader, &mut segments)?;
    };

    let mut reader = Reader::new(data);
    parse_segments_sequential(&mut reader, &mut segments)?;

    segments.sort_by_key(|seg| seg.header.segment_number);

    decode_with_segments(&segments)
}

fn decode_with_segments(segments: &[segment::Segment<'_>]) -> Result<Image> {
    // Pre-scan for stripe height from EndOfStripe segments.
    let height_from_stripes = segments
        .iter()
        .filter(|seg| seg.header.segment_type == SegmentType::EndOfStripe)
        .filter_map(|seg| u32::from_be_bytes(seg.data.try_into().ok()?).checked_add(1))
        .max();

    // Find and parse page information segment first.
    let (mut ctx, mut page_bitmap) = if let Some(page_info) = segments
        .iter()
        .find(|s| s.header.segment_type == SegmentType::PageInformation)
    {
        let mut reader = Reader::new(page_info.data);
        get_ctx(&mut reader, height_from_stripes)?
    } else {
        bail!(FormatError::MissingPageInfo);
    };

    // Process all segments.
    for seg in segments {
        let mut reader = Reader::new(seg.data);

        match seg.header.segment_type {
            SegmentType::PageInformation => {
                // Already processed above, skip.
            }
            SegmentType::ImmediateGenericRegion | SegmentType::ImmediateLosslessGenericRegion => {
                let had_unknown_length = seg.header.data_length.is_none();
                let header = generic::parse(&mut reader, had_unknown_length)?;

                if ctx.can_decode_directly(&page_bitmap, &header.region_info, false) {
                    generic::decode_into(&header, &mut page_bitmap)?;
                } else {
                    let region = generic::decode(&header)?;
                    page_bitmap.combine(
                        &region.bitmap,
                        region.bitmap.x_location as i32,
                        region.bitmap.y_location as i32,
                        region.combination_operator,
                    );
                }
                ctx.page_pristine = false;
            }
            SegmentType::IntermediateGenericRegion => {
                // Intermediate segments cannot have unknown length.
                let header = generic::parse(&mut reader, false)?;
                let region = generic::decode(&header)?;
                ctx.store_region(seg.header.segment_number, region.bitmap);
            }
            SegmentType::PatternDictionary => {
                let header = pattern::parse(&mut reader)?;
                let dictionary = pattern::decode(&header)?;
                ctx.store_pattern_dictionary(seg.header.segment_number, dictionary);
            }
            SegmentType::SymbolDictionary => {
                // "1) Concatenate all the input symbol dictionaries to form SDINSYMS."
                // (6.5.5, step 1)
                // Collect references to avoid cloning; symbols are only cloned if re-exported.
                let input_symbols: Vec<&Bitmap> = seg
                    .header
                    .referred_to_segments
                    .iter()
                    .filter_map(|&num| ctx.get_symbol_dictionary(num))
                    .flat_map(|dict| dict.exported_symbols.iter())
                    .collect();

                // Collect Huffman tables from referred table segments.
                let referred_tables: Vec<HuffmanTable> = seg
                    .header
                    .referred_to_segments
                    .iter()
                    .filter_map(|&num| ctx.get_huffman_table(num))
                    .cloned()
                    .collect();

                // Get retained contexts from the last referred symbol dictionary (7.4.2.2 step 3).
                let retained_contexts = seg
                    .header
                    .referred_to_segments
                    .last()
                    .and_then(|&num| ctx.get_symbol_dictionary(num))
                    .and_then(|dict| dict.retained_contexts.as_ref());

                let header = symbol::parse(&mut reader)?;
                let dictionary = symbol::decode(
                    &header,
                    &input_symbols,
                    &referred_tables,
                    &ctx.standard_tables,
                    retained_contexts,
                )?;
                ctx.store_symbol_dictionary(seg.header.segment_number, dictionary);
            }
            SegmentType::ImmediateTextRegion | SegmentType::ImmediateLosslessTextRegion => {
                // Collect symbols from referred symbol dictionaries (SBSYMS).
                let symbols: Vec<&Bitmap> = seg
                    .header
                    .referred_to_segments
                    .iter()
                    .filter_map(|&num| ctx.get_symbol_dictionary(num))
                    .flat_map(|dict| dict.exported_symbols.iter())
                    .collect();

                // Collect Huffman tables from referred table segments.
                // "These user-supplied Huffman decoding tables may be supplied either
                // as a Tables segment..." (7.4.3.1.6)
                let referred_tables: Vec<HuffmanTable> = seg
                    .header
                    .referred_to_segments
                    .iter()
                    .filter_map(|&num| ctx.get_huffman_table(num))
                    .cloned()
                    .collect();

                let header = text::parse(&mut reader, symbols.len() as u32)?;

                if ctx.can_decode_directly(
                    &page_bitmap,
                    &header.region_info,
                    header.flags.default_pixel,
                ) {
                    text::decode_into(
                        &header,
                        &symbols,
                        &referred_tables,
                        &ctx.standard_tables,
                        &mut page_bitmap,
                    )?;
                } else {
                    let region =
                        text::decode(&header, &symbols, &referred_tables, &ctx.standard_tables)?;
                    page_bitmap.combine(
                        &region.bitmap,
                        region.bitmap.x_location as i32,
                        region.bitmap.y_location as i32,
                        region.combination_operator,
                    );
                }
                ctx.page_pristine = false;
            }
            SegmentType::IntermediateTextRegion => {
                // Collect symbols from referred symbol dictionaries (SBSYMS).
                let symbols: Vec<&Bitmap> = seg
                    .header
                    .referred_to_segments
                    .iter()
                    .filter_map(|&num| ctx.get_symbol_dictionary(num))
                    .flat_map(|dict| dict.exported_symbols.iter())
                    .collect();

                // Collect Huffman tables from referred table segments.
                let referred_tables: Vec<HuffmanTable> = seg
                    .header
                    .referred_to_segments
                    .iter()
                    .filter_map(|&num| ctx.get_huffman_table(num))
                    .cloned()
                    .collect();

                let header = text::parse(&mut reader, symbols.len() as u32)?;
                let region =
                    text::decode(&header, &symbols, &referred_tables, &ctx.standard_tables)?;
                ctx.store_region(seg.header.segment_number, region.bitmap);
            }
            SegmentType::ImmediateHalftoneRegion | SegmentType::ImmediateLosslessHalftoneRegion => {
                let pattern_dict = seg
                    .header
                    .referred_to_segments
                    .first()
                    .and_then(|&num| ctx.get_pattern_dictionary(num))
                    .ok_or(SegmentError::MissingPatternDictionary)?;

                let header = halftone::parse(&mut reader)?;

                if ctx.can_decode_directly(
                    &page_bitmap,
                    &header.region_info,
                    header.flags.initial_pixel_color,
                ) {
                    halftone::decode_into(&header, pattern_dict, &mut page_bitmap)?;
                } else {
                    let region = halftone::decode(&header, pattern_dict)?;
                    page_bitmap.combine(
                        &region.bitmap,
                        region.bitmap.x_location as i32,
                        region.bitmap.y_location as i32,
                        region.combination_operator,
                    );
                }
                ctx.page_pristine = false;
            }
            SegmentType::IntermediateHalftoneRegion => {
                let pattern_dict = seg
                    .header
                    .referred_to_segments
                    .first()
                    .and_then(|&num| ctx.get_pattern_dictionary(num))
                    .ok_or(SegmentError::MissingPatternDictionary)?;

                let header = halftone::parse(&mut reader)?;
                let region = halftone::decode(&header, pattern_dict)?;
                ctx.store_region(seg.header.segment_number, region.bitmap);
            }
            SegmentType::IntermediateGenericRefinementRegion => {
                // Same logic as immediate refinement, but store result instead of combining.
                let reference = seg
                    .header
                    .referred_to_segments
                    .first()
                    .and_then(|&num| ctx.get_referred_segment(num))
                    .unwrap_or(&page_bitmap);

                let header = generic_refinement::parse(&mut reader)?;
                let region = generic_refinement::decode(&header, reference)?;
                ctx.store_region(seg.header.segment_number, region.bitmap);
            }
            SegmentType::ImmediateGenericRefinementRegion
            | SegmentType::ImmediateLosslessGenericRefinementRegion => {
                // "3) Determine the buffer associated with the region segment that
                // this segment refers to." (7.4.7.5)
                //
                // "2) If there are no referred-to segments, then use the page
                // bitmap as the reference buffer." (7.4.7.5)
                let referred_segment = seg
                    .header
                    .referred_to_segments
                    .first()
                    .and_then(|&num| ctx.get_referred_segment(num));

                let header = generic_refinement::parse(&mut reader)?;

                if let Some(referred_segment) = referred_segment
                    && ctx.can_decode_directly(&page_bitmap, &header.region_info, false)
                {
                    generic_refinement::decode_into(&header, referred_segment, &mut page_bitmap)?;
                } else {
                    let reference = referred_segment.unwrap_or(&page_bitmap);
                    let region = generic_refinement::decode(&header, reference)?;
                    page_bitmap.combine(
                        &region.bitmap,
                        region.bitmap.x_location as i32,
                        region.bitmap.y_location as i32,
                        region.combination_operator,
                    );
                }
                ctx.page_pristine = false;
            }
            SegmentType::Tables => {
                // "Tables – see 7.4.13." (type 53)
                // "This segment contains data which defines one or more user-supplied
                // Huffman coding tables." (7.4.13)
                let table = HuffmanTable::read_custom(&mut reader)?;
                ctx.store_huffman_table(seg.header.segment_number, table);
            }
            SegmentType::EndOfPage | SegmentType::EndOfFile => {
                break;
            }
            // Other segment types not yet implemented.
            _ => {}
        }
    }

    Ok(Image {
        width: page_bitmap.width,
        height: page_bitmap.height,
        stride: page_bitmap.stride,
        data: page_bitmap.data,
    })
}

/// Decoding context for a JBIG2 page.
///
/// This holds the page information and the page bitmap that regions are
/// decoded into.
pub(crate) struct DecodeContext {
    /// The parsed page information.
    pub(crate) page_info: PageInformation,
    /// Whether the page bitmap is still in its initial state (not yet painted to).
    pub(crate) page_pristine: bool,
    /// Decoded intermediate regions, stored as (`segment_number`, region) pairs.
    pub(crate) referred_segments: Vec<(u32, Bitmap)>,
    /// Decoded pattern dictionaries, stored as (`segment_number`, dictionary) pairs.
    pub(crate) pattern_dictionaries: Vec<(u32, PatternDictionary)>,
    /// Decoded symbol dictionaries, stored as (`segment_number`, dictionary) pairs.
    pub(crate) symbol_dictionaries: Vec<(u32, SymbolDictionary)>,
    /// Decoded Huffman tables from table segments, stored as (`segment_number`, table) pairs.
    /// "Tables – see 7.4.13." (type 53)
    pub(crate) huffman_tables: Vec<(u32, HuffmanTable)>,
    /// Standard Huffman tables (`TABLE_A` through `TABLE_O`).
    pub(crate) standard_tables: StandardHuffmanTables,
}

impl DecodeContext {
    /// Check if an immediate region can be decoded directly into the page bitmap.
    fn can_decode_directly(
        &self,
        page_bitmap: &Bitmap,
        region_info: &decode::RegionSegmentInfo,
        region_default_pixel: bool,
    ) -> bool {
        if !self.page_pristine {
            return false;
        }

        let covers_page = region_info.x_location == 0
            && region_info.y_location == 0
            && region_info.width == page_bitmap.width
            && region_info.height == page_bitmap.height;

        if !covers_page {
            return false;
        }

        let page_default_is_zero = self.page_info.flags.default_pixel == 0;

        if region_default_pixel == page_default_is_zero {
            return false;
        }

        let op = region_info.combination_operator;
        match op {
            CombinationOperator::Replace => true,
            CombinationOperator::Or | CombinationOperator::Xor => page_default_is_zero,
            CombinationOperator::And | CombinationOperator::Xnor => !page_default_is_zero,
        }
    }

    /// Store a decoded region for later reference.
    fn store_region(&mut self, segment_number: u32, region: Bitmap) {
        self.referred_segments.push((segment_number, region));
    }

    /// Look up a referred segment by number.
    fn get_referred_segment(&self, segment_number: u32) -> Option<&Bitmap> {
        self.referred_segments
            .binary_search_by_key(&segment_number, |(num, _)| *num)
            .ok()
            .map(|idx| &self.referred_segments[idx].1)
    }

    /// Store a decoded pattern dictionary for later reference.
    fn store_pattern_dictionary(&mut self, segment_number: u32, dictionary: PatternDictionary) {
        self.pattern_dictionaries.push((segment_number, dictionary));
    }

    /// Look up a pattern dictionary by segment number.
    fn get_pattern_dictionary(&self, segment_number: u32) -> Option<&PatternDictionary> {
        self.pattern_dictionaries
            .binary_search_by_key(&segment_number, |(num, _)| *num)
            .ok()
            .map(|idx| &self.pattern_dictionaries[idx].1)
    }

    /// Store a decoded symbol dictionary for later reference.
    fn store_symbol_dictionary(&mut self, segment_number: u32, dictionary: SymbolDictionary) {
        self.symbol_dictionaries.push((segment_number, dictionary));
    }

    /// Look up a symbol dictionary by segment number.
    fn get_symbol_dictionary(&self, segment_number: u32) -> Option<&SymbolDictionary> {
        self.symbol_dictionaries
            .binary_search_by_key(&segment_number, |(num, _)| *num)
            .ok()
            .map(|idx| &self.symbol_dictionaries[idx].1)
    }

    /// Store a decoded Huffman table for later reference.
    fn store_huffman_table(&mut self, segment_number: u32, table: HuffmanTable) {
        self.huffman_tables.push((segment_number, table));
    }

    /// Look up a Huffman table by segment number.
    fn get_huffman_table(&self, segment_number: u32) -> Option<&HuffmanTable> {
        self.huffman_tables
            .binary_search_by_key(&segment_number, |(num, _)| *num)
            .ok()
            .map(|idx| &self.huffman_tables[idx].1)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec::Vec;

    /// A simple pixel sink that collects decoded pixels row by row.
    struct PixelSink {
        rows: Vec<Vec<bool>>,
        current: Vec<bool>,
    }

    impl PixelSink {
        fn new() -> Self {
            Self {
                rows: Vec::new(),
                current: Vec::new(),
            }
        }
    }

    impl Decoder for PixelSink {
        fn push_pixel(&mut self, black: bool) {
            self.current.push(black);
        }

        fn push_pixel_chunk(&mut self, black: bool, chunk_count: u32) {
            for _ in 0..chunk_count * 8 {
                self.current.push(black);
            }
        }

        fn next_line(&mut self) {
            self.rows.push(core::mem::take(&mut self.current));
        }
    }

    // Minimal valid sequential JBIG2 file: 4×4 all-white image using MMR encoding.
    //
    // Structure:
    //   File header (sequential, 1 page)
    //   Segment 0: PageInformation — 4×4, default pixel = white (0)
    //   Segment 1: ImmediateGenericRegion — 4×4 MMR, all-white via V(0)×4 = 0xF0
    //   Segment 2: EndOfPage
    //   Segment 3: EndOfFile
    //
    // The MMR data encodes 4 all-white rows: each row is one V(0) bit (`1`),
    // 4 bits total → 0xF0 (MSB-first). With `invert_black: true`, CCITT "white"
    // maps to JBIG2 pixel value 0 (white).
    #[rustfmt::skip]
    const MINIMAL_JBIG2: &[u8] = &[
        // File header
        0x97, 0x4A, 0x42, 0x32, 0x0D, 0x0A, 0x1A, 0x0A, // magic
        0x01,                                              // flags: sequential, page count known
        0x00, 0x00, 0x00, 0x01,                            // 1 page

        // Segment 0: PageInformation (type 48), data_length = 19 bytes
        0x00, 0x00, 0x00, 0x00,  // segment_number = 0
        0x30,                    // flags: type = 48, page_assoc 1-byte
        0x00,                    // count_and_retention = 0 (0 referred segments)
        0x01,                    // page_association = 1
        0x00, 0x00, 0x00, 0x13,  // data_length = 19
        // PageInformation data (19 bytes):
        0x00, 0x00, 0x00, 0x04,  // width  = 4
        0x00, 0x00, 0x00, 0x04,  // height = 4
        0x00, 0x00, 0x00, 0x00,  // x_resolution = unknown
        0x00, 0x00, 0x00, 0x00,  // y_resolution = unknown
        0x00,                    // flags: default_pixel = 0 (white), operator = OR
        0x00, 0x00,              // striping = 0

        // Segment 1: ImmediateGenericRegion (type 38), data_length = 19 bytes
        0x00, 0x00, 0x00, 0x01,  // segment_number = 1
        0x26,                    // flags: type = 38, page_assoc 1-byte
        0x00,                    // count_and_retention = 0
        0x01,                    // page_association = 1
        0x00, 0x00, 0x00, 0x13,  // data_length = 19
        // RegionSegmentInfo (17 bytes):
        0x00, 0x00, 0x00, 0x04,  // width       = 4
        0x00, 0x00, 0x00, 0x04,  // height      = 4
        0x00, 0x00, 0x00, 0x00,  // x_location  = 0
        0x00, 0x00, 0x00, 0x00,  // y_location  = 0
        0x04,                    // region_flags: CombinationOperator::Replace (4)
        // GenericRegion data (2 bytes):
        0x01,                    // generic_region_flags: mmr = 1
        0xF0,                    // MMR data: 4 × V(0) = `1111` → 0xF0 (4 all-white rows)

        // Segment 2: EndOfPage (type 49)
        0x00, 0x00, 0x00, 0x02,  // segment_number = 2
        0x31,                    // flags: type = 49
        0x00,                    // count_and_retention = 0
        0x01,                    // page_association = 1
        0x00, 0x00, 0x00, 0x00,  // data_length = 0

        // Segment 3: EndOfFile (type 51)
        0x00, 0x00, 0x00, 0x03,  // segment_number = 3
        0x33,                    // flags: type = 51
        0x00,                    // count_and_retention = 0
        0x00,                    // page_association = 0 (not page-specific)
        0x00, 0x00, 0x00, 0x00,  // data_length = 0
    ];

    #[test]
    fn decode_minimal_jbig2_succeeds() {
        assert!(decode(MINIMAL_JBIG2).is_ok());
    }

    #[test]
    fn decode_minimal_jbig2_dimensions() {
        let image = decode(MINIMAL_JBIG2).expect("JBIG2 should decode");
        assert_eq!(image.width, 4);
        assert_eq!(image.height, 4);
    }

    #[test]
    fn decode_minimal_jbig2_all_white() {
        let image = decode(MINIMAL_JBIG2).expect("JBIG2 should decode");
        let mut sink = PixelSink::new();
        image.decode(&mut sink);
        assert_eq!(sink.rows.len(), 4);
        for row in &sink.rows {
            assert_eq!(row.len(), 4);
            for &black in row {
                assert!(!black, "expected white (non-black) pixel");
            }
        }
    }

    #[test]
    fn decode_empty_data_returns_error() {
        assert!(decode(&[]).is_err());
    }

    #[test]
    fn decode_embedded_no_globals() {
        // Embedded JBIG2 is the same bytes but without the file header;
        // MINIMAL_JBIG2 starts with the file header, so test embedded
        // with a truncated single-segment stream produces an error gracefully.
        assert!(decode_embedded(&[], None).is_err());
    }
}

/// Create a decode context from page information segment data.
///
/// This parses the page information and creates the initial page bitmap
/// with the default pixel value.
pub(crate) fn get_ctx(
    reader: &mut Reader<'_>,
    height_from_stripes: Option<u32>,
) -> Result<(DecodeContext, Bitmap)> {
    let page_info = parse_page_information(reader)?;

    // "A page's bitmap height may be declared in its page information segment
    // to be unknown (by specifying a height of 0xFFFFFFFF). In this case, the
    // page must be striped." (7.4.8.2)
    let height = if page_info.height == 0xFFFF_FFFF {
        height_from_stripes.ok_or(FormatError::UnknownPageHeight)?
    } else {
        page_info.height
    };

    // "Bit 2: Page default pixel value. This bit contains the initial value
    // for every pixel in the page, before any region segments are decoded
    // or drawn." (7.4.8.5)
    let page_bitmap = Bitmap::new_with(
        page_info.width,
        height,
        0,
        0,
        page_info.flags.default_pixel != 0,
    );

    let ctx = DecodeContext {
        page_info,
        page_pristine: true,
        referred_segments: Vec::new(),
        pattern_dictionaries: Vec::new(),
        symbol_dictionaries: Vec::new(),
        huffman_tables: Vec::new(),
        standard_tables: StandardHuffmanTables::new(),
    };

    Ok((ctx, page_bitmap))
}