pdf: wire the /Interpolate decision through to the renderer (#321)
- Commit
cce5ca57267a5eb336f3f094a8e7d9d5ab267ab2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 18:53 UTC (5 days ago)
- Parents
f858202
Issue #321 ('PDF app does not render properly') predates several
renderer rounds; the original-era causes (rotated-page matrix swap,
CalRGB transposition, the ARGB wire change, the Adobe YCCK polarity
fix in #924) were already fixed. A full audit of the remaining render
pipeline (colour spaces, JPX/JBIG2/CCITT decoders, transparency and
blend modes, text and font fallback, annotations, patterns/shadings,
/Rotate and CropBox handling — each now pinned by probe tests) found
one last provable defect: image_should_interpolate computed the
/Interpolate decision in Rust, but nothing carried it, so every image
was bilinearly smoothed on magnification — a magnified QR code,
barcode or scanned fax dissolved into a grey ramp.
Prim::Image now carries the decision (image XObjects and inline
images consult the dictionary; shading rasters set true), wire v11
writes the u8 interpolate byte the Kotlin parser already gated on,
and Kotlin applies it as isFilterBitmap. The version bump and the
byte land atomically, exactly as the wire contract demands; Kotlin
byte-count tests were moved to v11 in step. The remaining documented
surface (rasterized tiling-pattern cells, which have no source
/Interpolate value) is called out in the Rust README/SPEC_COVERAGE.
New issue321_interpolate_tests assert the byte end to end (bilevel 0,
contone and explicit-true 1, header declares 11) plus Rotate/CropBox
probes. Verified: cargo test -p pdf_render 663 passed; :pdf:testDevUnitTest
passes. #321 can now be closed as fixed.Diff
pdf/AGENTS.md
diff --git a/pdf/AGENTS.md b/pdf/AGENTS.mdindex 9c81274929..38d202536a 100644--- a/pdf/AGENTS.md+++ b/pdf/AGENTS.md@@ -24,6 +24,7 @@ _Install: ./install pdf (dev by default)._ - `util/` holds only `PdfNative` (the Rust engine bridge) — don't add more files there; the capture model is in `data/` - Search-index prewarm at open is page-count gated (`SafePdfDocument.MAX_PREWARM_PAGES`, 256): opening a document never eagerly interprets the whole book; larger documents build the same index lazily on first search - Adobe YCCK (APP14 transform 2) CMYK JPEGs reach the Rust decoder with all four samples in inverted-ink polarity; the CMYK32 arm inverts all four before converting (transform 0 samples are already true ink)+- Wire format is v11: the Image arm carries a per-image `/Interpolate` byte decided in Rust (`image_should_interpolate` — bilevel art is never smoothed, contone and explicit `/Interpolate true` are), and Kotlin applies it as `isFilterBitmap`; bumping the wire version without writing the byte desyncs every later primitive - Outline drawer intent is owned by `ui/PdfOutlineState` (saveable, explicit user action only) and drives the Material drawer state; width changes are layout only and never open or close it, and the wide layout's side pane is derived from the width class, not from drawer state - Opening reads the document bytes once through a chunked, capped read (`SafePdfDocument.MAX_PDF_BYTES`, 256 MiB): oversized or unreadable inputs fail with the viewer error state instead of loading whole into the heap, the same read classifies encryption for the password prompt, and cut-and-glue appends use the same bounded read; redaction presence is probed lazily once editing starts, not at open
pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfParser.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfParser.kt b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfParser.ktindex 06585b1988..58b43960a5 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfParser.kt@@ -13,7 +13,7 @@ import java.nio.ByteOrder * * Wire format v11 (must stay in sync with `pdf/src/main/rust/src/wire.rs`): * ```- * header: u32 MAGIC=0x50444657, u32 VERSION (11 is the newest understood; Rust emits 10),+ * header: u32 MAGIC=0x50444657, u32 VERSION (11 is the newest understood; Rust emits 11), * f32 pageWidth, f32 pageHeight, u32 primitiveCount * Legacy v1 fallback: header is f32 W,H,u32 count (no magic) * v2..v10 fallbacks: same layout with fewer trailing fields for older cached pages@@ -44,8 +44,8 @@ import java.nio.ByteOrder * absent emitter is a no-op. * ``` * Pure function -> unit-testable. v9 adds per-image alpha, v10 per-image blend mode, v11 the- * per-image /Interpolate flag. Rust still declares v10 until it writes that byte, at which- * point the two must be bumped together — see the note on WIRE_VERSION in wire.rs.+ * per-image /Interpolate flag. Rust emits v11 with that byte — see the note on+ * WIRE_VERSION in wire.rs. * * Robustness contract: a single malformed or over-sized primitive must never discard the * page. [parse] returns whatever decoded cleanly, because the caller@@ -80,7 +80,7 @@ object SafePdfParser { /** * Highest wire version this parser understands — NOT the version the producer emits. * `WIRE_VERSION` in `pdf/src/main/rust/src/wire.rs` is the emitted one and currently- * declares 10; it may lag this constant, because every field newer than what it+ * declares 11; it may lag this constant, because every field newer than what it * declares stays gated off below, but it must never exceed it. A higher version is not * rejected here — [parse] warns and carries on with those gates closed, so it reads too * few bytes per primitive and desyncs the rest of the buffer.
pdf/src/main/rust/README.md
diff --git a/pdf/src/main/rust/README.md b/pdf/src/main/rust/README.mdindex fa7ec8c59a..c13e4ee3c8 100644--- a/pdf/src/main/rust/README.md+++ b/pdf/src/main/rust/README.md@@ -127,7 +127,7 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes. - **Encryption** (`crypto.rs` + `decrypt.rs`): open and save with the Standard security handler — RC4-128 and **AES-128 (V4/R4)** and **AES-256 (V5/R6)**. `save_encrypted` defaults to AES-128.-- **Wire format v10**: header `MAGIC 0x50444657 VERSION=10 f32 w,h u32 count`;+- **Wire format v11**: header `MAGIC 0x50444657 VERSION=11 f32 w,h u32 count`; tags 1 Text, 2 Fill, 3 Stroke, 4 Image, 5 ClipPush (with a bezier-retentive path-ops section), 6 ClipPop, 7 GroupPush, 8 GroupPop, 9 TextClipApply, 10 SoftMaskPush, 11 SoftMaskContent, 12 SoftMaskPop, 13 SoftMaskTransfer (a@@ -135,16 +135,12 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes. rasterized tiling-pattern cell plus its step and lattice extent, so a periodic fill costs one bitmap rather than one image per tile). Tags 13 and 14 are *tag*-gated rather than version-gated — a decoder that never sees one is- unaffected — so the declared version stays 10. Text carries its render+ unaffected. Text carries its render mode (v4); Text/Fill/Stroke each carry a per-primitive blend byte (v5); Text also carries its device advance (v7) and bold/italic/family/outline flags plus- the horizontal scale (v8); images carry per-image alpha (v9) and blend (v10).- `SafePdfParser.kt` parses v10 and keeps the earlier versions as fallbacks. It is- also written to consume a **v11** that adds the per-image `/Interpolate` byte, but- that read is gated on v11 and Rust still declares v10, so the byte is neither- written nor read; the two sides are consistent, not desynchronized. Whoever bumps- Rust to v11 must start writing the byte in the same change (see the `/Interpolate`- limitation).+ the horizontal scale (v8); images carry per-image alpha (v9), blend (v10) and+ the `/Interpolate` decision (v11).+ `SafePdfParser.kt` parses v11 and keeps the earlier versions as fallbacks. - **Blend modes**: honored not just on transparency groups but on individual fills, strokes and text — the graphics-state `/BM` travels with each Text/Fill/ Stroke primitive and is applied per-draw in Kotlin via `android.graphics.BlendMode`.@@ -401,21 +397,13 @@ slight shift in the darkest tones rather than missing content. signature *verification* and byte-range-preserving incremental updates are not implemented. Signing scaffolding (`prepare_signature`) and detached CMS creation exist, but existing signatures are not validated on open.-- **`/Interpolate` is decided but never transmitted** (8.9.5.1): an image that asks- for smoothing and one that asks for none are filtered identically, so a magnified- QR code, barcode, scanned fax or 1-bit stencil turns into grey mush.- `image_should_interpolate` computes the right answer in Rust, but `Prim::Image`- has no field for it, the Image arm writes no interpolate byte, and the renderer- filters unconditionally. The same root cause has a second surface: a rasterized- tiling-pattern cell (`ImageTiled`) is drawn with bitmap filtering hard-coded on,- so a bilevel hatch pattern blurs when zoomed.- The two sides are consistent about it rather than desynchronized: the wire spec- defines the byte at v11 and the Kotlin decoder is written to consume it, but that- read is gated on v11 and Rust still declares v10 — so the byte is never written- and never read, and the gate fails safe. This is the same half-wired shape `/TR`- had before it was completed, which is why it can look finished from either side- alone. Whoever bumps Rust to v11 **must** write the byte in the same change;- `wire.rs` says so at the constant.+- **`/Interpolate` on a rasterized tiling-pattern cell** (8.9.5.1): the v11+ interpolate byte covers image XObjects and inline images, so a magnified+ QR code, barcode, scanned fax or 1-bit stencil now keeps hard edges. A+ rasterized tiling-pattern cell (`ImageTiled`) is still drawn with bitmap+ filtering hard-coded on, so a bilevel hatch pattern blurs when zoomed; the+ cell is a generated raster rather than a source image, so there is no+ source `/Interpolate` value to carry for it. - **A very dense page is truncated at 300,000 drawing primitives**: past that the rest of the page is not emitted, so a large-format vector drawing — a map, CAD sheet or dense chart — renders only partially. This is a memory floor rather
pdf/src/main/rust/SPEC_COVERAGE.md
diff --git a/pdf/src/main/rust/SPEC_COVERAGE.md b/pdf/src/main/rust/SPEC_COVERAGE.mdindex a13533d2f3..2a80773569 100644--- a/pdf/src/main/rust/SPEC_COVERAGE.md+++ b/pdf/src/main/rust/SPEC_COVERAGE.md@@ -312,14 +312,15 @@ Ordered by (likelihood × visibility), which is the only ordering worth having. though rarely present. 3. **ExtGState `/FL` — FIXED in round 3.** The one Table 58 key that had full plumbing (`bezier_steps_for_flatness`) and no parser.-4. **`/Interpolate` on images — built, never wired.** `images::image_should_interpolate`- computes the right answer and nothing calls it, so every image is bilinearly smoothed on- magnification, including bilevel art: a magnified QR code, barcode or scanned fax gets a- grey ramp and a translucent fringe instead of hard black and white (§8.9.5.1 Table 89).- Blocked on the wire format — `wire.rs` reserves a v11 `u8 interpolate` in the Image arm- and the Kotlin parser already has the `isV11` gate, so this needs a `Prim::Image` field,- a `WIRE_VERSION` bump and a Kotlin constant bump **atomically**. Cross-language; not- landed here.+4. **`/Interpolate` on images — FIXED.** `Prim::Image` carries the+ `images::image_should_interpolate` decision, wire v11 writes the `u8 interpolate`+ byte in the Image arm, and the Kotlin parser/drawer (which already had the+ `isV11` gate and `isFilterBitmap = prim.interpolate`) now receives it, so+ bilevel art — a magnified QR code, barcode or scanned fax — keeps hard black+ and white instead of a grey ramp and a translucent fringe (§8.9.5.1 Table 89).+ Covered end to end by `issue321_interpolate_tests`. The one remaining surface+ is the rasterized tiling-pattern cell (`ImageTiled`), drawn with filtering+ hard-coded on; it is a generated raster with no source `/Interpolate` value. 5. **Text clip (`Tr` 4-7) from Type 3 glyphs and from glyphs with no recoverable Unicode.** The clip is accumulated on the Kotlin side from substitute-glyph text records, and those two cases emit none, so the clip ends up under-constrained: content that should show@@ -349,7 +350,7 @@ first but not the second is read **only by tests**. | Item | Verdict | | --- | --- |-| `images::image_should_interpolate` | **Built and never wired up — a real gap.** Its own doc comment names the handoff and `wire.rs` reserves the field for it. Blocked on wire.rs + Kotlin; see §7 item 4. |+| `images::image_should_interpolate` | **Wired up.** `Prim::Image` carries it, wire v11 serializes it, and the Kotlin drawer applies it; see §7 item 4. | | `images::shading_device_size` | **Superseded leftover — delete.** `rasterize_shading`'s own `auto_size()` closure does the same job from the device-space clip bbox, which is the right quantity; `shading_device_size` uses the unit-square→device matrix, which is not. Every caller passes `size == 0`, so `auto_size()` always wins. Its only reference is its own test. | | `FontInfo::base_font` | **Diagnostic field, not unfinished work.** Its only reader is a `println!` in `debug_ishi_test`. The parts of the base font name that matter downstream are already distilled into `style.bold`/`style.italic` and `family` at parse time and shipped in the v8 `fontFlags` byte. Using the raw string for exact-family substitution would need a per-primitive wire string that nobody has started. Keep and annotate, or delete. |
pdf/src/main/rust/src/differential_tests.rs
diff --git a/pdf/src/main/rust/src/differential_tests.rs b/pdf/src/main/rust/src/differential_tests.rsindex a010027026..e0701d97d7 100644--- a/pdf/src/main/rust/src/differential_tests.rs+++ b/pdf/src/main/rust/src/differential_tests.rs@@ -163,7 +163,7 @@ fn fp_prim(p: &Prim) -> String { fp_pts(pts), *blend as u8 ),- Prim::Image { ctm, w, h, format, data, alpha, blend } => format!(+ Prim::Image { ctm, w, h, format, data, alpha, blend, .. } => format!( "Image|{}|{}|{}|{}|{}|{:016x}|{}|{}", fp_mat(ctm), w,
pdf/src/main/rust/src/images_part2.rs
diff --git a/pdf/src/main/rust/src/images_part2.rs b/pdf/src/main/rust/src/images_part2.rsindex 8503e404c7..3417544d86 100644--- a/pdf/src/main/rust/src/images_part2.rs+++ b/pdf/src/main/rust/src/images_part2.rs@@ -80,9 +80,8 @@ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u /// Whether the renderer should SMOOTH this image when it MAGNIFIES it. /// /// §8.9.5.1 Table 89: `/Interpolate` defaults to **false** — "no image interpolation-/// shall be performed". Nothing in this crate reads it today and the Kotlin side sets-/// `isFilterBitmap = true` unconditionally, so every image is bilinearly smoothed on-/// upscale. For a photograph that is what a reader wants and no viewer does otherwise.+/// shall be performed". Before wire v11 nothing carried this decision, so the Kotlin+/// side smoothed every image on upscale. For a photograph that is what a reader wants and no viewer does otherwise. /// For BILEVEL art it is destructive in exactly the way round 1 established for the /// downscale path: smoothing a barcode, a QR code, a scanned fax page or a stencil turns /// its two colours into a ramp of greys and its hard 0/255 alpha into a translucent@@ -93,19 +92,10 @@ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u /// deliberately — the deviation is invisible, whereas obeying it would make every /// magnified photograph blocky. ///-/// `interp` should pass this onto the `Prim::Image` record and `viewer` should carry it-/// on the wire and use it to choose `isFilterBitmap`. It is a standalone predicate rather-/// than an `ImageData` field so it can land without breaking either of their files.-///-/// UNWIRED, deliberately, and NOT dead code — do not delete it looking for a caller. The-/// policy is complete and tested (`interpolation_is_refused_for_bilevel_art`), but-/// `Prim::Image` has no field for it, so nothing serializes it and the Kotlin parser's-/// pre-v11 default (smooth) applies to everything. `wire.rs` records the rest: the wire-/// version bump to 11 and the `u8 interpolate` byte must land in the SAME change, because-/// bumping without writing the byte makes the parser eat the first byte of the image's-/// `u32 len` and desync every primitive after it. That crosses wire.rs and the Kotlin-/// side, so it is not this file's to finish.-#[allow(dead_code)]+/// The interpreter passes this onto the `Prim::Image` record; wire v11 carries it+/// and the Kotlin side uses it to choose `isFilterBitmap`. It is a standalone+/// predicate rather than an `ImageData` field, because shading rasters (which have+/// no source dictionary) set the flag directly at their emission sites. pub(crate) fn image_should_interpolate(doc: &Document, dict: &Dictionary) -> bool { // `/I` is the §8.9.7 Table 93 abbreviation for /Interpolate in an inline image // dictionary. (As a /CS *value* `/I` means Indexed; as a KEY it is unambiguous.)
pdf/src/main/rust/src/interpret_part3.rs
diff --git a/pdf/src/main/rust/src/interpret_part3.rs b/pdf/src/main/rust/src/interpret_part3.rsindex d90e0b51b9..6988f0944b 100644--- a/pdf/src/main/rust/src/interpret_part3.rs+++ b/pdf/src/main/rust/src/interpret_part3.rs@@ -268,7 +268,7 @@ impl SeededInterp { if let Some(Object::Stream(stream)) = o.first() { if let Some(img) = extract_inline_image(doc, stream, self.gs.fill, &self.colorspaces) { let sm_start = prims.len();- if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: self.gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode }); }+ if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: self.gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode, interpolate: image_should_interpolate(doc, &stream.dict) }); } if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } }
pdf/src/main/rust/src/interpret_part4.rs
diff --git a/pdf/src/main/rust/src/interpret_part4.rs b/pdf/src/main/rust/src/interpret_part4.rsindex d5c2c11838..c0c0351eea 100644--- a/pdf/src/main/rust/src/interpret_part4.rs+++ b/pdf/src/main/rust/src/interpret_part4.rs@@ -21,7 +21,7 @@ impl SeededInterp { if !text_only && !self.oc_stack.last().copied().unwrap_or(false) { if let Some(img) = extract_image(doc, stream, self.gs.fill, &self.colorspaces) { let sm_start = prims.len();- if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: self.gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode }); }+ if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: self.gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode, interpolate: image_should_interpolate(doc, &stream.dict) }); } if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } }
pdf/src/main/rust/src/interpret_part5.rs
diff --git a/pdf/src/main/rust/src/interpret_part5.rs b/pdf/src/main/rust/src/interpret_part5.rsindex f4bd21aa07..9a34c708d3 100644--- a/pdf/src/main/rust/src/interpret_part5.rs+++ b/pdf/src/main/rust/src/interpret_part5.rs@@ -141,7 +141,7 @@ impl SeededInterp { if let Some((ctm,w,h,data)) = rasterize_shading(doc, obj, &self.gs.ctm, &self.colorspaces, 0, clip_bbox_device) { if prims.len() < MAX_PRIMITIVES && !self.oc_stack.last().copied().unwrap_or(false) { let sm_start = prims.len();- prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode });+ prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode, interpolate: true }); if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } }
pdf/src/main/rust/src/interpret_part7.rs
diff --git a/pdf/src/main/rust/src/interpret_part7.rs b/pdf/src/main/rust/src/interpret_part7.rsindex 4321abd27c..c1e64f2d3d 100644--- a/pdf/src/main/rust/src/interpret_part7.rs+++ b/pdf/src/main/rust/src/interpret_part7.rs@@ -472,7 +472,7 @@ pub(crate) fn paint_pattern_stroke(stroke: PatternStroke<'_>) { // plain entry point. if let Some((ctm, w, h, data)) = rasterize_shading_as_pattern(doc, shobj, &pmat, cs_resources, 0, stroke_bbox) { if prims.len() < MAX_PRIMITIVES {- prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: gs.alpha_stroke as f32, blend: gs.blend_mode });+ prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: gs.alpha_stroke as f32, blend: gs.blend_mode, interpolate: true }); } } }
pdf/src/main/rust/src/interpret_part8.rs
diff --git a/pdf/src/main/rust/src/interpret_part8.rs b/pdf/src/main/rust/src/interpret_part8.rsindex 957d3c0407..092d427d44 100644--- a/pdf/src/main/rust/src/interpret_part8.rs+++ b/pdf/src/main/rust/src/interpret_part8.rs@@ -53,7 +53,7 @@ pub(crate) fn paint_pattern_fill(fill: PatternFill<'_>) { // `/Background`, the `sh` operator ignores it. if let Some((ctm, w, h, data)) = rasterize_shading_as_pattern(doc, shobj, &pmat, cs_resources, 0, fill_bbox) { if prims.len() < MAX_PRIMITIVES {- prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: alpha_fill, blend });+ prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: alpha_fill, blend, interpolate: true }); } } }
pdf/src/main/rust/src/issue321_interpolate_tests.rs
diff --git a/pdf/src/main/rust/src/issue321_interpolate_tests.rs b/pdf/src/main/rust/src/issue321_interpolate_tests.rsnew file mode 100644index 0000000000..25f79c06cc--- /dev/null+++ b/pdf/src/main/rust/src/issue321_interpolate_tests.rs@@ -0,0 +1,160 @@+//! Regression fixture for issue #321's remaining provable render defect:+//! bilevel images were bilinearly smoothed on magnification because the+//! `/Interpolate` decision never reached the consumer.+//!+//! `images::image_should_interpolate` computed the right answer and the Kotlin+//! parser/drawer already honoured a wire-v11 `interpolate` byte, but+//! `Prim::Image` carried no such field and the serializer stayed at v10, so+//! the parser's pre-v11 default (smooth everything) applied to stencils,+//! 1-bit scans and fax images — a magnified QR/barcode/fax page rendered as+//! grey fringes instead of hard black and white ("does not render properly").+//!+//! These tests drive synthetic ordinary PDFs through the real pipeline+//! (`interpret_page` -> `serialize`) on the host, no device needed.++#[cfg(test)]+mod issue321_interpolate {+ use crate::*;+ use lopdf::content::Operation;+ use crate::wire::serialize;++ /// One-page document painting image XObject `/Im0` at 100x100pt, with+ /// optional page `/Rotate` and `/CropBox` extras.+ fn doc_with_image(+ image_dict: Dictionary,+ image_data: Vec<u8>,+ page_extra: Dictionary,+ ) -> (Document, ObjectId) {+ let mut doc = Document::with_version("1.7");+ let img_id = doc.add_object(Stream::new(image_dict, image_data));+ let content = Content {+ operations: vec![+ Operation::new("q", vec![]),+ Operation::new(+ "cm",+ vec![100.into(), 0.into(), 0.into(), 100.into(), 10.into(), 10.into()],+ ),+ Operation::new("Do", vec![Object::Name(b"Im0".to_vec())]),+ Operation::new("Q", vec![]),+ ],+ }+ .encode()+ .unwrap();+ let content_id = doc.add_object(Stream::new(dictionary! {}, content));+ let pages_id = doc.new_object_id();+ let mut page = dictionary! {+ "Type" => "Page",+ "Parent" => pages_id,+ "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],+ "Resources" => dictionary! {+ "XObject" => dictionary! { "Im0" => img_id },+ },+ "Contents" => content_id,+ };+ for (k, v) in page_extra.iter() {+ page.set(k.clone(), v.clone());+ }+ let page_id = doc.add_object(page);+ doc.objects.insert(+ pages_id,+ Object::Dictionary(dictionary! {+ "Type" => "Pages", "Kids" => vec![page_id.into()], "Count" => 1,+ }),+ );+ let catalog_id = doc.add_object(dictionary! {+ "Type" => "Catalog", "Pages" => pages_id,+ });+ doc.trailer.set("Root", catalog_id);+ (doc, page_id)+ }++ fn only_image(doc: &Document, page_id: ObjectId) -> (bool, Vec<u8>) {+ let page = interpret_page(doc, page_id).expect("interpret");+ let interp = page+ .prims+ .iter()+ .find_map(|p| match p {+ Prim::Image { interpolate, .. } => Some(*interpolate),+ _ => None,+ })+ .expect("page must emit one image prim");+ (interp, serialize(&page))+ }++ /// Header (20) + tag (1) + ctm (24) + w/h (8) + format (1) + alpha (4) ++ /// blend (1) lands on the v11 interpolate byte.+ const INTERPOLATE_BYTE_AT: usize = 20 + 1 + 24 + 8 + 1 + 4 + 1;++ #[test]+ fn bilevel_image_is_not_interpolated_end_to_end() {+ let (doc, page_id) = doc_with_image(+ dictionary! {+ "Type" => "XObject", "Subtype" => "Image",+ "Width" => 2, "Height" => 2,+ "ColorSpace" => "DeviceGray", "BitsPerComponent" => 1,+ },+ vec![0b1000_0000, 0b0100_0000],+ dictionary! {},+ );+ let (interp, wire) = only_image(&doc, page_id);+ assert!(!interp, "a 1-bit image must never be smoothed on magnification");+ assert_eq!(u32::from_le_bytes(wire[4..8].try_into().unwrap()), 11, "wire must declare v11");+ assert_eq!(wire[INTERPOLATE_BYTE_AT], 0, "v11 interpolate byte must be 0 for bilevel art");+ }++ #[test]+ fn contone_and_explicitly_interpolated_images_stay_smooth() {+ let (doc, page_id) = doc_with_image(+ dictionary! {+ "Type" => "XObject", "Subtype" => "Image",+ "Width" => 2, "Height" => 2,+ "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8,+ },+ vec![0, 85, 170, 255],+ dictionary! {},+ );+ let (interp, wire) = only_image(&doc, page_id);+ assert!(interp, "an 8-bit contone image should be smoothed");+ assert_eq!(wire[INTERPOLATE_BYTE_AT], 1);++ // An explicit /Interpolate true wins even for bilevel art (§8.9.5.1).+ let (doc, page_id) = doc_with_image(+ dictionary! {+ "Type" => "XObject", "Subtype" => "Image",+ "Width" => 2, "Height" => 2,+ "ColorSpace" => "DeviceGray", "BitsPerComponent" => 1,+ "Interpolate" => true,+ },+ vec![0b1000_0000, 0b0100_0000],+ dictionary! {},+ );+ let (interp, _) = only_image(&doc, page_id);+ assert!(interp, "explicit /Interpolate true must be honoured");+ }++ /// Triage probes for two other #321 suspects, at the same pipeline seam:+ /// a `/Rotate 90` page reports swapped display dimensions, and a+ /// `/CropBox` offset page reports the cropped size. (Full coordinate+ /// coverage lives in `geometry`'s tests; this pins the interpret seam.)+ #[test]+ fn rotated_and_cropped_pages_report_display_geometry() {+ let img = || {+ dictionary! {+ "Type" => "XObject", "Subtype" => "Image",+ "Width" => 1, "Height" => 1,+ "ColorSpace" => "DeviceGray", "BitsPerComponent" => 8,+ }+ };+ let (doc, page_id) = doc_with_image(img(), vec![255], dictionary! { "Rotate" => 90 });+ let page = interpret_page(&doc, page_id).expect("interpret rotated");+ assert_eq!((page.width, page.height), (792.0, 612.0), "/Rotate 90 swaps display size");++ let (doc, page_id) = doc_with_image(+ img(),+ vec![255],+ dictionary! { "CropBox" => vec![100.into(), 100.into(), 400.into(), 500.into()] },+ );+ let page = interpret_page(&doc, page_id).expect("interpret cropped");+ assert_eq!((page.width, page.height), (300.0, 400.0), "CropBox ∩ MediaBox is the page");+ }+}
pdf/src/main/rust/src/lib.rs
diff --git a/pdf/src/main/rust/src/lib.rs b/pdf/src/main/rust/src/lib.rsindex b572623666..420a4c4c91 100644--- a/pdf/src/main/rust/src/lib.rs+++ b/pdf/src/main/rust/src/lib.rs@@ -96,6 +96,7 @@ mod perf_tests; #[cfg(test)] mod robustness_tests; #[cfg(test)] mod issue942_tests;+#[cfg(test)] mod issue321_interpolate_tests; #[cfg(test)] mod cov_geometry_tests; #[cfg(test)] mod cov_outlines_tests; #[cfg(test)] mod cov_interpret_tests;
pdf/src/main/rust/src/model.rs
diff --git a/pdf/src/main/rust/src/model.rs b/pdf/src/main/rust/src/model.rsindex 836c92881d..084fa29a14 100644--- a/pdf/src/main/rust/src/model.rs+++ b/pdf/src/main/rust/src/model.rs@@ -85,6 +85,10 @@ pub(crate) enum Prim { alpha: f32, /// Blend mode (from the graphics-state `/BM`) for compositing the image. blend: BlendMode,+ /// Whether the consumer may smooth this image when magnifying it+ /// (§8.9.5.1 `/Interpolate`, decided by `images::image_should_interpolate`).+ /// Serialized in v11.+ interpolate: bool, }, /// A tiling pattern (§8.7.3.3) as ONE cell bitmap repeated periodically, rather than /// as thousands of re-interpreted cells. Renders as a `BitmapShader` with
pdf/src/main/rust/src/reference_diff_tests_part1.rs
diff --git a/pdf/src/main/rust/src/reference_diff_tests_part1.rs b/pdf/src/main/rust/src/reference_diff_tests_part1.rsindex 1978fd773f..d004351700 100644--- a/pdf/src/main/rust/src/reference_diff_tests_part1.rs+++ b/pdf/src/main/rust/src/reference_diff_tests_part1.rs@@ -328,7 +328,7 @@ fn rasterize(page: &PageData, scale: f32) -> (Canvas, Skipped) { let argb = apply_alpha_to_argb(*argb, a as f64); r.fill_contours(&cs, false, argb); }- Prim::Image { ctm, w: iw, h: ih, format, data, alpha, blend } => {+ Prim::Image { ctm, w: iw, h: ih, format, data, alpha, blend, .. } => { if !matches!(blend, BlendMode::Normal) { r.skipped.blended += 1; }
pdf/src/main/rust/src/wire.rs
diff --git a/pdf/src/main/rust/src/wire.rs b/pdf/src/main/rust/src/wire.rsindex e9918cb423..f8106a6335 100644--- a/pdf/src/main/rust/src/wire.rs+++ b/pdf/src/main/rust/src/wire.rs@@ -1,8 +1,8 @@ use crate::*; const WIRE_MAGIC: u32 = 0x50444657; // 'PDFW'-/// The version this serializer EMITS. V10 carries the per-image blend mode (V9 added-/// per-image alpha).+/// The version this serializer EMITS. V11 carries the per-image interpolate flag+/// (V10 added the per-image blend mode, V9 the per-image alpha). /// /// KEEP IN SYNC WITH `SafePdfParser.WIRE_VERSION` in /// `pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfParser.kt`. That constant is the@@ -21,10 +21,10 @@ const WIRE_MAGIC: u32 = 0x50444657; // 'PDFW' /// `u32 len` as interpolate and desyncs every primitive from there on, so the bump and the /// field must land in the same change — and a jump straight from 10 to 12 must write BOTH /// the interpolate byte and whatever v12 adds.-/// `images::image_should_interpolate` already computes the value, but `Prim::Image` does-/// not carry it yet, so nothing serializes it and the parser's pre-v11 default (smooth)-/// applies.-const WIRE_VERSION: u32 = 10;+/// `Prim::Image` carries the value from `images::image_should_interpolate` and this+/// serializer writes it, so bilevel art is no longer smoothed by the parser's+/// pre-v11 default.+const WIRE_VERSION: u32 = 11; #[allow(dead_code)] const WIRE_VERSION_V2: u32 = 2; #[allow(dead_code)]@@ -96,15 +96,15 @@ fn truncate_str_safe(s: &str, max_bytes: usize) -> &str { } } -/// Serialize a page into a compact little-endian buffer v10:+/// Serialize a page into a compact little-endian buffer v11: /// /// ```text-/// header: u32 MAGIC=0x50444657, u32 VERSION=10, f32 pageWidth, f32 pageHeight, u32 primitiveCount+/// header: u32 MAGIC=0x50444657, u32 VERSION=11, f32 pageWidth, f32 pageHeight, u32 primitiveCount /// per primitive: u8 tag, then payload /// 1 Text: f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode (v4), u8 blend (v5), f32 advance (v7), u8 fontFlags (v8: bit0 bold bit1 italic, bits2-3 family 0=sans 1=serif 2=mono, bit4 outline-drawn), f32 hScale (v8) /// 2 Fill: u32 argb, u8 evenOdd, u16 nContours, [u16 nPts, [f32 x,y]...]... (v6), u8 blend (v5) /// 3 Stroke: u32 argb, f32 width, u8 nDash, [f32 dash]..., f32 phase, u8 cap, u8 join, f32 miter, u16 nPts, [f32 x, f32 y]..., u8 blend (v5)-/// 4 Image: 6×f32 ctm, u32 w, u32 h, u8 format, f32 alpha (v9), u8 blend (v10), u8 interpolate (v11, NOT emitted while VERSION is 10), u32 len, [bytes] (format 1=JPEG, 2=raw ARGB words — little-endian, i.e. B,G,R,A bytes in memory, exactly Android's ARGB_8888 layout so the consumer can `copyPixelsFromBuffer` with no swizzle; format 0=RGBA8888 is the legacy layout the serializer no longer emits for this arm, kept decodable on the consumer side)+/// 4 Image: 6×f32 ctm, u32 w, u32 h, u8 format, f32 alpha (v9), u8 blend (v10), u8 interpolate (v11), u32 len, [bytes] (format 1=JPEG, 2=raw ARGB words — little-endian, i.e. B,G,R,A bytes in memory, exactly Android's ARGB_8888 layout so the consumer can `copyPixelsFromBuffer` with no swizzle; format 0=RGBA8888 is the legacy layout the serializer no longer emits for this arm, kept decodable on the consumer side) /// 5 ClipPush: u8 evenOdd, u16 nPts, [f32 x,y]..., u16 nPathOps, [u8 kind, coords]... (path-ops section is v4) /// path-op kinds: 0 Move(2f32) 1 Line(2f32) 2 Cubic(6f32) 3 Close(0) ///@@ -215,7 +215,7 @@ pub fn serialize(page: &PageData) -> Vec<u8> { write_points(&mut buf, pts); buf.push(*blend as u8); // v5 }- Prim::Image { ctm, w, h, format, data, alpha, blend } => {+ Prim::Image { ctm, w, h, format, data, alpha, blend, interpolate } => { buf.push(TAG_IMAGE); for v in ctm { buf.extend_from_slice(&(*v as f32).to_le_bytes());@@ -235,6 +235,7 @@ pub fn serialize(page: &PageData) -> Vec<u8> { // V9 now serializes per-image alpha (from SMask or alpha_fill). buf.extend_from_slice(&alpha.to_le_bytes()); // v9 buf.push(*blend as u8); // v10: image blend mode+ buf.push(if *interpolate { 1 } else { 0 }); // v11: /Interpolate decision // FIX #9: data.len() as u32 truncates >4GB crafted image -> Kotlin OOB read. // Use try_from and cap data to u32::MAX, ensuring length field matches actual bytes written. let (len_u32, data_slice) = match u32::try_from(data.len()) {
pdf/src/main/rust/src/wire_part1.rs
diff --git a/pdf/src/main/rust/src/wire_part1.rs b/pdf/src/main/rust/src/wire_part1.rsindex 296657e0d0..2f93862a1d 100644--- a/pdf/src/main/rust/src/wire_part1.rs+++ b/pdf/src/main/rust/src/wire_part1.rs@@ -348,14 +348,14 @@ mod tests { "Stroke arm width changed", ); - // 4 Image: tag + 6 ctm + w + h + format + alpha + blend + len + payload. No v11- // interpolate byte while WIRE_VERSION is 10 — see the note on that constant.+ // 4 Image: tag + 6 ctm + w + h + format + alpha + blend + interpolate (v11) ++ // len + payload. assert_eq!( arm_len(Prim::Image { ctm: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], w: 1, h: 1, format: 0,- data: vec![1, 2, 3, 4], alpha: 1.0, blend: BlendMode::Normal,+ data: vec![1, 2, 3, 4], alpha: 1.0, blend: BlendMode::Normal, interpolate: false, }),- 1 + 24 + 4 + 4 + 1 + 4 + 1 + 4 + 4,+ 1 + 24 + 4 + 4 + 1 + 4 + 1 + 1 + 4 + 4, "Image arm width changed", ); @@ -440,12 +440,13 @@ mod tests { data, alpha: 1.0, blend: BlendMode::Normal,+ interpolate: true, }], }; // Payload offset: header (20) + tag (1) + ctm (24) + w/h (8). fn payload_at<'a>(buf: &'a [u8]) -> (u8, &'a [u8]) { let format_at = HEADER_LEN + 1 + 24 + 8;- (buf[format_at], &buf[format_at + 1 + 4 + 1 + 4..])+ (buf[format_at], &buf[format_at + 1 + 4 + 1 + 1 + 4..]) } // RGBA red pixel (255,0,0,255) -> ARGB word bytes B,G,R,A. let raw_buf = serialize(&image_page(0, vec![255, 0, 0, 255]));@@ -459,7 +460,7 @@ mod tests { } /// A version bump only means something if the payload changes with it, and the reverse- /// is just as fatal. Pin the emitted Image payload to the exact v10 field list so that+ /// is just as fatal. Pin the emitted Image payload to the exact v11 field list so that /// bumping WIRE_VERSION without writing the v11 interpolate byte — or writing the byte /// without bumping — fails here instead of silently desyncing the decoder. #[test]@@ -475,14 +476,16 @@ mod tests { data: vec![1, 2, 3, 4], alpha: 1.0, blend: BlendMode::Normal,+ interpolate: false, }], }; // header: magic + version + width + height + count. Payload: tag + 6xf32 ctm +- // u32 w + u32 h + u8 format + f32 alpha (v9) + u8 blend (v10) + u32 len + 4 bytes.- let v10_len = (4 + 4 + 4 + 4 + 4) + 1 + 24 + 4 + 4 + 1 + 4 + 1 + 4 + 4;+ // u32 w + u32 h + u8 format + f32 alpha (v9) + u8 blend (v10) + u8 interpolate+ // (v11) + u32 len + 4 bytes.+ let v11_len = (4 + 4 + 4 + 4 + 4) + 1 + 24 + 4 + 4 + 1 + 4 + 1 + 1 + 4 + 4; assert_eq!( (serialize(&page).len(), WIRE_VERSION),- (v10_len, 10),+ (v11_len, 11), "the Image payload and WIRE_VERSION must move together: SafePdfParser.kt reads \ a u8 interpolate between the blend byte and the u32 length once the declared \ version reaches 11"
pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfListingsTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfListingsTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfListingsTest.ktindex 01f1e229cf..1cd67bd1fa 100644--- a/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfListingsTest.kt+++ b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfListingsTest.kt@@ -130,29 +130,28 @@ class SafePdfListingsTest { * WHY THE IMAGE ARM SPECIFICALLY. It is the one primitive Rust pins to an exact length * independently, in `wire::tests::wire_version_matches_the_image_payload_layout`: *- * let v10_len = (4 + 4 + 4 + 4 + 4) + 1 + 24 + 4 + 4 + 1 + 4 + 1 + 4 + 4; // = 67- * assert_eq!((serialize(&page).len(), WIRE_VERSION), (v10_len, 10), ...)+ * let v11_len = (4 + 4 + 4 + 4 + 4) + 1 + 24 + 4 + 4 + 1 + 4 + 1 + 1 + 4 + 4; // = 68+ * assert_eq!((serialize(&page).len(), WIRE_VERSION), (v11_len, 11), ...) *- * for a 1x1 image with four bytes of data. Asserting the same 67 here couples the two:+ * for a 1x1 image with four bytes of data. Asserting the same 68 here couples the two: * change the Image layout in `wire.rs` and that test fails; change it in [WireWriter] and * this one does. Reproducing the arithmetic term by term rather than writing `67` is * deliberate — a bare total would still match if two fields changed by offsetting amounts. *- * VERSION 10, NOT [SafePdfParser.WIRE_VERSION]. Rust EMITS 10; the parser merely- * understands up to 11. Building at the parser's constant would add the v11 interpolate- * byte and describe a stream nothing currently produces.+ * VERSION 11 IS [SafePdfParser.WIRE_VERSION]. Rust EMITS 11 with the v11+ * interpolate byte; building at any older version would describe a stream nothing+ * currently produces. * * RESIDUAL, stated because it is not closed: the other thirteen tags have no Rust-side * length constant to pair with, so they remain transcription-against-transcription. A full * fix is a golden buffer emitted by Rust and checked into the test resources; this covers- * the arm that has actually moved twice (v9 alpha, v10 blend) and is next in line to move- * again (v11 interpolate).+ * the arm that has actually moved three times (v9 alpha, v10 blend, v11 interpolate). */ @Test fun theImageArmMatchesTheByteCountRustSerializes() { val header = 4 + 4 + 4 + 4 + 4- val payload = 1 + 24 + 4 + 4 + 1 + 4 + 1 + 4 + 4- val bytes = WireWriter(version = 10)+ val payload = 1 + 24 + 4 + 4 + 1 + 4 + 1 + 1 + 4 + 4+ val bytes = WireWriter(version = 11) .image(w = 1, h = 1, format = 0, data = ByteArray(4)) .build() assertEquals(@@ -197,14 +196,14 @@ class SafePdfListingsTest { * field by field, not as totals: a bare total still matches when two fields change by * offsetting amounts. *- * VERSION 10, not [SafePdfParser.WIRE_VERSION] — Rust EMITS 10, so the v11 interpolate- * byte is not in the stream and must not be in the arithmetic.+ * VERSION 11 IS [SafePdfParser.WIRE_VERSION] — Rust EMITS 11, so the v11+ * interpolate byte is in the stream and must be in the arithmetic. */ @Test fun everyArmMatchesTheByteCountRustSerializes() { val header = 4 + 4 + 4 + 4 + 4 fun armLen(write: WireWriter.() -> Unit): Int =- WireWriter(version = 10).apply(write).build().size - header+ WireWriter(version = 11).apply(write).build().size - header // Text with an N-byte string: tag + x + y + size + argb + len + N + hasStroke + // strokeArgb + strokeWidth + renderMode + blend + advance + fontFlags + hScale.@@ -226,9 +225,9 @@ class SafePdfListingsTest { "Stroke arm width", ) - // Image: tag + 6 ctm + w + h + format + alpha + blend + len + payload.+ // Image: tag + 6 ctm + w + h + format + alpha + blend + interpolate + len + payload. assertEquals(- 1 + 24 + 4 + 4 + 1 + 4 + 1 + 4 + 4,+ 1 + 24 + 4 + 4 + 1 + 4 + 1 + 1 + 4 + 4, armLen { image(w = 1, h = 1, data = ByteArray(4)) }, "Image arm width", )
pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfParserTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfParserTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfParserTest.ktindex 3ec3b3ef90..53f1f07d75 100644--- a/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfParserTest.kt+++ b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfParserTest.kt@@ -33,14 +33,14 @@ class SafePdfParserTest { } /**- * Rust declares `WIRE_VERSION = 10` and Kotlin understands up to 11. Every tag must+ * Rust declares `WIRE_VERSION = 11` and Kotlin understands up to 11. Every tag must * decode from the version Rust actually emits — a mishandled version renders every page * of every document blank. */ @Test fun theVersionRustActuallyEmitsDecodesEveryTag() { val page = SafePdfParser.parse(- WireWriter(version = 10)+ WireWriter(version = 11) .text(renderMode = 2) .fill() .stroke(dash = floatArrayOf(3f, 2f))