1
0
Fork 0
mirror of https://github.com/mozilla/pdf.js.git synced 2025-04-22 16:18:08 +02:00

Merge pull request #19525 from calixteman/bug1935076_part2

Provide a js fallback when the wasm version of openjpeg is failing to load (bug 1935076)
This commit is contained in:
Jonas Jenwald 2025-02-22 09:34:40 +01:00 committed by GitHub
commit 6d3bb47655
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 107 additions and 18 deletions

View file

@ -31,18 +31,44 @@ class JpxImage {
static #modulePromise = null;
static #hasJSFallback = false;
static #wasmUrl = null;
static setOptions({ handler, wasmUrl }) {
if (!this.#buffer) {
this.#wasmUrl = wasmUrl || null;
if (wasmUrl === null) {
this.#handler = handler;
}
if (this.#buffer || this.#hasJSFallback || this.#modulePromise) {
return;
}
this.#wasmUrl = wasmUrl || null;
if (wasmUrl === null) {
this.#handler = handler;
}
}
static async #instantiateWasm(imports, successCallback) {
static async #getJsModule(fallbackCallback) {
if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("TESTING")) {
this.#wasmUrl ??= "/build/generic/web/wasm/";
}
const path =
typeof PDFJSDev === "undefined"
? `../${this.#wasmUrl}openjpeg_nowasm_fallback.js`
: `${this.#wasmUrl}openjpeg_nowasm_fallback.js`;
let instance = null;
try {
const mod = await (typeof PDFJSDev === "undefined"
? import(path) // eslint-disable-line no-unsanitized/method
: __non_webpack_import__(path));
instance = mod.default();
} catch (e) {
warn(`JpxImage#getJsModule: ${e}`);
}
this.#hasJSFallback = true;
fallbackCallback(instance);
}
static async #instantiateWasm(fallbackCallback, imports, successCallback) {
const filename = "openjpeg.wasm";
try {
if (!this.#buffer) {
@ -57,9 +83,13 @@ class JpxImage {
}
const results = await WebAssembly.instantiate(this.#buffer, imports);
return successCallback(results.instance);
} catch (reason) {
warn(`JpxImage#instantiateWasm: ${reason}`);
this.#getJsModule(fallbackCallback);
return null;
} finally {
this.#handler = null;
this.#wasmUrl = null;
}
}
@ -67,12 +97,26 @@ class JpxImage {
bytes,
{ numComponents = 4, isIndexedColormap = false, smaskInData = false } = {}
) {
this.#modulePromise ||= OpenJPEG({
warn,
instantiateWasm: this.#instantiateWasm.bind(this),
});
if (!this.#modulePromise) {
const { promise, resolve } = Promise.withResolvers();
const promises = [promise];
if (this.#hasJSFallback) {
this.#getJsModule(resolve);
} else {
promises.push(
OpenJPEG({
warn,
instantiateWasm: this.#instantiateWasm.bind(this, resolve),
})
);
}
this.#modulePromise = Promise.race(promises);
}
const module = await this.#modulePromise;
if (!module) {
throw new JpxError("OpenJPEG failed to initialize");
}
let ptr;
try {