imagescript 4.0.0-rc.3 → 4.0.0-rc.4

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
@@ -39,6 +39,15 @@ Without a bundler, import it from jsDelivr in the browser:
39
39
  </script>
40
40
  ```
41
41
 
42
+ The codecs that can use worker threads (large AVIF and JPEG XL images, lossless WebP; the `threads` option) do so in
43
+ Node.js, Deno and Bun, and in browsers on cross-origin isolated pages. Where workers can't start, the work runs on the
44
+ calling thread: the output is the same, only slower, and nothing warns about it. Browsers refuse workers from another
45
+ origin, so the jsDelivr example above runs single-threaded; serve the package from your own origin (on a cross-origin
46
+ isolated page) to get threads.
47
+
48
+ Bundlers that write one file (esbuild, webpack) 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.
50
+
42
51
  ---
43
52
 
44
53
  ### Example
@@ -2,11 +2,12 @@ import { Image } from './image.js';
2
2
  import { Frame, FrameOptions } from './frame.js';
3
3
  /**
4
4
  * Encodes an animation a frame at a time, without keeping all frames in memory: see {@link Animation.webpEncoder},
5
- * {@link Animation.gifEncoder} and {@link Animation.apngEncoder}. The file is the one an {@link Animation} of the
6
- * frames encodes to, but for unoptimized WebPs with frames WebP can't store as they are (disposed to the previous
7
- * frame, or disposed with odd offsets): from the first of them on, the frames are the canvas they show (the same
8
- * animation, blending rounds differently by 1 at most). APNGs keep their frames compressed until the end: their pixel
9
- * format depends on all of them
5
+ * {@link Animation.gifEncoder} and {@link Animation.apngEncoder}
6
+ * @remarks
7
+ * The file is the one an {@link Animation} of the frames encodes to, but for unoptimized WebPs with frames WebP can't
8
+ * store as they are (disposed to the previous frame, or disposed with odd offsets): from the first of them on, the
9
+ * frames are the canvas they show (the same animation, blending rounds differently by 1 at most). APNGs keep their
10
+ * frames compressed until the end: their pixel format depends on all of them
10
11
  */
11
12
  export declare class AnimationEncoder {
12
13
  private readonly format;
@@ -26,8 +27,14 @@ export declare class AnimationEncoder {
26
27
  * default). The options override the frame's. The pixels are copied right away, the image can change afterwards
27
28
  * @param frame The frame or image
28
29
  * @param options See {@link FrameOptions}
30
+ * @throws `TypeError` if the frame isn't a {@link Frame} or an {@link Image}
31
+ * @throws `RangeError` if the duration is negative or more than the format stores
32
+ * @throws `Error` if the encoder is finished
29
33
  */
30
34
  add(frame: Frame | Image, options?: FrameOptions): Promise<void>;
31
- /** Encodes the rest and returns the file. The encoder can't be used afterwards */
35
+ /**
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
38
+ */
32
39
  finish(): Promise<Uint8Array<ArrayBuffer>>;
33
40
  }
@@ -45,12 +45,12 @@ export class AnimationEncoder {
45
45
  const image = own ? own.image : frame;
46
46
  if (!(image instanceof Image))
47
47
  throw new TypeError('encoder.add() takes a Frame or an Image');
48
- const duration = finite(options.duration ?? own?.duration ?? 100, 'frame duration');
48
+ const duration = finite(options.duration === undefined ? own?.duration ?? 100 : options.duration, 'frame duration');
49
49
  if (duration < 0)
50
50
  throw new RangeError('Invalid frame duration');
51
51
  fitDuration(duration, this.format.name);
52
- const x = Math.trunc(finite(options.xOffset ?? own?.xOffset ?? 0, 'x offset')) || 0;
53
- const y = Math.trunc(finite(options.yOffset ?? own?.yOffset ?? 0, 'y offset')) || 0;
52
+ const x = Math.trunc(finite(options.xOffset === undefined ? own?.xOffset ?? 0 : options.xOffset, 'x offset')) || 0;
53
+ const y = Math.trunc(finite(options.yOffset === undefined ? own?.yOffset ?? 0 : options.yOffset, 'y offset')) || 0;
54
54
  const disposal = options.disposalMode !== undefined ? Frame.__convert_disposal_mode__(options.disposalMode) : own ? own.__disposal_id__ : 1;
55
55
  const input = {
56
56
  x, y, width: image.width, height: image.height, duration, disposal,
@@ -83,7 +83,7 @@ export class AnimationEncoder {
83
83
  }
84
84
  static __webp__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }) {
85
85
  const loops = fitLoops(loopCount(count), 'WebP');
86
- canvas(width, height);
86
+ canvas(width, height, 'WebP');
87
87
  if (width > 1 << 24 || height > 1 << 24)
88
88
  throw new RangeError('WebP: canvas too large');
89
89
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
@@ -115,7 +115,7 @@ export class AnimationEncoder {
115
115
  const checked = paletteOptions(colors, dither, ditherStrength);
116
116
  const palette = { colors: checked.colors, dither: checked.dither, strength: checked.strength };
117
117
  const loops = fitLoops(loopCount(count), 'GIF');
118
- canvas(width, height);
118
+ canvas(width, height, 'GIF');
119
119
  const comments = gifComments(resolveMetadata(metadata));
120
120
  let first = null, restores = false;
121
121
  const rest = [];
@@ -143,7 +143,7 @@ export class AnimationEncoder {
143
143
  static __apng__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, compression: compressionOption = 4 }) {
144
144
  const compression = compressionLevel(compressionOption);
145
145
  const loops = fitLoops(loopCount(count), 'APNG');
146
- canvas(width, height);
146
+ canvas(width, height, 'APNG');
147
147
  const text = pngText(resolveMetadata(metadata));
148
148
  const stored = [];
149
149
  const cost = new png.AlphaCost();
@@ -190,9 +190,11 @@ export class AnimationEncoder {
190
190
  }, optimize);
191
191
  }
192
192
  }
193
- function canvas(width, height) {
193
+ function canvas(width, height, format) {
194
194
  if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1)
195
195
  throw new RangeError(`Invalid canvas size: ${width}x${height}`);
196
+ if (format === 'GIF' && (width > 0xffff || height > 0xffff))
197
+ throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${width}x${height}`);
196
198
  }
197
199
  function webpFrame(f) {
198
200
  let { x, y, width: w, height: h, pixels } = f;
@@ -6,19 +6,23 @@ import { AnimationEncoder } from './animation-encoder.js';
6
6
  export interface AnimationOptions {
7
7
  /**
8
8
  * How many times to repeat the animation: `Infinity` loops forever, 0 plays once, 1 plays twice, ... Anything else
9
- * throws: a RangeError unless it is an integer from 0 or `Infinity`, a TypeError unless it is a number. Default:
10
- * `Infinity`
9
+ * throws: a RangeError unless it is an integer from 0 or `Infinity`, a TypeError unless it is a number
10
+ * @defaultValue `Infinity`
11
11
  */
12
12
  loopCount?: number;
13
13
  }
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. Default: the
18
- * frames' right edge (the largest `xOffset + width`), following the frames until a canvas size is set
17
+ * The canvas width in pixels: frames (or the parts of them) outside the canvas aren't encoded
18
+ * @defaultValue The frames' right edge (the largest `xOffset + width`), following the frames until a canvas size is
19
+ * set
19
20
  */
20
21
  width?: number;
21
- /** The canvas height in pixels, like `width`. Default: the frames' bottom edge (the largest `yOffset + height`) */
22
+ /**
23
+ * The canvas height in pixels, like `width`
24
+ * @defaultValue The frames' bottom edge (the largest `yOffset + height`)
25
+ */
22
26
  height?: number;
23
27
  }
24
28
  /** The options all animation encoders have */
@@ -26,7 +30,10 @@ export interface AnimationEncodeOptions extends EncodeOptions {
26
30
  /**
27
31
  * Whether to store each frame as the area that changed since the frame before and merge identical frames, which
28
32
  * usually makes files a lot smaller. The file shows the same animation either way, but only decodes to the same
29
- * frames without it, which also encodes faster when little changes. Default: `true`
33
+ * frames without it, which also encodes faster when little changes. The exception is GIF, which has no partial
34
+ * transparency: without `optimize`, a semi-transparent pixel becomes opaque or transparent in its own frame, with
35
+ * it the frames are composited first
36
+ * @defaultValue `true`
30
37
  */
31
38
  optimize?: boolean;
32
39
  }
@@ -56,6 +63,14 @@ export interface APNGEncodeOptions extends PNGEncodeOptions, AnimationEncodeOpti
56
63
  export declare class Animation {
57
64
  /**
58
65
  * Creates a new animation
66
+ * @example
67
+ * ```ts
68
+ * const animation = new Animation([
69
+ * new Frame(new Image(64, 64).fill(0xff0000ff), { duration: 200 }),
70
+ * new Frame(new Image(64, 64).fill(0x0000ffff), { duration: 200 })
71
+ * ], { loopCount: 2 });
72
+ * const gif = await animation.encodeGIF();
73
+ * ```
59
74
  * @param frames The frames to create the animation from
60
75
  * @param options The canvas size and the loop count, see {@link AnimationCanvasOptions}
61
76
  */
@@ -101,9 +116,13 @@ export declare class Animation {
101
116
  /**
102
117
  * Resizes the animation to the given dimensions, scaling every frame and its offsets proportionally.
103
118
  * Pass {@link ResizeToOptions} with only a width or a height to keep the aspect ratio.
119
+ * @remarks
120
+ * With `fit: 'contain'` and a `background` that isn't transparent, the frames are composited onto it, so the animation
121
+ * has whole frames afterwards (the file shows the same, but it can't keep the frames' parts apart anymore)
104
122
  * @param width The new width
105
123
  * @param height The new height
106
124
  * @param options See {@link ResizeOptions}
125
+ * @throws `RangeError` if the width or height is less than 1 pixel, or the animation has no canvas
107
126
  */
108
127
  resize(width: number, height: number, options?: ResizeOptions): this;
109
128
  /**
@@ -174,6 +193,9 @@ export declare class Animation {
174
193
  * animation shows, but not necessarily to the same frames. Semi-transparent pixels become opaque or transparent
175
194
  * after the frames are composited
176
195
  * @param options See {@link GIFAnimationEncodeOptions}
196
+ * @throws `Error` if the animation has no frames
197
+ * @throws `RangeError` if the loop count or a frame's duration is more than GIF stores, or the canvas is wider or
198
+ * higher than 65535 pixels
177
199
  */
178
200
  encodeGIF(options?: GIFAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
179
201
  /**
@@ -182,6 +204,8 @@ export declare class Animation {
182
204
  * merged (unless the `optimize` option is false): the file shows exactly the same animation, but doesn't
183
205
  * necessarily decode to the same frames
184
206
  * @param options See {@link APNGEncodeOptions}
207
+ * @throws `Error` if the animation has no frames
208
+ * @throws `RangeError` if the loop count or a frame's duration is more than APNG stores
185
209
  */
186
210
  encodeAPNG(options?: APNGEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
187
211
  /**
@@ -189,12 +213,21 @@ export declare class Animation {
189
213
  * changed since the frame before, identical frames are merged (unless the `optimize` option is false): the file
190
214
  * shows the same animation, but doesn't necessarily decode to the same frames
191
215
  * @param options See {@link WebPAnimationEncodeOptions}
216
+ * @throws `Error` if the animation has no frames
217
+ * @throws `RangeError` if the loop count or a frame's duration is more than WebP stores
192
218
  */
193
219
  encodeWebP(options?: WebPAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
194
220
  /**
195
221
  * An encoder that makes an animated WebP a frame at a time, like {@link Animation.encodeWebP} (the same file),
196
222
  * without keeping the frames in memory: `await encoder.add(frame)` for each frame (a {@link Frame}, or an image
197
223
  * with `{ duration }`), then `await encoder.finish()` for the file
224
+ * @example
225
+ * ```ts
226
+ * const encoder = Animation.webpEncoder(64, 64, { quality: 80 });
227
+ * for (const color of [0xff0000ff, 0x00ff00ff, 0x0000ffff])
228
+ * await encoder.add(new Image(64, 64).fill(color), { duration: 200 });
229
+ * const webp = await encoder.finish();
230
+ * ```
198
231
  * @param width The canvas width
199
232
  * @param height The canvas height
200
233
  * @param options See {@link WebPAnimationEncodeOptions}, and {@link AnimationOptions.loopCount}
@@ -219,8 +252,15 @@ export declare class Animation {
219
252
  static apngEncoder(width: number, height: number, options?: APNGEncodeOptions & AnimationOptions): AnimationEncoder;
220
253
  /**
221
254
  * Decodes an animated GIF, APNG, WebP or JPEG XL into fully composited frames (still images become a single frame)
255
+ * @example
256
+ * ```ts
257
+ * const animation = await Animation.decode(gifBytes);
258
+ * const webp = await animation.resize({ width: 320 }).encodeWebP({ quality: 75 });
259
+ * ```
222
260
  * @param input The binary data to decode
223
261
  * @param options See {@link DecodeOptions}
262
+ * @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 truncated
224
264
  */
225
265
  static decode(input: BinaryData, options?: DecodeOptions): Promise<Animation>;
226
266
  }
package/dist/animation.js CHANGED
@@ -13,7 +13,7 @@ import { optimize } from "./util/optimize.js";
13
13
  import { paletteOptions } from "./codecs/quantize.js";
14
14
  import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
15
15
  import { checkOptions, oneOf, pixelLimit, checkThreads, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, color as checkColor } from "./util/options.js";
16
- import { MAX_PIXELS, decoding } from "./util/limits.js";
16
+ import { MAX_PIXELS, decoding, checkPixels } from "./util/limits.js";
17
17
  import { AnimationEncoder } from "./animation-encoder.js";
18
18
  function canvasFrames(width, height, frames) {
19
19
  return frames.map(({ pixels, duration }) => {
@@ -106,22 +106,44 @@ export class Animation {
106
106
  const originalWidth = this.width, originalHeight = this.height;
107
107
  if (!originalWidth || !originalHeight)
108
108
  throw new RangeError('An animation without frames or canvas can\'t be resized');
109
- let width = givenWidth ?? originalWidth / originalHeight * givenHeight;
110
- let height = givenHeight ?? originalHeight / originalWidth * width;
109
+ if (givenWidth !== undefined && Math.floor(givenWidth) < 1)
110
+ throw new RangeError('The animation has to be at least 1 pixel wide');
111
+ if (givenHeight !== undefined && Math.floor(givenHeight) < 1)
112
+ throw new RangeError('The animation has to be at least 1 pixel high');
113
+ let width, height;
111
114
  if (fit === 'inside' && givenWidth !== undefined && givenHeight !== undefined)
112
- [width, height] = insideSize(originalWidth, originalHeight, givenWidth, givenHeight);
113
- const canvas = canvasSize(Math.max(1, Math.round(width)), Math.max(1, Math.round(height)));
115
+ [width, height] = insideSize(originalWidth, originalHeight, givenWidth, givenHeight).map(Math.floor);
116
+ else if (givenWidth === undefined) {
117
+ height = Math.floor(givenHeight);
118
+ width = Math.max(1, Math.round(originalWidth / originalHeight * height));
119
+ }
120
+ else if (givenHeight === undefined) {
121
+ width = Math.floor(givenWidth);
122
+ height = Math.max(1, Math.round(originalHeight / originalWidth * width));
123
+ }
124
+ else
125
+ [width, height] = [Math.floor(givenWidth), Math.floor(givenHeight)];
126
+ const canvas = canvasSize(Math.max(1, width), Math.max(1, height));
114
127
  const sx = width / originalWidth, sy = height / originalHeight;
115
128
  const changes = this.__distinct__().map(frame => {
116
129
  const left = Math.round(frame.xOffset * sx), top = Math.round(frame.yOffset * sy);
117
130
  const right = Math.round((frame.xOffset + frame.width) * sx), bottom = Math.round((frame.yOffset + frame.height) * sy);
118
131
  return { frame, left, top, width: Math.max(1, right - left), height: Math.max(1, bottom - top) };
119
132
  });
120
- const resized = new Set();
133
+ const shared = new Set(), seen = new Set();
134
+ for (const { frame } of changes)
135
+ (seen.has(frame.image) ? shared : seen).add(frame.image);
136
+ const originals = new Map(Array.from(shared, image => [image, image.clone()]));
137
+ const resized = new Map();
121
138
  for (const { frame, left, top, width, height } of changes) {
122
- if (!resized.has(frame.image))
139
+ const size = `${width}x${height}`, done = resized.get(frame.image), original = originals.get(frame.image);
140
+ if (done === undefined) {
141
+ resized.set(frame.image, size);
123
142
  frame.image.resize(width, height, options);
124
- resized.add(frame.image);
143
+ }
144
+ else if (done !== size && original) {
145
+ frame.image = original.clone().resize(width, height, options);
146
+ }
125
147
  frame.xOffset = left;
126
148
  frame.yOffset = top;
127
149
  }
@@ -129,17 +151,16 @@ export class Animation {
129
151
  return this;
130
152
  }
131
153
  crop(x, y, width, height) {
132
- x = Math.max(0, Math.floor(finite(x, 'x')));
133
- y = Math.max(0, Math.floor(finite(y, 'y')));
134
- width = Math.min(Math.floor(finite(width, 'width')), this.width - x);
135
- height = Math.min(Math.floor(finite(height, 'height')), this.height - y);
136
- if (!(width >= 1 && height >= 1))
154
+ const left = Math.max(0, Math.floor(finite(x, 'x'))), top = Math.max(0, Math.floor(finite(y, 'y')));
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))
137
158
  throw new RangeError('The crop region has to overlap the canvas');
138
159
  for (const frame of this.__distinct__()) {
139
- frame.xOffset -= x;
140
- frame.yOffset -= y;
160
+ frame.xOffset -= left;
161
+ frame.yOffset -= top;
141
162
  }
142
- this.__canvas__ = [width, height];
163
+ this.__canvas__ = [right - left, bottom - top];
143
164
  this.frames = this.__clipped_frames__();
144
165
  return this;
145
166
  }
@@ -190,7 +211,7 @@ export class Animation {
190
211
  scale(factor, options) {
191
212
  if (!(finite(factor, 'factor') > 0))
192
213
  throw new RangeError(`Invalid scale factor: ${factor}`);
193
- return this.resize(this.width * factor, this.height * factor, options);
214
+ return this.resize(Math.max(1, this.width * factor), Math.max(1, this.height * factor), options);
194
215
  }
195
216
  trim(options = {}) {
196
217
  checkOptions(options, 'trim({ tolerance: 0.1 })');
@@ -273,6 +294,13 @@ export class Animation {
273
294
  throw new Error('Animation contains invalid frames');
274
295
  fitDuration(frame.duration, format);
275
296
  }
297
+ const { width, height } = this;
298
+ if (width < 1 || height < 1)
299
+ throw new RangeError('The animation has no canvas: every frame lies outside of it');
300
+ if (format === 'GIF' && (width > 0xffff || height > 0xffff))
301
+ throw new RangeError(`GIF: images can be at most 65535 pixels wide and high, not ${width}x${height}`);
302
+ if (format === 'WebP' && (width > 1 << 24 || height > 1 << 24))
303
+ throw new RangeError('WebP: canvas too large');
276
304
  }
277
305
  async encodeGIF(options = {}) {
278
306
  checkOptions(options, 'encodeGIF({ colors: 64 })');
@@ -411,7 +439,10 @@ export class Animation {
411
439
  }
412
440
  if (type === 'png') {
413
441
  const decoded = await png.decodeAnimation(data, false, maxPixels);
414
- const frames = orient(profile(canvasFrames(decoded.width, decoded.height, png.compositeAnimation(decoded)), decoded.icc), decoded.orientation);
442
+ const step = png.compositor(decoded.width, decoded.height), shown = [];
443
+ for await (const frame of decoded.frames)
444
+ shown.push({ pixels: step(frame), duration: frame.duration });
445
+ const frames = orient(profile(canvasFrames(decoded.width, decoded.height, shown), decoded.icc), decoded.orientation);
415
446
  const animation = new Animation(frames, { loopCount: fromPlays(decoded.plays), width: frames[0]?.width ?? decoded.width, height: frames[0]?.height ?? decoded.height });
416
447
  animation.__animationSignal__ = true;
417
448
  return animation;
@@ -424,6 +455,7 @@ export class Animation {
424
455
  const image = new Image(decoded.width, decoded.height);
425
456
  image.bitmap = alignedPixels(decoded.pixels);
426
457
  frames.push(new Frame(image, { duration: decoded.duration, disposalMode: 'background' }));
458
+ checkPixels(decoded.width, decoded.height, maxPixels, frames.length);
427
459
  orientation = decoded.orientation;
428
460
  loops = fromPlays(decoded.loopCount);
429
461
  animated ||= decoded.animated;
@@ -5,6 +5,7 @@ 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;
7
7
  const UNEXPECTED_END = new Error('GIF: unexpected end of data');
8
+ const EMPTY = new Uint8Array(0);
8
9
  export function encode({ width, height, loopCount = Infinity, frames }, palette, comments = []) {
9
10
  const restores = frames.some(frame => frame.dispose === 3);
10
11
  const parts = [header(width, height, loopCount, comments)];
@@ -144,7 +145,7 @@ export function decode(data, firstFrameOnly = false, maxPixels = MAX_PIXELS) {
144
145
  parse();
145
146
  }
146
147
  catch (err) {
147
- if (err !== UNEXPECTED_END)
148
+ if (err !== UNEXPECTED_END || !frames.length)
148
149
  throw err;
149
150
  }
150
151
  checkPixels(width, height, maxPixels, Math.max(1, frames.length));
@@ -153,7 +154,7 @@ export function decode(data, firstFrameOnly = false, maxPixels = MAX_PIXELS) {
153
154
  while (reader.offset < data.length) {
154
155
  const block = reader.u8();
155
156
  if (block === 0x3b)
156
- break;
157
+ return;
157
158
  if (block === 0x21) {
158
159
  const label = reader.u8();
159
160
  if (label === 0xf9) {
@@ -189,7 +190,7 @@ export function decode(data, firstFrameOnly = false, maxPixels = MAX_PIXELS) {
189
190
  }
190
191
  if (block !== 0x2c) {
191
192
  if (frames.length)
192
- break;
193
+ return;
193
194
  throw new Error(`GIF: unknown block type 0x${block.toString(16)}`);
194
195
  }
195
196
  const x = reader.u16();
@@ -223,8 +224,9 @@ export function decode(data, firstFrameOnly = false, maxPixels = MAX_PIXELS) {
223
224
  }
224
225
  frames.push({ x, y, width: fw, height: fh, delay, dispose, indices: ordered, colors, transparentIndex });
225
226
  if (firstFrameOnly)
226
- break;
227
+ return;
227
228
  }
229
+ throw UNEXPECTED_END;
228
230
  }
229
231
  }
230
232
  export function composite({ width, height, frames }) {
@@ -249,6 +251,7 @@ export function composite({ width, height, frames }) {
249
251
  }
250
252
  }
251
253
  output.push({ pixels: new Uint8Array(canvas.slice().buffer), delay: frame.delay });
254
+ frame.indices = EMPTY;
252
255
  if (frame.dispose === 3) {
253
256
  for (let y = y0; y < y1; y++)
254
257
  canvas.fill(0, y * width + x0, y * width + x1);
@@ -333,11 +336,19 @@ function lzwDecode(data, minCodeSize, pixelCount) {
333
336
  function readSubBlocks(reader) {
334
337
  const blocks = [];
335
338
  let total = 0;
336
- for (let length; reader.offset < reader.data.length && (length = reader.u8());) {
339
+ let terminated = false;
340
+ while (reader.offset < reader.data.length) {
341
+ const length = reader.u8();
342
+ if (!length) {
343
+ terminated = true;
344
+ break;
345
+ }
337
346
  const block = reader.slice(length);
338
347
  blocks.push(block);
339
348
  total += block.length;
340
349
  }
350
+ if (!terminated)
351
+ throw UNEXPECTED_END;
341
352
  const out = new Uint8Array(total);
342
353
  let offset = 0;
343
354
  for (const block of blocks) {
@@ -86,6 +86,8 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
86
86
  case 0xc2: {
87
87
  if (frame)
88
88
  throw new Error('JPEG: multiple frames are not supported');
89
+ if (end - start < 6)
90
+ throw new Error('JPEG: truncated frame header');
89
91
  if (data[start] !== 8)
90
92
  throw new Error(`JPEG: ${data[start]}-bit precision is not supported`);
91
93
  checkPixels(u16(start + 3), u16(start + 1), maxPixels);
@@ -18,8 +18,11 @@ class Sections {
18
18
  constructor(d, t) {
19
19
  this.d = d;
20
20
  this.t = t;
21
- if (t.offsets.length === 1)
21
+ if (t.offsets.length === 1) {
22
+ if (t.offsets[0] + t.sizes[0] > d.length)
23
+ throw new Error('JPEG XL: truncated data');
22
24
  this.single = new BitReader(d, t.offsets[0], t.offsets[0] + t.sizes[0]);
25
+ }
23
26
  }
24
27
  get(i) {
25
28
  if (this.single)
@@ -355,6 +355,7 @@ function parse(array) {
355
355
  let current = null;
356
356
  let sequence = 0;
357
357
  let animationError = false;
358
+ let ended = false, truncated = false;
358
359
  let offset = 8;
359
360
  while (offset + 8 <= array.length) {
360
361
  const length = view.getUint32(offset);
@@ -438,8 +439,10 @@ function parse(array) {
438
439
  srgb = true;
439
440
  else if (type === tEXt || type === zTXt || type === iTXt)
440
441
  text.push({ type, chunk });
441
- else if (type === IEND)
442
+ else if (type === IEND) {
443
+ ended = true;
442
444
  break;
445
+ }
443
446
  offset = end + 4;
444
447
  }
445
448
  if (!header)
@@ -459,10 +462,15 @@ function parse(array) {
459
462
  if (animation) {
460
463
  if (frames.length > animation.frames)
461
464
  frames.length = animation.frames;
462
- if (!frames.length || frames.length < animation.frames || frames.some(f => !f.data.length))
465
+ if (!ended) {
466
+ truncated = true;
467
+ while (frames.length && !frames[frames.length - 1].data.length)
468
+ frames.pop();
469
+ }
470
+ if (!frames.length || (frames.length < animation.frames && !truncated) || frames.some(f => !f.data.length))
463
471
  animationError = true;
464
472
  }
465
- return { header, palette, transparency, idat, exif, iccp: srgb ? null : iccp, text, animation, frames, animationError };
473
+ return { header, palette, transparency, idat, exif, iccp: srgb ? null : iccp, text, animation, frames, animationError, truncated };
466
474
  }
467
475
  function passesOf(p, width, height) {
468
476
  const bitsPerPixel = COLOR_TYPE_CHANNELS[p.header.colorType] * p.header.depth;
@@ -547,27 +555,45 @@ export async function decodeAnimation(array, firstFrameOnly = false, maxPixels =
547
555
  checkPixels(width, height, maxPixels, !p.animation || p.animationError || firstFrameOnly ? 1 : Math.max(1, p.frames.length));
548
556
  if (!p.animation || p.animationError) {
549
557
  const pixels = await decodeImageData(p, p.idat, width, height);
550
- return { width, height, plays: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, dispose: 0, blend: 0, pixels }], icc: await profile(p.iccp), orientation };
558
+ const still = async function* () {
559
+ yield { x: 0, y: 0, width, height, duration: 0, dispose: 0, blend: 0, pixels };
560
+ };
561
+ return { width, height, plays: 0, frames: still(), icc: await profile(p.iccp), orientation };
551
562
  }
552
- const frames = [];
553
- for (const { control: c, data } of p.frames) {
563
+ for (const { control: c } of p.frames)
554
564
  if (!c.width || !c.height || c.x + c.width > width || c.y + c.height > height)
555
565
  throw new Error('PNG: invalid APNG frame region');
556
- frames.push({
557
- x: c.x, y: c.y, width: c.width, height: c.height, duration: c.delay,
558
- dispose: !frames.length && c.dispose === 2 ? 1 : c.dispose,
559
- blend: c.blend,
560
- pixels: await decodeImageData(p, data, c.width, c.height)
561
- });
562
- if (firstFrameOnly)
563
- break;
566
+ async function* frames() {
567
+ let count = 0;
568
+ for (const { control: c, data } of p.frames) {
569
+ let pixels;
570
+ try {
571
+ pixels = await decodeImageData(p, data, c.width, c.height);
572
+ }
573
+ catch (error) {
574
+ if (p.truncated && count)
575
+ return;
576
+ throw error;
577
+ }
578
+ yield {
579
+ x: c.x, y: c.y, width: c.width, height: c.height, duration: c.delay,
580
+ dispose: !count++ && c.dispose === 2 ? 1 : c.dispose,
581
+ blend: c.blend,
582
+ pixels
583
+ };
584
+ if (firstFrameOnly)
585
+ return;
586
+ }
564
587
  }
565
- return { width, height, plays: p.animation.plays, frames, icc: await profile(p.iccp), orientation };
588
+ return { width, height, plays: p.animation.plays, frames: frames(), icc: await profile(p.iccp), orientation };
566
589
  }
567
590
  export function compositeAnimation({ width, height, frames }) {
591
+ const step = compositor(width, height);
592
+ return frames.map(f => ({ pixels: step(f), duration: f.duration }));
593
+ }
594
+ export function compositor(width, height) {
568
595
  const canvas = new Uint8Array(width * height * 4);
569
- const output = [];
570
- for (const f of frames) {
596
+ return f => {
571
597
  const previous = f.dispose === 2 ? canvas.slice() : null;
572
598
  for (let y = 0; y < f.height; y++) {
573
599
  if (f.blend === 0) {
@@ -593,14 +619,14 @@ export function compositeAnimation({ width, height, frames }) {
593
619
  }
594
620
  }
595
621
  }
596
- output.push({ pixels: canvas.slice(), duration: f.duration });
622
+ const shown = canvas.slice();
597
623
  if (f.dispose === 1)
598
624
  for (let y = 0; y < f.height; y++)
599
625
  canvas.fill(0, ((f.y + y) * width + f.x) * 4, ((f.y + y) * width + f.x + f.width) * 4);
600
626
  else if (previous)
601
627
  canvas.set(previous);
602
- }
603
- return output;
628
+ return shown;
629
+ };
604
630
  }
605
631
  const RAW_EXIF = /^Raw profile type (exif|APP1)$/;
606
632
  const XMP = 'XML:com.adobe.xmp';
@@ -1,18 +1,16 @@
1
- import { oneOf } from "../util/options.js";
1
+ import { oneOf, finite } from "../util/options.js";
2
2
  const WR = 3, WG = 4, WB = 2;
3
3
  const DITHER = { 'none': true, 'floyd-steinberg': true, 'atkinson': true, 'ordered': true };
4
4
  export const DITHER_METHODS = Object.keys(DITHER);
5
5
  export function paletteOptions(colors, dither, ditherStrength) {
6
6
  let count;
7
7
  if (colors !== undefined) {
8
- count = Number(colors);
8
+ count = finite(colors, 'colors');
9
9
  if (!Number.isInteger(count) || count < 2 || count > 256)
10
10
  throw new RangeError(`colors must be an integer from 2 to 256, not ${colors}`);
11
11
  }
12
12
  oneOf(dither, DITHER_METHODS, 'dither');
13
- const strength = Number(ditherStrength);
14
- if (!Number.isFinite(strength))
15
- throw new RangeError(`Invalid ditherStrength: ${ditherStrength}`);
13
+ const strength = finite(ditherStrength, 'ditherStrength');
16
14
  if (strength < 0 || strength > 1)
17
15
  throw new RangeError(`ditherStrength must be 0-1, not ${ditherStrength}`);
18
16
  return { colors: count, dither: dither, strength };
@@ -118,6 +118,8 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
118
118
  const samplesPerPixel = value(TAGS.SamplesPerPixel, 1);
119
119
  const bitsPerSample = values(TAGS.BitsPerSample, [1]);
120
120
  const bps = bitsPerSample[0];
121
+ if (typeof bps !== 'number')
122
+ throw new Error('TIFF: invalid BitsPerSample');
121
123
  if (bitsPerSample.some(b => b !== bps))
122
124
  throw new Error('TIFF: mixed bit depths are not supported');
123
125
  const compression = value(TAGS.Compression, 1);
@@ -160,6 +162,8 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
160
162
  checkPixels(width, height, maxPixels);
161
163
  checkPixels(segmentWidth, segmentHeight, Math.max(4 * width * height, 1 << 20));
162
164
  checkBytes(Math.ceil(width * samplesPerPixel * bps / 8) * height, maxPixels);
165
+ if (samplesPerPixel > 32)
166
+ throw new Error('TIFF: unsupported number of samples per pixel');
163
167
  const pixels = new Uint8Array(width * height * 4);
164
168
  if (compression === 7) {
165
169
  const jpegTables = tags.get(TAGS.JPEGTables);
@@ -186,8 +190,11 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
186
190
  if (tiled || planar || bps !== 8)
187
191
  throw new Error('TIFF: subsampled YCbCr is only supported for 8-bit strips');
188
192
  const [h, v] = subsampling;
193
+ if (![1, 2, 4].includes(h) || ![1, 2, 4].includes(v))
194
+ throw new Error('TIFF: unsupported YCbCr subsampling');
189
195
  const unitsPerRow = Math.ceil(width / h);
190
196
  const unitRowBytes = unitsPerRow * (h * v + 2);
197
+ checkBytes(Math.ceil(height / v) * unitRowBytes, maxPixels);
191
198
  const units = new Uint8Array(Math.ceil(height / v) * unitRowBytes);
192
199
  let written = 0;
193
200
  for (let s = 0; s < segmentsPerPlane && written < units.length; s++) {