agglomerative-clustering 3.4.2 → 3.6.0
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 -3
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +31 -66
- package/dist/index.mjs +31 -66
- package/dist/shared.cjs +250 -3
- package/dist/shared.mjs +241 -1
- package/dist/worker-thread.mjs +4 -1
- package/dist/worker.cjs +13 -0
- package/dist/worker.mjs +14 -1
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
|
|
|
16
16
|
- **Transparency-aware.** A logo's transparent background never ends up in its palette. GIF and palette PNG output are built in.
|
|
17
17
|
- **Off the main thread.** `agglomerative-clustering/worker` runs the same API in a Web Worker or Node worker thread.
|
|
18
18
|
- **Accurate and fast.** The lowest average error of the six JavaScript quantizers we benchmarked, at about the speed of libimagequant ([benchmarks](#benchmarks)).
|
|
19
|
-
- **Small and portable.** About
|
|
19
|
+
- **Small and portable.** About 82 KB of WebAssembly (40 KB gzipped)<!-- bench/spikes/wasm-size/results-size.txt -->, Node and browsers, TypeScript types, no runtime dependencies, deterministic output.
|
|
20
20
|
|
|
21
21
|
## Install
|
|
22
22
|
|
|
@@ -36,7 +36,7 @@ It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (Chrome
|
|
|
36
36
|
import sharp from 'sharp';
|
|
37
37
|
import { buildPalette, quantize } from 'agglomerative-clustering';
|
|
38
38
|
|
|
39
|
-
const { data, info } = await sharp('photo.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
39
|
+
const { data, info } = await sharp('photo.jpg').rotate().ensureAlpha().raw().toBuffer({ resolveWithObject: true });
|
|
40
40
|
const image = { data, format: 'rgba', width: info.width }; // in TypeScript: format: 'rgba' as const
|
|
41
41
|
|
|
42
42
|
const palette = await buildPalette(image, 8); // flat bytes: [r, g, b, r, g, b, ...]
|
|
@@ -67,6 +67,8 @@ shares.forEach((share, i) => {
|
|
|
67
67
|
});
|
|
68
68
|
```
|
|
69
69
|
|
|
70
|
+
Entries keep their place as `k` grows (split order), so palettes nest. For hex strings, the largest share first or a dominant colour, see [Heaviest first](docs/guides.md#heaviest-first).
|
|
71
|
+
|
|
70
72
|
**A colour-count slider:** cluster once, then cut and map as often as you like.
|
|
71
73
|
|
|
72
74
|
```js
|
|
@@ -80,7 +82,7 @@ slider.oninput = async () => {
|
|
|
80
82
|
};
|
|
81
83
|
```
|
|
82
84
|
|
|
83
|
-
Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources, which are premultiplied, and the conversion. RGB bytes passed bare are read as RGBA, so pass them as `{ data, format: 'rgb' }`. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
|
|
85
|
+
Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources, which are premultiplied, and the conversion. RGB bytes passed bare are read as RGBA; the library warns when it sees this (an error from 4.0), so pass them as `{ data, format: 'rgb' }`. To start from a PNG, JPEG, WebP or GIF file, decode it first: [Decoding image files](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#decoding-image-files) has a recipe for Node, browsers and edge runtimes. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
|
|
84
86
|
|
|
85
87
|
## How it works
|
|
86
88
|
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|
package/dist/index.cjs
CHANGED
|
@@ -470,70 +470,6 @@ const unpack = (wasm, pointer) => {
|
|
|
470
470
|
// A Uint8Array over exactly the same bytes, so views into a larger buffer (subarrays) stay views of their own range.
|
|
471
471
|
const bytes = data => (0, _shared.isUint8Array)(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
472
472
|
|
|
473
|
-
// ----- Encoded image files -------------------------------------------------------------------------------------------
|
|
474
|
-
// A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
|
|
475
|
-
// (fs.readFile, fetch().arrayBuffer()): it passes as pixels whenever its length is a multiple of 4 and gives a palette of
|
|
476
|
-
// nonsense. The signatures of the common formats are recognised so that it is reported instead. Only a bare Uint8Array is
|
|
477
|
-
// looked at: an ImageData or a { data, format } object has said what its bytes are, so it is never second-guessed, and a
|
|
478
|
-
// bare array that really is raw pixels can be passed as { data, format: 'rgba' } to say so.
|
|
479
|
-
//
|
|
480
|
-
// This is also where decoding would go. The library doesn't decode files today (that needs a decoder per format, and
|
|
481
|
-
// sharp, pngjs, createImageBitmap and the like already do it); when it does, a file recognised here is decoded into
|
|
482
|
-
// { data, format, width, height } instead of rejected, and `load` becomes asynchronous. See docs/ROADMAP.md.
|
|
483
|
-
const ascii = (bytes, at, text) => {
|
|
484
|
-
for (let i = 0; i < text.length; i++) {
|
|
485
|
-
if (bytes[at + i] !== text.charCodeAt(i)) {
|
|
486
|
-
return false;
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
return true;
|
|
490
|
-
};
|
|
491
|
-
|
|
492
|
-
// The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
|
|
493
|
-
// beyond the first few bytes, that raw pixels all but never match.
|
|
494
|
-
const sniffImageFormat = bytes => {
|
|
495
|
-
const length = bytes.length;
|
|
496
|
-
if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
|
|
497
|
-
return 'PNG';
|
|
498
|
-
}
|
|
499
|
-
// JPEG: FF D8, then a first segment: a marker that has a length (not a restart or a stuffed byte) and a length that fits
|
|
500
|
-
if (length >= 6 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF && bytes[3] >= 0xC0 && bytes[3] <= 0xFE && !(bytes[3] >= 0xD0 && bytes[3] <= 0xD9) && (bytes[4] << 8 | bytes[5]) >= 2 && 4 + (bytes[4] << 8 | bytes[5]) <= length) {
|
|
501
|
-
return 'JPEG';
|
|
502
|
-
}
|
|
503
|
-
if (length >= 6 && (ascii(bytes, 0, 'GIF87a') || ascii(bytes, 0, 'GIF89a'))) {
|
|
504
|
-
return 'GIF';
|
|
505
|
-
}
|
|
506
|
-
if (length >= 12 && ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) {
|
|
507
|
-
return 'WebP';
|
|
508
|
-
}
|
|
509
|
-
// BMP: 'BM', then the file's own length and two zero reserved fields, and a known header size
|
|
510
|
-
if (length >= 18 && bytes[0] === 0x42 && bytes[1] === 0x4D && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0 && (bytes[2] | bytes[3] << 8 | bytes[4] << 16 | bytes[5] << 24) === length && [12, 40, 52, 56, 64, 108, 124].includes(bytes[14]) && bytes[15] === 0 && bytes[16] === 0 && bytes[17] === 0) {
|
|
511
|
-
return 'BMP';
|
|
512
|
-
}
|
|
513
|
-
// TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
|
|
514
|
-
if (length >= 12) {
|
|
515
|
-
const little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
|
|
516
|
-
const big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
|
|
517
|
-
if (little || big) {
|
|
518
|
-
const u16 = at => little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
|
|
519
|
-
const offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
|
|
520
|
-
if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
|
|
521
|
-
return 'TIFF';
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
// ISO base media: a 'ftyp' box, then a brand
|
|
526
|
-
if (length >= 12 && ascii(bytes, 4, 'ftyp')) {
|
|
527
|
-
if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
|
|
528
|
-
return 'AVIF';
|
|
529
|
-
}
|
|
530
|
-
if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
|
|
531
|
-
return 'HEIC';
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
return null;
|
|
535
|
-
};
|
|
536
|
-
|
|
537
473
|
// The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
|
|
538
474
|
// or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
|
|
539
475
|
// call returns; until then (the first call) a copy is kept for when it has loaded.
|
|
@@ -552,6 +488,19 @@ const checkSize = (pixels, size, name, argument) => {
|
|
|
552
488
|
throw (0, _shared.fail)('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
|
|
553
489
|
}
|
|
554
490
|
};
|
|
491
|
+
|
|
492
|
+
// 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,
|
|
493
|
+
// just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
|
|
494
|
+
const noWarning = () => {};
|
|
495
|
+
// A call whose signal is already aborted fails before any work, so it doesn't use the warning up either.
|
|
496
|
+
const warningFor = image => {
|
|
497
|
+
const warning = (0, _shared.bareImageWarning)(image);
|
|
498
|
+
return warning ? signal => {
|
|
499
|
+
if (!(signal && signal.aborted)) {
|
|
500
|
+
(0, _shared.warnOnce)(warning, image.byteLength);
|
|
501
|
+
}
|
|
502
|
+
} : noWarning;
|
|
503
|
+
};
|
|
555
504
|
const load = image => {
|
|
556
505
|
if ((0, _shared.isClustering)(image) || (0, _shared.isPalette)(image)) {
|
|
557
506
|
const what = (0, _shared.isClustering)(image) ? 'a clustering (from buildClustering)' : 'a palette';
|
|
@@ -562,9 +511,9 @@ const load = image => {
|
|
|
562
511
|
throw (0, _shared.detachedError)('bare');
|
|
563
512
|
}
|
|
564
513
|
if ((0, _shared.isUint8Array)(image)) {
|
|
565
|
-
const encoded = sniffImageFormat(image);
|
|
514
|
+
const encoded = (0, _shared.sniffImageFormat)(image);
|
|
566
515
|
if (encoded) {
|
|
567
|
-
throw (0, _shared.fail)('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode
|
|
516
|
+
throw (0, _shared.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');
|
|
568
517
|
}
|
|
569
518
|
if (image.length % 4 !== 0) {
|
|
570
519
|
throw (0, _shared.fail)('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
|
|
@@ -978,8 +927,10 @@ const noOptions = (name, extra) => {
|
|
|
978
927
|
// happens before the call returns.
|
|
979
928
|
|
|
980
929
|
const buildClustering = async (image, options) => {
|
|
930
|
+
const warn = warningFor(image);
|
|
981
931
|
image = load(image);
|
|
982
932
|
const o = parseOptions(options, clusterOptions, image);
|
|
933
|
+
warn(o.signal);
|
|
983
934
|
const wasm = Module || (await acquire());
|
|
984
935
|
if (isControlled(o)) {
|
|
985
936
|
const report = reporter(o);
|
|
@@ -993,9 +944,11 @@ const buildClustering = async (image, options) => {
|
|
|
993
944
|
exports.buildClustering = buildClustering;
|
|
994
945
|
const getClustering = exports.getClustering = buildClustering;
|
|
995
946
|
const buildPalette = async (image, k, options) => {
|
|
947
|
+
const warn = warningFor(image);
|
|
996
948
|
image = load(image);
|
|
997
949
|
k = check(k);
|
|
998
950
|
const o = parseOptions(options, clusterOptions, image);
|
|
951
|
+
warn(o.signal);
|
|
999
952
|
const wasm = Module || (await acquire());
|
|
1000
953
|
if (isControlled(o)) {
|
|
1001
954
|
const report = reporter(o);
|
|
@@ -1131,10 +1084,12 @@ const readInfo = async (name, clustering, extra) => {
|
|
|
1131
1084
|
const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
|
|
1132
1085
|
exports.getClusteringInfo = getClusteringInfo;
|
|
1133
1086
|
const quantize = async (image, k, options) => {
|
|
1087
|
+
const warn = warningFor(image);
|
|
1134
1088
|
const wrap = getWrapper(image);
|
|
1135
1089
|
image = load(image);
|
|
1136
1090
|
k = check(k);
|
|
1137
1091
|
const o = parseOptions(options, quantizeOptions, image);
|
|
1092
|
+
warn(o.signal);
|
|
1138
1093
|
const wasm = Module || (await acquire());
|
|
1139
1094
|
if (isControlled(o)) {
|
|
1140
1095
|
const report = reporter(o);
|
|
@@ -1148,12 +1103,14 @@ const quantize = async (image, k, options) => {
|
|
|
1148
1103
|
};
|
|
1149
1104
|
exports.quantize = quantize;
|
|
1150
1105
|
const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
1106
|
+
const warn = warningFor(image);
|
|
1151
1107
|
const wrap = getWrapper(image);
|
|
1152
1108
|
image = load(image);
|
|
1153
1109
|
(0, _shared.readHeader)(clustering);
|
|
1154
1110
|
k = check(k);
|
|
1155
1111
|
const o = parseOptions(options, mapOptions, image);
|
|
1156
1112
|
clustering = held(clustering);
|
|
1113
|
+
warn(o.signal);
|
|
1157
1114
|
const wasm = Module || (await acquire());
|
|
1158
1115
|
checkAborted(o.signal);
|
|
1159
1116
|
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
@@ -1162,6 +1119,7 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
|
1162
1119
|
};
|
|
1163
1120
|
exports.quantizeFromClustering = quantizeFromClustering;
|
|
1164
1121
|
const quantizeWithPalette = async (image, palette, options) => {
|
|
1122
|
+
const warn = warningFor(image);
|
|
1165
1123
|
const wrap = getWrapper(image);
|
|
1166
1124
|
image = load(image);
|
|
1167
1125
|
(0, _shared.checkPalette)(palette);
|
|
@@ -1169,6 +1127,7 @@ const quantizeWithPalette = async (image, palette, options) => {
|
|
|
1169
1127
|
checkNotEmpty(palette, image, 1);
|
|
1170
1128
|
const space = matchingSpace(o, palette);
|
|
1171
1129
|
palette = held(palette);
|
|
1130
|
+
warn(o.signal);
|
|
1172
1131
|
const wasm = Module || (await acquire());
|
|
1173
1132
|
checkAborted(o.signal);
|
|
1174
1133
|
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)));
|
|
@@ -1176,10 +1135,12 @@ const quantizeWithPalette = async (image, palette, options) => {
|
|
|
1176
1135
|
};
|
|
1177
1136
|
exports.quantizeWithPalette = quantizeWithPalette;
|
|
1178
1137
|
const quantizeToIndices = async (image, k, options) => {
|
|
1138
|
+
const warn = warningFor(image);
|
|
1179
1139
|
const original = image;
|
|
1180
1140
|
image = load(image);
|
|
1181
1141
|
k = check(k);
|
|
1182
1142
|
const o = parseOptions(options, quantizeIndexOptions, image);
|
|
1143
|
+
warn(o.signal);
|
|
1183
1144
|
const wasm = Module || (await acquire());
|
|
1184
1145
|
if (isControlled(o)) {
|
|
1185
1146
|
const report = reporter(o);
|
|
@@ -1193,12 +1154,14 @@ const quantizeToIndices = async (image, k, options) => {
|
|
|
1193
1154
|
};
|
|
1194
1155
|
exports.quantizeToIndices = quantizeToIndices;
|
|
1195
1156
|
const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
|
|
1157
|
+
const warn = warningFor(image);
|
|
1196
1158
|
const original = image;
|
|
1197
1159
|
image = load(image);
|
|
1198
1160
|
const header = (0, _shared.readHeader)(clustering);
|
|
1199
1161
|
k = check(k);
|
|
1200
1162
|
const o = parseOptions(options, mapIndexOptions, image);
|
|
1201
1163
|
clustering = held(clustering);
|
|
1164
|
+
warn(o.signal);
|
|
1202
1165
|
const wasm = Module || (await acquire());
|
|
1203
1166
|
checkAborted(o.signal);
|
|
1204
1167
|
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
@@ -1210,6 +1173,7 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
|
|
|
1210
1173
|
};
|
|
1211
1174
|
exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
|
|
1212
1175
|
const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
1176
|
+
const warn = warningFor(image);
|
|
1213
1177
|
const original = image;
|
|
1214
1178
|
image = load(image);
|
|
1215
1179
|
(0, _shared.checkPalette)(palette);
|
|
@@ -1218,6 +1182,7 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1218
1182
|
const space = matchingSpace(o, palette);
|
|
1219
1183
|
const paletteSpace = (0, _shared.isPalette)(palette) ? palette.colorSpace : (0, _shared.colorSpaceName)(space);
|
|
1220
1184
|
palette = held(palette);
|
|
1185
|
+
warn(o.signal);
|
|
1221
1186
|
const wasm = Module || (await acquire());
|
|
1222
1187
|
checkAborted(o.signal);
|
|
1223
1188
|
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);
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import createWasmModule from './clustering.js';
|
|
2
|
-
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 } from "./shared.mjs";
|
|
2
|
+
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 } from "./shared.mjs";
|
|
3
3
|
|
|
4
4
|
// The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
|
|
5
5
|
export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
|
|
@@ -394,70 +394,6 @@ const unpack = (wasm, pointer) => {
|
|
|
394
394
|
// A Uint8Array over exactly the same bytes, so views into a larger buffer (subarrays) stay views of their own range.
|
|
395
395
|
const bytes = data => isUint8Array(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
396
396
|
|
|
397
|
-
// ----- Encoded image files -------------------------------------------------------------------------------------------
|
|
398
|
-
// A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
|
|
399
|
-
// (fs.readFile, fetch().arrayBuffer()): it passes as pixels whenever its length is a multiple of 4 and gives a palette of
|
|
400
|
-
// nonsense. The signatures of the common formats are recognised so that it is reported instead. Only a bare Uint8Array is
|
|
401
|
-
// looked at: an ImageData or a { data, format } object has said what its bytes are, so it is never second-guessed, and a
|
|
402
|
-
// bare array that really is raw pixels can be passed as { data, format: 'rgba' } to say so.
|
|
403
|
-
//
|
|
404
|
-
// This is also where decoding would go. The library doesn't decode files today (that needs a decoder per format, and
|
|
405
|
-
// sharp, pngjs, createImageBitmap and the like already do it); when it does, a file recognised here is decoded into
|
|
406
|
-
// { data, format, width, height } instead of rejected, and `load` becomes asynchronous. See docs/ROADMAP.md.
|
|
407
|
-
const ascii = (bytes, at, text) => {
|
|
408
|
-
for (let i = 0; i < text.length; i++) {
|
|
409
|
-
if (bytes[at + i] !== text.charCodeAt(i)) {
|
|
410
|
-
return false;
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
return true;
|
|
414
|
-
};
|
|
415
|
-
|
|
416
|
-
// The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
|
|
417
|
-
// beyond the first few bytes, that raw pixels all but never match.
|
|
418
|
-
const sniffImageFormat = bytes => {
|
|
419
|
-
const length = bytes.length;
|
|
420
|
-
if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
|
|
421
|
-
return 'PNG';
|
|
422
|
-
}
|
|
423
|
-
// JPEG: FF D8, then a first segment: a marker that has a length (not a restart or a stuffed byte) and a length that fits
|
|
424
|
-
if (length >= 6 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF && bytes[3] >= 0xC0 && bytes[3] <= 0xFE && !(bytes[3] >= 0xD0 && bytes[3] <= 0xD9) && (bytes[4] << 8 | bytes[5]) >= 2 && 4 + (bytes[4] << 8 | bytes[5]) <= length) {
|
|
425
|
-
return 'JPEG';
|
|
426
|
-
}
|
|
427
|
-
if (length >= 6 && (ascii(bytes, 0, 'GIF87a') || ascii(bytes, 0, 'GIF89a'))) {
|
|
428
|
-
return 'GIF';
|
|
429
|
-
}
|
|
430
|
-
if (length >= 12 && ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) {
|
|
431
|
-
return 'WebP';
|
|
432
|
-
}
|
|
433
|
-
// BMP: 'BM', then the file's own length and two zero reserved fields, and a known header size
|
|
434
|
-
if (length >= 18 && bytes[0] === 0x42 && bytes[1] === 0x4D && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0 && (bytes[2] | bytes[3] << 8 | bytes[4] << 16 | bytes[5] << 24) === length && [12, 40, 52, 56, 64, 108, 124].includes(bytes[14]) && bytes[15] === 0 && bytes[16] === 0 && bytes[17] === 0) {
|
|
435
|
-
return 'BMP';
|
|
436
|
-
}
|
|
437
|
-
// TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
|
|
438
|
-
if (length >= 12) {
|
|
439
|
-
const little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
|
|
440
|
-
const big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
|
|
441
|
-
if (little || big) {
|
|
442
|
-
const u16 = at => little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
|
|
443
|
-
const offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
|
|
444
|
-
if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
|
|
445
|
-
return 'TIFF';
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
// ISO base media: a 'ftyp' box, then a brand
|
|
450
|
-
if (length >= 12 && ascii(bytes, 4, 'ftyp')) {
|
|
451
|
-
if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
|
|
452
|
-
return 'AVIF';
|
|
453
|
-
}
|
|
454
|
-
if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
|
|
455
|
-
return 'HEIC';
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
return null;
|
|
459
|
-
};
|
|
460
|
-
|
|
461
397
|
// The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
|
|
462
398
|
// or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
|
|
463
399
|
// call returns; until then (the first call) a copy is kept for when it has loaded.
|
|
@@ -476,6 +412,19 @@ const checkSize = (pixels, size, name, argument) => {
|
|
|
476
412
|
throw fail('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
|
|
477
413
|
}
|
|
478
414
|
};
|
|
415
|
+
|
|
416
|
+
// 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,
|
|
417
|
+
// just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
|
|
418
|
+
const noWarning = () => {};
|
|
419
|
+
// A call whose signal is already aborted fails before any work, so it doesn't use the warning up either.
|
|
420
|
+
const warningFor = image => {
|
|
421
|
+
const warning = bareImageWarning(image);
|
|
422
|
+
return warning ? signal => {
|
|
423
|
+
if (!(signal && signal.aborted)) {
|
|
424
|
+
warnOnce(warning, image.byteLength);
|
|
425
|
+
}
|
|
426
|
+
} : noWarning;
|
|
427
|
+
};
|
|
479
428
|
const load = image => {
|
|
480
429
|
if (isClustering(image) || isPalette(image)) {
|
|
481
430
|
const what = isClustering(image) ? 'a clustering (from buildClustering)' : 'a palette';
|
|
@@ -488,7 +437,7 @@ const load = image => {
|
|
|
488
437
|
if (isUint8Array(image)) {
|
|
489
438
|
const encoded = sniffImageFormat(image);
|
|
490
439
|
if (encoded) {
|
|
491
|
-
throw fail('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode
|
|
440
|
+
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');
|
|
492
441
|
}
|
|
493
442
|
if (image.length % 4 !== 0) {
|
|
494
443
|
throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
|
|
@@ -902,8 +851,10 @@ const noOptions = (name, extra) => {
|
|
|
902
851
|
// happens before the call returns.
|
|
903
852
|
|
|
904
853
|
export const buildClustering = async (image, options) => {
|
|
854
|
+
const warn = warningFor(image);
|
|
905
855
|
image = load(image);
|
|
906
856
|
const o = parseOptions(options, clusterOptions, image);
|
|
857
|
+
warn(o.signal);
|
|
907
858
|
const wasm = Module || (await acquire());
|
|
908
859
|
if (isControlled(o)) {
|
|
909
860
|
const report = reporter(o);
|
|
@@ -916,9 +867,11 @@ export const buildClustering = async (image, options) => {
|
|
|
916
867
|
/** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
|
|
917
868
|
export const getClustering = buildClustering;
|
|
918
869
|
export const buildPalette = async (image, k, options) => {
|
|
870
|
+
const warn = warningFor(image);
|
|
919
871
|
image = load(image);
|
|
920
872
|
k = check(k);
|
|
921
873
|
const o = parseOptions(options, clusterOptions, image);
|
|
874
|
+
warn(o.signal);
|
|
922
875
|
const wasm = Module || (await acquire());
|
|
923
876
|
if (isControlled(o)) {
|
|
924
877
|
const report = reporter(o);
|
|
@@ -1049,10 +1002,12 @@ const readInfo = async (name, clustering, extra) => {
|
|
|
1049
1002
|
};
|
|
1050
1003
|
export const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
|
|
1051
1004
|
export const quantize = async (image, k, options) => {
|
|
1005
|
+
const warn = warningFor(image);
|
|
1052
1006
|
const wrap = getWrapper(image);
|
|
1053
1007
|
image = load(image);
|
|
1054
1008
|
k = check(k);
|
|
1055
1009
|
const o = parseOptions(options, quantizeOptions, image);
|
|
1010
|
+
warn(o.signal);
|
|
1056
1011
|
const wasm = Module || (await acquire());
|
|
1057
1012
|
if (isControlled(o)) {
|
|
1058
1013
|
const report = reporter(o);
|
|
@@ -1065,12 +1020,14 @@ export const quantize = async (image, k, options) => {
|
|
|
1065
1020
|
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));
|
|
1066
1021
|
};
|
|
1067
1022
|
export const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
1023
|
+
const warn = warningFor(image);
|
|
1068
1024
|
const wrap = getWrapper(image);
|
|
1069
1025
|
image = load(image);
|
|
1070
1026
|
readHeader(clustering);
|
|
1071
1027
|
k = check(k);
|
|
1072
1028
|
const o = parseOptions(options, mapOptions, image);
|
|
1073
1029
|
clustering = held(clustering);
|
|
1030
|
+
warn(o.signal);
|
|
1074
1031
|
const wasm = Module || (await acquire());
|
|
1075
1032
|
checkAborted(o.signal);
|
|
1076
1033
|
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
@@ -1078,6 +1035,7 @@ export const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
|
1078
1035
|
return result;
|
|
1079
1036
|
};
|
|
1080
1037
|
export const quantizeWithPalette = async (image, palette, options) => {
|
|
1038
|
+
const warn = warningFor(image);
|
|
1081
1039
|
const wrap = getWrapper(image);
|
|
1082
1040
|
image = load(image);
|
|
1083
1041
|
checkPalette(palette);
|
|
@@ -1085,16 +1043,19 @@ export const quantizeWithPalette = async (image, palette, options) => {
|
|
|
1085
1043
|
checkNotEmpty(palette, image, 1);
|
|
1086
1044
|
const space = matchingSpace(o, palette);
|
|
1087
1045
|
palette = held(palette);
|
|
1046
|
+
warn(o.signal);
|
|
1088
1047
|
const wasm = Module || (await acquire());
|
|
1089
1048
|
checkAborted(o.signal);
|
|
1090
1049
|
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)));
|
|
1091
1050
|
return result;
|
|
1092
1051
|
};
|
|
1093
1052
|
export const quantizeToIndices = async (image, k, options) => {
|
|
1053
|
+
const warn = warningFor(image);
|
|
1094
1054
|
const original = image;
|
|
1095
1055
|
image = load(image);
|
|
1096
1056
|
k = check(k);
|
|
1097
1057
|
const o = parseOptions(options, quantizeIndexOptions, image);
|
|
1058
|
+
warn(o.signal);
|
|
1098
1059
|
const wasm = Module || (await acquire());
|
|
1099
1060
|
if (isControlled(o)) {
|
|
1100
1061
|
const report = reporter(o);
|
|
@@ -1107,12 +1068,14 @@ export const quantizeToIndices = async (image, k, options) => {
|
|
|
1107
1068
|
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));
|
|
1108
1069
|
};
|
|
1109
1070
|
export const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
|
|
1071
|
+
const warn = warningFor(image);
|
|
1110
1072
|
const original = image;
|
|
1111
1073
|
image = load(image);
|
|
1112
1074
|
const header = readHeader(clustering);
|
|
1113
1075
|
k = check(k);
|
|
1114
1076
|
const o = parseOptions(options, mapIndexOptions, image);
|
|
1115
1077
|
clustering = held(clustering);
|
|
1078
|
+
warn(o.signal);
|
|
1116
1079
|
const wasm = Module || (await acquire());
|
|
1117
1080
|
checkAborted(o.signal);
|
|
1118
1081
|
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
@@ -1123,6 +1086,7 @@ export const quantizeToIndicesFromClustering = async (image, clustering, k, opti
|
|
|
1123
1086
|
return result;
|
|
1124
1087
|
};
|
|
1125
1088
|
export const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
1089
|
+
const warn = warningFor(image);
|
|
1126
1090
|
const original = image;
|
|
1127
1091
|
image = load(image);
|
|
1128
1092
|
checkPalette(palette);
|
|
@@ -1131,6 +1095,7 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1131
1095
|
const space = matchingSpace(o, palette);
|
|
1132
1096
|
const paletteSpace = isPalette(palette) ? palette.colorSpace : colorSpaceName(space);
|
|
1133
1097
|
palette = held(palette);
|
|
1098
|
+
warn(o.signal);
|
|
1134
1099
|
const wasm = Module || (await acquire());
|
|
1135
1100
|
checkAborted(o.signal);
|
|
1136
1101
|
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);
|
package/dist/shared.cjs
CHANGED
|
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.Clustering = Clustering;
|
|
7
7
|
exports.MARK = void 0;
|
|
8
8
|
exports.Palette = Palette;
|
|
9
|
-
exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.setEngine = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = exports.alphaModes = void 0;
|
|
9
|
+
exports.warnOnce = exports.version = exports.tooLarge = exports.sniffImageFormat = exports.snapshot = exports.sizeText = exports.silenceWarnings = exports.setEngine = exports.revive = exports.resetWarnings = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.looksLikeRgb = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = exports.bareLayout = exports.bareImageWarning = exports.alphaModes = void 0;
|
|
10
10
|
// Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
|
|
11
11
|
// header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
|
|
12
12
|
// './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
|
|
13
13
|
|
|
14
14
|
// The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
|
|
15
15
|
// is built from, src/version.hpp) in step with it. Do not edit it by hand.
|
|
16
|
-
const version = exports.version = '3.
|
|
16
|
+
const version = exports.version = '3.6.0';
|
|
17
17
|
const colorSpaceCodes = exports.colorSpaceCodes = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
|
@@ -306,9 +306,256 @@ const clusteringBrand = Symbol.for('agglomerative-clustering.clustering');
|
|
|
306
306
|
const isPalette = value => isUint8Array(value) && value[paletteBrand] === true;
|
|
307
307
|
exports.isPalette = isPalette;
|
|
308
308
|
const isClustering = value => isUint8Array(value) && value[clusteringBrand] === true;
|
|
309
|
+
|
|
310
|
+
// ----- Encoded image files -------------------------------------------------------------------------------------------
|
|
311
|
+
// A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
|
|
312
|
+
// (fs.readFile, fetch().arrayBuffer()): it passes as pixels whenever its length is a multiple of 4 and gives a palette of
|
|
313
|
+
// nonsense. The signatures of the common formats are recognised so that it is reported instead. Only a bare Uint8Array is
|
|
314
|
+
// looked at: an ImageData or a { data, format } object has said what its bytes are, so it is never second-guessed, and a
|
|
315
|
+
// bare array that really is raw pixels can be passed as { data, format: 'rgba' } to say so.
|
|
316
|
+
//
|
|
317
|
+
// Decoding is left to the caller: the library has no decoders and no dependency on one (PRINCIPLES "Settled
|
|
318
|
+
// decisions"), and the guides' "Decoding image files" gives a recipe per environment, which the message points to.
|
|
319
|
+
exports.isClustering = isClustering;
|
|
320
|
+
const ascii = (bytes, at, text) => {
|
|
321
|
+
for (let i = 0; i < text.length; i++) {
|
|
322
|
+
if (bytes[at + i] !== text.charCodeAt(i)) {
|
|
323
|
+
return false;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return true;
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
// The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
|
|
330
|
+
// beyond the first few bytes, that raw pixels all but never match.
|
|
331
|
+
const sniffImageFormat = bytes => {
|
|
332
|
+
const length = bytes.length;
|
|
333
|
+
if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
|
|
334
|
+
return 'PNG';
|
|
335
|
+
}
|
|
336
|
+
// JPEG: FF D8, then a first segment: a marker that has a length (not a restart or a stuffed byte) and a length that fits
|
|
337
|
+
if (length >= 6 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF && bytes[3] >= 0xC0 && bytes[3] <= 0xFE && !(bytes[3] >= 0xD0 && bytes[3] <= 0xD9) && (bytes[4] << 8 | bytes[5]) >= 2 && 4 + (bytes[4] << 8 | bytes[5]) <= length) {
|
|
338
|
+
return 'JPEG';
|
|
339
|
+
}
|
|
340
|
+
if (length >= 6 && (ascii(bytes, 0, 'GIF87a') || ascii(bytes, 0, 'GIF89a'))) {
|
|
341
|
+
return 'GIF';
|
|
342
|
+
}
|
|
343
|
+
if (length >= 12 && ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) {
|
|
344
|
+
return 'WebP';
|
|
345
|
+
}
|
|
346
|
+
// BMP: 'BM', then the file's own length and two zero reserved fields, and a known header size
|
|
347
|
+
if (length >= 18 && bytes[0] === 0x42 && bytes[1] === 0x4D && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0 && (bytes[2] | bytes[3] << 8 | bytes[4] << 16 | bytes[5] << 24) === length && [12, 40, 52, 56, 64, 108, 124].includes(bytes[14]) && bytes[15] === 0 && bytes[16] === 0 && bytes[17] === 0) {
|
|
348
|
+
return 'BMP';
|
|
349
|
+
}
|
|
350
|
+
// TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
|
|
351
|
+
if (length >= 12) {
|
|
352
|
+
const little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
|
|
353
|
+
const big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
|
|
354
|
+
if (little || big) {
|
|
355
|
+
const u16 = at => little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
|
|
356
|
+
const offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
|
|
357
|
+
if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
|
|
358
|
+
return 'TIFF';
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
// ISO base media: a 'ftyp' box, then a brand
|
|
363
|
+
if (length >= 12 && ascii(bytes, 4, 'ftyp')) {
|
|
364
|
+
if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
|
|
365
|
+
return 'AVIF';
|
|
366
|
+
}
|
|
367
|
+
if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
|
|
368
|
+
return 'HEIC';
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return null;
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
// ----- RGB and grey bytes passed bare -------------------------------------------------------------------------------
|
|
375
|
+
// The other common way to get a bare array wrong is bytes of another layout: RGB (sharp's plain .raw()), or grey and grey
|
|
376
|
+
// with alpha (fast-png's decode() of a grey PNG). Read as RGBA, every pixel takes bytes from its neighbours and one of them
|
|
377
|
+
// as its alpha, and nothing fails while the length divides by 4. They are never reinterpreted (a bare array is RGBA,
|
|
378
|
+
// PRINCIPLES), only reported: a warning in 3.x, an error from 4.0.
|
|
379
|
+
//
|
|
380
|
+
// The rules use E(k), the mean change between a byte and the one k before it (bench/spikes/bare-rgb/ and
|
|
381
|
+
// bench/spikes/bare-grey/: no false positives on 2,984 real RGBA images).
|
|
382
|
+
// - RGB, decided first: real RGBA changes least at a step of 4, RGB at a step of 3. A premultiplied white mask,
|
|
383
|
+
// (a, a, a, a), also scores high, so pixels with four equal bytes overrule it. Grey RGB is too smooth for that score,
|
|
384
|
+
// but where it changes its bytes come in equal triples at a step of 3 and not of 4.
|
|
385
|
+
// - 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.
|
|
386
|
+
// - Grey (1 byte a pixel): smoothest at a step of 1, unless most changing pixels have four equal bytes, which is real
|
|
387
|
+
// RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same; it then keeps the
|
|
388
|
+
// rgb-as-rgba code, whose text covers grey too.
|
|
389
|
+
// Units equal to the one before are skipped by the equal-byte counts, since flat areas read the same either way. It
|
|
390
|
+
// samples 512 windows of 96 bytes (each on a multiple of 12, a pixel under every reading, one in each 512th of the
|
|
391
|
+
// array), so it costs about 0.35 ms at any size. Returns 'rgb', 'grey', 'grey-alpha' or null.
|
|
392
|
+
exports.sniffImageFormat = sniffImageFormat;
|
|
393
|
+
const bareFloor = 192,
|
|
394
|
+
bareWindow = 96,
|
|
395
|
+
bareWindows = 512;
|
|
396
|
+
const bareLayout = d => {
|
|
397
|
+
if (d.length < bareFloor) {
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
const whole = d.length <= bareWindow * bareWindows;
|
|
401
|
+
const windows = whole ? 1 : bareWindows,
|
|
402
|
+
size = whole ? d.length : bareWindow;
|
|
403
|
+
const step = whole ? 0 : Math.floor((d.length - bareWindow) / (bareWindows - 1) / 12) * 12;
|
|
404
|
+
// Each window starts at a fixed pseudo-random multiple of 12 within its slot. Evenly spaced starts would alias with
|
|
405
|
+
// the image's rows (768×512 RGBA spaces them exactly one row apart), so every window would see only the left edge,
|
|
406
|
+
// and a cutout's transparent margin would hide the rest of the image.
|
|
407
|
+
const slots = step / 12,
|
|
408
|
+
last = d.length - size;
|
|
409
|
+
const startOf = w => whole ? 0 : Math.min(w * step + (Math.imul(w + 1, 0x9E3779B1) >>> 0) % slots * 12, last - last % 12);
|
|
410
|
+
let e1 = 0,
|
|
411
|
+
e2 = 0,
|
|
412
|
+
e3 = 0,
|
|
413
|
+
e4 = 0,
|
|
414
|
+
n = 0,
|
|
415
|
+
g3 = 0,
|
|
416
|
+
n3 = 0,
|
|
417
|
+
g4 = 0,
|
|
418
|
+
q4 = 0,
|
|
419
|
+
n4 = 0;
|
|
420
|
+
for (let w = 0; w < windows; w++) {
|
|
421
|
+
const start = startOf(w),
|
|
422
|
+
end = start + size;
|
|
423
|
+
for (let i = start + 4; i < end; i++) {
|
|
424
|
+
const v = d[i],
|
|
425
|
+
a = v - d[i - 1],
|
|
426
|
+
b = v - d[i - 2],
|
|
427
|
+
c = v - d[i - 3],
|
|
428
|
+
e = v - d[i - 4];
|
|
429
|
+
e1 += a < 0 ? -a : a;
|
|
430
|
+
e2 += b < 0 ? -b : b;
|
|
431
|
+
e3 += c < 0 ? -c : c;
|
|
432
|
+
e4 += e < 0 ? -e : e;
|
|
433
|
+
}
|
|
434
|
+
n += size - 4;
|
|
435
|
+
for (let i = start + 3; i + 2 < end; i += 3) {
|
|
436
|
+
if (d[i] === d[i - 3] && d[i + 1] === d[i - 2] && d[i + 2] === d[i - 1]) {
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
n3++;
|
|
440
|
+
if (d[i] === d[i + 1] && d[i] === d[i + 2]) {
|
|
441
|
+
g3++;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
for (let i = start + 4; i + 3 < end; i += 4) {
|
|
445
|
+
if (d[i] === d[i - 4] && d[i + 1] === d[i - 3] && d[i + 2] === d[i - 2] && d[i + 3] === d[i - 1]) {
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
n4++;
|
|
449
|
+
if (d[i] === d[i + 1] && d[i] === d[i + 2]) {
|
|
450
|
+
g4++;
|
|
451
|
+
if (d[i] === d[i + 3]) {
|
|
452
|
+
q4++;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
const E1 = e1 / n + 0.05,
|
|
458
|
+
E2 = e2 / n + 0.05,
|
|
459
|
+
E3 = e3 / n + 0.05,
|
|
460
|
+
E4 = e4 / n + 0.05;
|
|
461
|
+
const fewQuads = q4 < 0.5 * Math.max(1, n4);
|
|
462
|
+
const layout = E4 / E3 > 1.25 && fewQuads || g3 > 0.9 * Math.max(1, n3) && g4 < 0.6 * Math.max(1, n4) ? 'rgb' : E4 / E2 > 1.1 && E2 / E1 < 0.5 ? 'grey-alpha' : E4 / E1 > 1.5 && fewQuads ? 'grey' : null;
|
|
463
|
+
if (layout === null) {
|
|
464
|
+
return null;
|
|
465
|
+
}
|
|
466
|
+
// Bytes that mostly rise by one fixed step ((i * k) & 255, the usual fake image in tests) are pixels of no layout, and
|
|
467
|
+
// score 4/3 as RGB or 4 as grey whatever the step. Counted only for arrays about to be flagged, a second pass over the
|
|
468
|
+
// same windows, so RGBA (the usual input) doesn't pay for it.
|
|
469
|
+
let ramp = 0;
|
|
470
|
+
for (let w = 0; w < windows; w++) {
|
|
471
|
+
const start = startOf(w),
|
|
472
|
+
end = start + size;
|
|
473
|
+
for (let i = start + 4; i < end; i++) {
|
|
474
|
+
const rise = d[i] - d[i - 1] & 255;
|
|
475
|
+
if (rise !== 0 && rise === (d[i - 1] - d[i - 2] & 255)) {
|
|
476
|
+
ramp++;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
return ramp <= 0.5 * n ? layout : null;
|
|
481
|
+
};
|
|
482
|
+
exports.bareLayout = bareLayout;
|
|
483
|
+
const looksLikeRgb = d => bareLayout(d) === 'rgb';
|
|
484
|
+
|
|
485
|
+
// Codes already warned in this copy of the library (PRINCIPLES: once per code, per copy).
|
|
486
|
+
exports.looksLikeRgb = looksLikeRgb;
|
|
487
|
+
const warned = new Set();
|
|
488
|
+
const bareCodes = {
|
|
489
|
+
rgb: 'rgb-as-rgba',
|
|
490
|
+
grey: 'gray-as-rgba',
|
|
491
|
+
'grey-alpha': 'gray-as-rgba'
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
// The warning a bare image calls for, as {code, layout}, or null. It skips everything the main entry rejects (palettes
|
|
495
|
+
// and clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never both warns
|
|
496
|
+
// about its image and rejects it, and both entries share this one order. An array of one layout never takes another's
|
|
497
|
+
// code because its own was already used: it is classified first, and only then is its code checked.
|
|
498
|
+
const bareImageWarning = image => {
|
|
499
|
+
if (warned.has('rgb-as-rgba') && warned.has('gray-as-rgba') || !isUint8Array(image) || isPalette(image) || isClustering(image)) {
|
|
500
|
+
return null;
|
|
501
|
+
}
|
|
502
|
+
if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
|
|
503
|
+
return null;
|
|
504
|
+
}
|
|
505
|
+
const layout = bareLayout(image);
|
|
506
|
+
return layout === null || warned.has(bareCodes[layout]) ? null : {
|
|
507
|
+
code: bareCodes[layout],
|
|
508
|
+
layout
|
|
509
|
+
};
|
|
510
|
+
};
|
|
511
|
+
|
|
512
|
+
// The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
|
|
513
|
+
// process.on('warning') and --trace-warnings then work), else console.warn. Runtimes that imitate Node have an
|
|
514
|
+
// emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
|
|
515
|
+
// navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
|
|
516
|
+
// keeps Parcel from adding one.
|
|
517
|
+
exports.bareImageWarning = bareImageWarning;
|
|
518
|
+
const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
|
|
519
|
+
const warningText = {
|
|
520
|
+
'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.`,
|
|
521
|
+
'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.`
|
|
522
|
+
};
|
|
523
|
+
// `warning` is what bareImageWarning returned: {code, layout}.
|
|
524
|
+
const warnOnce = ({
|
|
525
|
+
code,
|
|
526
|
+
layout
|
|
527
|
+
}, byteLength) => {
|
|
528
|
+
if (warned.has(code)) {
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
warned.add(code);
|
|
532
|
+
const message = warningText[code](byteLength, layout);
|
|
533
|
+
const runtime = globalThis.process;
|
|
534
|
+
if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
|
|
535
|
+
runtime.emitWarning(message, {
|
|
536
|
+
type: 'AgglomerativeClusteringWarning',
|
|
537
|
+
code
|
|
538
|
+
});
|
|
539
|
+
} else if (typeof console !== 'undefined') {
|
|
540
|
+
console.warn(`agglomerative-clustering [${code}]: ${message}`);
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
// The worker thread's copy: its caller's side checks and warns (PRINCIPLES), so here every code counts as warned, which
|
|
544
|
+
// also skips the sampling.
|
|
545
|
+
exports.warnOnce = warnOnce;
|
|
546
|
+
const silenceWarnings = () => {
|
|
547
|
+
for (const code of Object.keys(warningText)) {
|
|
548
|
+
warned.add(code);
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
// For tests.
|
|
552
|
+
exports.silenceWarnings = silenceWarnings;
|
|
553
|
+
const resetWarnings = () => {
|
|
554
|
+
warned.clear();
|
|
555
|
+
};
|
|
309
556
|
// Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
|
|
310
557
|
// `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
|
|
311
|
-
exports.
|
|
558
|
+
exports.resetWarnings = resetWarnings;
|
|
312
559
|
const inspect = Symbol.for('nodejs.util.inspect.custom');
|
|
313
560
|
const view = label => function (depth, options, nodeInspect) {
|
|
314
561
|
const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
|
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 = '3.
|
|
7
|
+
export const version = '3.6.0';
|
|
8
8
|
export const colorSpaceCodes = {
|
|
9
9
|
'rgb': 0,
|
|
10
10
|
'oklab': 1
|
|
@@ -276,6 +276,246 @@ const paletteBrand = Symbol.for('agglomerative-clustering.palette');
|
|
|
276
276
|
const clusteringBrand = Symbol.for('agglomerative-clustering.clustering');
|
|
277
277
|
export const isPalette = value => isUint8Array(value) && value[paletteBrand] === true;
|
|
278
278
|
export const isClustering = value => isUint8Array(value) && value[clusteringBrand] === true;
|
|
279
|
+
|
|
280
|
+
// ----- Encoded image files -------------------------------------------------------------------------------------------
|
|
281
|
+
// A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
|
|
282
|
+
// (fs.readFile, fetch().arrayBuffer()): it passes as pixels whenever its length is a multiple of 4 and gives a palette of
|
|
283
|
+
// nonsense. The signatures of the common formats are recognised so that it is reported instead. Only a bare Uint8Array is
|
|
284
|
+
// looked at: an ImageData or a { data, format } object has said what its bytes are, so it is never second-guessed, and a
|
|
285
|
+
// bare array that really is raw pixels can be passed as { data, format: 'rgba' } to say so.
|
|
286
|
+
//
|
|
287
|
+
// Decoding is left to the caller: the library has no decoders and no dependency on one (PRINCIPLES "Settled
|
|
288
|
+
// decisions"), and the guides' "Decoding image files" gives a recipe per environment, which the message points to.
|
|
289
|
+
const ascii = (bytes, at, text) => {
|
|
290
|
+
for (let i = 0; i < text.length; i++) {
|
|
291
|
+
if (bytes[at + i] !== text.charCodeAt(i)) {
|
|
292
|
+
return false;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return true;
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
// The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
|
|
299
|
+
// beyond the first few bytes, that raw pixels all but never match.
|
|
300
|
+
export const sniffImageFormat = bytes => {
|
|
301
|
+
const length = bytes.length;
|
|
302
|
+
if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
|
|
303
|
+
return 'PNG';
|
|
304
|
+
}
|
|
305
|
+
// JPEG: FF D8, then a first segment: a marker that has a length (not a restart or a stuffed byte) and a length that fits
|
|
306
|
+
if (length >= 6 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF && bytes[3] >= 0xC0 && bytes[3] <= 0xFE && !(bytes[3] >= 0xD0 && bytes[3] <= 0xD9) && (bytes[4] << 8 | bytes[5]) >= 2 && 4 + (bytes[4] << 8 | bytes[5]) <= length) {
|
|
307
|
+
return 'JPEG';
|
|
308
|
+
}
|
|
309
|
+
if (length >= 6 && (ascii(bytes, 0, 'GIF87a') || ascii(bytes, 0, 'GIF89a'))) {
|
|
310
|
+
return 'GIF';
|
|
311
|
+
}
|
|
312
|
+
if (length >= 12 && ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) {
|
|
313
|
+
return 'WebP';
|
|
314
|
+
}
|
|
315
|
+
// BMP: 'BM', then the file's own length and two zero reserved fields, and a known header size
|
|
316
|
+
if (length >= 18 && bytes[0] === 0x42 && bytes[1] === 0x4D && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0 && (bytes[2] | bytes[3] << 8 | bytes[4] << 16 | bytes[5] << 24) === length && [12, 40, 52, 56, 64, 108, 124].includes(bytes[14]) && bytes[15] === 0 && bytes[16] === 0 && bytes[17] === 0) {
|
|
317
|
+
return 'BMP';
|
|
318
|
+
}
|
|
319
|
+
// TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
|
|
320
|
+
if (length >= 12) {
|
|
321
|
+
const little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
|
|
322
|
+
const big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
|
|
323
|
+
if (little || big) {
|
|
324
|
+
const u16 = at => little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
|
|
325
|
+
const offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
|
|
326
|
+
if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
|
|
327
|
+
return 'TIFF';
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
// ISO base media: a 'ftyp' box, then a brand
|
|
332
|
+
if (length >= 12 && ascii(bytes, 4, 'ftyp')) {
|
|
333
|
+
if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
|
|
334
|
+
return 'AVIF';
|
|
335
|
+
}
|
|
336
|
+
if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
|
|
337
|
+
return 'HEIC';
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return null;
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
// ----- RGB and grey bytes passed bare -------------------------------------------------------------------------------
|
|
344
|
+
// The other common way to get a bare array wrong is bytes of another layout: RGB (sharp's plain .raw()), or grey and grey
|
|
345
|
+
// with alpha (fast-png's decode() of a grey PNG). Read as RGBA, every pixel takes bytes from its neighbours and one of them
|
|
346
|
+
// as its alpha, and nothing fails while the length divides by 4. They are never reinterpreted (a bare array is RGBA,
|
|
347
|
+
// PRINCIPLES), only reported: a warning in 3.x, an error from 4.0.
|
|
348
|
+
//
|
|
349
|
+
// The rules use E(k), the mean change between a byte and the one k before it (bench/spikes/bare-rgb/ and
|
|
350
|
+
// bench/spikes/bare-grey/: no false positives on 2,984 real RGBA images).
|
|
351
|
+
// - RGB, decided first: real RGBA changes least at a step of 4, RGB at a step of 3. A premultiplied white mask,
|
|
352
|
+
// (a, a, a, a), also scores high, so pixels with four equal bytes overrule it. Grey RGB is too smooth for that score,
|
|
353
|
+
// but where it changes its bytes come in equal triples at a step of 3 and not of 4.
|
|
354
|
+
// - 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.
|
|
355
|
+
// - Grey (1 byte a pixel): smoothest at a step of 1, unless most changing pixels have four equal bytes, which is real
|
|
356
|
+
// RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same; it then keeps the
|
|
357
|
+
// rgb-as-rgba code, whose text covers grey too.
|
|
358
|
+
// Units equal to the one before are skipped by the equal-byte counts, since flat areas read the same either way. It
|
|
359
|
+
// samples 512 windows of 96 bytes (each on a multiple of 12, a pixel under every reading, one in each 512th of the
|
|
360
|
+
// array), so it costs about 0.35 ms at any size. Returns 'rgb', 'grey', 'grey-alpha' or null.
|
|
361
|
+
const bareFloor = 192,
|
|
362
|
+
bareWindow = 96,
|
|
363
|
+
bareWindows = 512;
|
|
364
|
+
export const bareLayout = d => {
|
|
365
|
+
if (d.length < bareFloor) {
|
|
366
|
+
return null;
|
|
367
|
+
}
|
|
368
|
+
const whole = d.length <= bareWindow * bareWindows;
|
|
369
|
+
const windows = whole ? 1 : bareWindows,
|
|
370
|
+
size = whole ? d.length : bareWindow;
|
|
371
|
+
const step = whole ? 0 : Math.floor((d.length - bareWindow) / (bareWindows - 1) / 12) * 12;
|
|
372
|
+
// Each window starts at a fixed pseudo-random multiple of 12 within its slot. Evenly spaced starts would alias with
|
|
373
|
+
// the image's rows (768×512 RGBA spaces them exactly one row apart), so every window would see only the left edge,
|
|
374
|
+
// and a cutout's transparent margin would hide the rest of the image.
|
|
375
|
+
const slots = step / 12,
|
|
376
|
+
last = d.length - size;
|
|
377
|
+
const startOf = w => whole ? 0 : Math.min(w * step + (Math.imul(w + 1, 0x9E3779B1) >>> 0) % slots * 12, last - last % 12);
|
|
378
|
+
let e1 = 0,
|
|
379
|
+
e2 = 0,
|
|
380
|
+
e3 = 0,
|
|
381
|
+
e4 = 0,
|
|
382
|
+
n = 0,
|
|
383
|
+
g3 = 0,
|
|
384
|
+
n3 = 0,
|
|
385
|
+
g4 = 0,
|
|
386
|
+
q4 = 0,
|
|
387
|
+
n4 = 0;
|
|
388
|
+
for (let w = 0; w < windows; w++) {
|
|
389
|
+
const start = startOf(w),
|
|
390
|
+
end = start + size;
|
|
391
|
+
for (let i = start + 4; i < end; i++) {
|
|
392
|
+
const v = d[i],
|
|
393
|
+
a = v - d[i - 1],
|
|
394
|
+
b = v - d[i - 2],
|
|
395
|
+
c = v - d[i - 3],
|
|
396
|
+
e = v - d[i - 4];
|
|
397
|
+
e1 += a < 0 ? -a : a;
|
|
398
|
+
e2 += b < 0 ? -b : b;
|
|
399
|
+
e3 += c < 0 ? -c : c;
|
|
400
|
+
e4 += e < 0 ? -e : e;
|
|
401
|
+
}
|
|
402
|
+
n += size - 4;
|
|
403
|
+
for (let i = start + 3; i + 2 < end; i += 3) {
|
|
404
|
+
if (d[i] === d[i - 3] && d[i + 1] === d[i - 2] && d[i + 2] === d[i - 1]) {
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
n3++;
|
|
408
|
+
if (d[i] === d[i + 1] && d[i] === d[i + 2]) {
|
|
409
|
+
g3++;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
for (let i = start + 4; i + 3 < end; i += 4) {
|
|
413
|
+
if (d[i] === d[i - 4] && d[i + 1] === d[i - 3] && d[i + 2] === d[i - 2] && d[i + 3] === d[i - 1]) {
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
n4++;
|
|
417
|
+
if (d[i] === d[i + 1] && d[i] === d[i + 2]) {
|
|
418
|
+
g4++;
|
|
419
|
+
if (d[i] === d[i + 3]) {
|
|
420
|
+
q4++;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
const E1 = e1 / n + 0.05,
|
|
426
|
+
E2 = e2 / n + 0.05,
|
|
427
|
+
E3 = e3 / n + 0.05,
|
|
428
|
+
E4 = e4 / n + 0.05;
|
|
429
|
+
const fewQuads = q4 < 0.5 * Math.max(1, n4);
|
|
430
|
+
const layout = E4 / E3 > 1.25 && fewQuads || g3 > 0.9 * Math.max(1, n3) && g4 < 0.6 * Math.max(1, n4) ? 'rgb' : E4 / E2 > 1.1 && E2 / E1 < 0.5 ? 'grey-alpha' : E4 / E1 > 1.5 && fewQuads ? 'grey' : null;
|
|
431
|
+
if (layout === null) {
|
|
432
|
+
return null;
|
|
433
|
+
}
|
|
434
|
+
// Bytes that mostly rise by one fixed step ((i * k) & 255, the usual fake image in tests) are pixels of no layout, and
|
|
435
|
+
// score 4/3 as RGB or 4 as grey whatever the step. Counted only for arrays about to be flagged, a second pass over the
|
|
436
|
+
// same windows, so RGBA (the usual input) doesn't pay for it.
|
|
437
|
+
let ramp = 0;
|
|
438
|
+
for (let w = 0; w < windows; w++) {
|
|
439
|
+
const start = startOf(w),
|
|
440
|
+
end = start + size;
|
|
441
|
+
for (let i = start + 4; i < end; i++) {
|
|
442
|
+
const rise = d[i] - d[i - 1] & 255;
|
|
443
|
+
if (rise !== 0 && rise === (d[i - 1] - d[i - 2] & 255)) {
|
|
444
|
+
ramp++;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return ramp <= 0.5 * n ? layout : null;
|
|
449
|
+
};
|
|
450
|
+
export const looksLikeRgb = d => bareLayout(d) === 'rgb';
|
|
451
|
+
|
|
452
|
+
// Codes already warned in this copy of the library (PRINCIPLES: once per code, per copy).
|
|
453
|
+
const warned = new Set();
|
|
454
|
+
const bareCodes = {
|
|
455
|
+
rgb: 'rgb-as-rgba',
|
|
456
|
+
grey: 'gray-as-rgba',
|
|
457
|
+
'grey-alpha': 'gray-as-rgba'
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
// The warning a bare image calls for, as {code, layout}, or null. It skips everything the main entry rejects (palettes
|
|
461
|
+
// and clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never both warns
|
|
462
|
+
// about its image and rejects it, and both entries share this one order. An array of one layout never takes another's
|
|
463
|
+
// code because its own was already used: it is classified first, and only then is its code checked.
|
|
464
|
+
export const bareImageWarning = image => {
|
|
465
|
+
if (warned.has('rgb-as-rgba') && warned.has('gray-as-rgba') || !isUint8Array(image) || isPalette(image) || isClustering(image)) {
|
|
466
|
+
return null;
|
|
467
|
+
}
|
|
468
|
+
if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
|
|
469
|
+
return null;
|
|
470
|
+
}
|
|
471
|
+
const layout = bareLayout(image);
|
|
472
|
+
return layout === null || warned.has(bareCodes[layout]) ? null : {
|
|
473
|
+
code: bareCodes[layout],
|
|
474
|
+
layout
|
|
475
|
+
};
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
// The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
|
|
479
|
+
// process.on('warning') and --trace-warnings then work), else console.warn. Runtimes that imitate Node have an
|
|
480
|
+
// emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
|
|
481
|
+
// navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
|
|
482
|
+
// keeps Parcel from adding one.
|
|
483
|
+
const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
|
|
484
|
+
const warningText = {
|
|
485
|
+
'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.`,
|
|
486
|
+
'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.`
|
|
487
|
+
};
|
|
488
|
+
// `warning` is what bareImageWarning returned: {code, layout}.
|
|
489
|
+
export const warnOnce = ({
|
|
490
|
+
code,
|
|
491
|
+
layout
|
|
492
|
+
}, byteLength) => {
|
|
493
|
+
if (warned.has(code)) {
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
warned.add(code);
|
|
497
|
+
const message = warningText[code](byteLength, layout);
|
|
498
|
+
const runtime = globalThis.process;
|
|
499
|
+
if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
|
|
500
|
+
runtime.emitWarning(message, {
|
|
501
|
+
type: 'AgglomerativeClusteringWarning',
|
|
502
|
+
code
|
|
503
|
+
});
|
|
504
|
+
} else if (typeof console !== 'undefined') {
|
|
505
|
+
console.warn(`agglomerative-clustering [${code}]: ${message}`);
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
// The worker thread's copy: its caller's side checks and warns (PRINCIPLES), so here every code counts as warned, which
|
|
509
|
+
// also skips the sampling.
|
|
510
|
+
export const silenceWarnings = () => {
|
|
511
|
+
for (const code of Object.keys(warningText)) {
|
|
512
|
+
warned.add(code);
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
// For tests.
|
|
516
|
+
export const resetWarnings = () => {
|
|
517
|
+
warned.clear();
|
|
518
|
+
};
|
|
279
519
|
// Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
|
|
280
520
|
// `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
|
|
281
521
|
const inspect = Symbol.for('nodejs.util.inspect.custom');
|
package/dist/worker-thread.mjs
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
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 } from "./shared.mjs";
|
|
4
|
+
import { MARK, mark, revive, isPalette, silenceWarnings } from "./shared.mjs";
|
|
5
|
+
|
|
6
|
+
// The caller's side checks for warnings and gives them (PRINCIPLES "Warnings"), so this copy stays quiet.
|
|
7
|
+
silenceWarnings();
|
|
5
8
|
|
|
6
9
|
// Images kept in the worker by `cluster`, with their clusterings, by handle id.
|
|
7
10
|
const handles = new Map();
|
package/dist/worker.cjs
CHANGED
|
@@ -907,6 +907,11 @@ const makeWorker = (options, allowScript) => {
|
|
|
907
907
|
}
|
|
908
908
|
throw abortReason(signal);
|
|
909
909
|
}
|
|
910
|
+
// The bare-image warning is decided here, on the caller's side and before a transfer can empty the
|
|
911
|
+
// array, and given once the call succeeds: the thread checks the other arguments, and its own copy is
|
|
912
|
+
// silenced (PRINCIPLES "Warnings").
|
|
913
|
+
const warning = (0, _shared.bareImageWarning)(image);
|
|
914
|
+
const byteLength = warning ? image.byteLength : 0;
|
|
910
915
|
let sent = send(image);
|
|
911
916
|
if (!ready()) {
|
|
912
917
|
sent = take(sent);
|
|
@@ -916,6 +921,9 @@ const makeWorker = (options, allowScript) => {
|
|
|
916
921
|
signal,
|
|
917
922
|
onProgress
|
|
918
923
|
});
|
|
924
|
+
if (warning) {
|
|
925
|
+
(0, _shared.warnOnce)(warning, byteLength);
|
|
926
|
+
}
|
|
919
927
|
return mapped ? rebuild(image)(result) : result;
|
|
920
928
|
})();
|
|
921
929
|
};
|
|
@@ -965,6 +973,8 @@ const makeWorker = (options, allowScript) => {
|
|
|
965
973
|
throw abortReason(signal);
|
|
966
974
|
}
|
|
967
975
|
const id = nextHandle++;
|
|
976
|
+
const warning = (0, _shared.bareImageWarning)(image);
|
|
977
|
+
const byteLength = warning ? image.byteLength : 0;
|
|
968
978
|
const sent = ready() ? send(image) : take(send(image));
|
|
969
979
|
// Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
|
|
970
980
|
// existing (see `abandoned`).
|
|
@@ -984,6 +994,9 @@ const makeWorker = (options, allowScript) => {
|
|
|
984
994
|
}
|
|
985
995
|
throw error;
|
|
986
996
|
}
|
|
997
|
+
if (warning) {
|
|
998
|
+
(0, _shared.warnOnce)(warning, byteLength);
|
|
999
|
+
}
|
|
987
1000
|
const output = rebuild(image);
|
|
988
1001
|
let released = false;
|
|
989
1002
|
// Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
|
package/dist/worker.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
|
|
5
5
|
// worker, started on first use.
|
|
6
6
|
|
|
7
|
-
import { fail, isCodedError, detachedError, isOptionsObject, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge } from "./shared.mjs";
|
|
7
|
+
import { fail, isCodedError, detachedError, isOptionsObject, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge, bareImageWarning, warnOnce } from "./shared.mjs";
|
|
8
8
|
|
|
9
9
|
// The same version, types and data-format version as the main entry (one implementation, in shared.js).
|
|
10
10
|
export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
|
|
@@ -838,6 +838,11 @@ const makeWorker = (options, allowScript) => {
|
|
|
838
838
|
}
|
|
839
839
|
throw abortReason(signal);
|
|
840
840
|
}
|
|
841
|
+
// The bare-image warning is decided here, on the caller's side and before a transfer can empty the
|
|
842
|
+
// array, and given once the call succeeds: the thread checks the other arguments, and its own copy is
|
|
843
|
+
// silenced (PRINCIPLES "Warnings").
|
|
844
|
+
const warning = bareImageWarning(image);
|
|
845
|
+
const byteLength = warning ? image.byteLength : 0;
|
|
841
846
|
let sent = send(image);
|
|
842
847
|
if (!ready()) {
|
|
843
848
|
sent = take(sent);
|
|
@@ -847,6 +852,9 @@ const makeWorker = (options, allowScript) => {
|
|
|
847
852
|
signal,
|
|
848
853
|
onProgress
|
|
849
854
|
});
|
|
855
|
+
if (warning) {
|
|
856
|
+
warnOnce(warning, byteLength);
|
|
857
|
+
}
|
|
850
858
|
return mapped ? rebuild(image)(result) : result;
|
|
851
859
|
})();
|
|
852
860
|
};
|
|
@@ -896,6 +904,8 @@ const makeWorker = (options, allowScript) => {
|
|
|
896
904
|
throw abortReason(signal);
|
|
897
905
|
}
|
|
898
906
|
const id = nextHandle++;
|
|
907
|
+
const warning = bareImageWarning(image);
|
|
908
|
+
const byteLength = warning ? image.byteLength : 0;
|
|
899
909
|
const sent = ready() ? send(image) : take(send(image));
|
|
900
910
|
// Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
|
|
901
911
|
// existing (see `abandoned`).
|
|
@@ -915,6 +925,9 @@ const makeWorker = (options, allowScript) => {
|
|
|
915
925
|
}
|
|
916
926
|
throw error;
|
|
917
927
|
}
|
|
928
|
+
if (warning) {
|
|
929
|
+
warnOnce(warning, byteLength);
|
|
930
|
+
}
|
|
918
931
|
const output = rebuild(image);
|
|
919
932
|
let released = false;
|
|
920
933
|
// Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agglomerative-clustering",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.6.0",
|
|
4
4
|
"description": "Colour palette extraction and image quantization with exact Ward clustering, in WebAssembly. Cluster an image once, then cut it to a palette of any size.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Rohan Fredriksson",
|
|
@@ -103,6 +103,9 @@
|
|
|
103
103
|
"@babel/core": "^7.27.4",
|
|
104
104
|
"@babel/plugin-transform-modules-commonjs": "^7.27.1",
|
|
105
105
|
"@babel/preset-env": "^7.27.2",
|
|
106
|
+
"@jsquash/jpeg": "^1.6.0",
|
|
107
|
+
"@jsquash/png": "^3.1.1",
|
|
108
|
+
"@jsquash/webp": "^1.5.0",
|
|
106
109
|
"@parcel/config-default": "^2.16.4",
|
|
107
110
|
"@parcel/core": "^2.16.4",
|
|
108
111
|
"@types/node": "^22.20.5",
|
|
@@ -119,6 +122,7 @@
|
|
|
119
122
|
"omggif": "^1.0.10",
|
|
120
123
|
"playwright-core": "^1.56.1",
|
|
121
124
|
"quantize": "^1.0.2",
|
|
125
|
+
"sharp": "^0.35.5",
|
|
122
126
|
"typescript": "^5.9.3",
|
|
123
127
|
"vite": "^8.0.10",
|
|
124
128
|
"vitest": "^4.1.5",
|