Modern Apps git

← Modern-Apps.git

pdf: fix red/blue swap when reopening captured PDFs

Commit
4696cbf84fe0c4f90ae23fd5e231c02b19f59921
Author
Vayun Mathur <[email protected]>
When
2026-12-02 03:12 UTC (4 days ago)
Parents
db16c07
A captured page saved via PdfExporter is written by Skia as a
FlateDecode image with an ICCBased sRGB colour space, so on reopen
the Rust renderer decodes it to a raw raster and ships it as wire
format 2: one little-endian ARGB word per pixel (0xAARRGGBB, i.e.
B,G,R,A bytes).

Root cause: SafePdfImages.decodeArgbWords fed those words to
Bitmap.copyPixelsFromBuffer on the claim that they are byte-for-byte
the ARGB_8888 bitmap layout. On a real device that call reads the
buffer in R,G,B,A memory order, so red rendered blue and vice versa
on every captured page. JPEG-in-PDF pages were unaffected because
they bypass this arm via the DCT passthrough, and the Robolectric
unit test could not catch it because its graphics stack reads the
same buffer as B,G,R,A. Device probes confirmed both halves: the
saved PDF's sample bytes match the source patches to +-1 (sRGB and
Display P3 sources alike), and copyPixelsFromBuffer(R,G,B,A bytes)
yields red on device while (B,G,R,A bytes) yields blue.

Fix: read format-2 payloads as the words they are - a bulk
little-endian IntBuffer get into the same IntArray the legacy
format-0 path has always used, then Bitmap.createBitmap(ints).
Int-based Bitmap APIs have identical colour semantics on device
and in Robolectric. The false bitmap-layout claim is corrected in
the wire-format documentation on both sides; no wire bytes change.

Tests: new Rust capture_color_tests drives eight known colour
patches through a Skia-shaped (FlateDecode, ICCBased) document,
interpret_page and wire::serialize and requires them back within
+-2 as ARGB words. New device test
PdfExporterDeviceTest.capturedPdfReopensWithFaithfulColours does
the full save-and-reopen round trip for PNG (+-4) and JPEG (+-12)
sources on an emulator. Existing SafePdfImagesZeroCopyTest now
documents why it alone cannot pin the byte order.

Verified: cargo test -p pdf_render green (677 passed, incl. the
new round-trip); :pdf:testDevUnitTest green; cargo fmt clean.
Lint report, stated explicitly: :pdf:lint and
:pdf:lintVitalRelease are RED at HEAD with the identical 6 errors
(5x RouteScreenshotCoverage in Route.kt, 1x ScaffoldSearch in
SafePdfViewerChrome.kt) before and after this change - none in
touched files, so this diff adds no lint findings. The pre-existing
device failure savePdfToUriBadSourceFailsCleanly fails identically
on clean HEAD; the new colour device test passes.

Diff

pdf/AGENTS.md
diff --git a/pdf/AGENTS.md b/pdf/AGENTS.mdindex 7154b3ebc4..00e4d1ee66 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 2 carries raw rasters as little-endian ARGB *words* (`0xAARRGGBB`); Kotlin must read them as words (int-based Bitmap APIs), never `Bitmap.copyPixelsFromBuffer` — on a real device that reads ARGB_8888 memory as R,G,B,A bytes and swaps R/B (captured scans are FlateDecode, so they all hit this arm; JPEG pages pass through untouched), while Robolectric reads the buffer the other way and cannot catch the swap. The device round-trip is pinned in `PdfExporterDeviceTest.capturedPdfReopensWithFaithfulColours` - 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 hands native a file descriptor (`SafePdfDocument.acquireDocumentFd` -> `PdfNative.openDocumentFd`): Rust dups and mmaps it, so no whole-file copy exists in the Kotlin heap or across JNI and file size alone never refuses an open; that one attempt classifies Opened / NeedsPassword / Failed (incl. not-a-PDF). Providers without a descriptor fall back to spooling the stream to a cache file in chunks (O(chunk) memory) and opening its descriptor. Cut-and-glue appends take the same descriptor path (`appendPdfFd`). The byte[] native API remains for small in-memory documents and keeps its own native size guard. Redaction presence is probed lazily once editing starts, not at open
pdf/src/androidTest/java/com/vayunmathur/pdf/ui/PdfExporterDeviceTest.kt
diff --git a/pdf/src/androidTest/java/com/vayunmathur/pdf/ui/PdfExporterDeviceTest.kt b/pdf/src/androidTest/java/com/vayunmathur/pdf/ui/PdfExporterDeviceTest.ktindex f32256da2d..6d87ef4789 100644--- a/pdf/src/androidTest/java/com/vayunmathur/pdf/ui/PdfExporterDeviceTest.kt+++ b/pdf/src/androidTest/java/com/vayunmathur/pdf/ui/PdfExporterDeviceTest.kt@@ -77,6 +77,71 @@ class PdfExporterDeviceTest {         savePdfToUri(ctx, listOf(CapturedImage(Uri.fromFile(pngFile("page3.png")))), Uri.fromFile(File(ctx.cacheDir, "out-ocr.pdf")), ScanFilter.NONE, addOcr = true)     } } +    /**+     * Colour round-trip: known patches -> capture save -> reopen through+     * the app's own viewer -> rendered pixels. This is the regression test+     * for the captured-PDF colour shift: Skia writes captured pages as+     * FlateDecode raw rasters, which the Rust renderer returns as wire+     * format 2 (ARGB words); the old consumer fed those words to+     * `Bitmap.copyPixelsFromBuffer`, whose on-device ARGB_8888 byte order+     * is R,G,B,A, swapping every red patch to blue. Robolectric decodes+     * that call the other way round, so only a device test can pin this.+     */+    @Test+    fun capturedPdfReopensWithFaithfulColours() { runBlocking {+        val patches = intArrayOf(+            Color.rgb(255, 0, 0), Color.rgb(0, 255, 0), Color.rgb(0, 0, 255),+            Color.rgb(255, 128, 0), Color.rgb(0, 128, 192), Color.rgb(128, 128, 128),+            Color.rgb(232, 180, 150), Color.rgb(32, 48, 64),+        )+        val srcBmp = Bitmap.createBitmap(320, 40, Bitmap.Config.ARGB_8888)+        val srcCanvas = android.graphics.Canvas(srcBmp)+        patches.forEachIndexed { i, c ->+            srcCanvas.drawRect(+                i * 40f, 0f, (i + 1) * 40f, 40f,+                android.graphics.Paint().apply { color = c },+            )+        }+        // PNG is lossless, so its round-trip must be tight; JPEG (the+        // camera-capture source) gets the wider band its encode earns.+        val cases = listOf(+            Triple("png", Bitmap.CompressFormat.PNG, 4),+            Triple("jpg", Bitmap.CompressFormat.JPEG, 12),+        )+        for ((name, format, tolerance) in cases) {+            val src = File(ctx.cacheDir, "colour-$name.${if (name == "jpg") "jpg" else "png"}")+            src.outputStream().use { srcBmp.compress(format, 95, it) }+            val out = File(ctx.cacheDir, "colour-$name.pdf")+            assertTrue(+                "save $name",+                savePdfToUri(ctx, listOf(CapturedImage(Uri.fromFile(src))), Uri.fromFile(out)),+            )+            val doc = com.vayunmathur.pdf.platform.SafePdfDocument.open(ctx, Uri.fromFile(out))+            assertTrue("reopen $name", doc != null)+            val page = doc!!.renderPage(0)+            val bmp = page?.primitives+                ?.filterIsInstance<com.vayunmathur.pdf.platform.PdfPrimitive.Image>()+                ?.firstOrNull()?.bitmap+            assertTrue("rendered image $name", bmp != null)+            patches.forEachIndexed { i, want ->+                val x = ((i + 0.5) * bmp!!.width / patches.size).toInt()+                val got = bmp.getPixel(x, bmp.height / 2)+                for ((chan, w, g) in listOf(+                    Triple("R", Color.red(want), Color.red(got)),+                    Triple("G", Color.green(want), Color.green(got)),+                    Triple("B", Color.blue(want), Color.blue(got)),+                )) {+                    assertTrue(+                        "$name patch $i channel $chan: want $w, got $g " ++                            "(an R/B swap renders patch 0 blue and patch 2 red)",+                        kotlin.math.abs(w - g) <= tolerance,+                    )+                }+            }+            doc.close()+        }+    } }+     @Test     fun warpQuadOnDevice() {         val src = Bitmap.createBitmap(40, 40, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.BLUE) }
pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfImages.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfImages.kt b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfImages.ktindex 15f9eea5a6..d3b8a2fe0b 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfImages.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfImages.kt@@ -147,36 +147,36 @@ object SafePdfImages {     }      /**-     * Format 2: raw ARGB words -> ARGB_8888 bitmap with no per-pixel loop-     * and no intermediate pixel array.+     * Format 2: raw ARGB words -> ARGB_8888 bitmap with no per-pixel loop.      *-     * Before (format 0, the only raw layout): wire bytes -> per-image-     * `ByteArray` -> `IntArray(w*h)` (one RGBA->ARGB iteration per pixel)-     * -> bitmap: at the 16 MP cap that is 64 MB + 64 MB transient on top of-     * the 64 MB bitmap. Android stores ARGB_8888 pixels as little-endian-     * ARGB words (B,G,R,A bytes in memory), which the wire's RGBA8888 bytes-     * are NOT — a plain [android.graphics.Bitmap.copyPixelsFromBuffer] over-     * RGBA swaps R and B (pinned by `SafePdfImagesZeroCopyTest`). So the-     * Rust serializer now emits format 2: each pixel as an ARGB word, which-     * is byte-for-byte the bitmap's in-memory layout. The caller hands a-     * slice/view of the already-materialised wire buffer; we allocate only-     * the bitmap and let `copyPixelsFromBuffer` move the bytes.+     * The wire payload is one little-endian ARGB word per pixel (bytes+     * B,G,R,A; the int value is `0xAARRGGBB`). It must be read AS WORDS,+     * through the int-based Bitmap APIs whose colour semantics are defined+     * identically on every runtime — never through+     * [android.graphics.Bitmap.copyPixelsFromBuffer]. That call interprets+     * the buffer in the bitmap's in-memory byte order, which for ARGB_8888+     * on a real device is R,G,B,A (device-verified: feeding it these+     * B,G,R,A bytes renders red as blue — the captured-scan colour swap),+     * while Robolectric's graphics stack interprets the same bytes as+     * B,G,R,A, which is why the old copyPixelsFromBuffer version passed+     * every unit test and still swapped R/B on device. Captured PDFs hit+     * this arm on every page (Skia writes them FlateDecode, so Rust+     * decodes them to raw rasters); JPEG-in-PDF pages bypass it via the+     * format-1 passthrough, which is why only captures shifted.+     *+     * The transfer is a bulk [java.nio.IntBuffer] get out of a duplicate of+     * the caller's slice (its position is left unchanged), so the payload+     * is never copied to a per-image ByteArray; the one IntArray matches+     * what the legacy format-0 path below has always allocated.      */     private fun decodeArgbWords(w: Int, h: Int, data: ByteBuffer): android.graphics.Bitmap? {         if (data.remaining().toLong() < w.toLong() * h * BYTES_PER_PIXEL) return null-        val bitmap = android.graphics.Bitmap.createBitmap(w, h, android.graphics.Bitmap.Config.ARGB_8888)-        // The wire carries straight (unpremultiplied) alpha, while a bitmap's-        // storage is premultiplied by default: copying the bytes in without-        // this flag would have draw/getPixel un-premultiply them a second-        // time and brighten every translucent pixel. The flag relabels the-        // storage without converting it, so drawing premultiplies once,-        // exactly as the int-array path did.-        bitmap.setPremultiplied(false)-        // copyPixelsFromBuffer consumes from the buffer's position, so hand-        // it a duplicate: the caller's position must stay where the next-        // primitive starts being measured from.-        bitmap.copyPixelsFromBuffer(data.duplicate())-        return bitmap+        val pixels = IntArray(w * h)+        val view = data.duplicate().order(java.nio.ByteOrder.LITTLE_ENDIAN)+        view.asIntBuffer().get(pixels)+        return android.graphics.Bitmap.createBitmap(+            pixels, w, h, android.graphics.Bitmap.Config.ARGB_8888+        )     }      /**@@ -205,7 +205,7 @@ object SafePdfImages {     private const val FORMAT_JPEG = 1     private const val FORMAT_RAW = 0 -    /** Raw pixels as little-endian ARGB words (B,G,R,A bytes in memory). */+    /** Raw pixels as little-endian ARGB words (int value `0xAARRGGBB`). */     internal const val FORMAT_ARGB_WORDS = 2     private const val CHANNEL_MASK = 0xFF     private const val BYTES_PER_PIXEL = 4L
pdf/src/main/rust/src/capture_color_tests.rs
diff --git a/pdf/src/main/rust/src/capture_color_tests.rs b/pdf/src/main/rust/src/capture_color_tests.rsnew file mode 100644index 0000000000..69db46aa6b--- /dev/null+++ b/pdf/src/main/rust/src/capture_color_tests.rs@@ -0,0 +1,151 @@+//! Synthetic round-trip for the captured-scan colour shift.+//!+//! A captured page saved through `PdfExporter` comes back as a Skia-written+//! PDF whose image is `FlateDecode` with an `[/ICCBased ...]` sRGB profile+//! (device-verified against `android.graphics.pdf.PdfDocument` output:+//! `/Width 842 /Height 105 /ColorSpace [/ICCBased 5 0 R] /Filter+//! /FlateDecode`, sample bytes identical to the source patches to +-1).+//! Rust decodes that to a raw raster, so the page reaches the consumer as+//! wire format 2 — one little-endian ARGB word per pixel. The regression+//! was at that seam: the consumer fed the words to+//! `Bitmap.copyPixelsFromBuffer`, which on a real device reads ARGB_8888+//! memory as R,G,B,A bytes, so every red patch rendered blue and vice+//! versa (JPEG-in-PDF pages, which pass through as format 1, never+//! shifted — which is why only captures looked wrong).+//!+//! This test drives a known colour-patch image through the real pipeline+//! (`interpret_page` -> `wire::serialize`), then decodes the payload+//! exactly as the fixed consumer does (little-endian ARGB words) and+//! requires every patch back within a tight tolerance. It also pins the+//! payload's word order directly, so a future "optimisation" that emits+//! bitmap-memory bytes instead fails here rather than on a phone.++#[cfg(test)]+mod capture_color {+    use crate::wire::serialize;+    use crate::*;+    use lopdf::content::Operation;++    /// The eight patches, in order: saturated primaries (an R/B swap is+    /// unmissable on these), orange/teal (a swap moves both channels), a+    /// mid grey (swap-invariant control), a skin tone and a dark slate.+    const PATCHES: [(u8, u8, u8); 8] = [+        (255, 0, 0),+        (0, 255, 0),+        (0, 0, 255),+        (255, 128, 0),+        (0, 128, 192),+        (128, 128, 128),+        (232, 180, 150),+        (32, 48, 64),+    ];+    const PATCH_W: u32 = 10;+    const W: u32 = PATCH_W * 8;+    const H: u32 = 10;++    fn flate(data: &[u8]) -> Vec<u8> {+        use flate2::write::ZlibEncoder;+        use std::io::Write;+        let mut enc = ZlibEncoder::new(Vec::new(), flate2::Compression::fast());+        enc.write_all(data).expect("flate write");+        enc.finish().expect("flate finish")+    }++    /// One-page document shaped like Skia's capture output: a single+    /// FlateDecode, ICCBased (no /Alternate, /N 3) image filling the page.+    fn captured_doc() -> (Document, ObjectId) {+        let mut samples = Vec::with_capacity((W * H * 3) as usize);+        for _y in 0..H {+            for (r, g, b) in PATCHES {+                for _x in 0..PATCH_W {+                    samples.extend_from_slice(&[r, g, b]);+                }+            }+        }+        let mut doc = Document::with_version("1.4");+        // The profile bytes are never parsed by the renderer (only /N and+        // /Alternate are read); the dict shape is what Skia emits.+        let icc_id = doc.add_object(Stream::new(dictionary! { "N" => 3 }, vec![0u8; 16]));+        let img_id = doc.add_object(Stream::new(+            dictionary! {+                "Type" => "XObject", "Subtype" => "Image",+                "Width" => W, "Height" => H,+                "ColorSpace" => Object::Array(vec![+                    Object::Name(b"ICCBased".to_vec()), Object::Reference(icc_id),+                ]),+                "BitsPerComponent" => 8, "Filter" => "FlateDecode",+            },+            flate(&samples),+        ));+        let content = Content {+            operations: vec![+                Operation::new("q", vec![]),+                Operation::new(+                    "cm",+                    vec![200.into(), 0.into(), 0.into(), 100.into(), 0.into(), 0.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 page_id = doc.add_object(dictionary! {+            "Type" => "Page", "Parent" => pages_id,+            "MediaBox" => vec![0.into(), 0.into(), 200.into(), 100.into()],+            "Resources" => dictionary! { "XObject" => dictionary! { "Im0" => img_id } },+            "Contents" => content_id,+        });+        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)+    }++    /// The format-2 payload of the page's only image, decoded from the wire+    /// buffer at its documented offset (see `wire::serialize`).+    fn image_payload(wire: &[u8]) -> (u8, u32, u32, &[u8]) {+        // header (20) + tag (1) + ctm (24) = w at 45; format after w/h.+        let rd32 = |at: usize| u32::from_le_bytes(wire[at..at + 4].try_into().unwrap());+        let (w, h) = (rd32(45), rd32(49));+        let format = wire[53];+        let len = rd32(53 + 1 + 4 + 1 + 1) as usize;+        let start = 53 + 1 + 4 + 1 + 1 + 4;+        (format, w, h, &wire[start..start + len])+    }++    #[test]+    fn captured_patch_round_trip_keeps_colours() {+        let (doc, page_id) = captured_doc();+        let page = interpret_page(&doc, page_id).expect("interpret captured page");+        let wire = serialize(&page);+        let (format, w, h, payload) = image_payload(&wire);+        assert_eq!(format, 2, "a decoded raw raster must leave as format 2 (ARGB words)");+        assert_eq!((w, h), (W, H));+        assert_eq!(payload.len(), (W * H * 4) as usize);+        for (i, &(r, g, b)) in PATCHES.iter().enumerate() {+            // Patch centre, read as the fixed consumer reads it: one+            // little-endian ARGB word per pixel.+            let x = (i as u32) * PATCH_W + PATCH_W / 2;+            let at = (((H / 2) * W + x) * 4) as usize;+            let word = u32::from_le_bytes(payload[at..at + 4].try_into().unwrap());+            let (pr, pg, pb) =+                (((word >> 16) & 0xFF) as u8, ((word >> 8) & 0xFF) as u8, (word & 0xFF) as u8);+            assert_eq!(((word >> 24) & 0xFF) as u8, 255, "patch {i} must stay opaque");+            for (want, got, chan) in [(r, pr, "R"), (g, pg, "G"), (b, pb, "B")] {+                assert!(+                    (want as i32 - got as i32).abs() <= 2,+                    "patch {i} channel {chan}: want {want}, got {got} \+                     (an R/B swap would put red at 255 in B, not R)"+                );+            }+        }+    }+}
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 d68a36507e..051c320fd2 100644--- a/pdf/src/main/rust/src/lib.rs+++ b/pdf/src/main/rust/src/lib.rs@@ -79,6 +79,8 @@ pub(crate) use draw::*; mod images; pub(crate) use images::*; +#[cfg(test)]+mod capture_color_tests; #[cfg(test)] mod cov_annotations_tests; #[cfg(test)]
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 aa31bdf1af..a1bf23de50 100644--- a/pdf/src/main/rust/src/wire.rs+++ b/pdf/src/main/rust/src/wire.rs@@ -67,7 +67,8 @@ pub(crate) const TRANSFER_LUT_SIZE: usize = 256; const TAG_IMAGE_TILED: u8 = 14; /// Wire format byte for a raw raster as little-endian ARGB words (tag 4 only; /// tag 14 carries no format byte and stays RGBA8888). Twin of-/// `SafePdfImages.FORMAT_ARGB_WORDS` in Kotlin.+/// `SafePdfImages.FORMAT_ARGB_WORDS` in Kotlin. Words, not bitmap-memory+/// bytes: see the tag-4 note in [`serialize`]. const FORMAT_ARGB_WORDS: u8 = 2;  const PATHOP_MOVE: u8 = 0;@@ -104,7 +105,7 @@ fn truncate_str_safe(s: &str, max_bytes: usize) -> &str { ///   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), 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 — one little-endian `0xAARRGGBB` word per pixel, i.e. B,G,R,A bytes; the consumer must read them AS WORDS through the int-based Bitmap APIs, never `copyPixelsFromBuffer`, whose ARGB_8888 byte order on a real device is R,G,B,A and would swap R/B; 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) ///@@ -247,11 +248,12 @@ pub fn serialize(page: &PageData) -> Vec<u8> {                 // Raw rasters (the producer's format 0, RGBA8888) are emitted                 // as format 2, ARGB words: writing B,G,R,A per pixel here —                 // inside the copy this serializer already makes into the wire-                // buffer — lets the consumer move the payload straight into-                // an ARGB_8888 Bitmap via copyPixelsFromBuffer instead of a-                // per-pixel RGBA->ARGB loop over an IntArray. No extra pass-                // or allocation: the bytes are written once, in final order.-                // JPEG (1) and anything else pass through untouched.+                // buffer — lets the consumer bulk-read little-endian ARGB+                // words instead of a per-pixel RGBA->ARGB loop. The payload+                // is WORDS, not bitmap memory: `copyPixelsFromBuffer` would+                // read it in the device bitmap's R,G,B,A byte order and swap+                // R/B (the captured-scan colour shift). JPEG (1) and anything+                // else pass through untouched.                 buf.push(if *format == 0 { FORMAT_ARGB_WORDS } else { *format });                 // FIX #10: previously `alpha: _` was ignored, causing opaque rendering for transparent images.                 // V9 now serializes per-image alpha (from SMask or alpha_fill).
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 84540df7ea..860ed98dae 100644--- a/pdf/src/main/rust/src/wire_part1.rs+++ b/pdf/src/main/rust/src/wire_part1.rs@@ -423,10 +423,13 @@ mod tests {         );     } -    /// Raw rasters leave the serializer as format 2 (ARGB words, B,G,R,A-    /// bytes) so the Kotlin consumer can `copyPixelsFromBuffer` them with-    /// no per-pixel swizzle; JPEG payloads are untouched. The byte count-    /// does not change — only the format byte and the channel order.+    /// Raw rasters leave the serializer as format 2 (ARGB words: one+    /// little-endian `0xAARRGGBB` word, i.e. B,G,R,A bytes) so the Kotlin+    /// consumer can bulk-read them as words with no per-pixel swizzle;+    /// JPEG payloads are untouched. The byte count does not change — only+    /// the format byte and the channel order. The payload is words, not+    /// bitmap memory: a `copyPixelsFromBuffer` consumer reads it in the+    /// device's R,G,B,A bitmap byte order and swaps R/B.     #[test]     fn raw_images_are_emitted_as_argb_words_and_jpeg_is_untouched() {         let image_page = |format: u8, data: Vec<u8>| PageData {
pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfImagesZeroCopyTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfImagesZeroCopyTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfImagesZeroCopyTest.ktindex 71f0332d62..867ed89cfd 100644--- a/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfImagesZeroCopyTest.kt+++ b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfImagesZeroCopyTest.kt@@ -27,7 +27,16 @@ class SafePdfImagesZeroCopyTest {         10, 20, 30, 255, 200, 150, 100, 255, 12, 34, 56, 128,     ).map { it.toByte() }.toByteArray() -    /** The same pixels as [rgba], in format 2's ARGB-word (B,G,R,A) byte order. */+    /**+     * The same pixels as [rgba], in format 2's ARGB-word byte order+     * (little-endian `0xAARRGGBB` words, i.e. B,G,R,A bytes). The decoder+     * must read these AS WORDS: on a real device `copyPixelsFromBuffer`+     * interprets a raw buffer in ARGB_8888's R,G,B,A memory order and+     * would render the red pixel below as blue (device-verified in+     * `PdfExporterDeviceTest.capturedPdfReopensWithFaithfulColours`;+     * Robolectric reads the buffer the other way, so this test alone+     * cannot catch that swap).+     */     private val argbWords: ByteArray = ByteArray(rgba.size).also { out ->         for (p in rgba.indices step 4) {             out[p] = rgba[p + 2]; out[p + 1] = rgba[p + 1]