From 43431c68109c0e893ea03b6771c117d9632520e1 Mon Sep 17 00:00:00 2001 From: "valery.bokov" Date: Tue, 8 Sep 2026 21:33:20 +0200 Subject: [PATCH] Increase chunk-size cap in Filter.decode() for large streams --- .../main/java/org/apache/pdfbox/filter/Filter.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/pdfbox/src/main/java/org/apache/pdfbox/filter/Filter.java b/pdfbox/src/main/java/org/apache/pdfbox/filter/Filter.java index a53cd63e520..5018f4dd6a1 100644 --- a/pdfbox/src/main/java/org/apache/pdfbox/filter/Filter.java +++ b/pdfbox/src/main/java/org/apache/pdfbox/filter/Filter.java @@ -279,14 +279,20 @@ public static RandomAccessRead decode(InputStream encoded, List filterLi length = randomAccessWriteBuffer.length(); } // we don't know the size of the decoded stream, just estimate a 4 times bigger size than the encoded stream - // use the estimated stream size as chunk size, use the default chunk size as limit to avoid to big values - if (length <= 0 || length >= RandomAccessReadBuffer.DEFAULT_CHUNK_SIZE_4KB / 4) + // use the estimated stream size as chunk size, capped to avoid excessive per-chunk + // preallocation, but without collapsing back to the tiny default for large streams - + // that would otherwise force thousands of small chunk allocations + if (length <= 0) { length = RandomAccessReadBuffer.DEFAULT_CHUNK_SIZE_4KB; } else { - length = length * 4; + // upper bound for the chunk size estimated from the encoded stream length in decode(), to + // avoid thousands of small chunk allocations for large streams while still bounding the + // worst-case preallocation for a single chunk + final int maxEstimatedChunkSize = 1 << 20; + length = Math.min(length, maxEstimatedChunkSize / 4) * 4; } randomAccessWriteBuffer = new RandomAccessReadWriteBuffer((int) length); output = new RandomAccessOutputStream(randomAccessWriteBuffer);