agglomerative-clustering 3.7.2 → 4.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/README.md +9 -8
- package/dist/choose.cjs +166 -0
- package/dist/choose.mjs +160 -0
- package/dist/clustering.cjs +1 -1
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +103 -64
- package/dist/index.d.cts +80 -19
- package/dist/index.d.ts +80 -19
- package/dist/index.mjs +102 -63
- package/dist/shared.cjs +129 -5
- package/dist/shared.mjs +123 -3
- package/dist/worker-thread.mjs +13 -2
- package/dist/worker.cjs +183 -64
- package/dist/worker.d.cts +51 -8
- package/dist/worker.d.ts +51 -8
- package/dist/worker.mjs +184 -65
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* How pixel bytes are laid out:
|
|
3
3
|
* - `'rgb'`: 3 bytes per pixel, red, green, blue.
|
|
4
|
-
* - `'rgba'`, `'bgra'`: 4 bytes, with
|
|
5
|
-
* Electron's `
|
|
4
|
+
* - `'rgba'`, `'bgra'`: 4 bytes, with alpha last, straight unless the image object says `premultiplied: true` (canvas
|
|
5
|
+
* surfaces, Electron's `toBitmap()`). BGRA is the order of Windows bitmaps and Electron's `nativeImage`.
|
|
6
6
|
* - `'rgbx'`, `'bgrx'`: 4 bytes whose last is padding, not alpha (Windows `BI_RGB` bitmaps, WebCodecs `'BGRX'`, ffmpeg
|
|
7
7
|
* `bgr0`): every pixel is opaque, and mapped output writes 255 there.
|
|
8
8
|
*
|
|
@@ -70,28 +70,61 @@ export const ditherSteps: readonly DitherSteps[];
|
|
|
70
70
|
export function isCodedError(value: unknown): value is CodedError;
|
|
71
71
|
|
|
72
72
|
/**
|
|
73
|
-
*
|
|
74
|
-
*
|
|
73
|
+
* RGBA or BGRA bytes. `premultiplied: true` says the colours are multiplied by alpha (canvas, Electron, WebGL).
|
|
74
|
+
* Internal: name it through `RawImage<'rgba'>` or `RawImage<'bgra'>`.
|
|
75
75
|
*/
|
|
76
|
-
|
|
76
|
+
interface RawImageWithAlpha<F extends 'rgba' | 'bgra' = 'rgba' | 'bgra'> {
|
|
77
77
|
data: Uint8Array | Uint8ClampedArray;
|
|
78
|
-
format:
|
|
78
|
+
format: F;
|
|
79
79
|
/** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
|
|
80
80
|
width?: number | undefined;
|
|
81
81
|
/** Height in pixels. Optional; copied to `quantize*` results. */
|
|
82
82
|
height?: number | undefined;
|
|
83
|
+
/**
|
|
84
|
+
* The colours are multiplied by alpha (what a canvas surface, Electron's `toBitmap()`, WebGL and Cairo hold). They are
|
|
85
|
+
* read as straight colours (divided by alpha), and `quantize*` gives the mapped colours back multiplied, copied as
|
|
86
|
+
* given: the result has the same `premultiplied` as the input. For a straight destination (`ImageData`, PNG encoders),
|
|
87
|
+
* use `quantizeToIndices` and write palette colours with the input's alpha; un-premultiplying the output loses colour. The guides' "Straight pixels from a premultiplied source" has the loop.
|
|
88
|
+
*/
|
|
89
|
+
premultiplied?: boolean | undefined;
|
|
83
90
|
}
|
|
84
91
|
|
|
92
|
+
/**
|
|
93
|
+
* Formats without alpha. `premultiplied: false` says nothing; `true` is rejected at run time (there is no alpha).
|
|
94
|
+
* Internal: name it through `RawImage<'rgb'>`, `RawImage<'rgbx'>` or `RawImage<'bgrx'>`.
|
|
95
|
+
*/
|
|
96
|
+
interface RawImageWithoutAlpha<F extends 'rgb' | 'rgbx' | 'bgrx' = 'rgb' | 'rgbx' | 'bgrx'> {
|
|
97
|
+
data: Uint8Array | Uint8ClampedArray;
|
|
98
|
+
format: F;
|
|
99
|
+
/** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
|
|
100
|
+
width?: number | undefined;
|
|
101
|
+
/** Height in pixels. Optional; copied to `quantize*` results. */
|
|
102
|
+
height?: number | undefined;
|
|
103
|
+
/** Accepted as `false` on any format and does nothing here; `true` is an `invalid-argument` error, since there is no alpha. */
|
|
104
|
+
premultiplied?: boolean | undefined;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
|
|
109
|
+
* `ImageData`. `RawImage<'bgra'>` is one format. Functions that return an image give back an object with the input's own
|
|
110
|
+
* keys (`format`, and `width`, `height` and `premultiplied` when given) and a new `data`.
|
|
111
|
+
*/
|
|
112
|
+
export type RawImage<F extends ImageFormat = ImageFormat> =
|
|
113
|
+
F extends 'rgba' | 'bgra' ? RawImageWithAlpha<F> : F extends 'rgb' | 'rgbx' | 'bgrx' ? RawImageWithoutAlpha<F> : never;
|
|
114
|
+
|
|
85
115
|
/**
|
|
86
116
|
* The platform's `ImageData` class where the global exists (the DOM lib, or typings for a canvas polyfill), and `never`
|
|
87
117
|
* where it doesn't, so these declarations compile with or without the DOM lib, in browser and Node-only projects.
|
|
88
118
|
*/
|
|
89
119
|
export type PlatformImageData = typeof globalThis extends { ImageData: { prototype: infer T } } ? T : never;
|
|
90
120
|
|
|
91
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* What a function that returns an image gives back for the input it was given: the same kind of thing. For an image
|
|
123
|
+
* object, one with the input's own keys and a new `data: Uint8Array`.
|
|
124
|
+
*/
|
|
92
125
|
export type ImageResult<I extends ImageLike> =
|
|
93
126
|
I extends Uint8Array ? Uint8Array
|
|
94
|
-
: I extends RawImage ?
|
|
127
|
+
: I extends RawImage ? Omit<I, 'data'> & { data: Uint8Array }
|
|
95
128
|
: I extends PlatformImageData ? PlatformImageData
|
|
96
129
|
: never;
|
|
97
130
|
|
|
@@ -147,16 +180,33 @@ export class Clustering extends Uint8Array {
|
|
|
147
180
|
constructor(buffer: ArrayBufferLike, byteOffset?: number, length?: number);
|
|
148
181
|
/** Only a type: what makes a `Clustering` different from a palette or other bytes to the compiler. */
|
|
149
182
|
readonly [clusteringBrand]: true;
|
|
150
|
-
/** The k-colour palette
|
|
183
|
+
/** The k-colour palette of this clustering. Takes no options. Runs on the calling thread, with the main entry. */
|
|
151
184
|
getPalette(this: Clustering, k: number): Promise<Palette>;
|
|
152
|
-
/** Palette, weights and shares
|
|
185
|
+
/** Palette, weights and shares of the k-colour cut. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
|
|
153
186
|
getSwatches(this: Clustering, k: number): Promise<Swatches>;
|
|
154
|
-
/** The error curve and totals
|
|
187
|
+
/** The error curve and totals of this clustering. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
|
|
155
188
|
getClusteringInfo(this: Clustering): Promise<ClusteringInfo>;
|
|
156
|
-
/** Maps `image` to
|
|
189
|
+
/** Maps `image` to this clustering's k-colour palette, returning the image's type. Runs on the calling thread, with the main entry. */
|
|
157
190
|
quantize<I extends ImageLike>(this: Clustering, image: I, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
|
|
158
|
-
/**
|
|
191
|
+
/** Maps `image` to this clustering's k-colour palette as palette indices. Runs on the calling thread, with the main entry. */
|
|
159
192
|
quantizeToIndices(this: Clustering, image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
193
|
+
/** Chooses the k entries of `palette` that best represent the clustered image: their positions and colours. Runs on the calling thread, with the main entry. */
|
|
194
|
+
chooseFrom(this: Clustering, palette: PaletteLike, k: number, options?: ChooseOptions): Promise<PaletteChoice>;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Options of `clustering.chooseFrom`. */
|
|
198
|
+
export interface ChooseOptions {
|
|
199
|
+
/** The space the search measures distance in: 'rgb' (default) or 'oklab'. It doesn't follow the clustering's space. */
|
|
200
|
+
colorSpace?: ColorSpace | undefined;
|
|
201
|
+
signal?: AbortSignal | undefined;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** What `clustering.chooseFrom` returns. */
|
|
205
|
+
export interface PaletteChoice {
|
|
206
|
+
/** Exactly k positions in the palette given, ascending: no ranking (count the mapped pixels for a legend). */
|
|
207
|
+
indices: number[];
|
|
208
|
+
/** The chosen colours, in the order of `indices`: map with it, and index s of the result is entry indices[s]. */
|
|
209
|
+
palette: Palette;
|
|
160
210
|
}
|
|
161
211
|
|
|
162
212
|
/** What is not a clustering: a `Clustering` is not accepted where a palette is. */
|
|
@@ -327,7 +377,8 @@ interface IndexedImageFields {
|
|
|
327
377
|
|
|
328
378
|
/**
|
|
329
379
|
* One palette index per pixel in `indices`: a `Uint8Array` up to 256 palette entries, a `Uint16Array` up to 65536, else a
|
|
330
|
-
* `Uint32Array`. `indexBits` says which (8, 16 or 32), and checking it narrows `indices` to that array type.
|
|
380
|
+
* `Uint32Array`. `indexBits` says which (8, 16 or 32), and checking it narrows `indices` to that array type. The palette
|
|
381
|
+
* is straight even for a premultiplied input: indexed output has no partial alpha, so there is nothing to premultiply.
|
|
331
382
|
*/
|
|
332
383
|
export type IndexedImage =
|
|
333
384
|
| (IndexedImageFields & { indexBits: 8; indices: Uint8Array })
|
|
@@ -375,7 +426,7 @@ export function getClustering(image: ImageLike, options?: ClusteringOptions): Pr
|
|
|
375
426
|
|
|
376
427
|
/**
|
|
377
428
|
* A palette of at most `k` colours for `image` (fewer if it has fewer distinct colours), as flat RGB bytes in split
|
|
378
|
-
* order (see `
|
|
429
|
+
* order (see `clustering.getPalette(k)`). It clusters the image each time: to try several sizes, call `buildClustering`
|
|
379
430
|
* once and cut it.
|
|
380
431
|
*
|
|
381
432
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
@@ -392,6 +443,8 @@ export function getPalette(image: ImageLike, k: number, options?: ClusteringOpti
|
|
|
392
443
|
*
|
|
393
444
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
394
445
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
446
|
+
*
|
|
447
|
+
* @deprecated Use `clustering.getPalette(k)`; off the main thread, `(await worker.load(clustering)).getPalette(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
395
448
|
*/
|
|
396
449
|
export function getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
|
|
397
450
|
|
|
@@ -400,7 +453,7 @@ export function getPaletteFromClustering(clustering: Clustering, k: number): Pro
|
|
|
400
453
|
* from one cut of one clustering, so they line up by construction: entry `i` of each describes the same colour.
|
|
401
454
|
*/
|
|
402
455
|
export interface Swatches {
|
|
403
|
-
/** The colours in split order, exactly what `
|
|
456
|
+
/** The colours in split order, exactly what `clustering.getPalette(k)` gives for the same `k`. */
|
|
404
457
|
palette: Palette;
|
|
405
458
|
/**
|
|
406
459
|
* Pixels per colour, counted as in clustering: by default fully transparent pixels count 0 and partly transparent ones
|
|
@@ -414,7 +467,7 @@ export interface Swatches {
|
|
|
414
467
|
|
|
415
468
|
/**
|
|
416
469
|
* The palette for `image` at `k` colours with each colour's weight and share: one call for swatches with percentages.
|
|
417
|
-
* It clusters the image each time; if you already have a clustering, use `
|
|
470
|
+
* It clusters the image each time; if you already have a clustering, use `clustering.getSwatches(k)`.
|
|
418
471
|
*
|
|
419
472
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
420
473
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
@@ -429,6 +482,8 @@ export function getSwatches(image: ImageLike, k: number, options?: ClusteringOpt
|
|
|
429
482
|
*
|
|
430
483
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
431
484
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
485
|
+
*
|
|
486
|
+
* @deprecated Use `clustering.getSwatches(k)`; off the main thread, `(await worker.load(clustering)).getSwatches(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
432
487
|
*/
|
|
433
488
|
export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
|
|
434
489
|
|
|
@@ -470,8 +525,10 @@ export interface ClusteringInfo {
|
|
|
470
525
|
|
|
471
526
|
/**
|
|
472
527
|
* Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
|
|
473
|
-
* clustering recorded no weights, so it is rejected with `unsupported-version` (as `
|
|
528
|
+
* clustering recorded no weights, so it is rejected with `unsupported-version` (as `clustering.getSwatches(k)` rejects it);
|
|
474
529
|
* the palette and mapping functions still read it.
|
|
530
|
+
*
|
|
531
|
+
* @deprecated Use `clustering.getClusteringInfo()`; off the main thread, `(await worker.load(clustering)).getClusteringInfo()` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
475
532
|
*/
|
|
476
533
|
export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
|
|
477
534
|
|
|
@@ -492,6 +549,8 @@ export function quantize<I extends ImageLike>(image: I, k: number, options?: Qua
|
|
|
492
549
|
*
|
|
493
550
|
* @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
|
|
494
551
|
* entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
|
|
552
|
+
*
|
|
553
|
+
* @deprecated Use `clustering.quantize(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantize(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
495
554
|
*/
|
|
496
555
|
export function quantizeFromClustering<I extends ImageLike>(image: I, clustering: Clustering, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
|
|
497
556
|
|
|
@@ -516,12 +575,14 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
|
|
|
516
575
|
export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
|
|
517
576
|
|
|
518
577
|
/**
|
|
519
|
-
* Like `quantizeFromClustering`, but returns palette indices. The palette is `
|
|
578
|
+
* Like `quantizeFromClustering`, but returns palette indices. The palette is `clustering.getPalette(k)`'s.
|
|
520
579
|
*
|
|
521
580
|
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|
|
522
581
|
* if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
|
|
523
582
|
* A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
|
|
524
583
|
* `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
|
|
584
|
+
*
|
|
585
|
+
* @deprecated Use `clustering.quantizeToIndices(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantizeToIndices(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
|
|
525
586
|
*/
|
|
526
587
|
export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
527
588
|
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import createWasmModule from './clustering.js';
|
|
2
|
-
import {
|
|
2
|
+
import { choose } from "./choose.mjs";
|
|
3
|
+
import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, setEngine, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge, sniffImageFormat, bareImageWarning, warnOnce, checkImageObject, checkSize, formatHint } from "./shared.mjs";
|
|
3
4
|
|
|
4
5
|
// The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
|
|
5
6
|
export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
|
|
@@ -20,27 +21,6 @@ const codes = {
|
|
|
20
21
|
'rgbx': 3,
|
|
21
22
|
'bgrx': 4
|
|
22
23
|
};
|
|
23
|
-
// A hint for a format name that isn't one: the right case, the name other libraries use for the same bytes, or the nearest
|
|
24
|
-
// supported layout.
|
|
25
|
-
const formatHint = format => {
|
|
26
|
-
if (typeof format !== 'string') {
|
|
27
|
-
return '';
|
|
28
|
-
}
|
|
29
|
-
const lower = format.toLowerCase();
|
|
30
|
-
if (lower !== format && imageFormats.includes(lower)) {
|
|
31
|
-
return ` Format names are lower case: '${lower}'.`;
|
|
32
|
-
}
|
|
33
|
-
if (lower === 'xrgb' || lower === 'rgb24') {
|
|
34
|
-
return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
|
|
35
|
-
}
|
|
36
|
-
if (lower === 'argb' || lower === 'argb32') {
|
|
37
|
-
return " Cairo and node-canvas ARGB32 is BGRA in memory on little-endian machines, and premultiplied: convert it to straight alpha and pass 'bgra' (see Input in the API docs).";
|
|
38
|
-
}
|
|
39
|
-
if (lower === 'bgr' || lower === 'bgr24') {
|
|
40
|
-
return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
|
|
41
|
-
}
|
|
42
|
-
return '';
|
|
43
|
-
};
|
|
44
24
|
const alphaModeCodes = {
|
|
45
25
|
'ignore': 0,
|
|
46
26
|
'weight': 1
|
|
@@ -425,20 +405,6 @@ const bytes = data => isUint8Array(data) ? data : new Uint8Array(data.buffer, da
|
|
|
425
405
|
// call returns; until then (the first call) a copy is kept for when it has loaded.
|
|
426
406
|
const held = data => Module ? data : data.slice();
|
|
427
407
|
|
|
428
|
-
// width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
|
|
429
|
-
// pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
|
|
430
|
-
const checkSize = (pixels, size, name, argument) => {
|
|
431
|
-
if (size === undefined) {
|
|
432
|
-
return;
|
|
433
|
-
}
|
|
434
|
-
if (!Number.isInteger(size) || size < 0) {
|
|
435
|
-
throw fail('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
|
|
436
|
-
}
|
|
437
|
-
if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
|
|
438
|
-
throw fail('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
|
|
439
|
-
}
|
|
440
|
-
};
|
|
441
|
-
|
|
442
408
|
// The bare-image warning (rgb-as-rgba, gray-as-rgba) for an image, decided before load() and given only once the call's own checks have passed,
|
|
443
409
|
// just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
|
|
444
410
|
const noWarning = () => {};
|
|
@@ -470,7 +436,8 @@ const load = image => {
|
|
|
470
436
|
}
|
|
471
437
|
return {
|
|
472
438
|
data: held(image),
|
|
473
|
-
format: 'rgba'
|
|
439
|
+
format: 'rgba',
|
|
440
|
+
premultiplied: false
|
|
474
441
|
};
|
|
475
442
|
}
|
|
476
443
|
if (isImageData(image)) {
|
|
@@ -481,7 +448,8 @@ const load = image => {
|
|
|
481
448
|
return {
|
|
482
449
|
data: held(bytes(image.data)),
|
|
483
450
|
format: 'rgba',
|
|
484
|
-
width: image.width
|
|
451
|
+
width: image.width,
|
|
452
|
+
premultiplied: false
|
|
485
453
|
};
|
|
486
454
|
}
|
|
487
455
|
if (ArrayBuffer.isView(image)) {
|
|
@@ -496,23 +464,12 @@ const load = image => {
|
|
|
496
464
|
if (isDetached(image.data)) {
|
|
497
465
|
throw detachedError('data');
|
|
498
466
|
}
|
|
499
|
-
|
|
500
|
-
throw fail('invalid-argument', `Invalid format: got ${describe(image.format)}; it must be ${formatNames}.${formatHint(image.format)}`, 'image');
|
|
501
|
-
}
|
|
502
|
-
const stride = channels(image.format);
|
|
503
|
-
if (image.data.length % stride !== 0) {
|
|
504
|
-
throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
|
|
505
|
-
}
|
|
506
|
-
const pixels = image.data.length / stride;
|
|
507
|
-
checkSize(pixels, image.width, 'image width', 'image');
|
|
508
|
-
checkSize(pixels, image.height, 'image height', 'image');
|
|
509
|
-
if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
|
|
510
|
-
throw fail('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
|
|
511
|
-
}
|
|
467
|
+
const premultiplied = checkImageObject(image);
|
|
512
468
|
return {
|
|
513
469
|
data: held(bytes(image.data)),
|
|
514
470
|
format: image.format,
|
|
515
|
-
width: image.width
|
|
471
|
+
width: image.width,
|
|
472
|
+
premultiplied
|
|
516
473
|
};
|
|
517
474
|
};
|
|
518
475
|
const getWrapper = image => {
|
|
@@ -524,7 +481,8 @@ const getWrapper = image => {
|
|
|
524
481
|
const {
|
|
525
482
|
format,
|
|
526
483
|
width,
|
|
527
|
-
height
|
|
484
|
+
height,
|
|
485
|
+
premultiplied
|
|
528
486
|
} = image;
|
|
529
487
|
return output => {
|
|
530
488
|
const result = {
|
|
@@ -537,6 +495,9 @@ const getWrapper = image => {
|
|
|
537
495
|
if (height !== undefined) {
|
|
538
496
|
result.height = height;
|
|
539
497
|
}
|
|
498
|
+
if (premultiplied !== undefined) {
|
|
499
|
+
result.premultiplied = premultiplied;
|
|
500
|
+
}
|
|
540
501
|
return result;
|
|
541
502
|
};
|
|
542
503
|
}
|
|
@@ -729,7 +690,9 @@ const allocate = (wasm, length) => {
|
|
|
729
690
|
|
|
730
691
|
// Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
|
|
731
692
|
// freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
|
|
732
|
-
|
|
693
|
+
// `premultiplied` (the loaded image's flag) un-premultiplies the first buffer after it is copied in; `mapped` also premultiplies
|
|
694
|
+
// the output payload (a mapped image, not indexed output) before it is unpacked.
|
|
695
|
+
const call = (wasm, buffers, fn, precision, premultiplied, mapped) => {
|
|
733
696
|
const pointers = [];
|
|
734
697
|
let outputPointer = 0;
|
|
735
698
|
let aborted = false;
|
|
@@ -739,12 +702,18 @@ const call = (wasm, buffers, fn, precision) => {
|
|
|
739
702
|
pointers.push(pointer);
|
|
740
703
|
wasm.HEAPU8.set(buffer, pointer);
|
|
741
704
|
}
|
|
705
|
+
if (premultiplied) {
|
|
706
|
+
wasm._unpremultiply(pointers[0], 0, buffers[0].length >> 2);
|
|
707
|
+
}
|
|
742
708
|
outputPointer = fn(...pointers);
|
|
743
709
|
// Only the functions that read a clustering return nothing: when its records don't fit together (see
|
|
744
710
|
// _get_palette_from_clustering), which a clustering whose checksum matches never does.
|
|
745
711
|
if (!outputPointer) {
|
|
746
712
|
throw fail('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
|
|
747
713
|
}
|
|
714
|
+
if (premultiplied && mapped) {
|
|
715
|
+
wasm._premultiply(outputPointer + 4, 0, buffers[0].length >> 2);
|
|
716
|
+
}
|
|
748
717
|
return unpack(wasm, outputPointer);
|
|
749
718
|
} catch (error) {
|
|
750
719
|
if (!isAbort(error)) {
|
|
@@ -815,6 +784,21 @@ const reporter = o => {
|
|
|
815
784
|
}
|
|
816
785
|
};
|
|
817
786
|
};
|
|
787
|
+
|
|
788
|
+
// The conversion passes in slices of this many pixels, so a long one gives the signal and the event loop a turn like the rest.
|
|
789
|
+
const convertSlice = 65536;
|
|
790
|
+
const convertInSlices = async (convert, pointer, pixels, o) => {
|
|
791
|
+
let last = performance.now();
|
|
792
|
+
for (let start = 0; start < pixels; start += convertSlice) {
|
|
793
|
+
checkAborted(o.signal);
|
|
794
|
+
convert(pointer, start, Math.min(pixels, start + convertSlice));
|
|
795
|
+
// Yield only once a slice's worth of time has gone, so a short pass doesn't pay a turn of the event loop per chunk.
|
|
796
|
+
if (start + convertSlice < pixels && performance.now() - last >= sliceMs) {
|
|
797
|
+
await yieldNow();
|
|
798
|
+
last = performance.now();
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
};
|
|
818
802
|
const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
|
|
819
803
|
|
|
820
804
|
// The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
|
|
@@ -839,6 +823,9 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
|
839
823
|
let aborted = false;
|
|
840
824
|
try {
|
|
841
825
|
wasm.HEAPU8.set(image.data, imagePointer);
|
|
826
|
+
if (image.premultiplied) {
|
|
827
|
+
await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
|
|
828
|
+
}
|
|
842
829
|
job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
|
|
843
830
|
report(0);
|
|
844
831
|
while (true) {
|
|
@@ -889,6 +876,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
|
|
|
889
876
|
sourcePointer = allocate(wasm, bytes.length);
|
|
890
877
|
wasm.HEAPU8.set(image.data, imagePointer);
|
|
891
878
|
wasm.HEAPU8.set(bytes, sourcePointer);
|
|
879
|
+
if (image.premultiplied) {
|
|
880
|
+
await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
|
|
881
|
+
}
|
|
892
882
|
const palette = source.palette ? sourcePointer : 0,
|
|
893
883
|
clustering = source.clustering ? sourcePointer : 0;
|
|
894
884
|
job = wasm._mapping_job_start(imagePointer, image.data.length, codes[image.format], palette, source.palette ? bytes.length : 0, clustering, source.clustering ? bytes.length : 0, source.k || 0, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, indices ? 1 : 0, cutoff);
|
|
@@ -910,6 +900,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
|
|
|
910
900
|
}
|
|
911
901
|
const pointer = wasm._mapping_job_result(job);
|
|
912
902
|
try {
|
|
903
|
+
if (image.premultiplied && !indices) {
|
|
904
|
+
await convertInSlices(wasm._premultiply, pointer + 4, image.data.length >> 2, o);
|
|
905
|
+
}
|
|
913
906
|
return unpack(wasm, pointer);
|
|
914
907
|
} finally {
|
|
915
908
|
wasm._free(pointer);
|
|
@@ -962,7 +955,7 @@ export const buildClustering = async (image, options) => {
|
|
|
962
955
|
report(1);
|
|
963
956
|
return markClustering(clustering);
|
|
964
957
|
}
|
|
965
|
-
return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision));
|
|
958
|
+
return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision, image.premultiplied));
|
|
966
959
|
};
|
|
967
960
|
/** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
|
|
968
961
|
export const getClustering = buildClustering;
|
|
@@ -981,7 +974,7 @@ export const buildPalette = async (image, k, options) => {
|
|
|
981
974
|
report(1);
|
|
982
975
|
return markPalette(palette, colorSpaceName(o.colorSpace));
|
|
983
976
|
}
|
|
984
|
-
return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), colorSpaceName(o.colorSpace));
|
|
977
|
+
return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision, image.premultiplied), colorSpaceName(o.colorSpace));
|
|
985
978
|
};
|
|
986
979
|
/** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
|
|
987
980
|
export const getPalette = buildPalette;
|
|
@@ -1120,7 +1113,7 @@ export const quantize = async (image, k, options) => {
|
|
|
1120
1113
|
report(1);
|
|
1121
1114
|
return mapped;
|
|
1122
1115
|
}
|
|
1123
|
-
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.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision));
|
|
1116
|
+
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.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision, image.premultiplied, true));
|
|
1124
1117
|
};
|
|
1125
1118
|
export const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
1126
1119
|
const warn = warningFor(image);
|
|
@@ -1143,7 +1136,7 @@ export const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
|
1143
1136
|
report(1);
|
|
1144
1137
|
return mapped;
|
|
1145
1138
|
}
|
|
1146
|
-
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.ditherMethod, o.ditherSteps, o.width)));
|
|
1139
|
+
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.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
|
|
1147
1140
|
return result;
|
|
1148
1141
|
};
|
|
1149
1142
|
export const quantizeWithPalette = async (image, palette, options) => {
|
|
@@ -1166,7 +1159,7 @@ export const quantizeWithPalette = async (image, palette, options) => {
|
|
|
1166
1159
|
report(1);
|
|
1167
1160
|
return mapped;
|
|
1168
1161
|
}
|
|
1169
|
-
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.ditherMethod, o.ditherSteps, o.width)));
|
|
1162
|
+
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.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
|
|
1170
1163
|
return result;
|
|
1171
1164
|
};
|
|
1172
1165
|
export const quantizeToIndices = async (image, k, options) => {
|
|
@@ -1188,7 +1181,7 @@ export const quantizeToIndices = async (image, k, options) => {
|
|
|
1188
1181
|
report(1);
|
|
1189
1182
|
return indexed;
|
|
1190
1183
|
}
|
|
1191
|
-
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.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision), original, colorSpaceName(o.colorSpace));
|
|
1184
|
+
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.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision, image.premultiplied), original, colorSpaceName(o.colorSpace));
|
|
1192
1185
|
};
|
|
1193
1186
|
export const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
|
|
1194
1187
|
const warn = warningFor(image);
|
|
@@ -1214,7 +1207,7 @@ export const quantizeToIndicesFromClustering = async (image, clustering, k, opti
|
|
|
1214
1207
|
report(1);
|
|
1215
1208
|
return indexed;
|
|
1216
1209
|
}
|
|
1217
|
-
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.ditherMethod, o.ditherSteps, o.width, cutoff)), original, colorSpaceName(header.colorSpace));
|
|
1210
|
+
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.ditherMethod, o.ditherSteps, o.width, cutoff), undefined, image.premultiplied), original, colorSpaceName(header.colorSpace));
|
|
1218
1211
|
return result;
|
|
1219
1212
|
};
|
|
1220
1213
|
export const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
@@ -1238,15 +1231,61 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1238
1231
|
report(1);
|
|
1239
1232
|
return indexed;
|
|
1240
1233
|
}
|
|
1241
|
-
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.ditherMethod, o.ditherSteps, o.width, o.transparent)), original, paletteSpace);
|
|
1234
|
+
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.ditherMethod, o.ditherSteps, o.width, o.transparent), undefined, image.premultiplied), original, paletteSpace);
|
|
1242
1235
|
return result;
|
|
1243
1236
|
};
|
|
1244
1237
|
|
|
1238
|
+
// clustering.chooseFrom: validates everything before its first await (the palette is copied, so the caller may change it
|
|
1239
|
+
// at once), then runs the search in choose.js on this thread with the cuts above.
|
|
1240
|
+
const chooseFrom = async (name, clustering, palette, k, options) => {
|
|
1241
|
+
const header = readHeader(clustering);
|
|
1242
|
+
checkPalette(palette);
|
|
1243
|
+
if (palette.length === 0) {
|
|
1244
|
+
throw fail('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
|
|
1245
|
+
}
|
|
1246
|
+
const entries = Uint8Array.from(palette);
|
|
1247
|
+
const count = entries.length / 3;
|
|
1248
|
+
k = check(k);
|
|
1249
|
+
if (k > count) {
|
|
1250
|
+
throw fail('invalid-argument', `Invalid k: ${k} is more than the ${count} entries in the palette; use ${count} or fewer.`, 'k');
|
|
1251
|
+
}
|
|
1252
|
+
const o = parseOptions(options, ['colorSpace', 'signal']);
|
|
1253
|
+
needsWeights(header);
|
|
1254
|
+
clustering = held(clustering);
|
|
1255
|
+
checkAborted(o.signal);
|
|
1256
|
+
const pause = async () => {
|
|
1257
|
+
checkAborted(o.signal);
|
|
1258
|
+
if (o.signal) {
|
|
1259
|
+
await yieldNow();
|
|
1260
|
+
checkAborted(o.signal);
|
|
1261
|
+
}
|
|
1262
|
+
};
|
|
1263
|
+
const indices = await choose({
|
|
1264
|
+
cut: size => cutPalette(name, clustering, size, []),
|
|
1265
|
+
swatches: () => cutSwatches(name, clustering, 1024, []),
|
|
1266
|
+
snap: async colours => (await quantizeToIndicesWithPalette({
|
|
1267
|
+
data: colours,
|
|
1268
|
+
format: 'rgb'
|
|
1269
|
+
}, entries, {
|
|
1270
|
+
colorSpace: 'rgb'
|
|
1271
|
+
})).indices,
|
|
1272
|
+
pause
|
|
1273
|
+
}, entries, k, colorSpaceName(o.colorSpace));
|
|
1274
|
+
indices.sort((x, y) => x - y);
|
|
1275
|
+
const chosen = new Uint8Array(3 * indices.length);
|
|
1276
|
+
indices.forEach((j, s) => chosen.set(entries.subarray(3 * j, 3 * j + 3), 3 * s));
|
|
1277
|
+
return {
|
|
1278
|
+
indices,
|
|
1279
|
+
palette: markPalette(chosen, 'rgb')
|
|
1280
|
+
};
|
|
1281
|
+
};
|
|
1282
|
+
|
|
1245
1283
|
// The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
|
|
1246
1284
|
setEngine({
|
|
1247
1285
|
cut: cutPalette,
|
|
1248
1286
|
cutSwatches,
|
|
1249
1287
|
info: readInfo,
|
|
1250
1288
|
quantizeFromClustering,
|
|
1251
|
-
quantizeToIndicesFromClustering
|
|
1289
|
+
quantizeToIndicesFromClustering,
|
|
1290
|
+
chooseFrom
|
|
1252
1291
|
});
|