agglomerative-clustering 3.8.0 → 4.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/clustering.cjs +1 -1
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +64 -68
- package/dist/index.d.cts +43 -9
- package/dist/index.d.ts +43 -9
- package/dist/index.mjs +64 -68
- package/dist/shared.cjs +161 -3
- package/dist/shared.mjs +153 -1
- package/dist/worker.cjs +31 -14
- package/dist/worker.mjs +32 -15
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -82,7 +82,7 @@ slider.oninput = async () => {
|
|
|
82
82
|
};
|
|
83
83
|
```
|
|
84
84
|
|
|
85
|
-
Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight
|
|
85
|
+
Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight, or premultiplied (canvas, Electron): pass `premultiplied: true` with `'rgba'` or `'bgra'`; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources and what to pass for each. Mapped output of a premultiplied image comes back premultiplied (palettes and indices are straight), so for an `ImageData` or a PNG encoder use the [straight-output recipe](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#straight-pixels-from-a-premultiplied-source). RGB bytes passed bare are read as RGBA; the library warns when it sees this (an error from 4.0), so pass them as `{ data, format: 'rgb' }`. To start from a PNG, JPEG, WebP or GIF file, decode it first: [Decoding image files](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#decoding-image-files) has a recipe for Node, browsers and edge runtimes. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
|
|
86
86
|
|
|
87
87
|
## How it works
|
|
88
88
|
|
package/dist/clustering.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use strict";var __agglomerativeGlueUrl=typeof __filename=="string"&&typeof process!="undefined"&&typeof process.getBuiltinModule=="function"?process.getBuiltinModule("node:url").pathToFileURL(__filename).href:"";
|
|
2
|
-
async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",__agglomerativeGlueUrl).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["m"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["n"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["o"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["p"];_free=Module["_free"]=wasmExports["q"];_get_clustering=Module["_get_clustering"]=wasmExports["r"];_get_palette=Module["_get_palette"]=wasmExports["s"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["t"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["u"];_quantize=Module["_quantize"]=wasmExports["v"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["w"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["x"];_quantize_indices=Module["_quantize_indices"]=wasmExports["y"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["z"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["A"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
2
|
+
async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",__agglomerativeGlueUrl).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_unpremultiply,_premultiply,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_unpremultiply=Module["_unpremultiply"]=wasmExports["i"];_premultiply=Module["_premultiply"]=wasmExports["j"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["k"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["l"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["m"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["n"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["o"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["p"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["q"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["r"];_free=Module["_free"]=wasmExports["s"];_get_clustering=Module["_get_clustering"]=wasmExports["t"];_get_palette=Module["_get_palette"]=wasmExports["u"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["v"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["w"];_quantize=Module["_quantize"]=wasmExports["x"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["y"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["z"];_quantize_indices=Module["_quantize_indices"]=wasmExports["A"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["B"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["C"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
3
3
|
;return Module}module.exports=createWasmModule;
|
package/dist/clustering.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["m"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["n"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["o"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["p"];_free=Module["_free"]=wasmExports["q"];_get_clustering=Module["_get_clustering"]=wasmExports["r"];_get_palette=Module["_get_palette"]=wasmExports["s"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["t"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["u"];_quantize=Module["_quantize"]=wasmExports["v"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["w"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["x"];_quantize_indices=Module["_quantize_indices"]=wasmExports["y"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["z"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["A"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
1
|
+
async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_unpremultiply,_premultiply,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_unpremultiply=Module["_unpremultiply"]=wasmExports["i"];_premultiply=Module["_premultiply"]=wasmExports["j"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["k"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["l"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["m"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["n"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["o"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["p"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["q"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["r"];_free=Module["_free"]=wasmExports["s"];_get_clustering=Module["_get_clustering"]=wasmExports["t"];_get_palette=Module["_get_palette"]=wasmExports["u"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["v"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["w"];_quantize=Module["_quantize"]=wasmExports["x"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["y"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["z"];_quantize_indices=Module["_quantize_indices"]=wasmExports["A"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["B"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["C"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
2
2
|
;return Module}export default createWasmModule;
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|
package/dist/index.cjs
CHANGED
|
@@ -96,27 +96,6 @@ const codes = {
|
|
|
96
96
|
'rgbx': 3,
|
|
97
97
|
'bgrx': 4
|
|
98
98
|
};
|
|
99
|
-
// A hint for a format name that isn't one: the right case, the name other libraries use for the same bytes, or the nearest
|
|
100
|
-
// supported layout.
|
|
101
|
-
const formatHint = format => {
|
|
102
|
-
if (typeof format !== 'string') {
|
|
103
|
-
return '';
|
|
104
|
-
}
|
|
105
|
-
const lower = format.toLowerCase();
|
|
106
|
-
if (lower !== format && _shared.imageFormats.includes(lower)) {
|
|
107
|
-
return ` Format names are lower case: '${lower}'.`;
|
|
108
|
-
}
|
|
109
|
-
if (lower === 'xrgb' || lower === 'rgb24') {
|
|
110
|
-
return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
|
|
111
|
-
}
|
|
112
|
-
if (lower === 'argb' || lower === 'argb32') {
|
|
113
|
-
return " Cairo and node-canvas ARGB32 is BGRA in memory on little-endian machines, and premultiplied: convert it to straight alpha and pass 'bgra' (see Input in the API docs).";
|
|
114
|
-
}
|
|
115
|
-
if (lower === 'bgr' || lower === 'bgr24') {
|
|
116
|
-
return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
|
|
117
|
-
}
|
|
118
|
-
return '';
|
|
119
|
-
};
|
|
120
99
|
const alphaModeCodes = {
|
|
121
100
|
'ignore': 0,
|
|
122
101
|
'weight': 1
|
|
@@ -502,20 +481,6 @@ const bytes = data => (0, _shared.isUint8Array)(data) ? data : new Uint8Array(da
|
|
|
502
481
|
// call returns; until then (the first call) a copy is kept for when it has loaded.
|
|
503
482
|
const held = data => Module ? data : data.slice();
|
|
504
483
|
|
|
505
|
-
// width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
|
|
506
|
-
// pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
|
|
507
|
-
const checkSize = (pixels, size, name, argument) => {
|
|
508
|
-
if (size === undefined) {
|
|
509
|
-
return;
|
|
510
|
-
}
|
|
511
|
-
if (!Number.isInteger(size) || size < 0) {
|
|
512
|
-
throw (0, _shared.fail)('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
|
|
513
|
-
}
|
|
514
|
-
if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
|
|
515
|
-
throw (0, _shared.fail)('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
|
|
516
|
-
}
|
|
517
|
-
};
|
|
518
|
-
|
|
519
484
|
// The bare-image warning (rgb-as-rgba, gray-as-rgba) for an image, decided before load() and given only once the call's own checks have passed,
|
|
520
485
|
// just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
|
|
521
486
|
const noWarning = () => {};
|
|
@@ -547,7 +512,8 @@ const load = image => {
|
|
|
547
512
|
}
|
|
548
513
|
return {
|
|
549
514
|
data: held(image),
|
|
550
|
-
format: 'rgba'
|
|
515
|
+
format: 'rgba',
|
|
516
|
+
premultiplied: false
|
|
551
517
|
};
|
|
552
518
|
}
|
|
553
519
|
if ((0, _shared.isImageData)(image)) {
|
|
@@ -558,7 +524,8 @@ const load = image => {
|
|
|
558
524
|
return {
|
|
559
525
|
data: held(bytes(image.data)),
|
|
560
526
|
format: 'rgba',
|
|
561
|
-
width: image.width
|
|
527
|
+
width: image.width,
|
|
528
|
+
premultiplied: false
|
|
562
529
|
};
|
|
563
530
|
}
|
|
564
531
|
if (ArrayBuffer.isView(image)) {
|
|
@@ -567,29 +534,12 @@ const load = image => {
|
|
|
567
534
|
if (typeof image !== 'object' || !image || !image.data || !image.format) {
|
|
568
535
|
throw (0, _shared.fail)('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${(0, _shared.imageHint)(image)}`, 'image');
|
|
569
536
|
}
|
|
570
|
-
|
|
571
|
-
throw (0, _shared.fail)('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
|
|
572
|
-
}
|
|
573
|
-
if ((0, _shared.isDetached)(image.data)) {
|
|
574
|
-
throw (0, _shared.detachedError)('data');
|
|
575
|
-
}
|
|
576
|
-
if (!_shared.imageFormats.includes(image.format)) {
|
|
577
|
-
throw (0, _shared.fail)('invalid-argument', `Invalid format: got ${(0, _shared.describe)(image.format)}; it must be ${_shared.formatNames}.${formatHint(image.format)}`, 'image');
|
|
578
|
-
}
|
|
579
|
-
const stride = (0, _shared.channels)(image.format);
|
|
580
|
-
if (image.data.length % stride !== 0) {
|
|
581
|
-
throw (0, _shared.fail)('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
|
|
582
|
-
}
|
|
583
|
-
const pixels = image.data.length / stride;
|
|
584
|
-
checkSize(pixels, image.width, 'image width', 'image');
|
|
585
|
-
checkSize(pixels, image.height, 'image height', 'image');
|
|
586
|
-
if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
|
|
587
|
-
throw (0, _shared.fail)('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
|
|
588
|
-
}
|
|
537
|
+
const premultiplied = (0, _shared.checkImageBody)(image);
|
|
589
538
|
return {
|
|
590
539
|
data: held(bytes(image.data)),
|
|
591
540
|
format: image.format,
|
|
592
|
-
width: image.width
|
|
541
|
+
width: image.width,
|
|
542
|
+
premultiplied
|
|
593
543
|
};
|
|
594
544
|
};
|
|
595
545
|
const getWrapper = image => {
|
|
@@ -601,7 +551,8 @@ const getWrapper = image => {
|
|
|
601
551
|
const {
|
|
602
552
|
format,
|
|
603
553
|
width,
|
|
604
|
-
height
|
|
554
|
+
height,
|
|
555
|
+
premultiplied
|
|
605
556
|
} = image;
|
|
606
557
|
return output => {
|
|
607
558
|
const result = {
|
|
@@ -614,6 +565,9 @@ const getWrapper = image => {
|
|
|
614
565
|
if (height !== undefined) {
|
|
615
566
|
result.height = height;
|
|
616
567
|
}
|
|
568
|
+
if (premultiplied !== undefined) {
|
|
569
|
+
result.premultiplied = premultiplied;
|
|
570
|
+
}
|
|
617
571
|
return result;
|
|
618
572
|
};
|
|
619
573
|
}
|
|
@@ -718,7 +672,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
718
672
|
throw (0, _shared.fail)('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
|
|
719
673
|
}
|
|
720
674
|
if (options.width !== undefined && image) {
|
|
721
|
-
checkSize(image.data.length / (0, _shared.channels)(image.format), options.width, 'width', 'options.width');
|
|
675
|
+
(0, _shared.checkSize)(image.data.length / (0, _shared.channels)(image.format), options.width, 'width', 'options.width');
|
|
722
676
|
}
|
|
723
677
|
const width = options.width !== undefined ? options.width : image ? image.width : undefined;
|
|
724
678
|
if (dither > 0) {
|
|
@@ -806,7 +760,9 @@ const allocate = (wasm, length) => {
|
|
|
806
760
|
|
|
807
761
|
// Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
|
|
808
762
|
// freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
|
|
809
|
-
|
|
763
|
+
// `premultiplied` (the loaded image's flag) un-premultiplies the first buffer after it is copied in; `mapped` also premultiplies
|
|
764
|
+
// the output payload (a mapped image, not indexed output) before it is unpacked.
|
|
765
|
+
const call = (wasm, buffers, fn, precision, premultiplied, mapped) => {
|
|
810
766
|
const pointers = [];
|
|
811
767
|
let outputPointer = 0;
|
|
812
768
|
let aborted = false;
|
|
@@ -816,12 +772,18 @@ const call = (wasm, buffers, fn, precision) => {
|
|
|
816
772
|
pointers.push(pointer);
|
|
817
773
|
wasm.HEAPU8.set(buffer, pointer);
|
|
818
774
|
}
|
|
775
|
+
if (premultiplied) {
|
|
776
|
+
wasm._unpremultiply(pointers[0], 0, buffers[0].length >> 2);
|
|
777
|
+
}
|
|
819
778
|
outputPointer = fn(...pointers);
|
|
820
779
|
// Only the functions that read a clustering return nothing: when its records don't fit together (see
|
|
821
780
|
// _get_palette_from_clustering), which a clustering whose checksum matches never does.
|
|
822
781
|
if (!outputPointer) {
|
|
823
782
|
throw (0, _shared.fail)('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
|
|
824
783
|
}
|
|
784
|
+
if (premultiplied && mapped) {
|
|
785
|
+
wasm._premultiply(outputPointer + 4, 0, buffers[0].length >> 2);
|
|
786
|
+
}
|
|
825
787
|
return unpack(wasm, outputPointer);
|
|
826
788
|
} catch (error) {
|
|
827
789
|
if (!isAbort(error)) {
|
|
@@ -892,6 +854,21 @@ const reporter = o => {
|
|
|
892
854
|
}
|
|
893
855
|
};
|
|
894
856
|
};
|
|
857
|
+
|
|
858
|
+
// The conversion passes in slices of this many pixels, so a long one gives the signal and the event loop a turn like the rest.
|
|
859
|
+
const convertSlice = 65536;
|
|
860
|
+
const convertInSlices = async (convert, pointer, pixels, o) => {
|
|
861
|
+
let last = performance.now();
|
|
862
|
+
for (let start = 0; start < pixels; start += convertSlice) {
|
|
863
|
+
checkAborted(o.signal);
|
|
864
|
+
convert(pointer, start, Math.min(pixels, start + convertSlice));
|
|
865
|
+
// Yield only once a slice's worth of time has gone, so a short pass doesn't pay a turn of the event loop per chunk.
|
|
866
|
+
if (start + convertSlice < pixels && performance.now() - last >= sliceMs) {
|
|
867
|
+
await yieldNow();
|
|
868
|
+
last = performance.now();
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
};
|
|
895
872
|
const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
|
|
896
873
|
|
|
897
874
|
// The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
|
|
@@ -916,6 +893,9 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
|
916
893
|
let aborted = false;
|
|
917
894
|
try {
|
|
918
895
|
wasm.HEAPU8.set(image.data, imagePointer);
|
|
896
|
+
if (image.premultiplied) {
|
|
897
|
+
await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
|
|
898
|
+
}
|
|
919
899
|
job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
|
|
920
900
|
report(0);
|
|
921
901
|
while (true) {
|
|
@@ -966,6 +946,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
|
|
|
966
946
|
sourcePointer = allocate(wasm, bytes.length);
|
|
967
947
|
wasm.HEAPU8.set(image.data, imagePointer);
|
|
968
948
|
wasm.HEAPU8.set(bytes, sourcePointer);
|
|
949
|
+
if (image.premultiplied) {
|
|
950
|
+
await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
|
|
951
|
+
}
|
|
969
952
|
const palette = source.palette ? sourcePointer : 0,
|
|
970
953
|
clustering = source.clustering ? sourcePointer : 0;
|
|
971
954
|
job = wasm._mapping_job_start(imagePointer, image.data.length, codes[image.format], palette, source.palette ? bytes.length : 0, clustering, source.clustering ? bytes.length : 0, source.k || 0, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, indices ? 1 : 0, cutoff);
|
|
@@ -987,6 +970,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
|
|
|
987
970
|
}
|
|
988
971
|
const pointer = wasm._mapping_job_result(job);
|
|
989
972
|
try {
|
|
973
|
+
if (image.premultiplied && !indices) {
|
|
974
|
+
await convertInSlices(wasm._premultiply, pointer + 4, image.data.length >> 2, o);
|
|
975
|
+
}
|
|
990
976
|
return unpack(wasm, pointer);
|
|
991
977
|
} finally {
|
|
992
978
|
wasm._free(pointer);
|
|
@@ -1028,6 +1014,7 @@ const noOptions = (name, extra) => {
|
|
|
1028
1014
|
// happens before the call returns.
|
|
1029
1015
|
|
|
1030
1016
|
const buildClustering = async (image, options) => {
|
|
1017
|
+
image = (0, _shared.imageCopy)(image);
|
|
1031
1018
|
const warn = warningFor(image);
|
|
1032
1019
|
image = load(image);
|
|
1033
1020
|
const o = parseOptions(options, clusterOptions, image);
|
|
@@ -1039,12 +1026,13 @@ const buildClustering = async (image, options) => {
|
|
|
1039
1026
|
report(1);
|
|
1040
1027
|
return (0, _shared.markClustering)(clustering);
|
|
1041
1028
|
}
|
|
1042
|
-
return (0, _shared.markClustering)(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision));
|
|
1029
|
+
return (0, _shared.markClustering)(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision, image.premultiplied));
|
|
1043
1030
|
};
|
|
1044
1031
|
/** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
|
|
1045
1032
|
exports.buildClustering = buildClustering;
|
|
1046
1033
|
const getClustering = exports.getClustering = buildClustering;
|
|
1047
1034
|
const buildPalette = async (image, k, options) => {
|
|
1035
|
+
image = (0, _shared.imageCopy)(image);
|
|
1048
1036
|
const warn = warningFor(image);
|
|
1049
1037
|
image = load(image);
|
|
1050
1038
|
k = check(k);
|
|
@@ -1059,7 +1047,7 @@ const buildPalette = async (image, k, options) => {
|
|
|
1059
1047
|
report(1);
|
|
1060
1048
|
return (0, _shared.markPalette)(palette, (0, _shared.colorSpaceName)(o.colorSpace));
|
|
1061
1049
|
}
|
|
1062
|
-
return (0, _shared.markPalette)(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), (0, _shared.colorSpaceName)(o.colorSpace));
|
|
1050
|
+
return (0, _shared.markPalette)(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision, image.premultiplied), (0, _shared.colorSpaceName)(o.colorSpace));
|
|
1063
1051
|
};
|
|
1064
1052
|
/** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
|
|
1065
1053
|
exports.buildPalette = buildPalette;
|
|
@@ -1127,7 +1115,9 @@ const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getS
|
|
|
1127
1115
|
// The same for an image: clusters it, then cuts, like getPalette.
|
|
1128
1116
|
exports.getSwatchesFromClustering = getSwatchesFromClustering;
|
|
1129
1117
|
const buildSwatches = async (image, k, options) => {
|
|
1118
|
+
image = (0, _shared.imageCopy)(image);
|
|
1130
1119
|
// Arguments are checked in the order they are given (image, then k, then options), as in every other function.
|
|
1120
|
+
// `load` only validates here (buildClustering loads again); both see the copy, so the caller's fields are read once.
|
|
1131
1121
|
load(image);
|
|
1132
1122
|
k = check(k);
|
|
1133
1123
|
return getSwatchesFromClustering(await buildClustering(image, options), k);
|
|
@@ -1185,6 +1175,7 @@ const readInfo = async (name, clustering, extra) => {
|
|
|
1185
1175
|
const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
|
|
1186
1176
|
exports.getClusteringInfo = getClusteringInfo;
|
|
1187
1177
|
const quantize = async (image, k, options) => {
|
|
1178
|
+
image = (0, _shared.imageCopy)(image);
|
|
1188
1179
|
const warn = warningFor(image);
|
|
1189
1180
|
const wrap = getWrapper(image);
|
|
1190
1181
|
image = load(image);
|
|
@@ -1203,10 +1194,11 @@ const quantize = async (image, k, options) => {
|
|
|
1203
1194
|
report(1);
|
|
1204
1195
|
return mapped;
|
|
1205
1196
|
}
|
|
1206
|
-
return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision));
|
|
1197
|
+
return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision, image.premultiplied, true));
|
|
1207
1198
|
};
|
|
1208
1199
|
exports.quantize = quantize;
|
|
1209
1200
|
const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
1201
|
+
image = (0, _shared.imageCopy)(image);
|
|
1210
1202
|
const warn = warningFor(image);
|
|
1211
1203
|
const wrap = getWrapper(image);
|
|
1212
1204
|
image = load(image);
|
|
@@ -1227,11 +1219,12 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
|
1227
1219
|
report(1);
|
|
1228
1220
|
return mapped;
|
|
1229
1221
|
}
|
|
1230
|
-
const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
|
|
1222
|
+
const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
|
|
1231
1223
|
return result;
|
|
1232
1224
|
};
|
|
1233
1225
|
exports.quantizeFromClustering = quantizeFromClustering;
|
|
1234
1226
|
const quantizeWithPalette = async (image, palette, options) => {
|
|
1227
|
+
image = (0, _shared.imageCopy)(image);
|
|
1235
1228
|
const warn = warningFor(image);
|
|
1236
1229
|
const wrap = getWrapper(image);
|
|
1237
1230
|
image = load(image);
|
|
@@ -1251,11 +1244,12 @@ const quantizeWithPalette = async (image, palette, options) => {
|
|
|
1251
1244
|
report(1);
|
|
1252
1245
|
return mapped;
|
|
1253
1246
|
}
|
|
1254
|
-
const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
|
|
1247
|
+
const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
|
|
1255
1248
|
return result;
|
|
1256
1249
|
};
|
|
1257
1250
|
exports.quantizeWithPalette = quantizeWithPalette;
|
|
1258
1251
|
const quantizeToIndices = async (image, k, options) => {
|
|
1252
|
+
image = (0, _shared.imageCopy)(image);
|
|
1259
1253
|
const warn = warningFor(image);
|
|
1260
1254
|
const original = image;
|
|
1261
1255
|
image = load(image);
|
|
@@ -1274,10 +1268,11 @@ const quantizeToIndices = async (image, k, options) => {
|
|
|
1274
1268
|
report(1);
|
|
1275
1269
|
return indexed;
|
|
1276
1270
|
}
|
|
1277
|
-
return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision), original, (0, _shared.colorSpaceName)(o.colorSpace));
|
|
1271
|
+
return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision, image.premultiplied), original, (0, _shared.colorSpaceName)(o.colorSpace));
|
|
1278
1272
|
};
|
|
1279
1273
|
exports.quantizeToIndices = quantizeToIndices;
|
|
1280
1274
|
const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
|
|
1275
|
+
image = (0, _shared.imageCopy)(image);
|
|
1281
1276
|
const warn = warningFor(image);
|
|
1282
1277
|
const original = image;
|
|
1283
1278
|
image = load(image);
|
|
@@ -1301,11 +1296,12 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
|
|
|
1301
1296
|
report(1);
|
|
1302
1297
|
return indexed;
|
|
1303
1298
|
}
|
|
1304
|
-
const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff)), original, (0, _shared.colorSpaceName)(header.colorSpace));
|
|
1299
|
+
const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff), undefined, image.premultiplied), original, (0, _shared.colorSpaceName)(header.colorSpace));
|
|
1305
1300
|
return result;
|
|
1306
1301
|
};
|
|
1307
1302
|
exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
|
|
1308
1303
|
const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
1304
|
+
image = (0, _shared.imageCopy)(image);
|
|
1309
1305
|
const warn = warningFor(image);
|
|
1310
1306
|
const original = image;
|
|
1311
1307
|
image = load(image);
|
|
@@ -1326,7 +1322,7 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1326
1322
|
report(1);
|
|
1327
1323
|
return indexed;
|
|
1328
1324
|
}
|
|
1329
|
-
const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
|
|
1325
|
+
const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), undefined, image.premultiplied), original, paletteSpace);
|
|
1330
1326
|
return result;
|
|
1331
1327
|
};
|
|
1332
1328
|
|
package/dist/index.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* How pixel bytes are laid out:
|
|
3
3
|
* - `'rgb'`: 3 bytes per pixel, red, green, blue.
|
|
4
|
-
* - `'rgba'`, `'bgra'`: 4 bytes, with
|
|
5
|
-
* Electron's `
|
|
4
|
+
* - `'rgba'`, `'bgra'`: 4 bytes, with alpha last, straight unless the image object says `premultiplied: true` (canvas
|
|
5
|
+
* surfaces, Electron's `toBitmap()`). BGRA is the order of Windows bitmaps and Electron's `nativeImage`.
|
|
6
6
|
* - `'rgbx'`, `'bgrx'`: 4 bytes whose last is padding, not alpha (Windows `BI_RGB` bitmaps, WebCodecs `'BGRX'`, ffmpeg
|
|
7
7
|
* `bgr0`): every pixel is opaque, and mapped output writes 255 there.
|
|
8
8
|
*
|
|
@@ -70,28 +70,61 @@ export const ditherSteps: readonly DitherSteps[];
|
|
|
70
70
|
export function isCodedError(value: unknown): value is CodedError;
|
|
71
71
|
|
|
72
72
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
73
|
+
* RGBA or BGRA bytes. `premultiplied: true` says the colours are multiplied by alpha (canvas, Electron, WebGL).
|
|
74
|
+
* Internal: name it through `RawImage<'rgba'>` or `RawImage<'bgra'>`.
|
|
75
|
+
*/
|
|
76
|
+
interface RawImageWithAlpha<F extends 'rgba' | 'bgra' = 'rgba' | 'bgra'> {
|
|
77
|
+
data: Uint8Array | Uint8ClampedArray;
|
|
78
|
+
format: F;
|
|
79
|
+
/** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
|
|
80
|
+
width?: number | undefined;
|
|
81
|
+
/** Height in pixels. Optional; copied to `quantize*` results. */
|
|
82
|
+
height?: number | undefined;
|
|
83
|
+
/**
|
|
84
|
+
* The colours are multiplied by alpha (what a canvas surface, Electron's `toBitmap()`, WebGL and Cairo hold). They are
|
|
85
|
+
* read as straight colours (divided by alpha), and `quantize*` gives the mapped colours back multiplied, copied as
|
|
86
|
+
* given: the result has the same `premultiplied` as the input. For a straight destination (`ImageData`, PNG encoders),
|
|
87
|
+
* use `quantizeToIndices` and write palette colours with the input's alpha; un-premultiplying the output loses colour. The guides' "Straight pixels from a premultiplied source" has the loop.
|
|
88
|
+
*/
|
|
89
|
+
premultiplied?: boolean | undefined;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Formats without alpha. `premultiplied: false` says nothing; `true` is rejected at run time (there is no alpha).
|
|
94
|
+
* Internal: name it through `RawImage<'rgb'>`, `RawImage<'rgbx'>` or `RawImage<'bgrx'>`.
|
|
75
95
|
*/
|
|
76
|
-
|
|
96
|
+
interface RawImageWithoutAlpha<F extends 'rgb' | 'rgbx' | 'bgrx' = 'rgb' | 'rgbx' | 'bgrx'> {
|
|
77
97
|
data: Uint8Array | Uint8ClampedArray;
|
|
78
|
-
format:
|
|
98
|
+
format: F;
|
|
79
99
|
/** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
|
|
80
100
|
width?: number | undefined;
|
|
81
101
|
/** Height in pixels. Optional; copied to `quantize*` results. */
|
|
82
102
|
height?: number | undefined;
|
|
103
|
+
/** Accepted as `false` on any format and does nothing here; `true` is an `invalid-argument` error, since there is no alpha. */
|
|
104
|
+
premultiplied?: boolean | undefined;
|
|
83
105
|
}
|
|
84
106
|
|
|
107
|
+
/**
|
|
108
|
+
* An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
|
|
109
|
+
* `ImageData`. `RawImage<'bgra'>` is one format. Functions that return an image give back an object with the input's own
|
|
110
|
+
* keys (`format`, and `width`, `height` and `premultiplied` when given) and a new `data`.
|
|
111
|
+
*/
|
|
112
|
+
export type RawImage<F extends ImageFormat = ImageFormat> =
|
|
113
|
+
F extends 'rgba' | 'bgra' ? RawImageWithAlpha<F> : F extends 'rgb' | 'rgbx' | 'bgrx' ? RawImageWithoutAlpha<F> : never;
|
|
114
|
+
|
|
85
115
|
/**
|
|
86
116
|
* The platform's `ImageData` class where the global exists (the DOM lib, or typings for a canvas polyfill), and `never`
|
|
87
117
|
* where it doesn't, so these declarations compile with or without the DOM lib, in browser and Node-only projects.
|
|
88
118
|
*/
|
|
89
119
|
export type PlatformImageData = typeof globalThis extends { ImageData: { prototype: infer T } } ? T : never;
|
|
90
120
|
|
|
91
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* What a function that returns an image gives back for the input it was given: the same kind of thing. For an image
|
|
123
|
+
* object, one with the input's own keys and a new `data: Uint8Array`.
|
|
124
|
+
*/
|
|
92
125
|
export type ImageResult<I extends ImageLike> =
|
|
93
126
|
I extends Uint8Array ? Uint8Array
|
|
94
|
-
: I extends RawImage ?
|
|
127
|
+
: I extends RawImage ? Omit<I, 'data'> & { data: Uint8Array }
|
|
95
128
|
: I extends PlatformImageData ? PlatformImageData
|
|
96
129
|
: never;
|
|
97
130
|
|
|
@@ -344,7 +377,8 @@ interface IndexedImageFields {
|
|
|
344
377
|
|
|
345
378
|
/**
|
|
346
379
|
* One palette index per pixel in `indices`: a `Uint8Array` up to 256 palette entries, a `Uint16Array` up to 65536, else a
|
|
347
|
-
* `Uint32Array`. `indexBits` says which (8, 16 or 32), and checking it narrows `indices` to that array type.
|
|
380
|
+
* `Uint32Array`. `indexBits` says which (8, 16 or 32), and checking it narrows `indices` to that array type. The palette
|
|
381
|
+
* is straight even for a premultiplied input: indexed output has no partial alpha, so there is nothing to premultiply.
|
|
348
382
|
*/
|
|
349
383
|
export type IndexedImage =
|
|
350
384
|
| (IndexedImageFields & { indexBits: 8; indices: Uint8Array })
|