Skip to content

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

M11: black-and-white RGB stays RGB where grey would be drawn otherwise

Grzegorz Martens450c327c6bcb
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index 3f53a07ff..838fa57ab 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -1332,7 +1332,7 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["from"],
)),
- t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: colour and grey images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), black-and-white images averaged down to 300 ppi above 450 ppi and each stored as CCITT Group 4 (or 1-bit Flate, once resampled) whenever that is smaller, thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.")
+ t("doc_reduce", "Reduce file size", "Write a smaller copy of the document to `path` with Acrobat's Reduce File Size choices: colour and grey images above 225 ppi downsampled to 150 ppi and JPEG-compressed (medium quality), black-and-white images averaged down to 300 ppi above 450 ppi and each stored as CCITT Group 4 (or 1-bit Flate, once resampled or packed from more bits) whenever that is smaller, thumbnails dropped, identical fonts and images merged, unused objects dropped, compressed object streams. If the copy wouldn't be smaller, nothing is written and `written` is false. The open document is unchanged.")
.cmd("optimize.reduce")
.with(schema(json!({ "doc": doc(), "path": { "type": "string" } }), &["doc", "path"])),
t("doc_initial_view", "Initial view", "Read or change how the document opens (Document Properties ▸ Initial View) and its reading options: navigation (page, bookmarks, pages, attachments, layers), layout (default, single, continuous, two_up, two_up_continuous, two_up_cover, two_up_continuous_cover), magnification (default, actual, fit_page, fit_width, fit_height, fit_visible, or a percentage), page, window options (fit_window, center_window, full_screen, display_title), interface options (hide_menubar, hide_toolbar, hide_window_ui), language and binding (left, right). Only the given ones change; returns the result. Undoable.").with(schema(
diff --git a/crates/optimize/README.md b/crates/optimize/README.md
index 0b159229a..e26ceba94 100644
--- a/crates/optimize/README.md
+++ b/crates/optimize/README.md
@@ -45,12 +45,15 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
row, not as T.4 sends them, is read as PdfCraft draws it, which at `/K 0` may be other rows than
were coded, and an image stored again keeps them). Packed to one bit first, unless a colour-key `/Mask` is in the image's
own values: eight-bit grey of only 0 and 255; eight-bit `DeviceRGB` of only black and white,
- which becomes `DeviceGray` (not calibrated RGB or RGB with a profile); and an indexed image of 2,
- 4 or 8 bits that uses only palette entries 0 and 1, which keeps its palette, whatever its two
- colours. A decode array stays when it means the same at one bit (grey's, or RGB's if the same
- for each component, as grey's); otherwise the image is left alone. The grey or colour settings
- take a packed image instead when they make it smaller still, its soft mask counted (resampled
- with it there, kept as it is here), as they can a dithered scan by downsampling it to JPEG.
+ which becomes `DeviceGray` (not calibrated RGB or RGB with a profile, nor one drawn where
+ `/DefaultGray` or `/DefaultRGB` is in force, which would then draw it otherwise, nor one whose
+ soft mask has a `/Matte`); and an indexed image of 2, 4 or 8 bits that uses only palette entries
+ 0 and 1, which keeps its palette, whatever its two colours. A decode array stays when it means
+ the same at one bit (grey's, or RGB's if the same for each component, as grey's), and an indexed
+ image's default one goes, as the default at one bit; otherwise the image is left alone. The grey
+ or colour settings take a packed image instead when they make it smaller still, its soft mask
+ counted (resampled with it there, kept as it is here), as they can a dithered scan by
+ downsampling it to JPEG.
- **Downsampling:** one whose effective resolution is above `above_ppi` is averaged down to
`target_ppi`: each new pixel takes the sample covering more of its area, and the dark one on a
tie, so a dark line half a new pixel wide stays: black in grey and the painted part of an image
@@ -62,17 +65,18 @@ let report = optimize_with_progress(&mut doc, &settings, &mut |stage| keep_going
a fax row (`pdfcraft_filters::MAX_CCITT_COLUMNS`), as the averaging keeps a counter for each
column. On a 600 ppi text page, Group 4 at 300 ppi is half the size.
- **Compression:** CCITT Group 4 (`pdfcraft_filters::encode_g4`), or 1-bit Flate when that is
- smaller, which only a resampled image or one packed from eight bits may be: a 1-bit image that
+ 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 stays. Group 4 alone is only decoded to be resampled;
Group 3, or Group 4 inside another filter such as `ASCII85Decode`, is stored again as Group 4
alone when that is smaller. With Retain, a resampled image keeps its kind of compression (CCITT,
- or Flate) and nothing else changes; eight-bit grey is then left to the grey settings. Every
- change is kept only when it is smaller as stored.
+ or Flate) and nothing else changes; an image of more bits is then left to the grey or colour
+ settings. Every change is kept only when it is smaller as stored.
- Apart from the downsampling it is lossless: the samples keep their meaning, so the colour
- space, decode array and `/Mask` stay. Group 4 wins on scans, whose ragged edges defeat Flate;
- on clean computer-drawn 1-bit art Flate can be smaller. Not yet: JBIG2, a lone Group 3 image to
- Group 4 without resampling (one behind another filter is stored again as Group 4), inline images, an image's own `/SMask` or `/Mask` image (only images drawn
- on a page are visited), and Group 4 for rows wider than 32,767 samples.
+ space, decode array and `/Mask` stay, but for packed RGB, which becomes grey with one decode
+ pair. Group 4 wins on scans, whose ragged edges defeat Flate; on clean computer-drawn 1-bit
+ art Flate can be smaller. Not yet: JBIG2, inline images, an image's own `/SMask` or `/Mask`
+ image (only images drawn on a page are visited), and Group 4 for rows wider than 32,767
+ samples.
- **Discard objects:** thumbnails, alternate images, document tags, print settings.
- **Clean up:** Flate for streams with no filter; for streams with an outer ASCII85 or ASCIIHex
layer, that layer is removed when the result is smaller (the inner filters keep their encoded
diff --git a/crates/optimize/src/images.rs b/crates/optimize/src/images.rs
index 8b55d4aeb..71fa945da 100644
--- a/crates/optimize/src/images.rs
+++ b/crates/optimize/src/images.rs
@@ -41,9 +41,10 @@ struct Walk<'a> {
doc: &'a Document,
/// The forms being walked right now, outermost first: a form drawing one of these is a cycle.
path: Vec<ObjRef>,
- /// Forms with their own resources already walked, by the linear part of their matrix. Drawing
- /// one again at the same scale (only moved) can't change any image's resolution.
- walked: HashSet<(ObjRef, [u64; 4])>,
+ /// Forms with their own resources already walked, by the linear part of their matrix and
+ /// whether default colour spaces were in force. Drawing one again at the same scale (only
+ /// moved) can't change any image's resolution.
+ walked: HashSet<(ObjRef, [u64; 4], bool)>,
/// Forms walked at least once.
seen: HashSet<ObjRef>,
rewalks: usize,
@@ -52,13 +53,17 @@ struct Walk<'a> {
/// False once a use may have been missed (depth or work limit).
complete: bool,
out: HashMap<ObjRef, f64>,
+ /// Images drawn at least once where `/DefaultGray` or `/DefaultRGB` is in force.
+ defaults: HashSet<ObjRef>,
}
impl Walk<'_> {
/// Walk one content stream, recording each image's displayed resolution (pixels per inch, the
- /// smaller of the two axes) and descending into form XObjects.
- fn content(&mut self, data: &[u8], resources: &Dict, ctm: Matrix) {
+ /// smaller of the two axes) and descending into form XObjects. `defaults`: an enclosing
+ /// stream's resources remap a device colour space.
+ fn content(&mut self, data: &[u8], resources: &Dict, ctm: Matrix, defaults: bool) {
let doc = self.doc;
+ let defaults = defaults || remaps_device_spaces(doc, resources);
let xobjects = resources.get(b"XObject").map(|x| doc.resolve(x)).and_then(|x| x.as_dict().cloned()).unwrap_or_default();
let mut stack = vec![ctm];
for op in pdfcraft_content::parse(data).ops {
@@ -90,8 +95,11 @@ impl Walk<'_> {
let e = self.out.entry(r).or_insert(f64::INFINITY);
*e = e.min(ppi);
}
+ if defaults {
+ self.defaults.insert(r);
+ }
}
- Some(b"Form") => self.form(r, s, resources, top),
+ Some(b"Form") => self.form(r, s, resources, top, defaults),
_ => {}
}
}
@@ -101,7 +109,7 @@ impl Walk<'_> {
}
/// Descend into form `r` drawn with `ctm` from a stream whose resources are `resources`.
- fn form(&mut self, r: ObjRef, s: &Stream, resources: &Dict, ctm: Matrix) {
+ fn form(&mut self, r: ObjRef, s: &Stream, resources: &Dict, ctm: Matrix, defaults: bool) {
if self.path.contains(&r) {
return;
}
@@ -116,7 +124,7 @@ impl Walk<'_> {
// A form without resources uses its caller's, so the same form can draw other images.
if own.is_some() {
let [a, b, c, d, ..] = inner.0;
- if !self.walked.insert((r, [a.to_bits(), b.to_bits(), c.to_bits(), d.to_bits()])) {
+ if !self.walked.insert((r, [a.to_bits(), b.to_bits(), c.to_bits(), d.to_bits()], defaults)) {
return;
}
}
@@ -136,17 +144,30 @@ impl Walk<'_> {
return;
};
self.path.push(r);
- self.content(&data, own.as_ref().unwrap_or(resources), inner);
+ self.content(&data, own.as_ref().unwrap_or(resources), inner, defaults);
self.path.pop();
}
}
+/// Whether `resources` remap a device colour space an image may be moved between, so that the
+/// same samples would be drawn otherwise: `/DefaultGray` or `/DefaultRGB` (ISO 32000-2 §8.6.5.6).
+fn remaps_device_spaces(doc: &Document, resources: &Dict) -> bool {
+ let spaces = resources.get(b"ColorSpace").map(|c| doc.resolve(c));
+ spaces.as_deref().and_then(Object::as_dict).is_some_and(|c| c.contains(b"DefaultGray") || c.contains(b"DefaultRGB"))
+}
+
/// The effective resolution (ppi) of every image drawn by `pages`: the smallest over its uses.
///
/// If forms nest too deeply, are drawn too many times, or a page's content doesn't decode within
/// its budget, every image is given `INFINITY` (never resampled), since its largest use may be
/// among those missed.
pub fn effective_resolutions(doc: &Document, pages: &[ObjRef]) -> HashMap<ObjRef, f64> {
+ walk_pages(doc, pages).0
+}
+
+/// [`effective_resolutions`], and the images drawn where `/DefaultGray` or `/DefaultRGB` is in
+/// force: all of them when a use may have been missed.
+fn walk_pages(doc: &Document, pages: &[ObjRef]) -> (HashMap<ObjRef, f64>, HashSet<ObjRef>) {
let mut walk = Walk {
doc,
path: Vec::new(),
@@ -156,6 +177,7 @@ pub fn effective_resolutions(doc: &Document, pages: &[ObjRef]) -> HashMap<ObjRef
budget: DecodeBudget::page(),
complete: true,
out: HashMap::new(),
+ defaults: HashSet::new(),
};
for p in pages {
let Some(dict) = doc.get(*p).as_dict().cloned() else { continue };
@@ -169,12 +191,13 @@ pub fn effective_resolutions(doc: &Document, pages: &[ObjRef]) -> HashMap<ObjRef
};
// Content coordinates are in page units; image resolution is in physical inches.
let unit = page.user_unit(doc);
- walk.content(&data, &res, Matrix([unit, 0.0, 0.0, unit, 0.0, 0.0]));
+ walk.content(&data, &res, Matrix([unit, 0.0, 0.0, unit, 0.0, 0.0]), false);
}
if !walk.complete {
walk.out.values_mut().for_each(|v| *v = f64::INFINITY);
+ walk.defaults.extend(walk.out.keys());
}
- walk.out
+ (walk.out, walk.defaults)
}
/// Colour components of a colour space PdfCraft resamples: gray (1) or RGB (3).
@@ -577,11 +600,13 @@ type Pixel = fn(&[u8]) -> Option<bool>;
/// - eight-bit `DeviceRGB` whose every pixel is black or white, which becomes `DeviceGray`. A
/// decode array the same for all three components becomes that one pair; another stops it.
/// Calibrated RGB and RGB with a profile are left out, as the profile could make them other
-/// than black and white;
+/// than black and white; so is one drawn where `/DefaultGray` or `/DefaultRGB` is in force
+/// (`defaults`), which would draw it otherwise as grey, and one whose soft mask has a `/Matte`
+/// of three components;
/// - an indexed image of 2, 4 or 8 bits that uses only palette entries 0 and 1, which stay 0 and
/// 1 at one bit, whatever their colours, so the colour space stays. A decode array other than
/// the default stops it: in index units it would mean something else at one bit.
-fn one_bit(doc: &Document, s: &Stream, pack: bool) -> Option<(Vec<u8>, u32, u32, Option<Dict>)> {
+fn one_bit(doc: &Document, s: &Stream, pack: bool, defaults: bool) -> Option<(Vec<u8>, u32, u32, Option<Dict>)> {
let d = &s.dict;
// Through u32 first, as everywhere here, so the product can't overflow.
let (w, h) = (u32::try_from(d.int(b"Width")?).ok()?, u32::try_from(d.int(b"Height")?).ok()?);
@@ -633,6 +658,10 @@ fn one_bit(doc: &Document, s: &Stream, pack: bool) -> Option<(Vec<u8>, u32, u32,
})
}
Object::Name(name) if matches!(name.as_slice(), b"DeviceRGB" | b"RGB") && bits == Some(8) => {
+ let matte = |m: &Object| matches!(&*doc.resolve(m), Object::Stream(m) if m.dict.contains(b"Matte"));
+ if defaults || d.get(b"SMask").is_some_and(matte) {
+ return None;
+ }
match decode.as_deref() {
None => {}
Some(Object::Array(v)) if v.len() == 6 && v.chunks(2).all(|pair| Some(pair) == v.get(..2)) => {
@@ -768,7 +797,8 @@ pub(crate) fn downsample_bits(data: &[u8], w: u32, h: u32, nw: u32, nh: u32, dar
}
/// A black-and-white image (see [`one_bit`]) resampled and stored again per `settings`, if that is
-/// smaller as stored; `ppi` is its effective resolution. Also says whether it was resampled.
+/// smaller as stored; `ppi` is its effective resolution, and `defaults` says it is drawn where
+/// `/DefaultGray` or `/DefaultRGB` is in force. Also says whether it was resampled.
///
/// - **Resampled** ([`downsample_bits`]) when its resolution is above `above_ppi`, to `target_ppi`,
/// unless it has a soft mask, whose own size would then have to follow, or is a halftone or a
@@ -781,9 +811,10 @@ pub(crate) fn downsample_bits(data: &[u8], w: u32, h: u32, nw: u32, nh: u32, dar
/// (CCITT, or Flate), and nothing else changes: an image of more bits stays as it is, for the
/// grey or colour settings.
///
-/// The samples keep their meaning, so the decode array and `/Mask` stay as they are, and the
-/// colour space too, but for black-and-white RGB, which becomes grey.
-fn mono(doc: &Document, s: &Stream, ppi: f64, settings: &MonoSettings) -> Option<(Stream, bool)> {
+/// The samples keep their meaning, so the colour space, decode array and `/Mask` stay, but for
+/// black-and-white RGB, which becomes grey with one decode pair, and an indexed image's default
+/// decode array, which goes as the default at one bit.
+fn mono(doc: &Document, s: &Stream, ppi: f64, defaults: bool, settings: &MonoSettings) -> Option<(Stream, bool)> {
let d = &s.dict;
let downsample = settings.downsample && ppi.is_finite() && ppi > settings.above_ppi && settings.target_ppi > 0.0 && !d.contains(b"SMask");
let retain = settings.compression == MonoCompression::Retain;
@@ -796,7 +827,7 @@ fn mono(doc: &Document, s: &Stream, ppi: f64, settings: &MonoSettings) -> Option
if (retain || g4_alone) && !downsample {
return None;
}
- let (data, w, h, packed) = one_bit(doc, s, !retain)?;
+ let (data, w, h, packed) = one_bit(doc, s, !retain, defaults)?;
let packed_from_more = packed.is_some();
let k = settings.target_ppi / ppi;
// `downsample_bits` keeps a counter for each column: no more columns than a fax row may have,
@@ -858,7 +889,7 @@ pub(crate) fn run(
report: &mut Report,
progress: &mut dyn FnMut(Stage) -> bool,
) -> Result<(), OptimizeError> {
- let ppi = effective_resolutions(doc, pages);
+ let (ppi, defaults) = walk_pages(doc, pages);
// Soft masks are processed with their image, not on their own.
let masks: HashSet<ObjRef> = ppi
.keys()
@@ -877,10 +908,10 @@ pub(crate) fn run(
let obj = doc.get(r);
let Object::Stream(s) = &*obj else { continue };
report.images += 1;
- // Packed from more bits a sample, it is lossless at one bit, but the grey settings can
- // make it smaller still (below).
+ // Packed from more bits a sample, it is lossless at one bit, but the grey or colour
+ // settings can make it smaller still (below).
let packed_from_more = s.dict.int(b"BitsPerComponent").is_some_and(|b| b > 1);
- let (packed, mono) = match mono(doc, s, ppi, &settings.mono) {
+ let (packed, mono) = match mono(doc, s, ppi, defaults.contains(&r), &settings.mono) {
Some(m) if packed_from_more => (Some(m), None),
m => (None, m),
};
diff --git a/crates/optimize/tests/optimize.rs b/crates/optimize/tests/optimize.rs
index cc8f2f468..259e11c77 100644
--- a/crates/optimize/tests/optimize.rs
+++ b/crates/optimize/tests/optimize.rs
@@ -918,6 +918,103 @@ fn rgb_and_two_colour_indexed_black_and_white_images_become_one_bit() {
assert!(render(&doc) == before, "the page looks the same");
}
+/// Black-and-white RGB stays RGB where grey would be drawn otherwise: drawn, on any of its uses,
+/// where `/DefaultGray` or `/DefaultRGB` is in force (ISO 32000-2 §8.6.5.6), from a page's
+/// resources or a form's own, as grey would then go through DefaultGray, or no longer through
+/// DefaultRGB; or with a soft mask whose `/Matte` has three components, one for each of RGB's. A
+/// form drawn where they are in force counts too, though it has resources of its own. The same
+/// image drawn plainly, or with a soft mask and no `/Matte`, becomes grey.
+#[test]
+fn black_and_white_rgb_stays_rgb_where_grey_would_be_drawn_otherwise() {
+ let mut doc = Document::new_empty();
+ let (w, h) = (1200u32, 480u32);
+ let rgb_data = samples_of(&bilevel(w, h, false), w, h, [&[0, 0, 0], &[255, 255, 255]], 8);
+ let image = |doc: &mut Document, cs: &str, data: &[u8], entries: &[(&str, Object)]| {
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("XObject"));
+ d.set(b"Subtype".to_vec(), Object::name("Image"));
+ d.set(b"Width".to_vec(), Object::Int(w.into()));
+ d.set(b"Height".to_vec(), Object::Int(h.into()));
+ d.set(b"BitsPerComponent".to_vec(), Object::Int(8));
+ d.set(b"ColorSpace".to_vec(), Object::name(cs));
+ for (k, v) in entries {
+ d.set(k.as_bytes().to_vec(), v.clone());
+ }
+ doc.add(Object::Stream(Stream::flate(d, data)))
+ };
+ let opaque = vec![255u8; (w * h) as usize];
+ let plain_mask = image(&mut doc, "DeviceGray", &opaque, &[]);
+ let matte_mask = image(&mut doc, "DeviceGray", &opaque, &[("Matte", Object::Array(vec![0.into(); 3]))]);
+ let plain = image(&mut doc, "DeviceRGB", &rgb_data, &[]);
+ let masked = image(&mut doc, "DeviceRGB", &rgb_data, &[("SMask", Object::Ref(plain_mask))]);
+ let matted = image(&mut doc, "DeviceRGB", &rgb_data, &[("SMask", Object::Ref(matte_mask))]);
+ let [under_gray, under_rgb, shared, in_form, nested] = [(); 5].map(|_| image(&mut doc, "DeviceRGB", &rgb_data, &[]));
+ let mut white_point = Dict::new();
+ white_point.set(b"WhitePoint".to_vec(), Object::Array(vec![Object::Real(0.9505), 1.into(), Object::Real(1.089)]));
+ let spaces = |key: &str| {
+ let family = if key == "DefaultGray" { "CalGray" } else { "CalRGB" };
+ let mut c = Dict::new();
+ c.set(key.as_bytes().to_vec(), Object::Array(vec![Object::name(family), Object::Dict(white_point.clone())]));
+ Object::Dict(c)
+ };
+ let draw = |names: &[&str]| names.iter().enumerate().map(|(i, n)| format!("q 200 0 0 80 6 {} cm /{n} Do Q ", 690 - 100 * i)).collect::<String>();
+ let form = |doc: &mut Document, im: ObjRef, spaces: Option<Object>| {
+ let mut xobjects = Dict::new();
+ xobjects.set(b"Im".to_vec(), Object::Ref(im));
+ let mut resources = Dict::new();
+ resources.set(b"XObject".to_vec(), Object::Dict(xobjects));
+ if let Some(spaces) = spaces {
+ resources.set(b"ColorSpace".to_vec(), spaces);
+ }
+ let mut f = Dict::new();
+ f.set(b"Type".to_vec(), Object::name("XObject"));
+ f.set(b"Subtype".to_vec(), Object::name("Form"));
+ f.set(b"BBox".to_vec(), Object::Array(vec![0.into(), 0.into(), 612.into(), 792.into()]));
+ f.set(b"Resources".to_vec(), Object::Dict(resources));
+ doc.add(Object::Stream(Stream::from_raw(f, draw(&["Im"]).into_bytes())))
+ };
+ // Drawn plainly first, then where DefaultGray is in force: the second walk must happen.
+ let plain_form = form(&mut doc, nested, None);
+ page(&mut doc, &[("A", plain), ("B", masked), ("C", matted), ("D", shared), ("E", plain_form)], &draw(&["A", "B", "C", "D", "E"]));
+ for (key, xobjects) in [("DefaultGray", vec![("A", under_gray), ("B", shared), ("C", plain_form)]), ("DefaultRGB", vec![("A", under_rgb)])] {
+ let names: Vec<&str> = xobjects.iter().map(|(n, _)| *n).collect();
+ let p = page(&mut doc, &xobjects, &draw(&names));
+ doc.update_dict(p, |d| {
+ let mut res = d.get(b"Resources").and_then(Object::as_dict).cloned().unwrap();
+ res.set(b"ColorSpace".to_vec(), spaces(key));
+ d.set(b"Resources".to_vec(), Object::Dict(res));
+ })
+ .unwrap();
+ }
+ // A form with its own resources, DefaultGray among them, on a page without any.
+ let gray_form = form(&mut doc, in_form, Some(spaces("DefaultGray")));
+ page(&mut doc, &[("F", gray_form)], "/F Do");
+ let kept = [under_gray, under_rgb, shared, in_form, nested, matted];
+ let before = kept.map(|r| stream(&doc, r));
+ // Colour and grey settings that leave images alone, so only this conversion acts.
+ let keep = ImageSettings { downsample: false, target_ppi: 150.0, above_ppi: 225.0, compression: Compression::Retain };
+ let settings = Settings { color: keep, gray: keep, ..Settings::default() };
+ let r = optimize(&mut doc, &settings).unwrap();
+ assert_eq!((r.images_resampled, r.images_recompressed), (0, 2), "{r:?}");
+ for i in [plain, masked] {
+ let s = stream(&doc, i);
+ assert_eq!((s.dict.get(b"ColorSpace"), s.dict.int(b"BitsPerComponent")), (Some(&Object::name("DeviceGray")), Some(1)), "{i:?}");
+ }
+ for (i, b) in kept.iter().zip(&before) {
+ let s = stream(&doc, *i);
+ assert_eq!((&s.dict, &s.raw), (&b.dict, &b.raw), "{i:?}");
+ }
+
+ // A use that couldn't be followed (forms nested too deep) may be where DefaultGray is in force.
+ let mut doc = Document::new_empty();
+ let img = image(&mut doc, "DeviceRGB", &rgb_data, &[]);
+ let deep = nested_forms(&mut doc, img, 13);
+ page(&mut doc, &[("Im", img), ("F", deep)], &draw(&["Im", "F"]));
+ let before = stream(&doc, img);
+ optimize(&mut doc, &settings).unwrap();
+ assert_eq!(stream(&doc, img).raw, before.raw, "a use not followed");
+}
+
/// Black-and-white images above 450 ppi are averaged down to 300 ppi, by default: 1-bit Flate, CCITT
/// Group 4 (alone and behind ASCIIHexDecode), an image mask (its inverting decode array stays), and
/// eight-bit grey and RGB of only black and white (the RGB also the other way round, with a decode
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index bc4c68d53..048afd9a3 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/optimize/tests/optimize.rs::group_3_fax_images_become_group_4", "crates/optimize/tests/optimize.rs::rgb_and_two_colour_indexed_black_and_white_images_become_one_bit", "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. Packed to one bit first, then stored the same way (colour-key masks aside): eight-bit grey of only black and white, eight-bit DeviceRGB of only black and white (as DeviceGray; calibrated RGB and RGB with a profile aside), and an indexed image of 2, 4 or 8 bits that uses only palette entries 0 and 1 (keeping its palette), unless the grey or colour settings make it smaller still, as they can a dithered scan downsampled to JPEG, its soft mask counted. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Group 3 fax images are stored again as Group 4 when that is smaller. CCITT fax images are decoded to be downsampled (optimize.downsample-images), and a resampled image is stored as Group 4 or 1-bit Flate, whichever is smaller. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples."
+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. Packed to one bit first, then stored the same way (colour-key masks aside): eight-bit grey of only black and white, eight-bit DeviceRGB of only black and white (as DeviceGray; calibrated RGB, RGB with a profile, RGB drawn where /DefaultGray or /DefaultRGB is in force, and RGB whose soft mask has a /Matte aside), and an indexed image of 2, 4 or 8 bits that uses only palette entries 0 and 1 (keeping its palette), unless the grey or colour settings make it smaller still, as they can a dithered scan downsampled to JPEG, its soft mask counted. Group 4 wins on scans; on clean computer-drawn 1-bit art Flate can be smaller, and the image then stays. Group 3 fax images are stored again as Group 4 when that is smaller. CCITT fax images are decoded to be downsampled (optimize.downsample-images), and a resampled image is stored as Group 4 or 1-bit Flate, whichever is smaller. Not yet: JBIG2 (lossless or lossy, which Adobe's help says beats CCITT for monochrome), inline images, soft masks and /Mask images, Group 4 for rows wider than 32,767 samples."
[[feature]]
id = "optimize.only-if-smaller"