pdfcer_image_codec/jbig2/generic.rs
1//! JBIG2 generic-region encoder: template 0, TPGDON, nominal AT pixels,
2//! wrapped as a PDF-embedded segment stream (ITU-T T.88 §6.2.5, §7.2,
3//! §7.4.6, §7.4.8, Annex D.3).
4//!
5//! Spec source: `filters/filter__jbig2_generic_encoder.md` §3 and §6 in
6//! the PDF-spec RAG.
7
8use super::mq::MqEncoder;
9
10/// The 16-bit context of Figure 8, under this module's bit ordering
11/// (RAG §3.5). SLTP is coded in the same bin as a pixel with this
12/// neighbourhood: one 65536-entry context array serves both.
13const SLTP_CONTEXT: usize = 0x9B25;
14
15/// Encodes 1-bit samples as a lossless JBIG2 generic region.
16///
17/// `samples` holds `height` rows of `width` pixels, one bit per pixel,
18/// MSB first, each row padded to a whole byte (the PDF image sample
19/// layout, ISO 32000-2 §8.9.3). Bits past the end of `samples` read as 0.
20///
21/// The output is a complete `/JBIG2Decode` stream in the embedded
22/// organisation (T.88 Annex D.3): a page-information segment for a
23/// `width` x `height` page, then one immediate lossless generic-region
24/// segment covering it (template 0, typical prediction on, nominal AT
25/// pixels, MQ coding). It needs no `/JBIG2Globals`, so no
26/// `/DecodeParms`. A PDF sample 1 is coded as a JBIG2 0 (white), so the
27/// decoded samples equal `samples` and the image keeps its `/Decode`.
28/// The image needs `/BitsPerComponent 1` and `/Width` and `/Height`
29/// equal to `width` and `height`, and must be an XObject: §7.4.7 does
30/// not allow the filter on an inline image.
31///
32/// # Examples
33///
34/// ```
35/// use pdfcer_image_codec::jbig2::encode_generic;
36///
37/// let stream = encode_generic(&[0xFF, 0x00], 8, 2);
38/// // Segment 0 is the page information, type 48.
39/// assert_eq!(&stream[..5], &[0, 0, 0, 0, 48]);
40/// assert!(stream.ends_with(&[0xFF, 0xAC]));
41/// ```
42#[must_use]
43pub fn encode_generic(samples: &[u8], width: u32, height: u32) -> Vec<u8> {
44 let data = code_region(samples, width, height);
45 let mut out = Vec::with_capacity(data.len() + 56);
46 // Page information (§7.4.8): segment 0, type 48, page 1, 19 bytes.
47 segment_header(&mut out, 0, 48, 19);
48 region_info(&mut out, width, height);
49 // Page flags: eventually lossless; default pixel 0; OR combination.
50 out.push(0x01);
51 // Page striping: none.
52 out.extend_from_slice(&[0, 0]);
53 // Immediate lossless generic region (§7.4.6.1): segment 1, type 39.
54 let length = u32::try_from(data.len() + 26).unwrap_or(u32::MAX);
55 segment_header(&mut out, 1, 39, length);
56 region_info(&mut out, width, height);
57 // Region flags: external combination operator OR.
58 out.push(0x00);
59 // Generic flags: MMR 0, template 0, TPGDON 1.
60 out.push(0x08);
61 // The nominal AT pixels A1-A4 (§6.2.5.4, Table 5).
62 out.extend_from_slice(&[0x03, 0xFF, 0xFD, 0xFF, 0x02, 0xFE, 0xFE, 0xFE]);
63 out.extend_from_slice(&data);
64 out
65}
66
67/// A short-form segment header (§7.2): number, type, no referred-to
68/// segments, page association 1, data length.
69fn segment_header(out: &mut Vec<u8>, number: u32, kind: u8, length: u32) {
70 out.extend_from_slice(&number.to_be_bytes());
71 out.extend_from_slice(&[kind, 0x00, 0x01]);
72 out.extend_from_slice(&length.to_be_bytes());
73}
74
75/// Width, height, and X and Y location 0 (§7.4.1 and §7.4.8 share it).
76fn region_info(out: &mut Vec<u8>, width: u32, height: u32) {
77 out.extend_from_slice(&width.to_be_bytes());
78 out.extend_from_slice(&height.to_be_bytes());
79 out.extend_from_slice(&[0; 8]);
80}
81
82/// The MQ-coded region data, ending with the `0xFF 0xAC` marker.
83fn code_region(samples: &[u8], width: u32, height: u32) -> Vec<u8> {
84 let w = width as usize;
85 let stride = w.div_ceil(8);
86 let zero = vec![0u8; w];
87 let mut mq = MqEncoder::new(1 << 16);
88 let (mut above2, mut above) = (zero.clone(), zero);
89 let mut ltp = false;
90 for y in 0..height as usize {
91 let row = unpack(
92 samples.get(y.saturating_mul(stride)..).unwrap_or_default(),
93 w,
94 );
95 // TPGD (§6.2.5.7, encoder side per RAG §3.4).
96 let sltp = (row == above) != ltp;
97 mq.encode(SLTP_CONTEXT, sltp);
98 ltp ^= sltp;
99 if !ltp {
100 code_row(&mut mq, &above2, &above, &row);
101 }
102 above2 = std::mem::replace(&mut above, row);
103 }
104 mq.finish()
105}
106
107/// JBIG2 pixels of one row: 1 is black, a PDF sample 0.
108fn unpack(line: &[u8], width: usize) -> Vec<u8> {
109 (0..width)
110 .map(|x| {
111 let byte = line.get(x / 8).copied().unwrap_or(0);
112 1 - ((byte >> (7 - x % 8)) & 1)
113 })
114 .collect()
115}
116
117/// Codes every pixel of `row` with the template 0 context (Figure 3,
118/// RAG §3.5): bits 15-11 are row -2 at x-2..=x+2 (A4, three fixed, A3),
119/// bits 10-4 row -1 at x-3..=x+3 (A2, five fixed, A1), bits 3-0 row 0 at
120/// x-4..=x-1. Pixels outside the bitmap are 0 (§6.2.5.2).
121fn code_row(mq: &mut MqEncoder, above2: &[u8], above: &[u8], row: &[u8]) {
122 let at = |r: &[u8], x: usize, plus: usize| -> usize {
123 x.checked_add(plus)
124 .and_then(|i| i.checked_sub(4))
125 .and_then(|i| r.get(i))
126 .map_or(0, |&p| usize::from(p))
127 };
128 // Windows primed for x = 0: what sits left of x+3 (row -2), x+4
129 // (row -1) and x (row 0), offset by 4 so the arithmetic stays unsigned.
130 let mut w2 = (0..4).fold(0, |w, i| (w << 1) | at(above2, 0, i + 2));
131 let mut w1 = (0..6).fold(0, |w, i| (w << 1) | at(above, 0, i + 1));
132 let mut w0 = 0;
133 for (x, &pixel) in row.iter().enumerate() {
134 w2 = ((w2 << 1) | at(above2, x, 6)) & 0x1F;
135 w1 = ((w1 << 1) | at(above, x, 7)) & 0x7F;
136 mq.encode((w2 << 11) | (w1 << 4) | w0, pixel == 1);
137 w0 = ((w0 << 1) | usize::from(pixel)) & 0x0F;
138 }
139}