agglomerative-clustering 3.5.0 → 3.7.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 +1 -1
- package/dist/clustering.cjs +1 -1
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +130 -16
- package/dist/index.d.cts +13 -15
- package/dist/index.d.ts +13 -15
- package/dist/index.mjs +131 -17
- package/dist/shared.cjs +88 -49
- package/dist/shared.mjs +84 -46
- package/dist/worker-thread.mjs +2 -2
- package/dist/worker.cjs +9 -11
- package/dist/worker.mjs +10 -12
- package/package.json +2 -2
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, sniffImageFormat,
|
|
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";
|
|
@@ -413,15 +413,15 @@ const checkSize = (pixels, size, name, argument) => {
|
|
|
413
413
|
}
|
|
414
414
|
};
|
|
415
415
|
|
|
416
|
-
// The rgb-as-rgba
|
|
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
417
|
// just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
|
|
418
418
|
const noWarning = () => {};
|
|
419
419
|
// A call whose signal is already aborted fails before any work, so it doesn't use the warning up either.
|
|
420
420
|
const warningFor = image => {
|
|
421
|
-
const
|
|
422
|
-
return
|
|
421
|
+
const warning = bareImageWarning(image);
|
|
422
|
+
return warning ? signal => {
|
|
423
423
|
if (!(signal && signal.aborted)) {
|
|
424
|
-
warnOnce(
|
|
424
|
+
warnOnce(warning, image.byteLength);
|
|
425
425
|
}
|
|
426
426
|
} : noWarning;
|
|
427
427
|
};
|
|
@@ -569,7 +569,8 @@ const check = k => {
|
|
|
569
569
|
// precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
|
|
570
570
|
// dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
|
|
571
571
|
// width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
|
|
572
|
-
// signal, onProgress: an AbortSignal and a progress callback, which make the clustering run in slices
|
|
572
|
+
// signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
|
|
573
|
+
// (see clusterInSlices and mapInSlices)
|
|
573
574
|
// 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);
|
|
574
575
|
// indexed output also gives them their own entry, which counts towards k
|
|
575
576
|
|
|
@@ -586,7 +587,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
586
587
|
options = snapshot(options);
|
|
587
588
|
for (const key of Object.keys(options)) {
|
|
588
589
|
if (!allowed.includes(key)) {
|
|
589
|
-
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' :
|
|
590
|
+
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
|
|
590
591
|
throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
|
|
591
592
|
}
|
|
592
593
|
}
|
|
@@ -664,9 +665,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
664
665
|
const controlOptions = ['signal', 'onProgress'];
|
|
665
666
|
const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
|
|
666
667
|
const quantizeOptions = [...clusterOptions, 'dither', 'width'];
|
|
667
|
-
|
|
668
|
-
// for a photo, seconds for a large image dithered; the guides show how to map in strips or cancel through a worker).
|
|
669
|
-
const mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
|
|
668
|
+
const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
|
|
670
669
|
const quantizeIndexOptions = quantizeOptions;
|
|
671
670
|
const mapIndexOptions = [...mapOptions, 'transparent'];
|
|
672
671
|
|
|
@@ -743,7 +742,7 @@ const call = (wasm, buffers, fn, precision) => {
|
|
|
743
742
|
};
|
|
744
743
|
|
|
745
744
|
// ----- Interruptible work -------------------------------------------------------------------------------------------
|
|
746
|
-
// A call given a `signal` or an `onProgress` runs its clustering in slices of about `sliceMs` milliseconds, giving the
|
|
745
|
+
// A call given a `signal` or an `onProgress` runs its clustering and its mapping in slices of about `sliceMs` milliseconds, giving the
|
|
747
746
|
// event loop a turn between them: the signal is checked (and progress reported) each time, other tasks can run, and
|
|
748
747
|
// in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
|
|
749
748
|
// result is the same either way: the slices are the same steps in the same order.
|
|
@@ -792,6 +791,20 @@ const reporter = o => {
|
|
|
792
791
|
};
|
|
793
792
|
const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
|
|
794
793
|
|
|
794
|
+
// The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
|
|
795
|
+
// the progress bar, so it is internal and can be retuned. Mapping's time relative to clustering's, measured on the 24
|
|
796
|
+
// Kodak photos (medians; bench/spikes/slicing-mapping/split.mjs → results-split.txt): undithered 0.1, Floyd–Steinberg
|
|
797
|
+
// 0.45, Atkinson 0.37, ordered 0.8 at 16 steps and about proportional to the steps; clustering below full precision is
|
|
798
|
+
// about 2.5 times faster. Steps not given are 64 for a palette of two colours, else 16, as in the C.
|
|
799
|
+
const mappingCost = [0.45, 0.37];
|
|
800
|
+
const clusteringShare = (o, k) => {
|
|
801
|
+
const dithered = o.dither > 0 && o.width > 0;
|
|
802
|
+
const ordered = dithered && o.ditherMethod === 2;
|
|
803
|
+
const steps = o.ditherSteps || (k <= 2 ? 64 : 16);
|
|
804
|
+
const cost = (!dithered ? 0.1 : ordered ? 0.8 * steps / 16 : mappingCost[o.ditherMethod]) * (o.precision < 8 ? 2.5 : 1);
|
|
805
|
+
return 1 / (1 + cost);
|
|
806
|
+
};
|
|
807
|
+
|
|
795
808
|
// Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
|
|
796
809
|
const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
797
810
|
checkAborted(o.signal);
|
|
@@ -835,6 +848,67 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
|
835
848
|
}
|
|
836
849
|
};
|
|
837
850
|
|
|
851
|
+
// Maps in slices and returns the output's payload, as `call` does for the one-shot exports. The palette is
|
|
852
|
+
// `source.palette`, or cut from `source.clustering` to `source.k` colours (a negative `colorSpace` then matches in the
|
|
853
|
+
// clustering's space). `indices` chooses indexed output, with `cutoff`. Progress goes from `from` to 1. A call that
|
|
854
|
+
// finishes in its first slice doesn't yield.
|
|
855
|
+
const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o, report, from) => {
|
|
856
|
+
checkAborted(o.signal);
|
|
857
|
+
const bytes = source.palette || source.clustering;
|
|
858
|
+
const imagePointer = allocate(wasm, image.data.length);
|
|
859
|
+
let sourcePointer = 0;
|
|
860
|
+
let job = 0;
|
|
861
|
+
let aborted = false;
|
|
862
|
+
try {
|
|
863
|
+
sourcePointer = allocate(wasm, bytes.length);
|
|
864
|
+
wasm.HEAPU8.set(image.data, imagePointer);
|
|
865
|
+
wasm.HEAPU8.set(bytes, sourcePointer);
|
|
866
|
+
const palette = source.palette ? sourcePointer : 0,
|
|
867
|
+
clustering = source.clustering ? sourcePointer : 0;
|
|
868
|
+
job = wasm._mapping_job_start(imagePointer, image.data.length, codes[image.format], palette, source.palette ? bytes.length : 0, clustering, source.clustering ? bytes.length : 0, source.k || 0, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, indices ? 1 : 0, cutoff);
|
|
869
|
+
if (!job) {
|
|
870
|
+
throw fail('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
|
|
871
|
+
}
|
|
872
|
+
// The job has its own copy of the palette, so the source can go now.
|
|
873
|
+
wasm._free(sourcePointer);
|
|
874
|
+
sourcePointer = 0;
|
|
875
|
+
report(from);
|
|
876
|
+
while (true) {
|
|
877
|
+
const progress = wasm._mapping_job_step(job, sliceMs);
|
|
878
|
+
if (progress >= 1000) {
|
|
879
|
+
break;
|
|
880
|
+
}
|
|
881
|
+
report(from + (1 - from) * progress / 1000);
|
|
882
|
+
await yieldNow();
|
|
883
|
+
checkAborted(o.signal);
|
|
884
|
+
}
|
|
885
|
+
const pointer = wasm._mapping_job_result(job);
|
|
886
|
+
try {
|
|
887
|
+
return unpack(wasm, pointer);
|
|
888
|
+
} finally {
|
|
889
|
+
wasm._free(pointer);
|
|
890
|
+
}
|
|
891
|
+
} catch (error) {
|
|
892
|
+
if (!isAbort(error)) {
|
|
893
|
+
throw error;
|
|
894
|
+
}
|
|
895
|
+
aborted = true;
|
|
896
|
+
discard(wasm);
|
|
897
|
+
throw outOfMemory(image.data.length, o.precision);
|
|
898
|
+
} finally {
|
|
899
|
+
if (!aborted) {
|
|
900
|
+
if (job) {
|
|
901
|
+
wasm._mapping_job_free(job);
|
|
902
|
+
}
|
|
903
|
+
if (sourcePointer) {
|
|
904
|
+
wasm._free(sourcePointer);
|
|
905
|
+
}
|
|
906
|
+
wasm._free(imagePointer);
|
|
907
|
+
retireIfLarge(wasm);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
|
|
838
912
|
// The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
|
|
839
913
|
// anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
|
|
840
914
|
// `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
|
|
@@ -1011,9 +1085,12 @@ export const quantize = async (image, k, options) => {
|
|
|
1011
1085
|
const wasm = Module || (await acquire());
|
|
1012
1086
|
if (isControlled(o)) {
|
|
1013
1087
|
const report = reporter(o);
|
|
1014
|
-
const
|
|
1015
|
-
|
|
1016
|
-
const mapped = wrap(
|
|
1088
|
+
const share = clusteringShare(o, k);
|
|
1089
|
+
const clustering = await clusterInSlices(wasm, image, o, report, share);
|
|
1090
|
+
const mapped = wrap(await mapInSlices(wasm, image, {
|
|
1091
|
+
clustering,
|
|
1092
|
+
k
|
|
1093
|
+
}, o.colorSpace, false, 0, o, report, share));
|
|
1017
1094
|
report(1);
|
|
1018
1095
|
return mapped;
|
|
1019
1096
|
}
|
|
@@ -1031,6 +1108,15 @@ export const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
|
1031
1108
|
const wasm = Module || (await acquire());
|
|
1032
1109
|
checkAborted(o.signal);
|
|
1033
1110
|
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
1111
|
+
if (isControlled(o)) {
|
|
1112
|
+
const report = reporter(o);
|
|
1113
|
+
const mapped = wrap(await mapInSlices(wasm, image, {
|
|
1114
|
+
clustering,
|
|
1115
|
+
k
|
|
1116
|
+
}, colorSpace, false, 0, o, report, 0));
|
|
1117
|
+
report(1);
|
|
1118
|
+
return mapped;
|
|
1119
|
+
}
|
|
1034
1120
|
const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
|
|
1035
1121
|
return result;
|
|
1036
1122
|
};
|
|
@@ -1046,6 +1132,14 @@ export const quantizeWithPalette = async (image, palette, options) => {
|
|
|
1046
1132
|
warn(o.signal);
|
|
1047
1133
|
const wasm = Module || (await acquire());
|
|
1048
1134
|
checkAborted(o.signal);
|
|
1135
|
+
if (isControlled(o)) {
|
|
1136
|
+
const report = reporter(o);
|
|
1137
|
+
const mapped = wrap(await mapInSlices(wasm, image, {
|
|
1138
|
+
palette
|
|
1139
|
+
}, space, false, 0, o, report, 0));
|
|
1140
|
+
report(1);
|
|
1141
|
+
return mapped;
|
|
1142
|
+
}
|
|
1049
1143
|
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)));
|
|
1050
1144
|
return result;
|
|
1051
1145
|
};
|
|
@@ -1059,9 +1153,12 @@ export const quantizeToIndices = async (image, k, options) => {
|
|
|
1059
1153
|
const wasm = Module || (await acquire());
|
|
1060
1154
|
if (isControlled(o)) {
|
|
1061
1155
|
const report = reporter(o);
|
|
1062
|
-
const
|
|
1063
|
-
|
|
1064
|
-
const indexed = unpackIndices(
|
|
1156
|
+
const share = clusteringShare(o, k);
|
|
1157
|
+
const clustering = await clusterInSlices(wasm, image, o, report, share);
|
|
1158
|
+
const indexed = unpackIndices(await mapInSlices(wasm, image, {
|
|
1159
|
+
clustering,
|
|
1160
|
+
k
|
|
1161
|
+
}, o.colorSpace, true, o.transparent, o, report, share), original, colorSpaceName(o.colorSpace));
|
|
1065
1162
|
report(1);
|
|
1066
1163
|
return indexed;
|
|
1067
1164
|
}
|
|
@@ -1082,6 +1179,15 @@ export const quantizeToIndicesFromClustering = async (image, clustering, k, opti
|
|
|
1082
1179
|
|
|
1083
1180
|
// The cutoff the clustering was made with is the default, so clustering and mapping agree unless a cutoff is named.
|
|
1084
1181
|
const cutoff = o.transparentGiven ? o.transparent : header.transparent;
|
|
1182
|
+
if (isControlled(o)) {
|
|
1183
|
+
const report = reporter(o);
|
|
1184
|
+
const indexed = unpackIndices(await mapInSlices(wasm, image, {
|
|
1185
|
+
clustering,
|
|
1186
|
+
k
|
|
1187
|
+
}, colorSpace, true, cutoff, o, report, 0), original, colorSpaceName(header.colorSpace));
|
|
1188
|
+
report(1);
|
|
1189
|
+
return indexed;
|
|
1190
|
+
}
|
|
1085
1191
|
const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff)), original, colorSpaceName(header.colorSpace));
|
|
1086
1192
|
return result;
|
|
1087
1193
|
};
|
|
@@ -1098,6 +1204,14 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1098
1204
|
warn(o.signal);
|
|
1099
1205
|
const wasm = Module || (await acquire());
|
|
1100
1206
|
checkAborted(o.signal);
|
|
1207
|
+
if (isControlled(o)) {
|
|
1208
|
+
const report = reporter(o);
|
|
1209
|
+
const indexed = unpackIndices(await mapInSlices(wasm, image, {
|
|
1210
|
+
palette
|
|
1211
|
+
}, space, true, o.transparent, o, report, 0), original, paletteSpace);
|
|
1212
|
+
report(1);
|
|
1213
|
+
return indexed;
|
|
1214
|
+
}
|
|
1101
1215
|
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);
|
|
1102
1216
|
return result;
|
|
1103
1217
|
};
|
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.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.
|
|
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.7.0';
|
|
17
17
|
const colorSpaceCodes = exports.colorSpaceCodes = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
|
@@ -371,31 +371,45 @@ const sniffImageFormat = bytes => {
|
|
|
371
371
|
return null;
|
|
372
372
|
};
|
|
373
373
|
|
|
374
|
-
// ----- RGB bytes passed bare
|
|
375
|
-
// The other common way to get a bare array wrong is RGB
|
|
376
|
-
//
|
|
377
|
-
//
|
|
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.
|
|
378
379
|
//
|
|
379
|
-
// The
|
|
380
|
-
//
|
|
381
|
-
//
|
|
382
|
-
//
|
|
383
|
-
//
|
|
384
|
-
//
|
|
385
|
-
// (
|
|
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.
|
|
386
392
|
exports.sniffImageFormat = sniffImageFormat;
|
|
387
|
-
const
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
const
|
|
391
|
-
if (d.length <
|
|
392
|
-
return
|
|
393
|
+
const bareFloor = 192,
|
|
394
|
+
bareWindow = 96,
|
|
395
|
+
bareWindows = 512;
|
|
396
|
+
const bareLayout = d => {
|
|
397
|
+
if (d.length < bareFloor) {
|
|
398
|
+
return null;
|
|
393
399
|
}
|
|
394
|
-
const whole = d.length <=
|
|
395
|
-
const windows = whole ? 1 :
|
|
396
|
-
size = whole ? d.length :
|
|
397
|
-
const step = whole ? 0 : Math.floor((d.length -
|
|
398
|
-
|
|
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,
|
|
399
413
|
e4 = 0,
|
|
400
414
|
n = 0,
|
|
401
415
|
g3 = 0,
|
|
@@ -404,14 +418,18 @@ const looksLikeRgb = d => {
|
|
|
404
418
|
q4 = 0,
|
|
405
419
|
n4 = 0;
|
|
406
420
|
for (let w = 0; w < windows; w++) {
|
|
407
|
-
const start = w
|
|
421
|
+
const start = startOf(w),
|
|
408
422
|
end = start + size;
|
|
409
423
|
for (let i = start + 4; i < end; i++) {
|
|
410
424
|
const v = d[i],
|
|
411
|
-
a = v - d[i -
|
|
412
|
-
b = v - d[i -
|
|
413
|
-
|
|
414
|
-
|
|
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;
|
|
415
433
|
}
|
|
416
434
|
n += size - 4;
|
|
417
435
|
for (let i = start + 3; i + 2 < end; i += 3) {
|
|
@@ -436,17 +454,21 @@ const looksLikeRgb = d => {
|
|
|
436
454
|
}
|
|
437
455
|
}
|
|
438
456
|
}
|
|
439
|
-
const
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
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;
|
|
443
465
|
}
|
|
444
|
-
// Bytes that mostly rise by one fixed step ((i * k) & 255, the usual fake image in tests) are pixels of
|
|
445
|
-
//
|
|
446
|
-
// so RGBA (the usual input) doesn't pay for it.
|
|
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.
|
|
447
469
|
let ramp = 0;
|
|
448
470
|
for (let w = 0; w < windows; w++) {
|
|
449
|
-
const start = w
|
|
471
|
+
const start = startOf(w),
|
|
450
472
|
end = start + size;
|
|
451
473
|
for (let i = start + 4; i < end; i++) {
|
|
452
474
|
const rise = d[i] - d[i - 1] & 255;
|
|
@@ -455,24 +477,36 @@ const looksLikeRgb = d => {
|
|
|
455
477
|
}
|
|
456
478
|
}
|
|
457
479
|
}
|
|
458
|
-
return ramp <= 0.5 * n;
|
|
480
|
+
return ramp <= 0.5 * n ? layout : null;
|
|
459
481
|
};
|
|
482
|
+
exports.bareLayout = bareLayout;
|
|
483
|
+
const looksLikeRgb = d => bareLayout(d) === 'rgb';
|
|
460
484
|
|
|
461
485
|
// Codes already warned in this copy of the library (PRINCIPLES: once per code, per copy).
|
|
462
486
|
exports.looksLikeRgb = looksLikeRgb;
|
|
463
487
|
const warned = new Set();
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
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)) {
|
|
470
500
|
return null;
|
|
471
501
|
}
|
|
472
502
|
if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
|
|
473
503
|
return null;
|
|
474
504
|
}
|
|
475
|
-
|
|
505
|
+
const layout = bareLayout(image);
|
|
506
|
+
return layout === null || warned.has(bareCodes[layout]) ? null : {
|
|
507
|
+
code: bareCodes[layout],
|
|
508
|
+
layout
|
|
509
|
+
};
|
|
476
510
|
};
|
|
477
511
|
|
|
478
512
|
// The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
|
|
@@ -480,17 +514,22 @@ const bareRgbWarning = image => {
|
|
|
480
514
|
// emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
|
|
481
515
|
// navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
|
|
482
516
|
// keeps Parcel from adding one.
|
|
483
|
-
exports.
|
|
517
|
+
exports.bareImageWarning = bareImageWarning;
|
|
484
518
|
const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
|
|
485
519
|
const warningText = {
|
|
486
|
-
'rgb-as-rgba': byteLength => `This image (${byteLength.toLocaleString('en-US')} bytes) looks like RGB bytes (3 per pixel) 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 really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once
|
|
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.`
|
|
487
522
|
};
|
|
488
|
-
|
|
523
|
+
// `warning` is what bareImageWarning returned: {code, layout}.
|
|
524
|
+
const warnOnce = ({
|
|
525
|
+
code,
|
|
526
|
+
layout
|
|
527
|
+
}, byteLength) => {
|
|
489
528
|
if (warned.has(code)) {
|
|
490
529
|
return;
|
|
491
530
|
}
|
|
492
531
|
warned.add(code);
|
|
493
|
-
const message = warningText[code](byteLength);
|
|
532
|
+
const message = warningText[code](byteLength, layout);
|
|
494
533
|
const runtime = globalThis.process;
|
|
495
534
|
if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
|
|
496
535
|
runtime.emitWarning(message, {
|