agglomerative-clustering 4.0.0-beta.2 → 4.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 +5 -5
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +40 -238
- package/dist/index.d.cts +15 -76
- package/dist/index.d.ts +15 -76
- package/dist/index.mjs +28 -221
- package/dist/shared.cjs +244 -84
- package/dist/shared.mjs +235 -78
- package/dist/worker-thread.mjs +16 -19
- package/dist/worker.cjs +235 -136
- package/dist/worker.d.cts +0 -32
- package/dist/worker.d.ts +0 -32
- package/dist/worker.mjs +234 -130
- package/package.json +2 -2
package/dist/shared.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
// The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
|
|
6
6
|
// is built from, src/version.hpp) in step with it. Do not edit it by hand.
|
|
7
|
-
export const version = '4.0.0-beta.
|
|
7
|
+
export const version = '4.0.0-beta.4';
|
|
8
8
|
export const colorSpaceCodes = {
|
|
9
9
|
'rgb': 0,
|
|
10
10
|
'oklab': 1
|
|
@@ -97,7 +97,7 @@ export const checkImageDataPixels = image => {
|
|
|
97
97
|
}
|
|
98
98
|
const needed = image.width * image.height * 4;
|
|
99
99
|
if (image.data.length !== needed) {
|
|
100
|
-
throw fail('invalid-argument', `Invalid image: this ImageData's data has ${image.data.length
|
|
100
|
+
throw fail('invalid-argument', `Invalid image: this ImageData's data has ${counted(image.data.length, 'byte', 'bytes')}, but ${image.width} x ${image.height} RGBA pixels need ${needed}.`, 'image');
|
|
101
101
|
}
|
|
102
102
|
return;
|
|
103
103
|
}
|
|
@@ -302,9 +302,11 @@ export const imageCopy = image => {
|
|
|
302
302
|
|
|
303
303
|
// What the main entry's `load` checks about an image object, from the copy imageCopy made, in its order: data's type, whether its
|
|
304
304
|
// buffer is detached, then checkImageObject. The worker entry runs the same before it posts an image. Returns the premultiplied flag.
|
|
305
|
+
// What to do with 16-bit pixels (a decoder's Uint16Array for a 16-bit PNG): the library reads 8 bits per channel.
|
|
306
|
+
const sixteenBit = data => Object.prototype.toString.call(data) === '[object Uint16Array]' ? ' 16-bit pixels (a Uint16Array, as decoders give for a 16-bit PNG) have to be shifted down to 8 bits first: Uint8Array.from(data, (v) => v >> 8).' : '';
|
|
305
307
|
export const checkImageBody = image => {
|
|
306
308
|
if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
|
|
307
|
-
throw fail('invalid-argument',
|
|
309
|
+
throw fail('invalid-argument', `Invalid image data: must be Uint8Array or Uint8ClampedArray.${sixteenBit(image.data)}`, 'image');
|
|
308
310
|
}
|
|
309
311
|
if (isDetached(image.data)) {
|
|
310
312
|
throw detachedError('data');
|
|
@@ -341,6 +343,9 @@ const ditherMethodCodes = {
|
|
|
341
343
|
export const ditherMethods = Object.freeze(Object.keys(ditherMethodCodes));
|
|
342
344
|
export const ditherSteps = Object.freeze([2, 4, 8, 16, 32, 64]);
|
|
343
345
|
|
|
346
|
+
// A count with its noun in the right number, for messages: 1 byte, 2 bytes.
|
|
347
|
+
export const counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
348
|
+
|
|
344
349
|
// A short description of a value for an error message.
|
|
345
350
|
export const describe = value => typeof value === 'string' ? `'${value}'` : typeof value === 'number' || typeof value === 'boolean' || value === null ? String(value) : Array.isArray(value) ? 'an array' : typeof value === 'object' ? `a ${Object.prototype.toString.call(value).slice(8, -1)}` : `a ${typeof value}`;
|
|
346
351
|
|
|
@@ -496,7 +501,7 @@ export const sniffImageFormat = bytes => {
|
|
|
496
501
|
// The other common way to get a bare array wrong is bytes of another layout: RGB (sharp's plain .raw()), or grey and grey
|
|
497
502
|
// with alpha (fast-png's decode() of a grey PNG). Read as RGBA, every pixel takes bytes from its neighbours and one of them
|
|
498
503
|
// as its alpha, and nothing fails while the length divides by 4. They are never reinterpreted (a bare array is RGBA,
|
|
499
|
-
// PRINCIPLES), only reported
|
|
504
|
+
// PRINCIPLES), only reported, as an error (a warning in 3.x).
|
|
500
505
|
//
|
|
501
506
|
// The rules use E(k), the mean change between a byte and the one k before it (bench/spikes/bare-rgb/ and
|
|
502
507
|
// bench/spikes/bare-grey/: no false positives on 2,984 real RGBA images).
|
|
@@ -505,8 +510,8 @@ export const sniffImageFormat = bytes => {
|
|
|
505
510
|
// but where it changes its bytes come in equal triples at a step of 3 and not of 4.
|
|
506
511
|
// - Grey and alpha (2 bytes a pixel): smooth at a step of 2 and rough at a step of 1, since grey and alpha bytes alternate.
|
|
507
512
|
// - Grey (1 byte a pixel): smoothest at a step of 1, unless most changing pixels have four equal bytes, which is real
|
|
508
|
-
// RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same;
|
|
509
|
-
//
|
|
513
|
+
// RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same; its error text
|
|
514
|
+
// covers grey too.
|
|
510
515
|
// Units equal to the one before are skipped by the equal-byte counts, since flat areas read the same either way. It
|
|
511
516
|
// samples 512 windows of 96 bytes (each on a multiple of 12, a pixel under every reading, one in each 512th of the
|
|
512
517
|
// array), so it costs about 0.35 ms at any size. Returns 'rgb', 'grey', 'grey-alpha' or null.
|
|
@@ -601,79 +606,30 @@ export const bareLayout = d => {
|
|
|
601
606
|
};
|
|
602
607
|
export const looksLikeRgb = d => bareLayout(d) === 'rgb';
|
|
603
608
|
|
|
604
|
-
//
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
grey: '
|
|
609
|
-
'grey-
|
|
609
|
+
// The error a bare image calls for, or null. It skips everything the main entry rejects for another reason (palettes and
|
|
610
|
+
// clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never gives two
|
|
611
|
+
// errors for its image and both entries share this one order.
|
|
612
|
+
const bareText = {
|
|
613
|
+
rgb: n => `Invalid image: these ${n} bytes look like RGB (3 per pixel) or grey, not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it is grey (fast-png's decode() of a grey PNG), expand it to RGBA: format: 'rgb' would misread it too. If it really is RGBA, pass { data, format: 'rgba' } to say so.`,
|
|
614
|
+
grey: n => `Invalid image: these ${n} bytes look like grey (1 per pixel), not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). fast-png's decode() gives this for a grey PNG (rows below 8 bits stay packed) and for a palette PNG's indices. Expand 8-bit grey to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()); there is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so.`,
|
|
615
|
+
'grey-alpha': n => `Invalid image: these ${n} bytes look like grey and alpha (2 per pixel), not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). fast-png's decode() gives this for a grey PNG with alpha. Expand it to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()); there is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so.`
|
|
610
616
|
};
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
// and clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never both warns
|
|
614
|
-
// about its image and rejects it, and both entries share this one order. An array of one layout never takes another's
|
|
615
|
-
// code because its own was already used: it is classified first, and only then is its code checked.
|
|
616
|
-
export const bareImageWarning = image => {
|
|
617
|
-
if (warned.has('rgb-as-rgba') && warned.has('gray-as-rgba') || !isUint8Array(image) || isPalette(image) || isClustering(image)) {
|
|
617
|
+
export const bareImageError = image => {
|
|
618
|
+
if (!isUint8Array(image) || isPalette(image) || isClustering(image)) {
|
|
618
619
|
return null;
|
|
619
620
|
}
|
|
620
621
|
if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
|
|
621
622
|
return null;
|
|
622
623
|
}
|
|
623
624
|
const layout = bareLayout(image);
|
|
624
|
-
return layout === null
|
|
625
|
-
code: bareCodes[layout],
|
|
626
|
-
layout
|
|
627
|
-
};
|
|
628
|
-
};
|
|
629
|
-
|
|
630
|
-
// The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
|
|
631
|
-
// process.on('warning') and --trace-warnings then work), else console.warn. Runtimes that imitate Node have an
|
|
632
|
-
// emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
|
|
633
|
-
// navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
|
|
634
|
-
// keeps Parcel from adding one.
|
|
635
|
-
const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
|
|
636
|
-
const warningText = {
|
|
637
|
-
'rgb-as-rgba': byteLength => `This image (${byteLength.toLocaleString('en-US')} bytes) looks like RGB bytes (3 per pixel), or grey, passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it is grey (fast-png's decode() of a grey PNG), expand it to RGBA; format: 'rgb' would misread it too. If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`,
|
|
638
|
-
'gray-as-rgba': (byteLength, layout) => (layout === 'grey-alpha' ? `This image (${byteLength.toLocaleString('en-US')} bytes) looks like grey and alpha bytes (2 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. fast-png's decode() gives this for a grey PNG with alpha.` : `This image (${byteLength.toLocaleString('en-US')} bytes) looks like grey bytes (1 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. fast-png's decode() gives this for a grey PNG (rows below 8 bits stay packed) and for a palette PNG's indices.`) + ` Expand ${layout === 'grey-alpha' ? 'it' : '8-bit grey'} to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()). There is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`
|
|
639
|
-
};
|
|
640
|
-
// `warning` is what bareImageWarning returned: {code, layout}.
|
|
641
|
-
export const warnOnce = ({
|
|
642
|
-
code,
|
|
643
|
-
layout
|
|
644
|
-
}, byteLength) => {
|
|
645
|
-
if (warned.has(code)) {
|
|
646
|
-
return;
|
|
647
|
-
}
|
|
648
|
-
warned.add(code);
|
|
649
|
-
const message = warningText[code](byteLength, layout);
|
|
650
|
-
const runtime = globalThis.process;
|
|
651
|
-
if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
|
|
652
|
-
runtime.emitWarning(message, {
|
|
653
|
-
type: 'AgglomerativeClusteringWarning',
|
|
654
|
-
code
|
|
655
|
-
});
|
|
656
|
-
} else if (typeof console !== 'undefined') {
|
|
657
|
-
console.warn(`agglomerative-clustering [${code}]: ${message}`);
|
|
658
|
-
}
|
|
659
|
-
};
|
|
660
|
-
// The worker thread's copy: its caller's side checks and warns (PRINCIPLES), so here every code counts as warned, which
|
|
661
|
-
// also skips the sampling.
|
|
662
|
-
export const silenceWarnings = () => {
|
|
663
|
-
for (const code of Object.keys(warningText)) {
|
|
664
|
-
warned.add(code);
|
|
665
|
-
}
|
|
666
|
-
};
|
|
667
|
-
// For tests.
|
|
668
|
-
export const resetWarnings = () => {
|
|
669
|
-
warned.clear();
|
|
625
|
+
return layout === null ? null : fail('invalid-argument', bareText[layout](image.byteLength.toLocaleString('en-US')), 'image');
|
|
670
626
|
};
|
|
671
627
|
// Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
|
|
672
628
|
// `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
|
|
673
629
|
const inspect = Symbol.for('nodejs.util.inspect.custom');
|
|
674
630
|
const view = label => function (depth, options, nodeInspect) {
|
|
675
631
|
const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
|
|
676
|
-
return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${plain.length
|
|
632
|
+
return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${counted(plain.length, 'byte', 'bytes')}]`}`;
|
|
677
633
|
};
|
|
678
634
|
const paletteView = view(palette => `Palette(${palette.colorSpace})`);
|
|
679
635
|
const clusteringView = view(() => 'Clustering');
|
|
@@ -689,7 +645,7 @@ export const markPalette = (bytes, colorSpace) => {
|
|
|
689
645
|
});
|
|
690
646
|
return bytes;
|
|
691
647
|
};
|
|
692
|
-
// Methods on a clustering: `clustering.getPalette(k)`
|
|
648
|
+
// Methods on a clustering: `clustering.getPalette(k)` cuts a palette from it, and so on. They are
|
|
693
649
|
// non-enumerable own properties, added with the tags, so a clustering stays a plain Uint8Array (`toEqual` and
|
|
694
650
|
// `deepStrictEqual` against plain bytes still pass), and slices and clones drop them as they drop the tags. They run on the
|
|
695
651
|
// calling thread with the main entry's functions, which the main entry puts in `engine` when it is evaluated; the worker
|
|
@@ -703,13 +659,13 @@ export const setEngine = value => {
|
|
|
703
659
|
engine = value;
|
|
704
660
|
}
|
|
705
661
|
};
|
|
706
|
-
// Each method's call shape and
|
|
662
|
+
// Each method's call shape and the loaded-handle form that serves it off the thread, for messages.
|
|
707
663
|
const methodNames = {
|
|
708
|
-
getPalette: ['getPalette(k)', '
|
|
709
|
-
getSwatches: ['getSwatches(k)', '
|
|
710
|
-
getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)
|
|
711
|
-
quantize: ['quantize(image, k)', '
|
|
712
|
-
quantizeToIndices: ['quantizeToIndices(image, k)', '
|
|
664
|
+
getPalette: ['getPalette(k)', "a loaded handle's getPalette: (await worker.load(clustering)).getPalette(k)"],
|
|
665
|
+
getSwatches: ['getSwatches(k)', "a loaded handle's getSwatches: (await worker.load(clustering)).getSwatches(k)"],
|
|
666
|
+
getClusteringInfo: ['getClusteringInfo()', "a loaded handle's getClusteringInfo: (await worker.load(clustering)).getClusteringInfo()"],
|
|
667
|
+
quantize: ['quantize(image, k)', "a loaded handle's quantize: (await worker.load(clustering)).quantize(image, k)"],
|
|
668
|
+
quantizeToIndices: ['quantizeToIndices(image, k)', "a loaded handle's quantizeToIndices: (await worker.load(clustering)).quantizeToIndices(image, k)"],
|
|
713
669
|
chooseFrom: ['chooseFrom(palette, k, options?)', "a loaded handle's chooseFrom: (await worker.load(clustering)).chooseFrom(palette, k)"]
|
|
714
670
|
};
|
|
715
671
|
// Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
|
|
@@ -832,6 +788,10 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
|
|
|
832
788
|
// those of a Uint8Array (bytes to copy, or a buffer with an offset and length to view).
|
|
833
789
|
export function Clustering(...args) {
|
|
834
790
|
const [source] = args;
|
|
791
|
+
// A palette gets the same hint as from every other function, before its bytes are copied.
|
|
792
|
+
if (isPalette(source)) {
|
|
793
|
+
readHeader(source);
|
|
794
|
+
}
|
|
835
795
|
// Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
|
|
836
796
|
// would coerce. A plain array must hold byte values, as for a palette.
|
|
837
797
|
const isBuffer = isArrayBufferLike(source);
|
|
@@ -921,17 +881,21 @@ const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes
|
|
|
921
881
|
// and a length of 0 or 3 more than a multiple of 9).
|
|
922
882
|
const notAClustering = clustering => {
|
|
923
883
|
const length = clustering.length;
|
|
884
|
+
// No bytes at all is not a 1.x clustering that lost its header: there is nothing to read.
|
|
885
|
+
if (length === 0) {
|
|
886
|
+
return fail('invalid-clustering', "Invalid clustering: it is empty (no bytes). A clustering comes from buildClustering, even for an image with no visible pixels.", 'clustering');
|
|
887
|
+
}
|
|
924
888
|
if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
|
|
925
889
|
return fail('invalid-clustering', "Invalid clustering: not a clustering from buildClustering. If it was stored by agglomerative-clustering 1.x, that format is no longer read: cluster the image again.", 'clustering');
|
|
926
890
|
}
|
|
927
891
|
if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
|
|
928
|
-
return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${length
|
|
892
|
+
return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${counted(length, 'byte', 'bytes')}): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
|
|
929
893
|
}
|
|
930
|
-
return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${length
|
|
894
|
+
return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${counted(length, 'byte', 'bytes')} that ${length === 1 ? "doesn't" : "don't"} start with a clustering header).`, 'clustering');
|
|
931
895
|
};
|
|
932
896
|
export const readHeader = clustering => {
|
|
933
897
|
if (isPalette(clustering)) {
|
|
934
|
-
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette
|
|
898
|
+
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette or clustering.getPalette(k); a clustering comes from buildClustering.", 'clustering');
|
|
935
899
|
}
|
|
936
900
|
if (!isUint8Array(clustering)) {
|
|
937
901
|
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from buildClustering.", 'clustering');
|
|
@@ -993,11 +957,11 @@ export const readHeader = clustering => {
|
|
|
993
957
|
throw notAClustering(clustering);
|
|
994
958
|
};
|
|
995
959
|
|
|
996
|
-
// Palettes are flat RGB bytes. An empty palette is allowed: it is what
|
|
960
|
+
// Palettes are flat RGB bytes. An empty palette is allowed: it is what buildPalette gives for a fully transparent
|
|
997
961
|
// image, and quantize maps such an image the same way.
|
|
998
962
|
export const checkPalette = palette => {
|
|
999
963
|
if (isClustering(palette)) {
|
|
1000
|
-
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with
|
|
964
|
+
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with clustering.getPalette(k), or map with clustering.quantize(image, k).", 'palette');
|
|
1001
965
|
}
|
|
1002
966
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
1003
967
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
|
@@ -1072,4 +1036,197 @@ export const revive = value => {
|
|
|
1072
1036
|
value[key] = reviveOne(value[key]);
|
|
1073
1037
|
}
|
|
1074
1038
|
return value;
|
|
1039
|
+
};
|
|
1040
|
+
|
|
1041
|
+
// ----- Arguments both entries check ------------------------------------------------------------------------------------
|
|
1042
|
+
// What the main entry checks about k and the options before it does any work, kept here so the worker entry runs the very same
|
|
1043
|
+
// checks, in the same order, before it posts anything.
|
|
1044
|
+
export const alphaModeCodes = {
|
|
1045
|
+
'ignore': 0,
|
|
1046
|
+
'weight': 1
|
|
1047
|
+
};
|
|
1048
|
+
|
|
1049
|
+
// Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
|
|
1050
|
+
// the WASM side holds (a larger one would overflow its int).
|
|
1051
|
+
export const checkK = k => {
|
|
1052
|
+
if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
|
|
1053
|
+
// A string is the usual slip (an input's `value`), so it gets its own fix.
|
|
1054
|
+
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}.`;
|
|
1055
|
+
throw fail('invalid-argument', `Invalid k: must be a whole number of colours, 1 or more.${got}`, 'k');
|
|
1056
|
+
}
|
|
1057
|
+
return Math.min(k, 0x7FFFFFFF);
|
|
1058
|
+
};
|
|
1059
|
+
|
|
1060
|
+
// Validates `options` against the keys a function accepts and fills in defaults:
|
|
1061
|
+
// colorSpace: 'rgb' (default) or 'oklab', the space colours are clustered and matched in; when mapping with a
|
|
1062
|
+
// clustering, the default is the space the clustering was made in (code -1)
|
|
1063
|
+
// alpha: 'weight' (default) counts RGBA pixels in proportion to their opacity; 'ignore' counts every pixel
|
|
1064
|
+
// precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
|
|
1065
|
+
// dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
|
|
1066
|
+
// width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
|
|
1067
|
+
// signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
|
|
1068
|
+
// (see clusterInSlices and mapInSlices)
|
|
1069
|
+
// 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);
|
|
1070
|
+
// indexed output also gives them their own entry, which counts towards k
|
|
1071
|
+
|
|
1072
|
+
// The settings of dither, which a caller may write as options of their own; naming one of these gets a pointer to the
|
|
1073
|
+
// object form.
|
|
1074
|
+
const ditherSettings = ['ditherMethod', 'ditherStrength', 'ditherSteps', 'method', 'strength', 'steps', 'mix'];
|
|
1075
|
+
export const parseOptions = (options, allowed, image) => {
|
|
1076
|
+
if (options === undefined) {
|
|
1077
|
+
options = {};
|
|
1078
|
+
}
|
|
1079
|
+
if (!isOptionsObject(options)) {
|
|
1080
|
+
throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
|
|
1081
|
+
}
|
|
1082
|
+
options = snapshot(options);
|
|
1083
|
+
for (const key of Object.keys(options)) {
|
|
1084
|
+
if (!allowed.includes(key)) {
|
|
1085
|
+
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
|
|
1086
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
const colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
|
|
1090
|
+
if (!colorSpaces.includes(colorSpace)) {
|
|
1091
|
+
throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
|
|
1092
|
+
}
|
|
1093
|
+
const alpha = options.alpha === undefined ? 'weight' : options.alpha;
|
|
1094
|
+
if (!alphaModes.includes(alpha)) {
|
|
1095
|
+
throw fail('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
|
|
1096
|
+
}
|
|
1097
|
+
const precision = options.precision === undefined ? 8 : options.precision;
|
|
1098
|
+
if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
|
|
1099
|
+
throw fail('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
|
|
1100
|
+
}
|
|
1101
|
+
const {
|
|
1102
|
+
strength: dither,
|
|
1103
|
+
method: ditherMethod,
|
|
1104
|
+
steps: ditherSteps
|
|
1105
|
+
} = parseDither(options.dither);
|
|
1106
|
+
|
|
1107
|
+
// The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
|
|
1108
|
+
// (a wrong row length would dither without an error, as long as it divides the pixel count).
|
|
1109
|
+
if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
|
|
1110
|
+
throw fail('invalid-argument', `Invalid width: options.width (${describe(options.width)}) does not match the image's width (${image.width}).`, 'options.width');
|
|
1111
|
+
}
|
|
1112
|
+
if (options.width !== undefined && image) {
|
|
1113
|
+
checkSize(image.data.length / channels(image.format), options.width, 'width', 'options.width');
|
|
1114
|
+
}
|
|
1115
|
+
const width = options.width !== undefined ? options.width : image ? image.width : undefined;
|
|
1116
|
+
if (dither > 0) {
|
|
1117
|
+
const stride = channels(image.format);
|
|
1118
|
+
if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
|
|
1119
|
+
throw fail('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
|
|
1120
|
+
}
|
|
1121
|
+
if (image.data.length / stride % width !== 0) {
|
|
1122
|
+
throw fail('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
const signal = options.signal;
|
|
1126
|
+
if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
|
|
1127
|
+
throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
|
|
1128
|
+
}
|
|
1129
|
+
const onProgress = options.onProgress;
|
|
1130
|
+
if (onProgress !== undefined && typeof onProgress !== 'function') {
|
|
1131
|
+
throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
// The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
|
|
1135
|
+
const transparentOption = options.transparent === undefined ? false : options.transparent;
|
|
1136
|
+
const transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
|
|
1137
|
+
if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
|
|
1138
|
+
throw fail('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
|
|
1139
|
+
}
|
|
1140
|
+
checkTransparentFormat(image, options);
|
|
1141
|
+
|
|
1142
|
+
// A cutoff replaces opacity weighting (pixels count whole or not at all), so naming both would leave one of them ignored.
|
|
1143
|
+
if (transparent > 0 && options.alpha !== undefined) {
|
|
1144
|
+
throw fail('invalid-argument', "Invalid options: `transparent` replaces `alpha` (with a cutoff, pixels count whole or not at all), so give one or the other.", 'options');
|
|
1145
|
+
}
|
|
1146
|
+
return {
|
|
1147
|
+
colorSpace: colorSpaceCodes[colorSpace],
|
|
1148
|
+
colorSpaceGiven: options.colorSpace !== undefined,
|
|
1149
|
+
alpha: alphaModeCodes[alpha],
|
|
1150
|
+
precision,
|
|
1151
|
+
dither,
|
|
1152
|
+
ditherMethod,
|
|
1153
|
+
ditherSteps,
|
|
1154
|
+
width: dither > 0 ? width : 0,
|
|
1155
|
+
transparent,
|
|
1156
|
+
transparentGiven: options.transparent !== undefined,
|
|
1157
|
+
signal,
|
|
1158
|
+
onProgress
|
|
1159
|
+
};
|
|
1160
|
+
};
|
|
1161
|
+
const controlOptions = ['signal', 'onProgress'];
|
|
1162
|
+
// `transparent: true` or a cutoff on a format with no alpha channel can't mean anything (no pixel is transparent), so it is
|
|
1163
|
+
// an error rather than a silent no-op. Only the call's own options count: a clustering's stored cutoff never reaches here.
|
|
1164
|
+
const checkTransparentFormat = (image, options) => {
|
|
1165
|
+
if (!image || hasAlpha(image.format) || options.transparent === undefined || options.transparent === false) {
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
const hint = image.format === 'rgbx' || image.format === 'bgrx' ? " If the fourth byte really is alpha, use 'rgba' or 'bgra'." : '';
|
|
1169
|
+
throw fail('invalid-argument', `Invalid transparent: '${image.format}' has no alpha, so no pixel can be transparent. Leave transparent out (false is accepted).${hint}`, 'options.transparent');
|
|
1170
|
+
};
|
|
1171
|
+
export const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
|
|
1172
|
+
export const quantizeOptions = [...clusterOptions, 'dither', 'width'];
|
|
1173
|
+
export const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
|
|
1174
|
+
export const quantizeIndexOptions = quantizeOptions;
|
|
1175
|
+
export const mapIndexOptions = [...mapOptions, 'transparent'];
|
|
1176
|
+
|
|
1177
|
+
// What a bare typed array passed as an image must be, in the order the main entry checks it: not a clustering or a palette,
|
|
1178
|
+
// then (when it is not detached, which the caller reports) for a Uint8Array not the bytes of an image file and a whole number
|
|
1179
|
+
// of RGBA pixels, and no other kind of array. The bare-RGB and grey check (bareImageError) follows, in the caller.
|
|
1180
|
+
export const checkPixelArray = image => {
|
|
1181
|
+
if (isClustering(image) || isPalette(image)) {
|
|
1182
|
+
const what = isClustering(image) ? 'a clustering (from buildClustering)' : 'a palette';
|
|
1183
|
+
const fix = isClustering(image) ? 'To cut a palette from it, use clustering.getPalette(k) (or clustering.quantize(image, k) to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
|
|
1184
|
+
throw fail('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
|
|
1185
|
+
}
|
|
1186
|
+
if (isDetached(image)) {
|
|
1187
|
+
return;
|
|
1188
|
+
}
|
|
1189
|
+
if (isUint8Array(image)) {
|
|
1190
|
+
const encoded = sniffImageFormat(image);
|
|
1191
|
+
if (encoded) {
|
|
1192
|
+
throw fail('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode them to pixels first and pass those ("Decoding image files" in the guides has a recipe for Node, browsers and edge runtimes). If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
|
|
1193
|
+
}
|
|
1194
|
+
if (image.length % 4 !== 0) {
|
|
1195
|
+
throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
|
|
1196
|
+
}
|
|
1197
|
+
return;
|
|
1198
|
+
}
|
|
1199
|
+
throw fail('invalid-argument', `Invalid image: a bare typed array must be a Uint8Array of RGBA bytes. For a Uint8ClampedArray such as imageData.data, pass the ImageData itself or { data, format: 'rgba' }.${sixteenBit(image)}`, 'image');
|
|
1200
|
+
};
|
|
1201
|
+
|
|
1202
|
+
// An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
|
|
1203
|
+
// fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
|
|
1204
|
+
// alpha from which an RGBA pixel needs a colour.
|
|
1205
|
+
export const checkNotEmpty = (palette, image, cutoff) => {
|
|
1206
|
+
if (palette.length > 0) {
|
|
1207
|
+
return;
|
|
1208
|
+
}
|
|
1209
|
+
const data = image.data;
|
|
1210
|
+
let visible = hasAlpha(image.format) ? false : data.length > 0;
|
|
1211
|
+
for (let i = 3; !visible && hasAlpha(image.format) && i < data.length; i += 4) {
|
|
1212
|
+
visible = data[i] >= cutoff;
|
|
1213
|
+
}
|
|
1214
|
+
if (visible) {
|
|
1215
|
+
throw fail('invalid-argument', "Invalid palette: it is empty, but the image has visible pixels to map to it.", 'palette');
|
|
1216
|
+
}
|
|
1217
|
+
};
|
|
1218
|
+
|
|
1219
|
+
// What clustering.chooseFrom checks about its palette and k, in order: the palette is flat RGB bytes and not empty, k is a
|
|
1220
|
+
// whole number of colours and no more than the palette has. Returns k.
|
|
1221
|
+
export const checkChoice = (palette, k) => {
|
|
1222
|
+
checkPalette(palette);
|
|
1223
|
+
if (palette.length === 0) {
|
|
1224
|
+
throw fail('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
|
|
1225
|
+
}
|
|
1226
|
+
const count = palette.length / 3;
|
|
1227
|
+
k = checkK(k);
|
|
1228
|
+
if (k > count) {
|
|
1229
|
+
throw fail('invalid-argument', `Invalid k: ${k} is more than the ${counted(count, 'entry', 'entries')} in the palette; use ${count} or fewer.`, 'k');
|
|
1230
|
+
}
|
|
1231
|
+
return k;
|
|
1075
1232
|
};
|
package/dist/worker-thread.mjs
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
// Runs inside the worker started by worker.js: receives calls, runs them with the main entry, and posts results
|
|
2
2
|
// back, transferring every result buffer. Imports `./index.mjs`, which exists only in dist/ (like clustering.js).
|
|
3
3
|
import * as ac from './index.mjs';
|
|
4
|
-
import { MARK, mark, revive, isPalette
|
|
5
|
-
|
|
6
|
-
// The caller's side checks for warnings and gives them (PRINCIPLES "Warnings"), so this copy stays quiet.
|
|
7
|
-
silenceWarnings();
|
|
4
|
+
import { version, MARK, mark, revive, isPalette } from "./shared.mjs";
|
|
8
5
|
|
|
9
6
|
// Images kept in the worker by `cluster`, with their clusterings, and clusterings alone from `load`, by handle id.
|
|
10
7
|
const handles = new Map();
|
|
@@ -31,7 +28,7 @@ const inClusteringSpace = async (id, options, palette) => {
|
|
|
31
28
|
}
|
|
32
29
|
const {
|
|
33
30
|
colorSpace
|
|
34
|
-
} = await
|
|
31
|
+
} = await handle(id).clustering.getClusteringInfo();
|
|
35
32
|
return {
|
|
36
33
|
...options,
|
|
37
34
|
colorSpace: options && options.colorSpace !== undefined ? options.colorSpace : colorSpace
|
|
@@ -44,10 +41,12 @@ const inClusteringSpace = async (id, options, palette) => {
|
|
|
44
41
|
const functions = Object.fromEntries(Object.entries(ac).filter(([name, value]) => typeof value === 'function' && !/^[A-Z]/.test(name)));
|
|
45
42
|
const methods = {
|
|
46
43
|
...functions,
|
|
44
|
+
// The first message every worker entry sends: which version this script is.
|
|
45
|
+
handshake: async () => version,
|
|
47
46
|
cluster: async (id, image, options) => {
|
|
48
47
|
handles.set(id, {
|
|
49
48
|
image,
|
|
50
|
-
clustering: await ac.
|
|
49
|
+
clustering: await ac.buildClustering(image, options)
|
|
51
50
|
});
|
|
52
51
|
},
|
|
53
52
|
load: async (id, clustering) => {
|
|
@@ -59,14 +58,14 @@ const methods = {
|
|
|
59
58
|
handles.delete(id);
|
|
60
59
|
},
|
|
61
60
|
handleGetClustering: async id => new ac.Clustering(handle(id).clustering),
|
|
62
|
-
handleGetPalette: async (id, k) =>
|
|
63
|
-
handleGetSwatches: async (id, k) =>
|
|
64
|
-
handleGetClusteringInfo: async id =>
|
|
61
|
+
handleGetPalette: async (id, k) => handle(id).clustering.getPalette(k),
|
|
62
|
+
handleGetSwatches: async (id, k) => handle(id).clustering.getSwatches(k),
|
|
63
|
+
handleGetClusteringInfo: async id => handle(id).clustering.getClusteringInfo(),
|
|
65
64
|
handleChooseFrom: async (id, palette, k, options) => handle(id).clustering.chooseFrom(palette, k, options),
|
|
66
|
-
handleQuantize: async (id, k, options) =>
|
|
67
|
-
handleQuantizeToIndices: async (id, k, options) =>
|
|
68
|
-
handleQuantizeImage: async (id, image, k, options) =>
|
|
69
|
-
handleQuantizeToIndicesImage: async (id, image, k, options) =>
|
|
65
|
+
handleQuantize: async (id, k, options) => handle(id).clustering.quantize(handle(id).image, k, options),
|
|
66
|
+
handleQuantizeToIndices: async (id, k, options) => handle(id).clustering.quantizeToIndices(handle(id).image, k, options),
|
|
67
|
+
handleQuantizeImage: async (id, image, k, options) => handle(id).clustering.quantize(image, k, options),
|
|
68
|
+
handleQuantizeToIndicesImage: async (id, image, k, options) => handle(id).clustering.quantizeToIndices(image, k, options),
|
|
70
69
|
handleQuantizeWithPalette: async (id, palette, options) => ac.quantizeWithPalette(handle(id).image, palette, await inClusteringSpace(id, options, palette)),
|
|
71
70
|
handleQuantizeToIndicesWithPalette: async (id, palette, options) => ac.quantizeToIndicesWithPalette(handle(id).image, palette, await inClusteringSpace(id, options, palette))
|
|
72
71
|
};
|
|
@@ -87,14 +86,12 @@ const buffers = value => {
|
|
|
87
86
|
|
|
88
87
|
// Where the options sit among each method's arguments, to give them the call's signal and progress callback.
|
|
89
88
|
const optionsIndex = {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
89
|
+
buildClustering: 1,
|
|
90
|
+
buildPalette: 2,
|
|
91
|
+
buildSwatches: 2,
|
|
93
92
|
quantize: 2,
|
|
94
|
-
quantizeFromClustering: 3,
|
|
95
93
|
quantizeWithPalette: 2,
|
|
96
94
|
quantizeToIndices: 2,
|
|
97
|
-
quantizeToIndicesFromClustering: 3,
|
|
98
95
|
quantizeToIndicesWithPalette: 2,
|
|
99
96
|
cluster: 2,
|
|
100
97
|
handleQuantize: 2,
|
|
@@ -191,7 +188,7 @@ const respond = async ({
|
|
|
191
188
|
stack: error.stack
|
|
192
189
|
} : {
|
|
193
190
|
name: 'Error',
|
|
194
|
-
message: String(error),
|
|
191
|
+
message: typeof error === 'function' ? 'a function was thrown' : String(error),
|
|
195
192
|
code: 'worker-failed'
|
|
196
193
|
}
|
|
197
194
|
});
|