imagescript 4.0.0-rc.5 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,18 +5,25 @@
5
5
  </picture>
6
6
  </h1>
7
7
 
8
- [![Documentation](https://img.shields.io/badge/Documentation-informational?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgcm9sZT0iaW1nIiBhcmlhLWxhYmVsPSJJbWFnZVNjcmlwdCI+PHRpdGxlPkltYWdlU2NyaXB0PC90aXRsZT48cGF0aCBkPSJNMTMyIDk2aC0xNGEzNCAzNCAwIDAgMC0zNCAzNHY3NGEzMCAzMCAwIDAgMS0zMCAzMGgtNnY0NGg2YTMwIDMwIDAgMCAxIDMwIDMwdjc0YTM0IDM0IDAgMCAwIDM0IDM0aDE0IE0zODAgOTZoMTRhMzQgMzQgMCAwIDEgMzQgMzR2NzRhMzAgMzAgMCAwIDAgMzAgMzBoNnY0NGgtNmEzMCAzMCAwIDAgMC0zMCAzMHY3NGEzNCAzNCAwIDAgMS0zNCAzNGgtMTQiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2ZmZiIgc3Ryb2tlLXdpZHRoPSIzMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PHJlY3QgeD0iMTY0IiB5PSIxNjQiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjI4IiB5PSIxNjQiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjkyIiB5PSIxNjQiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMTY0IiB5PSIyMjgiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjI4IiB5PSIyMjgiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjkyIiB5PSIyMjgiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMTY0IiB5PSIyOTIiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjI4IiB5PSIyOTIiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjkyIiB5PSIyOTIiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PC9zdmc+Cg==)](https://imagescript.dev/)
9
- [![Playground](https://img.shields.io/badge/Playground-Try%20it%20live-ff2d75?style=for-the-badge&labelColor=ff7a18&logoColor=white&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyNCAyNCc%2BPHBhdGggZmlsbD0nd2hpdGUnIGQ9J003IDQuNXYxNWwxMi41LTcuNXonLz48L3N2Zz4%3D)](https://try.imagescript.dev/)
10
-
11
- [![Github](https://img.shields.io/badge/Github-Repository-181717?logo=github&style=for-the-badge)](https://github.com/imagescript/ImageScript)
12
- [![Discord Server](https://img.shields.io/discord/691713541262147687.svg?label=Discord&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2&style=for-the-badge)](https://discord.gg/8hPrwAH)
8
+ <p align="center">
9
+ <a href="https://imagescript.dev/"><img alt="Documentation" src="https://img.shields.io/badge/Documentation-141821?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgcm9sZT0iaW1nIiBhcmlhLWxhYmVsPSJJbWFnZVNjcmlwdCI+PHRpdGxlPkltYWdlU2NyaXB0PC90aXRsZT48cGF0aCBkPSJNMTMyIDk2aC0xNGEzNCAzNCAwIDAgMC0zNCAzNHY3NGEzMCAzMCAwIDAgMS0zMCAzMGgtNnY0NGg2YTMwIDMwIDAgMCAxIDMwIDMwdjc0YTM0IDM0IDAgMCAwIDM0IDM0aDE0IE0zODAgOTZoMTRhMzQgMzQgMCAwIDEgMzQgMzR2NzRhMzAgMzAgMCAwIDAgMzAgMzBoNnY0NGgtNmEzMCAzMCAwIDAgMC0zMCAzMHY3NGEzNCAzNCAwIDAgMS0zNCAzNGgtMTQiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2ZmZiIgc3Ryb2tlLXdpZHRoPSIzMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PHJlY3QgeD0iMTY0IiB5PSIxNjQiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjI4IiB5PSIxNjQiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjkyIiB5PSIxNjQiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMTY0IiB5PSIyMjgiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjI4IiB5PSIyMjgiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjkyIiB5PSIyMjgiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMTY0IiB5PSIyOTIiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjI4IiB5PSIyOTIiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjkyIiB5PSIyOTIiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PC9zdmc+Cg=="></a>
10
+ <a href="https://try.imagescript.dev/"><img alt="Playground" src="https://img.shields.io/badge/Playground-141821?style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAyNCAyNCc%2BPHBhdGggZmlsbD0nd2hpdGUnIGQ9J003IDQuNXYxNWwxMi41LTcuNXonLz48L3N2Zz4%3D"></a>
11
+ <a href="https://github.com/imagescript/ImageScript/discussions"><img alt="Discussions" src="https://img.shields.io/badge/Discussions-141821?style=for-the-badge&logo=github&logoColor=white"></a>
12
+ <a href="https://discord.gg/8hPrwAH"><img alt="Discord" src="https://img.shields.io/badge/Discord-141821?style=for-the-badge&logo=discord&logoColor=white"></a>
13
+ </p>
14
+ <p align="center">
15
+ <a href="https://www.npmjs.com/package/imagescript"><img alt="npm" src="https://img.shields.io/npm/v/imagescript?style=flat-square&color=e85d8c&label=npm"></a>
16
+ <a href="https://jsr.io/@matmen/imagescript"><img alt="JSR" src="https://img.shields.io/jsr/v/@matmen/imagescript?style=flat-square&color=4c7df0&label=jsr"></a>
17
+ <a href="https://github.com/imagescript/ImageScript/actions/workflows/node.yml"><img alt="Tests" src="https://img.shields.io/github/actions/workflow/status/imagescript/ImageScript/node.yml?branch=master&style=flat-square&label=tests"></a>
18
+ <a href="https://github.com/imagescript/ImageScript/blob/master/LICENSE"><img alt="MIT license" src="https://img.shields.io/npm/l/imagescript?style=flat-square&color=8e6cef&label=license"></a>
19
+ </p>
13
20
 
14
21
  ---
15
22
 
16
23
  **ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, and no
17
- runtime dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's
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
24
+ runtime dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (such as Cloudflare
25
+ Workers), works with `import` and, on supported Node.js versions, `require()`, and ships with type
26
+ 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
27
  supports it.
21
28
 
22
29
  ```sh
@@ -24,29 +31,7 @@ npm install imagescript # Node.js, Bun and bundlers
24
31
  deno add jsr:@matmen/imagescript # Deno
25
32
  ```
26
33
 
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
-
29
- Without a bundler, import it from jsDelivr in the browser:
30
-
31
- ```html
32
- <script type="module">
33
- import { Image } from 'https://cdn.jsdelivr.net/npm/imagescript@4/+esm';
34
-
35
- const image = await Image.decode(await fetch('photo.jpg').then(r => r.arrayBuffer()));
36
- image.resize({ width: 256 });
37
- const url = URL.createObjectURL(new Blob([await image.encodePNG()], { type: 'image/png' }));
38
- document.body.append(Object.assign(document.createElement('img'), { src: url }));
39
- </script>
40
- ```
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, `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.
34
+ Upgrading from 3.x? Read [Migrating to 4.0](https://github.com/imagescript/ImageScript/blob/master/guides/Migrating%20to%204.0.md) first.
50
35
 
51
36
  ---
52
37
 
@@ -61,14 +46,27 @@ image.resize({ width: 256 }).roundCorners({ radius: 16 });
61
46
  await writeFile('output.png', await image.encodePNG());
62
47
  ```
63
48
 
64
- <p align="center">
65
- <a href="https://try.imagescript.dev/">
66
- <img src="https://github.com/imagescript/ImageScript/raw/master/media/playground-cta.svg" alt="Try ImageScript in the Playground" width="440">
67
- </a>
68
- </p>
69
-
70
49
  [![Example](https://github.com/imagescript/ImageScript/raw/master/tests/targets/readme.png)](https://github.com/imagescript/ImageScript/blob/master/tests/readme.js)
71
50
 
51
+ The same code runs everywhere, only reading and writing the bytes differs. `Image.decode()` takes any `ArrayBuffer` or
52
+ typed array (`fetch(url).then(r => r.arrayBuffer())` in a browser or on an edge runtime, `Deno.readFile()`,
53
+ `Bun.file().arrayBuffer()`), and the encoders return a `Uint8Array`. In a browser without a bundler, import it from jsDelivr:
54
+
55
+ ```js
56
+ import { Image } from 'https://cdn.jsdelivr.net/npm/imagescript@4/+esm';
57
+ ```
58
+
59
+ ### Threads and bundlers
60
+
61
+ The codecs that can use worker threads (large AVIF and JPEG XL images, lossless WebP; the `threads` option) do so in
62
+ Node.js, Deno and Bun, and in browsers on cross-origin isolated pages. Where workers can't start, the work runs on the
63
+ calling thread: the output is the same, only slower, and nothing warns about it. Browsers refuse workers from another
64
+ origin, so the jsDelivr import above runs single-threaded; serve the package from your own origin (on a cross-origin
65
+ isolated page) to get threads.
66
+
67
+ Bundlers that write one file (esbuild, Rollup, `bun build`) don't copy the worker's module: serve `dist/util/worker.js` next to the
68
+ bundle, or the same single-threaded fallback is used. webpack and Vite emit it.
69
+
72
70
  ---
73
71
 
74
72
  ### Features
@@ -88,7 +86,8 @@ await writeFile('output.png', await image.encodePNG());
88
86
  [Animations](https://imagescript.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL,
89
87
  and encoded as GIF, APNG or WebP, all at once or
90
88
  [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.
89
+ exactly; lossy encoding makes smaller files by approximating some image detail. `quality: 100` is lossless for WebP,
90
+ AVIF and JPEG XL (JPEG has no lossless mode). Without a `quality`, WebP and JPEG XL are lossless and AVIF is lossy.
92
91
 
93
92
  Not supported (decoding them throws an error): CCITT-compressed TIFF and arithmetic-coded JPEG. Lossless JPEG XL is
94
93
  fast but not small: for small lossless files, PNG or WebP are the better choice.
@@ -129,7 +128,3 @@ ImageScript builds on [fflate](https://github.com/101arrowz/fflate), libjpeg, [p
129
128
  [libjxl](https://github.com/libjxl/libjxl). The TrueType hinting follows [FreeType](https://freetype.org): portions of
130
129
  this software are copyright © 2026 The FreeType Project (www.freetype.org). All rights reserved. See
131
130
  [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for the licenses.
132
-
133
- ---
134
-
135
- Questions? Join the [Discord server](https://discord.gg/8hPrwAH).
@@ -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
  }