Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M11: JBIG2 symbol coding: tests for tall marks, the other corner and the symbol caps

Grzegorz Martens8eeafe330975
diff --git a/crates/filters/README.md b/crates/filters/README.md
index 5df0761eb..cf8ebb655 100644
--- a/crates/filters/README.md
+++ b/crates/filters/README.md
@@ -54,7 +54,7 @@ encode_jbig2_generic(data, columns, rows) -> Result<Vec<u8>, FilterError> // t
- `ccitt.rs`: Group 4 output decoded by `hayro-ccitt` (dev-dependency, an independent decoder) matches the input bits: a text-like page, padding bits, the widest row, and property tests over bitmaps of noise and of runs; any input returns rather than panics.
- `mq.rs`: the arithmetic coder reproduces Annex H.2's 30 bytes from its 256 decisions.
- `jbig2.rs`: output decoded by `hayro-jbig2` (dev-dependency, an independent decoder) matches the input bits: a text-like page (smaller than Group 4), edges, padding, all-white and all-black regions (typical rows), and property tests over bitmaps of noise and of runs; any input returns rather than panics.
-- `jbig2/symbols.rs`: the integer coders against Annex A's example and Table A.1; symbol-coded output decoded by `hayro-jbig2` matches the input bits for every plan and strip size: text whose letters repeat (under half the generic coding's size, the dictionary retained and referred to), large and lone marks left to a generic region, marks on the edges, touching at corners and inside each other's boxes, and property tests over glyphs scattered over each other and the edges with stray pixels (never larger than the generic coding); one shape, a blank page and noise are coded generically; marks joined at a corner are one mark, and 256 pixels a side is a symbol while 257 is left out; black padding bits are ignored; coordinates past 4,435 use Annex A's 32-bit range and PREV stays below 512; past 2^20 runs or 2^24 rows the image is coded generically; any input returns rather than panics.
+- `jbig2/symbols.rs`: the integer coders against Annex A's example and Table A.1; symbol-coded output decoded by `hayro-jbig2` matches the input bits for every plan and strip size: text whose letters repeat (under half the generic coding's size, the dictionary retained and referred to), large and lone marks left to a generic region, marks on the edges, touching at corners and inside each other's boxes, and property tests over glyphs scattered over each other and the edges with stray pixels (never larger than the generic coding); one shape, a blank page and noise are coded generically; marks joined at a corner, either way, are one mark, and 256 pixels a side is a symbol while 257 wide or tall is left out; black padding bits are ignored; coordinates past 4,435 use Annex A's 32-bit range and PREV stays below 512; past 2^20 runs, 2^24 rows, 65,536 symbols or 2^24 symbol pixels the image is coded generically, and at each cap it is not; any input returns rather than panics.
- `fuzz/`: a detached cargo-fuzz crate (`cargo +nightly fuzz run decode`, run from `crates/filters/`).
## Status
diff --git a/crates/filters/src/jbig2/symbols.rs b/crates/filters/src/jbig2/symbols.rs
index 48013e986..e4c79bc58 100644
--- a/crates/filters/src/jbig2/symbols.rs
+++ b/crates/filters/src/jbig2/symbols.rs
@@ -708,15 +708,20 @@ mod tests {
}
}
- /// Pixels touching only at a corner are one mark (8-connected); side by side with a white
- /// column between, two. A mark of 256 pixels a side is a symbol, one of 257 is left to the
- /// generic region. The diagonal and the dot occur twice, so both plans are made.
+ /// Pixels touching only at a corner, down to the right or down to the left, are one mark
+ /// (8-connected); side by side with a white column between, two. A mark of 256 pixels a side
+ /// is a symbol; one 257 wide, or 257 tall, is left to the generic region. The diagonal and the
+ /// dot occur twice, so both plans are made.
#[test]
fn marks_join_at_corners_and_large_ones_are_left_out() {
let mut picture = vec![vec![0u8; 300]; 300];
for i in 0..6 {
picture[10 + i][10 + i] = 1;
picture[10 + i][100 + i] = 1;
+ picture[10 + i][60 - i] = 1;
+ }
+ for row in &mut picture[0..257] {
+ row[280] = 1;
}
picture[30][10] = 1;
picture[30][12] = 1;
@@ -728,9 +733,22 @@ mod tests {
let data = samples(&picture);
let page = page(&data, 300, 300).unwrap();
let boxes: Vec<(u32, u32, u32, u32)> = page.marks.iter().map(|m| (m.x0, m.y0, m.x1 - m.x0, m.y1 - m.y0)).collect();
- assert_eq!(boxes, [(10, 10, 6, 6), (100, 10, 6, 6), (10, 30, 1, 1), (12, 30, 1, 1), (0, 40, 256, 1), (290, 44, 1, 256), (0, 60, 257, 1)]);
+ assert_eq!(
+ boxes,
+ [
+ (280, 0, 1, 257),
+ (10, 10, 6, 6),
+ (55, 10, 6, 6),
+ (100, 10, 6, 6),
+ (10, 30, 1, 1),
+ (12, 30, 1, 1),
+ (0, 40, 256, 1),
+ (290, 44, 1, 256),
+ (0, 60, 257, 1)
+ ]
+ );
let large: Vec<(u32, u32)> = page.large.iter().map(|m| (page.marks[*m as usize].x0, page.marks[*m as usize].y0)).collect();
- assert_eq!(large, [(0, 60)]);
+ assert_eq!(large, [(280, 0), (0, 60)]);
assert_eq!(every_plan_round_trips(&picture), 8);
}
@@ -748,6 +766,49 @@ mod tests {
assert!(page(&tall, 1, MAX_ROWS).is_some());
}
+ /// Past 65,536 distinct symbols, or 2^24 pixels of them, the image is left to generic coding;
+ /// at either cap it is still looked at.
+ #[test]
+ fn too_many_symbols_are_left_to_generic_coding() {
+ // `n` distinct marks of 17 × 3: full top and bottom rows joined by a code of 1 to n, in
+ // binary, on the row between.
+ let codes = |n: usize| {
+ let (columns, rows) = (256 * 18, n.div_ceil(256) * 4);
+ let mut picture = vec![vec![0u8; columns]; rows];
+ for k in 0..n {
+ let (x, y) = (k % 256 * 18, k / 256 * 4);
+ picture[y][x..x + 17].fill(1);
+ picture[y + 2][x..x + 17].fill(1);
+ for b in (0..17).filter(|b| (k + 1) >> b & 1 == 1) {
+ picture[y + 1][x + b] = 1;
+ }
+ }
+ (samples(&picture), columns as u32, rows as u32)
+ };
+ let (data, columns, rows) = codes(MAX_SYMBOLS);
+ assert_eq!(page(&data, columns, rows).map(|p| p.symbols.len()), Some(MAX_SYMBOLS));
+ let (data, columns, rows) = codes(MAX_SYMBOLS + 1);
+ assert!(page(&data, columns, rows).is_none());
+ // `n` black squares of 256 × 256, each with a white pixel in a different place: 2^16
+ // pixels a symbol, so 256 of them are exactly the cap.
+ let squares = |n: usize| {
+ let (columns, rows) = (16 * 258, n.div_ceil(16) * 258);
+ let mut picture = vec![vec![0u8; columns]; rows];
+ for k in 0..n {
+ let (x, y) = (k % 16 * 258, k / 16 * 258);
+ for row in &mut picture[y..y + 256] {
+ row[x..x + 256].fill(1);
+ }
+ picture[y + 1 + k / 254][x + 1 + k % 254] = 0;
+ }
+ (samples(&picture), columns as u32, rows as u32)
+ };
+ let (data, columns, rows) = squares(256);
+ assert_eq!(page(&data, columns, rows).map(|p| p.symbols.len()), Some(256));
+ let (data, columns, rows) = squares(257);
+ assert!(page(&data, columns, rows).is_none());
+ }
+
/// A page of text whose letters repeat exactly, as rendered text does, keeps each letter once:
/// a symbol dictionary and a text region, much smaller than the generic coding.
#[test]
@@ -798,7 +859,7 @@ mod tests {
for (x, y) in [(10, 5), (28, 14), (12, 14)] {
draw(&mut picture, &ell, x, y);
}
- // Corners touching: one mark.
+ // Corners touching: one mark (`marks_join_at_corners_and_large_ones_are_left_out` checks it).
picture[3][6] = 1;
picture[4][7] = 1;
picture[5][8] = 1;
diff --git a/crates/optimize/README.md b/crates/optimize/README.md
index 97915f8d8..8648e39d8 100644
--- a/crates/optimize/README.md
+++ b/crates/optimize/README.md
@@ -41,8 +41,9 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
its catalog) when that is smaller as stored. JBIG2 stores each distinct mark once, as a
symbol, when the image's marks repeat exactly, as rendered text's do: on six pages of
300 dpi text that came to 28% of a generic region's size and 17% of Group 4's. On scans,
- whose copies of a letter are seldom identical, it is nearly always a generic region: 27–33%
- smaller than Group 4 on the same pages with scan-like noise added. It is lossless: the
+ whose copies of a letter are seldom identical, symbols gain little: on the same pages with 2%
+ or more of the letters' edge pixels flipped at random, at most 8% below a generic region,
+ which was 27–33% below Group 4. It is lossless: the
samples decode to the same bits, so the colour space, decode array and masks stay. Group 4
wins on scans, whose ragged edges defeat Flate; on clean computer-drawn 1-bit art Flate can
be smaller, and the image then stays. Not yet:
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index e801495fd..2a83a68ed 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -7385,7 +7385,7 @@ status = "partial"
commands = ["optimize.advanced", "optimize.reduce"]
tools = ["doc_optimize", "doc_reduce"]
evidence = ["crates/filters/src/ccitt.rs::bitmaps_round_trip", "crates/filters/src/ccitt.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/ccitt.rs::what_it_cannot_encode_is_an_error", "crates/filters/src/mq.rs::the_annex_h_test_sequence_encodes_to_its_bytes", "crates/filters/src/jbig2.rs::bitmaps_round_trip", "crates/filters/src/jbig2.rs::a_page_of_text_like_marks_round_trips_and_shrinks", "crates/filters/src/jbig2/symbols.rs::repeated_marks_are_stored_once", "crates/filters/src/jbig2/symbols.rs::scattered_marks_round_trip", "crates/optimize/tests/optimize.rs::black_and_white_images_become_jbig2", "crates/optimize/tests/optimize.rs::rendered_text_becomes_jbig2_symbols", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_jbig2", "crates/optimize/tests/optimize.rs::black_and_white_images_become_ccitt_group_4", "crates/automation/tests/it/automation.rs::doc_optimize_stores_black_and_white_images_as_ccitt_group_4", "crates/ui-egui/tests/it/create.rs::the_pdf_optimizer_dialog_saves_an_optimized_copy"]
-notes = "CCITT Group 4 (the default, so Reduce File Size does it too) or JBIG2, both lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. JBIG2 stores each distinct mark once in a symbol dictionary and places its exact copies with a text region, larger and lone marks in a generic region (template 0, typical prediction), or the whole image as a generic region, whichever is smaller: on rendered 300 dpi text 28% of the generic region's size and 17% of Group 4's; on scans, whose copies of a letter are seldom identical, nearly always the generic region (27–33% smaller than Group 4 on the same pages with scan-like noise added). A document below PDF 1.4 gets /Version 1.4. Not yet: JBIG2 refinement coding of near-copies (where lossless gains on scans would come from), a symbol dictionary shared between images (/JBIG2Globals), JBIG2's lossy mode, monochrome downsampling, inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples (JBIG2 takes rows of up to 1,048,576). Redaction doesn't decode JBIG2 or Group 4 yet: a mark over part of such an image removes the whole image (nothing leaks). Export reads JBIG2, but nothing that exports an image reads Group 4 yet: Export ▸ Images and Save Image As refuse it, Copy Image fails, and Word, PowerPoint and HTML export leave the picture out."
+notes = "CCITT Group 4 (the default, so Reduce File Size does it too) or JBIG2, both lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (doc_optimize mono) stores a 1-bit image of one colour component (grey, indexed, a separation) or an image mask, kept with no filter or general-purpose ones, as Group 4 when that is smaller as stored; the samples decode to the same bits, so colour space, decode array and masks stay. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. JBIG2 stores each distinct mark once in a symbol dictionary and places its exact copies with a text region, larger and lone marks in a generic region (template 0, typical prediction), or the whole image as a generic region, whichever is smaller: on rendered 300 dpi text 28% of the generic region's size and 17% of Group 4's; on scans, whose copies of a letter are seldom identical, little: on the same pages with 2% or more of the letters' edge pixels flipped at random, at most 8% below the generic region, which was 27–33% below Group 4. A document below PDF 1.4 gets /Version 1.4. Not yet: JBIG2 refinement coding of near-copies (where lossless gains on scans would come from), a symbol dictionary shared between images (/JBIG2Globals), JBIG2's lossy mode, monochrome downsampling, inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples (JBIG2 takes rows of up to 1,048,576). Redaction doesn't decode JBIG2 or Group 4 yet: a mark over part of such an image removes the whole image (nothing leaks). Export reads JBIG2, but nothing that exports an image reads Group 4 yet: Export ▸ Images and Save Image As refuse it, Copy Image fails, and Word, PowerPoint and HTML export leave the picture out."
[[feature]]
id = "optimize.only-if-smaller"