@intellectual-frontiers/formats 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/archive.d.ts +147 -0
- package/dist/archive.js +765 -0
- package/dist/base64.d.ts +24 -0
- package/dist/base64.js +52 -0
- package/dist/cbor.d.ts +39 -0
- package/dist/cbor.js +244 -0
- package/dist/csv.d.ts +38 -0
- package/dist/csv.js +130 -0
- package/dist/der.d.ts +67 -0
- package/dist/der.js +221 -0
- package/dist/glob.d.ts +64 -0
- package/dist/glob.js +218 -0
- package/dist/hex.d.ts +17 -0
- package/dist/hex.js +30 -0
- package/dist/http.d.ts +46 -0
- package/dist/http.js +102 -0
- package/dist/json5.d.ts +46 -0
- package/dist/json5.js +291 -0
- package/dist/media-types.d.ts +28 -0
- package/dist/media-types.js +121 -0
- package/dist/mod.d.ts +39 -0
- package/dist/mod.js +31 -0
- package/dist/png.d.ts +124 -0
- package/dist/png.js +607 -0
- package/dist/semver.d.ts +94 -0
- package/dist/semver.js +331 -0
- package/dist/toml.d.ts +51 -0
- package/dist/toml.js +583 -0
- package/dist/ts-literal.d.ts +62 -0
- package/dist/ts-literal.js +173 -0
- package/dist/xml.d.ts +73 -0
- package/dist/xml.js +282 -0
- package/dist/yaml.d.ts +44 -0
- package/dist/yaml.js +706 -0
- package/package.json +118 -4
- package/src/archive.ts +831 -0
- package/src/base64.ts +51 -0
- package/src/cbor.ts +235 -0
- package/src/csv.ts +132 -0
- package/src/der.ts +224 -0
- package/src/glob.ts +210 -0
- package/src/hex.ts +28 -0
- package/src/http.ts +104 -0
- package/src/json5.ts +267 -0
- package/src/media-types.ts +127 -0
- package/src/mod.ts +102 -0
- package/src/png.ts +625 -0
- package/src/semver.ts +373 -0
- package/src/toml.ts +525 -0
- package/src/ts-literal.ts +183 -0
- package/src/xml.ts +291 -0
- package/src/yaml.ts +616 -0
package/src/png.ts
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
// Spec: 0001-formats FR-012
|
|
2
|
+
/**
|
|
3
|
+
* Pictures with no outside package (commons 0001-formats FR-012): a PNG read into eight-bit RGBA and written back, a picture
|
|
4
|
+
* resized with Pillow's Lanczos filter in its fixed point (on premultiplied alpha for RGBA), laid over another as Pillow's `alpha_composite`
|
|
5
|
+
* lays it, fitted as Pillow's `thumbnail` fits it, gathered into a multi-size icon file of PNG frames and read back from one, and two files
|
|
6
|
+
* compared by their pixels rather than their bytes (two zlib encoders give different bytes for one picture). Also a `#rrggbb` colour read
|
|
7
|
+
* into its channels and its relative luminance as WCAG measures it.
|
|
8
|
+
*
|
|
9
|
+
* The reader takes every PNG that is not interlaced: greyscale at 1, 2, 4, 8 and 16 bits, palette at 1, 2, 4 and 8 bits, and RGB,
|
|
10
|
+
* greyscale with alpha and RGBA at 8 and 16 bits, with `tRNS` transparency for greyscale, RGB and palette, and every filter (None, Sub,
|
|
11
|
+
* Up, Average, Paeth). Sixteen-bit samples keep their high byte. It refuses what is not a PNG it can trust, with a typed `PngError`: a bad
|
|
12
|
+
* signature, a chunk whose CRC-32 is wrong, data cut short, a colour type and bit depth PNG does not define, an interlaced (Adam7) picture,
|
|
13
|
+
* an unknown critical chunk, and a picture of more than `MAX_PIXELS` pixels, refused before anything is allocated or inflated for it; the
|
|
14
|
+
* inflater is stopped as soon as it gives more bytes than the picture needs, so a small hostile file cannot make it allocate more.
|
|
15
|
+
* Writers take a well-formed picture; a malformed one (a size that is not a positive integer, data of the wrong length) is a programming
|
|
16
|
+
* error and throws a `RangeError`.
|
|
17
|
+
*
|
|
18
|
+
* Taken from erga's `lib/ts/png`. What changed: readers return a typed error rather than a sentence, check every chunk's CRC and the
|
|
19
|
+
* picture's size, read the sub-byte depths and the `tRNS` of greyscale and RGB that erga ignored, and refuse an out-of-range palette index;
|
|
20
|
+
* erga's `resize` (each channel alone) is `resizeChannels` and its `resized` (on premultiplied alpha) is `resize`; `hexRgb` returns
|
|
21
|
+
* `undefined` for what is not a colour rather than black, and `luminance` takes channels rather than a hex string; `composite` clips an
|
|
22
|
+
* overlay that starts left of or above its base, and `premultiply` leaves a picture without alpha as it is.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* import { filled, readPng, writePng } from "./png.ts";
|
|
27
|
+
* const png = await writePng(filled(2, 2, [255, 0, 0, 128]));
|
|
28
|
+
* await readPng(png); // { kind: "ok", value: { width: 2, height: 2, channels: 4, data: Uint8Array [255, 0, 0, 128, ...] } }
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @module
|
|
32
|
+
*/
|
|
33
|
+
import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
|
|
34
|
+
import { concat, crc32 } from "./archive.ts";
|
|
35
|
+
|
|
36
|
+
/** A raster: its size, its channels (3 for RGB, 4 for RGBA) and its bytes, row by row, eight bits a channel. */
|
|
37
|
+
export type Picture = { readonly width: number; readonly height: number; readonly channels: 3 | 4; readonly data: Uint8Array };
|
|
38
|
+
|
|
39
|
+
/** A colour's red, green and blue, each 0 to 255. */
|
|
40
|
+
export type Rgb = readonly [number, number, number];
|
|
41
|
+
|
|
42
|
+
/** A colour's red, green, blue and alpha, each 0 to 255. */
|
|
43
|
+
export type Rgba = readonly [number, number, number, number];
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The most pixels a picture read may have: 2^24 (16,777,216, a 4096 by 4096 square). Its RGBA is then at most 64 MiB, and the inflated
|
|
47
|
+
* data of the largest kind (16-bit RGBA) at most 128 MiB. A file that declares more is refused as `too-large` before anything is read.
|
|
48
|
+
*/
|
|
49
|
+
export const MAX_PIXELS: number = 2 ** 24;
|
|
50
|
+
|
|
51
|
+
/** Why bytes are not a PNG or icon file this reader takes. */
|
|
52
|
+
export type PngError =
|
|
53
|
+
| { readonly kind: "signature"; readonly format: "png" | "ico" }
|
|
54
|
+
| { readonly kind: "crc"; readonly chunk: string; readonly at: number }
|
|
55
|
+
| { readonly kind: "truncated"; readonly message: string }
|
|
56
|
+
| { readonly kind: "malformed"; readonly message: string }
|
|
57
|
+
| { readonly kind: "unsupported"; readonly message: string }
|
|
58
|
+
| { readonly kind: "interlaced" }
|
|
59
|
+
| { readonly kind: "too-large"; readonly width: number; readonly height: number; readonly limit: number }
|
|
60
|
+
| { readonly kind: "ico-frame"; readonly index: number; readonly error: PngError };
|
|
61
|
+
|
|
62
|
+
/** A PNG error as one sentence. */
|
|
63
|
+
export function formatPngError(e: PngError): string {
|
|
64
|
+
switch (e.kind) {
|
|
65
|
+
case "signature":
|
|
66
|
+
return e.format === "png"
|
|
67
|
+
? "it is not a PNG: it does not begin with the PNG signature"
|
|
68
|
+
: "it is not an icon file: its header is not 0, 1";
|
|
69
|
+
case "crc":
|
|
70
|
+
return `the PNG is damaged: the CRC-32 of its ${JSON.stringify(e.chunk)} chunk at byte ${e.at} is wrong`;
|
|
71
|
+
case "truncated":
|
|
72
|
+
return `the PNG is cut short: ${e.message}`;
|
|
73
|
+
case "malformed":
|
|
74
|
+
return `the PNG is malformed: ${e.message}`;
|
|
75
|
+
case "unsupported":
|
|
76
|
+
return `the PNG uses what is not supported: ${e.message}`;
|
|
77
|
+
case "interlaced":
|
|
78
|
+
return "the PNG is interlaced (Adam7), which is not supported";
|
|
79
|
+
case "too-large":
|
|
80
|
+
return `the picture is too large: ${e.width} by ${e.height} pixels is more than ${e.limit}`;
|
|
81
|
+
case "ico-frame":
|
|
82
|
+
return `frame ${e.index} of the icon file: ${formatPngError(e.error)}`;
|
|
83
|
+
default:
|
|
84
|
+
return absurd(e);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const truncated = (message: string): Result<never, PngError> => err({ kind: "truncated", message });
|
|
89
|
+
const malformed = (message: string): Result<never, PngError> => err({ kind: "malformed", message });
|
|
90
|
+
const unsupported = (message: string): Result<never, PngError> => err({ kind: "unsupported", message });
|
|
91
|
+
|
|
92
|
+
const SIGNATURE: readonly number[] = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
|
93
|
+
|
|
94
|
+
function isSize(n: number): boolean {
|
|
95
|
+
return Number.isSafeInteger(n) && n > 0;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function checkPicture(p: Picture): void {
|
|
99
|
+
if (!isSize(p.width) || !isSize(p.height)) throw new RangeError(`a picture of ${p.width} by ${p.height} pixels`);
|
|
100
|
+
if (p.data.length !== p.width * p.height * p.channels)
|
|
101
|
+
throw new RangeError(`a picture of ${p.width} by ${p.height} by ${p.channels} with ${p.data.length} bytes`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** A picture of one colour, RGBA. A size that is not a positive integer throws a `RangeError`. */
|
|
105
|
+
export function filled(width: number, height: number, rgba: Rgba): Picture {
|
|
106
|
+
if (!isSize(width) || !isSize(height)) throw new RangeError(`a picture of ${width} by ${height} pixels`);
|
|
107
|
+
const data = new Uint8Array(width * height * 4);
|
|
108
|
+
for (let i = 0; i < width * height; i++) data.set(rgba, i * 4);
|
|
109
|
+
return { width, height, channels: 4, data };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The picture without its alpha; a picture without alpha as it is. */
|
|
113
|
+
export function rgbOf(p: Picture): Picture {
|
|
114
|
+
if (p.channels === 3) return p;
|
|
115
|
+
const data = new Uint8Array(p.width * p.height * 3);
|
|
116
|
+
for (let i = 0; i < p.width * p.height; i++) data.set(p.data.subarray(i * 4, i * 4 + 3), i * 3);
|
|
117
|
+
return { width: p.width, height: p.height, channels: 3, data };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The picture with alpha, opaque where it had none; a picture with alpha as it is. */
|
|
121
|
+
export function rgbaOf(p: Picture): Picture {
|
|
122
|
+
if (p.channels === 4) return p;
|
|
123
|
+
const data = new Uint8Array(p.width * p.height * 4);
|
|
124
|
+
for (let i = 0; i < p.width * p.height; i++) {
|
|
125
|
+
data.set(p.data.subarray(i * 3, i * 3 + 3), i * 4);
|
|
126
|
+
data[i * 4 + 3] = 255;
|
|
127
|
+
}
|
|
128
|
+
return { width: p.width, height: p.height, channels: 4, data };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The colour types PNG defines, with their samples per pixel and the bit depths each allows. */
|
|
132
|
+
const COLOUR_TYPES: ReadonlyMap<number, { readonly samples: number; readonly depths: readonly number[]; readonly name: string }> = new Map([
|
|
133
|
+
[0, { samples: 1, depths: [1, 2, 4, 8, 16], name: "greyscale" }],
|
|
134
|
+
[2, { samples: 3, depths: [8, 16], name: "RGB" }],
|
|
135
|
+
[3, { samples: 1, depths: [1, 2, 4, 8], name: "palette" }],
|
|
136
|
+
[4, { samples: 2, depths: [8, 16], name: "greyscale with alpha" }],
|
|
137
|
+
[6, { samples: 4, depths: [8, 16], name: "RGBA" }],
|
|
138
|
+
]);
|
|
139
|
+
|
|
140
|
+
/** The PNG header. */
|
|
141
|
+
type Header = {
|
|
142
|
+
readonly width: number;
|
|
143
|
+
readonly height: number;
|
|
144
|
+
readonly depth: number;
|
|
145
|
+
readonly colour: number;
|
|
146
|
+
readonly samples: number;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
function readHeader(data: Uint8Array): Result<Header, PngError> {
|
|
150
|
+
if (data.length !== 13) return malformed(`its IHDR chunk holds ${data.length} bytes, not 13`);
|
|
151
|
+
const v = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
152
|
+
const width = v.getUint32(0);
|
|
153
|
+
const height = v.getUint32(4);
|
|
154
|
+
const depth = data[8] ?? 0;
|
|
155
|
+
const colour = data[9] ?? 0;
|
|
156
|
+
if (width === 0 || height === 0 || width > 0x7fffffff || height > 0x7fffffff) return malformed(`a size of ${width} by ${height} pixels`);
|
|
157
|
+
if (data[10] !== 0) return malformed(`compression method ${data[10] ?? 0}`);
|
|
158
|
+
if (data[11] !== 0) return malformed(`filter method ${data[11] ?? 0}`);
|
|
159
|
+
if (data[12] === 1) return err({ kind: "interlaced" });
|
|
160
|
+
if (data[12] !== 0) return malformed(`interlace method ${data[12] ?? 0}`);
|
|
161
|
+
const type = COLOUR_TYPES.get(colour);
|
|
162
|
+
if (type === undefined) return unsupported(`colour type ${colour}`);
|
|
163
|
+
if (!type.depths.includes(depth)) return unsupported(`a bit depth of ${depth} for colour type ${colour} (${type.name})`);
|
|
164
|
+
if (width * height > MAX_PIXELS) return err({ kind: "too-large", width, height, limit: MAX_PIXELS });
|
|
165
|
+
return ok({ width, height, depth, colour, samples: type.samples });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** The chunks of a PNG that matter to its pixels, each checked against its CRC-32. */
|
|
169
|
+
type Chunks = { readonly header: Header; readonly palette: Uint8Array; readonly trns: Uint8Array | undefined; readonly idat: Uint8Array };
|
|
170
|
+
|
|
171
|
+
function readChunks(bytes: Uint8Array): Result<Chunks, PngError> {
|
|
172
|
+
if (bytes.length < 8 || SIGNATURE.some((b, i) => bytes[i] !== b)) return err({ kind: "signature", format: "png" });
|
|
173
|
+
const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
174
|
+
let header: Header | undefined;
|
|
175
|
+
let palette: Uint8Array | undefined;
|
|
176
|
+
let trns: Uint8Array | undefined;
|
|
177
|
+
const idat: Uint8Array[] = [];
|
|
178
|
+
for (let at = 8; ;) {
|
|
179
|
+
if (at + 12 > bytes.length) return truncated(`it ends at byte ${bytes.length} before its IEND chunk`);
|
|
180
|
+
const length = v.getUint32(at);
|
|
181
|
+
if (length > 0x7fffffff) return malformed(`a chunk at byte ${at} declares ${length} bytes`);
|
|
182
|
+
const typeBytes = bytes.subarray(at + 4, at + 8);
|
|
183
|
+
if (!typeBytes.every((b) => (b >= 0x41 && b <= 0x5a) || (b >= 0x61 && b <= 0x7a)))
|
|
184
|
+
return malformed(`the chunk at byte ${at} has a type that is not four letters`);
|
|
185
|
+
const type = String.fromCharCode(...typeBytes);
|
|
186
|
+
if (at + 12 + length > bytes.length) return truncated(`its ${JSON.stringify(type)} chunk at byte ${at} runs past the end`);
|
|
187
|
+
const data = bytes.subarray(at + 8, at + 8 + length);
|
|
188
|
+
if (crc32(bytes.subarray(at + 4, at + 8 + length)) !== v.getUint32(at + 8 + length)) return err({ kind: "crc", chunk: type, at });
|
|
189
|
+
if (header === undefined && type !== "IHDR") return malformed(`its first chunk is ${JSON.stringify(type)}, not IHDR`);
|
|
190
|
+
switch (type) {
|
|
191
|
+
case "IHDR": {
|
|
192
|
+
if (header !== undefined) return malformed("it has a second IHDR chunk");
|
|
193
|
+
const h = readHeader(data);
|
|
194
|
+
if (h.kind === "err") return h;
|
|
195
|
+
header = h.value;
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
case "PLTE":
|
|
199
|
+
if (length === 0 || length % 3 !== 0 || length > 768) return malformed(`its PLTE chunk holds ${length} bytes`);
|
|
200
|
+
palette = data;
|
|
201
|
+
break;
|
|
202
|
+
case "tRNS":
|
|
203
|
+
trns = data;
|
|
204
|
+
break;
|
|
205
|
+
case "IDAT":
|
|
206
|
+
idat.push(data);
|
|
207
|
+
break;
|
|
208
|
+
case "IEND":
|
|
209
|
+
if (header === undefined) return malformed("it has no IHDR chunk");
|
|
210
|
+
if (idat.length === 0) return malformed("it has no IDAT chunk");
|
|
211
|
+
if (header.colour === 3 && palette === undefined) return malformed("it is a palette picture with no PLTE chunk");
|
|
212
|
+
return ok({ header, palette: palette ?? new Uint8Array(), trns, idat: concat(idat) });
|
|
213
|
+
default:
|
|
214
|
+
if (((typeBytes[0] ?? 0) & 0x20) === 0) return unsupported(`the critical chunk ${JSON.stringify(type)}`);
|
|
215
|
+
}
|
|
216
|
+
at += 12 + length;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** The zlib data inflated by the web standard `DecompressionStream`, which must give exactly `expected` bytes; it is stopped beyond. */
|
|
221
|
+
async function inflate(data: Uint8Array, expected: number): Promise<Result<Uint8Array, PngError>> {
|
|
222
|
+
const out = new Uint8Array(expected);
|
|
223
|
+
let at = 0;
|
|
224
|
+
try {
|
|
225
|
+
const reader = new Blob([new Uint8Array(data)]).stream().pipeThrough(new DecompressionStream("deflate")).getReader();
|
|
226
|
+
for (;;) {
|
|
227
|
+
const { done, value } = await reader.read();
|
|
228
|
+
if (done) break;
|
|
229
|
+
if (at + value.length > expected) {
|
|
230
|
+
await reader.cancel().catch(() => undefined);
|
|
231
|
+
return malformed(`its image data inflates to more than the ${expected} bytes its size needs`);
|
|
232
|
+
}
|
|
233
|
+
out.set(value, at);
|
|
234
|
+
at += value.length;
|
|
235
|
+
}
|
|
236
|
+
} catch (e) {
|
|
237
|
+
return malformed(`its image data is not a zlib stream that inflates: ${e instanceof Error ? e.message : String(e)}`);
|
|
238
|
+
}
|
|
239
|
+
if (at < expected) return truncated(`its image data inflates to ${at} bytes where its size needs ${expected}`);
|
|
240
|
+
return ok(out);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function paeth(a: number, b: number, c: number): number {
|
|
244
|
+
const p = a + b - c;
|
|
245
|
+
const pa = Math.abs(p - a);
|
|
246
|
+
const pb = Math.abs(p - b);
|
|
247
|
+
const pc = Math.abs(p - c);
|
|
248
|
+
return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** The scanlines with their filters undone: `height` rows of `stride` bytes, `bpp` bytes back to the byte on the left. */
|
|
252
|
+
function unfilter(raw: Uint8Array, height: number, stride: number, bpp: number): Result<Uint8Array, PngError> {
|
|
253
|
+
const px = new Uint8Array(stride * height);
|
|
254
|
+
for (let y = 0; y < height; y++) {
|
|
255
|
+
const filter = raw[y * (stride + 1)] ?? 0;
|
|
256
|
+
if (filter > 4) return malformed(`row ${y} has filter type ${filter}`);
|
|
257
|
+
const src = y * (stride + 1) + 1;
|
|
258
|
+
const row = y * stride;
|
|
259
|
+
for (let x = 0; x < stride; x++) {
|
|
260
|
+
const s = raw[src + x] ?? 0;
|
|
261
|
+
const a = x >= bpp ? (px[row + x - bpp] ?? 0) : 0;
|
|
262
|
+
const b = y > 0 ? (px[row - stride + x] ?? 0) : 0;
|
|
263
|
+
const c = x >= bpp && y > 0 ? (px[row - stride + x - bpp] ?? 0) : 0;
|
|
264
|
+
const predicted = filter === 0 ? 0 : filter === 1 ? a : filter === 2 ? b : filter === 3 ? (a + b) >> 1 : paeth(a, b, c);
|
|
265
|
+
px[row + x] = (s + predicted) & 0xff;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return ok(px);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** The unfiltered samples expanded to eight-bit RGBA: palette and `tRNS` applied, sub-byte greyscale scaled, 16-bit samples cut to their high byte. */
|
|
272
|
+
function expand(px: Uint8Array, c: Chunks, stride: number): Result<Uint8Array, PngError> {
|
|
273
|
+
const { width, height, depth, colour, samples } = c.header;
|
|
274
|
+
const out = new Uint8Array(width * height * 4);
|
|
275
|
+
const max = (1 << Math.min(depth, 8)) - 1;
|
|
276
|
+
const trns = c.trns;
|
|
277
|
+
const key = (k: number): number => (trns === undefined ? -1 : ((trns[k * 2] ?? 0) << 8) | (trns[k * 2 + 1] ?? 0));
|
|
278
|
+
const entries = c.palette.length / 3;
|
|
279
|
+
for (let y = 0; y < height; y++) {
|
|
280
|
+
const row = y * stride;
|
|
281
|
+
/** Sample `k` of pixel `x`, at its full depth. */
|
|
282
|
+
const sample = (x: number, k: number): number => {
|
|
283
|
+
if (depth === 16) {
|
|
284
|
+
const i = row + (x * samples + k) * 2;
|
|
285
|
+
return ((px[i] ?? 0) << 8) | (px[i + 1] ?? 0);
|
|
286
|
+
}
|
|
287
|
+
if (depth === 8) return px[row + x * samples + k] ?? 0;
|
|
288
|
+
const bit = x * depth;
|
|
289
|
+
return ((px[row + (bit >> 3)] ?? 0) >> (8 - depth - (bit & 7))) & max;
|
|
290
|
+
};
|
|
291
|
+
const eight = (v: number): number => (depth === 16 ? v >> 8 : depth === 8 ? v : Math.round((v * 255) / max));
|
|
292
|
+
for (let x = 0; x < width; x++) {
|
|
293
|
+
const o = (y * width + x) * 4;
|
|
294
|
+
switch (colour) {
|
|
295
|
+
case 0: {
|
|
296
|
+
const g = sample(x, 0);
|
|
297
|
+
out.set([eight(g), eight(g), eight(g), trns !== undefined && trns.length >= 2 && g === key(0) ? 0 : 255], o);
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
case 2: {
|
|
301
|
+
const [r, g, b] = [sample(x, 0), sample(x, 1), sample(x, 2)];
|
|
302
|
+
const clear = trns !== undefined && trns.length >= 6 && r === key(0) && g === key(1) && b === key(2);
|
|
303
|
+
out.set([eight(r), eight(g), eight(b), clear ? 0 : 255], o);
|
|
304
|
+
break;
|
|
305
|
+
}
|
|
306
|
+
case 3: {
|
|
307
|
+
const k = sample(x, 0);
|
|
308
|
+
if (k >= entries) return malformed(`pixel ${x}, ${y} has palette index ${k} of a palette of ${entries}`);
|
|
309
|
+
out.set([c.palette[k * 3] ?? 0, c.palette[k * 3 + 1] ?? 0, c.palette[k * 3 + 2] ?? 0, trns?.[k] ?? 255], o);
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
312
|
+
case 4: {
|
|
313
|
+
const g = eight(sample(x, 0));
|
|
314
|
+
out.set([g, g, g, eight(sample(x, 1))], o);
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
default:
|
|
318
|
+
out.set([eight(sample(x, 0)), eight(sample(x, 1)), eight(sample(x, 2)), eight(sample(x, 3))], o);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return ok(out);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** A PNG read into eight-bit RGBA, its filters undone and its palette and transparency applied; or why it cannot be. */
|
|
326
|
+
export async function readPng(bytes: Uint8Array): Promise<Result<Picture, PngError>> {
|
|
327
|
+
const chunks = readChunks(bytes);
|
|
328
|
+
if (chunks.kind === "err") return chunks;
|
|
329
|
+
const { width, height, depth, samples } = chunks.value.header;
|
|
330
|
+
const bits = samples * depth;
|
|
331
|
+
const stride = Math.ceil((width * bits) / 8);
|
|
332
|
+
const raw = await inflate(chunks.value.idat, (stride + 1) * height);
|
|
333
|
+
if (raw.kind === "err") return raw;
|
|
334
|
+
const px = unfilter(raw.value, height, stride, Math.max(1, bits >> 3));
|
|
335
|
+
if (px.kind === "err") return px;
|
|
336
|
+
const data = expand(px.value, chunks.value, stride);
|
|
337
|
+
if (data.kind === "err") return data;
|
|
338
|
+
return ok({ width, height, channels: 4, data: data.value });
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async function deflate(data: Uint8Array): Promise<Uint8Array> {
|
|
342
|
+
const stream = new Blob([new Uint8Array(data)]).stream().pipeThrough(new CompressionStream("deflate"));
|
|
343
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function u32be(n: number): Uint8Array {
|
|
347
|
+
const b = new Uint8Array(4);
|
|
348
|
+
new DataView(b.buffer).setUint32(0, n >>> 0);
|
|
349
|
+
return b;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** A PNG chunk: its length, its type, its data and the CRC-32 of its type and data. */
|
|
353
|
+
function chunk(type: string, data: Uint8Array): Uint8Array {
|
|
354
|
+
const body = concat([new TextEncoder().encode(type), data]);
|
|
355
|
+
return concat([u32be(data.length), body, u32be(crc32(body))]);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** A picture written as an eight-bit RGB or RGBA PNG, each row unfiltered, its zlib stream the platform's `CompressionStream`. */
|
|
359
|
+
export async function writePng(p: Picture): Promise<Uint8Array> {
|
|
360
|
+
checkPicture(p);
|
|
361
|
+
const stride = p.width * p.channels;
|
|
362
|
+
const raw = new Uint8Array((stride + 1) * p.height);
|
|
363
|
+
for (let y = 0; y < p.height; y++) raw.set(p.data.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
|
|
364
|
+
const ihdr = new Uint8Array(13);
|
|
365
|
+
const v = new DataView(ihdr.buffer);
|
|
366
|
+
v.setUint32(0, p.width);
|
|
367
|
+
v.setUint32(4, p.height);
|
|
368
|
+
ihdr.set([8, p.channels === 4 ? 6 : 2, 0, 0, 0], 8);
|
|
369
|
+
return concat([Uint8Array.from(SIGNATURE), chunk("IHDR", ihdr), chunk("IDAT", await deflate(raw)), chunk("IEND", new Uint8Array())]);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** `a / 255` rounded down, the way Pillow computes it in integers: `((a >> 8) + a) >> 8`. */
|
|
373
|
+
const div255 = (a: number): number => Math.floor((Math.floor(a / 256) + a) / 256);
|
|
374
|
+
|
|
375
|
+
/** The picture with each colour channel multiplied by its alpha, rounded as Pillow rounds; a picture without alpha as it is. */
|
|
376
|
+
export function premultiply(p: Picture): Picture {
|
|
377
|
+
if (p.channels === 3) return p;
|
|
378
|
+
const data = p.data.slice();
|
|
379
|
+
for (let i = 0; i < data.length; i += 4) {
|
|
380
|
+
const a = data[i + 3] ?? 0;
|
|
381
|
+
for (let c = 0; c < 3; c++) data[i + c] = div255((data[i + c] ?? 0) * a + 128);
|
|
382
|
+
}
|
|
383
|
+
return { ...p, data };
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** The picture with each colour channel divided by its alpha again, as Pillow divides; a picture without alpha as it is. */
|
|
387
|
+
export function unpremultiply(p: Picture): Picture {
|
|
388
|
+
if (p.channels === 3) return p;
|
|
389
|
+
const data = p.data.slice();
|
|
390
|
+
for (let i = 0; i < data.length; i += 4) {
|
|
391
|
+
const a = data[i + 3] ?? 0;
|
|
392
|
+
if (a !== 0 && a !== 255) for (let c = 0; c < 3; c++) data[i + c] = Math.min(255, Math.floor((255 * (data[i + c] ?? 0)) / a));
|
|
393
|
+
}
|
|
394
|
+
return { ...p, data };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const PRECISION_BITS = 32 - 8 - 2;
|
|
398
|
+
const ONE = 2 ** PRECISION_BITS;
|
|
399
|
+
|
|
400
|
+
function lanczos(x: number): number {
|
|
401
|
+
const sinc = (v: number): number => (v === 0 ? 1 : Math.sin(v * Math.PI) / (v * Math.PI));
|
|
402
|
+
return x >= -3 && x < 3 ? sinc(x) * sinc(x / 3) : 0;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** For each output pixel along one axis, the first input pixel it reads and its fixed-point weights, as Pillow computes them. */
|
|
406
|
+
function coefficients(inSize: number, outSize: number): readonly (readonly [number, readonly number[]])[] {
|
|
407
|
+
const scale = Math.fround(inSize) / outSize;
|
|
408
|
+
const filterscale = Math.max(scale, 1);
|
|
409
|
+
const support = 3 * filterscale;
|
|
410
|
+
const inv = 1 / filterscale;
|
|
411
|
+
const out: (readonly [number, readonly number[]])[] = [];
|
|
412
|
+
for (let xx = 0; xx < outSize; xx++) {
|
|
413
|
+
const center = (xx + 0.5) * scale;
|
|
414
|
+
const xmin = Math.max(Math.trunc(center - support + 0.5), 0);
|
|
415
|
+
const xmax = Math.min(Math.trunc(center + support + 0.5), inSize) - xmin;
|
|
416
|
+
const k: number[] = [];
|
|
417
|
+
for (let x = 0; x < xmax; x++) k.push(lanczos((x + xmin - center + 0.5) * inv));
|
|
418
|
+
const ww = k.reduce((a, b) => a + b, 0);
|
|
419
|
+
const norm = ww !== 0 ? k.map((w) => w / ww) : k;
|
|
420
|
+
out.push([xmin, norm.map((w) => (w < 0 ? Math.trunc(-0.5 + w * ONE) : Math.trunc(0.5 + w * ONE)))]);
|
|
421
|
+
}
|
|
422
|
+
return out;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const clip8 = (ss: number): number => Math.min(255, Math.max(0, Math.floor(ss / ONE)));
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* A picture resized with Pillow's Lanczos filter in its fixed point, each channel filtered on its own (alpha too, and the colour channels
|
|
429
|
+
* without regard to it). A size that is not a positive integer throws a `RangeError`.
|
|
430
|
+
*/
|
|
431
|
+
export function resizeChannels(p: Picture, width: number, height: number): Picture {
|
|
432
|
+
if (!isSize(width) || !isSize(height)) throw new RangeError(`a resize to ${width} by ${height} pixels`);
|
|
433
|
+
const ch = p.channels;
|
|
434
|
+
const vert = coefficients(p.height, height);
|
|
435
|
+
const first = vert[0]?.[0] ?? 0;
|
|
436
|
+
const lastV = vert[vert.length - 1];
|
|
437
|
+
const last = lastV === undefined ? p.height : lastV[0] + lastV[1].length;
|
|
438
|
+
let cur = p;
|
|
439
|
+
let offset = 0;
|
|
440
|
+
if (width !== p.width) {
|
|
441
|
+
const horiz = coefficients(p.width, width);
|
|
442
|
+
const rows = last - first;
|
|
443
|
+
const data = new Uint8Array(width * rows * ch);
|
|
444
|
+
for (let y = 0; y < rows; y++) {
|
|
445
|
+
const base = (y + first) * p.width * ch;
|
|
446
|
+
horiz.forEach(([xmin, k], xx) => {
|
|
447
|
+
for (let c = 0; c < ch; c++) {
|
|
448
|
+
let ss = ONE / 2;
|
|
449
|
+
k.forEach((w, x) => (ss += (p.data[base + (x + xmin) * ch + c] ?? 0) * w));
|
|
450
|
+
data[(y * width + xx) * ch + c] = clip8(ss);
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
cur = { width, height: rows, channels: ch, data };
|
|
455
|
+
offset = first;
|
|
456
|
+
}
|
|
457
|
+
if (height !== p.height) {
|
|
458
|
+
const w = cur.width;
|
|
459
|
+
const src = cur.data;
|
|
460
|
+
const data = new Uint8Array(w * height * ch);
|
|
461
|
+
vert.forEach(([ymin0, k], yy) => {
|
|
462
|
+
const ymin = ymin0 - offset;
|
|
463
|
+
for (let x = 0; x < w; x++) {
|
|
464
|
+
for (let c = 0; c < ch; c++) {
|
|
465
|
+
let ss = ONE / 2;
|
|
466
|
+
k.forEach((wt, y) => (ss += (src[((y + ymin) * w + x) * ch + c] ?? 0) * wt));
|
|
467
|
+
data[(yy * w + x) * ch + c] = clip8(ss);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
});
|
|
471
|
+
cur = { width: w, height, channels: ch, data };
|
|
472
|
+
}
|
|
473
|
+
return cur;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** A picture resized as Pillow resizes it with its Lanczos filter: an RGBA picture on premultiplied alpha. The same size gives it back. */
|
|
477
|
+
export function resize(p: Picture, width: number, height: number): Picture {
|
|
478
|
+
if (width === p.width && height === p.height) return p;
|
|
479
|
+
return p.channels === 3 ? resizeChannels(p, width, height) : unpremultiply(resizeChannels(premultiply(p), width, height));
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* `over` laid on `base` with its top left corner at `(left, top)`, as Pillow's `alpha_composite` lays it; what falls outside `base` is
|
|
484
|
+
* cut off. The result has alpha; a picture without alpha is taken as opaque.
|
|
485
|
+
*/
|
|
486
|
+
export function composite(base: Picture, over: Picture, left: number, top: number): Picture {
|
|
487
|
+
const b = rgbaOf(base);
|
|
488
|
+
const o = rgbaOf(over);
|
|
489
|
+
const P = 128;
|
|
490
|
+
const data = b.data.slice();
|
|
491
|
+
for (let y = Math.max(0, -top); y < o.height && y + top < b.height; y++) {
|
|
492
|
+
for (let x = Math.max(0, -left); x < o.width && x + left < b.width; x++) {
|
|
493
|
+
const s = (y * o.width + x) * 4;
|
|
494
|
+
const i = ((y + top) * b.width + x + left) * 4;
|
|
495
|
+
const sa = o.data[s + 3] ?? 0;
|
|
496
|
+
if (sa === 0) continue;
|
|
497
|
+
const da = data[i + 3] ?? 0;
|
|
498
|
+
const outa255 = sa * 255 + da * (255 - sa);
|
|
499
|
+
const coef1 = Math.floor((sa * 255 * 255 * P) / outa255);
|
|
500
|
+
const coef2 = 255 * P - coef1;
|
|
501
|
+
for (let c = 0; c < 3; c++)
|
|
502
|
+
data[i + c] = Math.floor(div255((o.data[s + c] ?? 0) * coef1 + (data[i + c] ?? 0) * coef2 + 0x80 * P) / P);
|
|
503
|
+
data[i + 3] = div255(outa255 + 0x80);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return { ...b, data };
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** `art` laid at `(left, top)` on an opaque canvas of `colour`, the result without alpha. */
|
|
510
|
+
export function flatOn(colour: Rgb, width: number, height: number, art: Picture, left: number, top: number): Picture {
|
|
511
|
+
return rgbOf(composite(filled(width, height, [colour[0], colour[1], colour[2], 255]), art, left, top));
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** The size Pillow's `thumbnail` gives a picture fitted in `width` by `height`, its aspect kept; `undefined` where it already fits. */
|
|
515
|
+
export function thumbnailSize(p: Picture, width: number, height: number): readonly [number, number] | undefined {
|
|
516
|
+
if (width >= p.width && height >= p.height) return undefined;
|
|
517
|
+
const aspect = p.width / p.height;
|
|
518
|
+
const pick = (n: number, key: (v: number) => number): number => {
|
|
519
|
+
const lo = Math.floor(n);
|
|
520
|
+
const hi = Math.ceil(n);
|
|
521
|
+
return Math.max(key(hi) < key(lo) ? hi : lo, 1);
|
|
522
|
+
};
|
|
523
|
+
return width / height >= aspect
|
|
524
|
+
? [pick(height * aspect, (n) => Math.abs(aspect - n / height)), height]
|
|
525
|
+
: [width, pick(width / aspect, (n) => (n === 0 ? 0 : Math.abs(aspect - width / n)))];
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* A multi-size icon file of PNG frames, as Pillow writes one: one frame for each size asked that is at most the picture's width, height
|
|
530
|
+
* and 256, smallest first, each the picture fitted in that square (`thumbnailSize`) and resized (`resize`).
|
|
531
|
+
*/
|
|
532
|
+
export async function writeIco(p: Picture, sizes: readonly number[]): Promise<Uint8Array> {
|
|
533
|
+
const frames: Picture[] = [];
|
|
534
|
+
for (const s of [...new Set(sizes)].sort((a, b) => a - b).filter((s) => isSize(s) && s <= p.width && s <= p.height && s <= 256)) {
|
|
535
|
+
const t = s === p.width && s === p.height ? undefined : thumbnailSize(p, s, s);
|
|
536
|
+
frames.push(t === undefined ? p : resize(p, t[0], t[1]));
|
|
537
|
+
}
|
|
538
|
+
const pngs = await Promise.all(frames.map(writePng));
|
|
539
|
+
const head = new Uint8Array(6 + 16 * frames.length);
|
|
540
|
+
const v = new DataView(head.buffer);
|
|
541
|
+
v.setUint16(2, 1, true);
|
|
542
|
+
v.setUint16(4, frames.length, true);
|
|
543
|
+
let offset = head.length;
|
|
544
|
+
frames.forEach((f, i) => {
|
|
545
|
+
const e = 6 + 16 * i;
|
|
546
|
+
const size = pngs[i]?.length ?? 0;
|
|
547
|
+
head[e] = f.width < 256 ? f.width : 0;
|
|
548
|
+
head[e + 1] = f.height < 256 ? f.height : 0;
|
|
549
|
+
v.setUint16(e + 6, 32, true);
|
|
550
|
+
v.setUint32(e + 8, size, true);
|
|
551
|
+
v.setUint32(e + 12, offset, true);
|
|
552
|
+
offset += size;
|
|
553
|
+
});
|
|
554
|
+
return concat([head, ...pngs]);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Every frame of an icon file whose frames are PNGs, in the order of its directory; or why it cannot be read. */
|
|
558
|
+
export async function readIco(bytes: Uint8Array): Promise<Result<readonly Picture[], PngError>> {
|
|
559
|
+
if (bytes.length < 6 || bytes[0] !== 0 || bytes[1] !== 0 || bytes[2] !== 1 || bytes[3] !== 0)
|
|
560
|
+
return err({ kind: "signature", format: "ico" });
|
|
561
|
+
const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
562
|
+
const count = v.getUint16(4, true);
|
|
563
|
+
if (6 + 16 * count > bytes.length) return truncated(`the icon directory of ${count} frames runs past the end`);
|
|
564
|
+
const out: Picture[] = [];
|
|
565
|
+
for (let i = 0; i < count; i++) {
|
|
566
|
+
const e = 6 + 16 * i;
|
|
567
|
+
const size = v.getUint32(e + 8, true);
|
|
568
|
+
const offset = v.getUint32(e + 12, true);
|
|
569
|
+
if (offset + size > bytes.length) return truncated(`frame ${i} of the icon file runs past the end`);
|
|
570
|
+
const frame = bytes.subarray(offset, offset + size);
|
|
571
|
+
if (SIGNATURE.some((b, k) => frame[k] !== b)) return unsupported(`frame ${i} of the icon file is not a PNG (a BMP frame)`);
|
|
572
|
+
const p = await readPng(frame);
|
|
573
|
+
if (p.kind === "err") return err({ kind: "ico-frame", index: i, error: p.error });
|
|
574
|
+
out.push(p.value);
|
|
575
|
+
}
|
|
576
|
+
return ok(out);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** Whether two pictures have the same size and the same RGBA pixels (a picture without alpha taken as opaque). */
|
|
580
|
+
export function samePixels(a: Picture, b: Picture): boolean {
|
|
581
|
+
if (a.width !== b.width || a.height !== b.height) return false;
|
|
582
|
+
const x = rgbaOf(a).data;
|
|
583
|
+
const y = rgbaOf(b).data;
|
|
584
|
+
return x.length === y.length && x.every((v, i) => v === y[i]);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** Whether two PNG files, or two icon files, hold the same pictures pixel for pixel, whatever their zlib streams; false where either cannot be read. */
|
|
588
|
+
export async function samePicture(a: Uint8Array, b: Uint8Array): Promise<boolean> {
|
|
589
|
+
if (a.length === b.length && a.every((x, i) => x === b[i])) return true;
|
|
590
|
+
const isIco = (x: Uint8Array): boolean => x[0] === 0 && x[1] === 0 && x[2] === 1 && x[3] === 0;
|
|
591
|
+
if (isIco(a) && isIco(b)) {
|
|
592
|
+
const [x, y] = [await readIco(a), await readIco(b)];
|
|
593
|
+
return (
|
|
594
|
+
x.kind === "ok" &&
|
|
595
|
+
y.kind === "ok" &&
|
|
596
|
+
x.value.length === y.value.length &&
|
|
597
|
+
x.value.every((f, i) => {
|
|
598
|
+
const g = y.value[i];
|
|
599
|
+
return g !== undefined && samePixels(f, g);
|
|
600
|
+
})
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
const [x, y] = [await readPng(a), await readPng(b)];
|
|
604
|
+
return x.kind === "ok" && y.kind === "ok" && samePixels(x.value, y.value);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i;
|
|
608
|
+
|
|
609
|
+
/** A `#rrggbb` or `#rgb` colour (the `#` optional, any case) as its channels; `undefined` for what is not one. */
|
|
610
|
+
export function hexRgb(hex: string): Rgb | undefined {
|
|
611
|
+
const digits = HEX.exec(hex)?.[1];
|
|
612
|
+
if (digits === undefined) return undefined;
|
|
613
|
+
const full = digits.length === 3 ? [...digits].map((d) => d + d).join("") : digits;
|
|
614
|
+
const c = (i: number): number => Number.parseInt(full.slice(i, i + 2), 16);
|
|
615
|
+
return [c(0), c(2), c(4)];
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** A colour's relative luminance as WCAG 2 measures it, from 0 (black) to 1 (white). */
|
|
619
|
+
export function luminance(rgb: Rgb): number {
|
|
620
|
+
const linear = (v: number): number => {
|
|
621
|
+
const x = v / 255;
|
|
622
|
+
return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
|
|
623
|
+
};
|
|
624
|
+
return 0.2126 * linear(rgb[0]) + 0.7152 * linear(rgb[1]) + 0.0722 * linear(rgb[2]);
|
|
625
|
+
}
|