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