PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M11: JBIG2 alone isn't decoded for Group 4 unless it is resampled
Grzegorz Martens7d422a099851
diff --git a/crates/optimize/README.md b/crates/optimize/README.mdindex ee4216a14..27cada0d2 100644--- a/crates/optimize/README.md+++ b/crates/optimize/README.md@@ -78,12 +78,12 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going600 ppi page of text that is averaged, Group 4 at 300 ppi is about half the size.- **Compression:** CCITT Group 4 (`pdfcraft_filters::encode_g4`), or 1-bit Flate when that issmaller, which only a resampled image or one packed from more bits may be: a 1-bit image that- is only stored again becomes Group 4 or stays. Group 4 alone is only decoded to be resampled;+ is only stored again becomes Group 4 or stays. Group 4 alone is only decoded to be resampled, and so is JBIG2 alone when Group 4 is asked for;Group 3, or Group 4 inside another filter such as `ASCII85Decode`, is stored again as Group 4alone when that is smaller. Damaged Group 3 with end-of-line codes is stored as the decoderrecovers it, a bad row picked up again at the next code, as it reports no damage there; without- them, damage stops the decoding and the image is left alone. JBIG2, alone or inside another- filter, is stored again as the compression asks when that is smaller (as JBIG2 symbols where+ them, damage stops the decoding and the image is left alone. JBIG2 inside another filter, or+ alone when JBIG2 is asked for, is stored again as the compression asks when that is smaller (as JBIG2 symbols whereits own coding is a generic region, say); a symbol-coded scan, averaged, loses its exactrepeats and often comes out larger, and then stays as it is. A JBIG2 image stored again refers to no`/JBIG2Globals`, and one whose page isn't its size (PdfCraft'sdiff --git a/crates/optimize/src/images.rs b/crates/optimize/src/images.rsindex e0b0fb635..cdd3c89d9 100644--- a/crates/optimize/src/images.rs+++ b/crates/optimize/src/images.rs@@ -463,7 +463,7 @@ fn is_dct(s: &Stream) -> Option<bool> {#[cfg(test)]thread_local! {- /// Pixels decoded from JPEG data, for the test that keeps a mismatched JPEG from decoding.+ /// Pixels decoded, for the tests that keep an image from being decoded for nothing.static DECODED_PIXELS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };}@@ -819,6 +819,7 @@ fn one_bit(doc: &Document, s: &Stream, pack: bool, defaults: bool) -> Option<(Ve// A JBIG2 page, which has to be the image's size, is `len` bytes as rows of a bit._ => allowance(len, h)?,};+ count_decoded(u64::from(w) * u64::from(h));let mut data = doc.decoded_image_within(s, max).ok()?;if data.len() < len {return None;@@ -1079,8 +1080,8 @@ fn downsample_bits_checked(data: &[u8], w: u32, h: u32, nw: u32, nh: u32, dark_i/// - **Stored** as CCITT Group 4 with `CcittG4`, or JBIG2 with `Jbig2`, or as 1-bit Flate when that/// is smaller, which only a resampled image or one packed from more bits may be: a 1-bit image/// that is only stored again becomes Group 4 or JBIG2, or stays. Group 4 alone is only decoded-/// to be resampled; Group 3, Group 4 inside another filter, and JBIG2 are stored again like any-/// other. With `Retain`, a resampled image keeps its kind of compression (CCITT, JBIG2, or+/// to be resampled, and so is JBIG2 alone when Group 4 is asked for; Group 3, Group 4 inside+/// another filter, and JBIG2 otherwise are stored again like any other. With `Retain`, a resampled image keeps its kind of compression (CCITT, JBIG2, or/// Flate), and nothing else changes: an image of more bits stays as it is, for the grey or/// colour settings. A JBIG2 image stored again refers to no `/JBIG2Globals`.///@@ -1095,10 +1096,12 @@ fn mono(doc: &Document, s: &Stream, ppi: f64, defaults: bool, settings: &MonoSet// Its kind of compression, which Retain keeps, behind any other filters.let ccitt = fax.is_some();let jbig2 = matches!(s.filters().last(), Some((pdfcraft_filters::Filter::Jbig2, _)));- // Group 4 alone is only worth decoding to resample it. Group 3, Group 4 behind ASCII85Decode,- // say, and JBIG2 (whose symbols may be smaller than its own coding) can be smaller stored- // again alone.- let only_to_resample = retain || (fax.is_some_and(|p| p.k < 0) && s.filters().len() == 1 && settings.compression == MonoCompression::CcittG4);+ // Group 4 alone is only worth decoding to resample it, and so is JBIG2 alone when Group 4 is what+ // it would be stored as: that output is rarely smaller, and decoding an ordinary scan costs a+ // quarter of a second a page. Group 3, Group 4 behind ASCII85Decode, say, and JBIG2 stored as+ // JBIG2 (whose symbols may be smaller than its own coding) can be smaller stored again alone.+ let alone_to_g4 = s.filters().len() == 1 && settings.compression == MonoCompression::CcittG4;+ let only_to_resample = retain || (alone_to_g4 && (jbig2 || fax.is_some_and(|p| p.k < 0)));if only_to_resample && !downsample {return None;}@@ -1307,6 +1310,36 @@ mod dimension_tests {}/// A JPEG larger than its dictionary says is refused from its header, before its pixels are decoded.+ /// JBIG2 alone, with Group 4 asked for, is decoded only to be resampled. A cost guard: dropped,+ /// no output changes, and an ordinary scan pays a quarter of a second a page for nothing. Behind+ /// another filter it can still be stored again, as Group 4 can.+ #[test]+ fn a_jbig2_image_alone_is_not_decoded_for_group_4_unless_it_is_resampled() {+ let coded = pdfcraft_filters::encode_jbig2_generic(&[0xFF; 4], 16, 2).unwrap();+ let hex: Vec<u8> = coded.iter().flat_map(|b| format!("{b:02x}").into_bytes()).chain(*b">").collect();+ let image = |filter: Object, data: Vec<u8>| {+ let mut dict = Dict::new();+ dict.set(b"Width".to_vec(), Object::Int(16));+ dict.set(b"Height".to_vec(), Object::Int(2));+ dict.set(b"BitsPerComponent".to_vec(), Object::Int(1));+ dict.set(b"ColorSpace".to_vec(), Object::name("DeviceGray"));+ dict.set(b"Filter".to_vec(), filter);+ Stream::from_raw(dict, data)+ };+ let settings = MonoSettings { compression: MonoCompression::CcittG4, ..MonoSettings::REDUCE };+ let decoded = |s: &Stream, settings: &MonoSettings| {+ DECODED_PIXELS.with(|c| c.set(0));+ mono(&Document::new_empty(), s, 300.0, false, settings);+ DECODED_PIXELS.with(|c| c.get())+ };+ let alone = image(Object::name("JBIG2Decode"), coded.clone());+ assert_eq!(decoded(&alone, &settings), 0, "alone, for Group 4, below the threshold");+ let behind = image(Object::Array(vec![Object::name("ASCIIHexDecode"), Object::name("JBIG2Decode")]), hex);+ assert!(decoded(&behind, &settings) > 0, "behind another filter it can be stored again");+ let jbig2 = MonoSettings { compression: MonoCompression::Jbig2, ..MonoSettings::REDUCE };+ assert!(decoded(&alone, &jbig2) > 0, "stored as JBIG2 its symbols may come out smaller");+ }+#[test]fn a_jpeg_of_another_size_than_its_dictionary_is_not_decoded() {let data = jpeg(&vec![128; 1000 * 1000], 1, 1000, 1000, 50).unwrap_or_default();