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