Merge pull request #22587 from calixteman/perf/document-scoped-wasm

Scope the Wasm image decoders and PostScript functions to each document
This commit is contained in:
calixteman
2026-11-23 16:41:47 +01:00
committed by GitHub
14 changed files with 46 additions and 65 deletions
+5 -1
View File
@@ -19,12 +19,15 @@ import { JBig2CCITTFaxImage } from "./jbig2_ccittFax.js";
import { shadow } from "../shared/util.js";
class CCITTFaxStream extends DecodeStream {
constructor(str, maybeLength, params) {
#pdfManager;
constructor(str, maybeLength, params, pdfManager) {
super(maybeLength);
this.stream = str;
this.maybeLength = maybeLength;
this.dict = str.dict;
this.#pdfManager = pdfManager;
if (!(params instanceof Dict)) {
params = Dict.empty;
@@ -63,6 +66,7 @@ class CCITTFaxStream extends DecodeStream {
: this.bytes;
this.buffer = await JBig2CCITTFaxImage.instance.decode(
this.#pdfManager.binaryDataContext,
bytes,
this.dict.get("W", "Width"),
this.dict.get("H", "Height"),
-5
View File
@@ -16,16 +16,11 @@
import { clearPatternCaches } from "./pattern.js";
import { clearPrimitiveCaches } from "./primitives.js";
import { clearUnicodeCaches } from "./unicode.js";
import { WasmImage } from "./wasm_image.js";
function clearGlobalCaches() {
clearPatternCaches();
clearPrimitiveCaches();
clearUnicodeCaches();
// Remove the global `WasmImage` instances,
// since they may hold references to the WebAssembly modules.
WasmImage.cleanup();
}
export { clearGlobalCaches };
+2
View File
@@ -79,6 +79,7 @@ import { StreamsSequenceStream } from "./decode_stream.js";
import { stringToPDFString } from "./string_utils.js";
import { StructTreePage } from "./struct_tree.js";
import { TextLayerFonts } from "./text_layer_font.js";
import { WasmImage } from "./wasm_image.js";
import { XRef } from "./xref.js";
const LETTER_SIZE_MEDIABOX = [0, 0, 612, 792];
@@ -1869,6 +1870,7 @@ class PDFDocument {
}
async cleanup(manuallyTriggered = false) {
WasmImage.cleanup(this.pdfManager.binaryDataContext);
return this.catalog
? this.catalog.cleanup(manuallyTriggered)
: clearGlobalCaches();
+1 -7
View File
@@ -28,18 +28,12 @@ const FunctionType = {
};
class PDFFunctionFactory {
static #useWasm = true;
static setOptions({ useWasm }) {
this.#useWasm = useWasm;
}
constructor({ xref }) {
this.xref = xref;
}
get useWasm() {
return PDFFunctionFactory.#useWasm;
return this.xref.pdfManager.evaluatorOptions.useWasm;
}
async create(fn, parseArray = false) {
+2 -1
View File
@@ -31,8 +31,9 @@ class JBig2CCITTFaxImage extends WasmImage {
);
}
async decode(bytes, width, height, globals, CCITTOptions) {
async decode(context, bytes, width, height, globals, CCITTOptions) {
const module = await this._getModule(
context,
() =>
import(/* webpackChunkName: "jbig2" */ "../../external/jbig2/jbig2.js")
);
+5 -1
View File
@@ -24,13 +24,16 @@ import { shadow } from "../shared/util.js";
* the stream behaves like all the other DecodeStreams.
*/
class Jbig2Stream extends DecodeStream {
constructor(stream, maybeLength, params) {
#pdfManager;
constructor(stream, maybeLength, params, pdfManager) {
super(maybeLength);
this.stream = stream;
this.dict = stream.dict;
this.maybeLength = maybeLength;
this.params = params;
this.#pdfManager = pdfManager;
}
get bytes() {
@@ -85,6 +88,7 @@ class Jbig2Stream extends DecodeStream {
}
}
this.buffer = await JBig2CCITTFaxImage.instance.decode(
this.#pdfManager.binaryDataContext,
bytes,
this.dict.get("Width"),
this.dict.get("Height"),
+2
View File
@@ -32,6 +32,7 @@ class JpxImage extends WasmImage {
}
async decode(
context,
bytes,
{
numComponents,
@@ -43,6 +44,7 @@ class JpxImage extends WasmImage {
const padComponents = numComponents !== undefined;
numComponents ??= 4;
const module = await this._getModule(
context,
() =>
import(
/* webpackChunkName: "openjpeg" */ "../../external/openjpeg/openjpeg.js"
+9 -2
View File
@@ -22,12 +22,15 @@ import { shadow } from "../shared/util.js";
* the stream behaves like all the other DecodeStreams.
*/
class JpxStream extends DecodeStream {
constructor(stream, maybeLength) {
#pdfManager;
constructor(stream, maybeLength, pdfManager) {
super(maybeLength);
this.stream = stream;
this.dict = stream.dict;
this.maybeLength = maybeLength;
this.#pdfManager = pdfManager;
}
get bytes() {
@@ -49,7 +52,11 @@ class JpxStream extends DecodeStream {
return this.buffer;
}
bytes ||= this.bytes;
this.buffer = await JpxImage.instance.decode(bytes, decoderOptions);
this.buffer = await JpxImage.instance.decode(
this.#pdfManager.binaryDataContext,
bytes,
decoderOptions
);
this.bufferLength = this.buffer.length;
this.eof = true;
+4 -3
View File
@@ -807,6 +807,7 @@ class Parser {
return new NullStream();
}
const pdfManager = this.xref?.pdfManager;
try {
switch (name) {
case "Fl":
@@ -838,7 +839,7 @@ class Parser {
return new JpegStream(stream, maybeLength, params);
case "JPX":
case "JPXDecode":
return new JpxStream(stream, maybeLength);
return new JpxStream(stream, maybeLength, pdfManager);
case "A85":
case "ASCII85Decode":
return new Ascii85Stream(stream, maybeLength);
@@ -847,12 +848,12 @@ class Parser {
return new AsciiHexStream(stream, maybeLength);
case "CCF":
case "CCITTFaxDecode":
return new CCITTFaxStream(stream, maybeLength, params);
return new CCITTFaxStream(stream, maybeLength, params, pdfManager);
case "RL":
case "RunLengthDecode":
return new RunLengthStream(stream, maybeLength);
case "JBIG2Decode":
return new Jbig2Stream(stream, maybeLength, params);
return new Jbig2Stream(stream, maybeLength, params, pdfManager);
case "BrotliDecode":
if (params) {
return new PredictorStream(
+1 -20
View File
@@ -29,9 +29,7 @@ import { ImageResizer } from "./image_resizer.js";
import { JpegStream } from "./jpeg_stream.js";
import { OperatorList } from "./operator_list.js";
import { PDFDocument } from "./document.js";
import { PDFFunctionFactory } from "./function.js";
import { Stream } from "./stream.js";
import { WasmImage } from "./wasm_image.js";
/**
* @typedef { LocalPdfManager | NetworkPdfManager } PdfManager
@@ -49,8 +47,6 @@ function parseDocBaseUrl(url) {
}
class BasePdfManager {
static #handlers = new Map();
constructor({
// source,
// disableAutoFetch,
@@ -74,11 +70,6 @@ class BasePdfManager {
this._password = password;
this.enableXfa = enableXfa;
// Keep track of all active `MessageHandler`s to prevent issues with
// Wasm-decoding of images if multiple PDFs are parsed in parallel in one
// worker-thread and `useWorkerFetch = false` is set (fixes issue 22131).
BasePdfManager.#handlers.set(this, handler);
// Check `OffscreenCanvas` and `ImageDecoder` support once,
// rather than repeatedly throughout the worker-thread code.
evaluatorOptions.isOffscreenCanvasSupported &&=
@@ -93,14 +84,6 @@ class BasePdfManager {
ImageResizer.setOptions(evaluatorOptions);
JpegStream.setOptions(evaluatorOptions);
OperatorList.setOptions(evaluatorOptions);
const options = {
...evaluatorOptions,
getHandler: () =>
BasePdfManager.#handlers.values().find(h => !h.destroyed),
};
PDFFunctionFactory.setOptions(options);
WasmImage.setOptions(options);
}
get docId() {
@@ -184,9 +167,7 @@ class BasePdfManager {
this.pdfDocument.xref.encrypt?.setPassword(password);
}
terminate(reason) {
BasePdfManager.#handlers.delete(this);
}
terminate(reason) {}
}
class LocalPdfManager extends BasePdfManager {
+11 -21
View File
@@ -19,22 +19,16 @@ import { WasmLoader } from "./wasm_loader.js";
class WasmImage {
static #instances = new Set();
static #options = { useWasm: true, useWorkerFetch: true, wasmUrl: null };
#modulePromise = null;
static setOptions({ getHandler, useWasm, useWorkerFetch, wasmUrl }) {
WasmImage.#options = { getHandler, useWasm, useWorkerFetch, wasmUrl };
}
#modulePromises = new WeakMap();
// eslint-disable-next-line getter-return
static get instance() {
unreachable("Abstract getter `instance` accessed");
}
static cleanup() {
static cleanup(context) {
for (const instance of WasmImage.#instances) {
instance.#modulePromise = null;
instance.#modulePromises.delete(context);
}
}
@@ -51,12 +45,9 @@ class WasmImage {
WasmImage.#instances.add(this);
}
async #instantiateWasm(failureCallback, imports, successCallback) {
async #instantiateWasm(context, failureCallback, imports, successCallback) {
const loaded = await WasmLoader.load(
{
handler: WasmImage.#options.getHandler?.(),
options: WasmImage.#options,
},
context,
this._filename,
this._noWasmFilename,
instantiate => successCallback({ exports: instantiate(imports) })
@@ -66,23 +57,22 @@ class WasmImage {
}
}
_getModule(loadDecoder) {
if (!this.#modulePromise) {
_getModule(context, loadDecoder) {
return this.#modulePromises.getOrInsertComputed(context, () => {
const { promise, resolve } = createPromiseCapability();
this.#modulePromise = Promise.race([
return Promise.race([
promise,
loadDecoder().then(({ default: createDecoder }) =>
createDecoder({
warn,
instantiateWasm: this.#instantiateWasm.bind(this, resolve),
instantiateWasm: this.#instantiateWasm.bind(this, context, resolve),
})
),
]);
}
return this.#modulePromise;
});
}
async decode(bytes, _params) {
async decode(context, bytes, _params) {
unreachable("Abstract method `decode` called");
}
}
-4
View File
@@ -548,10 +548,6 @@ class MessageHandler {
this.#messageAC?.abort();
this.#messageAC = null;
}
get destroyed() {
return !this.#messageAC;
}
}
export { MessageHandler, wrapReason };
+2
View File
@@ -8135,7 +8135,9 @@ have written that much by now. So, here’s to squashing bugs.`);
// PDF document without any images, but with path-rendering.
const loadingTask2 = getDocument(
buildGetDocumentParams("clippath.pdf", {
useWasm: false,
useWorkerFetch: false,
wasmUrl: null,
worker,
})
);
+2
View File
@@ -155,6 +155,8 @@ class XRefMock {
stream = new NullStream();
pdfManager = { evaluatorOptions: { useWasm: true } };
constructor(array = []) {
for (const { ref, data } of array) {
this.#map.set(ref.toString(), data);