Files
squoosh/src/codecs/webp/Encoder.worker.ts
Jake Archibald 8006a1a5e7 Memory view rather than pointers (#144). Part of #141.
* Returning an object seems to work well

* This doesn't work

* This does!

* Better cast?

* Updating usage in Squoosh
2018-08-21 09:27:04 +01:00

44 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import webp_enc, { WebPModule } from '../../../codecs/webp_enc/webp_enc';
// Using require() so TypeScript doesnt complain about this not being a module.
import { EncodeOptions } from './encoder';
const wasmBinaryUrl = require('../../../codecs/webp_enc/webp_enc.wasm');
export default class WebPEncoder {
private emscriptenModule: Promise<WebPModule>;
constructor() {
this.emscriptenModule = new Promise((resolve) => {
const m = webp_enc({
// Just to be safe, dont automatically invoke any wasm functions
noInitialRun: false,
locateFile(url: string): string {
// Redirect the request for the wasm binary to whatever webpack gave us.
if (url.endsWith('.wasm')) {
return wasmBinaryUrl;
}
return url;
},
onRuntimeInitialized() {
// An Emscripten is a then-able that, for some reason, `then()`s itself,
// causing an infite loop when you wrap it in a real promise. Deleten the `then`
// prop solves this for now.
// See: https://github.com/kripken/emscripten/blob/incoming/src/postamble.js#L129
// TODO(surma@): File a bug with Emscripten on this.
delete (m as any).then;
resolve(m);
},
});
});
}
async encode(data: ImageData, options: EncodeOptions): Promise<ArrayBuffer> {
const module = await this.emscriptenModule;
const resultView = module.encode(data.data, data.width, data.height, options);
const result = new Uint8Array(resultView);
module.free_result();
return result.buffer as ArrayBuffer;
}
}