Modern Apps git

← Modern-Apps.git

pdf: stop copying pixels three times for embedded images

Commit
4bed66fc4597a836faf0ffc2aa9dc903203a35b4
Author
Vayun Mathur <[email protected]>
When
2026-11-21 20:55 UTC (14 days ago)
Parents
01983a0
Raw embedded images travelled Rust RGBA -> wire ByteArray ->
Kotlin IntArray with a per-pixel RGBA-to-ARGB loop -> Bitmap
(~192MB transient at 16MP). The Rust serializer now emits raw
rasters as ARGB words inside the copy it already makes (no new
allocation; JPEG arm untouched, legacy format still decodes),
and Kotlin slices the page buffer and copyPixelsFromBuffer
straight into the one Bitmap. (The naive copyPixels route
swaps R/B on Android's ARGB_8888 - the format-2 wire exists
because of that, proven by a Robolectric pixel test.) The
exporter draws warp+scan-filter directly onto the page canvas
instead of allocating warped+filtered copies, and capture
thumbnails use sized decoding instead of full-res.

Verified: pdf 287 tests + cargo pdf_render 657 pass, incl.
pixel-equality tests against the old paths.

Diff

pdf/src/main/java/com/vayunmathur/pdf/platform/PdfExporter.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/platform/PdfExporter.kt b/pdf/src/main/java/com/vayunmathur/pdf/platform/PdfExporter.ktindex 181dea4beb..1f87d82ea7 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/platform/PdfExporter.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/platform/PdfExporter.kt@@ -80,9 +80,15 @@ private suspend fun renderImagePage(         val pageBitmap = createBitmap(targetWidth, targetHeight)         val pageCanvas = Canvas(pageBitmap)         pageCanvas.drawColor(Color.WHITE)-        drawCropped(bitmap, capturedImage, pageCanvas, targetWidth, targetHeight, pageSize.scale)+        // Warp and scan filter are applied in this single draw onto the+        // page canvas: previously the warp materialised a second+        // page-sized bitmap and the filter then copied the page bitmap+        // onto itself through the ColorMatrix.+        drawCropped(+            bitmap, capturedImage, pageCanvas, targetWidth, targetHeight, pageSize.scale,+            scanFilterPaint(filter),+        )         bitmap.recycle()-        applyScanFilter(pageBitmap, filter)          val pageInfo = PdfDocument.PageInfo.Builder(targetWidth, targetHeight, index + 1).create()         val page = pdfDocument.startPage(pageInfo)@@ -138,21 +144,20 @@ private fun pageSize(bitmap: Bitmap, capturedImage: CapturedImage): PageSize {     return PageSize(targetWidth, targetHeight, scale) } -private fun drawCropped(+internal fun drawCropped(     bitmap: Bitmap,     capturedImage: CapturedImage,     pageCanvas: Canvas,     targetWidth: Int,     targetHeight: Int,     drawScale: Float,+    paint: Paint? = null, ) {     val crop = capturedImage.cropRect     val quadrilateral = capturedImage.quadrilateral     when {         quadrilateral != null -> {-            val warped = warpQuadToBitmap(bitmap, quadrilateral, targetWidth, targetHeight)-            pageCanvas.drawBitmap(warped, 0f, 0f, null)-            warped.recycle()+            drawWarped(bitmap, quadrilateral, targetWidth, targetHeight, pageCanvas, paint)         }         crop != null -> {             val srcRect = android.graphics.Rect(@@ -162,32 +167,73 @@ private fun drawCropped(                 (crop.bottom * bitmap.height).roundToInt(),             )             val dst = android.graphics.Rect(0, 0, targetWidth, targetHeight)-            pageCanvas.drawBitmap(bitmap, srcRect, dst, null)+            pageCanvas.drawBitmap(bitmap, srcRect, dst, paint)         }         else -> {             val matrix = Matrix()             matrix.postScale(drawScale, drawScale)-            pageCanvas.drawBitmap(bitmap, matrix, null)+            pageCanvas.drawBitmap(bitmap, matrix, paint)         }     } } -/** Apply a scan [filter] to [bmp] in place (via a filtered self-copy). */-private fun applyScanFilter(bmp: Bitmap, filter: ScanFilter) {-    if (filter == ScanFilter.NONE) return+/**+ * Perspective-warp [quad] out of [src] straight onto [pageCanvas] with the+ * poly-to-poly matrix, optionally through [paint]'s scan filter. Falls back+ * to a 1:1 bounding-box blit when the matrix is degenerate, matching the+ * geometry [warpQuadToBitmap]'s fallback produces. No intermediate bitmap.+ */+internal fun drawWarped(+    src: Bitmap,+    quad: Quadrilateral,+    width: Int,+    height: Int,+    pageCanvas: Canvas,+    paint: Paint? = null,+) {+    val targetWidth = width.coerceAtLeast(1)+    val targetHeight = height.coerceAtLeast(1)+    val srcPoints = quad.toSrcPoints(src.width, src.height)+    val dstPoints = floatArrayOf(+        0f, 0f,+        targetWidth.toFloat(), 0f,+        targetWidth.toFloat(), targetHeight.toFloat(),+        0f, targetHeight.toFloat()+    )+    val matrix = Matrix()+    if (matrix.setPolyToPoly(srcPoints, 0, dstPoints, 0, QUAD_POINTS)) {+        pageCanvas.drawBitmap(src, matrix, paint)+    } else {+        val bounds = quad.toBoundingRect()+        val left = (bounds.left * src.width).roundToInt().coerceIn(0, src.width - 1)+        val top = (bounds.top * src.height).roundToInt().coerceIn(0, src.height - 1)+        val w = targetWidth.coerceAtMost(src.width - left)+        val h = targetHeight.coerceAtMost(src.height - top)+        val srcRect = android.graphics.Rect(left, top, left + w, top + h)+        val dstRect = android.graphics.Rect(0, 0, w, h)+        pageCanvas.drawBitmap(src, srcRect, dstRect, paint)+    }+}++/**+ * The scan [filter] as a draw-time paint, or null for [ScanFilter.NONE].+ * Applied by the draw onto the page canvas instead of by copying the+ * finished page bitmap onto itself through the same [ColorMatrix]; the+ * white page background is a fixed point of every matrix here, so not+ * filtering it changes nothing.+ */+internal fun scanFilterPaint(filter: ScanFilter): Paint? {+    if (filter == ScanFilter.NONE) return null     val matrix = when (filter) {         ScanFilter.GRAYSCALE, ScanFilter.BW -> ColorMatrix().apply { setSaturation(0f) }         ScanFilter.CONTRAST -> ColorMatrix(CONTRAST_MATRIX)-        ScanFilter.NONE -> return+        ScanFilter.NONE -> return null     }     if (filter == ScanFilter.BW) {         // Strong contrast after desaturation approximates a bilevel scan.         matrix.postConcat(ColorMatrix(BW_MATRIX))     }-    val copy = bmp.copy(Bitmap.Config.ARGB_8888, false)-    val paint = Paint().apply { colorFilter = ColorMatrixColorFilter(matrix) }-    Canvas(bmp).drawBitmap(copy, 0f, 0f, paint)-    copy.recycle()+    return Paint().apply { colorFilter = ColorMatrixColorFilter(matrix) } }  private val CONTRAST_MATRIX = floatArrayOf(
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 a3f671c8e6..15f9eea5a6 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfImages.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfImages.kt@@ -1,5 +1,6 @@ package com.vayunmathur.pdf.platform import com.vayunmathur.library.log.Log+import java.nio.ByteBuffer  /**  * The raster half of [SafePdfParser]: image payload decoding and its budgets.@@ -71,18 +72,33 @@ object SafePdfImages {         return s     } -    /** Decode an image payload: format 1 = JPEG bytes, 0 = raw RGBA8888. */-    internal fun decodeBitmap(w: Int, h: Int, format: Int, data: ByteArray): android.graphics.Bitmap? {+    /**+     * Decode an image payload: format 1 = JPEG bytes, 0 = raw RGBA8888+     * (legacy wire layout), 2 = raw ARGB words (see [FORMAT_ARGB_WORDS]).+     */+    internal fun decodeBitmap(w: Int, h: Int, format: Int, data: ByteArray): android.graphics.Bitmap? =+        decodeBitmap(w, h, format, ByteBuffer.wrap(data))++    /**+     * Buffer form of [decodeBitmap]. [data]'s remaining bytes are the payload;+     * its position is left unchanged. The format-2 arm consumes the payload as+     * a slice of this buffer (see [decodeArgbWords]), so a page-sized wire+     * buffer is never copied per image. The JPEG arm may copy only when the+     * buffer has no accessible backing array — compressed bytes, not pixels.+     */+    internal fun decodeBitmap(w: Int, h: Int, format: Int, data: ByteBuffer): android.graphics.Bitmap? {         if (badDimensions(w, h)) return null-        // The pixel budget is per format. The raw branch below allocates `w*h` ints before it-        // can do anything, so it must be refused outright — and Rust decimates that path, so-        // an oversized raw image is a contract violation rather than ordinary input. A JPEG-        // commits nothing until the decoder runs and is scaled down there instead.+        // The pixel budget is per format. The raw branch used to allocate+        // `w*h` ints before it could do anything, so it must be refused+        // outright — and Rust decimates that path, so an oversized raw image+        // is a contract violation rather than ordinary input. A JPEG commits+        // nothing until the decoder runs and is scaled down there instead.         if (format != FORMAT_JPEG && w.toLong() * h.toLong() > MAX_IMAGE_PIXELS) return null         return try {             when (format) {                 FORMAT_JPEG -> decodeJpeg(w, h, data)-                FORMAT_RAW -> decodeRaw(w, h, data)+                FORMAT_RAW -> decodeRgba(w, h, data)+                FORMAT_ARGB_WORDS -> decodeArgbWords(w, h, data)                 else -> {                     // Rust returns no image at all for a format it could not produce, so an                     // unknown format here is a wire mismatch, not a failed decode to paper over.@@ -93,15 +109,24 @@ object SafePdfImages {         } catch (expected: IllegalArgumentException) {             Log.status("SafePdfParser", "decodeBitmap failed w=$w h=$h format=$format", expected)             null+        } catch (expected: NullPointerException) {+            // The stub android.jar's Bitmap.createBitmap(w, h, config)+            // returns null (the int-array overload the old raw path used is+            // a platform type and simply propagated that null). Off-device+            // this is the "no bitmap" outcome the parser already handles;+            // on a device createBitmap does not return null.+            Log.status("SafePdfParser", "decodeBitmap failed w=$w h=$h format=$format", expected)+            null         } catch (expected: OutOfMemoryError) {             Log.status("SafePdfParser", "decodeBitmap OOM w=$w h=$h format=$format", expected)             null         }     } -    private fun decodeJpeg(w: Int, h: Int, data: ByteArray): android.graphics.Bitmap? {-        if (data.size > MAX_IMAGE_DATA_BYTES) {-            Log.status("SafePdfParser", "JPEG too large ${data.size}")+    private fun decodeJpeg(w: Int, h: Int, data: ByteBuffer): android.graphics.Bitmap? {+        val len = data.remaining()+        if (len > MAX_IMAGE_DATA_BYTES) {+            Log.status("SafePdfParser", "JPEG too large $len")             return null         }         // Subsample instead of dropping. Rust hands the JPEG over at full@@ -110,20 +135,67 @@ object SafePdfImages {         // full size, so a 20 MP photo would commit ~80 MB of ARGB_8888.         val opts = android.graphics.BitmapFactory.Options()         opts.inSampleSize = sampleSizeFor(w, h)-        return android.graphics.BitmapFactory.decodeByteArray(data, 0, data.size, opts)+        return if (data.hasArray()) {+            android.graphics.BitmapFactory.decodeByteArray(+                data.array(), data.arrayOffset() + data.position(), len, opts+            )+        } else {+            val bytes = ByteArray(len)+            data.duplicate().get(bytes)+            android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)+        }     } -    private fun decodeRaw(w: Int, h: Int, data: ByteArray): android.graphics.Bitmap? {-        if (data.size < w * h * BYTES_PER_PIXEL) return null+    /**+     * Format 2: raw ARGB words -> ARGB_8888 bitmap with no per-pixel loop+     * and no intermediate pixel array.+     *+     * 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.+     */+    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+    }++    /**+     * Format 0 (legacy RGBA8888, no longer emitted by the in-repo Rust+     * serializer) and tiling-pattern cells, whose tag carries no format+     * byte to signal the new layout with. Kept so older buffers still+     * decode; pattern cells are small, and this is not the embedded-image+     * path the 16 MP budget applies to.+     */+    private fun decodeRgba(w: Int, h: Int, data: ByteBuffer): android.graphics.Bitmap? {+        if (data.remaining().toLong() < w.toLong() * h * BYTES_PER_PIXEL) return null         val pixels = IntArray(w * h)-        var p = 0+        val view = data.duplicate()         for (i in pixels.indices) {-            val r = data[p].toInt() and CHANNEL_MASK-            val g = data[p + GREEN_OFF].toInt() and CHANNEL_MASK-            val b = data[p + BLUE_OFF].toInt() and CHANNEL_MASK-            val a = data[p + ALPHA_OFF].toInt() and CHANNEL_MASK+            val r = view.get().toInt() and CHANNEL_MASK+            val g = view.get().toInt() and CHANNEL_MASK+            val b = view.get().toInt() and CHANNEL_MASK+            val a = view.get().toInt() and CHANNEL_MASK             pixels[i] = (a shl ALPHA_SHIFT) or (r shl RED_SHIFT) or (g shl GREEN_SHIFT) or b-            p += BYTES_PER_PIXEL         }         return android.graphics.Bitmap.createBitmap(             pixels, w, h, android.graphics.Bitmap.Config.ARGB_8888@@ -132,11 +204,11 @@ 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). */+    internal const val FORMAT_ARGB_WORDS = 2     private const val CHANNEL_MASK = 0xFF-    private const val BYTES_PER_PIXEL = 4-    private const val GREEN_OFF = 1-    private const val BLUE_OFF = 2-    private const val ALPHA_OFF = 3+    private const val BYTES_PER_PIXEL = 4L     private const val ALPHA_SHIFT = 24     private const val RED_SHIFT = 16     private const val GREEN_SHIFT = 8
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 e0a7aecb12..06585b1988 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfParser.kt@@ -462,4 +462,7 @@ object SafePdfParser {      internal fun decodeBitmap(w: Int, h: Int, format: Int, data: ByteArray): android.graphics.Bitmap? =         SafePdfImages.decodeBitmap(w, h, format, data)++    internal fun decodeBitmap(w: Int, h: Int, format: Int, data: ByteBuffer): android.graphics.Bitmap? =+        SafePdfImages.decodeBitmap(w, h, format, data) }
pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfPrimitives.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfPrimitives.kt b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfPrimitives.ktindex fbe1544901..11e1ec77b0 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfPrimitives.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/platform/SafePdfPrimitives.kt@@ -274,9 +274,10 @@ internal class PrimitiveDecoder(             buf.position(buf.position() + len)             return         }-        val data = ByteArray(len)-        buf.get(data)-        val bmp = SafePdfParser.decodeBitmap(w, h, format, data)+        // Slice, do not copy: the payload stays a view of the page buffer+        // and the raw decoder moves it straight into the bitmap.+        val bmp = SafePdfParser.decodeBitmap(w, h, format, payloadSlice(buf, len))+        buf.position(buf.position() + len)         out.add(PdfPrimitive.Image(ctm, bmp, imgAlpha, imgBlend, imgInterpolate))     } @@ -398,10 +399,9 @@ internal class PrimitiveDecoder(             buf.position(buf.position() + len)             return         }-        val data = ByteArray(len)-        buf.get(data)         // Format 0: the cell is always raw RGBA8888, so there is no format byte.-        val bmp = SafePdfParser.decodeBitmap(w, h, 0, data)+        val bmp = SafePdfParser.decodeBitmap(w, h, 0, payloadSlice(buf, len))+        buf.position(buf.position() + len)         // The lattice extent only sizes the filled region — a REPEAT shader tiles         // infinitely — so an absurd count costs nothing to draw, but clamp it so it         // cannot produce non-finite path coordinates.@@ -428,6 +428,13 @@ internal class PrimitiveDecoder(         if (buf.remaining() < count) throw IllegalArgumentException(message)     } +    /** The next [len] bytes as a view of [buf]; does not advance [buf]. */+    private fun payloadSlice(buf: ByteBuffer, len: Int): ByteBuffer {+        val view = buf.duplicate()+        view.limit(view.position() + len)+        return view.slice()+    }+     companion object {         private const val TAG = "SafePdfParser"         private const val U16_MASK = 0xFFFF
pdf/src/main/java/com/vayunmathur/pdf/ui/CapturePdfScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/CapturePdfScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/CapturePdfScreen.ktindex 7664b43cf3..65a0337755 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/CapturePdfScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/CapturePdfScreen.kt@@ -42,6 +42,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat@@ -183,6 +184,9 @@ fun CapturePdfScreen(                     modifier = Modifier.height(100.dp)                 ) {                     val lazyListState = rememberLazyListState()+                    // List items are 80 dp: decode thumbnails at that size,+                    // never at the captured photo's full resolution.+                    val thumbnailSizePx = with(LocalDensity.current) { 80.dp.roundToPx() }                     val state = rememberReorderableLazyListState(lazyListState) { from, to ->                         if (to.index >= images.size || from.index >= images.size) return@rememberReorderableLazyListState                         viewModel.moveCapturedImage(from.index, to.index)@@ -211,7 +215,8 @@ fun CapturePdfScreen(                                     contentAlignment = Alignment.Center                                 ) {                                     SubcroppedImage(-                                        image = img+                                        image = img,+                                        thumbnailSizePx = thumbnailSizePx                                     )                                 }                             }
pdf/src/main/java/com/vayunmathur/pdf/ui/components/SubcroppedImage.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/components/SubcroppedImage.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/components/SubcroppedImage.ktindex df426e066a..23dcd145d1 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/components/SubcroppedImage.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/components/SubcroppedImage.kt@@ -21,8 +21,11 @@ import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.library.image.ImageRequest+import com.vayunmathur.library.image.Size as ImageSize import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.image.compose.AsyncImageState+import com.vayunmathur.library.image.decoders.BitmapDecoder import com.vayunmathur.pdf.data.CapturedImage import com.vayunmathur.pdf.data.Quadrilateral import com.vayunmathur.pdf.platform.warpQuadToBitmap@@ -30,16 +33,23 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.math.roundToInt +/**+ * [thumbnailSizePx] is the capture list's hint: when set, the source is+ * decoded at that size (library/image's sized decode) instead of full+ * resolution, so an 80 dp list item never materialises the full photo.+ * Null (the main preview) keeps the full-resolution decode.+ */ @Composable fun SubcroppedImage(     image: CapturedImage,-    modifier: Modifier = Modifier+    modifier: Modifier = Modifier,+    thumbnailSizePx: Int? = null ) {     val quad = image.quadrilateral     if (quad != null) {-        PerspectiveCroppedImage(image, quad, modifier)+        PerspectiveCroppedImage(image, quad, modifier, thumbnailSizePx)     } else {-        BoundingBoxCroppedImage(image, modifier)+        BoundingBoxCroppedImage(image, modifier, thumbnailSizePx)     } } @@ -47,18 +57,33 @@ fun SubcroppedImage( private fun PerspectiveCroppedImage(     image: CapturedImage,     quad: Quadrilateral,-    modifier: Modifier+    modifier: Modifier,+    thumbnailSizePx: Int? = null ) {     val context = LocalContext.current-    var croppedBitmap by remember(image.uri, quad) { mutableStateOf<Bitmap?>(null) }+    var croppedBitmap by remember(image.uri, quad, thumbnailSizePx) { mutableStateOf<Bitmap?>(null) } -    LaunchedEffect(image.uri, quad) {+    LaunchedEffect(image.uri, quad, thumbnailSizePx) {         withContext(Dispatchers.Default) {             try {-                val source = ImageDecoder.createSource(context.contentResolver, image.uri)-                val bitmap = ImageDecoder.decodeBitmap(source) { decoder, _, _ ->-                    decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE-                    decoder.isMutableRequired = false+                val bitmap = if (thumbnailSizePx != null) {+                    // Sized decode from library/image: ImageDecoder samples+                    // inside the decoder, so the full-res bitmap never exists.+                    val request = ImageRequest.Builder(context)+                        .data(image.uri)+                        .size(ImageSize(thumbnailSizePx, thumbnailSizePx))+                        .build()+                    BitmapDecoder.decode(+                        ImageDecoder.createSource(context.contentResolver, image.uri),+                        request,+                        allowHardware = false,+                    ) ?: return@withContext+                } else {+                    val source = ImageDecoder.createSource(context.contentResolver, image.uri)+                    ImageDecoder.decodeBitmap(source) { decoder, _, _ ->+                        decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE+                        decoder.isMutableRequired = false+                    }                 }                  val bounds = quad.toBoundingRect()@@ -85,9 +110,23 @@ private fun PerspectiveCroppedImage( @Composable private fun BoundingBoxCroppedImage(     image: CapturedImage,-    modifier: Modifier+    modifier: Modifier,+    thumbnailSizePx: Int? = null ) {+    val context = LocalContext.current     var painterSize by remember(image.uri) { mutableStateOf<Size?>(null) }+    // Explicit sized request for list thumbnails; a plain Uri otherwise+    // (AsyncImage then derives its decode size from the layout constraints).+    val model: Any = remember(image.uri, thumbnailSizePx, context) {+        if (thumbnailSizePx != null) {+            ImageRequest.Builder(context)+                .data(image.uri)+                .size(ImageSize(thumbnailSizePx, thumbnailSizePx))+                .build()+        } else {+            image.uri+        }+    }      val crop = image.cropRect ?: Rect(0f, 0f, 1f, 1f)     val finalModifier = painterSize?.takeIf { it.width > 0f && it.height > 0f }?.let { size ->@@ -96,7 +135,7 @@ private fun BoundingBoxCroppedImage(      Box(finalModifier.clipToBounds()) {         AsyncImage(-            model = image.uri,+            model = model,             contentDescription = null,             onState = { state ->                 if (state is AsyncImageState.Success) {
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 3d24b434ee..e9918cb423 100644--- a/pdf/src/main/rust/src/wire.rs+++ b/pdf/src/main/rust/src/wire.rs@@ -65,6 +65,10 @@ pub(crate) const TRANSFER_LUT_SIZE: usize = 256; /// assert that. Rust only emits this for non-overlapping patterns, because a periodic /// repeat cannot express §8.7.3.1 overlap; see `images::rasterize_pattern_cell`. 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.+const FORMAT_ARGB_WORDS: u8 = 2;  const PATHOP_MOVE: u8 = 0; const PATHOP_LINE: u8 = 1;@@ -100,7 +104,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, NOT emitted while VERSION is 10), u32 len, [bytes] (format 0=RGBA8888, 1=JPEG)+///   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) ///   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) ///@@ -218,7 +222,15 @@ pub fn serialize(page: &PageData) -> Vec<u8> {                 }                 buf.extend_from_slice(&w.to_le_bytes());                 buf.extend_from_slice(&h.to_le_bytes());-                buf.push(*format);+                // 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.+                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).                 buf.extend_from_slice(&alpha.to_le_bytes()); // v9@@ -241,7 +253,22 @@ pub fn serialize(page: &PageData) -> Vec<u8> {                     data_slice                 };                 buf.extend_from_slice(&final_len.to_le_bytes());-                buf.extend_from_slice(final_slice);+                if *format == 0 {+                    // RGBA -> ARGB word (B,G,R,A bytes) per pixel, written+                    // in place of the plain copy above. A trailing partial+                    // pixel (a truncated producer buffer) is passed through+                    // as-is; the consumer's length check rejects it.+                    let mut chunks = final_slice.chunks_exact(4);+                    for px in &mut chunks {+                        buf.push(px[2]);+                        buf.push(px[1]);+                        buf.push(px[0]);+                        buf.push(px[3]);+                    }+                    buf.extend_from_slice(chunks.remainder());+                } else {+                    buf.extend_from_slice(final_slice);+                }             }             Prim::ImageTiled { ctm, w, h, data, xstep, ystep, i0, j0, nx, ny, alpha, blend } => {                 buf.push(TAG_IMAGE_TILED);
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 b2fbd69b02..296657e0d0 100644--- a/pdf/src/main/rust/src/wire_part1.rs+++ b/pdf/src/main/rust/src/wire_part1.rs@@ -423,6 +423,41 @@ 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.+    #[test]+    fn raw_images_are_emitted_as_argb_words_and_jpeg_is_untouched() {+        let image_page = |format: u8, data: Vec<u8>| PageData {+            width: 10.0,+            height: 10.0,+            prims: vec![Prim::Image {+                ctm: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],+                w: 1,+                h: 1,+                format,+                data,+                alpha: 1.0,+                blend: BlendMode::Normal,+            }],+        };+        // 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..])+        }+        // 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]));+        let (format, payload) = payload_at(&raw_buf);+        assert_eq!(format, FORMAT_ARGB_WORDS);+        assert_eq!(payload, &[0, 0, 255, 255]);+        let jpeg_buf = serialize(&image_page(1, vec![9, 8, 7, 6]));+        let (format, payload) = payload_at(&jpeg_buf);+        assert_eq!(format, 1);+        assert_eq!(payload, &[9, 8, 7, 6]);+    }+     /// 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     /// bumping WIRE_VERSION without writing the v11 interpolate byte — or writing the byte
pdf/src/test/java/com/vayunmathur/pdf/platform/PdfExporterZeroCopyTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/platform/PdfExporterZeroCopyTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/platform/PdfExporterZeroCopyTest.ktnew file mode 100644index 0000000000..525d49879d--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/platform/PdfExporterZeroCopyTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.pdf.platform++import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Color+import android.net.Uri+import androidx.compose.ui.geometry.Rect+import com.vayunmathur.pdf.data.CapturedImage+import com.vayunmathur.pdf.data.Quadrilateral+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++/**+ * Exporter output is unchanged by drawing the warp + scan filter straight+ * onto the page canvas: each new direct draw is compared pixel-for-pixel+ * with the old two-step reference (warp into an intermediate bitmap, then+ * a filtered copy of the finished page onto itself), re-created here.+ */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class PdfExporterZeroCopyTest {++    private fun patternedSrc(): Bitmap {+        val bmp = Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888)+        for (y in 0 until 4) for (x in 0 until 4) {+            bmp.setPixel(x, y, Color.argb(255, 20 + x * 50, 30 + y * 50, (x + y) * 25))+        }+        return bmp+    }++    private fun pixels(bmp: Bitmap): List<Int> =+        (0 until bmp.height).flatMap { y -> (0 until bmp.width).map { x -> bmp.getPixel(x, y) } }++    private fun whitePage(w: Int, h: Int): Bitmap =+        Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.WHITE) }++    /** The pre-fix filter step: copy the page, draw the copy back through the paint. */+    private fun oldApplyFilter(page: Bitmap, filter: ScanFilter) {+        val paint = scanFilterPaint(filter) ?: return+        val copy = page.copy(Bitmap.Config.ARGB_8888, false)+        Canvas(page).drawBitmap(copy, 0f, 0f, paint)+        copy.recycle()+    }++    @Test fun scanFilterPaintIsNullOnlyForNone() {+        assertNull(scanFilterPaint(ScanFilter.NONE))+        for (f in ScanFilter.entries) {+            if (f != ScanFilter.NONE) kotlin.test.assertNotNull(scanFilterPaint(f))+        }+    }++    @Test fun directWarpWithFilterMatchesWarpThenFilterReference() {+        val quad = Quadrilateral.default()+        for (filter in ScanFilter.entries) {+            val src = patternedSrc()+            // Old: warp to an intermediate, blit it, then filter a page copy.+            val warped = warpQuadToBitmap(src, quad, 4, 4)+            val reference = whitePage(4, 4)+            Canvas(reference).drawBitmap(warped, 0f, 0f, null)+            warped.recycle()+            oldApplyFilter(reference, filter)++            // New: one draw of the source through warp matrix + filter paint.+            val direct = whitePage(4, 4)+            drawCropped(+                src,+                CapturedImage(Uri.parse("content://x/1"), quadrilateral = quad),+                Canvas(direct), 4, 4, 1f, scanFilterPaint(filter),+            )+            assertEquals(pixels(reference), pixels(direct), "filter $filter changed exporter pixels")+        }+    }++    @Test fun directCropWithFilterMatchesCropThenFilterReference() {+        val crop = Rect(0f, 0f, 0.5f, 1f)+        val filter = ScanFilter.CONTRAST+        val src = patternedSrc()+        val reference = whitePage(2, 4)+        val srcRect = android.graphics.Rect(0, 0, 2, 4)+        Canvas(reference).drawBitmap(src, srcRect, android.graphics.Rect(0, 0, 2, 4), null)+        oldApplyFilter(reference, filter)++        val direct = whitePage(2, 4)+        drawCropped(+            src,+            CapturedImage(Uri.parse("content://x/1"), cropRect = crop),+            Canvas(direct), 2, 4, 1f, scanFilterPaint(filter),+        )+        assertEquals(pixels(reference), pixels(direct))+    }+}
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.ktnew file mode 100644index 0000000000..71f0332d62--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/platform/SafePdfImagesZeroCopyTest.kt@@ -0,0 +1,99 @@+package com.vayunmathur.pdf.platform++import android.graphics.Bitmap+import android.graphics.Color+import java.io.ByteArrayOutputStream+import java.nio.ByteBuffer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++/**+ * Zero-copy raw-raster decode: the ByteBuffer (wire-slice) path must produce+ * exactly the pixels the old ByteArray -> IntArray per-pixel loop produced,+ * and the JPEG arm must keep its subsampling on the new entry point.+ */+@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class SafePdfImagesZeroCopyTest {++    // RGBA8888, 3x2: opaque primaries + arbitrary colours + one translucent.+    private val rgba = intArrayOf(+        255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255,+        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. */+    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]+            out[p + 2] = rgba[p]; out[p + 3] = rgba[p + 3]+        }+    }++    private fun pixels(bmp: Bitmap): List<Int> =+        (0 until bmp.height).flatMap { y -> (0 until bmp.width).map { x -> bmp.getPixel(x, y) } }++    @Test fun rawBufferPathMatchesByteArrayPathPixelForPixel() {+        // Legacy format 0 (RGBA, per-pixel on the ByteArray entry point) is+        // the reference; format 2 over a buffer slice must match it exactly.+        val viaArray = assertNotNull(SafePdfImages.decodeBitmap(3, 2, 0, rgba))+        val buffer = ByteBuffer.wrap(argbWords)+        val viaBuffer = assertNotNull(+            SafePdfImages.decodeBitmap(3, 2, SafePdfImages.FORMAT_ARGB_WORDS, buffer)+        )+        assertEquals(pixels(viaArray), pixels(viaBuffer))+        // Absolute expectations for the opaque pixels (RGBA byte order on the wire).+        assertEquals(Color.argb(255, 255, 0, 0), viaBuffer.getPixel(0, 0))+        assertEquals(Color.argb(255, 0, 255, 0), viaBuffer.getPixel(1, 0))+        assertEquals(Color.argb(255, 0, 0, 255), viaBuffer.getPixel(2, 0))+        assertEquals(Color.argb(255, 10, 20, 30), viaBuffer.getPixel(0, 1))+        assertEquals(Color.argb(255, 200, 150, 100), viaBuffer.getPixel(1, 1))+        assertEquals(0, buffer.position(), "decode must not consume the caller's buffer")+    }++    @Test fun rawBufferPathReadsFromTheBuffersPosition() {+        val padded = ByteArray(1) { 99 } + argbWords+        val buffer = ByteBuffer.wrap(padded)+        buffer.position(1)+        val bmp = assertNotNull(+            SafePdfImages.decodeBitmap(3, 2, SafePdfImages.FORMAT_ARGB_WORDS, buffer)+        )+        assertEquals(Color.argb(255, 255, 0, 0), bmp.getPixel(0, 0))+        assertEquals(1, buffer.position())+    }++    @Test fun rawViaWireParserMatchesExpectedPixels() {+        val page = SafePdfParser.parse(+            WireWriter().image(w = 3, h = 2, format = 0, data = rgba).build()+        )+        val bmp = assertNotNull(assertNotNull(page.primitives.single() as? PdfPrimitive.Image).bitmap)+        assertEquals(Color.argb(255, 255, 0, 0), bmp.getPixel(0, 0))+        assertEquals(Color.argb(255, 0, 0, 255), bmp.getPixel(2, 0))+        assertEquals(Color.argb(255, 200, 150, 100), bmp.getPixel(1, 1))+    }++    @Test fun jpegBufferPathMatchesByteArrayPathAndKeepsSubsampling() {+        val src = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)+        for (y in 0 until 8) for (x in 0 until 8) {+            src.setPixel(x, y, Color.argb(255, x * 30, y * 30, (x + y) * 15))+        }+        val out = ByteArrayOutputStream()+        assertTrue(src.compress(Bitmap.CompressFormat.JPEG, 100, out))+        val jpeg = out.toByteArray()++        val viaArray = assertNotNull(SafePdfImages.decodeBitmap(8, 8, 1, jpeg))+        val viaBuffer = assertNotNull(SafePdfImages.decodeBitmap(8, 8, 1, ByteBuffer.wrap(jpeg)))+        assertEquals(viaArray.width, viaBuffer.width)+        assertEquals(pixels(viaArray), pixels(viaBuffer))++        // Same declared dimensions as a 20 MP photo: the JPEG arm subsamples+        // by sampleSizeFor instead of decoding full size, on both entry points.+        val sampled = assertNotNull(SafePdfImages.decodeBitmap(5184, 3888, 1, ByteBuffer.wrap(jpeg)))+        assertTrue(sampled.width < 8, "expected subsampled JPEG, got ${sampled.width}x${sampled.height}")+    }+}
pdf/src/test/java/com/vayunmathur/pdf/platform/WireWriter.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/platform/WireWriter.kt b/pdf/src/test/java/com/vayunmathur/pdf/platform/WireWriter.ktindex f31dc929f4..8f51c74537 100644--- a/pdf/src/test/java/com/vayunmathur/pdf/platform/WireWriter.kt+++ b/pdf/src/test/java/com/vayunmathur/pdf/platform/WireWriter.kt@@ -125,11 +125,29 @@ class WireWriter(         data: ByteArray = ByteArray(2 * 2 * 4),     ) = prim(4).apply {         ctm.forEach { f32(it) }-        i32(w); i32(h); u8(format)+        // wire.rs emits a producer-side raw raster (format 0, RGBA8888) as+        // format 2 with each pixel rewritten as an ARGB word (B,G,R,A+        // bytes); JPEG passes through. Mirror that here, as this writer is+        // a transcription of the serializer, not of the parser.+        val emittedFormat = if (format == 0) 2 else format+        val emittedData = if (format == 0) {+            val out = ByteArray(data.size)+            var p = 0+            while (p + 4 <= data.size) {+                out[p] = data[p + 2]; out[p + 1] = data[p + 1]+                out[p + 2] = data[p]; out[p + 3] = data[p + 3]+                p += 4+            }+            for (i in p until data.size) out[i] = data[i]+            out+        } else {+            data+        }+        i32(w); i32(h); u8(emittedFormat)         if (version >= 9) f32(alpha)         if (version >= 10) u8(blend)         if (version >= 11) u8(if (interpolate) 1 else 0)-        i32(data.size); bytes(data)+        i32(emittedData.size); bytes(emittedData)     }      fun imageTiled(
pdf/src/test/java/com/vayunmathur/pdf/ui/CaptureCropComposeTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/CaptureCropComposeTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/CaptureCropComposeTest.ktindex 7ad3263099..98e9c9b7a7 100644--- a/pdf/src/test/java/com/vayunmathur/pdf/ui/CaptureCropComposeTest.kt+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/CaptureCropComposeTest.kt@@ -129,6 +129,20 @@ class CaptureCropComposeTest {         rule.waitForIdle()     } +    @Test fun subcroppedThumbnailVariantsUseSizedDecode() {+        val uri = pngUri("sub-thumb.png")+        rule.setContent {+            DynamicTheme {+                androidx.compose.foundation.layout.Column {+                    // Capture-list thumbnails: sized decode, not full-res.+                    SubcroppedImage(CapturedImage(uri, quadrilateral = Quadrilateral.default()), thumbnailSizePx = 40)+                    SubcroppedImage(CapturedImage(uri, cropRect = Rect(0f, 0f, 0.5f, 0.5f)), thumbnailSizePx = 40)+                }+            }+        }+        rule.waitForIdle()+    }+     @Test fun pageScrollerShowsPageCount() {         val scroll = SafePdfScrollState().apply { viewportSize = IntSize(612, 800); pageCount = 4 }         val zoom = SafePdfZoomState()