imagescript 4.0.0-rc.5 → 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 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; CommonJS projects with `module: nodenext` need 5.8 or newer to `import` it. 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
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/v4/guides/Migrating%20to%204.0.md) first.
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, webpack, `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. Vite and Rollup emit it.
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,8 @@ 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.
92
93
 
93
94
  Not supported (decoding them throws an error): CCITT-compressed TIFF and arithmetic-coded JPEG. Lossless JPEG XL is
94
95
  fast but not small: for small lossless files, PNG or WebP are the better choice.
@@ -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 `Error` if no frame was added, or the encoder is finished already
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, boolean } 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)
@@ -43,13 +44,10 @@ export class AnimationEncoder {
43
44
  checkOptions(options, 'encoder.add(frame, { duration: 40 })');
44
45
  if (this.finished)
45
46
  throw new Error('The animation encoder is finished');
47
+ instance(frame, [Frame, Image], 'the frame of encoder.add()');
46
48
  const own = frame instanceof Frame ? frame : null;
47
49
  const image = own ? own.image : frame;
48
- if (!(image instanceof Image))
49
- throw new TypeError('encoder.add() takes a Frame or an Image');
50
- const duration = finite(options.duration === undefined ? own?.duration ?? 100 : options.duration, 'frame duration');
51
- if (duration < 0)
52
- throw new RangeError('Invalid frame duration');
50
+ const duration = nonNegative(options.duration === undefined ? own?.duration ?? 100 : options.duration, 'frame duration');
53
51
  fitDuration(duration, this.format.name);
54
52
  const x = Math.trunc(finite(options.xOffset === undefined ? own?.xOffset ?? 0 : options.xOffset, 'x offset')) || 0;
55
53
  const y = Math.trunc(finite(options.yOffset === undefined ? own?.yOffset ?? 0 : options.yOffset, 'y offset')) || 0;
@@ -74,8 +72,10 @@ export class AnimationEncoder {
74
72
  throw new Error('The animation encoder is finished');
75
73
  this.finished = true;
76
74
  await this.queue;
77
- if (!this.count)
78
- throw new Error('An animation needs at least one frame');
75
+ if (!this.count) {
76
+ this.finished = false;
77
+ throw new RangeError('An animation needs at least one frame, not 0');
78
+ }
79
79
  if (this.optimizer)
80
80
  for (const f of this.optimizer.end())
81
81
  await this.format.frame(f, true);
@@ -86,9 +86,8 @@ export class AnimationEncoder {
86
86
  static __webp__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }) {
87
87
  boolean(optimize, 'optimize');
88
88
  const loops = fitLoops(loopCount(count), 'WebP');
89
- canvas(width, height, 'WebP');
90
- if (width > 1 << 24 || height > 1 << 24)
91
- throw new RangeError('WebP: canvas too large');
89
+ [width, height] = canvas(width, height, 'WebP');
90
+ checkFormatSize('WebP', width, height, 1 << 24);
92
91
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
93
92
  const resolved = resolveMetadata(metadata), chunks = [];
94
93
  let alpha = false;
@@ -119,7 +118,7 @@ export class AnimationEncoder {
119
118
  const palette = { colors: checked.colors, dither: checked.dither, strength: checked.strength };
120
119
  boolean(optimize, 'optimize');
121
120
  const loops = fitLoops(loopCount(count), 'GIF');
122
- canvas(width, height, 'GIF');
121
+ [width, height] = canvas(width, height, 'GIF');
123
122
  const comments = gifComments(resolveMetadata(metadata));
124
123
  let first = null, restores = false;
125
124
  const rest = [];
@@ -148,7 +147,7 @@ export class AnimationEncoder {
148
147
  const compression = compressionLevel(compressionOption);
149
148
  boolean(optimize, 'optimize');
150
149
  const loops = fitLoops(loopCount(count), 'APNG');
151
- canvas(width, height, 'APNG');
150
+ [width, height] = canvas(width, height, 'APNG');
152
151
  const text = pngText(resolveMetadata(metadata));
153
152
  const stored = [];
154
153
  const cost = new png.AlphaCost();
@@ -195,15 +194,13 @@ export class AnimationEncoder {
195
194
  }, optimize);
196
195
  }
197
196
  }
198
- function canvas(width, height, format) {
199
- finite(width, 'width');
200
- finite(height, 'height');
201
- if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
202
- throw new RangeError(`Invalid canvas size: ${width}x${height}`);
203
- if (format === 'GIF' && (width > 0xffff || height > 0xffff))
204
- throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${width}x${height}`);
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];
205
202
  }
206
- function webpFrame(f) {
203
+ export function webpFrame(f) {
207
204
  let { x, y, width: w, height: h, pixels } = f;
208
205
  if (x & 1 || y & 1) {
209
206
  const dx = x & 1, dy = y & 1;
@@ -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) outside the canvas aren't encoded
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. The region is
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 tolerance, see
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;
@@ -194,8 +197,7 @@ export declare class Animation {
194
197
  * after the frames are composited
195
198
  * @param options See {@link GIFAnimationEncodeOptions}; the loop count is the animation's {@link loopCount} (the
196
199
  * streaming {@link gifEncoder} takes it as an option)
197
- * @throws `Error` if the animation has no frames
198
- * @throws `RangeError` if the loop count or a frame's duration is more than GIF stores, or the canvas is wider or
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
199
201
  * higher than 65535 pixels
200
202
  */
201
203
  encodeGIF(options?: GIFAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
@@ -206,18 +208,16 @@ export declare class Animation {
206
208
  * necessarily decode to the same frames
207
209
  * @param options See {@link APNGEncodeOptions}; the loop count is the animation's {@link loopCount} (the streaming
208
210
  * {@link apngEncoder} takes it as an option)
209
- * @throws `Error` if the animation has no frames
210
- * @throws `RangeError` if the loop count or a frame's duration is more than APNG stores
211
+ * @throws `RangeError` if the animation has no frames, the loop count or a frame's duration is more than APNG stores
211
212
  */
212
213
  encodeAPNG(options?: APNGEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
213
214
  /**
214
- * 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
215
216
  * changed since the frame before, identical frames are merged (unless the `optimize` option is false): the file
216
217
  * shows the same animation, but doesn't necessarily decode to the same frames
217
218
  * @param options See {@link WebPAnimationEncodeOptions}; the loop count is the animation's {@link loopCount} (the
218
219
  * streaming {@link webpEncoder} takes it as an option)
219
- * @throws `Error` if the animation has no frames
220
- * @throws `RangeError` if the loop count or a frame's duration is more than WebP stores
220
+ * @throws `RangeError` if the animation has no frames, the loop count or a frame's duration is more than WebP stores
221
221
  */
222
222
  encodeWebP(options?: WebPAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
223
223
  /**
@@ -231,16 +231,16 @@ export declare class Animation {
231
231
  * await encoder.add(new Image(64, 64).fill(color), { duration: 200 });
232
232
  * const webp = await encoder.finish();
233
233
  * ```
234
- * @param width The canvas width
235
- * @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)
236
236
  * @param options See {@link WebPAnimationEncodeOptions}, and {@link AnimationOptions.loopCount}
237
237
  */
238
238
  static webpEncoder(width: number, height: number, options?: WebPAnimationEncodeOptions & AnimationOptions): AnimationEncoder;
239
239
  /**
240
240
  * An encoder that makes an animated GIF a frame at a time, like {@link Animation.encodeGIF} (the same file),
241
241
  * without keeping the frames in memory: `await encoder.add(frame)` for each frame, then `await encoder.finish()`
242
- * @param width The canvas width
243
- * @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)
244
244
  * @param options See {@link GIFAnimationEncodeOptions}, and {@link AnimationOptions.loopCount}
245
245
  */
246
246
  static gifEncoder(width: number, height: number, options?: GIFAnimationEncodeOptions & AnimationOptions): AnimationEncoder;
@@ -248,8 +248,8 @@ export declare class Animation {
248
248
  * An encoder that makes an APNG a frame at a time, like {@link Animation.encodeAPNG} (the same file), keeping the
249
249
  * frames only compressed (the pixel format depends on all of them): `await encoder.add(frame)` for each frame,
250
250
  * then `await encoder.finish()`
251
- * @param width The canvas width
252
- * @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)
253
253
  * @param options See {@link APNGEncodeOptions}, and {@link AnimationOptions.loopCount}
254
254
  */
255
255
  static apngEncoder(width: number, height: number, options?: APNGEncodeOptions & AnimationOptions): AnimationEncoder;
package/dist/animation.js CHANGED
@@ -9,12 +9,12 @@ 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, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, boolean, color as checkColor } from "./util/options.js";
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
18
  import { describe } from "./util/inspect.js";
19
19
  function canvasFrames(width, height, frames) {
20
20
  return frames.map(({ pixels, duration }) => {
@@ -30,7 +30,7 @@ export class Animation {
30
30
  __framesView__ = null;
31
31
  __canvas__ = null;
32
32
  constructor(frames, options = {}) {
33
- checkOptions(options, 'Animation(frames, { loopCount: 2 })');
33
+ checkOptions(options, 'new Animation(frames, { loopCount: 2 })');
34
34
  const { loopCount: count = Infinity, width, height } = options;
35
35
  const loops = loopCount(count);
36
36
  if ((width === undefined) !== (height === undefined))
@@ -51,11 +51,11 @@ export class Animation {
51
51
  }
52
52
  set frames(frames) {
53
53
  if (frames === null || typeof frames !== 'object' || typeof frames[Symbol.iterator] !== 'function')
54
- throw new TypeError(`Animation() takes an array of Frame objects, not ${frames === null ? 'null' : typeof frames}`);
54
+ throw new TypeError(`Animation() takes an array of Frame objects, not ${shown(frames)}`);
55
55
  const copy = [];
56
56
  for (const frame of frames) {
57
57
  if (!(frame instanceof Frame))
58
- throw new TypeError(`Frame ${copy.length} is not an instance of Frame`);
58
+ throw new TypeError(`frames[${copy.length}] must be a Frame, not ${shown(frame)}`);
59
59
  copy.push(frame);
60
60
  }
61
61
  this.__frames__ = copy;
@@ -109,10 +109,10 @@ export class Animation {
109
109
  const originalWidth = this.width, originalHeight = this.height;
110
110
  if (!originalWidth || !originalHeight)
111
111
  throw new RangeError('An animation without frames or canvas can\'t be resized');
112
- if (givenWidth !== undefined && Math.floor(givenWidth) < 1)
113
- throw new RangeError('The animation has to be at least 1 pixel wide');
114
- if (givenHeight !== undefined && Math.floor(givenHeight) < 1)
115
- throw new RangeError('The animation has to be at least 1 pixel high');
112
+ if (givenWidth !== undefined)
113
+ pixels(givenWidth, 'width');
114
+ if (givenHeight !== undefined)
115
+ pixels(givenHeight, 'height');
116
116
  let width, height;
117
117
  if (fit === 'inside' && givenWidth !== undefined && givenHeight !== undefined)
118
118
  [width, height] = insideSize(originalWidth, originalHeight, givenWidth, givenHeight).map(Math.floor);
@@ -154,24 +154,31 @@ export class Animation {
154
154
  return this;
155
155
  }
156
156
  crop(x, y, width, height) {
157
- const left = Math.max(0, Math.floor(finite(x, 'x'))), top = Math.max(0, Math.floor(finite(y, 'y')));
158
- const right = Math.min(this.width, Math.floor(finite(x, 'x')) + Math.floor(finite(width, 'width')));
159
- const bottom = Math.min(this.height, Math.floor(finite(y, 'y')) + Math.floor(finite(height, 'height')));
160
- if (!(right - left >= 1 && bottom - top >= 1))
161
- 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');
162
158
  for (const frame of this.__distinct__()) {
163
- frame.xOffset -= left;
164
- frame.yOffset -= top;
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
+ }
165
173
  }
166
- this.__canvas__ = [right - left, bottom - top];
167
- this.frames = this.__clipped_frames__();
174
+ this.__canvas__ = [newWidth, newHeight];
168
175
  return this;
169
176
  }
170
177
  __contain__(width, height, options) {
171
178
  checkOptions(options, 'resize({ width, height, fit: \'contain\', background: 0x000000ff })');
172
179
  const { background = 0x00000000, ...resizeOpts } = options ?? {};
173
180
  const backgroundColor = checkColor(background, 'background');
174
- const [boxWidth, boxHeight] = canvasSize(Math.floor(finite(width, 'width')), Math.floor(finite(height, 'height')));
181
+ const [boxWidth, boxHeight] = canvasSize(width, height);
175
182
  this.resize({ width: boxWidth, height: boxHeight, fit: 'inside', ...resizeOpts });
176
183
  const x = (boxWidth - this.width) / 2 | 0, y = (boxHeight - this.height) / 2 | 0;
177
184
  for (const frame of this.__distinct__()) {
@@ -189,7 +196,7 @@ export class Animation {
189
196
  }
190
197
  __cover__(width, height, options) {
191
198
  checkOptions(options, 'resize({ width, height, fit: \'cover\' })');
192
- const [boxWidth, boxHeight] = canvasSize(Math.floor(finite(width, 'width')), Math.floor(finite(height, 'height')));
199
+ const [boxWidth, boxHeight] = canvasSize(width, height);
193
200
  const scale = Math.max(boxWidth / this.width, boxHeight / this.height);
194
201
  this.resize(Math.max(boxWidth, Math.round(this.width * scale)), Math.max(boxHeight, Math.round(this.height * scale)), options);
195
202
  return this.crop((this.width - boxWidth) / 2, (this.height - boxHeight) / 2, boxWidth, boxHeight);
@@ -212,8 +219,7 @@ export class Animation {
212
219
  return this;
213
220
  }
214
221
  scale(factor, options) {
215
- if (!(finite(factor, 'factor') > 0))
216
- throw new RangeError(`Invalid scale factor: ${factor}`);
222
+ scaleFactor(factor, this.width, this.height);
217
223
  return this.resize(Math.max(1, this.width * factor), Math.max(1, this.height * factor), options);
218
224
  }
219
225
  trim(options = {}) {
@@ -291,7 +297,7 @@ export class Animation {
291
297
  }
292
298
  __validate__(format) {
293
299
  if (!this.length)
294
- throw new Error('An animation needs at least one frame');
300
+ throw new RangeError('An animation needs at least one frame, not 0');
295
301
  for (const frame of this.frames) {
296
302
  if (!(frame instanceof Frame))
297
303
  throw new Error('Animation contains invalid frames');
@@ -300,10 +306,10 @@ export class Animation {
300
306
  const { width, height } = this;
301
307
  if (width < 1 || height < 1)
302
308
  throw new RangeError('The animation has no canvas: every frame lies outside of it');
303
- if (format === 'GIF' && (width > 0xffff || height > 0xffff))
304
- throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${width}x${height}`);
305
- if (format === 'WebP' && (width > 1 << 24 || height > 1 << 24))
306
- throw new RangeError('WebP: canvas too large');
309
+ if (format === 'GIF')
310
+ checkFormatSize('GIF', width, height, 0xffff);
311
+ if (format === 'WebP')
312
+ checkFormatSize('WebP', width, height, 1 << 24);
307
313
  }
308
314
  async encodeGIF(options = {}) {
309
315
  checkOptions(options, 'encodeGIF({ colors: 64 })');
@@ -350,26 +356,12 @@ export class Animation {
350
356
  }
351
357
  __webpFrames__() {
352
358
  const width = this.width, height = this.height;
353
- const clipped = this.__clipped_frames__();
354
- const fullFrames = clipped.some(f => f.disposalMode === 'previous' || (f.disposalMode === 'background' && (f.xOffset & 1 || f.yOffset & 1)));
355
- if (fullFrames)
356
- return png.compositeAnimation({ width, height, frames: this.__apngFrames__() })
357
- .map(c => ({ x: 0, y: 0, width, height, duration: c.duration, dispose: true, pixels: c.pixels }));
358
- return Array.from(clipped, frame => {
359
- let { xOffset: x, yOffset: y, width: w, height: h } = frame;
360
- let pixels = new Uint8Array(frame.image.bitmap.buffer, frame.image.bitmap.byteOffset, frame.image.bitmap.byteLength);
361
- if (x & 1 || y & 1) {
362
- const dx = x & 1, dy = y & 1;
363
- const padded = new Uint8Array((w + dx) * (h + dy) * 4);
364
- for (let row = 0; row < h; row++)
365
- padded.set(pixels.subarray(row * w * 4, (row + 1) * w * 4), ((row + dy) * (w + dx) + dx) * 4);
366
- pixels = padded;
367
- x -= dx;
368
- y -= dy;
369
- w += dx;
370
- h += dy;
371
- }
372
- 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);
373
365
  });
374
366
  }
375
367
  __optimized__(options) {
@@ -513,11 +505,4 @@ export class Animation {
513
505
  return animation;
514
506
  }
515
507
  }
516
- function canvasSize(width, height) {
517
- finite(width, 'width');
518
- finite(height, 'height');
519
- if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
520
- throw new RangeError(`Invalid canvas size: ${width}x${height}`);
521
- return [width, height];
522
- }
523
508
  describe(Animation, animation => ({ width: animation.width, height: animation.height, duration: animation.duration, frames: animation.frames.length }));
@@ -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
- if (width > 65536 || height > 65536)
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));
@@ -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 && i % 2 ? 0 : i % 2 ? 1 : -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 && i % 2 ? 0 : i % 2 ? 1 : -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;
@@ -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
  }
@@ -5,7 +5,7 @@
5
5
  * (Copyright 2014 Mozilla Foundation, Apache License 2.0). See THIRD_PARTY_NOTICES.md
6
6
  */
7
7
  import { ByteWriter } from "../util/bytes.js";
8
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
8
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.js";
9
9
  import { orientation as exifOrientation } from "./exif.js";
10
10
  import { concat } from "../util/mem.js";
11
11
  import { littleEndian } from "../util/alpha.js";
@@ -92,7 +92,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
92
92
  if (data[start] !== 8)
93
93
  throw new Error(`JPEG: ${data[start]}-bit precision is not supported`);
94
94
  checkPixels(u16(start + 3), u16(start + 1), maxPixels);
95
- frame = createFrame(marker === 0xc2, u16(start + 1), u16(start + 3), data.subarray(start + 5, end));
95
+ frame = createFrame(marker === 0xc2, u16(start + 1), u16(start + 3), data.subarray(start + 5, end), data.length - end);
96
96
  break;
97
97
  }
98
98
  case 0xc3:
@@ -165,7 +165,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
165
165
  const icc = profile.length && Array.from(profile).every(Boolean) ? concat(profile) : undefined;
166
166
  return { width: frame.width, height: frame.height, pixels: output(frame, adobe, jfif, transform), orientation, icc };
167
167
  }
168
- function createFrame(progressive, height, width, componentData) {
168
+ function createFrame(progressive, height, width, componentData, available) {
169
169
  const count = componentData[0];
170
170
  const sampling = [];
171
171
  for (let i = 0; i < count; i++) {
@@ -180,6 +180,13 @@ function createFrame(progressive, height, width, componentData) {
180
180
  const vmax = Math.max(...sampling.map(c => c.v));
181
181
  const mcusPerLine = Math.ceil(width / (8 * hmax));
182
182
  const mcusPerColumn = Math.ceil(height / (8 * vmax));
183
+ if (!progressive) {
184
+ let blocks = 0;
185
+ for (const c of sampling)
186
+ blocks += Math.ceil(Math.ceil(width * c.h / hmax) / 8) * Math.ceil(Math.ceil(height * c.v / vmax) / 8);
187
+ if (blocks * 2 > available * 8)
188
+ throw new Error('JPEG: the scan data is truncated');
189
+ }
183
190
  const components = sampling.map((c) => {
184
191
  const componentWidth = Math.ceil(width * c.h / hmax);
185
192
  const componentHeight = Math.ceil(height * c.v / vmax);
@@ -840,9 +847,10 @@ function reciprocals(table) {
840
847
  }
841
848
  return r;
842
849
  }
843
- export function encode(pixels, width, height, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling } = {}) {
844
- if (!width || !height || width > 0xffff || height > 0xffff)
850
+ export function encode(pixels, width, height, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling, rows } = {}) {
851
+ if (!width || !height)
845
852
  throw new RangeError('JPEG: invalid dimensions');
853
+ checkFormatSize('JPEG', width, height, 0xffff);
846
854
  quality = Math.min(100, Math.max(1, Math.round(quality)));
847
855
  const scale = quality < 50 ? Math.floor(5000 / quality) : 200 - quality * 2;
848
856
  const scaleTable = (base) => base.map(v => Math.min(255, Math.max(1, Math.floor((v * scale + 50) / 100))));
@@ -860,10 +868,12 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
860
868
  const Y = new Uint8Array(W * lumaBlocksY * 8), Cb = new Uint8Array(CW * chromaBlocksY * 8), Cr = new Uint8Array(CW * chromaBlocksY * 8);
861
869
  const rowWidth = CW * hmax;
862
870
  const cbRows = subsample ? new Uint8Array(2 * rowWidth) : Cb, crRows = subsample ? new Uint8Array(2 * rowWidth) : Cr;
863
- const words = littleEndian && pixels.byteOffset % 4 === 0 ? new Uint32Array(pixels.buffer, pixels.byteOffset, width * height) : null;
871
+ const words = littleEndian && pixels.byteOffset % 4 === 0 ? new Uint32Array(pixels.buffer, pixels.byteOffset, (rows ? width : width * height)) : null;
864
872
  for (let y = 0; y < height; y++) {
873
+ if (rows)
874
+ rows(y);
865
875
  const row = subsample ? (y & 1) * rowWidth : y * CW;
866
- let i = y * width * 4, o = y * W, c = row;
876
+ let i = rows ? 0 : y * width * 4, o = y * W, c = row;
867
877
  if (words)
868
878
  for (let x = 0, w = i >> 2; x < width; x++, w++, o++, c++) {
869
879
  const p = words[w], r = p & 255, g = p >> 8 & 255, b = p >> 16 & 255;
@@ -258,7 +258,7 @@ export async function encodeRGBA(rgba, width, height, level, text) {
258
258
  }
259
259
  export async function encodeAnimation(frames, width, height, plays, level, text) {
260
260
  if (!frames.length)
261
- throw new Error('PNG: an animation needs at least one frame');
261
+ throw new RangeError('PNG: an animation needs at least one frame, not 0');
262
262
  frames = [coverCanvas(frames[0], width, height), ...frames.slice(1)];
263
263
  for (const f of frames)
264
264
  checkFrame(f, width, height);
@@ -1,5 +1,5 @@
1
1
  import { encode as utf8 } from "../util/utf8.js";
2
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
2
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.js";
3
3
  const SIGNATURE = 'TRUEVISION-XFILE.\0';
4
4
  function readHeader(d) {
5
5
  if (d.length < 18)
@@ -182,8 +182,9 @@ function extensionArea({ author, comment, time, software }, alpha) {
182
182
  return area;
183
183
  }
184
184
  export function encode(rgba, width, height, extension) {
185
- if (width < 1 || height < 1 || width > 65535 || height > 65535)
186
- throw new RangeError('TGA: dimensions must be 1-65535');
185
+ if (width < 1 || height < 1)
186
+ throw new RangeError('TGA: dimensions must be at least 1');
187
+ checkFormatSize('TGA', width, height, 65535);
187
188
  let opaque = true;
188
189
  for (let i = 3; i < rgba.length; i += 4)
189
190
  if (rgba[i] !== 255) {
@@ -6,7 +6,7 @@
6
6
  * Copyright (c) 2012 Google Inc., BSD-3-Clause License
7
7
  */
8
8
  import { ByteWriter } from "../util/bytes.js";
9
- import { MAX_PIXELS, checkPixels } from "../util/limits.js";
9
+ import { MAX_PIXELS, checkPixels, checkFormatSize } from "../util/limits.js";
10
10
  import { runChunks, shared } from "../util/threads.js";
11
11
  const SIGNATURE = 0x2f;
12
12
  const CODE_LENGTH_ORDER = [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
@@ -1462,8 +1462,9 @@ export function predictorChunks({ p, src, modes, width, height, bits, candidates
1462
1462
  };
1463
1463
  }
1464
1464
  export async function encode(argb, width, height, threads = null, effort = 2) {
1465
- if (width < 1 || height < 1 || width > 16384 || height > 16384)
1466
- throw new RangeError('VP8L: dimensions must be 1-16384');
1465
+ if (width < 1 || height < 1)
1466
+ throw new RangeError('WebP: dimensions must be at least 1');
1467
+ checkFormatSize('WebP', width, height, 16384);
1467
1468
  const tuning = TUNING[Math.min(2, effort)];
1468
1469
  const colors = new Map();
1469
1470
  for (let i = 0; i < argb.length && colors.size <= 256; i++)