imagescript 4.0.0-rc.1 → 4.0.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,15 +1,19 @@
1
- This software is licensed under the following license(s):
2
- - GNU AFFERO GENERAL PUBLIC LICENSE, Version 3
3
- - MIT License
1
+ Copyright (c) 2020-2026 Mathis Mensing
4
2
 
5
- == SPDX-License-Identifier: AGPL-3.0-or-later OR MIT ==
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
6
9
 
7
- You may choose to comply with either one of the above
8
- mentioned licenses, but a license must be chosen.
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
9
12
 
10
- The corresponding license files can be found in the projects
11
- root directory, prefixed with LICENSE, suffixed with their
12
- corresponding SPDX identifier.
13
-
14
- Parts of this software are derived from third party projects under their
15
- own licenses (MIT, Apache-2.0 and the IJG license), see THIRD_PARTY_NOTICES.md.
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
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. 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: 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://imagescript.dev/documents/Migrating_to_4.0.html) first.
27
+ Upgrading from 3.x? Read [Migrating to 4.0](https://github.com/imagescript/ImageScript/blob/v4/guides/Migrating%20to%204.0.md) first.
28
28
 
29
29
  Without a bundler, import it from jsDelivr in the browser:
30
30
 
@@ -1,6 +1,6 @@
1
1
  # Third party notices
2
2
 
3
- ImageScript is licensed under AGPL-3.0-or-later OR MIT (see [LICENSE](LICENSE)). Parts of it are derived from the
3
+ ImageScript is licensed under MIT (see [LICENSE](LICENSE)). Parts of it are derived from the
4
4
  following projects, under their own licenses. Each derived file says so in its header.
5
5
 
6
6
  | Project | Used in | License |
@@ -18,6 +18,7 @@ export declare class AnimationEncoder {
18
18
  readonly width: number;
19
19
  /** The canvas height */
20
20
  readonly height: number;
21
+ private constructor();
21
22
  /** How many frames were added */
22
23
  get frameCount(): number;
23
24
  /**
@@ -7,7 +7,19 @@ 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 } from "./util/options.js";
10
+ import { checkOptions, finite, compressionLevel, loopCount, toPlays, fitLoops, fitDuration, maxDuration } from "./util/options.js";
11
+ function clipToCanvas(frame, width, height) {
12
+ const { x, y, width: w, height: h } = frame;
13
+ if (x >= 0 && y >= 0 && x + w <= width && y + h <= height)
14
+ return frame;
15
+ const left = Math.max(0, x), top = Math.max(0, y), right = Math.min(width, x + w), bottom = Math.min(height, y + h);
16
+ if (right <= left || bottom <= top)
17
+ return { ...frame, x: 0, y: 0, width: 1, height: 1, disposal: 1, dispose: 0, pixels: new Uint8Array(4) };
18
+ const pixels = new Uint8Array((right - left) * (bottom - top) * 4);
19
+ for (let row = top; row < bottom; row++)
20
+ pixels.set(frame.pixels.subarray(((row - y) * w + left - x) * 4, ((row - y) * w + right - x) * 4), (row - top) * (right - left) * 4);
21
+ return { ...frame, x: left, y: top, width: right - left, height: bottom - top, pixels };
22
+ }
11
23
  export class AnimationEncoder {
12
24
  format;
13
25
  optimizer;
@@ -25,7 +37,7 @@ export class AnimationEncoder {
25
37
  get frameCount() {
26
38
  return this.count;
27
39
  }
28
- add(frame, options = {}) {
40
+ async add(frame, options = {}) {
29
41
  checkOptions(options, 'encoder.add(frame, { duration: 40 })');
30
42
  if (this.finished)
31
43
  throw new Error('The animation encoder is finished');
@@ -33,12 +45,12 @@ export class AnimationEncoder {
33
45
  const image = own ? own.image : frame;
34
46
  if (!(image instanceof Image))
35
47
  throw new TypeError('encoder.add() takes a Frame or an Image');
36
- const duration = options.duration ?? own?.duration ?? 100;
37
- const x = options.xOffset ?? own?.xOffset ?? 0, y = options.yOffset ?? own?.yOffset ?? 0;
38
- if (finite(duration, 'frame duration') < 0)
48
+ const duration = finite(options.duration ?? own?.duration ?? 100, 'frame duration');
49
+ if (duration < 0)
39
50
  throw new RangeError('Invalid frame duration');
40
- finite(x, 'x offset');
41
- finite(y, 'y offset');
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;
42
54
  const disposal = options.disposalMode !== undefined ? Frame.__convert_disposal_mode__(options.disposalMode) : own ? own.__disposal_id__ : 1;
43
55
  const input = {
44
56
  x, y, width: image.width, height: image.height, duration, disposal,
@@ -46,9 +58,10 @@ export class AnimationEncoder {
46
58
  pixels: new Uint8Array(image.bitmap.buffer, image.bitmap.byteOffset, image.bitmap.byteLength).slice()
47
59
  };
48
60
  this.count++;
61
+ const given = this.optimizer ? input : clipToCanvas(input, this.width, this.height);
49
62
  return this.queue = this.queue.then(async () => {
50
63
  if (!this.optimizer)
51
- return this.format.frame(input, false);
64
+ return this.format.frame(given, false);
52
65
  this.optimizer.push(input);
53
66
  for (const f of this.optimizer.take())
54
67
  await this.format.frame(f, true);
@@ -83,7 +96,8 @@ export class AnimationEncoder {
83
96
  chunks.push(await webp.frameChunk(f, lossy, effort));
84
97
  };
85
98
  return new AnimationEncoder(width, height, {
86
- optimize: { replace: true, even: true, alpha: 'frame', tolerance: lossy ? webp.lossyTolerance(lossy.quality) : undefined },
99
+ name: 'WebP',
100
+ optimize: { replace: true, even: true, alpha: 'frame', tolerance: lossy ? webp.lossyTolerance(lossy.quality) : undefined, maxDuration: maxDuration('WebP') },
87
101
  async frame(f, optimized) {
88
102
  if (optimized)
89
103
  return add(f);
@@ -106,7 +120,8 @@ export class AnimationEncoder {
106
120
  let first = null, restores = false;
107
121
  const rest = [];
108
122
  return new AnimationEncoder(width, height, {
109
- optimize: { replace: false, even: false, alpha: 'frame', palette: 256, cover: true },
123
+ name: 'GIF',
124
+ optimize: { replace: false, even: false, alpha: 'frame', palette: 256, cover: true, maxDuration: maxDuration('GIF') },
110
125
  async frame(f, optimized) {
111
126
  if (!first && optimized)
112
127
  coverCanvas(f, width, height);
@@ -134,7 +149,8 @@ export class AnimationEncoder {
134
149
  const cost = new png.AlphaCost();
135
150
  let blended = false;
136
151
  return new AnimationEncoder(width, height, {
137
- optimize: { replace: true, even: false, alpha: () => cost.cost() },
152
+ name: 'APNG',
153
+ optimize: { replace: true, even: false, alpha: () => cost.cost(), maxDuration: maxDuration('APNG') },
138
154
  async frame(f, optimized) {
139
155
  let frame;
140
156
  if (optimized) {
@@ -1,5 +1,5 @@
1
1
  import { BinaryData } from './util/mem.js';
2
- import { DecodeOptions, EncodeOptions, GIFEncodeOptions, ResizeOptions, ResizeToOptions, RotateOptions, TransformOptions, AffineTransform, ShadowOptions, OutlineOptions, TrimOptions } from './image.js';
2
+ import { DecodeOptions, EncodeOptions, GIFEncodeOptions, ResizeOptions, ResizeToOptions, RotateOptions, TransformOptions, AffineTransform, ShadowOptions, OutlineOptions, TrimOptions, PNGEncodeOptions, WebPEncodeOptions, FlipDirection } from './image.js';
3
3
  import { Frame } from './frame.js';
4
4
  import { AnimationEncoder } from './animation-encoder.js';
5
5
  /** Options of {@link Animation} */
@@ -30,30 +30,24 @@ export interface AnimationEncodeOptions extends EncodeOptions {
30
30
  */
31
31
  optimize?: boolean;
32
32
  }
33
- /** Options of {@link Animation.encodeWebP} */
34
- export interface WebPAnimationEncodeOptions extends AnimationEncodeOptions {
35
- /**
36
- * Lossy compression quality (0-100): higher values usually preserve more detail but make larger files. Without
37
- * this option, frames are encoded losslessly
38
- */
39
- quality?: number;
40
- /**
41
- * Compression effort (0-6): higher effort can make smaller files but takes longer, see
42
- * {@link WebPEncodeOptions.effort}. Default: `2`
43
- */
44
- effort?: number;
45
- /** For lossy frames, improve color detail around sharp edges. Default: `false` */
46
- sharpYuv?: boolean;
47
- /** For lossy frames, the quality of the transparency channel (0-100). Default: `100` */
48
- alphaQuality?: number;
33
+ /**
34
+ * Options of {@link Animation.encodeWebP} and {@link Animation.webpEncoder}: those of {@link WebPEncodeOptions} for every
35
+ * frame (but `threads`: the frames are encoded one at a time), and the animation options. Without `quality` the frames
36
+ * are lossless
37
+ */
38
+ export interface WebPAnimationEncodeOptions extends Omit<WebPEncodeOptions, 'threads'>, AnimationEncodeOptions {
49
39
  }
50
- /** Options of {@link Animation.encodeGIF} and {@link Animation.gifEncoder}: the palette of {@link GIFEncodeOptions} and the animation options */
40
+ /**
41
+ * Options of {@link Animation.encodeGIF} and {@link Animation.gifEncoder}: those of {@link GIFEncodeOptions} for every
42
+ * frame, and the animation options
43
+ */
51
44
  export interface GIFAnimationEncodeOptions extends GIFEncodeOptions, AnimationEncodeOptions {
52
45
  }
53
- /** Options of {@link Animation.encodeAPNG} */
54
- export interface APNGEncodeOptions extends AnimationEncodeOptions {
55
- /** The zlib compression level (0-9), higher is smaller but slower. Default: `4` */
56
- compression?: number;
46
+ /**
47
+ * Options of {@link Animation.encodeAPNG} and {@link Animation.apngEncoder}: those of {@link PNGEncodeOptions}, and the
48
+ * animation options
49
+ */
50
+ export interface APNGEncodeOptions extends PNGEncodeOptions, AnimationEncodeOptions {
57
51
  }
58
52
  /**
59
53
  * An animation: frames ({@link Animation.frames}) that can be decoded from and encoded to GIF, APNG and WebP. It can be
@@ -127,6 +121,12 @@ export declare class Animation {
127
121
  * @param height The new canvas height
128
122
  */
129
123
  crop(x: number, y: number, width: number, height: number): this;
124
+ /**
125
+ * Flips / mirrors the animation horizontally or vertically, like {@link Image.flip}: every frame is flipped and
126
+ * moved to the mirrored place on the canvas, which keeps its size
127
+ * @param direction The direction to flip, see {@link FlipDirection}
128
+ */
129
+ flip(direction: FlipDirection): this;
130
130
  /**
131
131
  * Scales the animation by a factor: every frame and its offsets, and the canvas
132
132
  * @param factor The factor
package/dist/animation.js CHANGED
@@ -6,19 +6,19 @@ import * as jxl from "./codecs/jxl.js";
6
6
  import { availableThreads } from "./util/threads.js";
7
7
  import { view } from "./util/mem.js";
8
8
  import { GainMap } from "./gainmap.js";
9
- import { Image, resizeArguments, insideSize } from "./image.js";
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
12
  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
- import { checkOptions, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, color as checkColor } from "./util/options.js";
15
+ import { checkOptions, oneOf, pixelLimit, checkThreads, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, color as checkColor } from "./util/options.js";
16
16
  import { MAX_PIXELS, decoding } 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 }) => {
20
20
  const image = new Image(width, height);
21
- image.bitmap = pixels;
21
+ image.bitmap = alignedPixels(pixels);
22
22
  return new Frame(image, { duration, disposalMode: 'background' });
23
23
  });
24
24
  }
@@ -112,10 +112,16 @@ export class Animation {
112
112
  [width, height] = insideSize(originalWidth, originalHeight, givenWidth, givenHeight);
113
113
  const canvas = canvasSize(Math.max(1, Math.round(width)), Math.max(1, Math.round(height)));
114
114
  const sx = width / originalWidth, sy = height / originalHeight;
115
- for (const frame of this.frames) {
115
+ const changes = this.__distinct__().map(frame => {
116
116
  const left = Math.round(frame.xOffset * sx), top = Math.round(frame.yOffset * sy);
117
117
  const right = Math.round((frame.xOffset + frame.width) * sx), bottom = Math.round((frame.yOffset + frame.height) * sy);
118
- frame.image.resize(Math.max(1, right - left), Math.max(1, bottom - top), options);
118
+ return { frame, left, top, width: Math.max(1, right - left), height: Math.max(1, bottom - top) };
119
+ });
120
+ const resized = new Set();
121
+ for (const { frame, left, top, width, height } of changes) {
122
+ if (!resized.has(frame.image))
123
+ frame.image.resize(width, height, options);
124
+ resized.add(frame.image);
119
125
  frame.xOffset = left;
120
126
  frame.yOffset = top;
121
127
  }
@@ -129,7 +135,7 @@ export class Animation {
129
135
  height = Math.min(Math.floor(finite(height, 'height')), this.height - y);
130
136
  if (!(width >= 1 && height >= 1))
131
137
  throw new RangeError('The crop region has to overlap the canvas');
132
- for (const frame of this.frames) {
138
+ for (const frame of this.__distinct__()) {
133
139
  frame.xOffset -= x;
134
140
  frame.yOffset -= y;
135
141
  }
@@ -144,7 +150,7 @@ export class Animation {
144
150
  const [boxWidth, boxHeight] = canvasSize(Math.floor(finite(width, 'width')), Math.floor(finite(height, 'height')));
145
151
  this.resize({ width: boxWidth, height: boxHeight, fit: 'inside', ...resizeOpts });
146
152
  const x = (boxWidth - this.width) / 2 | 0, y = (boxHeight - this.height) / 2 | 0;
147
- for (const frame of this.frames) {
153
+ for (const frame of this.__distinct__()) {
148
154
  frame.xOffset += x;
149
155
  frame.yOffset += y;
150
156
  }
@@ -164,6 +170,23 @@ export class Animation {
164
170
  this.resize(Math.max(boxWidth, Math.round(this.width * scale)), Math.max(boxHeight, Math.round(this.height * scale)), options);
165
171
  return this.crop((this.width - boxWidth) / 2, (this.height - boxHeight) / 2, boxWidth, boxHeight);
166
172
  }
173
+ flip(direction) {
174
+ oneOf(direction, FLIP_DIRECTIONS, 'flip direction');
175
+ const width = this.width, height = this.height;
176
+ const flipped = new Set();
177
+ for (const frame of this.__distinct__()) {
178
+ if (!flipped.has(frame.image))
179
+ frame.image.flip(direction);
180
+ flipped.add(frame.image);
181
+ if (direction === 'horizontal')
182
+ frame.xOffset = width - frame.xOffset - frame.width;
183
+ else
184
+ frame.yOffset = height - frame.yOffset - frame.height;
185
+ }
186
+ if (width && height)
187
+ this.__canvas__ = [width, height];
188
+ return this;
189
+ }
167
190
  scale(factor, options) {
168
191
  if (!(finite(factor, 'factor') > 0))
169
192
  throw new RangeError(`Invalid scale factor: ${factor}`);
@@ -207,7 +230,7 @@ export class Animation {
207
230
  return [];
208
231
  return png.compositeAnimation({ width, height, frames: this.__apngFrames__() }).map(({ pixels, duration }) => {
209
232
  const image = new Image(width, height);
210
- image.bitmap = pixels;
233
+ image.bitmap = alignedPixels(pixels);
211
234
  return new Frame(image, { duration, disposalMode: 'background' });
212
235
  });
213
236
  }
@@ -223,6 +246,9 @@ export class Animation {
223
246
  this.__canvas__ = [probe.width, probe.height];
224
247
  return this;
225
248
  }
249
+ __distinct__() {
250
+ return [...new Set(this.__frames__)];
251
+ }
226
252
  __clipped_frames__() {
227
253
  const width = this.width, height = this.height;
228
254
  return this.frames.map(frame => {
@@ -239,19 +265,23 @@ export class Animation {
239
265
  return new Frame(clipped, { ...options, xOffset: left, yOffset: top });
240
266
  });
241
267
  }
242
- __validate__() {
243
- for (const frame of this.frames)
268
+ __validate__(format) {
269
+ if (!this.length)
270
+ throw new Error('An animation needs at least one frame');
271
+ for (const frame of this.frames) {
244
272
  if (!(frame instanceof Frame))
245
273
  throw new Error('Animation contains invalid frames');
274
+ fitDuration(frame.duration, format);
275
+ }
246
276
  }
247
277
  async encodeGIF(options = {}) {
248
278
  checkOptions(options, 'encodeGIF({ colors: 64 })');
249
279
  const { colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {}, optimize = true } = options;
250
280
  const palette = paletteOptions(colors, dither, ditherStrength);
251
281
  const loops = fitLoops(this.loopCount, 'GIF');
252
- this.__validate__();
282
+ this.__validate__('GIF');
253
283
  const frames = optimize
254
- ? this.__optimized__({ replace: false, even: false, alpha: 'frame', palette: 256, cover: true }).map(f => ({ ...f, dispose: f.dispose ? 3 : 1 }))
284
+ ? this.__optimized__({ replace: false, even: false, alpha: 'frame', palette: 256, cover: true, maxDuration: maxDuration('GIF') }).map(f => ({ ...f, dispose: f.dispose ? 3 : 1 }))
255
285
  : Array.from(this.__clipped_frames__(), frame => ({
256
286
  x: frame.xOffset,
257
287
  y: frame.yOffset,
@@ -268,11 +298,9 @@ export class Animation {
268
298
  checkOptions(options, 'encodeAPNG({ compression: 9 })');
269
299
  const { compression = 4, metadata = {}, optimize = true } = options;
270
300
  const loops = fitLoops(this.loopCount, 'APNG');
271
- this.__validate__();
272
- if (!this.length)
273
- throw new Error('An animation needs at least one frame');
301
+ this.__validate__('APNG');
274
302
  const frames = optimize
275
- ? this.__optimized__({ replace: true, even: false, alpha: frames => png.alphaCost(frames.map(f => f.pixels)) }).map(f => ({ ...f, dispose: f.dispose ? 1 : 0 }))
303
+ ? this.__optimized__({ replace: true, even: false, alpha: frames => png.alphaCost(frames.map(f => f.pixels)), maxDuration: maxDuration('APNG') }).map(f => ({ ...f, dispose: f.dispose ? 1 : 0 }))
276
304
  : this.__apngFrames__().map(({ blend: _, ...f }) => f);
277
305
  return png.encodeAnimation(frames, this.width, this.height, toPlays(loops), compressionLevel(compression), pngText(resolveMetadata(metadata)));
278
306
  }
@@ -280,12 +308,10 @@ export class Animation {
280
308
  checkOptions(options, 'animation.encodeWebP({ quality: 80 })');
281
309
  const { metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 } = options;
282
310
  const loops = fitLoops(this.loopCount, 'WebP');
283
- this.__validate__();
284
- if (!this.length)
285
- throw new Error('An animation needs at least one frame');
311
+ this.__validate__('WebP');
286
312
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
287
313
  const tolerance = lossy ? webp.lossyTolerance(lossy.quality) : undefined;
288
- const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame', tolerance }) : this.__webpFrames__();
314
+ const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame', tolerance, maxDuration: maxDuration('WebP') }) : this.__webpFrames__();
289
315
  return webp.encodeAnimation(frames, this.width, this.height, toPlays(loops), exifData(resolveMetadata(metadata)), lossy, effort);
290
316
  }
291
317
  __webpFrames__() {
@@ -343,13 +369,10 @@ export class Animation {
343
369
  static async decode(input, options = {}) {
344
370
  checkOptions(options, 'Animation.decode(data, { maxPixels: 1e8 })');
345
371
  const { maxPixels = MAX_PIXELS, threads = 1 } = options;
346
- if (!Number.isInteger(threads) || threads < 1)
347
- throw new RangeError(`threads must be a positive integer, not ${threads}`);
348
- if (!(Number(maxPixels) > 0))
349
- throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
372
+ checkThreads(threads);
373
+ pixelLimit(maxPixels);
350
374
  const { toneMapping = 'reinhard' } = options;
351
- if (toneMapping !== 'reinhard' && toneMapping !== 'clamp')
352
- throw new TypeError(`toneMapping must be 'reinhard' or 'clamp', not ${String(toneMapping)}`);
375
+ oneOf(toneMapping, TONE_MAPPINGS, 'toneMapping');
353
376
  return decoding(() => Animation.__decode__(input, options));
354
377
  }
355
378
  static __is_animated__(animation) {
@@ -399,7 +422,7 @@ export class Animation {
399
422
  let orientation = 1;
400
423
  for await (const decoded of jxl.frames(data, maxPixels, toneMapping, threads)) {
401
424
  const image = new Image(decoded.width, decoded.height);
402
- image.bitmap = decoded.pixels;
425
+ image.bitmap = alignedPixels(decoded.pixels);
403
426
  frames.push(new Frame(image, { duration: decoded.duration, disposalMode: 'background' }));
404
427
  orientation = decoded.orientation;
405
428
  loops = fromPlays(decoded.loopCount);
@@ -1487,7 +1487,7 @@ export class TileDecoder {
1487
1487
  const eobTok = m.symbol(cdf, eobCdf + ctx * 4, 2);
1488
1488
  let tok = eobTok + 1;
1489
1489
  let levelTok = tok * 0x41;
1490
- let mag = 0;
1490
+ let mag;
1491
1491
  let scanTable = null, stride, shift, shift2, mask, offsets = 0;
1492
1492
  if (txClass === TX_CLASS_2D) {
1493
1493
  const nonsquare = tx >= RTX_4X8 ? 1 : 0;
@@ -928,7 +928,7 @@ class TileEncoder {
928
928
  const w = tdim(tx, W) * 4, h = tdim(tx, H) * 4, sw = Math.min(w, 32), sh = Math.min(h, 32);
929
929
  const sx = plane ? this.ssx : 0, sy = plane ? this.ssy : 0;
930
930
  const vw = Math.max(0, Math.min(w, (f.width + sx >> sx) - px)), vh = Math.max(0, Math.min(h, (f.height + sy >> sy) - py));
931
- let eob = -1;
931
+ let eob;
932
932
  if (!(this.w && b.skip)) {
933
933
  const res = this.res, coefs = this.coefs, q = this.q;
934
934
  let sse = 0;
@@ -8,12 +8,14 @@ const DEFAULT_EPF = () => ({
8
8
  quantMul: 0.46, pass0SigmaScale: 0.9, pass2SigmaScale: 6.5, borderSadMul: 2 / 3, sigmaForModular: 1
9
9
  });
10
10
  const DEFAULT_GAB = [0.115169525, 0.061248592, 0.115169525, 0.061248592, 0.115169525, 0.061248592];
11
- function blendingInfo(r, haveExtra, resets, mainMode = -1) {
11
+ function blendingInfo(r, numExtra, resets, mainMode = -1) {
12
12
  const mode = r.u32(0, 1, 2, [3, 2]);
13
13
  if (mode > 4)
14
14
  throw new Error('JPEG XL: invalid blend mode');
15
- const usesAlpha = haveExtra && (mode === BLEND_BLEND || mode === BLEND_MULADD);
15
+ const usesAlpha = numExtra > 0 && (mode === BLEND_BLEND || mode === BLEND_MULADD);
16
16
  const alphaChannel = usesAlpha ? r.u32(0, 1, 2, [3, 3]) : 0;
17
+ if (alphaChannel >= Math.max(1, numExtra))
18
+ throw new Error('JPEG XL: invalid blend alpha channel');
17
19
  const clamp = usesAlpha || mode === BLEND_MUL ? r.bool() : false;
18
20
  const source = resets(mainMode >= 0 ? mainMode : mode) ? 0 : r.bits(2);
19
21
  return { mode, alphaChannel, clamp, source };
@@ -100,9 +102,9 @@ export function frameHeader(r, image) {
100
102
  let blending = { mode: BLEND_REPLACE, alphaChannel: 0, clamp: false, source: 0 };
101
103
  const ecBlending = [];
102
104
  if (!allDefault && normal) {
103
- blending = blendingInfo(r, numExtra > 0, resets);
105
+ blending = blendingInfo(r, numExtra, resets);
104
106
  for (let i = 0; i < numExtra; i++)
105
- ecBlending.push(blendingInfo(r, true, resets, blending.mode));
107
+ ecBlending.push(blendingInfo(r, numExtra, resets, blending.mode));
106
108
  }
107
109
  else
108
110
  for (let i = 0; i < numExtra; i++)
@@ -214,7 +214,7 @@ export function readICC(r) {
214
214
  const COMMON_TAGS = ['rTRC', 'rXYZ', 'cprt', 'wtpt', 'bkpt', 'rXYZ', 'gXYZ', 'bXYZ', 'kXYZ', 'rTRC', 'gTRC', 'bTRC', 'kTRC', 'chad', 'desc', 'chrm', 'dmnd', 'dmdd', 'lumi'];
215
215
  const COMMON_DATA = ['XYZ ', 'desc', 'text', 'mluc', 'para', 'curv', 'sf32', 'gbd '];
216
216
  export function decodeICC(stream) {
217
- let at = 0;
217
+ let at;
218
218
  const fail = () => {
219
219
  throw new RangeError('invalid ICC stream');
220
220
  };
@@ -280,7 +280,7 @@ export function findPatches(planes, stride, width, height, distance, numExtra) {
280
280
  maxH = Math.max(maxH, p.h);
281
281
  }
282
282
  let refW = Math.max(maxW, Math.sqrt(total)), refH = Math.max(maxH, Math.sqrt(total));
283
- let spots = [], usedH = 0;
283
+ let spots = [], usedH;
284
284
  for (;;) {
285
285
  refW = Math.floor(refW * 1.05 + 1);
286
286
  refH = Math.floor(refH * 1.05 + 1);
@@ -1,3 +1,4 @@
1
+ import { oneOf } from "../util/options.js";
1
2
  const WR = 3, WG = 4, WB = 2;
2
3
  const DITHER = { 'none': true, 'floyd-steinberg': true, 'atkinson': true, 'ordered': true };
3
4
  export const DITHER_METHODS = Object.keys(DITHER);
@@ -8,8 +9,7 @@ export function paletteOptions(colors, dither, ditherStrength) {
8
9
  if (!Number.isInteger(count) || count < 2 || count > 256)
9
10
  throw new RangeError(`colors must be an integer from 2 to 256, not ${colors}`);
10
11
  }
11
- if (!DITHER_METHODS.includes(dither))
12
- throw new TypeError(`dither must be one of ${DITHER_METHODS.map(name => `'${name}'`).join(', ')}, not ${String(dither)}`);
12
+ oneOf(dither, DITHER_METHODS, 'dither');
13
13
  const strength = Number(ditherStrength);
14
14
  if (!Number.isFinite(strength))
15
15
  throw new RangeError(`Invalid ditherStrength: ${ditherStrength}`);
@@ -17,15 +17,29 @@ export function paletteOptions(colors, dither, ditherStrength) {
17
17
  throw new RangeError(`ditherStrength must be 0-1, not ${ditherStrength}`);
18
18
  return { colors: count, dither: dither, strength };
19
19
  }
20
- export function dominantColor(pixels, include, clusters = 8) {
21
- const { palette, weights } = medianCut(pixels, clusters, 4, include);
22
- if (!weights.length)
20
+ export function dominantColor(pixels, include) {
21
+ const counts = new Uint32Array(4096), sums = new Float64Array(4096 * 3);
22
+ let found = false;
23
+ for (let i = 0; i < pixels.length; i += 4) {
24
+ if (pixels[i + 3] < 128)
25
+ continue;
26
+ const r = pixels[i], g = pixels[i + 1], b = pixels[i + 2];
27
+ if (!include(r, g, b))
28
+ continue;
29
+ const bin = (r >> 4) << 8 | (g >> 4) << 4 | b >> 4;
30
+ counts[bin]++;
31
+ sums[bin * 3] += r;
32
+ sums[bin * 3 + 1] += g;
33
+ sums[bin * 3 + 2] += b;
34
+ found = true;
35
+ }
36
+ if (!found)
23
37
  return null;
24
38
  let best = 0;
25
- for (let i = 1; i < weights.length; i++)
26
- if (weights[i] > weights[best])
27
- best = i;
28
- return [Math.round(palette[best * 3]), Math.round(palette[best * 3 + 1]), Math.round(palette[best * 3 + 2])];
39
+ for (let bin = 1; bin < 4096; bin++)
40
+ if (counts[bin] > counts[best])
41
+ best = bin;
42
+ return [Math.round(sums[best * 3] / counts[best]), Math.round(sums[best * 3 + 1] / counts[best]), Math.round(sums[best * 3 + 2] / counts[best])];
29
43
  }
30
44
  export function quantize(pixels, width, { maxColors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85, transparent = false } = {}) {
31
45
  const length = pixels.length >> 2;
@@ -93,7 +93,7 @@ function inflate(dat, buf) {
93
93
  if (!sl)
94
94
  return buf.subarray(0, 0);
95
95
  const tbts = sl * 8;
96
- let final = 0, pos = 0, bt = 0;
96
+ let final, pos = 0, bt = 0;
97
97
  do {
98
98
  let lm, dm, lbt, dbt;
99
99
  final = bits(dat, pos, 1);
package/dist/colors.js CHANGED
@@ -135,6 +135,8 @@ export class Colors {
135
135
  else if (positions.length === 2) {
136
136
  const gradient = gradientBetween(values[0], values[1]);
137
137
  return position => {
138
+ if (Number.isNaN(position))
139
+ throw new RangeError(`Invalid gradient position: ${position}`);
138
140
  if (position <= positions[0])
139
141
  return values[0];
140
142
  if (position >= positions[1])
@@ -150,6 +152,8 @@ export class Colors {
150
152
  if (minPos === undefined)
151
153
  continue;
152
154
  const maxPos = positions[i];
155
+ if (maxPos === minPos)
156
+ continue;
153
157
  let minVal = values[i - 1];
154
158
  if (minVal === undefined)
155
159
  minVal = values[i];
@@ -157,6 +161,12 @@ export class Colors {
157
161
  const gradient = gradientBetween(minVal, maxVal);
158
162
  gradients.push({ min: minPos, max: maxPos, gradient });
159
163
  }
164
+ if (!gradients.length)
165
+ return position => {
166
+ if (Number.isNaN(position))
167
+ throw new RangeError(`Invalid gradient position: ${position}`);
168
+ return position <= minDef ? values[0] : values[values.length - 1];
169
+ };
160
170
  return position => {
161
171
  if (position <= minDef)
162
172
  return gradients[0].gradient(0);
package/dist/frame.d.ts CHANGED
@@ -55,14 +55,17 @@ export declare class Frame {
55
55
  * @param duration Milliseconds, a finite number from 0
56
56
  */
57
57
  set duration(duration: number);
58
- /** The frame's horizontal offset in the animation (a finite number, else it throws a RangeError) */
58
+ /**
59
+ * The frame's horizontal offset in the animation: an integer, values with a fraction are truncated like image sizes
60
+ * (a value that isn't a finite number throws a RangeError)
61
+ */
59
62
  get xOffset(): number;
60
63
  /**
61
64
  * Sets the horizontal offset
62
65
  * @param x The offset in pixels
63
66
  */
64
67
  set xOffset(x: number);
65
- /** The frame's vertical offset in the animation (a finite number, else it throws a RangeError) */
68
+ /** The frame's vertical offset in the animation: an integer, like {@link Frame.xOffset} */
66
69
  get yOffset(): number;
67
70
  /**
68
71
  * Sets the vertical offset
package/dist/frame.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Image } from "./image.js";
2
- import { checkOptions, finite } from "./util/options.js";
2
+ import { checkOptions, finite, oneOf } from "./util/options.js";
3
3
  const DISPOSAL_MODES = ['any', 'keep', 'previous', 'background'];
4
4
  export class Frame {
5
5
  __image__;
@@ -8,10 +8,7 @@ export class Frame {
8
8
  __y__ = 0;
9
9
  __disposalMode__ = 1;
10
10
  static __convert_disposal_mode__(mode) {
11
- const id = DISPOSAL_MODES.indexOf(mode);
12
- if (id < 0)
13
- throw new RangeError('Invalid disposal mode');
14
- return id;
11
+ return DISPOSAL_MODES.indexOf(oneOf(mode, DISPOSAL_MODES, 'disposal mode'));
15
12
  }
16
13
  constructor(image, options = {}) {
17
14
  if (!(image instanceof Image))
@@ -51,13 +48,13 @@ export class Frame {
51
48
  return this.__x__;
52
49
  }
53
50
  set xOffset(x) {
54
- this.__x__ = finite(x, 'x offset');
51
+ this.__x__ = Math.trunc(finite(x, 'x offset')) || 0;
55
52
  }
56
53
  get yOffset() {
57
54
  return this.__y__;
58
55
  }
59
56
  set yOffset(y) {
60
- this.__y__ = finite(y, 'y offset');
57
+ this.__y__ = Math.trunc(finite(y, 'y offset')) || 0;
61
58
  }
62
59
  get disposalMode() {
63
60
  return DISPOSAL_MODES[this.__disposalMode__];