Compare commits

..

2 Commits

Author SHA1 Message Date
Surma
f4f97abf9d Testing lol 2021-08-10 08:28:12 -04:00
Surma
7c9d3d6ba6 Compile with -s MINIMAL_RUNTIME=1 2021-08-10 07:31:16 -04:00
115 changed files with 751 additions and 1342 deletions

View File

@@ -4,7 +4,6 @@ import { program } from 'commander/esm.mjs';
import JSON5 from 'json5'; import JSON5 from 'json5';
import path from 'path'; import path from 'path';
import { promises as fsp } from 'fs'; import { promises as fsp } from 'fs';
import { cpus } from 'os';
import ora from 'ora'; import ora from 'ora';
import kleur from 'kleur'; import kleur from 'kleur';
@@ -76,9 +75,7 @@ async function getInputFiles(paths) {
for (const inputPath of paths) { for (const inputPath of paths) {
const files = (await fsp.lstat(inputPath)).isDirectory() const files = (await fsp.lstat(inputPath)).isDirectory()
? (await fsp.readdir(inputPath, { withFileTypes: true })) ? (await fsp.readdir(inputPath, {withFileTypes: true})).filter(dirent => dirent.isFile()).map(dirent => path.join(inputPath, dirent.name))
.filter((dirent) => dirent.isFile())
.map((dirent) => path.join(inputPath, dirent.name))
: [inputPath]; : [inputPath];
for (const file of files) { for (const file of files) {
try { try {
@@ -104,7 +101,7 @@ async function getInputFiles(paths) {
async function processFiles(files) { async function processFiles(files) {
files = await getInputFiles(files); files = await getInputFiles(files);
const imagePool = new ImagePool(cpus().length); const imagePool = new ImagePool();
const results = new Map(); const results = new Map();
const progress = progressTracker(results); const progress = progressTracker(results);
@@ -119,8 +116,7 @@ async function processFiles(files) {
let decoded = 0; let decoded = 0;
let decodedFiles = await Promise.all( let decodedFiles = await Promise.all(
files.map(async (file) => { files.map(async (file) => {
const buffer = await fsp.readFile(file); const image = imagePool.ingestImage(file);
const image = imagePool.ingestImage(buffer);
await image.decoded; await image.decoded;
results.set(image, { results.set(image, {
file, file,
@@ -182,7 +178,7 @@ async function processFiles(files) {
const outputPath = path.join( const outputPath = path.join(
program.opts().outputDir, program.opts().outputDir,
path.basename(originalFile, path.extname(originalFile)) + path.basename(originalFile, path.extname(originalFile)) +
program.opts().suffix, program.opts().suffix
); );
for (const output of Object.values(image.encodedWith)) { for (const output of Object.values(image.encodedWith)) {
const outputFile = `${outputPath}.${(await output).extension}`; const outputFile = `${outputPath}.${(await output).extension}`;

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -1 +1 @@
"use strict";var Module={};var initializedJS=false;function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};function moduleLoaded(){}self.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;(e.data.urlOrBlob?import(e.data.urlOrBlob):import("./avif_enc_mt.js")).then(function(exports){return exports.default(Module)}).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();if(!initializedJS){Module["___embind_register_native_and_builtin_types"]();initializedJS=true}try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(Module["keepRuntimeAlive"]()){Module["PThread"].setExitStatus(result)}else{Module["PThread"].threadExit(result)}}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}}; "use strict";var Module={};var initializedJS=false;function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;function moduleLoaded(){}self.onmessage=function(e){try{if(e.data.cmd==="load"){var imports={};imports["wasm"]=e.data.wasmModule;imports["wasmMemory"]=e.data.wasmMemory;imports["buffer"]=imports["wasmMemory"].buffer;imports["ENVIRONMENT_IS_PTHREAD"]=true;(e.data.urlOrBlob?import(e.data.urlOrBlob):import("./avif_enc_mt.js")).then(function(exports){return exports.default(Module)}).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();if(!initializedJS){Module["___embind_register_native_and_builtin_types"]();initializedJS=true}try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};

View File

@@ -8,6 +8,7 @@ ENV LDFLAGS "${CFLAGS} \
-s ALLOW_MEMORY_GROWTH=1 \ -s ALLOW_MEMORY_GROWTH=1 \
-s TEXTDECODER=2 \ -s TEXTDECODER=2 \
-s NODEJS_CATCH_EXIT=0 -s NODEJS_CATCH_REJECTION=0 \ -s NODEJS_CATCH_EXIT=0 -s NODEJS_CATCH_REJECTION=0 \
-s MINIMAL_RUNTIME=1 \
" "
# Build and cache standard libraries with these flags + Embind. # Build and cache standard libraries with these flags + Embind.
RUN emcc ${CXXFLAGS} ${LDFLAGS} --bind -xc++ /dev/null -o /dev/null RUN emcc ${CXXFLAGS} ${LDFLAGS} --bind -xc++ /dev/null -o /dev/null

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,5 @@
CODEC_URL = https://github.com/libjxl/libjxl.git CODEC_URL = https://github.com/libjxl/libjxl.git
CODEC_VERSION = v0.5 CODEC_VERSION = 3f76321a7cbcf4f452894dc173eb7be60f508ecb
CODEC_DIR = node_modules/jxl CODEC_DIR = node_modules/jxl
CODEC_BUILD_ROOT := $(CODEC_DIR)/build CODEC_BUILD_ROOT := $(CODEC_DIR)/build
CODEC_MT_BUILD_DIR := $(CODEC_BUILD_ROOT)/mt CODEC_MT_BUILD_DIR := $(CODEC_BUILD_ROOT)/mt

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -10,13 +10,15 @@ using namespace emscripten;
thread_local const val Uint8Array = val::global("Uint8Array"); thread_local const val Uint8Array = val::global("Uint8Array");
struct JXLOptions { struct JXLOptions {
int effort; // 1 = slowest
// 7 = fastest
int speed;
float quality; float quality;
bool progressive; bool progressive;
int epf; int epf;
int nearLossless;
bool lossyPalette; bool lossyPalette;
size_t decodingSpeedTier; size_t decodingSpeedTier;
float photonNoiseIso;
}; };
val encode(std::string image, int width, int height, JXLOptions options) { val encode(std::string image, int width, int height, JXLOptions options) {
@@ -31,14 +33,11 @@ val encode(std::string image, int width, int height, JXLOptions options) {
pool_ptr = &pool; pool_ptr = &pool;
#endif #endif
size_t st = 10 - options.effort;
cparams.speed_tier = jxl::SpeedTier(st);
cparams.epf = options.epf; cparams.epf = options.epf;
cparams.speed_tier = static_cast<jxl::SpeedTier>(options.speed);
cparams.decoding_speed_tier = options.decodingSpeedTier; cparams.decoding_speed_tier = options.decodingSpeedTier;
cparams.photon_noise_iso = options.photonNoiseIso;
if (options.lossyPalette) { if (options.lossyPalette || options.nearLossless) {
cparams.lossy_palette = true; cparams.lossy_palette = true;
cparams.palette_colors = 0; cparams.palette_colors = 0;
cparams.options.predictor = jxl::Predictor::Zero; cparams.options.predictor = jxl::Predictor::Zero;
@@ -107,12 +106,12 @@ val encode(std::string image, int width, int height, JXLOptions options) {
EMSCRIPTEN_BINDINGS(my_module) { EMSCRIPTEN_BINDINGS(my_module) {
value_object<JXLOptions>("JXLOptions") value_object<JXLOptions>("JXLOptions")
.field("effort", &JXLOptions::effort) .field("speed", &JXLOptions::speed)
.field("quality", &JXLOptions::quality) .field("quality", &JXLOptions::quality)
.field("progressive", &JXLOptions::progressive) .field("progressive", &JXLOptions::progressive)
.field("nearLossless", &JXLOptions::nearLossless)
.field("lossyPalette", &JXLOptions::lossyPalette) .field("lossyPalette", &JXLOptions::lossyPalette)
.field("decodingSpeedTier", &JXLOptions::decodingSpeedTier) .field("decodingSpeedTier", &JXLOptions::decodingSpeedTier)
.field("photonNoiseIso", &JXLOptions::photonNoiseIso)
.field("epf", &JXLOptions::epf); .field("epf", &JXLOptions::epf);
function("encode", &encode); function("encode", &encode);

View File

@@ -1,11 +1,11 @@
export interface EncodeOptions { export interface EncodeOptions {
effort: number; speed: number;
quality: number; quality: number;
progressive: boolean; progressive: boolean;
epf: number; epf: number;
nearLossless: number;
lossyPalette: boolean; lossyPalette: boolean;
decodingSpeedTier: number; decodingSpeedTier: number;
photonNoiseIso: number;
} }
export interface JXLModule extends EmscriptenWasm.Module { export interface JXLModule extends EmscriptenWasm.Module {

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -1 +1 @@
"use strict";var Module={};var initializedJS=false;function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};function moduleLoaded(){}self.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;(e.data.urlOrBlob?import(e.data.urlOrBlob):import("./jxl_enc_mt.js")).then(function(exports){return exports.default(Module)}).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();if(!initializedJS){Module["___embind_register_native_and_builtin_types"]();initializedJS=true}try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(Module["keepRuntimeAlive"]()){Module["PThread"].setExitStatus(result)}else{Module["PThread"].threadExit(result)}}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}}; "use strict";var Module={};var initializedJS=false;function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;function moduleLoaded(){}self.onmessage=function(e){try{if(e.data.cmd==="load"){var imports={};imports["wasm"]=e.data.wasmModule;imports["wasmMemory"]=e.data.wasmMemory;imports["buffer"]=imports["wasmMemory"].buffer;imports["ENVIRONMENT_IS_PTHREAD"]=true;(e.data.urlOrBlob?import(e.data.urlOrBlob):import("./jxl_enc_mt.js")).then(function(exports){return exports.default(Module)}).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();if(!initializedJS){Module["___embind_register_native_and_builtin_types"]();initializedJS=true}try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -1 +1 @@
"use strict";var Module={};var initializedJS=false;function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};function moduleLoaded(){}self.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;(e.data.urlOrBlob?import(e.data.urlOrBlob):import("./jxl_enc_mt_simd.js")).then(function(exports){return exports.default(Module)}).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();if(!initializedJS){Module["___embind_register_native_and_builtin_types"]();initializedJS=true}try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(Module["keepRuntimeAlive"]()){Module["PThread"].setExitStatus(result)}else{Module["PThread"].threadExit(result)}}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}}; "use strict";var Module={};var initializedJS=false;function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;function moduleLoaded(){}self.onmessage=function(e){try{if(e.data.cmd==="load"){var imports={};imports["wasm"]=e.data.wasmModule;imports["wasmMemory"]=e.data.wasmMemory;imports["buffer"]=imports["wasmMemory"].buffer;imports["ENVIRONMENT_IS_PTHREAD"]=true;(e.data.urlOrBlob?import(e.data.urlOrBlob):import("./jxl_enc_mt_simd.js")).then(function(exports){return exports.default(Module)}).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();if(!initializedJS){Module["___embind_register_native_and_builtin_types"]();initializedJS=true}try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@@ -158,11 +158,6 @@ val encode(std::string image_in, int image_width, int image_height, MozJpegOptio
if (!opts.auto_subsample && opts.color_space == JCS_YCbCr) { if (!opts.auto_subsample && opts.color_space == JCS_YCbCr) {
cinfo.comp_info[0].h_samp_factor = opts.chroma_subsample; cinfo.comp_info[0].h_samp_factor = opts.chroma_subsample;
cinfo.comp_info[0].v_samp_factor = opts.chroma_subsample; cinfo.comp_info[0].v_samp_factor = opts.chroma_subsample;
if (opts.chroma_subsample > 2) {
// Otherwise encoding fails.
jpeg_c_set_int_param(&cinfo, JINT_DC_SCAN_OPT_MODE, 1);
}
} }
if (!opts.baseline && opts.progressive) { if (!opts.baseline && opts.progressive) {

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -1 +1 @@
"use strict";var Module={};var initializedJS=false;function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};function moduleLoaded(){}self.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;(e.data.urlOrBlob?import(e.data.urlOrBlob):import("./wp2_enc_mt.js")).then(function(exports){return exports.default(Module)}).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();if(!initializedJS){Module["___embind_register_native_and_builtin_types"]();initializedJS=true}try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(Module["keepRuntimeAlive"]()){Module["PThread"].setExitStatus(result)}else{Module["PThread"].threadExit(result)}}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}}; "use strict";var Module={};var initializedJS=false;function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;function moduleLoaded(){}self.onmessage=function(e){try{if(e.data.cmd==="load"){var imports={};imports["wasm"]=e.data.wasmModule;imports["wasmMemory"]=e.data.wasmMemory;imports["buffer"]=imports["wasmMemory"].buffer;imports["ENVIRONMENT_IS_PTHREAD"]=true;(e.data.urlOrBlob?import(e.data.urlOrBlob):import("./wp2_enc_mt.js")).then(function(exports){return exports.default(Module)}).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();if(!initializedJS){Module["___embind_register_native_and_builtin_types"]();initializedJS=true}try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -1 +1 @@
"use strict";var Module={};var initializedJS=false;function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};function moduleLoaded(){}self.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;(e.data.urlOrBlob?import(e.data.urlOrBlob):import("./wp2_enc_mt_simd.js")).then(function(exports){return exports.default(Module)}).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();if(!initializedJS){Module["___embind_register_native_and_builtin_types"]();initializedJS=true}try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(Module["keepRuntimeAlive"]()){Module["PThread"].setExitStatus(result)}else{Module["PThread"].threadExit(result)}}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}}; "use strict";var Module={};var initializedJS=false;function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;function moduleLoaded(){}self.onmessage=function(e){try{if(e.data.cmd==="load"){var imports={};imports["wasm"]=e.data.wasmModule;imports["wasmMemory"]=e.data.wasmMemory;imports["buffer"]=imports["wasmMemory"].buffer;imports["ENVIRONMENT_IS_PTHREAD"]=true;(e.data.urlOrBlob?import(e.data.urlOrBlob):import("./wp2_enc_mt_simd.js")).then(function(exports){return exports.default(Module)}).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();if(!initializedJS){Module["___embind_register_native_and_builtin_types"]();initializedJS=true}try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@@ -1,38 +0,0 @@
/**
* Copyright 2020 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { promises as fs } from 'fs';
const prefix = 'as-text:';
export default function dataURLPlugin() {
return {
name: 'as-text-plugin',
async resolveId(id, importer) {
if (!id.startsWith(prefix)) return;
const realId = id.slice(prefix.length);
const resolveResult = await this.resolve(realId, importer);
if (!resolveResult) throw Error(`Cannot find ${realId} from ${importer}`);
return prefix + resolveResult.id;
},
async load(id) {
if (!id.startsWith(prefix)) return;
const realId = id.slice(prefix.length);
this.addWatchFile(realId);
const source = await fs.readFile(realId, { encoding: 'utf-8' });
return `export default ${JSON.stringify(source)}`;
},
};
}

View File

@@ -20,7 +20,6 @@ const allSrcPlaceholder = 'CLIENT_BUNDLE_PLUGIN_ALL_SRC';
export function getDependencies(clientOutput, item) { export function getDependencies(clientOutput, item) {
const crawlDependencies = new Set([item.fileName]); const crawlDependencies = new Set([item.fileName]);
const referencedFiles = new Set();
for (const fileName of crawlDependencies) { for (const fileName of crawlDependencies) {
const chunk = clientOutput.find((v) => v.fileName === fileName); const chunk = clientOutput.find((v) => v.fileName === fileName);
@@ -28,24 +27,11 @@ export function getDependencies(clientOutput, item) {
for (const dep of chunk.imports) { for (const dep of chunk.imports) {
crawlDependencies.add(dep); crawlDependencies.add(dep);
} }
for (const dep of chunk.referencedFiles) {
referencedFiles.add(dep);
}
} }
// Don't add self as dependency // Don't add self as dependency
crawlDependencies.delete(item.fileName); crawlDependencies.delete(item.fileName);
// Merge referencedFiles as regular deps. They need to be in the same Set as
// some JS files might appear in both lists and need to be deduped too.
//
// Didn't do this as part of the main loop since their `chunk` can't have
// nested deps and sometimes might be missing altogether, depending on type.
for (const dep of referencedFiles) {
crawlDependencies.add(dep);
}
return [...crawlDependencies]; return [...crawlDependencies];
} }
@@ -153,9 +139,9 @@ export default function (inputOptions, outputOptions, resolveFileUrl) {
if (property.startsWith(allSrcPlaceholder)) { if (property.startsWith(allSrcPlaceholder)) {
const allModules = [ const allModules = [
clientEntry, clientEntry,
...dependencies ...dependencies.map((name) =>
.map((name) => clientOutput.find((item) => item.fileName === name)) clientOutput.find((item) => item.fileName === name),
.filter((item) => item.code), ),
]; ];
const inlineDefines = [ const inlineDefines = [

View File

@@ -14,40 +14,28 @@ import { promises as fs } from 'fs';
import { lookup as lookupMime } from 'mime-types'; import { lookup as lookupMime } from 'mime-types';
const prefix = /^data-url(-text)?:/; const prefix = 'data-url:';
export default function dataURLPlugin() { export default function dataURLPlugin() {
return { return {
name: 'data-url-plugin', name: 'data-url-plugin',
async resolveId(id, importer) { async resolveId(id, importer) {
const match = prefix.exec(id); if (!id.startsWith(prefix)) return;
if (!match) return;
return ( return (
match[0] + (await this.resolve(id.slice(match[0].length), importer)).id prefix + (await this.resolve(id.slice(prefix.length), importer)).id
); );
}, },
async load(id) { async load(id) {
const match = prefix.exec(id); if (!id.startsWith(prefix)) return;
if (!match) return; const realId = id.slice(prefix.length);
const isText = !!match[1];
const realId = id.slice(match[0].length);
this.addWatchFile(realId); this.addWatchFile(realId);
const source = await fs.readFile(realId); const source = await fs.readFile(realId);
const type = lookupMime(realId) || 'text/plain'; const type = lookupMime(realId) || 'text/plain';
if (isText) { return `export default 'data:${type};base64,${source.toString(
const encodedBody = encodeURIComponent(source.toString('utf8')); 'base64',
)}';`;
return `export default ${JSON.stringify(
`data:${type};charset=utf-8,${encodedBody}`,
)};`;
}
return `export default ${JSON.stringify(
`data:${type};base64,${source.toString('base64')}`,
)};`;
}, },
}; };
} }

View File

@@ -17,14 +17,10 @@ const prefix = 'entry-data:';
const mainNamePlaceholder = 'ENTRY_DATA_PLUGIN_MAIN_NAME'; const mainNamePlaceholder = 'ENTRY_DATA_PLUGIN_MAIN_NAME';
const dependenciesPlaceholder = 'ENTRY_DATA_PLUGIN_DEPS'; const dependenciesPlaceholder = 'ENTRY_DATA_PLUGIN_DEPS';
const placeholderRe = /(ENTRY_DATA_PLUGIN_(?:MAIN_NAME|DEPS))(\d+)/g; const placeholderRe = /(ENTRY_DATA_PLUGIN_(?:MAIN_NAME|DEPS))(\d+)/g;
const filenamePrefix = 'static/';
/** @param {string} fileName */
export function fileNameToURL(fileName) {
return fileName.replace(/^static\//, '/');
}
export default function entryDataPlugin() { export default function entryDataPlugin() {
/** @type {number} */ /** @type {string} */
let exportCounter; let exportCounter;
/** @type {Map<number, string>} */ /** @type {Map<number, string>} */
let counterToIdMap; let counterToIdMap;
@@ -73,11 +69,15 @@ export default function entryDataPlugin() {
if (!chunk) throw Error(`Cannot find ${id}`); if (!chunk) throw Error(`Cannot find ${id}`);
if (placeholder === mainNamePlaceholder) { if (placeholder === mainNamePlaceholder) {
return JSON.stringify(fileNameToURL(chunk.fileName)); return JSON.stringify(
chunk.fileName.slice(filenamePrefix.length),
);
} }
return JSON.stringify( return JSON.stringify(
getDependencies(chunks, chunk).map((filename) => fileNameToURL(filename)), getDependencies(chunks, chunk).map((item) =>
item.slice(filenamePrefix.length),
),
); );
}, },
); );

View File

@@ -28,17 +28,10 @@ if (!self.<%- amdFunctionName %>) {
<% } else { %> <% } else { %>
new Promise(resolve => { new Promise(resolve => {
if ("document" in self) { if ("document" in self) {
const link = document.createElement("link"); const script = document.createElement("script");
link.rel = "preload"; script.src = uri;
link.as = "script"; script.onload = resolve;
link.href = uri; document.head.appendChild(script);
link.onload = () => {
const script = document.createElement("script");
script.src = uri;
script.onload = resolve;
document.head.appendChild(script);
};
document.head.appendChild(link);
} else { } else {
self.nextDefineUri = uri; self.nextDefineUri = uri;
importScripts(uri); importScripts(uri);

View File

@@ -16,23 +16,21 @@ You can start using the libSquoosh by adding these lines to the top of your JS p
```js ```js
import { ImagePool } from '@squoosh/lib'; import { ImagePool } from '@squoosh/lib';
import { cpus } from 'os'; const imagePool = new ImagePool();
const imagePool = new ImagePool(cpus().length);
``` ```
This will create an image pool with an underlying processing pipeline that you can use to ingest and encode images. The ImagePool constructor takes one argument that defines how many parallel operations it is allowed to run at any given time. This will create an image pool with an underlying processing pipeline that you can use to ingest and encode images. The ImagePool constructor takes one argument that defines how many parallel operations it is allowed to run at any given time. By default, this number is set to the amount of CPU cores available in the system it is running on.
## Ingesting images ## Ingesting images
You can ingest a new image like so: You can ingest a new image like so:
```js ```js
import fs from 'fs/promises'; const imagePath = 'path/to/image.png';
const file = await fs.readFile('./path/to/image.png'); const image = imagePool.ingestImage(imagePath);
const image = imagePool.ingestImage(file);
``` ```
The `ingestImage` function can accept any [`ArrayBuffer`][arraybuffer] whether that is from `readFile()` or `fetch()`. The `ingestImage` function can take anything the node [`readFile`][readfile] function can take, including a buffer and `FileHandle`.
The returned `image` object is a representation of the original image, that you can now preprocess, encode, and extract information about. The returned `image` object is a representation of the original image, that you can now preprocess, encode, and extract information about.
@@ -41,7 +39,7 @@ The returned `image` object is a representation of the original image, that you
When an image has been ingested, you can start preprocessing it and encoding it to other formats. This example will resize the image and then encode it to a `.jpg` and `.jxl` image: When an image has been ingested, you can start preprocessing it and encoding it to other formats. This example will resize the image and then encode it to a `.jpg` and `.jxl` image:
```js ```js
await image.decoded; //Wait until the image is decoded before running preprocessors. await image.decoded; //Wait until the image is decoded before running preprocessors.
const preprocessOptions = { const preprocessOptions = {
//When both width and height are specified, the image resized to specified size. //When both width and height are specified, the image resized to specified size.
@@ -49,7 +47,7 @@ const preprocessOptions = {
enabled: true, enabled: true,
width: 100, width: 100,
height: 50, height: 50,
}, }
/* /*
//When either width or height is specified, the image resized to specified size keeping aspect ratio. //When either width or height is specified, the image resized to specified size keeping aspect ratio.
resize: { resize: {
@@ -57,7 +55,7 @@ const preprocessOptions = {
width: 100, width: 100,
} }
*/ */
}; }
await image.preprocess(preprocessOptions); await image.preprocess(preprocessOptions);
const encodeOptions = { const encodeOptions = {
@@ -65,8 +63,9 @@ const encodeOptions = {
jxl: { jxl: {
quality: 90, quality: 90,
}, },
}; }
await image.encode(encodeOptions); await image.encode(encodeOptions);
``` ```
The default values for each option can be found in the [`codecs.ts`][codecs.ts] file under `defaultEncoderOptions`. Every unspecified value will use the default value specified there. _Better documentation is needed here._ The default values for each option can be found in the [`codecs.ts`][codecs.ts] file under `defaultEncoderOptions`. Every unspecified value will use the default value specified there. _Better documentation is needed here._
@@ -169,4 +168,4 @@ const encodeOptions: {
[squoosh]: https://squoosh.app [squoosh]: https://squoosh.app
[codecs.ts]: https://github.com/GoogleChromeLabs/squoosh/blob/dev/libsquoosh/src/codecs.ts [codecs.ts]: https://github.com/GoogleChromeLabs/squoosh/blob/dev/libsquoosh/src/codecs.ts
[butteraugli]: https://github.com/google/butteraugli [butteraugli]: https://github.com/google/butteraugli
[arraybuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer [readfile]: https://nodejs.org/api/fs.html#fs_fspromises_readfile_path_options

View File

@@ -10,7 +10,7 @@ import { builtinModules } from 'module';
/** @type {import('rollup').RollupOptions} */ /** @type {import('rollup').RollupOptions} */
export default { export default {
input: 'src/index.ts', input: 'src/index.js',
output: { output: {
dir: 'build', dir: 'build',
format: 'cjs', format: 'cjs',

View File

@@ -9,12 +9,6 @@ import { cpus } from 'os';
hardwareConcurrency: cpus().length, hardwareConcurrency: cpus().length,
}; };
interface DecodeModule extends EmscriptenWasm.Module {
decode: (data: Uint8Array) => ImageData;
}
type DecodeModuleFactory = EmscriptenWasm.ModuleFactory<DecodeModule>;
interface RotateModuleInstance { interface RotateModuleInstance {
exports: { exports: {
memory: WebAssembly.Memory; memory: WebAssembly.Memory;
@@ -29,26 +23,17 @@ interface ResizeWithAspectParams {
target_height: number; target_height: number;
} }
export interface ResizeOptions { interface ResizeInstantiateOptions {
width: number; width: number;
height: number; height: number;
method: 'triangle' | 'catrom' | 'mitchell' | 'lanczos3'; method: string;
premultiply: boolean; premultiply: boolean;
linearRGB: boolean; linearRGB: boolean;
} }
export interface QuantOptions {
numColors: number;
dither: number;
}
export interface RotateOptions {
numRotations: number;
}
declare global { declare global {
// Needed for being able to use ImageData as type in codec types // Needed for being able to use ImageData as type in codec types
type ImageData = import('./image_data.js').default; type ImageData = typeof import('./image_data.js');
// Needed for being able to assign to `globalThis.ImageData` // Needed for being able to assign to `globalThis.ImageData`
var ImageData: ImageData['constructor']; var ImageData: ImageData['constructor'];
} }
@@ -56,23 +41,18 @@ declare global {
import type { QuantizerModule } from '../../codecs/imagequant/imagequant.js'; import type { QuantizerModule } from '../../codecs/imagequant/imagequant.js';
// MozJPEG // MozJPEG
import type { MozJPEGModule as MozJPEGEncodeModule } from '../../codecs/mozjpeg/enc/mozjpeg_enc';
import mozEnc from '../../codecs/mozjpeg/enc/mozjpeg_node_enc.js'; import mozEnc from '../../codecs/mozjpeg/enc/mozjpeg_node_enc.js';
import mozEncWasm from 'asset-url:../../codecs/mozjpeg/enc/mozjpeg_node_enc.wasm'; import mozEncWasm from 'asset-url:../../codecs/mozjpeg/enc/mozjpeg_node_enc.wasm';
import mozDec from '../../codecs/mozjpeg/dec/mozjpeg_node_dec.js'; import mozDec from '../../codecs/mozjpeg/dec/mozjpeg_node_dec.js';
import mozDecWasm from 'asset-url:../../codecs/mozjpeg/dec/mozjpeg_node_dec.wasm'; import mozDecWasm from 'asset-url:../../codecs/mozjpeg/dec/mozjpeg_node_dec.wasm';
import type { EncodeOptions as MozJPEGEncodeOptions } from '../../codecs/mozjpeg/enc/mozjpeg_enc';
// WebP // WebP
import type { WebPModule as WebPEncodeModule } from '../../codecs/webp/enc/webp_enc';
import webpEnc from '../../codecs/webp/enc/webp_node_enc.js'; import webpEnc from '../../codecs/webp/enc/webp_node_enc.js';
import webpEncWasm from 'asset-url:../../codecs/webp/enc/webp_node_enc.wasm'; import webpEncWasm from 'asset-url:../../codecs/webp/enc/webp_node_enc.wasm';
import webpDec from '../../codecs/webp/dec/webp_node_dec.js'; import webpDec from '../../codecs/webp/dec/webp_node_dec.js';
import webpDecWasm from 'asset-url:../../codecs/webp/dec/webp_node_dec.wasm'; import webpDecWasm from 'asset-url:../../codecs/webp/dec/webp_node_dec.wasm';
import type { EncodeOptions as WebPEncodeOptions } from '../../codecs/webp/enc/webp_enc.js';
// AVIF // AVIF
import type { AVIFModule as AVIFEncodeModule } from '../../codecs/avif/enc/avif_enc';
import avifEnc from '../../codecs/avif/enc/avif_node_enc.js'; import avifEnc from '../../codecs/avif/enc/avif_node_enc.js';
import avifEncWasm from 'asset-url:../../codecs/avif/enc/avif_node_enc.wasm'; import avifEncWasm from 'asset-url:../../codecs/avif/enc/avif_node_enc.wasm';
import avifEncMt from '../../codecs/avif/enc/avif_node_enc_mt.js'; import avifEncMt from '../../codecs/avif/enc/avif_node_enc_mt.js';
@@ -80,23 +60,18 @@ import avifEncMtWorker from 'chunk-url:../../codecs/avif/enc/avif_node_enc_mt.wo
import avifEncMtWasm from 'asset-url:../../codecs/avif/enc/avif_node_enc_mt.wasm'; import avifEncMtWasm from 'asset-url:../../codecs/avif/enc/avif_node_enc_mt.wasm';
import avifDec from '../../codecs/avif/dec/avif_node_dec.js'; import avifDec from '../../codecs/avif/dec/avif_node_dec.js';
import avifDecWasm from 'asset-url:../../codecs/avif/dec/avif_node_dec.wasm'; import avifDecWasm from 'asset-url:../../codecs/avif/dec/avif_node_dec.wasm';
import type { EncodeOptions as AvifEncodeOptions } from '../../codecs/avif/enc/avif_enc.js';
// JXL // JXL
import type { JXLModule as JXLEncodeModule } from '../../codecs/jxl/enc/jxl_enc';
import jxlEnc from '../../codecs/jxl/enc/jxl_node_enc.js'; import jxlEnc from '../../codecs/jxl/enc/jxl_node_enc.js';
import jxlEncWasm from 'asset-url:../../codecs/jxl/enc/jxl_node_enc.wasm'; import jxlEncWasm from 'asset-url:../../codecs/jxl/enc/jxl_node_enc.wasm';
import jxlDec from '../../codecs/jxl/dec/jxl_node_dec.js'; import jxlDec from '../../codecs/jxl/dec/jxl_node_dec.js';
import jxlDecWasm from 'asset-url:../../codecs/jxl/dec/jxl_node_dec.wasm'; import jxlDecWasm from 'asset-url:../../codecs/jxl/dec/jxl_node_dec.wasm';
import type { EncodeOptions as JxlEncodeOptions } from '../../codecs/jxl/enc/jxl_enc.js';
// WP2 // WP2
import type { WP2Module as WP2EncodeModule } from '../../codecs/wp2/enc/wp2_enc';
import wp2Enc from '../../codecs/wp2/enc/wp2_node_enc.js'; import wp2Enc from '../../codecs/wp2/enc/wp2_node_enc.js';
import wp2EncWasm from 'asset-url:../../codecs/wp2/enc/wp2_node_enc.wasm'; import wp2EncWasm from 'asset-url:../../codecs/wp2/enc/wp2_node_enc.wasm';
import wp2Dec from '../../codecs/wp2/dec/wp2_node_dec.js'; import wp2Dec from '../../codecs/wp2/dec/wp2_node_dec.js';
import wp2DecWasm from 'asset-url:../../codecs/wp2/dec/wp2_node_dec.wasm'; import wp2DecWasm from 'asset-url:../../codecs/wp2/dec/wp2_node_dec.wasm';
import type { EncodeOptions as WP2EncodeOptions } from '../../codecs/wp2/enc/wp2_enc.js';
// PNG // PNG
import * as pngEncDec from '../../codecs/png/pkg/squoosh_png.js'; import * as pngEncDec from '../../codecs/png/pkg/squoosh_png.js';
@@ -109,9 +84,6 @@ const pngEncDecPromise = pngEncDec.default(
import * as oxipng from '../../codecs/oxipng/pkg/squoosh_oxipng.js'; import * as oxipng from '../../codecs/oxipng/pkg/squoosh_oxipng.js';
import oxipngWasm from 'asset-url:../../codecs/oxipng/pkg/squoosh_oxipng_bg.wasm'; import oxipngWasm from 'asset-url:../../codecs/oxipng/pkg/squoosh_oxipng_bg.wasm';
const oxipngPromise = oxipng.default(fsp.readFile(pathify(oxipngWasm))); const oxipngPromise = oxipng.default(fsp.readFile(pathify(oxipngWasm)));
interface OxiPngEncodeOptions {
level: number;
}
// Resize // Resize
import * as resize from '../../codecs/resize/pkg/squoosh_resize.js'; import * as resize from '../../codecs/resize/pkg/squoosh_resize.js';
@@ -188,7 +160,13 @@ export const preprocessors = {
buffer: Uint8Array, buffer: Uint8Array,
input_width: number, input_width: number,
input_height: number, input_height: number,
{ width, height, method, premultiply, linearRGB }: ResizeOptions, {
width,
height,
method,
premultiply,
linearRGB,
}: ResizeInstantiateOptions,
) => { ) => {
({ width, height } = resizeWithAspect({ ({ width, height } = resizeWithAspect({
input_width, input_width,
@@ -229,7 +207,7 @@ export const preprocessors = {
buffer: Uint8Array, buffer: Uint8Array,
width: number, width: number,
height: number, height: number,
{ numColors, dither }: QuantOptions, { numColors, dither }: { numColors: number; dither: number },
) => ) =>
new ImageData( new ImageData(
imageQuant.quantize(buffer, width, height, numColors, dither), imageQuant.quantize(buffer, width, height, numColors, dither),
@@ -250,7 +228,7 @@ export const preprocessors = {
buffer: Uint8Array, buffer: Uint8Array,
width: number, width: number,
height: number, height: number,
{ numRotations }: RotateOptions, { numRotations }: { numRotations: number },
) => { ) => {
const degrees = (numRotations * 90) % 360; const degrees = (numRotations * 90) % 360;
const sameDimensions = degrees == 0 || degrees == 180; const sameDimensions = degrees == 0 || degrees == 180;
@@ -279,20 +257,15 @@ export const preprocessors = {
numRotations: 0, numRotations: 0,
}, },
}, },
} as const; };
export const codecs = { export const codecs = {
mozjpeg: { mozjpeg: {
name: 'MozJPEG', name: 'MozJPEG',
extension: 'jpg', extension: 'jpg',
detectors: [/^\xFF\xD8\xFF/], detectors: [/^\xFF\xD8\xFF/],
dec: () => dec: () => instantiateEmscriptenWasm(mozDec, mozDecWasm),
instantiateEmscriptenWasm(mozDec as DecodeModuleFactory, mozDecWasm), enc: () => instantiateEmscriptenWasm(mozEnc, mozEncWasm),
enc: () =>
instantiateEmscriptenWasm(
mozEnc as EmscriptenWasm.ModuleFactory<MozJPEGEncodeModule>,
mozEncWasm,
),
defaultEncoderOptions: { defaultEncoderOptions: {
quality: 75, quality: 75,
baseline: false, baseline: false,
@@ -321,13 +294,8 @@ export const codecs = {
name: 'WebP', name: 'WebP',
extension: 'webp', extension: 'webp',
detectors: [/^RIFF....WEBPVP8[LX ]/s], detectors: [/^RIFF....WEBPVP8[LX ]/s],
dec: () => dec: () => instantiateEmscriptenWasm(webpDec, webpDecWasm),
instantiateEmscriptenWasm(webpDec as DecodeModuleFactory, webpDecWasm), enc: () => instantiateEmscriptenWasm(webpEnc, webpEncWasm),
enc: () =>
instantiateEmscriptenWasm(
webpEnc as EmscriptenWasm.ModuleFactory<WebPEncodeModule>,
webpEncWasm,
),
defaultEncoderOptions: { defaultEncoderOptions: {
quality: 75, quality: 75,
target_size: 0, target_size: 0,
@@ -367,20 +335,16 @@ export const codecs = {
name: 'AVIF', name: 'AVIF',
extension: 'avif', extension: 'avif',
detectors: [/^\x00\x00\x00 ftypavif\x00\x00\x00\x00/], detectors: [/^\x00\x00\x00 ftypavif\x00\x00\x00\x00/],
dec: () => dec: () => instantiateEmscriptenWasm(avifDec, avifDecWasm),
instantiateEmscriptenWasm(avifDec as DecodeModuleFactory, avifDecWasm),
enc: async () => { enc: async () => {
if (await threads()) { if (await threads()) {
return instantiateEmscriptenWasm( return instantiateEmscriptenWasm(
avifEncMt as EmscriptenWasm.ModuleFactory<AVIFEncodeModule>, avifEncMt,
avifEncMtWasm, avifEncMtWasm,
avifEncMtWorker, avifEncMtWorker,
); );
} }
return instantiateEmscriptenWasm( return instantiateEmscriptenWasm(avifEnc, avifEncWasm);
avifEnc as EmscriptenWasm.ModuleFactory<AVIFEncodeModule>,
avifEncWasm,
);
}, },
defaultEncoderOptions: { defaultEncoderOptions: {
cqLevel: 33, cqLevel: 33,
@@ -404,21 +368,16 @@ export const codecs = {
name: 'JPEG-XL', name: 'JPEG-XL',
extension: 'jxl', extension: 'jxl',
detectors: [/^\xff\x0a/], detectors: [/^\xff\x0a/],
dec: () => dec: () => instantiateEmscriptenWasm(jxlDec, jxlDecWasm),
instantiateEmscriptenWasm(jxlDec as DecodeModuleFactory, jxlDecWasm), enc: () => instantiateEmscriptenWasm(jxlEnc, jxlEncWasm),
enc: () =>
instantiateEmscriptenWasm(
jxlEnc as EmscriptenWasm.ModuleFactory<JXLEncodeModule>,
jxlEncWasm,
),
defaultEncoderOptions: { defaultEncoderOptions: {
effort: 1, speed: 4,
quality: 75, quality: 75,
progressive: false, progressive: false,
epf: -1, epf: -1,
nearLossless: 0,
lossyPalette: false, lossyPalette: false,
decodingSpeedTier: 0, decodingSpeedTier: 0,
photonNoiseIso: 0,
}, },
autoOptimize: { autoOptimize: {
option: 'quality', option: 'quality',
@@ -430,13 +389,8 @@ export const codecs = {
name: 'WebP2', name: 'WebP2',
extension: 'wp2', extension: 'wp2',
detectors: [/^\xF4\xFF\x6F/], detectors: [/^\xF4\xFF\x6F/],
dec: () => dec: () => instantiateEmscriptenWasm(wp2Dec, wp2DecWasm),
instantiateEmscriptenWasm(wp2Dec as DecodeModuleFactory, wp2DecWasm), enc: () => instantiateEmscriptenWasm(wp2Enc, wp2EncWasm),
enc: () =>
instantiateEmscriptenWasm(
wp2Enc as EmscriptenWasm.ModuleFactory<WP2EncodeModule>,
wp2EncWasm,
),
defaultEncoderOptions: { defaultEncoderOptions: {
quality: 75, quality: 75,
alpha_quality: 75, alpha_quality: 75,
@@ -467,7 +421,7 @@ export const codecs = {
await oxipngPromise; await oxipngPromise;
return { return {
encode: ( encode: (
buffer: Uint8ClampedArray | ArrayBuffer, buffer: Uint8Array,
width: number, width: number,
height: number, height: number,
opts: { level: number }, opts: { level: number },
@@ -490,13 +444,4 @@ export const codecs = {
max: 1, max: 1,
}, },
}, },
} as const;
export {
MozJPEGEncodeOptions,
WebPEncodeOptions,
AvifEncodeOptions,
JxlEncodeOptions,
WP2EncodeOptions,
OxiPngEncodeOptions,
}; };

View File

@@ -19,7 +19,7 @@ export function instantiateEmscriptenWasm<T extends EmscriptenWasm.Module>(
// These will have changed in the bundling process and // These will have changed in the bundling process and
// we need to inject them here. // we need to inject them here.
if (requestPath.endsWith('.wasm')) return pathify(path); if (requestPath.endsWith('.wasm')) return pathify(path);
if (requestPath.endsWith('.worker.js')) return pathify(workerJS); if (requestPath.endsWith('.worker.js')) return new URL(workerJS).pathname;
return requestPath; return requestPath;
}, },
}); });

224
libsquoosh/src/index.js Normal file
View File

@@ -0,0 +1,224 @@
import { isMainThread } from 'worker_threads';
import { cpus } from 'os';
import { promises as fsp } from 'fs';
import { codecs as encoders, preprocessors } from './codecs.js';
import WorkerPool from './worker_pool.js';
import { autoOptimize } from './auto-optimizer.js';
export { ImagePool, encoders, preprocessors };
async function decodeFile({ file }) {
let buffer;
if (ArrayBuffer.isView(file)) {
buffer = Buffer.from(file.buffer);
file = 'Binary blob';
} else if (file instanceof ArrayBuffer) {
buffer = Buffer.from(file);
file = 'Binary blob';
} else if (file instanceof Buffer) {
buffer = file;
file = 'Binary blob';
} else if (typeof file === 'string') {
buffer = await fsp.readFile(file);
} else {
throw Error('Unexpected input type');
}
const firstChunk = buffer.slice(0, 16);
const firstChunkString = Array.from(firstChunk)
.map((v) => String.fromCodePoint(v))
.join('');
const key = Object.entries(encoders).find(([name, { detectors }]) =>
detectors.some((detector) => detector.exec(firstChunkString)),
)?.[0];
if (!key) {
throw Error(`${file} has an unsupported format`);
}
const rgba = (await encoders[key].dec()).decode(new Uint8Array(buffer));
return {
bitmap: rgba,
size: buffer.length,
};
}
async function preprocessImage({ preprocessorName, options, image }) {
const preprocessor = await preprocessors[preprocessorName].instantiate();
image.bitmap = await preprocessor(
image.bitmap.data,
image.bitmap.width,
image.bitmap.height,
options,
);
return image;
}
async function encodeImage({
bitmap: bitmapIn,
encName,
encConfig,
optimizerButteraugliTarget,
maxOptimizerRounds,
}) {
let binary;
let optionsUsed = encConfig;
const encoder = await encoders[encName].enc();
if (encConfig === 'auto') {
const optionToOptimize = encoders[encName].autoOptimize.option;
const decoder = await encoders[encName].dec();
const encode = (bitmapIn, quality) =>
encoder.encode(
bitmapIn.data,
bitmapIn.width,
bitmapIn.height,
Object.assign({}, encoders[encName].defaultEncoderOptions, {
[optionToOptimize]: quality,
}),
);
const decode = (binary) => decoder.decode(binary);
const { binary: optimizedBinary, quality } = await autoOptimize(
bitmapIn,
encode,
decode,
{
min: encoders[encName].autoOptimize.min,
max: encoders[encName].autoOptimize.max,
butteraugliDistanceGoal: optimizerButteraugliTarget,
maxRounds: maxOptimizerRounds,
},
);
binary = optimizedBinary;
optionsUsed = {
// 5 significant digits is enough
[optionToOptimize]: Math.round(quality * 10000) / 10000,
};
} else {
binary = encoder.encode(
bitmapIn.data.buffer,
bitmapIn.width,
bitmapIn.height,
encConfig,
);
}
return {
optionsUsed,
binary,
extension: encoders[encName].extension,
size: binary.length,
};
}
// both decoding and encoding go through the worker pool
function handleJob(params) {
const { operation } = params;
switch (operation) {
case 'encode':
return encodeImage(params);
case 'decode':
return decodeFile(params);
case 'preprocess':
return preprocessImage(params);
default:
throw Error(`Invalid job "${operation}"`);
}
}
/**
* Represents an ingested image.
*/
class Image {
constructor(workerPool, file) {
this.file = file;
this.workerPool = workerPool;
this.decoded = workerPool.dispatchJob({ operation: 'decode', file });
this.encodedWith = {};
}
/**
* Define one or several preprocessors to use on the image.
* @param {object} preprocessOptions - An object with preprocessors to use, and their settings.
* @returns {Promise<undefined>} - A promise that resolves when all preprocessors have completed their work.
*/
async preprocess(preprocessOptions = {}) {
for (const [name, options] of Object.entries(preprocessOptions)) {
if (!Object.keys(preprocessors).includes(name)) {
throw Error(`Invalid preprocessor "${name}"`);
}
const preprocessorOptions = Object.assign(
{},
preprocessors[name].defaultOptions,
options,
);
this.decoded = this.workerPool.dispatchJob({
operation: 'preprocess',
preprocessorName: name,
image: await this.decoded,
options: preprocessorOptions,
});
await this.decoded;
}
}
/**
* Define one or several encoders to use on the image.
* @param {object} encodeOptions - An object with encoders to use, and their settings.
* @returns {Promise<undefined>} - A promise that resolves when the image has been encoded with all the specified encoders.
*/
async encode(encodeOptions = {}) {
const { bitmap } = await this.decoded;
for (const [encName, options] of Object.entries(encodeOptions)) {
if (!Object.keys(encoders).includes(encName)) {
continue;
}
const encRef = encoders[encName];
const encConfig =
typeof options === 'string'
? options
: Object.assign({}, encRef.defaultEncoderOptions, options);
this.encodedWith[encName] = this.workerPool.dispatchJob({
operation: 'encode',
bitmap,
encName,
encConfig,
optimizerButteraugliTarget: Number(
encodeOptions.optimizerButteraugliTarget ?? 1.4,
),
maxOptimizerRounds: Number(encodeOptions.maxOptimizerRounds ?? 6),
});
}
await Promise.all(Object.values(this.encodedWith));
}
}
/**
* A pool where images can be ingested and squooshed.
*/
class ImagePool {
/**
* Create a new pool.
* @param {number} [threads] - Number of concurrent image processes to run in the pool. Defaults to the number of CPU cores in the system.
*/
constructor(threads) {
this.workerPool = new WorkerPool(threads || cpus().length, __filename);
}
/**
* Ingest an image into the image pool.
* @param {string | Buffer | URL | object} image - The image or path to the image that should be ingested and decoded.
* @returns {Image} - A custom class reference to the decoded image.
*/
ingestImage(image) {
return new Image(this.workerPool, image);
}
/**
* Closes the underlying image processing pipeline. The already processed images will still be there, but no new processing can start.
* @returns {Promise<undefined>} - A promise that resolves when the underlying pipeline has closed.
*/
async close() {
await this.workerPool.join();
}
}
if (!isMainThread) {
WorkerPool.useThisThreadAsWorker(handleJob);
}

View File

@@ -1,307 +0,0 @@
import { isMainThread } from 'worker_threads';
import {
AvifEncodeOptions,
codecs as encoders,
JxlEncodeOptions,
MozJPEGEncodeOptions,
OxiPngEncodeOptions,
preprocessors,
QuantOptions,
ResizeOptions,
RotateOptions,
WebPEncodeOptions,
WP2EncodeOptions,
} from './codecs.js';
import WorkerPool from './worker_pool.js';
import { autoOptimize } from './auto-optimizer.js';
import type ImageData from './image_data';
export { ImagePool, encoders, preprocessors };
type EncoderKey = keyof typeof encoders;
type PreprocessorKey = keyof typeof preprocessors;
type PreprocessOptions = {
resize?: ResizeOptions;
quant?: QuantOptions;
rotate?: RotateOptions;
};
type EncodeResult = {
optionsUsed: object;
binary: Uint8Array;
extension: string;
size: number;
};
type EncoderOptions = {
mozjpeg?: Partial<MozJPEGEncodeOptions>;
webp?: Partial<WebPEncodeOptions>;
avif?: Partial<AvifEncodeOptions>;
jxl?: Partial<JxlEncodeOptions>;
wp2?: Partial<WP2EncodeOptions>;
oxipng?: Partial<OxiPngEncodeOptions>;
};
async function decodeFile({
file,
}: {
file: ArrayBuffer | ArrayLike<number>;
}): Promise<{ bitmap: ImageData; size: number }> {
const array = new Uint8Array(file);
const firstChunk = array.slice(0, 16);
const firstChunkString = Array.from(firstChunk)
.map((v) => String.fromCodePoint(v))
.join('');
const key = Object.entries(encoders).find(([_name, { detectors }]) =>
detectors.some((detector) => detector.exec(firstChunkString)),
)?.[0] as EncoderKey | undefined;
if (!key) {
throw Error(`File has an unsupported format`);
}
const encoder = encoders[key];
const mod = await encoder.dec();
const rgba = mod.decode(array);
return {
bitmap: rgba,
size: array.length,
};
}
async function preprocessImage({
preprocessorName,
options,
image,
}: {
preprocessorName: PreprocessorKey;
options: any;
image: { bitmap: ImageData };
}) {
const preprocessor = await preprocessors[preprocessorName].instantiate();
image.bitmap = await preprocessor(
Uint8Array.from(image.bitmap.data),
image.bitmap.width,
image.bitmap.height,
options,
);
return image;
}
async function encodeImage({
bitmap: bitmapIn,
encName,
encConfig,
optimizerButteraugliTarget,
maxOptimizerRounds,
}: {
bitmap: ImageData;
encName: EncoderKey;
encConfig: any;
optimizerButteraugliTarget: number;
maxOptimizerRounds: number;
}): Promise<EncodeResult> {
let binary: Uint8Array;
let optionsUsed = encConfig;
const encoder = await encoders[encName].enc();
if (encConfig === 'auto') {
const optionToOptimize = encoders[encName].autoOptimize.option;
const decoder = await encoders[encName].dec();
const encode = (bitmapIn: ImageData, quality: number) =>
encoder.encode(
bitmapIn.data,
bitmapIn.width,
bitmapIn.height,
Object.assign({}, encoders[encName].defaultEncoderOptions as any, {
[optionToOptimize]: quality,
}),
);
const decode = (binary: Uint8Array) => decoder.decode(binary);
const nonNullEncode = (bitmap: ImageData, quality: number): Uint8Array => {
const result = encode(bitmap, quality);
if (!result) {
throw new Error('There was an error while encoding');
}
return result;
};
const { binary: optimizedBinary, quality } = await autoOptimize(
bitmapIn,
nonNullEncode,
decode,
{
min: encoders[encName].autoOptimize.min,
max: encoders[encName].autoOptimize.max,
butteraugliDistanceGoal: optimizerButteraugliTarget,
maxRounds: maxOptimizerRounds,
},
);
binary = optimizedBinary;
optionsUsed = {
// 5 significant digits is enough
[optionToOptimize]: Math.round(quality * 10000) / 10000,
};
} else {
const result = encoder.encode(
bitmapIn.data.buffer,
bitmapIn.width,
bitmapIn.height,
encConfig,
);
if (!result) {
throw new Error('There was an error while encoding');
}
binary = result;
}
return {
optionsUsed,
binary,
extension: encoders[encName].extension,
size: binary.length,
};
}
type EncodeParams = { operation: 'encode' } & Parameters<typeof encodeImage>[0];
type DecodeParams = { operation: 'decode' } & Parameters<typeof decodeFile>[0];
type PreprocessParams = { operation: 'preprocess' } & Parameters<
typeof preprocessImage
>[0];
type JobMessage = EncodeParams | DecodeParams | PreprocessParams;
function handleJob(params: JobMessage) {
switch (params.operation) {
case 'encode':
return encodeImage(params);
case 'decode':
return decodeFile(params);
case 'preprocess':
return preprocessImage(params);
default:
throw Error(`Invalid job "${(params as any).operation}"`);
}
}
/**
* Represents an ingested image.
*/
class Image {
public file: ArrayBuffer | ArrayLike<number>;
public workerPool: WorkerPool<JobMessage, any>;
public decoded: Promise<{ bitmap: ImageData }>;
public encodedWith: { [key in EncoderKey]?: EncodeResult };
constructor(
workerPool: WorkerPool<JobMessage, any>,
file: ArrayBuffer | ArrayLike<number>,
) {
this.file = file;
this.workerPool = workerPool;
this.decoded = workerPool.dispatchJob({ operation: 'decode', file });
this.encodedWith = {};
}
/**
* Define one or several preprocessors to use on the image.
* @param {PreprocessOptions} preprocessOptions - An object with preprocessors to use, and their settings.
* @returns {Promise<undefined>} - A promise that resolves when all preprocessors have completed their work.
*/
async preprocess(preprocessOptions: PreprocessOptions = {}) {
for (const [name, options] of Object.entries(preprocessOptions)) {
if (!Object.keys(preprocessors).includes(name)) {
throw Error(`Invalid preprocessor "${name}"`);
}
const preprocessorName = name as PreprocessorKey;
const preprocessorOptions = Object.assign(
{},
preprocessors[preprocessorName].defaultOptions,
options,
);
this.decoded = this.workerPool.dispatchJob({
operation: 'preprocess',
preprocessorName,
image: await this.decoded,
options: preprocessorOptions,
});
await this.decoded;
}
}
/**
* Define one or several encoders to use on the image.
* @param {object} encodeOptions - An object with encoders to use, and their settings.
* @returns {Promise<{ [key in keyof T]: EncodeResult }>} - A promise that resolves when the image has been encoded with all the specified encoders.
*/
async encode<T extends EncoderOptions>(
encodeOptions: {
optimizerButteraugliTarget?: number;
maxOptimizerRounds?: number;
} & T,
): Promise<{ [key in keyof T]: EncodeResult }> {
const { bitmap } = await this.decoded;
const setEncodedWithPromises = [];
for (const [name, options] of Object.entries(encodeOptions)) {
if (!Object.keys(encoders).includes(name)) {
continue;
}
const encName = name as EncoderKey;
const encRef = encoders[encName];
const encConfig =
typeof options === 'string'
? options
: Object.assign({}, encRef.defaultEncoderOptions, options);
setEncodedWithPromises.push(
this.workerPool
.dispatchJob({
operation: 'encode',
bitmap,
encName,
encConfig,
optimizerButteraugliTarget: Number(
encodeOptions.optimizerButteraugliTarget ?? 1.4,
),
maxOptimizerRounds: Number(encodeOptions.maxOptimizerRounds ?? 6),
})
.then((encodeResult) => {
this.encodedWith[encName] = encodeResult;
}),
);
}
await Promise.all(setEncodedWithPromises);
return this.encodedWith as { [key in keyof T]: EncodeResult };
}
}
/**
* A pool where images can be ingested and squooshed.
*/
class ImagePool {
public workerPool: WorkerPool<JobMessage, any>;
/**
* Create a new pool.
* @param {number} [threads] - Number of concurrent image processes to run in the pool.
*/
constructor(threads: number) {
this.workerPool = new WorkerPool(threads, __filename);
}
/**
* Ingest an image into the image pool.
* @param {ArrayBuffer | ArrayLike<number>} file - The image that should be ingested and decoded.
* @returns {Image} - A custom class reference to the decoded image.
*/
ingestImage(file: ArrayBuffer | ArrayLike<number>): Image {
return new Image(this.workerPool, file);
}
/**
* Closes the underlying image processing pipeline. The already processed images will still be there, but no new processing can start.
* @returns {Promise<void>} - A promise that resolves when the underlying pipeline has closed.
*/
async close(): Promise<void> {
await this.workerPool.join();
}
}
if (!isMainThread) {
WorkerPool.useThisThreadAsWorker(handleJob);
}

View File

@@ -7,19 +7,26 @@ function uuid() {
).join(''); ).join('');
} }
interface Job<I> { function jobPromise(worker, msg) {
msg: I; return new Promise((resolve, reject) => {
resolve: Function; const id = uuid();
reject: Function; worker.postMessage({ msg, id });
worker.on('message', function f({ error, result, id: rid }) {
if (rid !== id) {
return;
}
if (error) {
reject(error);
return;
}
worker.off('message', f);
resolve(result);
});
});
} }
export default class WorkerPool<I, O> { export default class WorkerPool {
public numWorkers: number; constructor(numWorkers, workerFile) {
public jobQueue: TransformStream<Job<I>, Job<I>>;
public workerQueue: TransformStream<Worker, Worker>;
public done: Promise<void>;
constructor(numWorkers: number, workerFile: string) {
this.numWorkers = numWorkers; this.numWorkers = numWorkers;
this.jobQueue = new TransformStream(); this.jobQueue = new TransformStream();
this.workerQueue = new TransformStream(); this.workerQueue = new TransformStream();
@@ -41,14 +48,9 @@ export default class WorkerPool<I, O> {
await this._terminateAll(); await this._terminateAll();
return; return;
} }
if (!value) {
throw new Error('Reader did not return any value');
}
const { msg, resolve, reject } = value; const { msg, resolve, reject } = value;
const worker = await this._nextWorker(); const worker = await this._nextWorker();
this.jobPromise(worker, msg) jobPromise(worker, msg)
.then((result) => resolve(result)) .then((result) => resolve(result))
.catch((reason) => reject(reason)) .catch((reason) => reject(reason))
.finally(() => { .finally(() => {
@@ -64,10 +66,6 @@ export default class WorkerPool<I, O> {
const reader = this.workerQueue.readable.getReader(); const reader = this.workerQueue.readable.getReader();
const { value } = await reader.read(); const { value } = await reader.read();
reader.releaseLock(); reader.releaseLock();
if (!value) {
throw new Error('No worker left');
}
return value; return value;
} }
@@ -84,7 +82,7 @@ export default class WorkerPool<I, O> {
await this.done; await this.done;
} }
dispatchJob(msg: I): Promise<O> { dispatchJob(msg) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const writer = this.jobQueue.writable.getWriter(); const writer = this.jobQueue.writable.getWriter();
writer.write({ msg, resolve, reject }); writer.write({ msg, resolve, reject });
@@ -92,32 +90,14 @@ export default class WorkerPool<I, O> {
}); });
} }
private jobPromise(worker: Worker, msg: I) { static useThisThreadAsWorker(cb) {
return new Promise((resolve, reject) => { parentPort.on('message', async (data) => {
const id = uuid();
worker.postMessage({ msg, id });
worker.on('message', function f({ error, result, id: rid }) {
if (rid !== id) {
return;
}
if (error) {
reject(error);
return;
}
worker.off('message', f);
resolve(result);
});
});
}
static useThisThreadAsWorker<I, O>(cb: (msg: I) => O) {
parentPort!.on('message', async (data) => {
const { msg, id } = data; const { msg, id } = data;
try { try {
const result = await cb(msg); const result = await cb(msg);
parentPort!.postMessage({ result, id }); parentPort.postMessage({ result, id });
} catch (e) { } catch (e) {
parentPort!.postMessage({ error: e.message, id }); parentPort.postMessage({ error: e.message, id });
} }
}); });
} }

15
missing-types.d.ts vendored
View File

@@ -44,21 +44,6 @@ declare module 'data-url:*' {
export default url; export default url;
} }
declare module 'data-url-text:*' {
const url: string;
export default url;
}
declare module 'as-text:*' {
const text: string;
export default text;
}
declare module 'service-worker:*' {
const url: string;
export default url;
}
declare var ga: { declare var ga: {
(...args: any[]): void; (...args: any[]): void;
q: any[]; q: any[];

40
package-lock.json generated
View File

@@ -32,7 +32,7 @@
"lodash.camelcase": "^4.3.0", "lodash.camelcase": "^4.3.0",
"mime-types": "^2.1.28", "mime-types": "^2.1.28",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
"pointer-tracker": "^2.5.3", "pointer-tracker": "^2.4.0",
"postcss": "^7.0.35", "postcss": "^7.0.35",
"postcss-modules": "^3.2.2", "postcss-modules": "^3.2.2",
"postcss-nested": "^4.2.3", "postcss-nested": "^4.2.3",
@@ -48,20 +48,6 @@
"which": "^2.0.2" "which": "^2.0.2"
} }
}, },
"../pointer-tracker": {
"version": "2.5.0",
"extraneous": true,
"license": "Apache-2.0",
"devDependencies": {
"husky": "^4.2.5",
"lint-staged": "^10.2.11",
"prettier": "^2.0.5",
"rollup": "^2.23.1",
"rollup-plugin-terser": "^7.0.0",
"rollup-plugin-typescript2": "^0.27.2",
"typescript": "^3.9.7"
}
},
"node_modules/@babel/code-frame": { "node_modules/@babel/code-frame": {
"version": "7.10.4", "version": "7.10.4",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz",
@@ -3885,9 +3871,9 @@
} }
}, },
"node_modules/pointer-tracker": { "node_modules/pointer-tracker": {
"version": "2.5.3", "version": "2.4.0",
"resolved": "https://registry.npmjs.org/pointer-tracker/-/pointer-tracker-2.5.3.tgz", "resolved": "https://registry.npmjs.org/pointer-tracker/-/pointer-tracker-2.4.0.tgz",
"integrity": "sha512-LiJUeIbzk4dXq678YeyrZ++mdY17q4n/2sBHfU9wIuvmSzdiPgMvmvWN2g8mY4J7YwYOIrqrZUWP/MfFHVwYtg==", "integrity": "sha512-pWI2tpaM/XNtc9mUTv42Rmjf6mkHvE8LT5DDEq0G7baPNhxNM9E3CepubPplSoSLk9E5bwQrAMyDcPVmJyTW4g==",
"dev": true "dev": true
}, },
"node_modules/postcss": { "node_modules/postcss": {
@@ -8990,9 +8976,9 @@
} }
}, },
"@surma/rollup-plugin-off-main-thread": { "@surma/rollup-plugin-off-main-thread": {
"version": "2.2.2", "version": "2.2.1",
"resolved": "https://registry.npmjs.org/@surma/rollup-plugin-off-main-thread/-/rollup-plugin-off-main-thread-2.2.2.tgz", "resolved": "https://registry.npmjs.org/@surma/rollup-plugin-off-main-thread/-/rollup-plugin-off-main-thread-2.2.1.tgz",
"integrity": "sha512-dOD6nGZ79RmWKDRQuC7SOGXMvDkkLwBogu+epfVFMKiy2kOUtLZkb8wV/ettuMt37YJAJKYCKUmxSbZL2LkUQg==", "integrity": "sha512-7OU8wfyv18YPWVmecg2/0Jh+pm3lQbvPhIWHd1YQpoxPKPW/vsDNGBaCnMKsZbz29RjgCoXKugAjyagPncgdEw==",
"dev": true, "dev": true,
"requires": { "requires": {
"ejs": "^3.1.6", "ejs": "^3.1.6",
@@ -11960,9 +11946,9 @@
} }
}, },
"pointer-tracker": { "pointer-tracker": {
"version": "2.5.3", "version": "2.4.0",
"resolved": "https://registry.npmjs.org/pointer-tracker/-/pointer-tracker-2.5.3.tgz", "resolved": "https://registry.npmjs.org/pointer-tracker/-/pointer-tracker-2.4.0.tgz",
"integrity": "sha512-LiJUeIbzk4dXq678YeyrZ++mdY17q4n/2sBHfU9wIuvmSzdiPgMvmvWN2g8mY4J7YwYOIrqrZUWP/MfFHVwYtg==", "integrity": "sha512-pWI2tpaM/XNtc9mUTv42Rmjf6mkHvE8LT5DDEq0G7baPNhxNM9E3CepubPplSoSLk9E5bwQrAMyDcPVmJyTW4g==",
"dev": true "dev": true
}, },
"postcss": { "postcss": {
@@ -15994,9 +15980,9 @@
"dev": true "dev": true
}, },
"wasm-feature-detect": { "wasm-feature-detect": {
"version": "1.2.11", "version": "1.2.9",
"resolved": "https://registry.npmjs.org/wasm-feature-detect/-/wasm-feature-detect-1.2.11.tgz", "resolved": "https://registry.npmjs.org/wasm-feature-detect/-/wasm-feature-detect-1.2.9.tgz",
"integrity": "sha512-HUqwaodrQGaZgz1lZaNioIkog9tkeEJjrM3eq4aUL04whXOVDRc/o2EGb/8kV0QX411iAYWEqq7fMBmJ6dKS6w==" "integrity": "sha512-2E9/gtLVLpv2wnZDyYv8WY2dR9gHbmyv5uhZsnOcMSzqc78aGZpKQORPNcnrPwAU23nFUo7GAwKuoTAWRgsJ7Q=="
}, },
"which": { "which": {
"version": "2.0.2", "version": "2.0.2",

View File

@@ -14,7 +14,7 @@
"@rollup/plugin-commonjs": "^17.0.0", "@rollup/plugin-commonjs": "^17.0.0",
"@rollup/plugin-node-resolve": "^11.1.0", "@rollup/plugin-node-resolve": "^11.1.0",
"@rollup/plugin-replace": "^2.3.4", "@rollup/plugin-replace": "^2.3.4",
"@surma/rollup-plugin-off-main-thread": "^2.2.2", "@surma/rollup-plugin-off-main-thread": "^2.2.1",
"@types/dedent": "^0.7.0", "@types/dedent": "^0.7.0",
"@types/mime-types": "^2.1.0", "@types/mime-types": "^2.1.0",
"@types/node": "^14.14.7", "@types/node": "^14.14.7",
@@ -32,7 +32,7 @@
"lodash.camelcase": "^4.3.0", "lodash.camelcase": "^4.3.0",
"mime-types": "^2.1.28", "mime-types": "^2.1.28",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
"pointer-tracker": "^2.5.3", "pointer-tracker": "^2.4.0",
"postcss": "^7.0.35", "postcss": "^7.0.35",
"postcss-modules": "^3.2.2", "postcss-modules": "^3.2.2",
"postcss-nested": "^4.2.3", "postcss-nested": "^4.2.3",
@@ -58,6 +58,6 @@
"*.rs": "rustfmt" "*.rs": "rustfmt"
}, },
"dependencies": { "dependencies": {
"wasm-feature-detect": "^1.2.11" "wasm-feature-detect": "^1.2.9"
} }
} }

View File

@@ -18,7 +18,6 @@ import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser'; import { terser } from 'rollup-plugin-terser';
import OMT from '@surma/rollup-plugin-off-main-thread'; import OMT from '@surma/rollup-plugin-off-main-thread';
import replace from '@rollup/plugin-replace'; import replace from '@rollup/plugin-replace';
import { importMetaAssets } from '@web/rollup-plugin-import-meta-assets';
import simpleTS from './lib/simple-ts'; import simpleTS from './lib/simple-ts';
import clientBundlePlugin from './lib/client-bundle-plugin'; import clientBundlePlugin from './lib/client-bundle-plugin';
@@ -32,12 +31,11 @@ import featurePlugin from './lib/feature-plugin';
import initialCssPlugin from './lib/initial-css-plugin'; import initialCssPlugin from './lib/initial-css-plugin';
import serviceWorkerPlugin from './lib/sw-plugin'; import serviceWorkerPlugin from './lib/sw-plugin';
import dataURLPlugin from './lib/data-url-plugin'; import dataURLPlugin from './lib/data-url-plugin';
import asTextPlugin from './lib/as-text-plugin';
import entryDataPlugin, { fileNameToURL } from './lib/entry-data-plugin';
import dedent from 'dedent'; import dedent from 'dedent';
import entryDataPlugin from './lib/entry-data-plugin';
function resolveFileUrl({ fileName }) { function resolveFileUrl({ fileName }) {
return JSON.stringify(fileNameToURL(fileName)); return JSON.stringify(fileName.replace(/^static\//, '/'));
} }
function resolveImportMetaUrlInStaticBuild(property, { moduleId }) { function resolveImportMetaUrlInStaticBuild(property, { moduleId }) {
@@ -72,7 +70,7 @@ export default async function ({ watch }) {
await del('.tmp/build'); await del('.tmp/build');
const isProduction = !watch; const isProduction = !watch && !process.env.DEBUG;
const tsPluginInstance = simpleTS('.', { const tsPluginInstance = simpleTS('.', {
watch, watch,
@@ -90,7 +88,6 @@ export default async function ({ watch }) {
'codecs', 'codecs',
]), ]),
urlPlugin(), urlPlugin(),
asTextPlugin(),
dataURLPlugin(), dataURLPlugin(),
cssPlugin(), cssPlugin(),
]; ];
@@ -121,7 +118,6 @@ export default async function ({ watch }) {
plugins: [ plugins: [
{ resolveFileUrl }, { resolveFileUrl },
OMT({ loader: await omtLoaderPromise }), OMT({ loader: await omtLoaderPromise }),
importMetaAssets(),
serviceWorkerPlugin({ serviceWorkerPlugin({
output: 'static/serviceworker.js', output: 'static/serviceworker.js',
}), }),

View File

@@ -37,10 +37,8 @@ main();
ga('set', 'transport', 'beacon'); ga('set', 'transport', 'beacon');
ga('set', 'dimension1', displayMode); ga('set', 'dimension1', displayMode);
ga('send', 'pageview', '/index.html', { title: 'Squoosh' }); ga('send', 'pageview', '/index.html', { title: 'Squoosh' });
// Load the GA script without keeping the browser spinner going. // Load the GA script
addEventListener('load', () => { const script = document.createElement('script');
const script = document.createElement('script'); script.src = 'https://www.google-analytics.com/analytics.js';
script.src = 'https://www.google-analytics.com/analytics.js'; document.head.appendChild(script);
document.head.appendChild(script);
});
} }

View File

@@ -20,7 +20,7 @@ const REFLECTED_ATTRIBUTES = [
'disabled', 'disabled',
]; ];
function getPrecision(value: string): number { function getPrescision(value: string): number {
const afterDecimal = value.split('.')[1]; const afterDecimal = value.split('.')[1];
return afterDecimal ? afterDecimal.length : 0; return afterDecimal ? afterDecimal.length : 0;
} }
@@ -112,24 +112,18 @@ class RangeInputElement extends HTMLElement {
this.dispatchEvent(retargetted); this.dispatchEvent(retargetted);
}; };
private _getDisplayValue(value: number): string {
if (value >= 10000) return (value / 1000).toFixed(1) + 'k';
const labelPrecision =
Number(this.labelPrecision) || getPrecision(this.step) || 0;
return labelPrecision
? value.toFixed(labelPrecision)
: Math.round(value).toString();
}
private _update = () => { private _update = () => {
// Not connected? // Not connected?
if (!this._valueDisplay) return; if (!this._valueDisplay) return;
const value = Number(this.value) || 0; const value = Number(this.value) || 0;
const min = Number(this.min) || 0; const min = Number(this.min) || 0;
const max = Number(this.max) || 100; const max = Number(this.max) || 100;
const labelPrecision =
Number(this.labelPrecision) || getPrescision(this.step) || 0;
const percent = (100 * (value - min)) / (max - min); const percent = (100 * (value - min)) / (max - min);
const displayValue = this._getDisplayValue(value); const displayValue = labelPrecision
? value.toFixed(labelPrecision)
: Math.round(value).toString();
this._valueDisplay!.textContent = displayValue; this._valueDisplay!.textContent = displayValue;
this.style.setProperty('--value-percent', percent + '%'); this.style.setProperty('--value-percent', percent + '%');

View File

@@ -35,7 +35,7 @@
text-decoration-style: dotted; text-decoration-style: dotted;
text-decoration-color: var(--main-theme-color); text-decoration-color: var(--main-theme-color);
text-underline-position: under; text-underline-position: under;
width: 54px; width: 48px;
position: relative; position: relative;
left: 5px; left: 5px;

View File

@@ -1,7 +1,6 @@
.options-scroller { .options-scroller {
--horizontal-padding: 15px; --horizontal-padding: 15px;
border-radius: var(--scroller-radius); border-radius: var(--scroller-radius);
overflow: hidden;
/* At smaller widths, the multi-panel handles the scrolling */ /* At smaller widths, the multi-panel handles the scrolling */
@media (min-width: 600px) { @media (min-width: 600px) {

View File

@@ -1,6 +1,5 @@
import PointerTracker, { Pointer } from 'pointer-tracker'; import PointerTracker, { Pointer } from 'pointer-tracker';
import 'add-css:./styles.css'; import 'add-css:./styles.css';
import { isSafari } from 'client/lazy-app/util';
interface Point { interface Point {
clientX: number; clientX: number;
@@ -82,7 +81,6 @@ function createPoint(): SVGPoint {
} }
const MIN_SCALE = 0.01; const MIN_SCALE = 0.01;
const MAX_SCALE = 100000;
export default class PinchZoom extends HTMLElement { export default class PinchZoom extends HTMLElement {
// The element that we'll transform. // The element that we'll transform.
@@ -106,23 +104,14 @@ export default class PinchZoom extends HTMLElement {
const pointerTracker: PointerTracker = new PointerTracker(this, { const pointerTracker: PointerTracker = new PointerTracker(this, {
start: (pointer, event) => { start: (pointer, event) => {
// We only want to track 2 pointers at most // We only want to track 2 pointers at most
if ( if (pointerTracker.currentPointers.length === 2 || !this._positioningEl)
pointerTracker.currentPointers.length === 2 ||
!this._positioningEl
) {
return false; return false;
}
event.preventDefault(); event.preventDefault();
return true; return true;
}, },
move: (previousPointers) => { move: (previousPointers) => {
this._onPointerMove(previousPointers, pointerTracker.currentPointers); this._onPointerMove(previousPointers, pointerTracker.currentPointers);
}, },
// Unfortunately Safari on iOS has a bug where pointer event capturing
// doesn't work in some cases, and we hit those cases due to our event
// retargeting in pinch-zoom.
// https://bugs.webkit.org/show_bug.cgi?id=220196
avoidPointerEvents: isSafari,
}); });
this.addEventListener('wheel', (event) => this._onWheel(event)); this.addEventListener('wheel', (event) => this._onWheel(event));
@@ -255,9 +244,6 @@ export default class PinchZoom extends HTMLElement {
// Avoid scaling to zero // Avoid scaling to zero
if (scale < MIN_SCALE) return; if (scale < MIN_SCALE) return;
// Avoid scaling to very large values
if (scale > MAX_SCALE) return;
// Return if there's no change // Return if there's no change
if (scale === this.scale && x === this.x && y === this.y) return; if (scale === this.scale && x === this.x && y === this.y) return;
@@ -310,13 +296,9 @@ export default class PinchZoom extends HTMLElement {
deltaY *= 15; deltaY *= 15;
} }
const zoomingOut = deltaY > 0;
// ctrlKey is true when pinch-zooming on a trackpad. // ctrlKey is true when pinch-zooming on a trackpad.
const divisor = ctrlKey ? 100 : 300; const divisor = ctrlKey ? 100 : 300;
// when zooming out, invert the delta and the ratio to keep zoom stable const scaleDiff = 1 - deltaY / divisor;
const ratio = 1 - (zoomingOut ? -deltaY : deltaY) / divisor;
const scaleDiff = zoomingOut ? 1 / ratio : ratio;
this._applyChange({ this._applyChange({
scaleDiff, scaleDiff,

View File

@@ -5,10 +5,8 @@ import './custom-els/PinchZoom';
import './custom-els/TwoUp'; import './custom-els/TwoUp';
import * as style from './style.css'; import * as style from './style.css';
import 'add-css:./style.css'; import 'add-css:./style.css';
import { shallowEqual, isSafari } from '../../util'; import { shallowEqual } from '../../util';
import { import {
ToggleAliasingIcon,
ToggleAliasingActiveIcon,
ToggleBackgroundIcon, ToggleBackgroundIcon,
AddIcon, AddIcon,
RemoveIcon, RemoveIcon,
@@ -21,6 +19,7 @@ import { cleanSet } from '../../util/clean-modify';
import type { SourceImage } from '../../Compress'; import type { SourceImage } from '../../Compress';
import { linkRef } from 'shared/prerendered-app/util'; import { linkRef } from 'shared/prerendered-app/util';
import { drawDataToCanvas } from 'client/lazy-app/util/canvas'; import { drawDataToCanvas } from 'client/lazy-app/util/canvas';
interface Props { interface Props {
source?: SourceImage; source?: SourceImage;
preprocessorState?: PreprocessorState; preprocessorState?: PreprocessorState;
@@ -36,7 +35,6 @@ interface State {
scale: number; scale: number;
editingScale: boolean; editingScale: boolean;
altBackground: boolean; altBackground: boolean;
aliasing: boolean;
} }
const scaleToOpts: ScaleToOpts = { const scaleToOpts: ScaleToOpts = {
@@ -51,7 +49,6 @@ export default class Output extends Component<Props, State> {
scale: 1, scale: 1,
editingScale: false, editingScale: false,
altBackground: false, altBackground: false,
aliasing: false,
}; };
canvasLeft?: HTMLCanvasElement; canvasLeft?: HTMLCanvasElement;
canvasRight?: HTMLCanvasElement; canvasRight?: HTMLCanvasElement;
@@ -148,12 +145,6 @@ export default class Output extends Component<Props, State> {
return props.rightCompressed || (props.source && props.source.preprocessed); return props.rightCompressed || (props.source && props.source.preprocessed);
} }
private toggleAliasing = () => {
this.setState((state) => ({
aliasing: !state.aliasing,
}));
};
private toggleBackground = () => { private toggleBackground = () => {
this.setState({ this.setState({
altBackground: !this.state.altBackground, altBackground: !this.state.altBackground,
@@ -264,7 +255,7 @@ export default class Output extends Component<Props, State> {
render( render(
{ mobileView, leftImgContain, rightImgContain, source }: Props, { mobileView, leftImgContain, rightImgContain, source }: Props,
{ scale, editingScale, altBackground, aliasing }: State, { scale, editingScale, altBackground }: State,
) { ) {
const leftDraw = this.leftDrawable(); const leftDraw = this.leftDrawable();
const rightDraw = this.rightDrawable(); const rightDraw = this.rightDrawable();
@@ -284,11 +275,7 @@ export default class Output extends Component<Props, State> {
onTouchStartCapture={this.onRetargetableEvent} onTouchStartCapture={this.onRetargetableEvent}
onTouchEndCapture={this.onRetargetableEvent} onTouchEndCapture={this.onRetargetableEvent}
onTouchMoveCapture={this.onRetargetableEvent} onTouchMoveCapture={this.onRetargetableEvent}
onPointerDownCapture={ onPointerDownCapture={this.onRetargetableEvent}
// We avoid pointer events in our PinchZoom due to a Safari bug.
// That means we also need to avoid them here too, else we end up preventing the fallback mouse events.
isSafari ? undefined : this.onRetargetableEvent
}
onMouseDownCapture={this.onRetargetableEvent} onMouseDownCapture={this.onRetargetableEvent}
onWheelCapture={this.onRetargetableEvent} onWheelCapture={this.onRetargetableEvent}
> >
@@ -298,9 +285,7 @@ export default class Output extends Component<Props, State> {
ref={linkRef(this, 'pinchZoomLeft')} ref={linkRef(this, 'pinchZoomLeft')}
> >
<canvas <canvas
class={`${style.pinchTarget} ${ class={style.pinchTarget}
aliasing ? style.pixelated : ''
}`}
ref={linkRef(this, 'canvasLeft')} ref={linkRef(this, 'canvasLeft')}
width={leftDraw && leftDraw.width} width={leftDraw && leftDraw.width}
height={leftDraw && leftDraw.height} height={leftDraw && leftDraw.height}
@@ -316,9 +301,7 @@ export default class Output extends Component<Props, State> {
ref={linkRef(this, 'pinchZoomRight')} ref={linkRef(this, 'pinchZoomRight')}
> >
<canvas <canvas
class={`${style.pinchTarget} ${ class={style.pinchTarget}
aliasing ? style.pixelated : ''
}`}
ref={linkRef(this, 'canvasRight')} ref={linkRef(this, 'canvasRight')}
width={rightDraw && rightDraw.width} width={rightDraw && rightDraw.width}
height={rightDraw && rightDraw.height} height={rightDraw && rightDraw.height}
@@ -362,31 +345,10 @@ export default class Output extends Component<Props, State> {
</button> </button>
</div> </div>
<div class={style.buttonGroup}> <div class={style.buttonGroup}>
<button <button class={style.firstButton} onClick={this.onRotateClick}>
class={style.firstButton}
onClick={this.onRotateClick}
title="Rotate"
>
<RotateIcon /> <RotateIcon />
</button> </button>
{!isSafari && ( <button class={style.lastButton} onClick={this.toggleBackground}>
<button
class={style.button}
onClick={this.toggleAliasing}
title="Toggle smoothing"
>
{aliasing ? (
<ToggleAliasingActiveIcon />
) : (
<ToggleAliasingIcon />
)}
</button>
)}
<button
class={style.lastButton}
onClick={this.toggleBackground}
title="Toggle background"
>
{altBackground ? ( {altBackground ? (
<ToggleBackgroundActiveIcon /> <ToggleBackgroundActiveIcon />
) : ( ) : (

View File

@@ -86,7 +86,8 @@
font-size: 1.2rem; font-size: 1.2rem;
cursor: pointer; cursor: pointer;
&:focus-visible { &:focus {
/* box-shadow: 0 0 0 2px var(--hot-pink); */
box-shadow: 0 0 0 2px #fff; box-shadow: 0 0 0 2px #fff;
outline: none; outline: none;
z-index: 1; z-index: 1;
@@ -160,8 +161,3 @@ input.zoom {
pointer-events: auto; pointer-events: auto;
} }
} }
.pixelated {
image-rendering: crisp-edges;
image-rendering: pixelated;
}

View File

@@ -11,25 +11,6 @@ const Icon = (props: preact.JSX.HTMLAttributes) => (
/> />
); );
export const ToggleAliasingIcon = (props: preact.JSX.HTMLAttributes) => (
<Icon {...props}>
<circle
cx="12"
cy="12"
r="8"
fill="none"
stroke="currentColor"
stroke-width="2"
/>
</Icon>
);
export const ToggleAliasingActiveIcon = (props: preact.JSX.HTMLAttributes) => (
<Icon {...props}>
<path d="M12 3h5v2h2v2h2v5h-2V9h-2V7h-2V5h-3V3M21 12v5h-2v2h-2v2h-5v-2h3v-2h2v-2h2v-3h2M12 21H7v-2H5v-2H3v-5h2v3h2v2h2v2h3v2M3 12V7h2V5h2V3h5v2H9v2H7v2H5v3H3" />
</Icon>
);
export const ToggleBackgroundIcon = (props: preact.JSX.HTMLAttributes) => ( export const ToggleBackgroundIcon = (props: preact.JSX.HTMLAttributes) => (
<Icon {...props}> <Icon {...props}>
<path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm2 4v-2H3c0 1.1.9 2 2 2zM3 9h2V7H3v2zm12 12h2v-2h-2v2zm4-18H9a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h10a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2zm0 12H9V5h10v10zm-8 6h2v-2h-2v2zm-4 0h2v-2H7v2z" /> <path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm2 4v-2H3c0 1.1.9 2 2 2zM3 9h2V7H3v2zm12 12h2v-2h-2v2zm4-18H9a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h10a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2zm0 12H9V5h10v10zm-8 6h2v-2h-2v2zm-4 0h2v-2H7v2z" />

View File

@@ -14,11 +14,6 @@
import * as WebCodecs from '../util/web-codecs'; import * as WebCodecs from '../util/web-codecs';
import { drawableToImageData } from './canvas'; import { drawableToImageData } from './canvas';
/** If render engine is Safari */
export const isSafari =
/Safari\//.test(navigator.userAgent) &&
!/Chrom(e|ium)\//.test(navigator.userAgent);
/** /**
* Compare two objects, returning a boolean indicating if * Compare two objects, returning a boolean indicating if
* they have the same properties and strictly equal values. * they have the same properties and strictly equal values.

View File

@@ -19,4 +19,9 @@ interface Navigator {
declare module 'add-css:*' {} declare module 'add-css:*' {}
declare module 'service-worker:*' {
const url: string;
export default url;
}
declare module 'preact/debug' {} declare module 'preact/debug' {}

View File

@@ -11,6 +11,7 @@
* limitations under the License. * limitations under the License.
*/ */
import type { AVIFModule } from 'codecs/avif/dec/avif_dec'; import type { AVIFModule } from 'codecs/avif/dec/avif_dec';
import wasmUrl from 'url:codecs/avif/dec/avif_dec.wasm';
import { initEmscriptenModule, blobToArrayBuffer } from 'features/worker-utils'; import { initEmscriptenModule, blobToArrayBuffer } from 'features/worker-utils';
let emscriptenModule: Promise<AVIFModule>; let emscriptenModule: Promise<AVIFModule>;
@@ -18,7 +19,7 @@ let emscriptenModule: Promise<AVIFModule>;
export default async function decode(blob: Blob): Promise<ImageData> { export default async function decode(blob: Blob): Promise<ImageData> {
if (!emscriptenModule) { if (!emscriptenModule) {
const decoder = await import('codecs/avif/dec/avif_dec'); const decoder = await import('codecs/avif/dec/avif_dec');
emscriptenModule = initEmscriptenModule(decoder.default); emscriptenModule = initEmscriptenModule(decoder.default, wasmUrl);
} }
const [module, data] = await Promise.all([ const [module, data] = await Promise.all([

View File

@@ -11,13 +11,14 @@
* limitations under the License. * limitations under the License.
*/ */
import jxlDecoder, { JXLModule } from 'codecs/jxl/dec/jxl_dec'; import jxlDecoder, { JXLModule } from 'codecs/jxl/dec/jxl_dec';
import wasmUrl from 'url:codecs/jxl/dec/jxl_dec.wasm';
import { initEmscriptenModule, blobToArrayBuffer } from 'features/worker-utils'; import { initEmscriptenModule, blobToArrayBuffer } from 'features/worker-utils';
let emscriptenModule: Promise<JXLModule>; let emscriptenModule: Promise<JXLModule>;
export default async function decode(blob: Blob): Promise<ImageData> { export default async function decode(blob: Blob): Promise<ImageData> {
if (!emscriptenModule) { if (!emscriptenModule) {
emscriptenModule = initEmscriptenModule(jxlDecoder); emscriptenModule = initEmscriptenModule(jxlDecoder, wasmUrl);
} }
const [module, data] = await Promise.all([ const [module, data] = await Promise.all([

View File

@@ -11,6 +11,7 @@
* limitations under the License. * limitations under the License.
*/ */
import type { WebPModule } from 'codecs/webp/dec/webp_dec'; import type { WebPModule } from 'codecs/webp/dec/webp_dec';
import wasmUrl from 'url:codecs/webp/dec/webp_dec.wasm';
import { initEmscriptenModule, blobToArrayBuffer } from 'features/worker-utils'; import { initEmscriptenModule, blobToArrayBuffer } from 'features/worker-utils';
let emscriptenModule: Promise<WebPModule>; let emscriptenModule: Promise<WebPModule>;
@@ -18,7 +19,7 @@ let emscriptenModule: Promise<WebPModule>;
export default async function decode(blob: Blob): Promise<ImageData> { export default async function decode(blob: Blob): Promise<ImageData> {
if (!emscriptenModule) { if (!emscriptenModule) {
const decoder = await import('codecs/webp/dec/webp_dec'); const decoder = await import('codecs/webp/dec/webp_dec');
emscriptenModule = initEmscriptenModule(decoder.default); emscriptenModule = initEmscriptenModule(decoder.default, wasmUrl);
} }
const [module, data] = await Promise.all([ const [module, data] = await Promise.all([

View File

@@ -11,13 +11,14 @@
* limitations under the License. * limitations under the License.
*/ */
import wp2Decoder, { WP2Module } from 'codecs/wp2/dec/wp2_dec'; import wp2Decoder, { WP2Module } from 'codecs/wp2/dec/wp2_dec';
import wasmUrl from 'url:codecs/wp2/dec/wp2_dec.wasm';
import { initEmscriptenModule, blobToArrayBuffer } from 'features/worker-utils'; import { initEmscriptenModule, blobToArrayBuffer } from 'features/worker-utils';
let emscriptenModule: Promise<WP2Module>; let emscriptenModule: Promise<WP2Module>;
export default async function decode(blob: Blob): Promise<ImageData> { export default async function decode(blob: Blob): Promise<ImageData> {
if (!emscriptenModule) { if (!emscriptenModule) {
emscriptenModule = initEmscriptenModule(wp2Decoder); emscriptenModule = initEmscriptenModule(wp2Decoder, wasmUrl);
} }
const [module, data] = await Promise.all([ const [module, data] = await Promise.all([

View File

@@ -12,6 +12,9 @@
*/ */
import type { AVIFModule } from 'codecs/avif/enc/avif_enc'; import type { AVIFModule } from 'codecs/avif/enc/avif_enc';
import type { EncodeOptions } from '../shared/meta'; import type { EncodeOptions } from '../shared/meta';
import wasmUrlWithoutMT from 'url:codecs/avif/enc/avif_enc.wasm';
import wasmUrlWithMT from 'url:codecs/avif/enc/avif_enc_mt.wasm';
import workerUrl from 'omt:codecs/avif/enc/avif_enc_mt.worker.js';
import { initEmscriptenModule } from 'features/worker-utils'; import { initEmscriptenModule } from 'features/worker-utils';
import { threads } from 'wasm-feature-detect'; import { threads } from 'wasm-feature-detect';
@@ -20,10 +23,14 @@ let emscriptenModule: Promise<AVIFModule>;
async function init() { async function init() {
if (await threads()) { if (await threads()) {
const avifEncoder = await import('codecs/avif/enc/avif_enc_mt'); const avifEncoder = await import('codecs/avif/enc/avif_enc_mt');
return initEmscriptenModule<AVIFModule>(avifEncoder.default); return initEmscriptenModule<AVIFModule>(
avifEncoder.default,
wasmUrlWithMT,
workerUrl,
);
} }
const avifEncoder = await import('codecs/avif/enc/avif_enc.js'); const avifEncoder = await import('codecs/avif/enc/avif_enc.js');
return initEmscriptenModule(avifEncoder.default); return initEmscriptenModule(avifEncoder.default, wasmUrlWithoutMT);
} }
export default async function encode( export default async function encode(

View File

@@ -29,9 +29,10 @@ interface State {
slightLoss: boolean; slightLoss: boolean;
autoEdgePreservingFilter: boolean; autoEdgePreservingFilter: boolean;
decodingSpeedTier: number; decodingSpeedTier: number;
photonNoiseIso: number;
} }
const maxSpeed = 7;
export class Options extends Component<Props, State> { export class Options extends Component<Props, State> {
static getDerivedStateFromProps( static getDerivedStateFromProps(
props: Props, props: Props,
@@ -46,7 +47,7 @@ export class Options extends Component<Props, State> {
// Create default form state from options // Create default form state from options
return { return {
options, options,
effort: options.effort, effort: maxSpeed - options.speed,
quality: options.quality, quality: options.quality,
progressive: options.progressive, progressive: options.progressive,
edgePreservingFilter: options.epf === -1 ? 2 : options.epf, edgePreservingFilter: options.epf === -1 ? 2 : options.epf,
@@ -54,7 +55,6 @@ export class Options extends Component<Props, State> {
slightLoss: options.lossyPalette, slightLoss: options.lossyPalette,
autoEdgePreservingFilter: options.epf === -1, autoEdgePreservingFilter: options.epf === -1,
decodingSpeedTier: options.decodingSpeedTier, decodingSpeedTier: options.decodingSpeedTier,
photonNoiseIso: options.photonNoiseIso,
}; };
} }
@@ -87,15 +87,15 @@ export class Options extends Component<Props, State> {
}; };
const newOptions: EncodeOptions = { const newOptions: EncodeOptions = {
effort: optionState.effort, speed: maxSpeed - optionState.effort,
quality: optionState.lossless ? 100 : optionState.quality, quality: optionState.lossless ? 100 : optionState.quality,
progressive: optionState.progressive, progressive: optionState.progressive,
epf: optionState.autoEdgePreservingFilter epf: optionState.autoEdgePreservingFilter
? -1 ? -1
: optionState.edgePreservingFilter, : optionState.edgePreservingFilter,
nearLossless: 0,
lossyPalette: optionState.lossless ? optionState.slightLoss : false, lossyPalette: optionState.lossless ? optionState.slightLoss : false,
decodingSpeedTier: optionState.decodingSpeedTier, decodingSpeedTier: optionState.decodingSpeedTier,
photonNoiseIso: optionState.photonNoiseIso,
}; };
// Updating options, so we don't recalculate in getDerivedStateFromProps. // Updating options, so we don't recalculate in getDerivedStateFromProps.
@@ -121,7 +121,6 @@ export class Options extends Component<Props, State> {
slightLoss, slightLoss,
autoEdgePreservingFilter, autoEdgePreservingFilter,
decodingSpeedTier, decodingSpeedTier,
photonNoiseIso,
}: State, }: State,
) { ) {
// I'm rendering both lossy and lossless forms, as it becomes much easier when // I'm rendering both lossy and lossless forms, as it becomes much easier when
@@ -165,6 +164,7 @@ export class Options extends Component<Props, State> {
<label class={style.optionToggle}> <label class={style.optionToggle}>
Auto edge filter Auto edge filter
<Checkbox <Checkbox
name="autoEdgeFilter"
checked={autoEdgePreservingFilter} checked={autoEdgePreservingFilter}
onChange={this._inputChange( onChange={this._inputChange(
'autoEdgePreservingFilter', 'autoEdgePreservingFilter',
@@ -199,17 +199,6 @@ export class Options extends Component<Props, State> {
Optimise for decoding speed (worse compression): Optimise for decoding speed (worse compression):
</Range> </Range>
</div> </div>
<div class={style.optionOneCell}>
<Range
min="0"
max="50000"
step="100"
value={photonNoiseIso}
onInput={this._inputChange('photonNoiseIso', 'number')}
>
Noise equivalent to ISO:
</Range>
</div>
</div> </div>
)} )}
</Expander> </Expander>
@@ -223,8 +212,8 @@ export class Options extends Component<Props, State> {
</label> </label>
<div class={style.optionOneCell}> <div class={style.optionOneCell}>
<Range <Range
min="3" min="0"
max="9" max={maxSpeed - 1}
value={effort} value={effort}
onInput={this._inputChange('effort', 'number')} onInput={this._inputChange('effort', 'number')}
> >

View File

@@ -18,11 +18,11 @@ export const label = 'JPEG XL (beta)';
export const mimeType = 'image/jxl'; export const mimeType = 'image/jxl';
export const extension = 'jxl'; export const extension = 'jxl';
export const defaultOptions: EncodeOptions = { export const defaultOptions: EncodeOptions = {
effort: 7, speed: 4,
quality: 75, quality: 75,
progressive: false, progressive: false,
epf: -1, epf: -1,
nearLossless: 0,
lossyPalette: false, lossyPalette: false,
decodingSpeedTier: 0, decodingSpeedTier: 0,
photonNoiseIso: 0,
}; };

View File

@@ -16,19 +16,31 @@ import type { EncodeOptions } from '../shared/meta';
import { initEmscriptenModule } from 'features/worker-utils'; import { initEmscriptenModule } from 'features/worker-utils';
import { threads, simd } from 'wasm-feature-detect'; import { threads, simd } from 'wasm-feature-detect';
import wasmUrl from 'url:codecs/jxl/enc/jxl_enc.wasm';
import wasmUrlWithMT from 'url:codecs/jxl/enc/jxl_enc_mt.wasm';
import workerUrl from 'omt:codecs/jxl/enc/jxl_enc_mt.worker.js';
import wasmUrlWithMTAndSIMD from 'url:codecs/jxl/enc/jxl_enc_mt_simd.wasm';
import workerUrlWithSIMD from 'omt:codecs/jxl/enc/jxl_enc_mt_simd.worker.js';
let emscriptenModule: Promise<JXLModule>; let emscriptenModule: Promise<JXLModule>;
async function init() { async function init() {
if (await threads()) { if (await threads()) {
if (await simd()) { if (await simd()) {
const jxlEncoder = await import('codecs/jxl/enc/jxl_enc_mt_simd'); const jxlEncoder = await import('codecs/jxl/enc/jxl_enc_mt_simd');
return initEmscriptenModule(jxlEncoder.default); return initEmscriptenModule(
jxlEncoder.default,
wasmUrlWithMTAndSIMD,
workerUrlWithSIMD,
);
} }
const jxlEncoder = await import('codecs/jxl/enc/jxl_enc_mt'); const jxlEncoder = await import('codecs/jxl/enc/jxl_enc_mt');
return initEmscriptenModule(jxlEncoder.default); return initEmscriptenModule(jxlEncoder.default, wasmUrlWithMT, workerUrl);
} }
const jxlEncoder = await import('codecs/jxl/enc/jxl_enc'); const jxlEncoder = await import('codecs/jxl/enc/jxl_enc');
return initEmscriptenModule(jxlEncoder.default); return initEmscriptenModule(jxlEncoder.default, wasmUrl);
} }
export default async function encode( export default async function encode(

View File

@@ -12,6 +12,7 @@
*/ */
import mozjpeg_enc, { MozJPEGModule } from 'codecs/mozjpeg/enc/mozjpeg_enc'; import mozjpeg_enc, { MozJPEGModule } from 'codecs/mozjpeg/enc/mozjpeg_enc';
import { EncodeOptions } from '../shared/meta'; import { EncodeOptions } from '../shared/meta';
import wasmUrl from 'url:codecs/mozjpeg/enc/mozjpeg_enc.wasm';
import { initEmscriptenModule } from 'features/worker-utils'; import { initEmscriptenModule } from 'features/worker-utils';
let emscriptenModule: Promise<MozJPEGModule>; let emscriptenModule: Promise<MozJPEGModule>;
@@ -21,7 +22,7 @@ export default async function encode(
options: EncodeOptions, options: EncodeOptions,
): Promise<ArrayBuffer> { ): Promise<ArrayBuffer> {
if (!emscriptenModule) { if (!emscriptenModule) {
emscriptenModule = initEmscriptenModule(mozjpeg_enc); emscriptenModule = initEmscriptenModule(mozjpeg_enc, wasmUrl);
} }
const module = await emscriptenModule; const module = await emscriptenModule;

View File

@@ -10,27 +10,30 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import initOxiWasmST, {
optimise as optimiseST,
} from 'codecs/oxipng/pkg/squoosh_oxipng';
import initOxiWasmMT, {
initThreadPool,
optimise as optimiseMT,
} from 'codecs/oxipng/pkg-parallel/squoosh_oxipng';
import oxiWasmUrlST from 'url:codecs/oxipng/pkg/squoosh_oxipng_bg.wasm';
import oxiWasmUrlMT from 'url:codecs/oxipng/pkg-parallel/squoosh_oxipng_bg.wasm';
import { EncodeOptions } from '../shared/meta'; import { EncodeOptions } from '../shared/meta';
import { threads } from 'wasm-feature-detect'; import { threads } from 'wasm-feature-detect';
async function initMT() { async function initMT() {
const { default: init, initThreadPool, optimise } = await import( await initOxiWasmMT(oxiWasmUrlMT);
'codecs/oxipng/pkg-parallel/squoosh_oxipng'
);
await init();
await initThreadPool(navigator.hardwareConcurrency); await initThreadPool(navigator.hardwareConcurrency);
return optimise; return optimiseMT;
} }
async function initST() { async function initST() {
const { default: init, optimise } = await import( await initOxiWasmST(oxiWasmUrlST);
'codecs/oxipng/pkg/squoosh_oxipng' return optimiseST;
);
await init();
return optimise;
} }
let wasmReady: ReturnType<typeof initMT | typeof initST>; let wasmReady: Promise<typeof optimiseMT | typeof optimiseST>;
export default async function encode( export default async function encode(
data: ArrayBuffer, data: ArrayBuffer,

View File

@@ -16,15 +16,18 @@ import type { EncodeOptions } from '../shared/meta';
import { initEmscriptenModule } from 'features/worker-utils'; import { initEmscriptenModule } from 'features/worker-utils';
import { simd } from 'wasm-feature-detect'; import { simd } from 'wasm-feature-detect';
import wasmUrl from 'url:codecs/webp/enc/webp_enc.wasm';
import wasmUrlWithSIMD from 'url:codecs/webp/enc/webp_enc_simd.wasm';
let emscriptenModule: Promise<WebPModule>; let emscriptenModule: Promise<WebPModule>;
async function init() { async function init() {
if (await simd()) { if (await simd()) {
const webpEncoder = await import('codecs/webp/enc/webp_enc_simd'); const webpEncoder = await import('codecs/webp/enc/webp_enc_simd');
return initEmscriptenModule(webpEncoder.default); return initEmscriptenModule(webpEncoder.default, wasmUrlWithSIMD);
} }
const webpEncoder = await import('codecs/webp/enc/webp_enc'); const webpEncoder = await import('codecs/webp/enc/webp_enc');
return initEmscriptenModule(webpEncoder.default); return initEmscriptenModule(webpEncoder.default, wasmUrl);
} }
export default async function encode( export default async function encode(

View File

@@ -16,19 +16,31 @@ import type { EncodeOptions } from '../shared/meta';
import { initEmscriptenModule } from 'features/worker-utils'; import { initEmscriptenModule } from 'features/worker-utils';
import { threads, simd } from 'wasm-feature-detect'; import { threads, simd } from 'wasm-feature-detect';
import wasmUrl from 'url:codecs/wp2/enc/wp2_enc.wasm';
import wasmUrlWithMT from 'url:codecs/wp2/enc/wp2_enc_mt.wasm';
import workerUrl from 'omt:codecs/wp2/enc/wp2_enc_mt.worker.js';
import wasmUrlWithMTAndSIMD from 'url:codecs/wp2/enc/wp2_enc_mt_simd.wasm';
import workerUrlWithSIMD from 'omt:codecs/wp2/enc/wp2_enc_mt_simd.worker.js';
let emscriptenModule: Promise<WP2Module>; let emscriptenModule: Promise<WP2Module>;
async function init() { async function init() {
if (await threads()) { if (await threads()) {
if (await simd()) { if (await simd()) {
const wp2Encoder = await import('codecs/wp2/enc/wp2_enc_mt_simd'); const wp2Encoder = await import('codecs/wp2/enc/wp2_enc_mt_simd');
return initEmscriptenModule(wp2Encoder.default); return initEmscriptenModule(
wp2Encoder.default,
wasmUrlWithMTAndSIMD,
workerUrlWithSIMD,
);
} }
const wp2Encoder = await import('codecs/wp2/enc/wp2_enc_mt'); const wp2Encoder = await import('codecs/wp2/enc/wp2_enc_mt');
return initEmscriptenModule(wp2Encoder.default); return initEmscriptenModule(wp2Encoder.default, wasmUrlWithMT, workerUrl);
} }
const wp2Encoder = await import('codecs/wp2/enc/wp2_enc'); const wp2Encoder = await import('codecs/wp2/enc/wp2_enc');
return initEmscriptenModule(wp2Encoder.default); return initEmscriptenModule(wp2Encoder.default, wasmUrl);
} }
export default async function encode( export default async function encode(

View File

@@ -11,6 +11,7 @@
* limitations under the License. * limitations under the License.
*/ */
import imagequant, { QuantizerModule } from 'codecs/imagequant/imagequant'; import imagequant, { QuantizerModule } from 'codecs/imagequant/imagequant';
import wasmUrl from 'url:codecs/imagequant/imagequant.wasm';
import { initEmscriptenModule } from 'features/worker-utils'; import { initEmscriptenModule } from 'features/worker-utils';
import { Options } from '../shared/meta'; import { Options } from '../shared/meta';
@@ -21,7 +22,7 @@ export default async function process(
opts: Options, opts: Options,
): Promise<ImageData> { ): Promise<ImageData> {
if (!emscriptenModule) { if (!emscriptenModule) {
emscriptenModule = initEmscriptenModule(imagequant); emscriptenModule = initEmscriptenModule(imagequant, wasmUrl);
} }
const module = await emscriptenModule; const module = await emscriptenModule;

Some files were not shown because too many files have changed in this diff Show More