agglomerative-clustering 3.0.0-beta.5 → 3.0.0-beta.7
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 +75 -22
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +87 -26
- package/dist/index.d.cts +19 -25
- package/dist/index.d.ts +19 -25
- package/dist/index.mjs +88 -27
- package/dist/shared.cjs +31 -7
- package/dist/shared.mjs +25 -4
- package/dist/worker.cjs +77 -10
- package/dist/worker.d.cts +10 -3
- package/dist/worker.d.ts +10 -3
- package/dist/worker.mjs +72 -10
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -250,9 +250,9 @@ interface IndexedImageFields {
|
|
|
250
250
|
/** The index of the entry for fully transparent pixels, or `null` if there is none. */
|
|
251
251
|
transparentIndex: number | null;
|
|
252
252
|
/** Copied from the input, when it is `ImageData` or a `RawImage` with `width`. */
|
|
253
|
-
width?: number;
|
|
253
|
+
width?: number | undefined;
|
|
254
254
|
/** Copied from the input, when it is `ImageData` or a `RawImage` with `height`. */
|
|
255
|
-
height?: number;
|
|
255
|
+
height?: number | undefined;
|
|
256
256
|
}
|
|
257
257
|
|
|
258
258
|
/**
|
|
@@ -282,10 +282,10 @@ export const version: string;
|
|
|
282
282
|
/**
|
|
283
283
|
* The version of the data this library stores: the format of the clusterings `getClustering` writes (`getClusteringInfo`
|
|
284
284
|
* reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
|
|
285
|
-
* changes only when the stored format does, so a new release that keeps the format keeps this number
|
|
286
|
-
*
|
|
285
|
+
* changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
|
|
286
|
+
* may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
|
|
287
287
|
*/
|
|
288
|
-
export const formatVersion:
|
|
288
|
+
export const formatVersion: number;
|
|
289
289
|
|
|
290
290
|
/**
|
|
291
291
|
* Loads the WebAssembly module. Every other function does it on first use, so calling `init` is optional, except to
|
|
@@ -356,7 +356,13 @@ export function getSwatches(image: ImageLike, k: number, options?: ClusteringOpt
|
|
|
356
356
|
*/
|
|
357
357
|
export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
|
|
358
358
|
|
|
359
|
-
|
|
359
|
+
/** What a clustering holds (`getClusteringInfo`). */
|
|
360
|
+
export interface ClusteringInfo {
|
|
361
|
+
/**
|
|
362
|
+
* The format of the clustering's bytes: the data version (compare it with the exported `formatVersion`, the one this
|
|
363
|
+
* build writes), not the library's `version`. 3 for a clustering from 3.x; a later minor release may write a higher one.
|
|
364
|
+
*/
|
|
365
|
+
formatVersion: number;
|
|
360
366
|
colorSpace: ColorSpace;
|
|
361
367
|
/** Bits per channel it was clustered with. */
|
|
362
368
|
precision: number;
|
|
@@ -367,12 +373,6 @@ interface ClusteringInfoFields {
|
|
|
367
373
|
transparent: false | number;
|
|
368
374
|
/** The largest palette it can be cut to: its number of distinct clustered colours (fewer than the image's own when `precision` is below 8). */
|
|
369
375
|
maxColors: number;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
/** What a 3.x clustering holds. A clustering you just made with `getClustering` is this one: check `formatVersion === 3` to narrow to it. */
|
|
373
|
-
export interface ClusteringInfoV3 extends ClusteringInfoFields {
|
|
374
|
-
/** The format of the clustering's bytes: the data version (see `formatVersion`, the one this build writes), not the library's `version`. */
|
|
375
|
-
formatVersion: 3;
|
|
376
376
|
/** Total weight in pixels (opacity-weighted). */
|
|
377
377
|
totalWeight: number;
|
|
378
378
|
/**
|
|
@@ -392,19 +392,11 @@ export interface ClusteringInfoV3 extends ClusteringInfoFields {
|
|
|
392
392
|
explained: Float64Array;
|
|
393
393
|
}
|
|
394
394
|
|
|
395
|
-
/**
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
mse: null;
|
|
401
|
-
explained: null;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
/** What `getClusteringInfo` returns: check `formatVersion` to narrow to the 3.x or 2.x shape. */
|
|
405
|
-
export type ClusteringInfo = ClusteringInfoV3 | ClusteringInfoV2;
|
|
406
|
-
|
|
407
|
-
/** Reads what a clustering holds, including its error curve for choosing a palette size. */
|
|
395
|
+
/**
|
|
396
|
+
* Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
|
|
397
|
+
* clustering recorded no weights, so it is rejected with `unsupported-version` (as `getSwatchesFromClustering` rejects it);
|
|
398
|
+
* the palette and mapping functions still read it.
|
|
399
|
+
*/
|
|
408
400
|
export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
|
|
409
401
|
|
|
410
402
|
/**
|
|
@@ -442,6 +434,7 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
|
|
|
442
434
|
*
|
|
443
435
|
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|
|
444
436
|
* if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
|
|
437
|
+
* A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
|
|
445
438
|
*/
|
|
446
439
|
export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
|
|
447
440
|
|
|
@@ -450,6 +443,7 @@ export function quantizeToIndices(image: ImageLike, k: number, options?: Quantiz
|
|
|
450
443
|
*
|
|
451
444
|
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|
|
452
445
|
* if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
|
|
446
|
+
* A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
|
|
453
447
|
*/
|
|
454
448
|
export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
455
449
|
|
package/dist/index.d.ts
CHANGED
|
@@ -250,9 +250,9 @@ interface IndexedImageFields {
|
|
|
250
250
|
/** The index of the entry for fully transparent pixels, or `null` if there is none. */
|
|
251
251
|
transparentIndex: number | null;
|
|
252
252
|
/** Copied from the input, when it is `ImageData` or a `RawImage` with `width`. */
|
|
253
|
-
width?: number;
|
|
253
|
+
width?: number | undefined;
|
|
254
254
|
/** Copied from the input, when it is `ImageData` or a `RawImage` with `height`. */
|
|
255
|
-
height?: number;
|
|
255
|
+
height?: number | undefined;
|
|
256
256
|
}
|
|
257
257
|
|
|
258
258
|
/**
|
|
@@ -282,10 +282,10 @@ export const version: string;
|
|
|
282
282
|
/**
|
|
283
283
|
* The version of the data this library stores: the format of the clusterings `getClustering` writes (`getClusteringInfo`
|
|
284
284
|
* reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
|
|
285
|
-
* changes only when the stored format does, so a new release that keeps the format keeps this number
|
|
286
|
-
*
|
|
285
|
+
* changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
|
|
286
|
+
* may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
|
|
287
287
|
*/
|
|
288
|
-
export const formatVersion:
|
|
288
|
+
export const formatVersion: number;
|
|
289
289
|
|
|
290
290
|
/**
|
|
291
291
|
* Loads the WebAssembly module. Every other function does it on first use, so calling `init` is optional, except to
|
|
@@ -356,7 +356,13 @@ export function getSwatches(image: ImageLike, k: number, options?: ClusteringOpt
|
|
|
356
356
|
*/
|
|
357
357
|
export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
|
|
358
358
|
|
|
359
|
-
|
|
359
|
+
/** What a clustering holds (`getClusteringInfo`). */
|
|
360
|
+
export interface ClusteringInfo {
|
|
361
|
+
/**
|
|
362
|
+
* The format of the clustering's bytes: the data version (compare it with the exported `formatVersion`, the one this
|
|
363
|
+
* build writes), not the library's `version`. 3 for a clustering from 3.x; a later minor release may write a higher one.
|
|
364
|
+
*/
|
|
365
|
+
formatVersion: number;
|
|
360
366
|
colorSpace: ColorSpace;
|
|
361
367
|
/** Bits per channel it was clustered with. */
|
|
362
368
|
precision: number;
|
|
@@ -367,12 +373,6 @@ interface ClusteringInfoFields {
|
|
|
367
373
|
transparent: false | number;
|
|
368
374
|
/** The largest palette it can be cut to: its number of distinct clustered colours (fewer than the image's own when `precision` is below 8). */
|
|
369
375
|
maxColors: number;
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
/** What a 3.x clustering holds. A clustering you just made with `getClustering` is this one: check `formatVersion === 3` to narrow to it. */
|
|
373
|
-
export interface ClusteringInfoV3 extends ClusteringInfoFields {
|
|
374
|
-
/** The format of the clustering's bytes: the data version (see `formatVersion`, the one this build writes), not the library's `version`. */
|
|
375
|
-
formatVersion: 3;
|
|
376
376
|
/** Total weight in pixels (opacity-weighted). */
|
|
377
377
|
totalWeight: number;
|
|
378
378
|
/**
|
|
@@ -392,19 +392,11 @@ export interface ClusteringInfoV3 extends ClusteringInfoFields {
|
|
|
392
392
|
explained: Float64Array;
|
|
393
393
|
}
|
|
394
394
|
|
|
395
|
-
/**
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
mse: null;
|
|
401
|
-
explained: null;
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
/** What `getClusteringInfo` returns: check `formatVersion` to narrow to the 3.x or 2.x shape. */
|
|
405
|
-
export type ClusteringInfo = ClusteringInfoV3 | ClusteringInfoV2;
|
|
406
|
-
|
|
407
|
-
/** Reads what a clustering holds, including its error curve for choosing a palette size. */
|
|
395
|
+
/**
|
|
396
|
+
* Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
|
|
397
|
+
* clustering recorded no weights, so it is rejected with `unsupported-version` (as `getSwatchesFromClustering` rejects it);
|
|
398
|
+
* the palette and mapping functions still read it.
|
|
399
|
+
*/
|
|
408
400
|
export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
|
|
409
401
|
|
|
410
402
|
/**
|
|
@@ -442,6 +434,7 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
|
|
|
442
434
|
*
|
|
443
435
|
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|
|
444
436
|
* if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
|
|
437
|
+
* A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
|
|
445
438
|
*/
|
|
446
439
|
export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
|
|
447
440
|
|
|
@@ -450,6 +443,7 @@ export function quantizeToIndices(image: ImageLike, k: number, options?: Quantiz
|
|
|
450
443
|
*
|
|
451
444
|
* @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
|
|
452
445
|
* if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
|
|
446
|
+
* A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
|
|
453
447
|
*/
|
|
454
448
|
export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
455
449
|
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import createWasmModule from './clustering.js';
|
|
2
|
-
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData } from "./shared.mjs";
|
|
2
|
+
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } 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 } from "./shared.mjs";
|
|
@@ -84,6 +84,11 @@ const hasSimd = () => {
|
|
|
84
84
|
// Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
|
|
85
85
|
// process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
|
|
86
86
|
const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
|
|
87
|
+
// A browser page or worker, as opposed to a server-side runtime that isn't Node (Cloudflare Workers, Vercel's edge runtime,
|
|
88
|
+
// Deno Deploy): only those have a document, a worker scope or a browser's user agent.
|
|
89
|
+
const isBrowserLike = () => typeof document !== 'undefined' || typeof WorkerGlobalScope !== 'undefined' || typeof navigator !== 'undefined' && /Mozilla\//.test(String(navigator.userAgent));
|
|
90
|
+
// Where the advice for a server runtime ends: a deployment that left the .wasm behind.
|
|
91
|
+
const deployAdvice = "In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the bundler or file tracer may have left the package's dist/ files out: include node_modules/agglomerative-clustering/dist in the function's files, or leave the package unbundled (external).";
|
|
87
92
|
// Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
|
|
88
93
|
const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
|
|
89
94
|
const wasmLoadFailed = (cause, given) => {
|
|
@@ -103,7 +108,14 @@ const wasmLoadFailed = (cause, given) => {
|
|
|
103
108
|
// Where an explicit init({ wasm }) URL or path pointed, to name in the message.
|
|
104
109
|
const where = typeof given === 'string' ? ` (${given})` : '';
|
|
105
110
|
let advice;
|
|
106
|
-
if (/
|
|
111
|
+
if (/disallowed by embedder|code generation disallowed/i.test(text) && !isNodeLike && !isBrowserLike()) {
|
|
112
|
+
// Edge runtimes (Cloudflare Workers, Vercel's edge runtime) compile WebAssembly only at build time, from an import.
|
|
113
|
+
advice = "This runtime doesn't compile WebAssembly while it runs, from bytes or from a URL (edge runtimes such as Cloudflare Workers and Vercel's): import clustering.wasm as a module, which the bundler compiles when it builds (in Wrangler a plain import of 'agglomerative-clustering/clustering.wasm'; in Next.js a relative path with ?module), and pass it to init({ wasm }) before the first call, as the README shows for Cloudflare Workers and Next.js.";
|
|
114
|
+
} else if (/(memory|allocate)/i.test(text) && /(could not|cannot|can't|failed to|out of) (allocate|memory|reserve)/i.test(text)) {
|
|
115
|
+
// A 64-bit engine reserves the module's whole address range up front (about 10 GB of virtual memory per instance),
|
|
116
|
+
// though it only uses what it needs; an address-space limit refuses that reservation.
|
|
117
|
+
advice = "The engine couldn't reserve memory for the module. Each instance reserves a large range of address space up front (about 10 GB of virtual memory on 64-bit engines, of which it uses only what it needs), so a limit on virtual memory (ulimit -v, or a container's address-space limit) refuses it: lift that limit, or run fewer instances (each worker has its own).";
|
|
118
|
+
} else if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
|
|
107
119
|
// Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
|
|
108
120
|
// Which policy applies depends on where the module is compiled: a worker started from a blob: URL (the worker entry
|
|
109
121
|
// does that for a script from another origin, a content script's included) follows the page's.
|
|
@@ -119,6 +131,14 @@ const wasmLoadFailed = (cause, given) => {
|
|
|
119
131
|
reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
|
|
120
132
|
advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
|
|
121
133
|
}
|
|
134
|
+
} else if (isNodeLike && typeof given === 'string' && /^https?:/i.test(given)) {
|
|
135
|
+
// Node fetches an http(s) URL itself (see nodeWasmFile), so the server or the network failed, not a path.
|
|
136
|
+
reason = `the .wasm file could not be fetched${where}: ${reason}`;
|
|
137
|
+
advice = "Check that this machine can reach that URL and that it serves this package's clustering.wasm. On a server, a path to the package's own copy (or its bytes) avoids the request.";
|
|
138
|
+
} else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text) && isNodeLike) {
|
|
139
|
+
// In Node the file is read from disk, so the browser's reasons (a CSP, an extension's resources) don't apply.
|
|
140
|
+
reason = given ? `the .wasm file could not be read${where}` : 'the .wasm file could not be read (the package looks for clustering.wasm next to its script)';
|
|
141
|
+
advice = given ? `Check that path: it must be this package's clustering.wasm (relative paths are read from the working directory, ${globalThis.process.cwd()}). ${deployAdvice}` : `Keep the package's dist/ files together, or say where clustering.wasm is with init({ wasm: path }). ${deployAdvice}`;
|
|
122
142
|
} else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
|
|
123
143
|
reason = given ? `the .wasm file could not be fetched${where}` : 'the .wasm file could not be fetched (the package looks for clustering.wasm next to its script)';
|
|
124
144
|
const blocked = " If it is there, something may block the request: a Content-Security-Policy's connect-src, or, in a browser extension's content script, a clustering.wasm not listed in web_accessible_resources (the browser's console names the URL).";
|
|
@@ -130,7 +150,13 @@ const wasmLoadFailed = (cause, given) => {
|
|
|
130
150
|
if (/Invalid URL/i.test(reason)) {
|
|
131
151
|
reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
|
|
132
152
|
}
|
|
133
|
-
advice =
|
|
153
|
+
advice = `If the package was bundled (a server build, a CommonJS bundle from esbuild or Rollup, a plugin's single file), the bundler moved clustering.wasm or dropped what tells the package where it is, and the package's own copy wasn't found from the working directory either: leave the package out of the bundle (mark it external; in Next.js, serverExternalPackages: ['agglomerative-clustering']), or say where the file is with init({ wasm: path }) or give its bytes. ${deployAdvice}`;
|
|
154
|
+
} else if (!isBrowserLike()) {
|
|
155
|
+
// A server runtime that isn't Node (an edge runtime, Deno Deploy): it has no page, so a CSP or a 404 page are unlikely.
|
|
156
|
+
if (/Invalid URL/i.test(reason)) {
|
|
157
|
+
reason = "the package can't tell where clustering.wasm is in this runtime";
|
|
158
|
+
}
|
|
159
|
+
advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the README shows how for Cloudflare Workers and Next.js); elsewhere its bytes or URL.";
|
|
134
160
|
} else {
|
|
135
161
|
advice = "Check that clustering.wasm is served next to the script (not a 404, and with the application/wasm type) and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).";
|
|
136
162
|
}
|
|
@@ -210,6 +236,14 @@ const nodeWasmFile = async wasm => {
|
|
|
210
236
|
}
|
|
211
237
|
const isFileUrl = /^file:/i.test(text);
|
|
212
238
|
// A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
|
|
239
|
+
// An http(s) URL is fetched here: the glue would read it as a file path in Node.
|
|
240
|
+
if (/^https?:/i.test(text)) {
|
|
241
|
+
const response = await fetch(text);
|
|
242
|
+
if (!response.ok) {
|
|
243
|
+
throw new Error(`HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}`);
|
|
244
|
+
}
|
|
245
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
246
|
+
}
|
|
213
247
|
if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
|
|
214
248
|
return null;
|
|
215
249
|
}
|
|
@@ -305,7 +339,23 @@ const retireIfLarge = instance => {
|
|
|
305
339
|
discard(instance);
|
|
306
340
|
}
|
|
307
341
|
};
|
|
308
|
-
|
|
342
|
+
// What to try depends on the call: a large input has to shrink whatever else changes, and `precision: 6` helps only a
|
|
343
|
+
// clustering (`precision` given) that isn't already at 6 or below.
|
|
344
|
+
const outOfMemory = (bytes, precision) => {
|
|
345
|
+
const large = bytes >= 2 ** 28;
|
|
346
|
+
const tries = [];
|
|
347
|
+
if (large) {
|
|
348
|
+
tries.push(`scale the image down (its pixels alone are ${sizeText(bytes)}; a few megapixels give as good a palette)`);
|
|
349
|
+
}
|
|
350
|
+
if (precision > 6) {
|
|
351
|
+
tries.push('try `precision: 6`, which bounds the memory an image with very many colours needs');
|
|
352
|
+
}
|
|
353
|
+
if (!large) {
|
|
354
|
+
tries.push('use a smaller image');
|
|
355
|
+
}
|
|
356
|
+
const text = tries.join(', or ');
|
|
357
|
+
return fail('out-of-memory', `The WebAssembly module ran out of memory (it can use up to 2 GB for one image). ${text[0].toUpperCase()}${text.slice(1)}.`);
|
|
358
|
+
};
|
|
309
359
|
const unpack = (wasm, pointer) => {
|
|
310
360
|
const lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
|
|
311
361
|
const length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
|
|
@@ -424,6 +474,7 @@ const load = image => {
|
|
|
424
474
|
if (isDetached(image.data)) {
|
|
425
475
|
throw fail('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
|
|
426
476
|
}
|
|
477
|
+
checkImageDataPixels(image);
|
|
427
478
|
return {
|
|
428
479
|
data: held(bytes(image.data)),
|
|
429
480
|
format: 'rgba',
|
|
@@ -655,18 +706,27 @@ const checkNotEmpty = (palette, image, cutoff) => {
|
|
|
655
706
|
// The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
|
|
656
707
|
const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : colorSpaces[isPalette(palette) ? palette.colorSpace : 'rgb'];
|
|
657
708
|
|
|
709
|
+
// Allocates `length` bytes in the WASM heap, or throws a coded out-of-memory error.
|
|
710
|
+
const allocate = (wasm, length) => {
|
|
711
|
+
if (length >= maxBytes) {
|
|
712
|
+
throw tooLarge(length);
|
|
713
|
+
}
|
|
714
|
+
const pointer = wasm._malloc(length);
|
|
715
|
+
if (!pointer) {
|
|
716
|
+
throw fail('out-of-memory', length >= 2 ** 28 ? `Failed to allocate ${sizeText(length)} of WASM memory for the input: the module has at most 2 GB in all, so an image this size leaves too little room for the work on it. Scale the image down first.` : "Failed to allocate WASM memory.");
|
|
717
|
+
}
|
|
718
|
+
return pointer;
|
|
719
|
+
};
|
|
720
|
+
|
|
658
721
|
// Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
|
|
659
|
-
// freeing everything afterwards.
|
|
660
|
-
const call = (wasm, buffers, fn) => {
|
|
722
|
+
// freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
|
|
723
|
+
const call = (wasm, buffers, fn, precision) => {
|
|
661
724
|
const pointers = [];
|
|
662
725
|
let outputPointer = 0;
|
|
663
726
|
let aborted = false;
|
|
664
727
|
try {
|
|
665
728
|
for (const buffer of buffers) {
|
|
666
|
-
const pointer = wasm
|
|
667
|
-
if (!pointer) {
|
|
668
|
-
throw fail('out-of-memory', "Failed to allocate WASM memory.");
|
|
669
|
-
}
|
|
729
|
+
const pointer = allocate(wasm, buffer.length);
|
|
670
730
|
pointers.push(pointer);
|
|
671
731
|
wasm.HEAPU8.set(buffer, pointer);
|
|
672
732
|
}
|
|
@@ -683,7 +743,7 @@ const call = (wasm, buffers, fn) => {
|
|
|
683
743
|
}
|
|
684
744
|
aborted = true;
|
|
685
745
|
discard(wasm);
|
|
686
|
-
throw outOfMemory();
|
|
746
|
+
throw outOfMemory(buffers[0].length, precision);
|
|
687
747
|
} finally {
|
|
688
748
|
// After an abort the instance is being thrown away, and its allocator can't be trusted.
|
|
689
749
|
if (!aborted) {
|
|
@@ -751,10 +811,7 @@ const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
|
|
|
751
811
|
// Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
|
|
752
812
|
const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
753
813
|
checkAborted(o.signal);
|
|
754
|
-
const imagePointer = wasm
|
|
755
|
-
if (!imagePointer) {
|
|
756
|
-
throw fail('out-of-memory', "Failed to allocate WASM memory.");
|
|
757
|
-
}
|
|
814
|
+
const imagePointer = allocate(wasm, image.data.length);
|
|
758
815
|
let job = 0;
|
|
759
816
|
let aborted = false;
|
|
760
817
|
try {
|
|
@@ -782,7 +839,7 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
|
782
839
|
}
|
|
783
840
|
aborted = true;
|
|
784
841
|
discard(wasm);
|
|
785
|
-
throw outOfMemory();
|
|
842
|
+
throw outOfMemory(image.data.length, o.precision);
|
|
786
843
|
} finally {
|
|
787
844
|
if (!aborted) {
|
|
788
845
|
if (job) {
|
|
@@ -816,7 +873,7 @@ export const getClustering = async (image, options) => {
|
|
|
816
873
|
report(1);
|
|
817
874
|
return markClustering(clustering);
|
|
818
875
|
}
|
|
819
|
-
return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent)));
|
|
876
|
+
return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision));
|
|
820
877
|
};
|
|
821
878
|
export const getPalette = async (image, k, options) => {
|
|
822
879
|
image = load(image);
|
|
@@ -831,7 +888,7 @@ export const getPalette = async (image, k, options) => {
|
|
|
831
888
|
report(1);
|
|
832
889
|
return markPalette(palette, colorSpaceName(o.colorSpace));
|
|
833
890
|
}
|
|
834
|
-
return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent)), colorSpaceName(o.colorSpace));
|
|
891
|
+
return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), colorSpaceName(o.colorSpace));
|
|
835
892
|
};
|
|
836
893
|
export const getPaletteFromClustering = async (clustering, k, ...extra) => {
|
|
837
894
|
const header = readHeader(clustering);
|
|
@@ -851,6 +908,14 @@ const weightsOf = (wasm, clustering, header, k) => {
|
|
|
851
908
|
return new Float64Array(bytes.buffer, bytes.byteOffset, bytes.length / 8);
|
|
852
909
|
};
|
|
853
910
|
|
|
911
|
+
// The functions that report weights (swatches, the error curve) need a clustering from 3.x: 2.x recorded none. The others
|
|
912
|
+
// (palettes and mapping) still read 2.x clusterings.
|
|
913
|
+
const needsWeights = header => {
|
|
914
|
+
if (header.version < 3) {
|
|
915
|
+
throw fail('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
|
|
854
919
|
// A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
|
|
855
920
|
// arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
|
|
856
921
|
// proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
|
|
@@ -858,9 +923,7 @@ export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
|
|
|
858
923
|
const header = readHeader(clustering);
|
|
859
924
|
k = check(k);
|
|
860
925
|
noOptions('getSwatchesFromClustering', extra);
|
|
861
|
-
|
|
862
|
-
throw fail('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
|
|
863
|
-
}
|
|
926
|
+
needsWeights(header);
|
|
864
927
|
clustering = held(clustering);
|
|
865
928
|
const wasm = Module || (await acquire());
|
|
866
929
|
const palette = markPalette(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), colorSpaceName(header.colorSpace));
|
|
@@ -896,6 +959,7 @@ export const getSwatches = async (image, k, options) => {
|
|
|
896
959
|
export const getClusteringInfo = async (clustering, ...extra) => {
|
|
897
960
|
const header = readHeader(clustering);
|
|
898
961
|
noOptions('getClusteringInfo', extra);
|
|
962
|
+
needsWeights(header);
|
|
899
963
|
const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
|
|
900
964
|
const info = {
|
|
901
965
|
formatVersion: header.version,
|
|
@@ -903,13 +967,10 @@ export const getClusteringInfo = async (clustering, ...extra) => {
|
|
|
903
967
|
precision: header.precision,
|
|
904
968
|
transparent: header.transparent === 0 ? false : header.transparent,
|
|
905
969
|
maxColors: colors,
|
|
906
|
-
totalWeight:
|
|
970
|
+
totalWeight: 0,
|
|
907
971
|
mse: null,
|
|
908
972
|
explained: null
|
|
909
973
|
};
|
|
910
|
-
if (header.version < 3) {
|
|
911
|
-
return info;
|
|
912
|
-
}
|
|
913
974
|
const view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
|
|
914
975
|
const pixels = 2 ** clustering[7] / (clustering[6] === 1 ? 255 : 1);
|
|
915
976
|
const total = view.getUint32(8, true);
|
|
@@ -952,7 +1013,7 @@ export const quantize = async (image, k, options) => {
|
|
|
952
1013
|
report(1);
|
|
953
1014
|
return mapped;
|
|
954
1015
|
}
|
|
955
|
-
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.width, o.transparent)));
|
|
1016
|
+
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.width, o.transparent), o.precision));
|
|
956
1017
|
};
|
|
957
1018
|
export const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
958
1019
|
const wrap = getWrapper(image);
|
|
@@ -994,7 +1055,7 @@ export const quantizeToIndices = async (image, k, options) => {
|
|
|
994
1055
|
report(1);
|
|
995
1056
|
return indexed;
|
|
996
1057
|
}
|
|
997
|
-
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.width, o.transparent)), original, colorSpaceName(o.colorSpace));
|
|
1058
|
+
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.width, o.transparent), o.precision), original, colorSpaceName(o.colorSpace));
|
|
998
1059
|
};
|
|
999
1060
|
export const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
|
|
1000
1061
|
const original = image;
|
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.snapshot = exports.revive = exports.readHeader = 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.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = void 0;
|
|
9
|
+
exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.revive = exports.readHeader = 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.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = exports.checkImageDataPixels = 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.0.0-beta.
|
|
16
|
+
const version = exports.version = '3.0.0-beta.7';
|
|
17
17
|
const colorSpaces = exports.colorSpaces = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
|
@@ -42,9 +42,19 @@ const fail = (code, message, argument) => Object.assign(new Error(message), argu
|
|
|
42
42
|
argument
|
|
43
43
|
});
|
|
44
44
|
|
|
45
|
+
// The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
|
|
46
|
+
// buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
|
|
47
|
+
// small number and hand back a block too short for the copy. Such buffers are rejected before any allocation, and the
|
|
48
|
+
// worker entry rejects them before sending, as the main entry does (from 4 GB a buffer can't even be cloned to send).
|
|
49
|
+
exports.fail = fail;
|
|
50
|
+
const maxBytes = exports.maxBytes = 2 ** 31;
|
|
51
|
+
const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
|
|
52
|
+
exports.sizeText = sizeText;
|
|
53
|
+
const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
|
|
54
|
+
|
|
45
55
|
// Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
|
|
46
56
|
// whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
|
|
47
|
-
exports.
|
|
57
|
+
exports.tooLarge = tooLarge;
|
|
48
58
|
const tag = value => Object.prototype.toString.call(value);
|
|
49
59
|
const isUint8Array = value => ArrayBuffer.isView(value) && tag(value) === '[object Uint8Array]';
|
|
50
60
|
exports.isUint8Array = isUint8Array;
|
|
@@ -73,10 +83,21 @@ const isDetached = view => {
|
|
|
73
83
|
exports.isDetached = isDetached;
|
|
74
84
|
const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tag(value) === '[object ImageData]' || typeof value.constructor === 'function' && value.constructor.name === 'ImageData' && isUint8ClampedArray(value.data) && Number.isInteger(value.width) && Number.isInteger(value.height));
|
|
75
85
|
|
|
86
|
+
// ImageData can hold other pixel formats than 8-bit RGBA (Chromium's pixelFormat: 'rgba-float16', with a Float16Array of
|
|
87
|
+
// pixels). The library reads 8-bit RGBA only, so those are rejected, rather than read as the bytes of their floats.
|
|
88
|
+
exports.isImageData = isImageData;
|
|
89
|
+
const checkImageDataPixels = image => {
|
|
90
|
+
if (isUint8ClampedArray(image.data)) {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const format = typeof image.pixelFormat === 'string' ? ` (pixelFormat: '${image.pixelFormat}')` : '';
|
|
94
|
+
throw fail('invalid-argument', `Invalid image: this ImageData doesn't hold 8-bit RGBA pixels${format}, and the library reads only those. Ask for 8-bit pixels with getImageData(x, y, width, height, { pixelFormat: 'rgba-unorm8' }), or draw it to a canvas with the default format and take getImageData() from that.`, 'image');
|
|
95
|
+
};
|
|
96
|
+
|
|
76
97
|
// An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
|
|
77
98
|
// implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
|
|
78
99
|
// no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
|
|
79
|
-
exports.
|
|
100
|
+
exports.checkImageDataPixels = checkImageDataPixels;
|
|
80
101
|
const imageDataLike = (like, pixels) => {
|
|
81
102
|
const {
|
|
82
103
|
width,
|
|
@@ -348,7 +369,10 @@ const readHeader = clustering => {
|
|
|
348
369
|
if (version === 3 && length >= 13) {
|
|
349
370
|
const headerLength = clustering[2],
|
|
350
371
|
recordLength = clustering[3];
|
|
351
|
-
|
|
372
|
+
// Header lengths are 22 (every release) or 13 (the fixture from before 3.0.0-beta.1, kept readable by the format
|
|
373
|
+
// rules), or longer from a later release that adds fields. 14 to 20 was never written: it is a damaged length, which
|
|
374
|
+
// would also put the checksum field out of reach, so the checksum couldn't catch it.
|
|
375
|
+
if ((headerLength === 13 || headerLength >= checksumAt + 4) && recordLength >= 21 && headerLength <= length) {
|
|
352
376
|
// A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
|
|
353
377
|
// doesn't know is how a later release would add one, so it asks for an upgrade rather than misreading it.
|
|
354
378
|
if (clustering[4] > 1 || clustering[6] > 1) {
|
|
@@ -357,8 +381,8 @@ const readHeader = clustering => {
|
|
|
357
381
|
const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
|
|
358
382
|
const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
|
|
359
383
|
if (padding < 9) {
|
|
360
|
-
//
|
|
361
|
-
//
|
|
384
|
+
// A 13-byte header (from before 3.0.0-beta.1) has no checksum field. A damaged header length of 13 skips this
|
|
385
|
+
// check, but then the records don't line up, which the replay reports.
|
|
362
386
|
if (!checked.has(clustering) && headerLength >= checksumAt + 4) {
|
|
363
387
|
const stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
|
|
364
388
|
if (stored !== 0 && stored !== crc32(clustering)) {
|
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.0.0-beta.
|
|
7
|
+
export const version = '3.0.0-beta.7';
|
|
8
8
|
export const colorSpaces = {
|
|
9
9
|
'rgb': 0,
|
|
10
10
|
'oklab': 1
|
|
@@ -31,6 +31,14 @@ export const fail = (code, message, argument) => Object.assign(new Error(message
|
|
|
31
31
|
argument
|
|
32
32
|
});
|
|
33
33
|
|
|
34
|
+
// The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
|
|
35
|
+
// buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
|
|
36
|
+
// small number and hand back a block too short for the copy. Such buffers are rejected before any allocation, and the
|
|
37
|
+
// worker entry rejects them before sending, as the main entry does (from 4 GB a buffer can't even be cloned to send).
|
|
38
|
+
export const maxBytes = 2 ** 31;
|
|
39
|
+
export const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
|
|
40
|
+
export const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
|
|
41
|
+
|
|
34
42
|
// Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
|
|
35
43
|
// whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
|
|
36
44
|
const tag = value => Object.prototype.toString.call(value);
|
|
@@ -57,6 +65,16 @@ export const isDetached = view => {
|
|
|
57
65
|
// jsdom, skia-canvas, whose tag is plain [object Object]).
|
|
58
66
|
export const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tag(value) === '[object ImageData]' || typeof value.constructor === 'function' && value.constructor.name === 'ImageData' && isUint8ClampedArray(value.data) && Number.isInteger(value.width) && Number.isInteger(value.height));
|
|
59
67
|
|
|
68
|
+
// ImageData can hold other pixel formats than 8-bit RGBA (Chromium's pixelFormat: 'rgba-float16', with a Float16Array of
|
|
69
|
+
// pixels). The library reads 8-bit RGBA only, so those are rejected, rather than read as the bytes of their floats.
|
|
70
|
+
export const checkImageDataPixels = image => {
|
|
71
|
+
if (isUint8ClampedArray(image.data)) {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const format = typeof image.pixelFormat === 'string' ? ` (pixelFormat: '${image.pixelFormat}')` : '';
|
|
75
|
+
throw fail('invalid-argument', `Invalid image: this ImageData doesn't hold 8-bit RGBA pixels${format}, and the library reads only those. Ask for 8-bit pixels with getImageData(x, y, width, height, { pixelFormat: 'rgba-unorm8' }), or draw it to a canvas with the default format and take getImageData() from that.`, 'image');
|
|
76
|
+
};
|
|
77
|
+
|
|
60
78
|
// An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
|
|
61
79
|
// implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
|
|
62
80
|
// no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
|
|
@@ -323,7 +341,10 @@ export const readHeader = clustering => {
|
|
|
323
341
|
if (version === 3 && length >= 13) {
|
|
324
342
|
const headerLength = clustering[2],
|
|
325
343
|
recordLength = clustering[3];
|
|
326
|
-
|
|
344
|
+
// Header lengths are 22 (every release) or 13 (the fixture from before 3.0.0-beta.1, kept readable by the format
|
|
345
|
+
// rules), or longer from a later release that adds fields. 14 to 20 was never written: it is a damaged length, which
|
|
346
|
+
// would also put the checksum field out of reach, so the checksum couldn't catch it.
|
|
347
|
+
if ((headerLength === 13 || headerLength >= checksumAt + 4) && recordLength >= 21 && headerLength <= length) {
|
|
327
348
|
// A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
|
|
328
349
|
// doesn't know is how a later release would add one, so it asks for an upgrade rather than misreading it.
|
|
329
350
|
if (clustering[4] > 1 || clustering[6] > 1) {
|
|
@@ -332,8 +353,8 @@ export const readHeader = clustering => {
|
|
|
332
353
|
const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
|
|
333
354
|
const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
|
|
334
355
|
if (padding < 9) {
|
|
335
|
-
//
|
|
336
|
-
//
|
|
356
|
+
// A 13-byte header (from before 3.0.0-beta.1) has no checksum field. A damaged header length of 13 skips this
|
|
357
|
+
// check, but then the records don't line up, which the replay reports.
|
|
337
358
|
if (!checked.has(clustering) && headerLength >= checksumAt + 4) {
|
|
338
359
|
const stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
|
|
339
360
|
if (stored !== 0 && stored !== crc32(clustering)) {
|