imagescript 4.0.0-rc.4 → 4.0.0-rc.6
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 +9 -5
- package/dist/animation-encoder.d.ts +2 -1
- package/dist/animation-encoder.js +23 -19
- package/dist/animation.d.ts +26 -20
- package/dist/animation.js +58 -55
- package/dist/codecs/avif-enc.js +3 -3
- package/dist/codecs/avif.js +7 -2
- package/dist/codecs/bmp.js +1 -1
- package/dist/codecs/gif.js +2 -2
- package/dist/codecs/jpeg.js +55 -14
- package/dist/codecs/jxl/vardct-enc.js +2 -1
- package/dist/codecs/png.js +7 -3
- package/dist/codecs/tga.js +4 -3
- package/dist/codecs/tiff.js +1 -1
- package/dist/codecs/vp8.js +1 -1
- package/dist/codecs/vp8l.js +4 -3
- package/dist/codecs/webp.js +11 -9
- package/dist/colors.d.ts +10 -8
- package/dist/colors.js +28 -31
- package/dist/frame.d.ts +4 -3
- package/dist/frame.js +6 -8
- package/dist/gainmap.d.ts +6 -6
- package/dist/gainmap.js +32 -24
- package/dist/image.d.ts +75 -37
- package/dist/image.js +189 -163
- package/dist/metadata.d.ts +12 -1
- package/dist/metadata.js +30 -5
- package/dist/render/color.js +16 -3
- package/dist/render/colr.js +3 -3
- package/dist/render/filter.js +27 -3
- package/dist/render/font.js +54 -18
- package/dist/render/layout.js +2 -2
- package/dist/render/linebreak.js +9 -12
- package/dist/render/svg-text.js +112 -28
- package/dist/render/svg.js +183 -34
- package/dist/render/text.js +93 -23
- package/dist/text-layout.d.ts +2 -1
- package/dist/text-layout.js +3 -8
- package/dist/util/alpha.js +1 -1
- package/dist/util/inspect.js +16 -0
- package/dist/util/limits.d.ts +16 -3
- package/dist/util/limits.js +20 -5
- package/dist/util/mem.d.ts +2 -0
- package/dist/util/mem.js +24 -4
- package/dist/util/optimize.js +4 -3
- package/dist/util/options.js +104 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
**ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, and no
|
|
17
17
|
runtime dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's
|
|
18
18
|
Edge Runtime, Deno Deploy), works with `import` and, on supported Node.js versions, `require()`, and ships with type
|
|
19
|
-
definitions (TypeScript 5.7 or newer:
|
|
19
|
+
definitions (TypeScript 5.7 or newer; CommonJS projects need `module: nodenext` and 5.8 or newer to `import` it (`module: node16` can't). With older versions and `skipLibCheck`, the encoders' return types become `any`). Large AVIF and JPEG XL operations, and lossless WebP encoding, can use multiple CPU cores when the runtime
|
|
20
20
|
supports it.
|
|
21
21
|
|
|
22
22
|
```sh
|
|
@@ -24,7 +24,7 @@ npm install imagescript # Node.js, Bun and bundlers
|
|
|
24
24
|
deno add jsr:@matmen/imagescript # Deno
|
|
25
25
|
```
|
|
26
26
|
|
|
27
|
-
Upgrading from 3.x? Read [Migrating to 4.0](https://github.com/imagescript/ImageScript/blob/
|
|
27
|
+
Upgrading from 3.x? Read [Migrating to 4.0](https://github.com/imagescript/ImageScript/blob/master/guides/Migrating%20to%204.0.md) first.
|
|
28
28
|
|
|
29
29
|
Without a bundler, import it from jsDelivr in the browser:
|
|
30
30
|
|
|
@@ -45,8 +45,8 @@ calling thread: the output is the same, only slower, and nothing warns about it.
|
|
|
45
45
|
origin, so the jsDelivr example above runs single-threaded; serve the package from your own origin (on a cross-origin
|
|
46
46
|
isolated page) to get threads.
|
|
47
47
|
|
|
48
|
-
Bundlers that write one file (esbuild,
|
|
49
|
-
bundle, or the same single-threaded fallback is used.
|
|
48
|
+
Bundlers that write one file (esbuild, Rollup, `bun build`) don't copy the worker's module: serve `dist/util/worker.js` next to the
|
|
49
|
+
bundle, or the same single-threaded fallback is used. webpack and Vite emit it.
|
|
50
50
|
|
|
51
51
|
---
|
|
52
52
|
|
|
@@ -88,7 +88,11 @@ await writeFile('output.png', await image.encodePNG());
|
|
|
88
88
|
[Animations](https://imagescript.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL,
|
|
89
89
|
and encoded as GIF, APNG or WebP, all at once or
|
|
90
90
|
[frame by frame](https://imagescript.dev/classes/Animation.html#webpencoder). Lossless encoding keeps every pixel
|
|
91
|
-
exactly; lossy encoding makes smaller files by approximating some image detail.
|
|
91
|
+
exactly; lossy encoding makes smaller files by approximating some image detail. `quality: 100` is lossless for WebP,
|
|
92
|
+
AVIF and JPEG XL (JPEG has no lossless mode). Without a `quality`, WebP and JPEG XL are lossless and AVIF is lossy.
|
|
93
|
+
|
|
94
|
+
Not supported (decoding them throws an error): CCITT-compressed TIFF and arithmetic-coded JPEG. Lossless JPEG XL is
|
|
95
|
+
fast but not small: for small lossless files, PNG or WebP are the better choice.
|
|
92
96
|
|
|
93
97
|
Embedded color profiles are converted to sRGB, the standard color format for most screens, where supported. CMYK and
|
|
94
98
|
lookup-table profiles are left unchanged.
|
|
@@ -34,7 +34,8 @@ export declare class AnimationEncoder {
|
|
|
34
34
|
add(frame: Frame | Image, options?: FrameOptions): Promise<void>;
|
|
35
35
|
/**
|
|
36
36
|
* Encodes the rest and returns the file. The encoder can't be used afterwards
|
|
37
|
-
* @throws `
|
|
37
|
+
* @throws `RangeError` if no frame was added
|
|
38
|
+
* @throws `Error` if the encoder is finished already
|
|
38
39
|
*/
|
|
39
40
|
finish(): Promise<Uint8Array<ArrayBuffer>>;
|
|
40
41
|
}
|
|
@@ -7,7 +7,8 @@ import { Frame } from "./frame.js";
|
|
|
7
7
|
import { Optimizer, Compositor, coverCanvas, fillUnchanged } from "./util/optimize.js";
|
|
8
8
|
import { compressAsync, decompressAsync } from "./codecs/zlib.js";
|
|
9
9
|
import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
|
|
10
|
-
import { checkOptions, finite, compressionLevel, loopCount, toPlays, fitLoops, fitDuration, maxDuration } from "./util/options.js";
|
|
10
|
+
import { instance, checkOptions, finite, nonNegative, canvasSize, compressionLevel, loopCount, toPlays, fitLoops, fitDuration, maxDuration, boolean } from "./util/options.js";
|
|
11
|
+
import { checkFormatSize } from "./util/limits.js";
|
|
11
12
|
function clipToCanvas(frame, width, height) {
|
|
12
13
|
const { x, y, width: w, height: h } = frame;
|
|
13
14
|
if (x >= 0 && y >= 0 && x + w <= width && y + h <= height)
|
|
@@ -30,6 +31,8 @@ export class AnimationEncoder {
|
|
|
30
31
|
height;
|
|
31
32
|
constructor(width, height, format, optimize) {
|
|
32
33
|
this.format = format;
|
|
34
|
+
if (!format)
|
|
35
|
+
throw new TypeError('AnimationEncoder is created by Animation.gifEncoder(), apngEncoder() or webpEncoder()');
|
|
33
36
|
this.width = width;
|
|
34
37
|
this.height = height;
|
|
35
38
|
this.optimizer = optimize ? new Optimizer(width, height, format.optimize) : null;
|
|
@@ -41,13 +44,10 @@ export class AnimationEncoder {
|
|
|
41
44
|
checkOptions(options, 'encoder.add(frame, { duration: 40 })');
|
|
42
45
|
if (this.finished)
|
|
43
46
|
throw new Error('The animation encoder is finished');
|
|
47
|
+
instance(frame, [Frame, Image], 'the frame of encoder.add()');
|
|
44
48
|
const own = frame instanceof Frame ? frame : null;
|
|
45
49
|
const image = own ? own.image : frame;
|
|
46
|
-
|
|
47
|
-
throw new TypeError('encoder.add() takes a Frame or an Image');
|
|
48
|
-
const duration = finite(options.duration === undefined ? own?.duration ?? 100 : options.duration, 'frame duration');
|
|
49
|
-
if (duration < 0)
|
|
50
|
-
throw new RangeError('Invalid frame duration');
|
|
50
|
+
const duration = nonNegative(options.duration === undefined ? own?.duration ?? 100 : options.duration, 'frame duration');
|
|
51
51
|
fitDuration(duration, this.format.name);
|
|
52
52
|
const x = Math.trunc(finite(options.xOffset === undefined ? own?.xOffset ?? 0 : options.xOffset, 'x offset')) || 0;
|
|
53
53
|
const y = Math.trunc(finite(options.yOffset === undefined ? own?.yOffset ?? 0 : options.yOffset, 'y offset')) || 0;
|
|
@@ -72,8 +72,10 @@ export class AnimationEncoder {
|
|
|
72
72
|
throw new Error('The animation encoder is finished');
|
|
73
73
|
this.finished = true;
|
|
74
74
|
await this.queue;
|
|
75
|
-
if (!this.count)
|
|
76
|
-
|
|
75
|
+
if (!this.count) {
|
|
76
|
+
this.finished = false;
|
|
77
|
+
throw new RangeError('An animation needs at least one frame, not 0');
|
|
78
|
+
}
|
|
77
79
|
if (this.optimizer)
|
|
78
80
|
for (const f of this.optimizer.end())
|
|
79
81
|
await this.format.frame(f, true);
|
|
@@ -82,10 +84,10 @@ export class AnimationEncoder {
|
|
|
82
84
|
return this.format.file(optimizer);
|
|
83
85
|
}
|
|
84
86
|
static __webp__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }) {
|
|
87
|
+
boolean(optimize, 'optimize');
|
|
85
88
|
const loops = fitLoops(loopCount(count), 'WebP');
|
|
86
|
-
canvas(width, height, 'WebP');
|
|
87
|
-
|
|
88
|
-
throw new RangeError('WebP: canvas too large');
|
|
89
|
+
[width, height] = canvas(width, height, 'WebP');
|
|
90
|
+
checkFormatSize('WebP', width, height, 1 << 24);
|
|
89
91
|
const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
|
|
90
92
|
const resolved = resolveMetadata(metadata), chunks = [];
|
|
91
93
|
let alpha = false;
|
|
@@ -114,8 +116,9 @@ export class AnimationEncoder {
|
|
|
114
116
|
static __gif__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85 }) {
|
|
115
117
|
const checked = paletteOptions(colors, dither, ditherStrength);
|
|
116
118
|
const palette = { colors: checked.colors, dither: checked.dither, strength: checked.strength };
|
|
119
|
+
boolean(optimize, 'optimize');
|
|
117
120
|
const loops = fitLoops(loopCount(count), 'GIF');
|
|
118
|
-
canvas(width, height, 'GIF');
|
|
121
|
+
[width, height] = canvas(width, height, 'GIF');
|
|
119
122
|
const comments = gifComments(resolveMetadata(metadata));
|
|
120
123
|
let first = null, restores = false;
|
|
121
124
|
const rest = [];
|
|
@@ -142,8 +145,9 @@ export class AnimationEncoder {
|
|
|
142
145
|
}
|
|
143
146
|
static __apng__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, compression: compressionOption = 4 }) {
|
|
144
147
|
const compression = compressionLevel(compressionOption);
|
|
148
|
+
boolean(optimize, 'optimize');
|
|
145
149
|
const loops = fitLoops(loopCount(count), 'APNG');
|
|
146
|
-
canvas(width, height, 'APNG');
|
|
150
|
+
[width, height] = canvas(width, height, 'APNG');
|
|
147
151
|
const text = pngText(resolveMetadata(metadata));
|
|
148
152
|
const stored = [];
|
|
149
153
|
const cost = new png.AlphaCost();
|
|
@@ -190,13 +194,13 @@ export class AnimationEncoder {
|
|
|
190
194
|
}, optimize);
|
|
191
195
|
}
|
|
192
196
|
}
|
|
193
|
-
function canvas(
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
197
|
+
function canvas(widthArgument, heightArgument, format) {
|
|
198
|
+
const [width, height] = canvasSize(widthArgument, heightArgument);
|
|
199
|
+
if (format === 'GIF')
|
|
200
|
+
checkFormatSize('GIF', width, height, 0xffff);
|
|
201
|
+
return [width, height];
|
|
198
202
|
}
|
|
199
|
-
function webpFrame(f) {
|
|
203
|
+
export function webpFrame(f) {
|
|
200
204
|
let { x, y, width: w, height: h, pixels } = f;
|
|
201
205
|
if (x & 1 || y & 1) {
|
|
202
206
|
const dx = x & 1, dy = y & 1;
|
package/dist/animation.d.ts
CHANGED
|
@@ -14,7 +14,8 @@ export interface AnimationOptions {
|
|
|
14
14
|
/** Options of {@link Animation}'s constructor: the canvas size and the loop count */
|
|
15
15
|
export interface AnimationCanvasOptions extends AnimationOptions {
|
|
16
16
|
/**
|
|
17
|
-
* The canvas width in pixels: frames (or the parts of them)
|
|
17
|
+
* The canvas width in pixels (a fraction is truncated, like the size of an image): frames (or the parts of them)
|
|
18
|
+
* outside the canvas aren't encoded
|
|
18
19
|
* @defaultValue The frames' right edge (the largest `xOffset + width`), following the frames until a canvas size is
|
|
19
20
|
* set
|
|
20
21
|
*/
|
|
@@ -132,7 +133,8 @@ export declare class Animation {
|
|
|
132
133
|
*/
|
|
133
134
|
resize(options: ResizeToOptions): this;
|
|
134
135
|
/**
|
|
135
|
-
* Crops the canvas to the given region: the frames move with it and are cut to the new canvas
|
|
136
|
+
* Crops the canvas to the given region: the frames move with it and are cut to the new canvas (the same `Frame`
|
|
137
|
+
* objects, with new images where they are cut; a frame entirely outside becomes a transparent pixel). The region is
|
|
136
138
|
* clipped to the canvas, so the result can be smaller than the requested size
|
|
137
139
|
* @param x The x offset (0-based)
|
|
138
140
|
* @param y The y offset (0-based)
|
|
@@ -155,7 +157,8 @@ export declare class Animation {
|
|
|
155
157
|
/**
|
|
156
158
|
* Trims the canvas: removes the borders of one color around what any frame shows (in the composited animation),
|
|
157
159
|
* like {@link Image.trim}. The frames keep their pixels, the canvas is cropped like {@link Animation.crop}
|
|
158
|
-
* @param options The color (by default the top left pixel of the first frame) and the
|
|
160
|
+
* @param options The color (by default the top left pixel of the canvas as the first frame shows it) and the
|
|
161
|
+
* tolerance, see
|
|
159
162
|
* {@link TrimOptions}
|
|
160
163
|
*/
|
|
161
164
|
trim(options?: TrimOptions): this;
|
|
@@ -192,9 +195,9 @@ export declare class Animation {
|
|
|
192
195
|
* before and merges identical frames (unless the `optimize` option is false), so the file decodes to what the
|
|
193
196
|
* animation shows, but not necessarily to the same frames. Semi-transparent pixels become opaque or transparent
|
|
194
197
|
* after the frames are composited
|
|
195
|
-
* @param options See {@link GIFAnimationEncodeOptions}
|
|
196
|
-
* @
|
|
197
|
-
* @throws `RangeError` if the loop count or a frame's duration is more than GIF stores, or the canvas is wider or
|
|
198
|
+
* @param options See {@link GIFAnimationEncodeOptions}; the loop count is the animation's {@link loopCount} (the
|
|
199
|
+
* streaming {@link gifEncoder} takes it as an option)
|
|
200
|
+
* @throws `RangeError` if the animation has no frames, the loop count or a frame's duration is more than GIF stores, or the canvas is wider or
|
|
198
201
|
* higher than 65535 pixels
|
|
199
202
|
*/
|
|
200
203
|
encodeGIF(options?: GIFAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
@@ -203,18 +206,18 @@ export declare class Animation {
|
|
|
203
206
|
* the first frame. Each frame is stored as the area that changed since the frame before, identical frames are
|
|
204
207
|
* merged (unless the `optimize` option is false): the file shows exactly the same animation, but doesn't
|
|
205
208
|
* necessarily decode to the same frames
|
|
206
|
-
* @param options See {@link APNGEncodeOptions}
|
|
207
|
-
*
|
|
208
|
-
* @throws `RangeError` if the loop count or a frame's duration is more than APNG stores
|
|
209
|
+
* @param options See {@link APNGEncodeOptions}; the loop count is the animation's {@link loopCount} (the streaming
|
|
210
|
+
* {@link apngEncoder} takes it as an option)
|
|
211
|
+
* @throws `RangeError` if the animation has no frames, the loop count or a frame's duration is more than APNG stores
|
|
209
212
|
*/
|
|
210
213
|
encodeAPNG(options?: APNGEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
211
214
|
/**
|
|
212
|
-
* Encodes the animation as animated WebP, lossless or (with a quality) lossy. Each frame is stored as the area that
|
|
215
|
+
* Encodes the animation as animated WebP, lossless or (with a quality below 100) lossy. Each frame is stored as the area that
|
|
213
216
|
* changed since the frame before, identical frames are merged (unless the `optimize` option is false): the file
|
|
214
217
|
* shows the same animation, but doesn't necessarily decode to the same frames
|
|
215
|
-
* @param options See {@link WebPAnimationEncodeOptions}
|
|
216
|
-
* @
|
|
217
|
-
* @throws `RangeError` if the loop count or a frame's duration is more than WebP stores
|
|
218
|
+
* @param options See {@link WebPAnimationEncodeOptions}; the loop count is the animation's {@link loopCount} (the
|
|
219
|
+
* streaming {@link webpEncoder} takes it as an option)
|
|
220
|
+
* @throws `RangeError` if the animation has no frames, the loop count or a frame's duration is more than WebP stores
|
|
218
221
|
*/
|
|
219
222
|
encodeWebP(options?: WebPAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
220
223
|
/**
|
|
@@ -228,16 +231,16 @@ export declare class Animation {
|
|
|
228
231
|
* await encoder.add(new Image(64, 64).fill(color), { duration: 200 });
|
|
229
232
|
* const webp = await encoder.finish();
|
|
230
233
|
* ```
|
|
231
|
-
* @param width The canvas width
|
|
232
|
-
* @param height The canvas height
|
|
234
|
+
* @param width The canvas width in pixels (a fraction is truncated, like the size of an image)
|
|
235
|
+
* @param height The canvas height in pixels (a fraction is truncated)
|
|
233
236
|
* @param options See {@link WebPAnimationEncodeOptions}, and {@link AnimationOptions.loopCount}
|
|
234
237
|
*/
|
|
235
238
|
static webpEncoder(width: number, height: number, options?: WebPAnimationEncodeOptions & AnimationOptions): AnimationEncoder;
|
|
236
239
|
/**
|
|
237
240
|
* An encoder that makes an animated GIF a frame at a time, like {@link Animation.encodeGIF} (the same file),
|
|
238
241
|
* without keeping the frames in memory: `await encoder.add(frame)` for each frame, then `await encoder.finish()`
|
|
239
|
-
* @param width The canvas width
|
|
240
|
-
* @param height The canvas height
|
|
242
|
+
* @param width The canvas width in pixels (a fraction is truncated, like the size of an image)
|
|
243
|
+
* @param height The canvas height in pixels (a fraction is truncated)
|
|
241
244
|
* @param options See {@link GIFAnimationEncodeOptions}, and {@link AnimationOptions.loopCount}
|
|
242
245
|
*/
|
|
243
246
|
static gifEncoder(width: number, height: number, options?: GIFAnimationEncodeOptions & AnimationOptions): AnimationEncoder;
|
|
@@ -245,8 +248,8 @@ export declare class Animation {
|
|
|
245
248
|
* An encoder that makes an APNG a frame at a time, like {@link Animation.encodeAPNG} (the same file), keeping the
|
|
246
249
|
* frames only compressed (the pixel format depends on all of them): `await encoder.add(frame)` for each frame,
|
|
247
250
|
* then `await encoder.finish()`
|
|
248
|
-
* @param width The canvas width
|
|
249
|
-
* @param height The canvas height
|
|
251
|
+
* @param width The canvas width in pixels (a fraction is truncated, like the size of an image)
|
|
252
|
+
* @param height The canvas height in pixels (a fraction is truncated)
|
|
250
253
|
* @param options See {@link APNGEncodeOptions}, and {@link AnimationOptions.loopCount}
|
|
251
254
|
*/
|
|
252
255
|
static apngEncoder(width: number, height: number, options?: APNGEncodeOptions & AnimationOptions): AnimationEncoder;
|
|
@@ -257,10 +260,13 @@ export declare class Animation {
|
|
|
257
260
|
* const animation = await Animation.decode(gifBytes);
|
|
258
261
|
* const webp = await animation.resize({ width: 320 }).encodeWebP({ quality: 75 });
|
|
259
262
|
* ```
|
|
263
|
+
* @remarks A still image becomes one frame of 100 ms, the {@link Frame} default. An AVIF image sequence is decoded as
|
|
264
|
+
* its first frame only. A file that is cut off keeps the frames that arrived whole (like browsers show it) and
|
|
265
|
+
* throws when not even the first one did
|
|
260
266
|
* @param input The binary data to decode
|
|
261
267
|
* @param options See {@link DecodeOptions}
|
|
262
268
|
* @throws {@link LimitError} if the frames have more than `options.maxPixels` pixels together
|
|
263
|
-
* @throws `Error` if the data isn't a supported image, or is damaged or
|
|
269
|
+
* @throws `Error` if the data isn't a supported image, or is damaged or cut off before its first whole frame
|
|
264
270
|
*/
|
|
265
271
|
static decode(input: BinaryData, options?: DecodeOptions): Promise<Animation>;
|
|
266
272
|
}
|
package/dist/animation.js
CHANGED
|
@@ -9,12 +9,13 @@ import { GainMap } from "./gainmap.js";
|
|
|
9
9
|
import { Image, resizeArguments, insideSize, alignedPixels, FLIP_DIRECTIONS, TONE_MAPPINGS } from "./image.js";
|
|
10
10
|
import { Frame } from "./frame.js";
|
|
11
11
|
import { ImageType } from "./image-type.js";
|
|
12
|
-
import { optimize } from "./util/optimize.js";
|
|
12
|
+
import { optimize, Compositor } from "./util/optimize.js";
|
|
13
13
|
import { paletteOptions } from "./codecs/quantize.js";
|
|
14
14
|
import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
|
|
15
|
-
import { checkOptions, oneOf, pixelLimit, checkThreads,
|
|
16
|
-
import { MAX_PIXELS, decoding, checkPixels } from "./util/limits.js";
|
|
17
|
-
import { AnimationEncoder } from "./animation-encoder.js";
|
|
15
|
+
import { shown, scaleFactor, checkOptions, oneOf, pixelLimit, checkThreads, pixels, canvasSize, cropBounds, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, boolean, color as checkColor } from "./util/options.js";
|
|
16
|
+
import { MAX_PIXELS, decoding, checkPixels, checkFormatSize } from "./util/limits.js";
|
|
17
|
+
import { AnimationEncoder, webpFrame } from "./animation-encoder.js";
|
|
18
|
+
import { describe } from "./util/inspect.js";
|
|
18
19
|
function canvasFrames(width, height, frames) {
|
|
19
20
|
return frames.map(({ pixels, duration }) => {
|
|
20
21
|
const image = new Image(width, height);
|
|
@@ -29,7 +30,7 @@ export class Animation {
|
|
|
29
30
|
__framesView__ = null;
|
|
30
31
|
__canvas__ = null;
|
|
31
32
|
constructor(frames, options = {}) {
|
|
32
|
-
checkOptions(options, 'Animation(frames, { loopCount: 2 })');
|
|
33
|
+
checkOptions(options, 'new Animation(frames, { loopCount: 2 })');
|
|
33
34
|
const { loopCount: count = Infinity, width, height } = options;
|
|
34
35
|
const loops = loopCount(count);
|
|
35
36
|
if ((width === undefined) !== (height === undefined))
|
|
@@ -49,10 +50,12 @@ export class Animation {
|
|
|
49
50
|
return this.__framesView__ ??= Object.freeze([...this.__frames__]);
|
|
50
51
|
}
|
|
51
52
|
set frames(frames) {
|
|
53
|
+
if (frames === null || typeof frames !== 'object' || typeof frames[Symbol.iterator] !== 'function')
|
|
54
|
+
throw new TypeError(`Animation() takes an array of Frame objects, not ${shown(frames)}`);
|
|
52
55
|
const copy = [];
|
|
53
56
|
for (const frame of frames) {
|
|
54
57
|
if (!(frame instanceof Frame))
|
|
55
|
-
throw new TypeError(`
|
|
58
|
+
throw new TypeError(`frames[${copy.length}] must be a Frame, not ${shown(frame)}`);
|
|
56
59
|
copy.push(frame);
|
|
57
60
|
}
|
|
58
61
|
this.__frames__ = copy;
|
|
@@ -106,10 +109,10 @@ export class Animation {
|
|
|
106
109
|
const originalWidth = this.width, originalHeight = this.height;
|
|
107
110
|
if (!originalWidth || !originalHeight)
|
|
108
111
|
throw new RangeError('An animation without frames or canvas can\'t be resized');
|
|
109
|
-
if (givenWidth !== undefined
|
|
110
|
-
|
|
111
|
-
if (givenHeight !== undefined
|
|
112
|
-
|
|
112
|
+
if (givenWidth !== undefined)
|
|
113
|
+
pixels(givenWidth, 'width');
|
|
114
|
+
if (givenHeight !== undefined)
|
|
115
|
+
pixels(givenHeight, 'height');
|
|
113
116
|
let width, height;
|
|
114
117
|
if (fit === 'inside' && givenWidth !== undefined && givenHeight !== undefined)
|
|
115
118
|
[width, height] = insideSize(originalWidth, originalHeight, givenWidth, givenHeight).map(Math.floor);
|
|
@@ -151,24 +154,31 @@ export class Animation {
|
|
|
151
154
|
return this;
|
|
152
155
|
}
|
|
153
156
|
crop(x, y, width, height) {
|
|
154
|
-
const left =
|
|
155
|
-
const right = Math.min(this.width, Math.floor(finite(x, 'x')) + Math.floor(finite(width, 'width')));
|
|
156
|
-
const bottom = Math.min(this.height, Math.floor(finite(y, 'y')) + Math.floor(finite(height, 'height')));
|
|
157
|
-
if (!(right - left >= 1 && bottom - top >= 1))
|
|
158
|
-
throw new RangeError('The crop region has to overlap the canvas');
|
|
157
|
+
const [left, top, newWidth, newHeight] = cropBounds(this.width, this.height, x, y, width, height, 'canvas');
|
|
159
158
|
for (const frame of this.__distinct__()) {
|
|
160
|
-
frame.xOffset
|
|
161
|
-
|
|
159
|
+
const frameLeft = frame.xOffset - left, frameTop = frame.yOffset - top;
|
|
160
|
+
const cutLeft = Math.max(0, frameLeft), cutTop = Math.max(0, frameTop);
|
|
161
|
+
const cutRight = Math.min(newWidth, frameLeft + frame.width), cutBottom = Math.min(newHeight, frameTop + frame.height);
|
|
162
|
+
if (cutRight <= cutLeft || cutBottom <= cutTop) {
|
|
163
|
+
frame.image = new Image(1, 1);
|
|
164
|
+
frame.xOffset = frame.yOffset = 0;
|
|
165
|
+
frame.disposalMode = 'keep';
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
if (cutLeft !== frameLeft || cutTop !== frameTop || cutRight - cutLeft !== frame.width || cutBottom - cutTop !== frame.height)
|
|
169
|
+
frame.image = frame.image.extract(cutLeft - frameLeft, cutTop - frameTop, cutRight - cutLeft, cutBottom - cutTop);
|
|
170
|
+
frame.xOffset = cutLeft;
|
|
171
|
+
frame.yOffset = cutTop;
|
|
172
|
+
}
|
|
162
173
|
}
|
|
163
|
-
this.__canvas__ = [
|
|
164
|
-
this.frames = this.__clipped_frames__();
|
|
174
|
+
this.__canvas__ = [newWidth, newHeight];
|
|
165
175
|
return this;
|
|
166
176
|
}
|
|
167
177
|
__contain__(width, height, options) {
|
|
168
178
|
checkOptions(options, 'resize({ width, height, fit: \'contain\', background: 0x000000ff })');
|
|
169
179
|
const { background = 0x00000000, ...resizeOpts } = options ?? {};
|
|
170
180
|
const backgroundColor = checkColor(background, 'background');
|
|
171
|
-
const [boxWidth, boxHeight] = canvasSize(
|
|
181
|
+
const [boxWidth, boxHeight] = canvasSize(width, height);
|
|
172
182
|
this.resize({ width: boxWidth, height: boxHeight, fit: 'inside', ...resizeOpts });
|
|
173
183
|
const x = (boxWidth - this.width) / 2 | 0, y = (boxHeight - this.height) / 2 | 0;
|
|
174
184
|
for (const frame of this.__distinct__()) {
|
|
@@ -186,7 +196,7 @@ export class Animation {
|
|
|
186
196
|
}
|
|
187
197
|
__cover__(width, height, options) {
|
|
188
198
|
checkOptions(options, 'resize({ width, height, fit: \'cover\' })');
|
|
189
|
-
const [boxWidth, boxHeight] = canvasSize(
|
|
199
|
+
const [boxWidth, boxHeight] = canvasSize(width, height);
|
|
190
200
|
const scale = Math.max(boxWidth / this.width, boxHeight / this.height);
|
|
191
201
|
this.resize(Math.max(boxWidth, Math.round(this.width * scale)), Math.max(boxHeight, Math.round(this.height * scale)), options);
|
|
192
202
|
return this.crop((this.width - boxWidth) / 2, (this.height - boxHeight) / 2, boxWidth, boxHeight);
|
|
@@ -209,8 +219,7 @@ export class Animation {
|
|
|
209
219
|
return this;
|
|
210
220
|
}
|
|
211
221
|
scale(factor, options) {
|
|
212
|
-
|
|
213
|
-
throw new RangeError(`Invalid scale factor: ${factor}`);
|
|
222
|
+
scaleFactor(factor, this.width, this.height);
|
|
214
223
|
return this.resize(Math.max(1, this.width * factor), Math.max(1, this.height * factor), options);
|
|
215
224
|
}
|
|
216
225
|
trim(options = {}) {
|
|
@@ -288,7 +297,7 @@ export class Animation {
|
|
|
288
297
|
}
|
|
289
298
|
__validate__(format) {
|
|
290
299
|
if (!this.length)
|
|
291
|
-
throw new
|
|
300
|
+
throw new RangeError('An animation needs at least one frame, not 0');
|
|
292
301
|
for (const frame of this.frames) {
|
|
293
302
|
if (!(frame instanceof Frame))
|
|
294
303
|
throw new Error('Animation contains invalid frames');
|
|
@@ -297,14 +306,15 @@ export class Animation {
|
|
|
297
306
|
const { width, height } = this;
|
|
298
307
|
if (width < 1 || height < 1)
|
|
299
308
|
throw new RangeError('The animation has no canvas: every frame lies outside of it');
|
|
300
|
-
if (format === 'GIF'
|
|
301
|
-
|
|
302
|
-
if (format === 'WebP'
|
|
303
|
-
|
|
309
|
+
if (format === 'GIF')
|
|
310
|
+
checkFormatSize('GIF', width, height, 0xffff);
|
|
311
|
+
if (format === 'WebP')
|
|
312
|
+
checkFormatSize('WebP', width, height, 1 << 24);
|
|
304
313
|
}
|
|
305
314
|
async encodeGIF(options = {}) {
|
|
306
315
|
checkOptions(options, 'encodeGIF({ colors: 64 })');
|
|
307
316
|
const { colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {}, optimize = true } = options;
|
|
317
|
+
boolean(optimize, 'optimize');
|
|
308
318
|
const palette = paletteOptions(colors, dither, ditherStrength);
|
|
309
319
|
const loops = fitLoops(this.loopCount, 'GIF');
|
|
310
320
|
this.__validate__('GIF');
|
|
@@ -325,6 +335,7 @@ export class Animation {
|
|
|
325
335
|
async encodeAPNG(options = {}) {
|
|
326
336
|
checkOptions(options, 'encodeAPNG({ compression: 9 })');
|
|
327
337
|
const { compression = 4, metadata = {}, optimize = true } = options;
|
|
338
|
+
boolean(optimize, 'optimize');
|
|
328
339
|
const loops = fitLoops(this.loopCount, 'APNG');
|
|
329
340
|
this.__validate__('APNG');
|
|
330
341
|
const frames = optimize
|
|
@@ -335,6 +346,7 @@ export class Animation {
|
|
|
335
346
|
async encodeWebP(options = {}) {
|
|
336
347
|
checkOptions(options, 'animation.encodeWebP({ quality: 80 })');
|
|
337
348
|
const { metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 } = options;
|
|
349
|
+
boolean(optimize, 'optimize');
|
|
338
350
|
const loops = fitLoops(this.loopCount, 'WebP');
|
|
339
351
|
this.__validate__('WebP');
|
|
340
352
|
const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
|
|
@@ -344,26 +356,12 @@ export class Animation {
|
|
|
344
356
|
}
|
|
345
357
|
__webpFrames__() {
|
|
346
358
|
const width = this.width, height = this.height;
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
let { xOffset: x, yOffset: y, width: w, height: h } = frame;
|
|
354
|
-
let pixels = new Uint8Array(frame.image.bitmap.buffer, frame.image.bitmap.byteOffset, frame.image.bitmap.byteLength);
|
|
355
|
-
if (x & 1 || y & 1) {
|
|
356
|
-
const dx = x & 1, dy = y & 1;
|
|
357
|
-
const padded = new Uint8Array((w + dx) * (h + dy) * 4);
|
|
358
|
-
for (let row = 0; row < h; row++)
|
|
359
|
-
padded.set(pixels.subarray(row * w * 4, (row + 1) * w * 4), ((row + dy) * (w + dx) + dx) * 4);
|
|
360
|
-
pixels = padded;
|
|
361
|
-
x -= dx;
|
|
362
|
-
y -= dy;
|
|
363
|
-
w += dx;
|
|
364
|
-
h += dy;
|
|
365
|
-
}
|
|
366
|
-
return { x, y, width: w, height: h, duration: frame.duration, dispose: frame.disposalMode === 'background', pixels };
|
|
359
|
+
const compositor = new Compositor(width, height);
|
|
360
|
+
let full = false;
|
|
361
|
+
return this.__apngFrames__().map(f => {
|
|
362
|
+
const shown = compositor.push(f);
|
|
363
|
+
full ||= f.dispose === 2 || (f.dispose === 1 && !!(f.x & 1 || f.y & 1));
|
|
364
|
+
return full ? { x: 0, y: 0, width, height, duration: f.duration, dispose: true, blend: false, pixels: shown } : webpFrame(f);
|
|
367
365
|
});
|
|
368
366
|
}
|
|
369
367
|
__optimized__(options) {
|
|
@@ -408,6 +406,9 @@ export class Animation {
|
|
|
408
406
|
}
|
|
409
407
|
static async __decode__(input, options) {
|
|
410
408
|
const { maxPixels = MAX_PIXELS, applyColorProfile = true, threads = Math.max(1, Math.min(availableThreads(), 8)), applyOrientation = true, toneMapping = 'reinhard', gainMap = true } = options;
|
|
409
|
+
boolean(applyOrientation, 'applyOrientation');
|
|
410
|
+
boolean(applyColorProfile, 'applyColorProfile');
|
|
411
|
+
boolean(gainMap, 'gainMap');
|
|
411
412
|
const orient = (frames, orientation) => {
|
|
412
413
|
if (applyOrientation && orientation > 1)
|
|
413
414
|
for (const frame of frames)
|
|
@@ -431,11 +432,14 @@ export class Animation {
|
|
|
431
432
|
const frames = orient(profile(canvasFrames(decoded.width, decoded.height, webp.composite(decoded)), decoded.icc), decoded.orientation);
|
|
432
433
|
const animation = new Animation(frames, { loopCount: fromPlays(decoded.loopCount), width: frames[0]?.width ?? decoded.width, height: frames[0]?.height ?? decoded.height });
|
|
433
434
|
animation.__animationSignal__ = animated;
|
|
435
|
+
if (!animated)
|
|
436
|
+
for (const frame of frames)
|
|
437
|
+
frame.duration = 100;
|
|
434
438
|
return animation;
|
|
435
439
|
}
|
|
436
440
|
if (type === 'png' && !png.isAnimated(data)) {
|
|
437
441
|
const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile });
|
|
438
|
-
return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration:
|
|
442
|
+
return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 100 }]), { loopCount: Infinity, width: image.width, height: image.height });
|
|
439
443
|
}
|
|
440
444
|
if (type === 'png') {
|
|
441
445
|
const decoded = await png.decodeAnimation(data, false, maxPixels);
|
|
@@ -482,11 +486,14 @@ export class Animation {
|
|
|
482
486
|
}
|
|
483
487
|
const animation = new Animation(frames, { loopCount: animated ? loops : Infinity, ...(frames.length ? { width: frames[0].width, height: frames[0].height } : {}) });
|
|
484
488
|
animation.__animationSignal__ = animated;
|
|
489
|
+
if (!animated)
|
|
490
|
+
for (const frame of frames)
|
|
491
|
+
frame.duration = 100;
|
|
485
492
|
return animation;
|
|
486
493
|
}
|
|
487
494
|
if (type) {
|
|
488
495
|
const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile, toneMapping, gainMap, threads });
|
|
489
|
-
return new Animation([new Frame(image
|
|
496
|
+
return new Animation([new Frame(image)], { width: image.width, height: image.height });
|
|
490
497
|
}
|
|
491
498
|
throw new Error('Unsupported image type');
|
|
492
499
|
}
|
|
@@ -498,8 +505,4 @@ export class Animation {
|
|
|
498
505
|
return animation;
|
|
499
506
|
}
|
|
500
507
|
}
|
|
501
|
-
|
|
502
|
-
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
|
|
503
|
-
throw new RangeError(`Invalid canvas size: ${width}x${height}`);
|
|
504
|
-
return [width, height];
|
|
505
|
-
}
|
|
508
|
+
describe(Animation, animation => ({ width: animation.width, height: animation.height, duration: animation.duration, frames: animation.frames.length }));
|
package/dist/codecs/avif-enc.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { encodeAV1, encodeAV1Threaded } from "./av1/encode.js";
|
|
2
2
|
import { startThreads } from "../util/threads.js";
|
|
3
|
+
import { checkFormatSize } from "../util/limits.js";
|
|
3
4
|
import { writeISO } from "./gainmap.js";
|
|
4
5
|
const MIN_THREADED_PIXELS = [640 * 640, 448 * 448, 320 * 320], PIXELS_PER_THREAD = [512 << 10, 256 << 10, 256 << 10];
|
|
5
6
|
const QINDEX = [
|
|
@@ -156,8 +157,7 @@ function seqMonochrome(d, o) {
|
|
|
156
157
|
export async function encode(rgba, width, height, { quality, alphaQuality, subsampling, effort, exif, threads: maxThreads, gainMap }) {
|
|
157
158
|
if (width < 1 || height < 1)
|
|
158
159
|
throw new RangeError('AVIF: dimensions must be at least 1');
|
|
159
|
-
|
|
160
|
-
throw new RangeError('AVIF: dimensions must be at most 65536');
|
|
160
|
+
checkFormatSize('AVIF', width, height, 65536);
|
|
161
161
|
let opaque = true;
|
|
162
162
|
for (let i = 3; i < rgba.length; i += 4)
|
|
163
163
|
if (rgba[i] !== 255) {
|
|
@@ -243,7 +243,7 @@ export async function encode(rgba, width, height, { quality, alphaQuality, subsa
|
|
|
243
243
|
type: 'av01', name: 'GMap', hidden: true, data: [map],
|
|
244
244
|
props: [property(fullBox('ispe', 0, 0, u32(gainMap.width), u32(gainMap.height))), property(av1C(map)) | 0x80, property(nclx(MAP_CICP)), property(pixi(mapGray ? 1 : 3))]
|
|
245
245
|
});
|
|
246
|
-
tmapId = items.push({ type: 'tmap', name: 'TMap', data: [[0], writeISO(gainMap.params)], props: [ispe, property(nclx([cicp[0], 16, cicp[2]]))] });
|
|
246
|
+
tmapId = items.push({ type: 'tmap', name: 'TMap', data: [[0], writeISO(gainMap.params)], props: [ispe, property(nclx(gainMap.params.alternate ?? [cicp[0], 16, cicp[2]]))] });
|
|
247
247
|
}
|
|
248
248
|
const exifId = exif?.length ? items.push({ type: 'Exif', name: 'Exif', data: [u32(0), exif], props: [] }) : 0;
|
|
249
249
|
const sizes = items.map(item => item.data.reduce((n, d) => n + d.length, 0));
|
package/dist/codecs/avif.js
CHANGED
|
@@ -313,7 +313,7 @@ function convertRowSubsampled(c, j) {
|
|
|
313
313
|
const adjRow = layout === 1 && !(j === 0 || j === height - 1 && j % 2) ? j % 2 ? cs : -cs : 0;
|
|
314
314
|
for (let i = 0, p = j * width * 4; i < width; i++, p += 4) {
|
|
315
315
|
const lum = tableY[Y[yRow + i]];
|
|
316
|
-
const o = uvRow + (i >> 1), adjCol = i === 0 || i === width - 1
|
|
316
|
+
const o = uvRow + (i >> 1), adjCol = i === 0 || i === width - 1 ? 0 : i % 2 ? 1 : -1;
|
|
317
317
|
const cb = f32(f32(f32(w9[U[o]] + w3[U[o + adjCol]]) + w3[U[o + adjRow]]) + w1[U[o + adjCol + adjRow]]);
|
|
318
318
|
const cr = f32(f32(f32(w9[V[o]] + w3[V[o + adjCol]]) + w3[V[o + adjRow]]) + w1[V[o + adjCol + adjRow]]);
|
|
319
319
|
out[p] = toByte(f32(lum + f32(cr2 * cr)));
|
|
@@ -345,7 +345,7 @@ function convertRow(c, j) {
|
|
|
345
345
|
cr = tableUV[V[o]];
|
|
346
346
|
}
|
|
347
347
|
else {
|
|
348
|
-
const adjCol = i === 0 || i === width - 1
|
|
348
|
+
const adjCol = i === 0 || i === width - 1 ? 0 : i % 2 ? 1 : -1;
|
|
349
349
|
cb = f32(f32(f32(f32(tableUV[U[o]] * 0.5625) + f32(tableUV[U[o + adjCol]] * 0.1875)) +
|
|
350
350
|
f32(tableUV[U[o + adjRow]] * 0.1875)) + f32(tableUV[U[o + adjCol + adjRow]] * 0.0625));
|
|
351
351
|
cr = f32(f32(f32(f32(tableUV[V[o]] * 0.5625) + f32(tableUV[V[o + adjCol]] * 0.1875)) +
|
|
@@ -563,6 +563,11 @@ async function decodeGainMap(d, primary, items, idat, maxPixels) {
|
|
|
563
563
|
const mapItem = items.get(inputs[1]);
|
|
564
564
|
if (!params || !mapItem)
|
|
565
565
|
return undefined;
|
|
566
|
+
const colors = { primaries: 0, transfer: 0, matrix: 0 };
|
|
567
|
+
if (tmap.props.some(({ box }) => box.type === 'colr' && box.end - box.start >= 11 && fourcc(d, box.start) === 'nclx')) {
|
|
568
|
+
applyColr(d, tmap, colors);
|
|
569
|
+
params.alternate = [colors.primaries, colors.transfer, colors.matrix];
|
|
570
|
+
}
|
|
566
571
|
const yuv = await decodeItem(d, mapItem, items, idat, maxPixels, null);
|
|
567
572
|
applyColr(d, mapItem, yuv);
|
|
568
573
|
yuv.transfer = 13;
|
package/dist/codecs/bmp.js
CHANGED
|
@@ -161,7 +161,7 @@ export function decodeDIB(d, o, pixelOffset, maxPixels, ico = false) {
|
|
|
161
161
|
: (a << 24 | sample(cb, v) << 16 | sample(cg, v) << 8 | sample(cr, v)) >>> 0;
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
|
-
if (ca.max && !alphaSeen)
|
|
164
|
+
if (ca.max && !alphaSeen && !info.masks)
|
|
165
165
|
for (let i = 0; i < out.length; i++)
|
|
166
166
|
out[i] |= 0xff000000;
|
|
167
167
|
if (ico && bits === 32 && alphaSeen)
|
package/dist/codecs/gif.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ByteWriter } from "../util/bytes.js";
|
|
2
2
|
import { quantize } from "./quantize.js";
|
|
3
|
-
import { MAX_PIXELS, PixelBudget, checkPixels } from "../util/limits.js";
|
|
3
|
+
import { MAX_PIXELS, FRAME_PIXELS, PixelBudget, checkPixels } from "../util/limits.js";
|
|
4
4
|
const DISPOSAL_TO_GIF = [0, 1, 3, 2];
|
|
5
5
|
const DISPOSAL_FROM_GIF = [0, 1, 3, 2, 0, 0, 0, 0];
|
|
6
6
|
const MAX_CODE = 4095;
|
|
@@ -140,7 +140,7 @@ export function decode(data, firstFrameOnly = false, maxPixels = MAX_PIXELS) {
|
|
|
140
140
|
let loopCount = 0;
|
|
141
141
|
let hasLoopExtension = false;
|
|
142
142
|
let control = null;
|
|
143
|
-
const budget = new PixelBudget(maxPixels);
|
|
143
|
+
const budget = new PixelBudget(maxPixels, firstFrameOnly ? 0 : FRAME_PIXELS);
|
|
144
144
|
try {
|
|
145
145
|
parse();
|
|
146
146
|
}
|