agglomerative-clustering 3.0.0-beta.2 → 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 +101 -17
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +537 -1034
- package/dist/index.d.cts +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.mjs +520 -1018
- package/dist/shared.cjs +167 -152
- package/dist/shared.mjs +149 -150
- package/dist/worker-thread.mjs +115 -349
- package/dist/worker.mjs +435 -746
- package/package.json +4 -1
package/dist/index.mjs
CHANGED
|
@@ -1,94 +1,69 @@
|
|
|
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 _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 }; })(); }
|
|
3
|
-
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); }
|
|
4
|
-
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); }
|
|
5
|
-
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); }); }; }
|
|
6
|
-
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
|
|
7
|
-
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."); }
|
|
8
|
-
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; } }
|
|
9
|
-
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
|
|
10
|
-
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
|
|
11
|
-
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; }
|
|
12
|
-
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); }
|
|
13
1
|
import createWasmModule from './clustering.js';
|
|
14
|
-
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, 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
|
|
8
|
+
export const formatVersion = latestVersion;
|
|
21
9
|
|
|
22
10
|
// Checked by tag rather than `instanceof`, so values from another realm are recognised: an ImageData from an iframe's
|
|
23
11
|
// canvas, a WebAssembly.Module compiled by a bundler's runtime (Next.js Edge's `import wasm from '…wasm?module'`), a URL
|
|
24
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.
|
|
25
|
-
|
|
26
|
-
return Object.prototype.toString.call(value);
|
|
27
|
-
};
|
|
13
|
+
const tagOf = value => Object.prototype.toString.call(value);
|
|
28
14
|
// (`instanceof` is kept too, for implementations without the tag, such as node-canvas's ImageData.)
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
return _typeof(value) === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
|
|
34
|
-
};
|
|
35
|
-
var isURL = function isURL(value) {
|
|
36
|
-
return _typeof(value) === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
|
|
37
|
-
};
|
|
38
|
-
var codes = {
|
|
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 = {
|
|
39
19
|
'rgba': 0,
|
|
40
20
|
'rgb': 1
|
|
41
21
|
};
|
|
42
|
-
|
|
22
|
+
const alphaModes = {
|
|
43
23
|
'ignore': 0,
|
|
44
24
|
'weight': 1
|
|
45
25
|
};
|
|
46
|
-
|
|
26
|
+
let Module = null;
|
|
47
27
|
|
|
48
28
|
// Turns init's `wasm` option into the settings the Emscripten glue understands. The glue finds its .wasm file next to
|
|
49
29
|
// itself by default (`new URL('clustering.wasm', import.meta.url)`); this lets a caller say where it is, or hand over
|
|
50
30
|
// the bytes or an already compiled module, for CDNs, strict CSPs and runtimes (such as Cloudflare Workers) that
|
|
51
31
|
// cannot fetch or compile it that way. `onError` receives instantiation errors, which the glue would otherwise swallow.
|
|
52
|
-
|
|
32
|
+
const wasmSettings = (wasm, onError) => {
|
|
53
33
|
if (wasm === undefined) {
|
|
54
34
|
return {};
|
|
55
35
|
}
|
|
56
36
|
if (typeof wasm === 'string' || isURL(wasm)) {
|
|
57
|
-
|
|
37
|
+
const location = String(wasm);
|
|
58
38
|
return {
|
|
59
|
-
locateFile:
|
|
60
|
-
return path.endsWith('.wasm') ? location : directory + path;
|
|
61
|
-
}
|
|
39
|
+
locateFile: (path, directory) => path.endsWith('.wasm') ? location : directory + path
|
|
62
40
|
};
|
|
63
41
|
}
|
|
64
42
|
// Bytes and compiled modules go through `instantiateWasm`: this build of the glue reads no `wasmBinary` setting. The glue
|
|
65
43
|
// sets itself up on the instance inside `receive`, which throws for a module that isn't this one (it has other exports);
|
|
66
44
|
// that is reported as a failed load rather than left to escape, which would leave the load waiting forever.
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
}
|
|
76
|
-
};
|
|
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
|
+
}
|
|
77
53
|
};
|
|
78
54
|
if (isArrayBufferLike(wasm) || ArrayBuffer.isView(wasm)) {
|
|
79
|
-
|
|
55
|
+
const source = isArrayBufferLike(wasm) ? wasm : new Uint8Array(wasm.buffer, wasm.byteOffset, wasm.byteLength);
|
|
80
56
|
return {
|
|
81
|
-
instantiateWasm:
|
|
82
|
-
WebAssembly.instantiate(source, imports).then(
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
}, onError);
|
|
57
|
+
instantiateWasm: (imports, receive) => {
|
|
58
|
+
WebAssembly.instantiate(source, imports).then(({
|
|
59
|
+
instance
|
|
60
|
+
}) => accept(receive)(instance), onError);
|
|
86
61
|
}
|
|
87
62
|
};
|
|
88
63
|
}
|
|
89
64
|
if (isWasmModule(wasm)) {
|
|
90
65
|
return {
|
|
91
|
-
instantiateWasm:
|
|
66
|
+
instantiateWasm: (imports, receive) => {
|
|
92
67
|
WebAssembly.instantiate(wasm, imports).then(accept(receive), onError);
|
|
93
68
|
}
|
|
94
69
|
};
|
|
@@ -100,25 +75,27 @@ var wasmSettings = function wasmSettings(wasm, onError) {
|
|
|
100
75
|
// bundler that moved the file, an engine without WebAssembly SIMD. The engine's own error (a CompileError, a failed fetch)
|
|
101
76
|
// says little about which, so the message leads with what happened and then gives the likely fix for where it ran.
|
|
102
77
|
// The smallest module that uses a SIMD instruction (from wasm-feature-detect), to tell an old engine from a missing file.
|
|
103
|
-
|
|
104
|
-
|
|
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 = () => {
|
|
105
80
|
try {
|
|
106
|
-
return
|
|
81
|
+
return typeof WebAssembly === 'object' && WebAssembly.validate(new Uint8Array(simdProbe));
|
|
107
82
|
} catch (error) {
|
|
108
83
|
return false;
|
|
109
84
|
}
|
|
110
85
|
};
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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];
|
|
114
91
|
// Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
|
|
115
92
|
// and wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
|
|
116
|
-
|
|
117
|
-
|
|
93
|
+
let reason = text.replace(/\s*\(?Build with -sASSERTIONS for more info\.?\)?/, '').trim().replace(/\.+$/, '');
|
|
94
|
+
const aborted = /^Aborted\((.*)\)$/.exec(reason);
|
|
118
95
|
if (aborted) {
|
|
119
96
|
reason = aborted[1].replace(/\.+$/, '');
|
|
120
97
|
}
|
|
121
|
-
|
|
98
|
+
let advice;
|
|
122
99
|
if (!hasSimd()) {
|
|
123
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).";
|
|
124
101
|
} else if (given) {
|
|
@@ -128,8 +105,8 @@ var wasmLoadFailed = function wasmLoadFailed(cause, given) {
|
|
|
128
105
|
} else {
|
|
129
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 }).";
|
|
130
107
|
}
|
|
131
|
-
return Object.assign(fail('wasm-load-failed',
|
|
132
|
-
cause
|
|
108
|
+
return Object.assign(fail('wasm-load-failed', `Could not load the WebAssembly module: ${reason || 'unknown error'}. ${advice}`), {
|
|
109
|
+
cause
|
|
133
110
|
});
|
|
134
111
|
};
|
|
135
112
|
|
|
@@ -137,223 +114,148 @@ var wasmLoadFailed = function wasmLoadFailed(cause, given) {
|
|
|
137
114
|
// not a public interface. One left over from another version (a stale cache, a CDN serving an old file, an `init({ wasm })`
|
|
138
115
|
// pointing at the wrong one) would misbehave in ways nothing explains, so the module says which version it is and a
|
|
139
116
|
// mismatch is reported when it loads.
|
|
140
|
-
|
|
117
|
+
const checkWasmVersion = instance => {
|
|
141
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
|
|
142
119
|
// this library's at all may have none either: both are reported as a version mismatch, never as a stray TypeError.
|
|
143
|
-
|
|
120
|
+
let found = '';
|
|
144
121
|
try {
|
|
145
|
-
|
|
146
|
-
|
|
122
|
+
const pointer = instance._library_version();
|
|
123
|
+
const heap = instance.HEAPU8;
|
|
147
124
|
if (typeof pointer === 'number' && pointer > 0 && heap) {
|
|
148
|
-
|
|
125
|
+
let end = pointer;
|
|
149
126
|
while (heap[end] !== 0 && end - pointer < 64) {
|
|
150
127
|
end++;
|
|
151
128
|
}
|
|
152
|
-
found = String.fromCharCode
|
|
129
|
+
found = String.fromCharCode(...heap.subarray(pointer, end));
|
|
153
130
|
}
|
|
154
131
|
} catch (error) {/* no version export */}
|
|
155
|
-
|
|
132
|
+
const expected = `agglomerative-clustering@${version}`;
|
|
156
133
|
if (found !== expected) {
|
|
157
|
-
|
|
158
|
-
throw fail('wasm-load-failed',
|
|
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.`);
|
|
159
136
|
}
|
|
160
137
|
};
|
|
161
138
|
|
|
162
139
|
// Instantiates the module from init's `wasm` option (undefined: the glue finds the .wasm next to itself).
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
140
|
+
const instantiate = wasm => {
|
|
141
|
+
let reject;
|
|
142
|
+
const failed = new Promise((_, r) => {
|
|
166
143
|
reject = r;
|
|
167
144
|
});
|
|
168
|
-
failed
|
|
169
|
-
|
|
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]);
|
|
170
155
|
};
|
|
171
156
|
|
|
172
157
|
// The bytes of this package's clustering.wasm as Node resolves it from the working directory, for when the copy next to
|
|
173
158
|
// the script is missing (see acquire). The specifiers are built at run time so bundlers leave them alone (see worker.js).
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
createRequire = _yield$import.createRequire;
|
|
185
|
-
_context.n = 2;
|
|
186
|
-
return import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
|
|
187
|
-
case 2:
|
|
188
|
-
_yield$import2 = _context.v;
|
|
189
|
-
readFile = _yield$import2.readFile;
|
|
190
|
-
file = createRequire("".concat(process.cwd(), "/")).resolve('agglomerative-clustering/clustering.wasm');
|
|
191
|
-
return _context.a(2, readFile(file));
|
|
192
|
-
}
|
|
193
|
-
}, _callee);
|
|
194
|
-
}));
|
|
195
|
-
return function packagedWasm() {
|
|
196
|
-
return _ref2.apply(this, arguments);
|
|
197
|
-
};
|
|
198
|
-
}();
|
|
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
|
+
};
|
|
199
169
|
|
|
200
170
|
// The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
|
|
201
|
-
|
|
171
|
+
let loading = null;
|
|
202
172
|
|
|
203
173
|
// Calls get the instance they run on from `acquire` and keep using it, so replacing the current instance (see `discard`)
|
|
204
174
|
// never changes the module under a call already in flight.
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
if (!Module) {
|
|
241
|
-
_context3.n = 5;
|
|
242
|
-
break;
|
|
243
|
-
}
|
|
244
|
-
return _context3.a(2, Module);
|
|
245
|
-
case 5:
|
|
246
|
-
if (!loading) {
|
|
247
|
-
wasm = options.wasm;
|
|
248
|
-
loading = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
|
|
249
|
-
var instance, fallback, _t, _t2;
|
|
250
|
-
return _regenerator().w(function (_context2) {
|
|
251
|
-
while (1) switch (_context2.n) {
|
|
252
|
-
case 0:
|
|
253
|
-
_context2.p = 0;
|
|
254
|
-
_context2.n = 1;
|
|
255
|
-
return instantiate(wasm);
|
|
256
|
-
case 1:
|
|
257
|
-
instance = _context2.v;
|
|
258
|
-
_context2.n = 8;
|
|
259
|
-
break;
|
|
260
|
-
case 2:
|
|
261
|
-
_context2.p = 2;
|
|
262
|
-
_t = _context2.v;
|
|
263
|
-
if (!(wasm === undefined && isNodeLike)) {
|
|
264
|
-
_context2.n = 4;
|
|
265
|
-
break;
|
|
266
|
-
}
|
|
267
|
-
_context2.n = 3;
|
|
268
|
-
return packagedWasm()["catch"](function () {
|
|
269
|
-
return null;
|
|
270
|
-
});
|
|
271
|
-
case 3:
|
|
272
|
-
_t2 = _context2.v;
|
|
273
|
-
_context2.n = 5;
|
|
274
|
-
break;
|
|
275
|
-
case 4:
|
|
276
|
-
_t2 = null;
|
|
277
|
-
case 5:
|
|
278
|
-
fallback = _t2;
|
|
279
|
-
if (fallback) {
|
|
280
|
-
_context2.n = 6;
|
|
281
|
-
break;
|
|
282
|
-
}
|
|
283
|
-
throw wasmLoadFailed(_t, wasm !== undefined);
|
|
284
|
-
case 6:
|
|
285
|
-
_context2.n = 7;
|
|
286
|
-
return instantiate(fallback)["catch"](function () {
|
|
287
|
-
throw wasmLoadFailed(_t, false);
|
|
288
|
-
});
|
|
289
|
-
case 7:
|
|
290
|
-
instance = _context2.v;
|
|
291
|
-
case 8:
|
|
292
|
-
checkWasmVersion(instance);
|
|
293
|
-
Module = instance;
|
|
294
|
-
return _context2.a(2, instance);
|
|
295
|
-
}
|
|
296
|
-
}, _callee2, null, [[0, 2]]);
|
|
297
|
-
}))()["catch"](function (error) {
|
|
298
|
-
loading = null;
|
|
299
|
-
throw error;
|
|
300
|
-
});
|
|
301
|
-
}
|
|
302
|
-
return _context3.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
|
+
});
|
|
303
210
|
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
211
|
+
checkWasmVersion(instance);
|
|
212
|
+
Module = instance;
|
|
213
|
+
return instance;
|
|
214
|
+
})().catch(error => {
|
|
215
|
+
loading = null;
|
|
216
|
+
throw error;
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
return loading;
|
|
220
|
+
};
|
|
310
221
|
|
|
311
222
|
// Loads the WebAssembly module. Every other function does this on first use, so calling it is optional, except to
|
|
312
223
|
// say where the .wasm file is (`wasm`), which must come before anything else. The first load that succeeds wins:
|
|
313
224
|
// later calls, with or without options, get the same module.
|
|
314
|
-
export
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
while (1) switch (_context4.n) {
|
|
318
|
-
case 0:
|
|
319
|
-
_context4.n = 1;
|
|
320
|
-
return acquire(options);
|
|
321
|
-
case 1:
|
|
322
|
-
return _context4.a(2);
|
|
323
|
-
}
|
|
324
|
-
}, _callee4);
|
|
325
|
-
}));
|
|
326
|
-
return function init(_x2) {
|
|
327
|
-
return _ref5.apply(this, arguments);
|
|
328
|
-
};
|
|
329
|
-
}();
|
|
225
|
+
export const init = async options => {
|
|
226
|
+
await acquire(options);
|
|
227
|
+
};
|
|
330
228
|
|
|
331
229
|
// A WebAssembly abort, which is what running out of memory looks like, leaves the instance's heap full of whatever the
|
|
332
230
|
// failed call had allocated and never freed (the abort skips destructors), so every later large call on it would fail
|
|
333
231
|
// too. The instance is therefore discarded: the next call loads a fresh one, and calls already running keep theirs.
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
};
|
|
337
|
-
var discard = function discard(instance) {
|
|
232
|
+
const isAbort = error => error instanceof Error && error.name === 'RuntimeError' && /^Aborted\(/.test(error.message);
|
|
233
|
+
const discard = instance => {
|
|
338
234
|
if (Module === instance) {
|
|
339
235
|
Module = null;
|
|
340
236
|
loading = null;
|
|
341
237
|
}
|
|
342
238
|
};
|
|
343
|
-
|
|
344
|
-
|
|
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
|
+
}
|
|
345
248
|
};
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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));
|
|
350
254
|
return outputBuffer;
|
|
351
255
|
};
|
|
352
256
|
|
|
353
257
|
// A Uint8Array over exactly the same bytes, so views into a larger buffer (subarrays) stay views of their own range.
|
|
354
|
-
|
|
355
|
-
return isUint8Array(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
356
|
-
};
|
|
258
|
+
const bytes = data => isUint8Array(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
357
259
|
|
|
358
260
|
// ----- Encoded image files -------------------------------------------------------------------------------------------
|
|
359
261
|
// A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
|
|
@@ -365,8 +267,8 @@ var bytes = function bytes(data) {
|
|
|
365
267
|
// This is also where decoding would go. The library doesn't decode files today (that needs a decoder per format, and
|
|
366
268
|
// sharp, pngjs, createImageBitmap and the like already do it); when it does, a file recognised here is decoded into
|
|
367
269
|
// { data, format, width, height } instead of rejected, and `load` becomes asynchronous. See docs/ROADMAP.md.
|
|
368
|
-
|
|
369
|
-
for (
|
|
270
|
+
const ascii = (bytes, at, text) => {
|
|
271
|
+
for (let i = 0; i < text.length; i++) {
|
|
370
272
|
if (bytes[at + i] !== text.charCodeAt(i)) {
|
|
371
273
|
return false;
|
|
372
274
|
}
|
|
@@ -376,8 +278,8 @@ var ascii = function ascii(bytes, at, text) {
|
|
|
376
278
|
|
|
377
279
|
// The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
|
|
378
280
|
// beyond the first few bytes, that raw pixels all but never match.
|
|
379
|
-
|
|
380
|
-
|
|
281
|
+
const sniffImageFormat = bytes => {
|
|
282
|
+
const length = bytes.length;
|
|
381
283
|
if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
|
|
382
284
|
return 'PNG';
|
|
383
285
|
}
|
|
@@ -397,13 +299,11 @@ var sniffImageFormat = function sniffImageFormat(bytes) {
|
|
|
397
299
|
}
|
|
398
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
|
|
399
301
|
if (length >= 12) {
|
|
400
|
-
|
|
401
|
-
|
|
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;
|
|
402
304
|
if (little || big) {
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
};
|
|
406
|
-
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;
|
|
407
307
|
if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
|
|
408
308
|
return 'TIFF';
|
|
409
309
|
}
|
|
@@ -414,51 +314,16 @@ var sniffImageFormat = function sniffImageFormat(bytes) {
|
|
|
414
314
|
if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
|
|
415
315
|
return 'AVIF';
|
|
416
316
|
}
|
|
417
|
-
if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(
|
|
418
|
-
return ascii(bytes, 8, brand);
|
|
419
|
-
})) {
|
|
317
|
+
if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
|
|
420
318
|
return 'HEIC';
|
|
421
319
|
}
|
|
422
320
|
}
|
|
423
321
|
return null;
|
|
424
322
|
};
|
|
425
323
|
|
|
426
|
-
// What to say about something that isn't an image, when it is a common thing to pass by mistake: each has a one-line fix.
|
|
427
|
-
var imageHint = function imageHint(image) {
|
|
428
|
-
var decode = " Decode it to pixels first, then pass them.";
|
|
429
|
-
if (image === undefined || image === null) {
|
|
430
|
-
return " Got ".concat(image, ".");
|
|
431
|
-
}
|
|
432
|
-
if (typeof image === 'string') {
|
|
433
|
-
return " Got a string (a file name, URL or data URL?): load and decode it to pixels first.";
|
|
434
|
-
}
|
|
435
|
-
if (_typeof(image) !== 'object') {
|
|
436
|
-
return " Got a ".concat(_typeof(image), ".");
|
|
437
|
-
}
|
|
438
|
-
if (Array.isArray(image)) {
|
|
439
|
-
return " Got a plain array: use new Uint8Array(array) for RGBA bytes, or { data: new Uint8Array(array), format: 'rgb' }.";
|
|
440
|
-
}
|
|
441
|
-
if (isArrayBufferLike(image)) {
|
|
442
|
-
return " Got an ArrayBuffer, which has no pixel layout: wrap it, new Uint8Array(buffer) for RGBA bytes (if it holds an encoded image file, decode it first).";
|
|
443
|
-
}
|
|
444
|
-
if (typeof image.getContext === 'function') {
|
|
445
|
-
return " Got a canvas: pass its pixels, canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).";
|
|
446
|
-
}
|
|
447
|
-
if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
|
|
448
|
-
return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
|
|
449
|
-
}
|
|
450
|
-
if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
|
|
451
|
-
return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
|
|
452
|
-
}
|
|
453
|
-
if (image.data && !image.format) {
|
|
454
|
-
return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
|
|
455
|
-
}
|
|
456
|
-
return '';
|
|
457
|
-
};
|
|
458
|
-
|
|
459
324
|
// A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
|
|
460
|
-
|
|
461
|
-
|
|
325
|
+
const isDetached = view => {
|
|
326
|
+
const buffer = view.buffer;
|
|
462
327
|
if (typeof buffer.detached === 'boolean') {
|
|
463
328
|
return buffer.detached;
|
|
464
329
|
}
|
|
@@ -473,36 +338,34 @@ var isDetached = function isDetached(view) {
|
|
|
473
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
|
|
474
339
|
// or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
|
|
475
340
|
// call returns; until then (the first call) a copy is kept for when it has loaded.
|
|
476
|
-
|
|
477
|
-
return Module ? data : data.slice();
|
|
478
|
-
};
|
|
341
|
+
const held = data => Module ? data : data.slice();
|
|
479
342
|
|
|
480
343
|
// width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
|
|
481
344
|
// pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
|
|
482
|
-
|
|
345
|
+
const checkSize = (pixels, size, name, argument) => {
|
|
483
346
|
if (size === undefined) {
|
|
484
347
|
return;
|
|
485
348
|
}
|
|
486
349
|
if (!Number.isInteger(size) || size < 0) {
|
|
487
|
-
throw fail('invalid-argument',
|
|
350
|
+
throw fail('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
|
|
488
351
|
}
|
|
489
352
|
if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
|
|
490
|
-
throw fail('invalid-argument',
|
|
353
|
+
throw fail('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
|
|
491
354
|
}
|
|
492
355
|
};
|
|
493
|
-
|
|
356
|
+
const load = image => {
|
|
494
357
|
if (isClustering(image) || isPalette(image)) {
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
throw fail('invalid-argument',
|
|
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');
|
|
498
361
|
}
|
|
499
362
|
if (ArrayBuffer.isView(image) && isDetached(image)) {
|
|
500
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');
|
|
501
364
|
}
|
|
502
365
|
if (isUint8Array(image)) {
|
|
503
|
-
|
|
366
|
+
const encoded = sniffImageFormat(image);
|
|
504
367
|
if (encoded) {
|
|
505
|
-
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');
|
|
506
369
|
}
|
|
507
370
|
if (image.length % 4 !== 0) {
|
|
508
371
|
throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
|
|
@@ -525,8 +388,8 @@ var load = function load(image) {
|
|
|
525
388
|
if (ArrayBuffer.isView(image)) {
|
|
526
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');
|
|
527
390
|
}
|
|
528
|
-
if (
|
|
529
|
-
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');
|
|
530
393
|
}
|
|
531
394
|
if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
|
|
532
395
|
throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
|
|
@@ -537,15 +400,15 @@ var load = function load(image) {
|
|
|
537
400
|
if (!Object.keys(codes).includes(image.format)) {
|
|
538
401
|
throw fail('invalid-argument', "Invalid format: must be 'rgb' or 'rgba'.", 'image');
|
|
539
402
|
}
|
|
540
|
-
|
|
403
|
+
const channels = image.format === 'rgb' ? 3 : 4;
|
|
541
404
|
if (image.data.length % channels !== 0) {
|
|
542
|
-
throw fail('invalid-argument',
|
|
405
|
+
throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${channels} for '${image.format}'.`, 'image');
|
|
543
406
|
}
|
|
544
|
-
|
|
407
|
+
const pixels = image.data.length / channels;
|
|
545
408
|
checkSize(pixels, image.width, 'image width', 'image');
|
|
546
409
|
checkSize(pixels, image.height, 'image height', 'image');
|
|
547
410
|
if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
|
|
548
|
-
throw fail('invalid-argument',
|
|
411
|
+
throw fail('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
|
|
549
412
|
}
|
|
550
413
|
return {
|
|
551
414
|
data: held(bytes(image.data)),
|
|
@@ -553,61 +416,61 @@ var load = function load(image) {
|
|
|
553
416
|
width: image.width
|
|
554
417
|
};
|
|
555
418
|
};
|
|
556
|
-
|
|
419
|
+
const getWrapper = image => {
|
|
557
420
|
if (isImageData(image)) {
|
|
558
421
|
// The pixels stay in the colour space they came in ('display-p3' canvases), so the result must say so.
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
};
|
|
567
|
-
}
|
|
568
|
-
if (!isUint8Array(image) &&
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
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 = {
|
|
574
439
|
data: output,
|
|
575
|
-
format
|
|
440
|
+
format
|
|
576
441
|
};
|
|
577
|
-
if (
|
|
578
|
-
result.width =
|
|
442
|
+
if (width !== undefined) {
|
|
443
|
+
result.width = width;
|
|
579
444
|
}
|
|
580
|
-
if (
|
|
581
|
-
result.height =
|
|
445
|
+
if (height !== undefined) {
|
|
446
|
+
result.height = height;
|
|
582
447
|
}
|
|
583
448
|
return result;
|
|
584
449
|
};
|
|
585
450
|
}
|
|
586
|
-
return
|
|
587
|
-
return output;
|
|
588
|
-
};
|
|
451
|
+
return output => output;
|
|
589
452
|
};
|
|
590
453
|
|
|
591
454
|
// Decodes _quantize_indices output: [entries, transparent index, index bytes] as 32-bit little-endian values, then
|
|
592
455
|
// the palette, then the indices. `image` is the caller's original input, for its width and height.
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
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);
|
|
603
466
|
// Little-endian, like the WASM heap, which Emscripten's own typed-array views already assume of the host.
|
|
604
467
|
new Uint8Array(indices.buffer).set(output.subarray(start));
|
|
605
468
|
// `colors` is the palette without the transparent entry, ready to map with again (the entry is black and takes no part in matching)
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
palette
|
|
609
|
-
colors
|
|
610
|
-
indices
|
|
469
|
+
const colors = transparent < 0 ? palette : markPalette(palette.slice(0, 3 * transparent), colorSpace);
|
|
470
|
+
const result = {
|
|
471
|
+
palette,
|
|
472
|
+
colors,
|
|
473
|
+
indices,
|
|
611
474
|
indexBits: 8 * indexBytes,
|
|
612
475
|
transparentIndex: transparent < 0 ? null : transparent
|
|
613
476
|
};
|
|
@@ -624,9 +487,11 @@ var unpackIndices = function unpackIndices(output, image, colorSpace) {
|
|
|
624
487
|
|
|
625
488
|
// Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
|
|
626
489
|
// the WASM side holds (a larger one would overflow its int).
|
|
627
|
-
|
|
490
|
+
const check = k => {
|
|
628
491
|
if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
|
|
629
|
-
|
|
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');
|
|
630
495
|
}
|
|
631
496
|
return Math.min(k, 0x7FFFFFFF);
|
|
632
497
|
};
|
|
@@ -642,7 +507,7 @@ var check = function check(k) {
|
|
|
642
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);
|
|
643
508
|
// indexed output also gives them their own entry, which counts towards k
|
|
644
509
|
|
|
645
|
-
|
|
510
|
+
const parseOptions = (options, allowed, image) => {
|
|
646
511
|
if (options === undefined) {
|
|
647
512
|
options = {};
|
|
648
513
|
}
|
|
@@ -650,25 +515,24 @@ var parseOptions = function parseOptions(options, allowed, image) {
|
|
|
650
515
|
throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
|
|
651
516
|
}
|
|
652
517
|
options = snapshot(options);
|
|
653
|
-
for (
|
|
654
|
-
var key = _Object$keys2[_i2];
|
|
518
|
+
for (const key of Object.keys(options)) {
|
|
655
519
|
if (!allowed.includes(key)) {
|
|
656
|
-
throw fail('invalid-argument',
|
|
520
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.`, `options.${key}`);
|
|
657
521
|
}
|
|
658
522
|
}
|
|
659
|
-
|
|
523
|
+
const colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
|
|
660
524
|
if (!Object.keys(colorSpaces).includes(colorSpace)) {
|
|
661
525
|
throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
|
|
662
526
|
}
|
|
663
|
-
|
|
527
|
+
const alpha = options.alpha === undefined ? 'weight' : options.alpha;
|
|
664
528
|
if (!Object.keys(alphaModes).includes(alpha)) {
|
|
665
529
|
throw fail('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
|
|
666
530
|
}
|
|
667
|
-
|
|
531
|
+
const precision = options.precision === undefined ? 8 : options.precision;
|
|
668
532
|
if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
|
|
669
533
|
throw fail('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
|
|
670
534
|
}
|
|
671
|
-
|
|
535
|
+
const dither = options.dither === undefined || options.dither === false ? 0 : options.dither === true ? 1 : options.dither;
|
|
672
536
|
if (typeof dither !== 'number' || !Number.isFinite(dither) || dither < 0 || dither > 1) {
|
|
673
537
|
throw fail('invalid-argument', "Invalid dither: must be a boolean or a number from 0 to 1.", 'options.dither');
|
|
674
538
|
}
|
|
@@ -676,14 +540,14 @@ var parseOptions = function parseOptions(options, allowed, image) {
|
|
|
676
540
|
// The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
|
|
677
541
|
// (a wrong row length would dither without an error, as long as it divides the pixel count).
|
|
678
542
|
if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
|
|
679
|
-
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');
|
|
680
544
|
}
|
|
681
545
|
if (options.width !== undefined && image) {
|
|
682
546
|
checkSize(image.data.length / (image.format === 'rgb' ? 3 : 4), options.width, 'width', 'options.width');
|
|
683
547
|
}
|
|
684
|
-
|
|
548
|
+
const width = options.width !== undefined ? options.width : image ? image.width : undefined;
|
|
685
549
|
if (dither > 0) {
|
|
686
|
-
|
|
550
|
+
const channels = image.format === 'rgb' ? 3 : 4;
|
|
687
551
|
if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
|
|
688
552
|
throw fail('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
|
|
689
553
|
}
|
|
@@ -691,18 +555,18 @@ var parseOptions = function parseOptions(options, allowed, image) {
|
|
|
691
555
|
throw fail('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
|
|
692
556
|
}
|
|
693
557
|
}
|
|
694
|
-
|
|
695
|
-
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')) {
|
|
696
560
|
throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
|
|
697
561
|
}
|
|
698
|
-
|
|
562
|
+
const onProgress = options.onProgress;
|
|
699
563
|
if (onProgress !== undefined && typeof onProgress !== 'function') {
|
|
700
564
|
throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
|
|
701
565
|
}
|
|
702
566
|
|
|
703
567
|
// The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
|
|
704
|
-
|
|
705
|
-
|
|
568
|
+
const transparentOption = options.transparent === undefined ? false : options.transparent;
|
|
569
|
+
const transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
|
|
706
570
|
if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
|
|
707
571
|
throw fail('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
|
|
708
572
|
}
|
|
@@ -715,34 +579,34 @@ var parseOptions = function parseOptions(options, allowed, image) {
|
|
|
715
579
|
colorSpace: colorSpaces[colorSpace],
|
|
716
580
|
colorSpaceGiven: options.colorSpace !== undefined,
|
|
717
581
|
alpha: alphaModes[alpha],
|
|
718
|
-
precision
|
|
719
|
-
dither
|
|
582
|
+
precision,
|
|
583
|
+
dither,
|
|
720
584
|
width: dither > 0 ? width : 0,
|
|
721
|
-
transparent
|
|
585
|
+
transparent,
|
|
722
586
|
transparentGiven: options.transparent !== undefined,
|
|
723
|
-
signal
|
|
724
|
-
onProgress
|
|
587
|
+
signal,
|
|
588
|
+
onProgress
|
|
725
589
|
};
|
|
726
590
|
};
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
591
|
+
const controlOptions = ['signal', 'onProgress'];
|
|
592
|
+
const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
|
|
593
|
+
const quantizeOptions = [...clusterOptions, 'dither', 'width'];
|
|
730
594
|
// The functions that only map pixels take just `signal`: they finish in milliseconds, so there is nothing to report progress
|
|
731
595
|
// on or to interrupt part way; a signal that is already aborted does no work, which is all it can mean.
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
596
|
+
const mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
|
|
597
|
+
const quantizeIndexOptions = quantizeOptions;
|
|
598
|
+
const mapIndexOptions = [...mapOptions, 'transparent'];
|
|
735
599
|
|
|
736
600
|
// An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
|
|
737
601
|
// fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
|
|
738
602
|
// alpha from which an RGBA pixel needs a colour.
|
|
739
|
-
|
|
603
|
+
const checkNotEmpty = (palette, image, cutoff) => {
|
|
740
604
|
if (palette.length > 0) {
|
|
741
605
|
return;
|
|
742
606
|
}
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
for (
|
|
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) {
|
|
746
610
|
visible = data[i] >= cutoff;
|
|
747
611
|
}
|
|
748
612
|
if (visible) {
|
|
@@ -751,35 +615,24 @@ var checkNotEmpty = function checkNotEmpty(palette, image, cutoff) {
|
|
|
751
615
|
};
|
|
752
616
|
|
|
753
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.
|
|
754
|
-
|
|
755
|
-
return o.colorSpaceGiven ? o.colorSpace : colorSpaces[isPalette(palette) ? palette.colorSpace : 'rgb'];
|
|
756
|
-
};
|
|
618
|
+
const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : colorSpaces[isPalette(palette) ? palette.colorSpace : 'rgb'];
|
|
757
619
|
|
|
758
620
|
// Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
|
|
759
621
|
// freeing everything afterwards.
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
622
|
+
const call = (wasm, buffers, fn) => {
|
|
623
|
+
const pointers = [];
|
|
624
|
+
let outputPointer = 0;
|
|
625
|
+
let aborted = false;
|
|
764
626
|
try {
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
var buffer = _step.value;
|
|
770
|
-
var pointer = wasm._malloc(buffer.length);
|
|
771
|
-
if (!pointer) {
|
|
772
|
-
throw fail('out-of-memory', "Failed to allocate WASM memory.");
|
|
773
|
-
}
|
|
774
|
-
pointers.push(pointer);
|
|
775
|
-
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.");
|
|
776
631
|
}
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
} finally {
|
|
780
|
-
_iterator.f();
|
|
632
|
+
pointers.push(pointer);
|
|
633
|
+
wasm.HEAPU8.set(buffer, pointer);
|
|
781
634
|
}
|
|
782
|
-
outputPointer = fn
|
|
635
|
+
outputPointer = fn(...pointers);
|
|
783
636
|
// Only the functions that read a clustering return nothing: when its records don't fit together (see
|
|
784
637
|
// _get_palette_from_clustering), which a clustering whose checksum matches never does.
|
|
785
638
|
if (!outputPointer) {
|
|
@@ -796,21 +649,13 @@ var call = function call(wasm, buffers, fn) {
|
|
|
796
649
|
} finally {
|
|
797
650
|
// After an abort the instance is being thrown away, and its allocator can't be trusted.
|
|
798
651
|
if (!aborted) {
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
try {
|
|
802
|
-
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
|
|
803
|
-
var _pointer = _step2.value;
|
|
804
|
-
wasm._free(_pointer);
|
|
805
|
-
}
|
|
806
|
-
} catch (err) {
|
|
807
|
-
_iterator2.e(err);
|
|
808
|
-
} finally {
|
|
809
|
-
_iterator2.f();
|
|
652
|
+
for (const pointer of pointers) {
|
|
653
|
+
wasm._free(pointer);
|
|
810
654
|
}
|
|
811
655
|
if (outputPointer) {
|
|
812
656
|
wasm._free(outputPointer);
|
|
813
657
|
}
|
|
658
|
+
retireIfLarge(wasm);
|
|
814
659
|
}
|
|
815
660
|
}
|
|
816
661
|
};
|
|
@@ -821,21 +666,20 @@ var call = function call(wasm, buffers, fn) {
|
|
|
821
666
|
// in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
|
|
822
667
|
// result is the same either way: the slices are the same steps in the same order.
|
|
823
668
|
|
|
824
|
-
|
|
669
|
+
const sliceMs = 10;
|
|
825
670
|
|
|
826
671
|
// Gives other tasks (a cancel message, timers, painting) a turn.
|
|
827
|
-
|
|
672
|
+
const yieldNow = () => {
|
|
828
673
|
if (typeof setImmediate === 'function') {
|
|
829
|
-
return new Promise(
|
|
830
|
-
return setImmediate(resolve);
|
|
831
|
-
});
|
|
674
|
+
return new Promise(resolve => setImmediate(resolve));
|
|
832
675
|
}
|
|
833
676
|
if (typeof MessageChannel === 'function') {
|
|
834
|
-
return new Promise(
|
|
835
|
-
|
|
836
|
-
port1
|
|
837
|
-
port2
|
|
838
|
-
|
|
677
|
+
return new Promise(resolve => {
|
|
678
|
+
const {
|
|
679
|
+
port1,
|
|
680
|
+
port2
|
|
681
|
+
} = new MessageChannel();
|
|
682
|
+
port1.onmessage = () => {
|
|
839
683
|
port1.close();
|
|
840
684
|
port2.close();
|
|
841
685
|
resolve();
|
|
@@ -843,242 +687,126 @@ var yieldNow = function yieldNow() {
|
|
|
843
687
|
port2.postMessage(null);
|
|
844
688
|
});
|
|
845
689
|
}
|
|
846
|
-
return new Promise(
|
|
847
|
-
return setTimeout(resolve, 0);
|
|
848
|
-
});
|
|
690
|
+
return new Promise(resolve => setTimeout(resolve, 0));
|
|
849
691
|
};
|
|
850
692
|
|
|
851
693
|
// Like fetch, an aborted call rejects with the signal's reason (an AbortError unless the caller gave another).
|
|
852
|
-
|
|
694
|
+
const checkAborted = signal => {
|
|
853
695
|
if (signal && signal.aborted) {
|
|
854
696
|
throw signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
|
|
855
697
|
}
|
|
856
698
|
};
|
|
857
699
|
|
|
858
700
|
// Reports progress as a fraction from 0 to 1, never going backwards and only when it changes.
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
return
|
|
862
|
-
|
|
701
|
+
const reporter = o => {
|
|
702
|
+
let last = -1;
|
|
703
|
+
return fraction => {
|
|
704
|
+
const value = Math.min(1, Math.max(0, fraction));
|
|
863
705
|
if (o.onProgress && value > last) {
|
|
864
706
|
last = value;
|
|
865
707
|
o.onProgress(value);
|
|
866
708
|
}
|
|
867
709
|
};
|
|
868
710
|
};
|
|
869
|
-
|
|
870
|
-
return o.signal !== undefined || o.onProgress !== undefined;
|
|
871
|
-
};
|
|
711
|
+
const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
|
|
872
712
|
|
|
873
713
|
// Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
_context5.p = 2;
|
|
891
|
-
wasm.HEAPU8.set(image.data, imagePointer);
|
|
892
|
-
job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
|
|
893
|
-
report(0);
|
|
894
|
-
case 3:
|
|
895
|
-
if (!true) {
|
|
896
|
-
_context5.n = 6;
|
|
897
|
-
break;
|
|
898
|
-
}
|
|
899
|
-
progress = wasm._clustering_job_step(job, sliceMs);
|
|
900
|
-
if (!(progress >= 1000)) {
|
|
901
|
-
_context5.n = 4;
|
|
902
|
-
break;
|
|
903
|
-
}
|
|
904
|
-
return _context5.a(3, 6);
|
|
905
|
-
case 4:
|
|
906
|
-
report(share * progress / 1000);
|
|
907
|
-
_context5.n = 5;
|
|
908
|
-
return yieldNow();
|
|
909
|
-
case 5:
|
|
910
|
-
checkAborted(o.signal);
|
|
911
|
-
_context5.n = 3;
|
|
912
|
-
break;
|
|
913
|
-
case 6:
|
|
914
|
-
pointer = wasm._clustering_job_result(job);
|
|
915
|
-
_context5.p = 7;
|
|
916
|
-
return _context5.a(2, unpack(wasm, pointer));
|
|
917
|
-
case 8:
|
|
918
|
-
_context5.p = 8;
|
|
919
|
-
wasm._free(pointer);
|
|
920
|
-
return _context5.f(8);
|
|
921
|
-
case 9:
|
|
922
|
-
_context5.n = 12;
|
|
923
|
-
break;
|
|
924
|
-
case 10:
|
|
925
|
-
_context5.p = 10;
|
|
926
|
-
_t3 = _context5.v;
|
|
927
|
-
if (isAbort(_t3)) {
|
|
928
|
-
_context5.n = 11;
|
|
929
|
-
break;
|
|
930
|
-
}
|
|
931
|
-
throw _t3;
|
|
932
|
-
case 11:
|
|
933
|
-
aborted = true;
|
|
934
|
-
discard(wasm);
|
|
935
|
-
throw outOfMemory();
|
|
936
|
-
case 12:
|
|
937
|
-
_context5.p = 12;
|
|
938
|
-
if (!aborted) {
|
|
939
|
-
if (job) {
|
|
940
|
-
wasm._clustering_job_free(job);
|
|
941
|
-
}
|
|
942
|
-
wasm._free(imagePointer);
|
|
943
|
-
}
|
|
944
|
-
return _context5.f(12);
|
|
945
|
-
case 13:
|
|
946
|
-
return _context5.a(2);
|
|
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;
|
|
947
730
|
}
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
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);
|
|
752
|
+
}
|
|
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
|
+
};
|
|
954
766
|
|
|
955
767
|
// Every function checks its arguments and takes its bytes (see `held`) before it waits for anything: when the module is
|
|
956
768
|
// already loaded, `Module || await acquire()` doesn't wait, and the work up to the first slice of a long clustering
|
|
957
769
|
// happens before the call returns.
|
|
958
770
|
|
|
959
|
-
export
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
}, _callee6);
|
|
995
|
-
}));
|
|
996
|
-
return function getClustering(_x8, _x9) {
|
|
997
|
-
return _ref7.apply(this, arguments);
|
|
998
|
-
};
|
|
999
|
-
}();
|
|
1000
|
-
export var getPalette = /*#__PURE__*/function () {
|
|
1001
|
-
var _ref8 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(image, k, options) {
|
|
1002
|
-
var o, wasm, report, clustering, palette, _t5;
|
|
1003
|
-
return _regenerator().w(function (_context7) {
|
|
1004
|
-
while (1) switch (_context7.n) {
|
|
1005
|
-
case 0:
|
|
1006
|
-
image = load(image);
|
|
1007
|
-
k = check(k);
|
|
1008
|
-
o = parseOptions(options, clusterOptions, image);
|
|
1009
|
-
_t5 = Module;
|
|
1010
|
-
if (_t5) {
|
|
1011
|
-
_context7.n = 2;
|
|
1012
|
-
break;
|
|
1013
|
-
}
|
|
1014
|
-
_context7.n = 1;
|
|
1015
|
-
return acquire();
|
|
1016
|
-
case 1:
|
|
1017
|
-
_t5 = _context7.v;
|
|
1018
|
-
case 2:
|
|
1019
|
-
wasm = _t5;
|
|
1020
|
-
if (!isControlled(o)) {
|
|
1021
|
-
_context7.n = 4;
|
|
1022
|
-
break;
|
|
1023
|
-
}
|
|
1024
|
-
report = reporter(o);
|
|
1025
|
-
_context7.n = 3;
|
|
1026
|
-
return clusterInSlices(wasm, image, o, report, 0.99);
|
|
1027
|
-
case 3:
|
|
1028
|
-
clustering = _context7.v;
|
|
1029
|
-
checkAborted(o.signal);
|
|
1030
|
-
palette = call(wasm, [clustering], function (clusteringPointer) {
|
|
1031
|
-
return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
|
|
1032
|
-
});
|
|
1033
|
-
report(1);
|
|
1034
|
-
return _context7.a(2, markPalette(palette, colorSpaceName(o.colorSpace)));
|
|
1035
|
-
case 4:
|
|
1036
|
-
return _context7.a(2, markPalette(call(wasm, [image.data], function (imagePointer) {
|
|
1037
|
-
return wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent);
|
|
1038
|
-
}), colorSpaceName(o.colorSpace)));
|
|
1039
|
-
}
|
|
1040
|
-
}, _callee7);
|
|
1041
|
-
}));
|
|
1042
|
-
return function getPalette(_x0, _x1, _x10) {
|
|
1043
|
-
return _ref8.apply(this, arguments);
|
|
1044
|
-
};
|
|
1045
|
-
}();
|
|
1046
|
-
export var getPaletteFromClustering = /*#__PURE__*/function () {
|
|
1047
|
-
var _ref9 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(clustering, k) {
|
|
1048
|
-
var header, wasm, _t6;
|
|
1049
|
-
return _regenerator().w(function (_context8) {
|
|
1050
|
-
while (1) switch (_context8.n) {
|
|
1051
|
-
case 0:
|
|
1052
|
-
header = readHeader(clustering);
|
|
1053
|
-
k = check(k);
|
|
1054
|
-
clustering = held(clustering);
|
|
1055
|
-
_t6 = Module;
|
|
1056
|
-
if (_t6) {
|
|
1057
|
-
_context8.n = 2;
|
|
1058
|
-
break;
|
|
1059
|
-
}
|
|
1060
|
-
_context8.n = 1;
|
|
1061
|
-
return acquire();
|
|
1062
|
-
case 1:
|
|
1063
|
-
_t6 = _context8.v;
|
|
1064
|
-
case 2:
|
|
1065
|
-
wasm = _t6;
|
|
1066
|
-
return _context8.a(2, markPalette(call(wasm, [clustering], function (clusteringPointer) {
|
|
1067
|
-
return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
|
|
1068
|
-
}), colorSpaceName(header.colorSpace)));
|
|
1069
|
-
}
|
|
1070
|
-
}, _callee8);
|
|
1071
|
-
}));
|
|
1072
|
-
return function getPaletteFromClustering(_x11, _x12) {
|
|
1073
|
-
return _ref9.apply(this, arguments);
|
|
1074
|
-
};
|
|
1075
|
-
}();
|
|
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
|
+
};
|
|
1076
806
|
|
|
1077
807
|
// The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
return wasm._get_palette_weights(clusteringPointer, clustering.length, k);
|
|
1081
|
-
});
|
|
808
|
+
const weightsOf = (wasm, clustering, header, k) => {
|
|
809
|
+
const bytes = call(wasm, [clustering], clusteringPointer => wasm._get_palette_weights(clusteringPointer, clustering.length, k));
|
|
1082
810
|
if (header.merges > 0 && bytes.length === 0) {
|
|
1083
811
|
throw fail('invalid-clustering', "Invalid clustering: its weights are inconsistent.", 'clustering');
|
|
1084
812
|
}
|
|
@@ -1088,401 +816,175 @@ var weightsOf = function weightsOf(wasm, clustering, header, k) {
|
|
|
1088
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
|
|
1089
817
|
// arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
|
|
1090
818
|
// proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
|
|
1091
|
-
export
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
wasm = _t7;
|
|
1117
|
-
palette = markPalette(call(wasm, [clustering], function (clusteringPointer) {
|
|
1118
|
-
return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
|
|
1119
|
-
}), colorSpaceName(header.colorSpace));
|
|
1120
|
-
weights = weightsOf(wasm, clustering, header, k);
|
|
1121
|
-
total = 0;
|
|
1122
|
-
_iterator3 = _createForOfIteratorHelper(weights);
|
|
1123
|
-
try {
|
|
1124
|
-
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
|
|
1125
|
-
weight = _step3.value;
|
|
1126
|
-
total += weight;
|
|
1127
|
-
}
|
|
1128
|
-
} catch (err) {
|
|
1129
|
-
_iterator3.e(err);
|
|
1130
|
-
} finally {
|
|
1131
|
-
_iterator3.f();
|
|
1132
|
-
}
|
|
1133
|
-
shares = new Float64Array(weights.length);
|
|
1134
|
-
if (total > 0) {
|
|
1135
|
-
for (i = 0; i < weights.length; i++) {
|
|
1136
|
-
shares[i] = weights[i] / total;
|
|
1137
|
-
}
|
|
1138
|
-
}
|
|
1139
|
-
return _context9.a(2, {
|
|
1140
|
-
palette: palette,
|
|
1141
|
-
weights: weights,
|
|
1142
|
-
shares: shares
|
|
1143
|
-
});
|
|
1144
|
-
}
|
|
1145
|
-
}, _callee9);
|
|
1146
|
-
}));
|
|
1147
|
-
return function getSwatchesFromClustering(_x13, _x14) {
|
|
1148
|
-
return _ref0.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
|
|
1149
844
|
};
|
|
1150
|
-
}
|
|
845
|
+
};
|
|
1151
846
|
|
|
1152
847
|
// The same for an image: clusters it, then cuts, like getPalette.
|
|
1153
|
-
export
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
// Arguments are checked in the order they are given (image, then k, then options), as in every other function.
|
|
1160
|
-
load(image);
|
|
1161
|
-
k = check(k);
|
|
1162
|
-
_t8 = getSwatchesFromClustering;
|
|
1163
|
-
_context0.n = 1;
|
|
1164
|
-
return getClustering(image, options);
|
|
1165
|
-
case 1:
|
|
1166
|
-
_t9 = _context0.v;
|
|
1167
|
-
_t0 = k;
|
|
1168
|
-
return _context0.a(2, _t8(_t9, _t0));
|
|
1169
|
-
}
|
|
1170
|
-
}, _callee0);
|
|
1171
|
-
}));
|
|
1172
|
-
return function getSwatches(_x15, _x16, _x17) {
|
|
1173
|
-
return _ref1.apply(this, arguments);
|
|
1174
|
-
};
|
|
1175
|
-
}();
|
|
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
|
+
};
|
|
1176
854
|
|
|
1177
855
|
// What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
|
|
1178
856
|
// squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
|
|
1179
857
|
// weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
|
|
1180
|
-
export
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
maxColors: colors,
|
|
1194
|
-
totalWeight: null,
|
|
1195
|
-
mse: null,
|
|
1196
|
-
explained: null
|
|
1197
|
-
};
|
|
1198
|
-
if (!(header.version < 3)) {
|
|
1199
|
-
_context1.n = 1;
|
|
1200
|
-
break;
|
|
1201
|
-
}
|
|
1202
|
-
return _context1.a(2, info);
|
|
1203
|
-
case 1:
|
|
1204
|
-
view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
|
|
1205
|
-
pixels = Math.pow(2, clustering[7]) / (clustering[6] === 1 ? 255 : 1);
|
|
1206
|
-
total = view.getUint32(8, true);
|
|
1207
|
-
info.totalWeight = total * pixels;
|
|
1208
|
-
info.mse = new Float64Array(colors);
|
|
1209
|
-
info.explained = new Float64Array(colors);
|
|
1210
|
-
// The error of the leaf clusters: what `precision` below 8 discarded by grouping colours (0 before it was recorded).
|
|
1211
|
-
remaining = header.headerLength >= 17 ? view.getFloat32(13, true) : 0;
|
|
1212
|
-
if (colors > 0) {
|
|
1213
|
-
info.mse[colors - 1] = remaining / total / 3;
|
|
1214
|
-
}
|
|
1215
|
-
for (i = header.merges - 1; i >= 0; i--) {
|
|
1216
|
-
remaining += view.getFloat32(header.headerLength + 3 + i * header.recordLength + 17, true);
|
|
1217
|
-
info.mse[i] = remaining / total / 3;
|
|
1218
|
-
}
|
|
1219
|
-
// Errors are sums of squares, so a cost that is negative or not a number can only come from damaged bytes (a clustering
|
|
1220
|
-
// from 3.0.0-beta.1 has no checksum to catch them first).
|
|
1221
|
-
_i3 = 0;
|
|
1222
|
-
case 2:
|
|
1223
|
-
if (!(_i3 < colors)) {
|
|
1224
|
-
_context1.n = 4;
|
|
1225
|
-
break;
|
|
1226
|
-
}
|
|
1227
|
-
if (!(!(info.mse[_i3] >= 0) || !Number.isFinite(info.mse[_i3]))) {
|
|
1228
|
-
_context1.n = 3;
|
|
1229
|
-
break;
|
|
1230
|
-
}
|
|
1231
|
-
throw fail('invalid-clustering', "Invalid clustering: its recorded errors are not valid numbers, so it is damaged. Cluster the image again.", 'clustering');
|
|
1232
|
-
case 3:
|
|
1233
|
-
_i3++;
|
|
1234
|
-
_context1.n = 2;
|
|
1235
|
-
break;
|
|
1236
|
-
case 4:
|
|
1237
|
-
// The share of the image's variance each palette size keeps; 1 throughout for an image of one colour.
|
|
1238
|
-
for (_i4 = 0; _i4 < colors; _i4++) {
|
|
1239
|
-
info.explained[_i4] = info.mse[0] > 0 ? Math.max(0, Math.min(1, 1 - info.mse[_i4] / info.mse[0])) : 1;
|
|
1240
|
-
}
|
|
1241
|
-
return _context1.a(2, info);
|
|
1242
|
-
}
|
|
1243
|
-
}, _callee1);
|
|
1244
|
-
}));
|
|
1245
|
-
return function getClusteringInfo(_x18) {
|
|
1246
|
-
return _ref10.apply(this, arguments);
|
|
1247
|
-
};
|
|
1248
|
-
}();
|
|
1249
|
-
export var quantize = /*#__PURE__*/function () {
|
|
1250
|
-
var _ref11 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10(image, k, options) {
|
|
1251
|
-
var wrap, o, wasm, report, clustering, mapped, _t1;
|
|
1252
|
-
return _regenerator().w(function (_context10) {
|
|
1253
|
-
while (1) switch (_context10.n) {
|
|
1254
|
-
case 0:
|
|
1255
|
-
wrap = getWrapper(image);
|
|
1256
|
-
image = load(image);
|
|
1257
|
-
k = check(k);
|
|
1258
|
-
o = parseOptions(options, quantizeOptions, image);
|
|
1259
|
-
_t1 = Module;
|
|
1260
|
-
if (_t1) {
|
|
1261
|
-
_context10.n = 2;
|
|
1262
|
-
break;
|
|
1263
|
-
}
|
|
1264
|
-
_context10.n = 1;
|
|
1265
|
-
return acquire();
|
|
1266
|
-
case 1:
|
|
1267
|
-
_t1 = _context10.v;
|
|
1268
|
-
case 2:
|
|
1269
|
-
wasm = _t1;
|
|
1270
|
-
if (!isControlled(o)) {
|
|
1271
|
-
_context10.n = 4;
|
|
1272
|
-
break;
|
|
1273
|
-
}
|
|
1274
|
-
report = reporter(o);
|
|
1275
|
-
_context10.n = 3;
|
|
1276
|
-
return clusterInSlices(wasm, image, o, report, 0.9);
|
|
1277
|
-
case 3:
|
|
1278
|
-
clustering = _context10.v;
|
|
1279
|
-
checkAborted(o.signal);
|
|
1280
|
-
mapped = wrap(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
|
|
1281
|
-
return wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width);
|
|
1282
|
-
}));
|
|
1283
|
-
report(1);
|
|
1284
|
-
return _context10.a(2, mapped);
|
|
1285
|
-
case 4:
|
|
1286
|
-
return _context10.a(2, wrap(call(wasm, [image.data], function (imagePointer) {
|
|
1287
|
-
return wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent);
|
|
1288
|
-
})));
|
|
1289
|
-
}
|
|
1290
|
-
}, _callee10);
|
|
1291
|
-
}));
|
|
1292
|
-
return function quantize(_x19, _x20, _x21) {
|
|
1293
|
-
return _ref11.apply(this, arguments);
|
|
1294
|
-
};
|
|
1295
|
-
}();
|
|
1296
|
-
export var quantizeFromClustering = /*#__PURE__*/function () {
|
|
1297
|
-
var _ref12 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee11(image, clustering, k, options) {
|
|
1298
|
-
var wrap, o, wasm, colorSpace, result, _t10;
|
|
1299
|
-
return _regenerator().w(function (_context11) {
|
|
1300
|
-
while (1) switch (_context11.n) {
|
|
1301
|
-
case 0:
|
|
1302
|
-
wrap = getWrapper(image);
|
|
1303
|
-
image = load(image);
|
|
1304
|
-
readHeader(clustering);
|
|
1305
|
-
k = check(k);
|
|
1306
|
-
o = parseOptions(options, mapOptions, image);
|
|
1307
|
-
clustering = held(clustering);
|
|
1308
|
-
_t10 = Module;
|
|
1309
|
-
if (_t10) {
|
|
1310
|
-
_context11.n = 2;
|
|
1311
|
-
break;
|
|
1312
|
-
}
|
|
1313
|
-
_context11.n = 1;
|
|
1314
|
-
return acquire();
|
|
1315
|
-
case 1:
|
|
1316
|
-
_t10 = _context11.v;
|
|
1317
|
-
case 2:
|
|
1318
|
-
wasm = _t10;
|
|
1319
|
-
checkAborted(o.signal);
|
|
1320
|
-
colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
1321
|
-
result = wrap(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
|
|
1322
|
-
return wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width);
|
|
1323
|
-
}));
|
|
1324
|
-
return _context11.a(2, result);
|
|
1325
|
-
}
|
|
1326
|
-
}, _callee11);
|
|
1327
|
-
}));
|
|
1328
|
-
return function quantizeFromClustering(_x22, _x23, _x24, _x25) {
|
|
1329
|
-
return _ref12.apply(this, arguments);
|
|
1330
|
-
};
|
|
1331
|
-
}();
|
|
1332
|
-
export var quantizeWithPalette = /*#__PURE__*/function () {
|
|
1333
|
-
var _ref13 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee12(image, palette, options) {
|
|
1334
|
-
var wrap, o, space, wasm, result, _t11;
|
|
1335
|
-
return _regenerator().w(function (_context12) {
|
|
1336
|
-
while (1) switch (_context12.n) {
|
|
1337
|
-
case 0:
|
|
1338
|
-
wrap = getWrapper(image);
|
|
1339
|
-
image = load(image);
|
|
1340
|
-
checkPalette(palette);
|
|
1341
|
-
o = parseOptions(options, mapOptions, image);
|
|
1342
|
-
checkNotEmpty(palette, image, 1);
|
|
1343
|
-
space = matchingSpace(o, palette);
|
|
1344
|
-
palette = held(palette);
|
|
1345
|
-
_t11 = Module;
|
|
1346
|
-
if (_t11) {
|
|
1347
|
-
_context12.n = 2;
|
|
1348
|
-
break;
|
|
1349
|
-
}
|
|
1350
|
-
_context12.n = 1;
|
|
1351
|
-
return acquire();
|
|
1352
|
-
case 1:
|
|
1353
|
-
_t11 = _context12.v;
|
|
1354
|
-
case 2:
|
|
1355
|
-
wasm = _t11;
|
|
1356
|
-
checkAborted(o.signal);
|
|
1357
|
-
result = wrap(call(wasm, [image.data, palette], function (imagePointer, palettePointer) {
|
|
1358
|
-
return wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.width);
|
|
1359
|
-
}));
|
|
1360
|
-
return _context12.a(2, result);
|
|
1361
|
-
}
|
|
1362
|
-
}, _callee12);
|
|
1363
|
-
}));
|
|
1364
|
-
return function quantizeWithPalette(_x26, _x27, _x28) {
|
|
1365
|
-
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
|
|
1366
871
|
};
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
return _ref16.apply(this, arguments);
|
|
1487
|
-
};
|
|
1488
|
-
}();
|
|
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
|
+
};
|