Add AVIF thread support

This commit is contained in:
Surma
2021-06-25 00:11:25 +01:00
parent d12b040bd3
commit d4056026fb
7 changed files with 99 additions and 4 deletions

View File

@@ -1,5 +1,13 @@
import { promises as fsp } from 'fs';
import { instantiateEmscriptenWasm, pathify } from './emscripten-utils.js';
import { threads } from 'wasm-feature-detect';
import { cpus } from 'os';
// We use `navigator.hardwareConcurrency` for Emscriptens pthread pool size.
// This is the only workaround I can get working without crying.
(globalThis as any).navigator = {
hardwareConcurrency: cpus().length,
};
interface RotateModuleInstance {
exports: {
@@ -47,6 +55,9 @@ import webpDecWasm from 'asset-url:../../codecs/webp/dec/webp_node_dec.wasm';
// AVIF
import avifEnc from '../../codecs/avif/enc/avif_node_enc.js';
import avifEncWasm from 'asset-url:../../codecs/avif/enc/avif_node_enc.wasm';
import avifEncMt from '../../codecs/avif/enc/avif_node_enc_mt.js';
import avifEncMtWorker from 'chunk-url:../../codecs/avif/enc/avif_node_enc_mt.worker.js';
import avifEncMtWasm from 'asset-url:../../codecs/avif/enc/avif_node_enc_mt.wasm';
import avifDec from '../../codecs/avif/dec/avif_node_dec.js';
import avifDecWasm from 'asset-url:../../codecs/avif/dec/avif_node_dec.wasm';
@@ -325,7 +336,16 @@ export const codecs = {
extension: 'avif',
detectors: [/^\x00\x00\x00 ftypavif\x00\x00\x00\x00/],
dec: () => instantiateEmscriptenWasm(avifDec, avifDecWasm),
enc: () => instantiateEmscriptenWasm(avifEnc, avifEncWasm),
enc: async () => {
if (await threads()) {
return instantiateEmscriptenWasm(
avifEncMt,
avifEncMtWasm,
avifEncMtWorker,
);
}
return instantiateEmscriptenWasm(avifEnc, avifEncWasm);
},
defaultEncoderOptions: {
cqLevel: 33,
cqAlphaLevel: -1,

View File

@@ -1,4 +1,4 @@
import { fileURLToPath } from 'url';
import { fileURLToPath, URL } from 'url';
export function pathify(path: string): string {
if (path.startsWith('file://')) {
@@ -10,10 +10,14 @@ export function pathify(path: string): string {
export function instantiateEmscriptenWasm<T extends EmscriptenWasm.Module>(
factory: EmscriptenWasm.ModuleFactory<T>,
path: string,
workerWasm: string = '',
): Promise<T> {
return factory({
locateFile() {
return pathify(path);
locateFile(requestPath) {
if (requestPath.endsWith('.wasm')) return pathify(path);
if (requestPath.endsWith('.worker.js'))
return new URL(workerWasm).pathname;
return requestPath;
},
});
}

View File

@@ -23,6 +23,11 @@ declare module 'asset-url:../../codecs/resize/pkg/squoosh_resize_bg.wasm' {
export default value;
}
declare module 'chunk-url:../../codecs/avif/enc/avif_node_enc_mt.worker.js' {
const value: string;
export default value;
}
// These don't exist in NodeJS types so we're not able to use them but they are referenced in some emscripten and codec types
// Thus, we need to explicitly assign them to be `never`
// We're also not able to use the APIs that use these types