agglomerative-clustering 3.0.0-beta.1 → 3.0.0-beta.3
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 +192 -49
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +649 -830
- package/dist/index.d.cts +16 -15
- package/dist/index.d.ts +16 -15
- package/dist/index.mjs +633 -828
- package/dist/shared.cjs +202 -132
- package/dist/shared.mjs +184 -130
- package/dist/worker-thread.mjs +115 -349
- package/dist/worker.d.ts +2 -2
- package/dist/worker.mjs +480 -646
- package/package.json +4 -1
package/dist/index.mjs
CHANGED
|
@@ -1,65 +1,70 @@
|
|
|
1
|
-
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
|
|
2
|
-
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
|
|
3
|
-
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (c = i[4] || 3, u = i[5] === e ? i[3] : i[5], i[4] = 3, i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
|
|
4
|
-
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { var o = function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); }; o("next", 0), o("throw", 1), o("return", 2); } }, _regeneratorDefine2(e, r, n, t); }
|
|
5
|
-
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
|
|
6
|
-
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
|
|
7
|
-
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
|
|
8
|
-
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
|
|
9
|
-
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
|
|
10
|
-
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
|
|
11
|
-
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
|
|
12
|
-
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
|
|
13
1
|
import createWasmModule from './clustering.js';
|
|
14
|
-
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, markPalette, markClustering, latestVersion, readHeader, checkPalette } from "./shared.mjs";
|
|
2
|
+
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette } from "./shared.mjs";
|
|
15
3
|
|
|
16
4
|
// The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
|
|
17
5
|
export { version, Palette, Clustering } from "./shared.mjs";
|
|
18
6
|
// The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
|
|
19
7
|
// `version`, it changes only when the stored format does, so a 3.x release that keeps the format keeps this number.
|
|
20
|
-
export
|
|
21
|
-
|
|
8
|
+
export const formatVersion = latestVersion;
|
|
9
|
+
|
|
10
|
+
// Checked by tag rather than `instanceof`, so values from another realm are recognised: an ImageData from an iframe's
|
|
11
|
+
// canvas, a WebAssembly.Module compiled by a bundler's runtime (Next.js Edge's `import wasm from '…wasm?module'`), a URL
|
|
12
|
+
// from a vm context. A tag can be faked, but only on purpose, and the value is then used as what it claims to be.
|
|
13
|
+
const tagOf = value => Object.prototype.toString.call(value);
|
|
14
|
+
// (`instanceof` is kept too, for implementations without the tag, such as node-canvas's ImageData.)
|
|
15
|
+
const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
|
|
16
|
+
const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
|
|
17
|
+
const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
|
|
18
|
+
const codes = {
|
|
22
19
|
'rgba': 0,
|
|
23
20
|
'rgb': 1
|
|
24
21
|
};
|
|
25
|
-
|
|
22
|
+
const alphaModes = {
|
|
26
23
|
'ignore': 0,
|
|
27
24
|
'weight': 1
|
|
28
25
|
};
|
|
29
|
-
|
|
26
|
+
let Module = null;
|
|
30
27
|
|
|
31
28
|
// Turns init's `wasm` option into the settings the Emscripten glue understands. The glue finds its .wasm file next to
|
|
32
29
|
// itself by default (`new URL('clustering.wasm', import.meta.url)`); this lets a caller say where it is, or hand over
|
|
33
30
|
// the bytes or an already compiled module, for CDNs, strict CSPs and runtimes (such as Cloudflare Workers) that
|
|
34
31
|
// cannot fetch or compile it that way. `onError` receives instantiation errors, which the glue would otherwise swallow.
|
|
35
|
-
|
|
32
|
+
const wasmSettings = (wasm, onError) => {
|
|
36
33
|
if (wasm === undefined) {
|
|
37
34
|
return {};
|
|
38
35
|
}
|
|
39
|
-
if (typeof wasm === 'string' || wasm
|
|
40
|
-
|
|
36
|
+
if (typeof wasm === 'string' || isURL(wasm)) {
|
|
37
|
+
const location = String(wasm);
|
|
41
38
|
return {
|
|
42
|
-
locateFile:
|
|
43
|
-
return path.endsWith('.wasm') ? location : directory + path;
|
|
44
|
-
}
|
|
39
|
+
locateFile: (path, directory) => path.endsWith('.wasm') ? location : directory + path
|
|
45
40
|
};
|
|
46
41
|
}
|
|
47
|
-
// Bytes and compiled modules go through `instantiateWasm`: this build of the glue reads no `wasmBinary` setting.
|
|
42
|
+
// Bytes and compiled modules go through `instantiateWasm`: this build of the glue reads no `wasmBinary` setting. The glue
|
|
43
|
+
// sets itself up on the instance inside `receive`, which throws for a module that isn't this one (it has other exports);
|
|
44
|
+
// that is reported as a failed load rather than left to escape, which would leave the load waiting forever.
|
|
45
|
+
const accept = receive => instance => {
|
|
46
|
+
try {
|
|
47
|
+
receive(instance);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
onError(Object.assign(new Error("it is not agglomerative-clustering's module (it lacks the memory and functions this script uses)"), {
|
|
50
|
+
cause: error
|
|
51
|
+
}));
|
|
52
|
+
}
|
|
53
|
+
};
|
|
48
54
|
if (isArrayBufferLike(wasm) || ArrayBuffer.isView(wasm)) {
|
|
49
|
-
|
|
55
|
+
const source = isArrayBufferLike(wasm) ? wasm : new Uint8Array(wasm.buffer, wasm.byteOffset, wasm.byteLength);
|
|
50
56
|
return {
|
|
51
|
-
instantiateWasm:
|
|
52
|
-
WebAssembly.instantiate(source, imports).then(
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
}, onError);
|
|
57
|
+
instantiateWasm: (imports, receive) => {
|
|
58
|
+
WebAssembly.instantiate(source, imports).then(({
|
|
59
|
+
instance
|
|
60
|
+
}) => accept(receive)(instance), onError);
|
|
56
61
|
}
|
|
57
62
|
};
|
|
58
63
|
}
|
|
59
|
-
if (
|
|
64
|
+
if (isWasmModule(wasm)) {
|
|
60
65
|
return {
|
|
61
|
-
instantiateWasm:
|
|
62
|
-
WebAssembly.instantiate(wasm, imports).then(receive, onError);
|
|
66
|
+
instantiateWasm: (imports, receive) => {
|
|
67
|
+
WebAssembly.instantiate(wasm, imports).then(accept(receive), onError);
|
|
63
68
|
}
|
|
64
69
|
};
|
|
65
70
|
}
|
|
@@ -67,10 +72,41 @@ var wasmSettings = function wasmSettings(wasm, onError) {
|
|
|
67
72
|
};
|
|
68
73
|
|
|
69
74
|
// A module that cannot be loaded is the commonest first-run failure: a 404, a Content-Security-Policy that blocks it, a
|
|
70
|
-
//
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
75
|
+
// bundler that moved the file, an engine without WebAssembly SIMD. The engine's own error (a CompileError, a failed fetch)
|
|
76
|
+
// says little about which, so the message leads with what happened and then gives the likely fix for where it ran.
|
|
77
|
+
// The smallest module that uses a SIMD instruction (from wasm-feature-detect), to tell an old engine from a missing file.
|
|
78
|
+
const simdProbe = [0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11];
|
|
79
|
+
const hasSimd = () => {
|
|
80
|
+
try {
|
|
81
|
+
return typeof WebAssembly === 'object' && WebAssembly.validate(new Uint8Array(simdProbe));
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
// Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
|
|
87
|
+
// process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
|
|
88
|
+
const isNodeLike = typeof process !== 'undefined' && !!(process.versions && process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
|
|
89
|
+
const wasmLoadFailed = (cause, given) => {
|
|
90
|
+
const text = String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0];
|
|
91
|
+
// Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
|
|
92
|
+
// and wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
|
|
93
|
+
let reason = text.replace(/\s*\(?Build with -sASSERTIONS for more info\.?\)?/, '').trim().replace(/\.+$/, '');
|
|
94
|
+
const aborted = /^Aborted\((.*)\)$/.exec(reason);
|
|
95
|
+
if (aborted) {
|
|
96
|
+
reason = aborted[1].replace(/\.+$/, '');
|
|
97
|
+
}
|
|
98
|
+
let advice;
|
|
99
|
+
if (!hasSimd()) {
|
|
100
|
+
advice = "This engine has no WebAssembly SIMD, which the module needs (Chrome and Edge 91, Firefox 89, Safari 16.4, Node 16.4 or newer).";
|
|
101
|
+
} else if (given) {
|
|
102
|
+
advice = "Check what init({ wasm }) was given: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).";
|
|
103
|
+
} else if (isNodeLike) {
|
|
104
|
+
advice = "If the package was bundled into a server build (Next.js and others), the bundler may have moved or renamed clustering.wasm: leave the package out of the bundle (in Next.js, serverExternalPackages: ['agglomerative-clustering']) or give the module with init({ wasm }).";
|
|
105
|
+
} else {
|
|
106
|
+
advice = "Check that clustering.wasm is served next to the script (not a 404, and with the application/wasm type) and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).";
|
|
107
|
+
}
|
|
108
|
+
return Object.assign(fail('wasm-load-failed', `Could not load the WebAssembly module: ${reason || 'unknown error'}. ${advice}`), {
|
|
109
|
+
cause
|
|
74
110
|
});
|
|
75
111
|
};
|
|
76
112
|
|
|
@@ -78,149 +114,148 @@ var wasmLoadFailed = function wasmLoadFailed(cause) {
|
|
|
78
114
|
// not a public interface. One left over from another version (a stale cache, a CDN serving an old file, an `init({ wasm })`
|
|
79
115
|
// pointing at the wrong one) would misbehave in ways nothing explains, so the module says which version it is and a
|
|
80
116
|
// mismatch is reported when it loads.
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
117
|
+
const checkWasmVersion = instance => {
|
|
118
|
+
// A module from before 3.0 has no version export (the glue's wrapper then throws or returns nothing), and one that isn't
|
|
119
|
+
// this library's at all may have none either: both are reported as a version mismatch, never as a stray TypeError.
|
|
120
|
+
let found = '';
|
|
121
|
+
try {
|
|
122
|
+
const pointer = instance._library_version();
|
|
123
|
+
const heap = instance.HEAPU8;
|
|
124
|
+
if (typeof pointer === 'number' && pointer > 0 && heap) {
|
|
125
|
+
let end = pointer;
|
|
126
|
+
while (heap[end] !== 0 && end - pointer < 64) {
|
|
127
|
+
end++;
|
|
128
|
+
}
|
|
129
|
+
found = String.fromCharCode(...heap.subarray(pointer, end));
|
|
89
130
|
}
|
|
90
|
-
|
|
91
|
-
}
|
|
92
|
-
var expected = "agglomerative-clustering@".concat(version);
|
|
131
|
+
} catch (error) {/* no version export */}
|
|
132
|
+
const expected = `agglomerative-clustering@${version}`;
|
|
93
133
|
if (found !== expected) {
|
|
94
|
-
|
|
134
|
+
const what = found ? found : 'from another version (one from before 3.0, which does not say which, or not this library\'s module at all)';
|
|
135
|
+
throw fail('wasm-load-failed', `The WebAssembly module is ${what}, but this script is ${expected}: a stale or mixed-up clustering.wasm (a cache or CDN serving another version, or init({ wasm }) pointing at one). Serve the .wasm that came with this version of the package.`);
|
|
95
136
|
}
|
|
96
137
|
};
|
|
97
138
|
|
|
139
|
+
// Instantiates the module from init's `wasm` option (undefined: the glue finds the .wasm next to itself).
|
|
140
|
+
const instantiate = wasm => {
|
|
141
|
+
let reject;
|
|
142
|
+
const failed = new Promise((_, r) => {
|
|
143
|
+
reject = r;
|
|
144
|
+
});
|
|
145
|
+
failed.catch(() => {});
|
|
146
|
+
// The glue's own console output (failed fetches, "Aborted()") is turned off: every failure reaches the caller as an error.
|
|
147
|
+
const quiet = {
|
|
148
|
+
print: () => {},
|
|
149
|
+
printErr: () => {}
|
|
150
|
+
};
|
|
151
|
+
return Promise.race([createWasmModule({
|
|
152
|
+
...quiet,
|
|
153
|
+
...wasmSettings(wasm, reject)
|
|
154
|
+
}), failed]);
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
// The bytes of this package's clustering.wasm as Node resolves it from the working directory, for when the copy next to
|
|
158
|
+
// the script is missing (see acquire). The specifiers are built at run time so bundlers leave them alone (see worker.js).
|
|
159
|
+
const packagedWasm = async () => {
|
|
160
|
+
const {
|
|
161
|
+
createRequire
|
|
162
|
+
} = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'module'].join(':'));
|
|
163
|
+
const {
|
|
164
|
+
readFile
|
|
165
|
+
} = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
|
|
166
|
+
const file = createRequire(`${process.cwd()}/`).resolve('agglomerative-clustering/clustering.wasm');
|
|
167
|
+
return readFile(file);
|
|
168
|
+
};
|
|
169
|
+
|
|
98
170
|
// The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
|
|
99
|
-
|
|
171
|
+
let loading = null;
|
|
100
172
|
|
|
101
173
|
// Calls get the instance they run on from `acquire` and keep using it, so replacing the current instance (see `discard`)
|
|
102
174
|
// never changes the module under a call already in flight.
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
});
|
|
139
|
-
failed["catch"](function () {});
|
|
140
|
-
settings = wasmSettings(options.wasm, reject);
|
|
141
|
-
if (!Module) {
|
|
142
|
-
_context2.n = 5;
|
|
143
|
-
break;
|
|
144
|
-
}
|
|
145
|
-
return _context2.a(2, Module);
|
|
146
|
-
case 5:
|
|
147
|
-
if (!loading) {
|
|
148
|
-
loading = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
|
|
149
|
-
var instance;
|
|
150
|
-
return _regenerator().w(function (_context) {
|
|
151
|
-
while (1) switch (_context.n) {
|
|
152
|
-
case 0:
|
|
153
|
-
_context.n = 1;
|
|
154
|
-
return Promise.race([createWasmModule(settings), failed])["catch"](function (error) {
|
|
155
|
-
throw wasmLoadFailed(error);
|
|
156
|
-
});
|
|
157
|
-
case 1:
|
|
158
|
-
instance = _context.v;
|
|
159
|
-
checkWasmVersion(instance);
|
|
160
|
-
Module = instance;
|
|
161
|
-
return _context.a(2, instance);
|
|
162
|
-
}
|
|
163
|
-
}, _callee);
|
|
164
|
-
}))()["catch"](function (error) {
|
|
165
|
-
loading = null;
|
|
166
|
-
throw error;
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
return _context2.a(2, loading);
|
|
175
|
+
const acquire = async options => {
|
|
176
|
+
if (options === undefined) {
|
|
177
|
+
options = {};
|
|
178
|
+
}
|
|
179
|
+
if (!isOptionsObject(options)) {
|
|
180
|
+
throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
|
|
181
|
+
}
|
|
182
|
+
options = snapshot(options);
|
|
183
|
+
for (const key of Object.keys(options)) {
|
|
184
|
+
if (key !== 'wasm') {
|
|
185
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected wasm.`, `options.${key}`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// Checked on every call, so a bad value is reported even when the module is already loaded.
|
|
189
|
+
wasmSettings(options.wasm, () => {});
|
|
190
|
+
if (Module) {
|
|
191
|
+
return Module;
|
|
192
|
+
}
|
|
193
|
+
if (!loading) {
|
|
194
|
+
const wasm = options.wasm;
|
|
195
|
+
loading = (async () => {
|
|
196
|
+
let instance;
|
|
197
|
+
try {
|
|
198
|
+
instance = await instantiate(wasm);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
// In Node, a bundler that rewrote the glue's `new URL('clustering.wasm', import.meta.url)` (a Next.js server
|
|
201
|
+
// build, say) leaves it pointing at a file that isn't there. The package's own copy is then looked for the
|
|
202
|
+
// way Node resolves packages, from the working directory; if that fails too, the first error is reported.
|
|
203
|
+
const fallback = wasm === undefined && isNodeLike ? await packagedWasm().catch(() => null) : null;
|
|
204
|
+
if (!fallback) {
|
|
205
|
+
throw wasmLoadFailed(error, wasm !== undefined);
|
|
206
|
+
}
|
|
207
|
+
instance = await instantiate(fallback).catch(() => {
|
|
208
|
+
throw wasmLoadFailed(error, false);
|
|
209
|
+
});
|
|
170
210
|
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
211
|
+
checkWasmVersion(instance);
|
|
212
|
+
Module = instance;
|
|
213
|
+
return instance;
|
|
214
|
+
})().catch(error => {
|
|
215
|
+
loading = null;
|
|
216
|
+
throw error;
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
return loading;
|
|
220
|
+
};
|
|
177
221
|
|
|
178
222
|
// Loads the WebAssembly module. Every other function does this on first use, so calling it is optional, except to
|
|
179
223
|
// say where the .wasm file is (`wasm`), which must come before anything else. The first load that succeeds wins:
|
|
180
224
|
// later calls, with or without options, get the same module.
|
|
181
|
-
export
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
while (1) switch (_context3.n) {
|
|
185
|
-
case 0:
|
|
186
|
-
_context3.n = 1;
|
|
187
|
-
return acquire(options);
|
|
188
|
-
case 1:
|
|
189
|
-
return _context3.a(2);
|
|
190
|
-
}
|
|
191
|
-
}, _callee3);
|
|
192
|
-
}));
|
|
193
|
-
return function init(_x2) {
|
|
194
|
-
return _ref4.apply(this, arguments);
|
|
195
|
-
};
|
|
196
|
-
}();
|
|
225
|
+
export const init = async options => {
|
|
226
|
+
await acquire(options);
|
|
227
|
+
};
|
|
197
228
|
|
|
198
229
|
// A WebAssembly abort, which is what running out of memory looks like, leaves the instance's heap full of whatever the
|
|
199
230
|
// failed call had allocated and never freed (the abort skips destructors), so every later large call on it would fail
|
|
200
231
|
// too. The instance is therefore discarded: the next call loads a fresh one, and calls already running keep theirs.
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
};
|
|
204
|
-
var discard = function discard(instance) {
|
|
232
|
+
const isAbort = error => error instanceof Error && error.name === 'RuntimeError' && /^Aborted\(/.test(error.message);
|
|
233
|
+
const discard = instance => {
|
|
205
234
|
if (Module === instance) {
|
|
206
235
|
Module = null;
|
|
207
236
|
loading = null;
|
|
208
237
|
}
|
|
209
238
|
};
|
|
210
|
-
|
|
211
|
-
|
|
239
|
+
// WebAssembly memory only grows: an instance that once held a huge image keeps all that memory for the life of the process.
|
|
240
|
+
// So when a call leaves the heap larger than this, the instance is retired like an aborted one: calls already running keep
|
|
241
|
+
// it, the next call loads a fresh one (a few milliseconds, next to the seconds such an image took), and the old memory is
|
|
242
|
+
// freed when nothing uses it any more.
|
|
243
|
+
const retireAbove = 256 * 1024 * 1024;
|
|
244
|
+
const retireIfLarge = instance => {
|
|
245
|
+
if (instance.HEAPU8 && instance.HEAPU8.length > retireAbove) {
|
|
246
|
+
discard(instance);
|
|
247
|
+
}
|
|
212
248
|
};
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
249
|
+
const outOfMemory = () => fail('out-of-memory', "The WebAssembly module ran out of memory (it can use up to 2 GB for one image). Try `precision: 6`, which bounds the memory an image with very many colours needs, or a smaller image.");
|
|
250
|
+
const unpack = (wasm, pointer) => {
|
|
251
|
+
const lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
|
|
252
|
+
const length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
|
|
253
|
+
const outputBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer + 4, pointer + 4 + length));
|
|
217
254
|
return outputBuffer;
|
|
218
255
|
};
|
|
219
256
|
|
|
220
257
|
// A Uint8Array over exactly the same bytes, so views into a larger buffer (subarrays) stay views of their own range.
|
|
221
|
-
|
|
222
|
-
return isUint8Array(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
223
|
-
};
|
|
258
|
+
const bytes = data => isUint8Array(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
224
259
|
|
|
225
260
|
// ----- Encoded image files -------------------------------------------------------------------------------------------
|
|
226
261
|
// A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
|
|
@@ -232,8 +267,8 @@ var bytes = function bytes(data) {
|
|
|
232
267
|
// This is also where decoding would go. The library doesn't decode files today (that needs a decoder per format, and
|
|
233
268
|
// sharp, pngjs, createImageBitmap and the like already do it); when it does, a file recognised here is decoded into
|
|
234
269
|
// { data, format, width, height } instead of rejected, and `load` becomes asynchronous. See docs/ROADMAP.md.
|
|
235
|
-
|
|
236
|
-
for (
|
|
270
|
+
const ascii = (bytes, at, text) => {
|
|
271
|
+
for (let i = 0; i < text.length; i++) {
|
|
237
272
|
if (bytes[at + i] !== text.charCodeAt(i)) {
|
|
238
273
|
return false;
|
|
239
274
|
}
|
|
@@ -243,8 +278,8 @@ var ascii = function ascii(bytes, at, text) {
|
|
|
243
278
|
|
|
244
279
|
// The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
|
|
245
280
|
// beyond the first few bytes, that raw pixels all but never match.
|
|
246
|
-
|
|
247
|
-
|
|
281
|
+
const sniffImageFormat = bytes => {
|
|
282
|
+
const length = bytes.length;
|
|
248
283
|
if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
|
|
249
284
|
return 'PNG';
|
|
250
285
|
}
|
|
@@ -264,13 +299,11 @@ var sniffImageFormat = function sniffImageFormat(bytes) {
|
|
|
264
299
|
}
|
|
265
300
|
// TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
|
|
266
301
|
if (length >= 12) {
|
|
267
|
-
|
|
268
|
-
|
|
302
|
+
const little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
|
|
303
|
+
const big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
|
|
269
304
|
if (little || big) {
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
};
|
|
273
|
-
var offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
|
|
305
|
+
const u16 = at => little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
|
|
306
|
+
const offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
|
|
274
307
|
if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
|
|
275
308
|
return 'TIFF';
|
|
276
309
|
}
|
|
@@ -281,64 +314,73 @@ var sniffImageFormat = function sniffImageFormat(bytes) {
|
|
|
281
314
|
if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
|
|
282
315
|
return 'AVIF';
|
|
283
316
|
}
|
|
284
|
-
if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(
|
|
285
|
-
return ascii(bytes, 8, brand);
|
|
286
|
-
})) {
|
|
317
|
+
if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
|
|
287
318
|
return 'HEIC';
|
|
288
319
|
}
|
|
289
320
|
}
|
|
290
321
|
return null;
|
|
291
322
|
};
|
|
292
323
|
|
|
293
|
-
//
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
if (
|
|
297
|
-
return
|
|
298
|
-
}
|
|
299
|
-
if (typeof image === 'string') {
|
|
300
|
-
return " Got a string (a file name, URL or data URL?): load and decode it to pixels first.";
|
|
324
|
+
// A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
|
|
325
|
+
const isDetached = view => {
|
|
326
|
+
const buffer = view.buffer;
|
|
327
|
+
if (typeof buffer.detached === 'boolean') {
|
|
328
|
+
return buffer.detached;
|
|
301
329
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
return
|
|
330
|
+
try {
|
|
331
|
+
new Uint8Array(buffer, 0, 0);
|
|
332
|
+
return false;
|
|
333
|
+
} catch (error) {
|
|
334
|
+
return true;
|
|
307
335
|
}
|
|
308
|
-
|
|
309
|
-
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
// The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
|
|
339
|
+
// or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
|
|
340
|
+
// call returns; until then (the first call) a copy is kept for when it has loaded.
|
|
341
|
+
const held = data => Module ? data : data.slice();
|
|
342
|
+
|
|
343
|
+
// width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
|
|
344
|
+
// pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
|
|
345
|
+
const checkSize = (pixels, size, name, argument) => {
|
|
346
|
+
if (size === undefined) {
|
|
347
|
+
return;
|
|
310
348
|
}
|
|
311
|
-
if (
|
|
312
|
-
|
|
349
|
+
if (!Number.isInteger(size) || size < 0) {
|
|
350
|
+
throw fail('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
|
|
313
351
|
}
|
|
314
|
-
if (
|
|
315
|
-
|
|
352
|
+
if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
|
|
353
|
+
throw fail('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
|
|
316
354
|
}
|
|
317
|
-
|
|
318
|
-
|
|
355
|
+
};
|
|
356
|
+
const load = image => {
|
|
357
|
+
if (isClustering(image) || isPalette(image)) {
|
|
358
|
+
const what = isClustering(image) ? 'a clustering (from getClustering)' : 'a palette';
|
|
359
|
+
const fix = isClustering(image) ? 'To cut a palette from it, use getPaletteFromClustering (or quantizeFromClustering to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
|
|
360
|
+
throw fail('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
|
|
319
361
|
}
|
|
320
|
-
if (image
|
|
321
|
-
|
|
362
|
+
if (ArrayBuffer.isView(image) && isDetached(image)) {
|
|
363
|
+
throw fail('invalid-argument', "Invalid image: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
|
|
322
364
|
}
|
|
323
|
-
return '';
|
|
324
|
-
};
|
|
325
|
-
var load = function load(image) {
|
|
326
365
|
if (isUint8Array(image)) {
|
|
327
|
-
|
|
366
|
+
const encoded = sniffImageFormat(image);
|
|
328
367
|
if (encoded) {
|
|
329
|
-
throw fail('invalid-argument',
|
|
368
|
+
throw fail('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode it first (in a browser, draw it to a canvas or use createImageBitmap, then pass getImageData(); in Node use sharp, pngjs or similar) and pass the raw pixels. If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
|
|
330
369
|
}
|
|
331
370
|
if (image.length % 4 !== 0) {
|
|
332
371
|
throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
|
|
333
372
|
}
|
|
334
373
|
return {
|
|
335
|
-
data: image,
|
|
374
|
+
data: held(image),
|
|
336
375
|
format: 'rgba'
|
|
337
376
|
};
|
|
338
377
|
}
|
|
339
|
-
if (
|
|
378
|
+
if (isImageData(image)) {
|
|
379
|
+
if (isDetached(image.data)) {
|
|
380
|
+
throw fail('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
|
|
381
|
+
}
|
|
340
382
|
return {
|
|
341
|
-
data: bytes(image.data),
|
|
383
|
+
data: held(bytes(image.data)),
|
|
342
384
|
format: 'rgba',
|
|
343
385
|
width: image.width
|
|
344
386
|
};
|
|
@@ -346,93 +388,89 @@ var load = function load(image) {
|
|
|
346
388
|
if (ArrayBuffer.isView(image)) {
|
|
347
389
|
throw fail('invalid-argument', "Invalid image: a bare typed array must be a Uint8Array of RGBA bytes. For a Uint8ClampedArray such as imageData.data, pass the ImageData itself or { data, format: 'rgba' }.", 'image');
|
|
348
390
|
}
|
|
349
|
-
if (
|
|
350
|
-
throw fail('invalid-argument',
|
|
391
|
+
if (typeof image !== 'object' || !image || !image.data || !image.format) {
|
|
392
|
+
throw fail('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${imageHint(image)}`, 'image');
|
|
351
393
|
}
|
|
352
394
|
if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
|
|
353
395
|
throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
|
|
354
396
|
}
|
|
397
|
+
if (isDetached(image.data)) {
|
|
398
|
+
throw fail('invalid-argument', "Invalid image data: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
|
|
399
|
+
}
|
|
355
400
|
if (!Object.keys(codes).includes(image.format)) {
|
|
356
401
|
throw fail('invalid-argument', "Invalid format: must be 'rgb' or 'rgba'.", 'image');
|
|
357
402
|
}
|
|
358
|
-
|
|
403
|
+
const channels = image.format === 'rgb' ? 3 : 4;
|
|
359
404
|
if (image.data.length % channels !== 0) {
|
|
360
|
-
throw fail('invalid-argument',
|
|
405
|
+
throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${channels} for '${image.format}'.`, 'image');
|
|
361
406
|
}
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
var value = image[key];
|
|
368
|
-
if (value !== undefined && (!Number.isInteger(value) || value < 0)) {
|
|
369
|
-
throw fail('invalid-argument', "Invalid image ".concat(key, ": must be a whole number of pixels."), 'image');
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
if (image.width !== undefined && image.height !== undefined && image.width * image.height !== image.data.length / channels) {
|
|
373
|
-
throw fail('invalid-argument', "Invalid image: width x height (".concat(image.width, " x ").concat(image.height, ") does not match its ").concat(image.data.length / channels, " pixels."), 'image');
|
|
407
|
+
const pixels = image.data.length / channels;
|
|
408
|
+
checkSize(pixels, image.width, 'image width', 'image');
|
|
409
|
+
checkSize(pixels, image.height, 'image height', 'image');
|
|
410
|
+
if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
|
|
411
|
+
throw fail('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
|
|
374
412
|
}
|
|
375
413
|
return {
|
|
376
|
-
data: bytes(image.data),
|
|
414
|
+
data: held(bytes(image.data)),
|
|
377
415
|
format: image.format,
|
|
378
416
|
width: image.width
|
|
379
417
|
};
|
|
380
418
|
};
|
|
381
|
-
|
|
382
|
-
if (
|
|
419
|
+
const getWrapper = image => {
|
|
420
|
+
if (isImageData(image)) {
|
|
383
421
|
// The pixels stay in the colour space they came in ('display-p3' canvases), so the result must say so.
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
};
|
|
392
|
-
}
|
|
393
|
-
if (!isUint8Array(image) &&
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
422
|
+
const {
|
|
423
|
+
width,
|
|
424
|
+
height,
|
|
425
|
+
colorSpace
|
|
426
|
+
} = image;
|
|
427
|
+
return output => new ImageData(new Uint8ClampedArray(output.buffer), width, height, colorSpace ? {
|
|
428
|
+
colorSpace
|
|
429
|
+
} : undefined);
|
|
430
|
+
}
|
|
431
|
+
if (!isUint8Array(image) && typeof image === 'object' && image && image.data && image.format) {
|
|
432
|
+
const {
|
|
433
|
+
format,
|
|
434
|
+
width,
|
|
435
|
+
height
|
|
436
|
+
} = image;
|
|
437
|
+
return output => {
|
|
438
|
+
const result = {
|
|
399
439
|
data: output,
|
|
400
|
-
format
|
|
440
|
+
format
|
|
401
441
|
};
|
|
402
|
-
if (
|
|
403
|
-
result.width =
|
|
442
|
+
if (width !== undefined) {
|
|
443
|
+
result.width = width;
|
|
404
444
|
}
|
|
405
|
-
if (
|
|
406
|
-
result.height =
|
|
445
|
+
if (height !== undefined) {
|
|
446
|
+
result.height = height;
|
|
407
447
|
}
|
|
408
448
|
return result;
|
|
409
449
|
};
|
|
410
450
|
}
|
|
411
|
-
return
|
|
412
|
-
return output;
|
|
413
|
-
};
|
|
451
|
+
return output => output;
|
|
414
452
|
};
|
|
415
453
|
|
|
416
454
|
// Decodes _quantize_indices output: [entries, transparent index, index bytes] as 32-bit little-endian values, then
|
|
417
455
|
// the palette, then the indices. `image` is the caller's original input, for its width and height.
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
456
|
+
const unpackIndices = (output, image, colorSpace) => {
|
|
457
|
+
const view = new DataView(output.buffer, output.byteOffset, output.byteLength);
|
|
458
|
+
const entries = view.getUint32(0, true);
|
|
459
|
+
const transparent = view.getInt32(4, true);
|
|
460
|
+
const indexBytes = view.getUint32(8, true);
|
|
461
|
+
const palette = markPalette(output.slice(12, 12 + 3 * entries), colorSpace);
|
|
462
|
+
const start = 12 + 3 * entries;
|
|
463
|
+
const count = (output.length - start) / indexBytes;
|
|
464
|
+
const Indices = indexBytes === 1 ? Uint8Array : indexBytes === 2 ? Uint16Array : Uint32Array;
|
|
465
|
+
const indices = new Indices(count);
|
|
428
466
|
// Little-endian, like the WASM heap, which Emscripten's own typed-array views already assume of the host.
|
|
429
467
|
new Uint8Array(indices.buffer).set(output.subarray(start));
|
|
430
468
|
// `colors` is the palette without the transparent entry, ready to map with again (the entry is black and takes no part in matching)
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
palette
|
|
434
|
-
colors
|
|
435
|
-
indices
|
|
469
|
+
const colors = transparent < 0 ? palette : markPalette(palette.slice(0, 3 * transparent), colorSpace);
|
|
470
|
+
const result = {
|
|
471
|
+
palette,
|
|
472
|
+
colors,
|
|
473
|
+
indices,
|
|
436
474
|
indexBits: 8 * indexBytes,
|
|
437
475
|
transparentIndex: transparent < 0 ? null : transparent
|
|
438
476
|
};
|
|
@@ -449,9 +487,11 @@ var unpackIndices = function unpackIndices(output, image, colorSpace) {
|
|
|
449
487
|
|
|
450
488
|
// Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
|
|
451
489
|
// the WASM side holds (a larger one would overflow its int).
|
|
452
|
-
|
|
490
|
+
const check = k => {
|
|
453
491
|
if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
|
|
454
|
-
|
|
492
|
+
// A string is the usual slip (an input's `value`), so it gets its own fix.
|
|
493
|
+
const got = typeof k === 'string' ? ` Got the string ${JSON.stringify(k.length > 20 ? `${k.slice(0, 20)}…` : k)}: convert it first, e.g. Number(input.value).` : typeof k === 'number' ? ` Got ${k}.` : ` Got ${k === null ? 'null' : typeof k}.`;
|
|
494
|
+
throw fail('invalid-argument', `Invalid k: must be a whole number of colours, 1 or more.${got}`, 'k');
|
|
455
495
|
}
|
|
456
496
|
return Math.min(k, 0x7FFFFFFF);
|
|
457
497
|
};
|
|
@@ -467,7 +507,7 @@ var check = function check(k) {
|
|
|
467
507
|
// transparent: false (default), true (cutoff 128) or a cutoff from 1 to 255: pixels with alpha below it are left out of clustering (and the rest count whole);
|
|
468
508
|
// indexed output also gives them their own entry, which counts towards k
|
|
469
509
|
|
|
470
|
-
|
|
510
|
+
const parseOptions = (options, allowed, image) => {
|
|
471
511
|
if (options === undefined) {
|
|
472
512
|
options = {};
|
|
473
513
|
}
|
|
@@ -475,25 +515,24 @@ var parseOptions = function parseOptions(options, allowed, image) {
|
|
|
475
515
|
throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
|
|
476
516
|
}
|
|
477
517
|
options = snapshot(options);
|
|
478
|
-
for (
|
|
479
|
-
var key = _Object$keys2[_i3];
|
|
518
|
+
for (const key of Object.keys(options)) {
|
|
480
519
|
if (!allowed.includes(key)) {
|
|
481
|
-
throw fail('invalid-argument',
|
|
520
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.`, `options.${key}`);
|
|
482
521
|
}
|
|
483
522
|
}
|
|
484
|
-
|
|
523
|
+
const colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
|
|
485
524
|
if (!Object.keys(colorSpaces).includes(colorSpace)) {
|
|
486
525
|
throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
|
|
487
526
|
}
|
|
488
|
-
|
|
527
|
+
const alpha = options.alpha === undefined ? 'weight' : options.alpha;
|
|
489
528
|
if (!Object.keys(alphaModes).includes(alpha)) {
|
|
490
529
|
throw fail('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
|
|
491
530
|
}
|
|
492
|
-
|
|
531
|
+
const precision = options.precision === undefined ? 8 : options.precision;
|
|
493
532
|
if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
|
|
494
533
|
throw fail('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
|
|
495
534
|
}
|
|
496
|
-
|
|
535
|
+
const dither = options.dither === undefined || options.dither === false ? 0 : options.dither === true ? 1 : options.dither;
|
|
497
536
|
if (typeof dither !== 'number' || !Number.isFinite(dither) || dither < 0 || dither > 1) {
|
|
498
537
|
throw fail('invalid-argument', "Invalid dither: must be a boolean or a number from 0 to 1.", 'options.dither');
|
|
499
538
|
}
|
|
@@ -501,11 +540,14 @@ var parseOptions = function parseOptions(options, allowed, image) {
|
|
|
501
540
|
// The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
|
|
502
541
|
// (a wrong row length would dither without an error, as long as it divides the pixel count).
|
|
503
542
|
if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
|
|
504
|
-
throw fail('invalid-argument',
|
|
543
|
+
throw fail('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
|
|
505
544
|
}
|
|
506
|
-
|
|
545
|
+
if (options.width !== undefined && image) {
|
|
546
|
+
checkSize(image.data.length / (image.format === 'rgb' ? 3 : 4), options.width, 'width', 'options.width');
|
|
547
|
+
}
|
|
548
|
+
const width = options.width !== undefined ? options.width : image ? image.width : undefined;
|
|
507
549
|
if (dither > 0) {
|
|
508
|
-
|
|
550
|
+
const channels = image.format === 'rgb' ? 3 : 4;
|
|
509
551
|
if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
|
|
510
552
|
throw fail('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
|
|
511
553
|
}
|
|
@@ -513,18 +555,18 @@ var parseOptions = function parseOptions(options, allowed, image) {
|
|
|
513
555
|
throw fail('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
|
|
514
556
|
}
|
|
515
557
|
}
|
|
516
|
-
|
|
517
|
-
if (signal !== undefined && (signal === null ||
|
|
558
|
+
const signal = options.signal;
|
|
559
|
+
if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
|
|
518
560
|
throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
|
|
519
561
|
}
|
|
520
|
-
|
|
562
|
+
const onProgress = options.onProgress;
|
|
521
563
|
if (onProgress !== undefined && typeof onProgress !== 'function') {
|
|
522
564
|
throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
|
|
523
565
|
}
|
|
524
566
|
|
|
525
567
|
// The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
|
|
526
|
-
|
|
527
|
-
|
|
568
|
+
const transparentOption = options.transparent === undefined ? false : options.transparent;
|
|
569
|
+
const transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
|
|
528
570
|
if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
|
|
529
571
|
throw fail('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
|
|
530
572
|
}
|
|
@@ -537,54 +579,65 @@ var parseOptions = function parseOptions(options, allowed, image) {
|
|
|
537
579
|
colorSpace: colorSpaces[colorSpace],
|
|
538
580
|
colorSpaceGiven: options.colorSpace !== undefined,
|
|
539
581
|
alpha: alphaModes[alpha],
|
|
540
|
-
precision
|
|
541
|
-
dither
|
|
582
|
+
precision,
|
|
583
|
+
dither,
|
|
542
584
|
width: dither > 0 ? width : 0,
|
|
543
|
-
transparent
|
|
585
|
+
transparent,
|
|
544
586
|
transparentGiven: options.transparent !== undefined,
|
|
545
|
-
signal
|
|
546
|
-
onProgress
|
|
587
|
+
signal,
|
|
588
|
+
onProgress
|
|
547
589
|
};
|
|
548
590
|
};
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
591
|
+
const controlOptions = ['signal', 'onProgress'];
|
|
592
|
+
const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
|
|
593
|
+
const quantizeOptions = [...clusterOptions, 'dither', 'width'];
|
|
552
594
|
// The functions that only map pixels take just `signal`: they finish in milliseconds, so there is nothing to report progress
|
|
553
595
|
// on or to interrupt part way; a signal that is already aborted does no work, which is all it can mean.
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
596
|
+
const mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
|
|
597
|
+
const quantizeIndexOptions = quantizeOptions;
|
|
598
|
+
const mapIndexOptions = [...mapOptions, 'transparent'];
|
|
557
599
|
|
|
558
|
-
//
|
|
559
|
-
|
|
560
|
-
|
|
600
|
+
// An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
|
|
601
|
+
// fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
|
|
602
|
+
// alpha from which an RGBA pixel needs a colour.
|
|
603
|
+
const checkNotEmpty = (palette, image, cutoff) => {
|
|
604
|
+
if (palette.length > 0) {
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
const data = image.data;
|
|
608
|
+
let visible = image.format === 'rgb' ? data.length > 0 : false;
|
|
609
|
+
for (let i = 3; !visible && i < data.length; i += 4) {
|
|
610
|
+
visible = data[i] >= cutoff;
|
|
611
|
+
}
|
|
612
|
+
if (visible) {
|
|
613
|
+
throw fail('invalid-argument', "Invalid palette: it is empty, but the image has visible pixels to map to it.", 'palette');
|
|
614
|
+
}
|
|
561
615
|
};
|
|
562
616
|
|
|
617
|
+
// The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
|
|
618
|
+
const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : colorSpaces[isPalette(palette) ? palette.colorSpace : 'rgb'];
|
|
619
|
+
|
|
563
620
|
// Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
|
|
564
621
|
// freeing everything afterwards.
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
622
|
+
const call = (wasm, buffers, fn) => {
|
|
623
|
+
const pointers = [];
|
|
624
|
+
let outputPointer = 0;
|
|
625
|
+
let aborted = false;
|
|
569
626
|
try {
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
var buffer = _step.value;
|
|
575
|
-
var pointer = wasm._malloc(buffer.length);
|
|
576
|
-
if (!pointer) {
|
|
577
|
-
throw fail('out-of-memory', "Failed to allocate WASM memory.");
|
|
578
|
-
}
|
|
579
|
-
pointers.push(pointer);
|
|
580
|
-
wasm.HEAPU8.set(buffer, pointer);
|
|
627
|
+
for (const buffer of buffers) {
|
|
628
|
+
const pointer = wasm._malloc(buffer.length);
|
|
629
|
+
if (!pointer) {
|
|
630
|
+
throw fail('out-of-memory', "Failed to allocate WASM memory.");
|
|
581
631
|
}
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
}
|
|
585
|
-
|
|
632
|
+
pointers.push(pointer);
|
|
633
|
+
wasm.HEAPU8.set(buffer, pointer);
|
|
634
|
+
}
|
|
635
|
+
outputPointer = fn(...pointers);
|
|
636
|
+
// Only the functions that read a clustering return nothing: when its records don't fit together (see
|
|
637
|
+
// _get_palette_from_clustering), which a clustering whose checksum matches never does.
|
|
638
|
+
if (!outputPointer) {
|
|
639
|
+
throw 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');
|
|
586
640
|
}
|
|
587
|
-
outputPointer = fn.apply(void 0, pointers);
|
|
588
641
|
return unpack(wasm, outputPointer);
|
|
589
642
|
} catch (error) {
|
|
590
643
|
if (!isAbort(error)) {
|
|
@@ -596,21 +649,13 @@ var call = function call(wasm, buffers, fn) {
|
|
|
596
649
|
} finally {
|
|
597
650
|
// After an abort the instance is being thrown away, and its allocator can't be trusted.
|
|
598
651
|
if (!aborted) {
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
try {
|
|
602
|
-
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
|
|
603
|
-
var _pointer = _step2.value;
|
|
604
|
-
wasm._free(_pointer);
|
|
605
|
-
}
|
|
606
|
-
} catch (err) {
|
|
607
|
-
_iterator2.e(err);
|
|
608
|
-
} finally {
|
|
609
|
-
_iterator2.f();
|
|
652
|
+
for (const pointer of pointers) {
|
|
653
|
+
wasm._free(pointer);
|
|
610
654
|
}
|
|
611
655
|
if (outputPointer) {
|
|
612
656
|
wasm._free(outputPointer);
|
|
613
657
|
}
|
|
658
|
+
retireIfLarge(wasm);
|
|
614
659
|
}
|
|
615
660
|
}
|
|
616
661
|
};
|
|
@@ -621,21 +666,20 @@ var call = function call(wasm, buffers, fn) {
|
|
|
621
666
|
// in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
|
|
622
667
|
// result is the same either way: the slices are the same steps in the same order.
|
|
623
668
|
|
|
624
|
-
|
|
669
|
+
const sliceMs = 10;
|
|
625
670
|
|
|
626
671
|
// Gives other tasks (a cancel message, timers, painting) a turn.
|
|
627
|
-
|
|
672
|
+
const yieldNow = () => {
|
|
628
673
|
if (typeof setImmediate === 'function') {
|
|
629
|
-
return new Promise(
|
|
630
|
-
return setImmediate(resolve);
|
|
631
|
-
});
|
|
674
|
+
return new Promise(resolve => setImmediate(resolve));
|
|
632
675
|
}
|
|
633
676
|
if (typeof MessageChannel === 'function') {
|
|
634
|
-
return new Promise(
|
|
635
|
-
|
|
636
|
-
port1
|
|
637
|
-
port2
|
|
638
|
-
|
|
677
|
+
return new Promise(resolve => {
|
|
678
|
+
const {
|
|
679
|
+
port1,
|
|
680
|
+
port2
|
|
681
|
+
} = new MessageChannel();
|
|
682
|
+
port1.onmessage = () => {
|
|
639
683
|
port1.close();
|
|
640
684
|
port2.close();
|
|
641
685
|
resolve();
|
|
@@ -643,215 +687,126 @@ var yieldNow = function yieldNow() {
|
|
|
643
687
|
port2.postMessage(null);
|
|
644
688
|
});
|
|
645
689
|
}
|
|
646
|
-
return new Promise(
|
|
647
|
-
return setTimeout(resolve, 0);
|
|
648
|
-
});
|
|
690
|
+
return new Promise(resolve => setTimeout(resolve, 0));
|
|
649
691
|
};
|
|
650
692
|
|
|
651
693
|
// Like fetch, an aborted call rejects with the signal's reason (an AbortError unless the caller gave another).
|
|
652
|
-
|
|
694
|
+
const checkAborted = signal => {
|
|
653
695
|
if (signal && signal.aborted) {
|
|
654
696
|
throw signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
|
|
655
697
|
}
|
|
656
698
|
};
|
|
657
699
|
|
|
658
700
|
// Reports progress as a fraction from 0 to 1, never going backwards and only when it changes.
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
return
|
|
662
|
-
|
|
701
|
+
const reporter = o => {
|
|
702
|
+
let last = -1;
|
|
703
|
+
return fraction => {
|
|
704
|
+
const value = Math.min(1, Math.max(0, fraction));
|
|
663
705
|
if (o.onProgress && value > last) {
|
|
664
706
|
last = value;
|
|
665
707
|
o.onProgress(value);
|
|
666
708
|
}
|
|
667
709
|
};
|
|
668
710
|
};
|
|
669
|
-
|
|
670
|
-
return o.signal !== undefined || o.onProgress !== undefined;
|
|
671
|
-
};
|
|
711
|
+
const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
|
|
672
712
|
|
|
673
713
|
// Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
_context4.p = 2;
|
|
691
|
-
wasm.HEAPU8.set(image.data, imagePointer);
|
|
692
|
-
job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
|
|
693
|
-
report(0);
|
|
694
|
-
case 3:
|
|
695
|
-
if (!true) {
|
|
696
|
-
_context4.n = 6;
|
|
697
|
-
break;
|
|
698
|
-
}
|
|
699
|
-
progress = wasm._clustering_job_step(job, sliceMs);
|
|
700
|
-
if (!(progress >= 1000)) {
|
|
701
|
-
_context4.n = 4;
|
|
702
|
-
break;
|
|
703
|
-
}
|
|
704
|
-
return _context4.a(3, 6);
|
|
705
|
-
case 4:
|
|
706
|
-
report(share * progress / 1000);
|
|
707
|
-
_context4.n = 5;
|
|
708
|
-
return yieldNow();
|
|
709
|
-
case 5:
|
|
710
|
-
checkAborted(o.signal);
|
|
711
|
-
_context4.n = 3;
|
|
712
|
-
break;
|
|
713
|
-
case 6:
|
|
714
|
-
pointer = wasm._clustering_job_result(job);
|
|
715
|
-
_context4.p = 7;
|
|
716
|
-
return _context4.a(2, unpack(wasm, pointer));
|
|
717
|
-
case 8:
|
|
718
|
-
_context4.p = 8;
|
|
719
|
-
wasm._free(pointer);
|
|
720
|
-
return _context4.f(8);
|
|
721
|
-
case 9:
|
|
722
|
-
_context4.n = 12;
|
|
723
|
-
break;
|
|
724
|
-
case 10:
|
|
725
|
-
_context4.p = 10;
|
|
726
|
-
_t = _context4.v;
|
|
727
|
-
if (isAbort(_t)) {
|
|
728
|
-
_context4.n = 11;
|
|
729
|
-
break;
|
|
730
|
-
}
|
|
731
|
-
throw _t;
|
|
732
|
-
case 11:
|
|
733
|
-
aborted = true;
|
|
734
|
-
discard(wasm);
|
|
735
|
-
throw outOfMemory();
|
|
736
|
-
case 12:
|
|
737
|
-
_context4.p = 12;
|
|
738
|
-
if (!aborted) {
|
|
739
|
-
if (job) {
|
|
740
|
-
wasm._clustering_job_free(job);
|
|
741
|
-
}
|
|
742
|
-
wasm._free(imagePointer);
|
|
743
|
-
}
|
|
744
|
-
return _context4.f(12);
|
|
745
|
-
case 13:
|
|
746
|
-
return _context4.a(2);
|
|
747
|
-
}
|
|
748
|
-
}, _callee4, null, [[7,, 8, 9], [2, 10, 12, 13]]);
|
|
749
|
-
}));
|
|
750
|
-
return function clusterInSlices(_x3, _x4, _x5, _x6, _x7) {
|
|
751
|
-
return _ref5.apply(this, arguments);
|
|
752
|
-
};
|
|
753
|
-
}();
|
|
754
|
-
export var getClustering = /*#__PURE__*/function () {
|
|
755
|
-
var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(image, options) {
|
|
756
|
-
var wasm, o, report, clustering;
|
|
757
|
-
return _regenerator().w(function (_context5) {
|
|
758
|
-
while (1) switch (_context5.n) {
|
|
759
|
-
case 0:
|
|
760
|
-
_context5.n = 1;
|
|
761
|
-
return acquire();
|
|
762
|
-
case 1:
|
|
763
|
-
wasm = _context5.v;
|
|
764
|
-
image = load(image);
|
|
765
|
-
o = parseOptions(options, clusterOptions, image);
|
|
766
|
-
if (!isControlled(o)) {
|
|
767
|
-
_context5.n = 3;
|
|
768
|
-
break;
|
|
769
|
-
}
|
|
770
|
-
report = reporter(o);
|
|
771
|
-
_context5.n = 2;
|
|
772
|
-
return clusterInSlices(wasm, image, o, report, 1);
|
|
773
|
-
case 2:
|
|
774
|
-
clustering = _context5.v;
|
|
775
|
-
report(1);
|
|
776
|
-
return _context5.a(2, markClustering(clustering));
|
|
777
|
-
case 3:
|
|
778
|
-
return _context5.a(2, markClustering(call(wasm, [image.data], function (imagePointer) {
|
|
779
|
-
return wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
|
|
780
|
-
})));
|
|
781
|
-
}
|
|
782
|
-
}, _callee5);
|
|
783
|
-
}));
|
|
784
|
-
return function getClustering(_x8, _x9) {
|
|
785
|
-
return _ref6.apply(this, arguments);
|
|
786
|
-
};
|
|
787
|
-
}();
|
|
788
|
-
export var getPalette = /*#__PURE__*/function () {
|
|
789
|
-
var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, k, options) {
|
|
790
|
-
var wasm, o, report, clustering, palette;
|
|
791
|
-
return _regenerator().w(function (_context6) {
|
|
792
|
-
while (1) switch (_context6.n) {
|
|
793
|
-
case 0:
|
|
794
|
-
_context6.n = 1;
|
|
795
|
-
return acquire();
|
|
796
|
-
case 1:
|
|
797
|
-
wasm = _context6.v;
|
|
798
|
-
image = load(image);
|
|
799
|
-
k = check(k);
|
|
800
|
-
o = parseOptions(options, clusterOptions, image);
|
|
801
|
-
if (!isControlled(o)) {
|
|
802
|
-
_context6.n = 3;
|
|
803
|
-
break;
|
|
804
|
-
}
|
|
805
|
-
report = reporter(o);
|
|
806
|
-
_context6.n = 2;
|
|
807
|
-
return clusterInSlices(wasm, image, o, report, 0.99);
|
|
808
|
-
case 2:
|
|
809
|
-
clustering = _context6.v;
|
|
810
|
-
checkAborted(o.signal);
|
|
811
|
-
palette = call(wasm, [clustering], function (clusteringPointer) {
|
|
812
|
-
return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
|
|
813
|
-
});
|
|
814
|
-
report(1);
|
|
815
|
-
return _context6.a(2, markPalette(palette, colorSpaceName(o.colorSpace)));
|
|
816
|
-
case 3:
|
|
817
|
-
return _context6.a(2, markPalette(call(wasm, [image.data], function (imagePointer) {
|
|
818
|
-
return wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent);
|
|
819
|
-
}), colorSpaceName(o.colorSpace)));
|
|
714
|
+
const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
715
|
+
checkAborted(o.signal);
|
|
716
|
+
const imagePointer = wasm._malloc(image.data.length);
|
|
717
|
+
if (!imagePointer) {
|
|
718
|
+
throw fail('out-of-memory', "Failed to allocate WASM memory.");
|
|
719
|
+
}
|
|
720
|
+
let job = 0;
|
|
721
|
+
let aborted = false;
|
|
722
|
+
try {
|
|
723
|
+
wasm.HEAPU8.set(image.data, imagePointer);
|
|
724
|
+
job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
|
|
725
|
+
report(0);
|
|
726
|
+
while (true) {
|
|
727
|
+
const progress = wasm._clustering_job_step(job, sliceMs);
|
|
728
|
+
if (progress >= 1000) {
|
|
729
|
+
break;
|
|
820
730
|
}
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
731
|
+
report(share * progress / 1000);
|
|
732
|
+
await yieldNow();
|
|
733
|
+
checkAborted(o.signal);
|
|
734
|
+
}
|
|
735
|
+
const pointer = wasm._clustering_job_result(job);
|
|
736
|
+
try {
|
|
737
|
+
return unpack(wasm, pointer);
|
|
738
|
+
} finally {
|
|
739
|
+
wasm._free(pointer);
|
|
740
|
+
}
|
|
741
|
+
} catch (error) {
|
|
742
|
+
if (!isAbort(error)) {
|
|
743
|
+
throw error;
|
|
744
|
+
}
|
|
745
|
+
aborted = true;
|
|
746
|
+
discard(wasm);
|
|
747
|
+
throw outOfMemory();
|
|
748
|
+
} finally {
|
|
749
|
+
if (!aborted) {
|
|
750
|
+
if (job) {
|
|
751
|
+
wasm._clustering_job_free(job);
|
|
842
752
|
}
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
753
|
+
wasm._free(imagePointer);
|
|
754
|
+
retireIfLarge(wasm);
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
};
|
|
758
|
+
|
|
759
|
+
// The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
|
|
760
|
+
// anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
|
|
761
|
+
const noOptions = (name, extra) => {
|
|
762
|
+
if (extra.some(value => value !== undefined)) {
|
|
763
|
+
throw fail('invalid-argument', `Invalid arguments: ${name} takes no options (a clustering already records its colour space, precision and cutoff). To map pixels with other options, use quantizeFromClustering.`, 'options');
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
|
|
767
|
+
// Every function checks its arguments and takes its bytes (see `held`) before it waits for anything: when the module is
|
|
768
|
+
// already loaded, `Module || await acquire()` doesn't wait, and the work up to the first slice of a long clustering
|
|
769
|
+
// happens before the call returns.
|
|
770
|
+
|
|
771
|
+
export const getClustering = async (image, options) => {
|
|
772
|
+
image = load(image);
|
|
773
|
+
const o = parseOptions(options, clusterOptions, image);
|
|
774
|
+
const wasm = Module || (await acquire());
|
|
775
|
+
if (isControlled(o)) {
|
|
776
|
+
const report = reporter(o);
|
|
777
|
+
const clustering = await clusterInSlices(wasm, image, o, report, 1);
|
|
778
|
+
report(1);
|
|
779
|
+
return markClustering(clustering);
|
|
780
|
+
}
|
|
781
|
+
return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent)));
|
|
782
|
+
};
|
|
783
|
+
export const getPalette = async (image, k, options) => {
|
|
784
|
+
image = load(image);
|
|
785
|
+
k = check(k);
|
|
786
|
+
const o = parseOptions(options, clusterOptions, image);
|
|
787
|
+
const wasm = Module || (await acquire());
|
|
788
|
+
if (isControlled(o)) {
|
|
789
|
+
const report = reporter(o);
|
|
790
|
+
const clustering = await clusterInSlices(wasm, image, o, report, 0.99);
|
|
791
|
+
checkAborted(o.signal);
|
|
792
|
+
const palette = call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k));
|
|
793
|
+
report(1);
|
|
794
|
+
return markPalette(palette, colorSpaceName(o.colorSpace));
|
|
795
|
+
}
|
|
796
|
+
return 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)), colorSpaceName(o.colorSpace));
|
|
797
|
+
};
|
|
798
|
+
export const getPaletteFromClustering = async (clustering, k, ...extra) => {
|
|
799
|
+
const header = readHeader(clustering);
|
|
800
|
+
k = check(k);
|
|
801
|
+
noOptions('getPaletteFromClustering', extra);
|
|
802
|
+
clustering = held(clustering);
|
|
803
|
+
const wasm = Module || (await acquire());
|
|
804
|
+
return markPalette(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), colorSpaceName(header.colorSpace));
|
|
805
|
+
};
|
|
849
806
|
|
|
850
807
|
// The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
return wasm._get_palette_weights(clusteringPointer, clustering.length, k);
|
|
854
|
-
});
|
|
808
|
+
const weightsOf = (wasm, clustering, header, k) => {
|
|
809
|
+
const bytes = call(wasm, [clustering], clusteringPointer => wasm._get_palette_weights(clusteringPointer, clustering.length, k));
|
|
855
810
|
if (header.merges > 0 && bytes.length === 0) {
|
|
856
811
|
throw fail('invalid-clustering', "Invalid clustering: its weights are inconsistent.", 'clustering');
|
|
857
812
|
}
|
|
@@ -861,325 +816,175 @@ var weightsOf = function weightsOf(wasm, clustering, header, k) {
|
|
|
861
816
|
// A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
|
|
862
817
|
// arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
|
|
863
818
|
// proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
|
|
864
|
-
export
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
|
|
890
|
-
weight = _step3.value;
|
|
891
|
-
total += weight;
|
|
892
|
-
}
|
|
893
|
-
} catch (err) {
|
|
894
|
-
_iterator3.e(err);
|
|
895
|
-
} finally {
|
|
896
|
-
_iterator3.f();
|
|
897
|
-
}
|
|
898
|
-
shares = new Float64Array(weights.length);
|
|
899
|
-
if (total > 0) {
|
|
900
|
-
for (i = 0; i < weights.length; i++) {
|
|
901
|
-
shares[i] = weights[i] / total;
|
|
902
|
-
}
|
|
903
|
-
}
|
|
904
|
-
return _context8.a(2, {
|
|
905
|
-
palette: palette,
|
|
906
|
-
weights: weights,
|
|
907
|
-
shares: shares
|
|
908
|
-
});
|
|
909
|
-
}
|
|
910
|
-
}, _callee8);
|
|
911
|
-
}));
|
|
912
|
-
return function getSwatchesFromClustering(_x13, _x14) {
|
|
913
|
-
return _ref9.apply(this, arguments);
|
|
819
|
+
export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
|
|
820
|
+
const header = readHeader(clustering);
|
|
821
|
+
k = check(k);
|
|
822
|
+
noOptions('getSwatchesFromClustering', extra);
|
|
823
|
+
if (header.version < 3) {
|
|
824
|
+
throw fail('unsupported-version', `Invalid clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
|
|
825
|
+
}
|
|
826
|
+
clustering = held(clustering);
|
|
827
|
+
const wasm = Module || (await acquire());
|
|
828
|
+
const palette = markPalette(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), colorSpaceName(header.colorSpace));
|
|
829
|
+
const weights = weightsOf(wasm, clustering, header, k);
|
|
830
|
+
let total = 0;
|
|
831
|
+
for (const weight of weights) {
|
|
832
|
+
total += weight;
|
|
833
|
+
}
|
|
834
|
+
const shares = new Float64Array(weights.length);
|
|
835
|
+
if (total > 0) {
|
|
836
|
+
for (let i = 0; i < weights.length; i++) {
|
|
837
|
+
shares[i] = weights[i] / total;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
return {
|
|
841
|
+
palette,
|
|
842
|
+
weights,
|
|
843
|
+
shares
|
|
914
844
|
};
|
|
915
|
-
}
|
|
845
|
+
};
|
|
916
846
|
|
|
917
847
|
// The same for an image: clusters it, then cuts, like getPalette.
|
|
918
|
-
export
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
// Arguments are checked in the order they are given (image, then k, then options), as in every other function.
|
|
925
|
-
load(image);
|
|
926
|
-
k = check(k);
|
|
927
|
-
_t2 = getSwatchesFromClustering;
|
|
928
|
-
_context9.n = 1;
|
|
929
|
-
return getClustering(image, options);
|
|
930
|
-
case 1:
|
|
931
|
-
_t3 = _context9.v;
|
|
932
|
-
_t4 = k;
|
|
933
|
-
return _context9.a(2, _t2(_t3, _t4));
|
|
934
|
-
}
|
|
935
|
-
}, _callee9);
|
|
936
|
-
}));
|
|
937
|
-
return function getSwatches(_x15, _x16, _x17) {
|
|
938
|
-
return _ref0.apply(this, arguments);
|
|
939
|
-
};
|
|
940
|
-
}();
|
|
848
|
+
export const getSwatches = async (image, k, options) => {
|
|
849
|
+
// Arguments are checked in the order they are given (image, then k, then options), as in every other function.
|
|
850
|
+
load(image);
|
|
851
|
+
k = check(k);
|
|
852
|
+
return getSwatchesFromClustering(await getClustering(image, options), k);
|
|
853
|
+
};
|
|
941
854
|
|
|
942
855
|
// What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
|
|
943
856
|
// squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
|
|
944
857
|
// weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
|
|
945
|
-
export
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
maxColors: colors,
|
|
959
|
-
totalWeight: null,
|
|
960
|
-
mse: null,
|
|
961
|
-
explained: null
|
|
962
|
-
};
|
|
963
|
-
if (!(header.version < 3)) {
|
|
964
|
-
_context0.n = 1;
|
|
965
|
-
break;
|
|
966
|
-
}
|
|
967
|
-
return _context0.a(2, info);
|
|
968
|
-
case 1:
|
|
969
|
-
view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
|
|
970
|
-
pixels = Math.pow(2, clustering[7]) / (clustering[6] === 1 ? 255 : 1);
|
|
971
|
-
total = view.getUint32(8, true);
|
|
972
|
-
info.totalWeight = total * pixels;
|
|
973
|
-
info.mse = new Float64Array(colors);
|
|
974
|
-
info.explained = new Float64Array(colors);
|
|
975
|
-
// The error of the leaf clusters: what `precision` below 8 discarded by grouping colours (0 before it was recorded).
|
|
976
|
-
remaining = header.headerLength >= 17 ? view.getFloat32(13, true) : 0;
|
|
977
|
-
if (colors > 0) {
|
|
978
|
-
info.mse[colors - 1] = remaining / total / 3;
|
|
979
|
-
}
|
|
980
|
-
for (i = header.merges - 1; i >= 0; i--) {
|
|
981
|
-
remaining += view.getFloat32(header.headerLength + 3 + i * header.recordLength + 17, true);
|
|
982
|
-
info.mse[i] = remaining / total / 3;
|
|
983
|
-
}
|
|
984
|
-
// The share of the image's variance each palette size keeps; 1 throughout for an image of one colour.
|
|
985
|
-
for (_i4 = 0; _i4 < colors; _i4++) {
|
|
986
|
-
info.explained[_i4] = info.mse[0] > 0 ? Math.max(0, Math.min(1, 1 - info.mse[_i4] / info.mse[0])) : 1;
|
|
987
|
-
}
|
|
988
|
-
return _context0.a(2, info);
|
|
989
|
-
}
|
|
990
|
-
}, _callee0);
|
|
991
|
-
}));
|
|
992
|
-
return function getClusteringInfo(_x18) {
|
|
993
|
-
return _ref1.apply(this, arguments);
|
|
994
|
-
};
|
|
995
|
-
}();
|
|
996
|
-
export var quantize = /*#__PURE__*/function () {
|
|
997
|
-
var _ref10 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1(image, k, options) {
|
|
998
|
-
var wasm, wrap, o, report, clustering, mapped;
|
|
999
|
-
return _regenerator().w(function (_context1) {
|
|
1000
|
-
while (1) switch (_context1.n) {
|
|
1001
|
-
case 0:
|
|
1002
|
-
_context1.n = 1;
|
|
1003
|
-
return acquire();
|
|
1004
|
-
case 1:
|
|
1005
|
-
wasm = _context1.v;
|
|
1006
|
-
wrap = getWrapper(image);
|
|
1007
|
-
image = load(image);
|
|
1008
|
-
k = check(k);
|
|
1009
|
-
o = parseOptions(options, quantizeOptions, image);
|
|
1010
|
-
if (!isControlled(o)) {
|
|
1011
|
-
_context1.n = 3;
|
|
1012
|
-
break;
|
|
1013
|
-
}
|
|
1014
|
-
report = reporter(o);
|
|
1015
|
-
_context1.n = 2;
|
|
1016
|
-
return clusterInSlices(wasm, image, o, report, 0.9);
|
|
1017
|
-
case 2:
|
|
1018
|
-
clustering = _context1.v;
|
|
1019
|
-
checkAborted(o.signal);
|
|
1020
|
-
mapped = wrap(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
|
|
1021
|
-
return wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width);
|
|
1022
|
-
}));
|
|
1023
|
-
report(1);
|
|
1024
|
-
return _context1.a(2, mapped);
|
|
1025
|
-
case 3:
|
|
1026
|
-
return _context1.a(2, wrap(call(wasm, [image.data], function (imagePointer) {
|
|
1027
|
-
return wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent);
|
|
1028
|
-
})));
|
|
1029
|
-
}
|
|
1030
|
-
}, _callee1);
|
|
1031
|
-
}));
|
|
1032
|
-
return function quantize(_x19, _x20, _x21) {
|
|
1033
|
-
return _ref10.apply(this, arguments);
|
|
1034
|
-
};
|
|
1035
|
-
}();
|
|
1036
|
-
export var quantizeFromClustering = /*#__PURE__*/function () {
|
|
1037
|
-
var _ref11 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10(image, clustering, k, options) {
|
|
1038
|
-
var wasm, wrap, o, colorSpace, result;
|
|
1039
|
-
return _regenerator().w(function (_context10) {
|
|
1040
|
-
while (1) switch (_context10.n) {
|
|
1041
|
-
case 0:
|
|
1042
|
-
_context10.n = 1;
|
|
1043
|
-
return acquire();
|
|
1044
|
-
case 1:
|
|
1045
|
-
wasm = _context10.v;
|
|
1046
|
-
wrap = getWrapper(image);
|
|
1047
|
-
image = load(image);
|
|
1048
|
-
readHeader(clustering);
|
|
1049
|
-
k = check(k);
|
|
1050
|
-
o = parseOptions(options, mapOptions, image);
|
|
1051
|
-
checkAborted(o.signal);
|
|
1052
|
-
colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
1053
|
-
result = wrap(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
|
|
1054
|
-
return wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width);
|
|
1055
|
-
}));
|
|
1056
|
-
return _context10.a(2, result);
|
|
1057
|
-
}
|
|
1058
|
-
}, _callee10);
|
|
1059
|
-
}));
|
|
1060
|
-
return function quantizeFromClustering(_x22, _x23, _x24, _x25) {
|
|
1061
|
-
return _ref11.apply(this, arguments);
|
|
1062
|
-
};
|
|
1063
|
-
}();
|
|
1064
|
-
export var quantizeWithPalette = /*#__PURE__*/function () {
|
|
1065
|
-
var _ref12 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee11(image, palette, options) {
|
|
1066
|
-
var wasm, wrap, o, result;
|
|
1067
|
-
return _regenerator().w(function (_context11) {
|
|
1068
|
-
while (1) switch (_context11.n) {
|
|
1069
|
-
case 0:
|
|
1070
|
-
_context11.n = 1;
|
|
1071
|
-
return acquire();
|
|
1072
|
-
case 1:
|
|
1073
|
-
wasm = _context11.v;
|
|
1074
|
-
wrap = getWrapper(image);
|
|
1075
|
-
image = load(image);
|
|
1076
|
-
checkPalette(palette);
|
|
1077
|
-
o = parseOptions(options, mapOptions, image);
|
|
1078
|
-
checkAborted(o.signal);
|
|
1079
|
-
result = wrap(call(wasm, [image.data, palette], function (imagePointer, palettePointer) {
|
|
1080
|
-
return wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, matchingSpace(o, palette), o.dither, o.width);
|
|
1081
|
-
}));
|
|
1082
|
-
return _context11.a(2, result);
|
|
1083
|
-
}
|
|
1084
|
-
}, _callee11);
|
|
1085
|
-
}));
|
|
1086
|
-
return function quantizeWithPalette(_x26, _x27, _x28) {
|
|
1087
|
-
return _ref12.apply(this, arguments);
|
|
1088
|
-
};
|
|
1089
|
-
}();
|
|
1090
|
-
export var quantizeToIndices = /*#__PURE__*/function () {
|
|
1091
|
-
var _ref13 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee12(image, k, options) {
|
|
1092
|
-
var wasm, original, o, report, clustering, indexed;
|
|
1093
|
-
return _regenerator().w(function (_context12) {
|
|
1094
|
-
while (1) switch (_context12.n) {
|
|
1095
|
-
case 0:
|
|
1096
|
-
_context12.n = 1;
|
|
1097
|
-
return acquire();
|
|
1098
|
-
case 1:
|
|
1099
|
-
wasm = _context12.v;
|
|
1100
|
-
original = image;
|
|
1101
|
-
image = load(image);
|
|
1102
|
-
k = check(k);
|
|
1103
|
-
o = parseOptions(options, quantizeIndexOptions, image);
|
|
1104
|
-
if (!isControlled(o)) {
|
|
1105
|
-
_context12.n = 3;
|
|
1106
|
-
break;
|
|
1107
|
-
}
|
|
1108
|
-
report = reporter(o);
|
|
1109
|
-
_context12.n = 2;
|
|
1110
|
-
return clusterInSlices(wasm, image, o, report, 0.9);
|
|
1111
|
-
case 2:
|
|
1112
|
-
clustering = _context12.v;
|
|
1113
|
-
checkAborted(o.signal);
|
|
1114
|
-
indexed = unpackIndices(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
|
|
1115
|
-
return wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width, o.transparent);
|
|
1116
|
-
}), original, colorSpaceName(o.colorSpace));
|
|
1117
|
-
report(1);
|
|
1118
|
-
return _context12.a(2, indexed);
|
|
1119
|
-
case 3:
|
|
1120
|
-
return _context12.a(2, unpackIndices(call(wasm, [image.data], function (imagePointer) {
|
|
1121
|
-
return wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent);
|
|
1122
|
-
}), original, colorSpaceName(o.colorSpace)));
|
|
1123
|
-
}
|
|
1124
|
-
}, _callee12);
|
|
1125
|
-
}));
|
|
1126
|
-
return function quantizeToIndices(_x29, _x30, _x31) {
|
|
1127
|
-
return _ref13.apply(this, arguments);
|
|
858
|
+
export const getClusteringInfo = async (clustering, ...extra) => {
|
|
859
|
+
const header = readHeader(clustering);
|
|
860
|
+
noOptions('getClusteringInfo', extra);
|
|
861
|
+
const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
|
|
862
|
+
const info = {
|
|
863
|
+
formatVersion: header.version,
|
|
864
|
+
colorSpace: colorSpaceName(header.colorSpace),
|
|
865
|
+
precision: header.precision,
|
|
866
|
+
transparent: header.transparent === 0 ? false : header.transparent,
|
|
867
|
+
maxColors: colors,
|
|
868
|
+
totalWeight: null,
|
|
869
|
+
mse: null,
|
|
870
|
+
explained: null
|
|
1128
871
|
};
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
}
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
872
|
+
if (header.version < 3) {
|
|
873
|
+
return info;
|
|
874
|
+
}
|
|
875
|
+
const view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
|
|
876
|
+
const pixels = 2 ** clustering[7] / (clustering[6] === 1 ? 255 : 1);
|
|
877
|
+
const total = view.getUint32(8, true);
|
|
878
|
+
info.totalWeight = total * pixels;
|
|
879
|
+
info.mse = new Float64Array(colors);
|
|
880
|
+
info.explained = new Float64Array(colors);
|
|
881
|
+
// The error of the leaf clusters: what `precision` below 8 discarded by grouping colours (0 before it was recorded).
|
|
882
|
+
let remaining = header.headerLength >= 17 ? view.getFloat32(13, true) : 0;
|
|
883
|
+
if (colors > 0) {
|
|
884
|
+
info.mse[colors - 1] = remaining / total / 3;
|
|
885
|
+
}
|
|
886
|
+
for (let i = header.merges - 1; i >= 0; i--) {
|
|
887
|
+
remaining += view.getFloat32(header.headerLength + 3 + i * header.recordLength + 17, true);
|
|
888
|
+
info.mse[i] = remaining / total / 3;
|
|
889
|
+
}
|
|
890
|
+
// Errors are sums of squares, so a cost that is negative or not a number can only come from damaged bytes (a clustering
|
|
891
|
+
// from 3.0.0-beta.1 has no checksum to catch them first).
|
|
892
|
+
for (let i = 0; i < colors; i++) {
|
|
893
|
+
if (!(info.mse[i] >= 0) || !Number.isFinite(info.mse[i])) {
|
|
894
|
+
throw fail('invalid-clustering', "Invalid clustering: its recorded errors are not valid numbers, so it is damaged. Cluster the image again.", 'clustering');
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
// The share of the image's variance each palette size keeps; 1 throughout for an image of one colour.
|
|
898
|
+
for (let i = 0; i < colors; i++) {
|
|
899
|
+
info.explained[i] = info.mse[0] > 0 ? Math.max(0, Math.min(1, 1 - info.mse[i] / info.mse[0])) : 1;
|
|
900
|
+
}
|
|
901
|
+
return info;
|
|
902
|
+
};
|
|
903
|
+
export const quantize = async (image, k, options) => {
|
|
904
|
+
const wrap = getWrapper(image);
|
|
905
|
+
image = load(image);
|
|
906
|
+
k = check(k);
|
|
907
|
+
const o = parseOptions(options, quantizeOptions, image);
|
|
908
|
+
const wasm = Module || (await acquire());
|
|
909
|
+
if (isControlled(o)) {
|
|
910
|
+
const report = reporter(o);
|
|
911
|
+
const clustering = await clusterInSlices(wasm, image, o, report, 0.9);
|
|
912
|
+
checkAborted(o.signal);
|
|
913
|
+
const mapped = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width)));
|
|
914
|
+
report(1);
|
|
915
|
+
return mapped;
|
|
916
|
+
}
|
|
917
|
+
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.width, o.transparent)));
|
|
918
|
+
};
|
|
919
|
+
export const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
920
|
+
const wrap = getWrapper(image);
|
|
921
|
+
image = load(image);
|
|
922
|
+
readHeader(clustering);
|
|
923
|
+
k = check(k);
|
|
924
|
+
const o = parseOptions(options, mapOptions, image);
|
|
925
|
+
clustering = held(clustering);
|
|
926
|
+
const wasm = Module || (await acquire());
|
|
927
|
+
checkAborted(o.signal);
|
|
928
|
+
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
929
|
+
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.width)));
|
|
930
|
+
return result;
|
|
931
|
+
};
|
|
932
|
+
export const quantizeWithPalette = async (image, palette, options) => {
|
|
933
|
+
const wrap = getWrapper(image);
|
|
934
|
+
image = load(image);
|
|
935
|
+
checkPalette(palette);
|
|
936
|
+
const o = parseOptions(options, mapOptions, image);
|
|
937
|
+
checkNotEmpty(palette, image, 1);
|
|
938
|
+
const space = matchingSpace(o, palette);
|
|
939
|
+
palette = held(palette);
|
|
940
|
+
const wasm = Module || (await acquire());
|
|
941
|
+
checkAborted(o.signal);
|
|
942
|
+
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.width)));
|
|
943
|
+
return result;
|
|
944
|
+
};
|
|
945
|
+
export const quantizeToIndices = async (image, k, options) => {
|
|
946
|
+
const original = image;
|
|
947
|
+
image = load(image);
|
|
948
|
+
k = check(k);
|
|
949
|
+
const o = parseOptions(options, quantizeIndexOptions, image);
|
|
950
|
+
const wasm = Module || (await acquire());
|
|
951
|
+
if (isControlled(o)) {
|
|
952
|
+
const report = reporter(o);
|
|
953
|
+
const clustering = await clusterInSlices(wasm, image, o, report, 0.9);
|
|
954
|
+
checkAborted(o.signal);
|
|
955
|
+
const indexed = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width, o.transparent)), original, colorSpaceName(o.colorSpace));
|
|
956
|
+
report(1);
|
|
957
|
+
return indexed;
|
|
958
|
+
}
|
|
959
|
+
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.width, o.transparent)), original, colorSpaceName(o.colorSpace));
|
|
960
|
+
};
|
|
961
|
+
export const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
|
|
962
|
+
const original = image;
|
|
963
|
+
image = load(image);
|
|
964
|
+
const header = readHeader(clustering);
|
|
965
|
+
k = check(k);
|
|
966
|
+
const o = parseOptions(options, mapIndexOptions, image);
|
|
967
|
+
clustering = held(clustering);
|
|
968
|
+
const wasm = Module || (await acquire());
|
|
969
|
+
checkAborted(o.signal);
|
|
970
|
+
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
971
|
+
|
|
972
|
+
// The cutoff the clustering was made with is the default, so clustering and mapping agree unless a cutoff is named.
|
|
973
|
+
const cutoff = o.transparentGiven ? o.transparent : header.transparent;
|
|
974
|
+
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.width, cutoff)), original, colorSpaceName(header.colorSpace));
|
|
975
|
+
return result;
|
|
976
|
+
};
|
|
977
|
+
export const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
978
|
+
const original = image;
|
|
979
|
+
image = load(image);
|
|
980
|
+
checkPalette(palette);
|
|
981
|
+
const o = parseOptions(options, mapIndexOptions, image);
|
|
982
|
+
checkNotEmpty(palette, image, o.transparent > 0 ? o.transparent : 1);
|
|
983
|
+
const space = matchingSpace(o, palette);
|
|
984
|
+
const paletteSpace = isPalette(palette) ? palette.colorSpace : colorSpaceName(space);
|
|
985
|
+
palette = held(palette);
|
|
986
|
+
const wasm = Module || (await acquire());
|
|
987
|
+
checkAborted(o.signal);
|
|
988
|
+
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.width, o.transparent)), original, paletteSpace);
|
|
989
|
+
return result;
|
|
990
|
+
};
|