fix(docreader): keep pdfium bitmap alive while copying SMask pixels

to_pil() shares the BGRA buffer; dropping the PdfBitmap before convert
use-after-frees. Copy pixels first, keep opaque RGB/L modes, and log when
render=True falls back to the raw (mask-blind) decode.
main
wizardchen 2026-08-24 14:25:28 +08:00 committed by lyingbug
parent 0fe0b39461
commit f20427df13
2 changed files with 189 additions and 52 deletions

View File

@ -1195,19 +1195,40 @@ def _decode_embedded_image_pil(obj):
object through pdfium's imaging pipeline and carries the mask as an alpha
channel; compositing over white then yields what the page looks like
(JPEG cannot keep alpha, and pages render on white).
The ``PdfBitmap`` is kept alive until pixels are copied: ``to_pil()``
shares the pdfium buffer for RGBA/RGBX/L, and releasing the handle first
would use-after-free. Opaque RGB/L images keep their mode so grayscale
hashes and JPEGs stay single-channel.
"""
from PIL import Image
bitmap = None
try:
pil = obj.get_bitmap(render=True).to_pil()
except Exception:
pil = obj.get_bitmap().to_pil()
if pil.mode in ("RGBA", "LA", "PA"):
pil = pil.convert("RGBA")
if pil.getchannel("A").getextrema()[0] < 255:
background = Image.new("RGBA", pil.size, (255, 255, 255, 255))
pil = Image.alpha_composite(background, pil)
return pil.convert("RGB")
try:
bitmap = obj.get_bitmap(render=True)
except Exception:
logger.warning(
"get_bitmap(render=True) failed; falling back to raw decode",
exc_info=True,
)
_close_pdfium_resource(bitmap)
bitmap = obj.get_bitmap()
pil = bitmap.to_pil()
if pil.mode in ("RGBA", "LA", "PA"):
src_mode = pil.mode
rgba = pil.convert("RGBA")
if rgba.getchannel("A").getextrema()[0] < 255:
background = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
return Image.alpha_composite(background, rgba).convert("RGB")
if src_mode == "LA":
return rgba.convert("L")
return rgba.convert("RGB")
if pil.mode in ("RGB", "L"):
return pil.copy()
return pil.convert("RGB")
finally:
_close_pdfium_resource(bitmap)
def _extract_embedded_images(pdf, classes, raw, base_name: str, quality: int) -> dict:

View File

@ -8,8 +8,10 @@ from a production PDF exported by a plotting tool.
"""
import base64
import gc
import io
import unittest
from unittest.mock import patch
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_raw
@ -24,46 +26,7 @@ PAGE_W, PAGE_H = 612, 792
IMG_W, IMG_H = 120, 90
def _build_smask_pdf() -> bytes:
"""Hand-built PDF: one black RGB image shaped by an SMask circle.
The base plane is entirely black; the SMask is opaque (255) inside a
filled circle and transparent (0) elsewhere, so a viewer shows a black
circle on the white page — and a decoder that drops the mask shows pure
black.
"""
base = b"\x00\x00\x00" * (IMG_W * IMG_H)
cx, cy, radius = IMG_W // 2, IMG_H // 2, 30
mask = bytearray(IMG_W * IMG_H)
for y in range(IMG_H):
for x in range(IMG_W):
if (x - cx) ** 2 + (y - cy) ** 2 <= radius * radius:
mask[y * IMG_W + x] = 255
contents = b"q 480 0 0 360 66 216 cm /Im0 Do Q\n"
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
(
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %d %d] "
b"/Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>"
% (PAGE_W, PAGE_H)
),
b"<< /Length %d >>\nstream\n" % len(contents) + contents + b"endstream",
(
b"<< /Type /XObject /Subtype /Image /Width %d /Height %d "
b"/ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask 6 0 R "
b"/Length %d >>\nstream\n" % (IMG_W, IMG_H, len(base))
+ base
+ b"\nendstream"
),
(
b"<< /Type /XObject /Subtype /Image /Width %d /Height %d "
b"/ColorSpace /DeviceGray /BitsPerComponent 8 /Length %d >>\nstream\n"
% (IMG_W, IMG_H, len(mask))
+ bytes(mask)
+ b"\nendstream"
),
]
def _pdf_from_objects(objects: list) -> bytes:
out = bytearray(b"%PDF-1.7\n")
offsets = []
for i, body in enumerate(objects, start=1):
@ -81,6 +44,72 @@ def _build_smask_pdf() -> bytes:
return bytes(out)
def _page_objects(image_obj: bytes, extra_objs: list | None = None) -> list:
contents = b"q 480 0 0 360 66 216 cm /Im0 Do Q\n"
objects = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
(
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %d %d] "
b"/Resources << /XObject << /Im0 5 0 R >> >> /Contents 4 0 R >>"
% (PAGE_W, PAGE_H)
),
b"<< /Length %d >>\nstream\n" % len(contents) + contents + b"endstream",
image_obj,
]
if extra_objs:
objects.extend(extra_objs)
return objects
def _circle_mask() -> bytes:
cx, cy, radius = IMG_W // 2, IMG_H // 2, 30
mask = bytearray(IMG_W * IMG_H)
for y in range(IMG_H):
for x in range(IMG_W):
if (x - cx) ** 2 + (y - cy) ** 2 <= radius * radius:
mask[y * IMG_W + x] = 255
return bytes(mask)
def _build_smask_pdf(base_rgb=(0, 0, 0)) -> bytes:
"""Hand-built PDF: one RGB image shaped by an SMask circle.
The SMask is opaque (255) inside a filled circle and transparent (0)
elsewhere. A decoder that drops the mask shows the raw base plane only.
"""
r, g, b = base_rgb
base = bytes((r, g, b)) * (IMG_W * IMG_H)
mask = _circle_mask()
image = (
b"<< /Type /XObject /Subtype /Image /Width %d /Height %d "
b"/ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask 6 0 R "
b"/Length %d >>\nstream\n" % (IMG_W, IMG_H, len(base))
+ base
+ b"\nendstream"
)
mask_obj = (
b"<< /Type /XObject /Subtype /Image /Width %d /Height %d "
b"/ColorSpace /DeviceGray /BitsPerComponent 8 /Length %d >>\nstream\n"
% (IMG_W, IMG_H, len(mask))
+ mask
+ b"\nendstream"
)
return _pdf_from_objects(_page_objects(image, [mask_obj]))
def _build_opaque_gray_pdf(level: int = 128) -> bytes:
data = bytes((level,)) * (IMG_W * IMG_H)
image = (
b"<< /Type /XObject /Subtype /Image /Width %d /Height %d "
b"/ColorSpace /DeviceGray /BitsPerComponent 8 /Length %d >>\nstream\n"
% (IMG_W, IMG_H, len(data))
+ data
+ b"\nendstream"
)
return _pdf_from_objects(_page_objects(image))
def _first_image_object(pdf):
for page in pdf:
for obj in page.get_objects():
@ -89,6 +118,17 @@ def _first_image_object(pdf):
raise AssertionError("test PDF has no image object")
def _raw_decode(obj):
bitmap = obj.get_bitmap()
try:
pil = bitmap.to_pil()
if pil.mode in ("RGB", "L"):
return pil.copy()
return pil.convert("RGB")
finally:
bitmap.close()
class DecodeEmbeddedImageTest(unittest.TestCase):
def test_smask_image_composites_over_white(self):
pdf = pdfium.PdfDocument(_build_smask_pdf())
@ -103,7 +143,58 @@ class DecodeEmbeddedImageTest(unittest.TestCase):
# Opaque circle center keeps the base-plane colour (black).
self.assertLess(pil.getpixel((IMG_W // 2, IMG_H // 2))[0], 40)
def test_opaque_image_without_mask_unchanged(self):
def test_colored_smask_keeps_base_color(self):
pdf = pdfium.PdfDocument(_build_smask_pdf(base_rgb=(200, 30, 40)))
try:
pil = _decode_embedded_image_pil(_first_image_object(pdf))
finally:
pdf.close()
self.assertEqual(pil.mode, "RGB")
self.assertGreater(pil.getpixel((2, 2))[0], 200)
center = pil.getpixel((IMG_W // 2, IMG_H // 2))
self.assertGreater(center[0], 150)
self.assertLess(center[1], 80)
self.assertLess(center[2], 80)
def test_opaque_image_matches_raw_pixels(self):
buf = io.BytesIO()
Image.new("RGB", (100, 80), (10, 200, 30)).save(buf, format="PDF")
pdf = pdfium.PdfDocument(buf.getvalue())
try:
obj = _first_image_object(pdf)
raw = _raw_decode(obj)
pil = _decode_embedded_image_pil(obj)
finally:
pdf.close()
self.assertEqual(pil.size, raw.size)
self.assertEqual(pil.mode, raw.mode)
self.assertEqual(pil.tobytes(), raw.tobytes())
def test_opaque_gray_fallback_keeps_l_mode(self):
# render=True typically returns BGRA even for DeviceGray; the raw
# fallback must keep L so grayscale hashes/JPEGs stay single-channel.
pdf = pdfium.PdfDocument(_build_opaque_gray_pdf(128))
try:
obj = _first_image_object(pdf)
raw = _raw_decode(obj)
self.assertEqual(raw.mode, "L")
original = obj.get_bitmap
def _boom(render=False, **kwargs):
if render:
raise RuntimeError("render unavailable")
return original(render=render, **kwargs)
with patch.object(obj, "get_bitmap", side_effect=_boom):
with self.assertLogs("docreader.parser.pdf_parser", level="WARNING"):
pil = _decode_embedded_image_pil(obj)
finally:
pdf.close()
self.assertEqual(pil.mode, "L")
self.assertEqual(pil.getpixel((IMG_W // 2, IMG_H // 2)), 128)
self.assertEqual(pil.tobytes(), raw.tobytes())
def test_decoded_image_survives_bitmap_gc(self):
buf = io.BytesIO()
Image.new("RGB", (100, 80), (10, 200, 30)).save(buf, format="PDF")
pdf = pdfium.PdfDocument(buf.getvalue())
@ -111,8 +202,33 @@ class DecodeEmbeddedImageTest(unittest.TestCase):
pil = _decode_embedded_image_pil(_first_image_object(pdf))
finally:
pdf.close()
self.assertEqual(pil.mode, "RGB")
self.assertEqual(pil.getpixel((50, 40))[1], 200)
gc.collect()
self.assertEqual(pil.getpixel((50, 40)), (10, 200, 30))
def test_render_failure_falls_back_to_raw(self):
buf = io.BytesIO()
Image.new("RGB", (100, 80), (10, 200, 30)).save(buf, format="PDF")
pdf = pdfium.PdfDocument(buf.getvalue())
try:
obj = _first_image_object(pdf)
raw = _raw_decode(obj)
original = obj.get_bitmap
def _boom(render=False, **kwargs):
if render:
raise RuntimeError("render unavailable")
return original(render=render, **kwargs)
with patch.object(obj, "get_bitmap", side_effect=_boom):
with self.assertLogs(
"docreader.parser.pdf_parser", level="WARNING"
) as logs:
pil = _decode_embedded_image_pil(obj)
finally:
pdf.close()
self.assertTrue(any("falling back to raw decode" in m for m in logs.output))
self.assertEqual(pil.mode, raw.mode)
self.assertEqual(pil.tobytes(), raw.tobytes())
class ExtractEmbeddedImagesTest(unittest.TestCase):