Skip to content

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

M11: eight-bit black-and-white grey takes the smaller of one bit and the grey settings

Grzegorz Martensf33227886d17
diff --git a/crates/optimize/README.md b/crates/optimize/README.md
index bfd3dad7d..518910fea 100644
--- a/crates/optimize/README.md
+++ b/crates/optimize/README.md
@@ -38,7 +38,9 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
colour component (grey, indexed, a separation) or an image mask, stored with no filter or with
general-purpose ones, is stored again as CCITT Group 4 (`pdfcraft_filters::encode_g4`) when
that is smaller as stored. An eight-bit grey image of only 0 and 255 is packed to one bit first
- (not an indexed image, whose samples are palette indices, nor one with a colour-key `/Mask`). It is lossless: the samples decode to the same bits, so the colour
+ (not an indexed image, whose samples are palette indices, nor one with a colour-key `/Mask`),
+ unless the grey settings make it smaller still, as they can a dithered scan by downsampling it
+ to JPEG. 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:
JBIG2, monochrome downsampling, inline images, soft masks and `/Mask` images, and rows wider
diff --git a/crates/optimize/src/images.rs b/crates/optimize/src/images.rs
index 08e65d037..8550affb5 100644
--- a/crates/optimize/src/images.rs
+++ b/crates/optimize/src/images.rs
@@ -635,7 +635,7 @@ fn bilevel_grey(doc: &Document, s: &Stream, compression: MonoCompression) -> Opt
let (w, h) = (usize::try_from(w).ok()?, usize::try_from(h).ok()?);
// Through its parameters given by reference too: without a PNG predictor's tag bytes taken
// off, rows of 0 and 255 would still pass below, each shifted by a byte.
- let samples = doc.with_direct_parms(s).decoded().ok()?;
+ let samples = doc.with_direct_parms(s).decoded_within(allowance(w.checked_mul(h)?, u32::try_from(h).ok()?)?).ok()?;
let samples = samples.get(..w.checked_mul(h)?)?;
let stride = w.div_ceil(8);
let mut packed = vec![0u8; stride.checked_mul(h)?];
@@ -686,16 +686,38 @@ pub(crate) fn run(
let obj = doc.get(r);
let Object::Stream(s) = &*obj else { continue };
report.images += 1;
- if let Some(new) = mono(doc, s, settings.mono).or_else(|| bilevel_grey(doc, s, settings.mono)) {
+ if let Some(new) = mono(doc, s, settings.mono) {
report.image_bytes_before += s.raw.len();
report.image_bytes_after += new.raw.len();
report.images_recompressed += 1;
doc.set(r, Object::Stream(new));
continue;
}
- let Some(n) = s.dict.get(b"ColorSpace").and_then(|cs| components(doc, cs)) else { continue };
- let st = if n == 1 { &settings.gray } else { &settings.color };
- let Some((new, smask)) = process(doc, s, ppi, st, n) else { continue };
+ let packed = bilevel_grey(doc, s, settings.mono);
+ let n = s.dict.get(b"ColorSpace").and_then(|cs| components(doc, cs));
+ let processed = n.and_then(|n| process(doc, s, ppi, if n == 1 { &settings.gray } else { &settings.color }, n));
+ // An image packed from eight bits is lossless at one bit, but the grey settings can make it
+ // smaller still (a dithered scan, downsampled and JPEG-compressed): the smaller wins,
+ // counting a soft mask resampled with it.
+ let smask_len = |smask: Option<&(ObjRef, Stream)>| match smask {
+ Some((_, m)) => Some(m.raw.len()),
+ None => s.dict.reference(b"SMask").map(|m| match &*doc.get(m) {
+ Object::Stream(m) => m.raw.len(),
+ _ => 0,
+ }),
+ };
+ let total = |new: &Stream, smask: Option<&(ObjRef, Stream)>| Some(crate::stored_len(new)?.saturating_add(smask_len(smask).unwrap_or(0)));
+ let packed_wins = packed.as_ref().is_some_and(|p| {
+ processed.as_ref().is_none_or(|(new, smask)| total(p, None).zip(total(new, smask.as_ref())).is_some_and(|(a, b)| a <= b))
+ });
+ if let Some(new) = packed.filter(|_| packed_wins) {
+ report.image_bytes_before += s.raw.len();
+ report.image_bytes_after += new.raw.len();
+ report.images_recompressed += 1;
+ doc.set(r, Object::Stream(new));
+ continue;
+ }
+ let Some((new, smask)) = processed else { continue };
let resized = new.dict.int(b"Width") != s.dict.int(b"Width") || new.dict.int(b"Height") != s.dict.int(b"Height");
report.image_bytes_before += s.raw.len();
report.image_bytes_after += new.raw.len();
diff --git a/crates/optimize/tests/optimize.rs b/crates/optimize/tests/optimize.rs
index f861da9d2..73ed54d6b 100644
--- a/crates/optimize/tests/optimize.rs
+++ b/crates/optimize/tests/optimize.rs
@@ -548,9 +548,10 @@ fn images_whose_decode_parms_are_references_come_out_as_with_them_direct() {
}
/// An image whose data decodes far past what its samples can need (a decompression bomb) is left
-/// alone rather than decoded up to the 1 GiB limit: a 1-bit one that would become Group 4, and an
-/// eight-bit one that would be resampled, each with four megabytes of zeros after its samples. Stored
-/// as ASCIIHex text under Flate, broken into lines of 64 digits, their samples aren't a bomb.
+/// alone rather than decoded up to the 1 GiB limit: a 1-bit one that would become Group 4, an
+/// eight-bit one that would be resampled, and an eight-bit one of only black and white that would
+/// be packed to one bit, each with four megabytes of zeros after its samples. Stored as ASCIIHex
+/// text under Flate, broken into lines of 64 digits, their samples aren't a bomb.
#[test]
fn images_whose_data_decodes_far_past_their_samples_are_left_alone() {
let (w, h) = (1200u32, 480u32);
@@ -562,13 +563,18 @@ fn images_whose_data_decodes_far_past_their_samples_are_left_alone() {
let grey = |bits: i64| [("BitsPerComponent", bits.into()), ("ColorSpace", Object::name("DeviceGray"))];
let one_bit = mono_image(&mut doc, w, h, &padded(&text), None, &grey(1));
let eight_bit = mono_image(&mut doc, w, h, &padded(&shades), None, &grey(8));
+ let packed = mono_image(&mut doc, w, h, &padded(&self::eight_bit(&text, w, h)), None, &grey(8));
// 300 × 120 pt is 288 ppi; 144 × 57.6 pt is 600 ppi.
- page(&mut doc, &[("A", one_bit), ("B", eight_bit)], "q 300 0 0 120 20 600 cm /A Do Q q 144 0 0 57.6 20 400 cm /B Do Q");
- let before = [one_bit, eight_bit].map(|r| stream(&doc, r).raw);
+ page(
+ &mut doc,
+ &[("A", one_bit), ("B", eight_bit), ("C", packed)],
+ "q 300 0 0 120 20 600 cm /A Do Q q 144 0 0 57.6 20 400 cm /B Do Q q 300 0 0 120 20 200 cm /C Do Q",
+ );
+ let before = [one_bit, eight_bit, packed].map(|r| stream(&doc, r).raw);
let r = optimize(&mut doc, &Settings::default()).unwrap();
- let after = [one_bit, eight_bit].map(|r| stream(&doc, r).raw);
+ let after = [one_bit, eight_bit, packed].map(|r| stream(&doc, r).raw);
if padding == 0 {
- assert_eq!((r.images_resampled, r.images_recompressed), (1, 1), "{r:?}");
+ assert_eq!((r.images_resampled, r.images_recompressed), (1, 2), "{r:?}");
} else {
assert_eq!((r.images_resampled, r.images_recompressed), (0, 0), "{r:?}");
assert_eq!(after, before);
@@ -608,6 +614,63 @@ fn eight_bit(bits: &[u8], w: u32, h: u32) -> Vec<u8> {
(0..h as usize).flat_map(|y| (0..w as usize).map(move |x| if bits[y * stride + x / 8] & (0x80 >> (x % 8)) != 0 { 255 } else { 0 })).collect()
}
+/// Eight-bit samples of only 0 and 255, dithered (Floyd–Steinberg) from a smooth picture as a
+/// scanner's halftone mode gives them: no shade but black and white, in short runs.
+fn dithered(w: u32, h: u32) -> Vec<u8> {
+ let (w, h) = (w as usize, h as usize);
+ let mut level: Vec<f32> = (0..w * h).map(|i| 127.5 + 127.5 * ((i % w) as f32 / 37.0).sin() * ((i / w) as f32 / 53.0).cos()).collect();
+ let mut out = vec![0u8; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ let i = y * w + x;
+ let v = if level[i] < 128.0 { 0.0 } else { 255.0 };
+ out[i] = v as u8;
+ let e = level[i] - v;
+ if x + 1 < w {
+ level[i + 1] += e * 7.0 / 16.0;
+ }
+ if y + 1 < h {
+ if x > 0 {
+ level[i + w - 1] += e * 3.0 / 16.0;
+ }
+ level[i + w] += e * 5.0 / 16.0;
+ if x + 1 < w {
+ level[i + w + 1] += e / 16.0;
+ }
+ }
+ }
+ }
+ out
+}
+
+/// A dithered scan stored as eight-bit grey of only black and white is smaller downsampled and
+/// JPEG-compressed by the grey settings than packed to one bit, which can't shrink its dots: the
+/// smaller wins, so Reduce File Size makes it no larger than with Monochrome Images on Retain.
+/// Clean text is still packed to one bit at the same resolution.
+#[test]
+fn eight_bit_black_and_white_takes_the_smaller_of_one_bit_and_the_grey_settings() {
+ let (w, h) = (1200u32, 1500u32);
+ for (what, samples) in [("dither", dithered(w, h)), ("text", eight_bit(&bilevel(w, h, false), w, h))] {
+ let build = || {
+ let mut doc = Document::new_empty();
+ let img = mono_image(&mut doc, w, h, &samples, None, &[("BitsPerComponent", 8.into()), ("ColorSpace", Object::name("DeviceGray"))]);
+ // 288 × 360 pt is 300 ppi, above where the grey settings downsample.
+ page(&mut doc, &[("A", img)], "q 288 0 0 360 20 400 cm /A Do Q");
+ (doc, img)
+ };
+ let (mut doc, img) = build();
+ optimize(&mut doc, &Settings::default()).unwrap();
+ let (mut retained, _) = build();
+ optimize(&mut retained, &Settings { mono: MonoCompression::Retain, ..Settings::default() }).unwrap();
+ let (s, kept) = (stream(&doc, img), stream(&retained, img));
+ let bits = if what == "dither" { 8 } else { 1 };
+ assert_eq!(s.dict.int(b"BitsPerComponent"), Some(bits), "{what}: {} bytes, {} with Retain", s.raw.len(), kept.raw.len());
+ if what == "dither" {
+ assert!(s.raw.len() <= kept.raw.len(), "{what}: {} bytes, {} with Retain", s.raw.len(), kept.raw.len());
+ }
+ }
+}
+
/// Eight-bit grey images of only black and white (as some scanners and converters write scans)
/// become one-bit Group 4, losslessly: the page looks the same, an inverting decode array
/// included. Not touched by this: a grey image with any other shade, an indexed image (its samples
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index bf96832b1..81c971dbc 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/optimize/tests/optimize.rs::eight_bit_black_and_white_images_become_one_bit", "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/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, lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size does it too; 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. An eight-bit grey image of only black and white is packed to one bit first, then stored the same way (indexed images and colour-key masks aside). Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), monochrome downsampling, inline images, soft masks and /Mask images, rows wider than 32,767 samples. Redaction doesn't decode Group 4 yet (a mark over part of such an image removes it whole; nothing leaks)."
+notes = "CCITT Group 4, lossless: PDF Optimizer ▸ Images ▸ Monochrome Images (on by default, so Reduce File Size does it too; 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. An eight-bit grey image of only black and white is packed to one bit first, then stored the same way (indexed images and colour-key masks aside), unless the grey settings make it smaller still (a dithered scan downsampled to JPEG). Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), monochrome downsampling, inline images, soft masks and /Mask images, rows wider than 32,767 samples. Redaction doesn't decode Group 4 yet (a mark over part of such an image removes it whole; nothing leaks)."
[[feature]]
id = "optimize.only-if-smaller"