agglomerative-clustering 1.1.3 → 2.0.0-beta.1

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/dist/index.cjs CHANGED
@@ -6,6 +6,9 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.quantizeWithPalette = exports.quantizeWithClustering = exports.quantize = exports.init = exports.getPaletteFromClustering = exports.getPalette = exports.getClustering = void 0;
7
7
  var _clustering = _interopRequireDefault(require("./clustering.js"));
8
8
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
9
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
10
+ 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; } }
11
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
9
12
  function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
10
13
  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 }; })(); }
11
14
  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); }
@@ -15,6 +18,14 @@ var codes = {
15
18
  'rgba': 0,
16
19
  'rgb': 1
17
20
  };
21
+ var colorSpaces = {
22
+ 'rgb': 0,
23
+ 'oklab': 1
24
+ };
25
+ var alphaModes = {
26
+ 'ignore': 0,
27
+ 'weight': 1
28
+ };
18
29
  var Module = null;
19
30
  var init = exports.init = /*#__PURE__*/function () {
20
31
  var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
@@ -54,7 +65,8 @@ var load = function load(image) {
54
65
  if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
55
66
  return {
56
67
  data: new Uint8Array(image.data.buffer),
57
- format: 'rgba'
68
+ format: 'rgba',
69
+ width: image.width
58
70
  };
59
71
  }
60
72
  if (_typeof(image) !== 'object' || !image || !image.data || !image.format) {
@@ -68,7 +80,8 @@ var load = function load(image) {
68
80
  }
69
81
  return {
70
82
  data: image.data instanceof Uint8ClampedArray ? new Uint8Array(image.data.buffer) : image.data,
71
- format: image.format
83
+ format: image.format,
84
+ width: image.width
72
85
  };
73
86
  };
74
87
  var getWrapper = function getWrapper(image) {
@@ -80,12 +93,21 @@ var getWrapper = function getWrapper(image) {
80
93
  };
81
94
  }
82
95
  if (!(image instanceof Uint8Array) && _typeof(image) === 'object' && image && image.data && image.format) {
83
- var format = image.format;
96
+ var format = image.format,
97
+ _width = image.width,
98
+ _height = image.height;
84
99
  return function (output) {
85
- return {
100
+ var result = {
86
101
  data: output,
87
102
  format: format
88
103
  };
104
+ if (_width !== undefined) {
105
+ result.width = _width;
106
+ }
107
+ if (_height !== undefined) {
108
+ result.height = _height;
109
+ }
110
+ return result;
89
111
  };
90
112
  }
91
113
  return function (output) {
@@ -97,9 +119,117 @@ var check = function check(k) {
97
119
  throw new Error("Invalid k: must be a strictly positive integer.");
98
120
  }
99
121
  };
122
+
123
+ // Validates `options` against the keys a function accepts and fills in defaults:
124
+ // colorSpace: 'rgb' (default) or 'oklab', the space colours are clustered and matched in; when mapping with a
125
+ // clustering, the default is the space the clustering was made in (code -1)
126
+ // alpha: 'weight' (default) counts RGBA pixels in proportion to their opacity; 'ignore' counts every pixel
127
+ // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
128
+ // dither: false (default), true, or a strength in [0, 1]; error diffusion when mapping pixels
129
+ // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
130
+ var parseOptions = function parseOptions(options, allowed, image) {
131
+ if (options === undefined) {
132
+ options = {};
133
+ }
134
+ if (options === null || _typeof(options) !== 'object' || Array.isArray(options)) {
135
+ throw new Error("Invalid options: expected an object.");
136
+ }
137
+ for (var _i = 0, _Object$keys = Object.keys(options); _i < _Object$keys.length; _i++) {
138
+ var key = _Object$keys[_i];
139
+ if (!allowed.includes(key)) {
140
+ throw new Error("Invalid option '".concat(key, "': expected one of ").concat(allowed.join(', '), "."));
141
+ }
142
+ }
143
+ var colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
144
+ if (!Object.keys(colorSpaces).includes(colorSpace)) {
145
+ throw new Error("Invalid colorSpace: must be 'rgb' or 'oklab'.");
146
+ }
147
+ var alpha = options.alpha === undefined ? 'weight' : options.alpha;
148
+ if (!Object.keys(alphaModes).includes(alpha)) {
149
+ throw new Error("Invalid alpha: must be 'weight' or 'ignore'.");
150
+ }
151
+ var precision = options.precision === undefined ? 8 : options.precision;
152
+ if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
153
+ throw new Error("Invalid precision: must be an integer from 1 to 8.");
154
+ }
155
+ var dither = options.dither === undefined || options.dither === false ? 0 : options.dither === true ? 1 : options.dither;
156
+ if (typeof dither !== 'number' || !Number.isFinite(dither) || dither < 0 || dither > 1) {
157
+ throw new Error("Invalid dither: must be a boolean or a number from 0 to 1.");
158
+ }
159
+ var width = options.width !== undefined ? options.width : image ? image.width : undefined;
160
+ if (dither > 0) {
161
+ var channels = image.format === 'rgb' ? 3 : 4;
162
+ if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
163
+ throw new Error("Invalid width: dithering needs the image width, as `options.width` or the image's `width`.");
164
+ }
165
+ if (image.data.length / channels % width !== 0) {
166
+ throw new Error("Invalid width: the image's pixel count is not a multiple of it.");
167
+ }
168
+ }
169
+ return {
170
+ colorSpace: colorSpaces[colorSpace],
171
+ colorSpaceGiven: options.colorSpace !== undefined,
172
+ alpha: alphaModes[alpha],
173
+ precision: precision,
174
+ dither: dither,
175
+ width: dither > 0 ? width : 0
176
+ };
177
+ };
178
+ var clusterOptions = ['colorSpace', 'precision', 'alpha'];
179
+ var quantizeOptions = ['colorSpace', 'precision', 'alpha', 'dither', 'width'];
180
+ var mapOptions = ['colorSpace', 'dither', 'width'];
181
+
182
+ // Clusterings are 0 or 3 bytes more than a multiple of 9 (1.x, no header), or 4 or 7 more with the 2.x header.
183
+ var checkClustering = function checkClustering(clustering) {
184
+ if (!(clustering instanceof Uint8Array)) {
185
+ throw new Error("Invalid clustering: must be a Uint8Array from getClustering.");
186
+ }
187
+ var rest = clustering.length % 9;
188
+ var legacy = clustering.length === 0 || rest === 3;
189
+ var current = (clustering.length === 4 || rest === 7) && clustering[0] === 0xAC && clustering[1] === 2 && clustering[2] <= 1;
190
+ if (!legacy && !current) {
191
+ throw new Error("Invalid clustering: not a clustering from getClustering.");
192
+ }
193
+ };
194
+
195
+ // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
196
+ // freeing everything afterwards.
197
+ var call = function call(buffers, fn) {
198
+ var pointers = [];
199
+ var outputPointer = 0;
200
+ try {
201
+ var _iterator = _createForOfIteratorHelper(buffers),
202
+ _step;
203
+ try {
204
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
205
+ var buffer = _step.value;
206
+ var pointer = Module._malloc(buffer.length);
207
+ if (!pointer) {
208
+ throw new Error("Failed to allocate WASM memory.");
209
+ }
210
+ pointers.push(pointer);
211
+ Module.HEAPU8.set(buffer, pointer);
212
+ }
213
+ } catch (err) {
214
+ _iterator.e(err);
215
+ } finally {
216
+ _iterator.f();
217
+ }
218
+ outputPointer = fn.apply(void 0, pointers);
219
+ return unpack(outputPointer);
220
+ } finally {
221
+ for (var _i2 = 0, _pointers = pointers; _i2 < _pointers.length; _i2++) {
222
+ var _pointer = _pointers[_i2];
223
+ Module._free(_pointer);
224
+ }
225
+ if (outputPointer) {
226
+ Module._free(outputPointer);
227
+ }
228
+ }
229
+ };
100
230
  var getClustering = exports.getClustering = /*#__PURE__*/function () {
101
- var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(image) {
102
- var imagePointer, outputPointer;
231
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(image, options) {
232
+ var o;
103
233
  return _regenerator().w(function (_context2) {
104
234
  while (1) switch (_context2.n) {
105
235
  case 0:
@@ -107,35 +237,20 @@ var getClustering = exports.getClustering = /*#__PURE__*/function () {
107
237
  return init();
108
238
  case 1:
109
239
  image = load(image);
110
- imagePointer = Module._malloc(image.data.length);
111
- if (imagePointer) {
112
- _context2.n = 2;
113
- break;
114
- }
115
- throw new Error("Failed to allocate WASM memory.");
116
- case 2:
117
- outputPointer = 0;
118
- _context2.p = 3;
119
- Module.HEAPU8.set(image.data, imagePointer);
120
- outputPointer = Module._get_clustering(imagePointer, image.data.length, codes[image.format]);
121
- return _context2.a(2, unpack(outputPointer));
122
- case 4:
123
- _context2.p = 4;
124
- Module._free(imagePointer);
125
- if (outputPointer) Module._free(outputPointer);
126
- return _context2.f(4);
127
- case 5:
128
- return _context2.a(2);
240
+ o = parseOptions(options, clusterOptions, image);
241
+ return _context2.a(2, call([image.data], function (imagePointer) {
242
+ return Module._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha);
243
+ }));
129
244
  }
130
- }, _callee2, null, [[3,, 4, 5]]);
245
+ }, _callee2);
131
246
  }));
132
- return function getClustering(_x) {
247
+ return function getClustering(_x, _x2) {
133
248
  return _ref2.apply(this, arguments);
134
249
  };
135
250
  }();
136
251
  var getPalette = exports.getPalette = /*#__PURE__*/function () {
137
- var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(image, k) {
138
- var imagePointer, outputPointer;
252
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(image, k, options) {
253
+ var o;
139
254
  return _regenerator().w(function (_context3) {
140
255
  while (1) switch (_context3.n) {
141
256
  case 0:
@@ -144,71 +259,40 @@ var getPalette = exports.getPalette = /*#__PURE__*/function () {
144
259
  case 1:
145
260
  image = load(image);
146
261
  check(k);
147
- imagePointer = Module._malloc(image.data.length);
148
- if (imagePointer) {
149
- _context3.n = 2;
150
- break;
151
- }
152
- throw new Error("Failed to allocate WASM memory.");
153
- case 2:
154
- outputPointer = 0;
155
- _context3.p = 3;
156
- Module.HEAPU8.set(image.data, imagePointer);
157
- outputPointer = Module._get_palette(imagePointer, image.data.length, codes[image.format], k);
158
- return _context3.a(2, unpack(outputPointer));
159
- case 4:
160
- _context3.p = 4;
161
- Module._free(imagePointer);
162
- if (outputPointer) Module._free(outputPointer);
163
- return _context3.f(4);
164
- case 5:
165
- return _context3.a(2);
262
+ o = parseOptions(options, clusterOptions, image);
263
+ return _context3.a(2, call([image.data], function (imagePointer) {
264
+ return Module._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha);
265
+ }));
166
266
  }
167
- }, _callee3, null, [[3,, 4, 5]]);
267
+ }, _callee3);
168
268
  }));
169
- return function getPalette(_x2, _x3) {
269
+ return function getPalette(_x3, _x4, _x5) {
170
270
  return _ref3.apply(this, arguments);
171
271
  };
172
272
  }();
173
273
  var getPaletteFromClustering = exports.getPaletteFromClustering = /*#__PURE__*/function () {
174
274
  var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(clustering, k) {
175
- var clusteringPointer, outputPointer;
176
275
  return _regenerator().w(function (_context4) {
177
276
  while (1) switch (_context4.n) {
178
277
  case 0:
179
278
  _context4.n = 1;
180
279
  return init();
181
280
  case 1:
281
+ checkClustering(clustering);
182
282
  check(k);
183
- clusteringPointer = Module._malloc(clustering.length);
184
- if (clusteringPointer) {
185
- _context4.n = 2;
186
- break;
187
- }
188
- throw new Error("Failed to allocate WASM memory.");
189
- case 2:
190
- outputPointer = 0;
191
- _context4.p = 3;
192
- Module.HEAPU8.set(clustering, clusteringPointer);
193
- outputPointer = Module._get_palette_from_clustering(clusteringPointer, clustering.length, k);
194
- return _context4.a(2, unpack(outputPointer));
195
- case 4:
196
- _context4.p = 4;
197
- Module._free(clusteringPointer);
198
- if (outputPointer) Module._free(outputPointer);
199
- return _context4.f(4);
200
- case 5:
201
- return _context4.a(2);
283
+ return _context4.a(2, call([clustering], function (clusteringPointer) {
284
+ return Module._get_palette_from_clustering(clusteringPointer, clustering.length, k);
285
+ }));
202
286
  }
203
- }, _callee4, null, [[3,, 4, 5]]);
287
+ }, _callee4);
204
288
  }));
205
- return function getPaletteFromClustering(_x4, _x5) {
289
+ return function getPaletteFromClustering(_x6, _x7) {
206
290
  return _ref4.apply(this, arguments);
207
291
  };
208
292
  }();
209
293
  var quantize = exports.quantize = /*#__PURE__*/function () {
210
- var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(image, k) {
211
- var wrap, imagePointer, outputPointer;
294
+ var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(image, k, options) {
295
+ var wrap, o;
212
296
  return _regenerator().w(function (_context5) {
213
297
  while (1) switch (_context5.n) {
214
298
  case 0:
@@ -218,35 +302,20 @@ var quantize = exports.quantize = /*#__PURE__*/function () {
218
302
  wrap = getWrapper(image);
219
303
  image = load(image);
220
304
  check(k);
221
- imagePointer = Module._malloc(image.data.length);
222
- if (imagePointer) {
223
- _context5.n = 2;
224
- break;
225
- }
226
- throw new Error("Failed to allocate WASM memory.");
227
- case 2:
228
- outputPointer = 0;
229
- _context5.p = 3;
230
- Module.HEAPU8.set(image.data, imagePointer);
231
- outputPointer = Module._quantize(imagePointer, image.data.length, codes[image.format], k);
232
- return _context5.a(2, wrap(unpack(outputPointer)));
233
- case 4:
234
- _context5.p = 4;
235
- Module._free(imagePointer);
236
- if (outputPointer) Module._free(outputPointer);
237
- return _context5.f(4);
238
- case 5:
239
- return _context5.a(2);
305
+ o = parseOptions(options, quantizeOptions, image);
306
+ return _context5.a(2, wrap(call([image.data], function (imagePointer) {
307
+ return Module._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width);
308
+ })));
240
309
  }
241
- }, _callee5, null, [[3,, 4, 5]]);
310
+ }, _callee5);
242
311
  }));
243
- return function quantize(_x6, _x7) {
312
+ return function quantize(_x8, _x9, _x0) {
244
313
  return _ref5.apply(this, arguments);
245
314
  };
246
315
  }();
247
316
  var quantizeWithClustering = exports.quantizeWithClustering = /*#__PURE__*/function () {
248
- var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, clustering, k) {
249
- var wrap, imagePointer, clusteringPointer, outputPointer;
317
+ var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, clustering, k, options) {
318
+ var wrap, o, colorSpace;
250
319
  return _regenerator().w(function (_context6) {
251
320
  while (1) switch (_context6.n) {
252
321
  case 0:
@@ -255,46 +324,23 @@ var quantizeWithClustering = exports.quantizeWithClustering = /*#__PURE__*/funct
255
324
  case 1:
256
325
  wrap = getWrapper(image);
257
326
  image = load(image);
327
+ checkClustering(clustering);
258
328
  check(k);
259
- imagePointer = Module._malloc(image.data.length);
260
- if (imagePointer) {
261
- _context6.n = 2;
262
- break;
263
- }
264
- throw new Error("Failed to allocate WASM memory.");
265
- case 2:
266
- clusteringPointer = Module._malloc(clustering.length);
267
- if (clusteringPointer) {
268
- _context6.n = 3;
269
- break;
270
- }
271
- Module._free(imagePointer);
272
- throw new Error("Failed to allocate WASM memory.");
273
- case 3:
274
- outputPointer = 0;
275
- _context6.p = 4;
276
- Module.HEAPU8.set(image.data, imagePointer);
277
- Module.HEAPU8.set(clustering, clusteringPointer);
278
- outputPointer = Module._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k);
279
- return _context6.a(2, wrap(unpack(outputPointer)));
280
- case 5:
281
- _context6.p = 5;
282
- Module._free(imagePointer);
283
- Module._free(clusteringPointer);
284
- if (outputPointer) Module._free(outputPointer);
285
- return _context6.f(5);
286
- case 6:
287
- return _context6.a(2);
329
+ o = parseOptions(options, mapOptions, image);
330
+ colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
331
+ return _context6.a(2, wrap(call([image.data, clustering], function (imagePointer, clusteringPointer) {
332
+ return Module._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width);
333
+ })));
288
334
  }
289
- }, _callee6, null, [[4,, 5, 6]]);
335
+ }, _callee6);
290
336
  }));
291
- return function quantizeWithClustering(_x8, _x9, _x0) {
337
+ return function quantizeWithClustering(_x1, _x10, _x11, _x12) {
292
338
  return _ref6.apply(this, arguments);
293
339
  };
294
340
  }();
295
341
  var quantizeWithPalette = exports.quantizeWithPalette = /*#__PURE__*/function () {
296
- var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(image, palette) {
297
- var wrap, imagePointer, palettePointer, outputPointer;
342
+ var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(image, palette, options) {
343
+ var wrap, o;
298
344
  return _regenerator().w(function (_context7) {
299
345
  while (1) switch (_context7.n) {
300
346
  case 0:
@@ -303,39 +349,14 @@ var quantizeWithPalette = exports.quantizeWithPalette = /*#__PURE__*/function ()
303
349
  case 1:
304
350
  wrap = getWrapper(image);
305
351
  image = load(image);
306
- imagePointer = Module._malloc(image.data.length);
307
- if (imagePointer) {
308
- _context7.n = 2;
309
- break;
310
- }
311
- throw new Error("Failed to allocate WASM memory.");
312
- case 2:
313
- palettePointer = Module._malloc(palette.length);
314
- if (palettePointer) {
315
- _context7.n = 3;
316
- break;
317
- }
318
- Module._free(imagePointer);
319
- throw new Error("Failed to allocate WASM memory.");
320
- case 3:
321
- outputPointer = 0;
322
- _context7.p = 4;
323
- Module.HEAPU8.set(image.data, imagePointer);
324
- Module.HEAPU8.set(palette, palettePointer);
325
- outputPointer = Module._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length);
326
- return _context7.a(2, wrap(unpack(outputPointer)));
327
- case 5:
328
- _context7.p = 5;
329
- Module._free(imagePointer);
330
- Module._free(palettePointer);
331
- if (outputPointer) Module._free(outputPointer);
332
- return _context7.f(5);
333
- case 6:
334
- return _context7.a(2);
352
+ o = parseOptions(options, mapOptions, image);
353
+ return _context7.a(2, wrap(call([image.data, palette], function (imagePointer, palettePointer) {
354
+ return Module._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, o.colorSpace, o.dither, o.width);
355
+ })));
335
356
  }
336
- }, _callee7, null, [[4,, 5, 6]]);
357
+ }, _callee7);
337
358
  }));
338
- return function quantizeWithPalette(_x1, _x10) {
359
+ return function quantizeWithPalette(_x13, _x14, _x15) {
339
360
  return _ref7.apply(this, arguments);
340
361
  };
341
362
  }();
package/dist/index.d.ts CHANGED
@@ -3,26 +3,76 @@ export type ImageFormat = 'rgb' | 'rgba';
3
3
  export interface RawImage {
4
4
  data: Uint8Array | Uint8ClampedArray;
5
5
  format: ImageFormat;
6
+ /** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
7
+ width?: number;
8
+ /** Height in pixels. Optional; copied to `quantize*` results. */
9
+ height?: number;
6
10
  }
7
11
 
8
12
  export type ImageLike = Uint8Array | ImageData | RawImage;
9
13
 
14
+ /** The space colours are clustered and matched in. */
15
+ export type ColorSpace = 'rgb' | 'oklab';
16
+
17
+ /** How pixel opacity affects clustering. */
18
+ export type AlphaMode = 'weight' | 'ignore';
19
+
20
+ export interface ClusteringOptions {
21
+ /**
22
+ * `'rgb'` (default) minimises squared sRGB error, which is what MSE/PSNR measure.
23
+ * `'oklab'` clusters in OKLab, where distances track perceived colour difference.
24
+ */
25
+ colorSpace?: ColorSpace;
26
+ /**
27
+ * Bits per channel, 1-8 (default 8: every distinct colour is clustered exactly). Lower values group colours
28
+ * that share their top bits before clustering, at their mean colour, which bounds the time spent on images
29
+ * with very many distinct colours. 6 is a good choice for large photos.
30
+ */
31
+ precision?: number;
32
+ /**
33
+ * How RGBA pixels count. `'weight'` (default): in proportion to their opacity, so fully transparent pixels are
34
+ * ignored and semi-transparent ones count partially. `'ignore'`: every pixel counts fully, as in 1.x.
35
+ */
36
+ alpha?: AlphaMode;
37
+ }
38
+
39
+ export interface MappingOptions {
40
+ /**
41
+ * The space pixels are matched to their nearest palette colour in. Default `'rgb'`, except in
42
+ * `quantizeWithClustering`, where it defaults to the space the clustering was made in.
43
+ */
44
+ colorSpace?: ColorSpace;
45
+ /**
46
+ * Error-diffusion dithering (serpentine Floyd-Steinberg): `false` (default), `true`, or a strength from 0 to 1.
47
+ * Needs the image width: taken from `ImageData` or `RawImage.width`, or given as `width`.
48
+ */
49
+ dither?: boolean | number;
50
+ /** Image width in pixels, for dithering a `Uint8Array` or a `RawImage` without `width`. */
51
+ width?: number;
52
+ }
53
+
54
+ export type QuantizeOptions = ClusteringOptions & MappingOptions;
55
+
10
56
  export function init(): Promise<void>;
11
57
 
12
- export function getClustering(image: ImageLike): Promise<Uint8Array>;
58
+ export function getClustering(image: ImageLike, options?: ClusteringOptions): Promise<Uint8Array>;
13
59
 
14
- export function getPalette(image: ImageLike, k: number): Promise<Uint8Array>;
60
+ export function getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Uint8Array>;
15
61
 
62
+ /**
63
+ * Cuts a clustering to at most `k` colours, in split order: index 0 is the dominant colour, and the palette for
64
+ * `k + 1` is the palette for `k` with one entry refined and one colour appended.
65
+ */
16
66
  export function getPaletteFromClustering(clustering: Uint8Array, k: number): Promise<Uint8Array>;
17
67
 
18
- export function quantize(image: Uint8Array, k: number): Promise<Uint8Array>;
19
- export function quantize(image: ImageData, k: number): Promise<ImageData>;
20
- export function quantize(image: RawImage, k: number): Promise<RawImage>;
68
+ export function quantize(image: Uint8Array, k: number, options?: QuantizeOptions): Promise<Uint8Array>;
69
+ export function quantize(image: ImageData, k: number, options?: QuantizeOptions): Promise<ImageData>;
70
+ export function quantize(image: RawImage, k: number, options?: QuantizeOptions): Promise<RawImage>;
21
71
 
22
- export function quantizeWithClustering(image: Uint8Array, clustering: Uint8Array, k: number): Promise<Uint8Array>;
23
- export function quantizeWithClustering(image: ImageData, clustering: Uint8Array, k: number): Promise<ImageData>;
24
- export function quantizeWithClustering(image: RawImage, clustering: Uint8Array, k: number): Promise<RawImage>;
72
+ export function quantizeWithClustering(image: Uint8Array, clustering: Uint8Array, k: number, options?: MappingOptions): Promise<Uint8Array>;
73
+ export function quantizeWithClustering(image: ImageData, clustering: Uint8Array, k: number, options?: MappingOptions): Promise<ImageData>;
74
+ export function quantizeWithClustering(image: RawImage, clustering: Uint8Array, k: number, options?: MappingOptions): Promise<RawImage>;
25
75
 
26
- export function quantizeWithPalette(image: Uint8Array, palette: Uint8Array): Promise<Uint8Array>;
27
- export function quantizeWithPalette(image: ImageData, palette: Uint8Array): Promise<ImageData>;
28
- export function quantizeWithPalette(image: RawImage, palette: Uint8Array): Promise<RawImage>;
76
+ export function quantizeWithPalette(image: Uint8Array, palette: Uint8Array, options?: MappingOptions): Promise<Uint8Array>;
77
+ export function quantizeWithPalette(image: ImageData, palette: Uint8Array, options?: MappingOptions): Promise<ImageData>;
78
+ export function quantizeWithPalette(image: RawImage, palette: Uint8Array, options?: MappingOptions): Promise<RawImage>;