imagescript 3.8.1 → 3.10.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
@@ -8,8 +8,9 @@
8
8
  ---
9
9
 
10
10
  **ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, no
11
- dependencies. It runs in Node.js 22.13+, Deno, Bun and browsers, with `import` or `require()`, and includes type
12
- definitions.
11
+ dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's Edge
12
+ Runtime, Deno Deploy), works with both `import` and `require()`, and ships with type definitions. Large images are
13
+ encoded and decoded on several threads wherever the runtime supports workers.
13
14
 
14
15
  ```sh
15
16
  npm install imagescript # Node.js, Bun and bundlers
@@ -29,8 +30,8 @@ image.resize(256, Image.RESIZE_AUTO).roundCorners(16);
29
30
  await writeFile('output.png', await image.encode());
30
31
  ```
31
32
 
32
- Coordinates are 0-based, `(0, 0)` is the top left pixel. A bigger example is the
33
- [README image generation](https://github.com/matmen/ImageScript/blob/master/tests/readme.js):
33
+ Coordinates start at `(0, 0)`, the top left pixel. For a bigger example, see the
34
+ [script that generates this image](https://github.com/matmen/ImageScript/blob/master/tests/readme.js):
34
35
 
35
36
  [![Example](https://github.com/matmen/ImageScript/raw/master/tests/targets/readme.png)](https://github.com/matmen/ImageScript/blob/master/tests/readme.js)
36
37
 
@@ -49,12 +50,15 @@ Coordinates are 0-based, `(0, 0)` is the top left pixel. A bigger example is the
49
50
  | BMP, QOI, TGA, Netpbm | ✓ | ✓ |
50
51
  | TIFF, ICO/CUR, Radiance HDR | ✓ | |
51
52
 
52
- Animated WebPs and JPEG XLs decode too, and [animations](https://imagescript.matmen.dev/classes/Animation.html)
53
- encode as GIF, APNG or WebP, also [a frame at a time](https://imagescript.matmen.dev/classes/Animation.html#webpencoder).
53
+ [Animations](https://imagescript.matmen.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL,
54
+ and encoded as GIF, APNG or WebP, all at once or
55
+ [frame by frame](https://imagescript.matmen.dev/classes/Animation.html#webpencoder). Embedded color profiles (Display
56
+ P3, Adobe RGB, ...) are converted to sRGB when decoding, so images look the way browsers show them.
54
57
 
55
- - [Text rendering](https://imagescript.matmen.dev/classes/Image.html#rendertext) with TrueType and OpenType fonts,
56
- in every script, with color emoji
57
- - [SVG rendering](https://imagescript.matmen.dev/classes/Image.html#rendersvg) (no text)
58
+ - [Text rendering](https://imagescript.matmen.dev/classes/Image.html#rendertext) with TrueType and OpenType fonts:
59
+ all scripts, color emoji
60
+ - [SVG rendering](https://imagescript.matmen.dev/classes/Image.html#rendersvg), including text (with fonts you pass
61
+ or fonts embedded in the SVG)
58
62
  - [Resizing](https://imagescript.matmen.dev/classes/Image.html#resize),
59
63
  [cropping](https://imagescript.matmen.dev/classes/Image.html#crop),
60
64
  [rotating](https://imagescript.matmen.dev/classes/Image.html#rotate),
@@ -66,9 +70,9 @@ encode as GIF, APNG or WebP, also [a frame at a time](https://imagescript.matmen
66
70
  [brightness](https://imagescript.matmen.dev/classes/Image.html#brightness),
67
71
  [hueShift](https://imagescript.matmen.dev/classes/Image.html#hueshift), ...
68
72
 
69
- See the [documentation](https://imagescript.matmen.dev/) for everything else, and the
70
- [changelog](https://github.com/matmen/ImageScript/blob/master/CHANGELOG.md) when upgrading from an older major version.
71
- [bench/](bench/README.md) compares ImageScript to Jimp, sharp and others.
73
+ The [documentation](https://imagescript.matmen.dev/) covers the full API. When upgrading from an older major version,
74
+ see the [changelog](https://github.com/matmen/ImageScript/blob/master/CHANGELOG.md). [bench/](bench/README.md)
75
+ compares ImageScript's speed and file sizes with Jimp, sharp and other libraries.
72
76
 
73
77
  ---
74
78
 
@@ -17,7 +17,7 @@ following projects, under their own licenses. Each derived file says so in its h
17
17
  | [libaom](https://aomedia.googlesource.com/aom/) by the Alliance for Open Media | `src/codecs/av1/msac-enc.ts` (the symbol encoder), `src/codecs/av1/fdct.ts` (the forward Walsh-Hadamard transform), `src/codecs/av1/encode.ts` (the loop filter level from the quantizer), `src/codecs/avif-enc.ts` (the quantizer to qindex table) | BSD-2-Clause |
18
18
  | [libavif](https://github.com/AOMediaCodec/libavif) by Joe Drago | `src/codecs/avif.ts` (YUV to RGB conversion with bilinear chroma upsampling, alpha range expansion and unpremultiplication) | BSD-2-Clause |
19
19
  | [jxl-oxide](https://github.com/tirr-c/jxl-oxide) by Wonwoo Choi | `src/codecs/jxl/*` (the JPEG XL decoder: bit reader, header and frame header fields, entropy decoding, VarDCT, dequantization matrices, transforms, restoration filters, upsampling, the parsing of patches, splines and noise) | MIT (or Apache-2.0) |
20
- | [libjxl](https://github.com/libjxl/libjxl) by the JPEG XL Project Authors | `src/codecs/jxl/modular.ts` (Modular decoding: MA trees, predictors, the self-correcting predictor, transforms), `src/codecs/jxl/frame.ts` (the sections of frames, the order of the rendering stages, reference frames), `src/codecs/jxl/blend.ts`, `src/codecs/jxl/color.ts` (XYB to RGB), `src/codecs/jxl/features.ts` (rendering patches, splines and noise), `src/codecs/jxl/fast-lossless.ts` (the lossless encoder: palette detection, YCoCg, the gradient predictor, prefix codes, runs as LZ77, the headers) | BSD-3-Clause |
20
+ | [libjxl](https://github.com/libjxl/libjxl) by the JPEG XL Project Authors | `src/codecs/jxl/modular.ts` (Modular decoding: MA trees, predictors, the self-correcting predictor, transforms), `src/codecs/jxl/frame.ts` (the sections of frames, the order of the rendering stages, reference frames), `src/codecs/jxl/blend.ts`, `src/codecs/jxl/color.ts` (XYB to RGB), `src/codecs/jxl/features.ts` (rendering patches, splines and noise), `src/codecs/jxl/fast-lossless.ts` (the lossless encoder: palette detection, YCoCg, the gradient predictor, prefix codes, runs as LZ77, the headers), `src/codecs/jxl/patches-enc.ts` (finding text-like patches, packing them into a reference frame, quantizing it like Modular XYB, the patch dictionary) | BSD-3-Clause |
21
21
  | [JPEG XL conformance](https://github.com/libjxl/conformance) by the JPEG XL Project Authors | `tests/jxl/alpha-*.jxl`, `animation-spline.jxl`, `blendmodes.jxl`, `mul-no-extra-channels.jxl` (test files) | BSD-3-Clause |
22
22
  | [Various smartphones - Android, Blackberry, Windows Phone, and iOS.jpg](https://commons.wikimedia.org/wiki/File:Various_smartphones_-_Android,_Blackberry,_Windows_Phone,_and_iOS.jpg) by Carlos Varela | `tests/targets/external.png` and `external.jpg` (a square of it, scaled to 638x638), the test files made from them (`tests/avif`, `tests/jxl`, `tests/ico`, `tests/hdr`, `tests/qoi`, `tests/tiffs`) and the test targets showing them; `bench/inputs/photo.jpg` (unmodified) | [CC BY 2.0](https://creativecommons.org/licenses/by/2.0/) |
23
23
  | [FreeType](https://freetype.org) | `src/render/hinting.ts` (behavior and parts of the logic of the TrueType interpreter) | FreeType License |
@@ -25,8 +25,11 @@ following projects, under their own licenses. Each derived file says so in its h
25
25
  | [Pillow](https://github.com/python-pillow/Pillow) | `src/util/resample.ts` (filter coefficients, box, bilinear and bicubic filters) | MIT-CMU |
26
26
  | [HarfBuzz](https://github.com/harfbuzz/harfbuzz) | `src/render/buffer.ts`, `src/render/layout.ts`, `src/render/shape.ts`, `src/render/shapers/*` (OpenType shaping: buffer, GSUB/GPOS, normalization, fallback positioning, the script shapers and syllable grammars), `scripts/unicode.js` (shaping category tables) | Old MIT |
27
27
  | [Universal Shaping Engine data](https://github.com/harfbuzz/harfbuzz/tree/main/src/ms-use) by Microsoft | `scripts/ms-use` (category overrides, invalid vowel sequences), the tables generated from them in `src/render/unicode-data.ts` | MIT |
28
- | [resvg](https://github.com/linebender/resvg) by the Resvg Authors | `src/render/filter.ts` (the filter effects: regions, inputs, color spaces, box blur (based on [fastblur](https://github.com/fschutt/fastblur)), IIR blur, offset, flood, composite, merge, drop shadow, color matrix, component transfer, tile, morphology, convolution), `src/render/svg.ts` (the filters' attributes like usvg; how patterns are rendered and their reference cycles broken, following resvg and usvg; the markers' placement and orientation, ported from usvg; as many cubics per arc as kurbo makes for usvg; how images are fitted, clipped and sampled), `tests/svgs/resvg` (test cases with resvg's renderings) | MIT (or Apache-2.0) |
29
- | [tiny-skia](https://github.com/linebender/tiny-skia) by Yevhenii Reizner (from [Skia](https://skia.org) by Google) | `src/render/filter.ts` (feBlend's blend modes) | BSD-3-Clause |
28
+ | [resvg](https://github.com/linebender/resvg) by the Resvg Authors | `src/render/filter.ts` (the filter effects: regions, inputs, color spaces, box blur (based on [fastblur](https://github.com/fschutt/fastblur)), IIR blur, offset, flood, composite, merge, drop shadow, color matrix, component transfer, tile, morphology, convolution), `src/render/svg.ts` (the filters' attributes like usvg; how patterns are rendered and their reference cycles broken, following resvg and usvg; the markers' placement and orientation, ported from usvg; as many cubics per arc as kurbo makes for usvg; how images are fitted, clipped and sampled; transform-origin, paint-order, context-fill and context-stroke, mix-blend-mode and isolation, following usvg; how text elements are read: whitespace, positions, chunks, spans, decorations, baseline shifts, text paths, as in usvg), `src/render/svg-text.ts` (text layout ported from usvg: shaping across spans, spacing, text length, anchors, positions along paths, baselines, decorations, vertical text, color glyphs' placement), `tests/svgs/resvg` (test cases with resvg's renderings) | MIT (or Apache-2.0) |
29
+ | resvg's test fonts: [Noto](https://notofonts.github.io) fonts by Google, [Amiri](https://github.com/aliftype/amiri) by Khaled Hosny, [M+](https://mplusfonts.github.io) by the M+ Fonts Project, [Sedgwick Ave Display](https://github.com/googlefonts/sedgwickave) by Kevin Burke, [Source Sans Pro](https://github.com/adobe-fonts/source-sans) by Adobe, [Yellowtail](https://fonts.google.com/specimen/Yellowtail) by Astigmatic, [Twemoji](https://github.com/twitter/twemoji) by Twitter, a CFF and sbix test font of resvg | `tests/fonts/resvg` (subsets, see `scripts/resvg-test-fonts.py`; their licenses are next to them) | OFL-1.1, Apache-2.0, MIT, CC-BY 4.0 (Twemoji's graphics) |
30
+ | [fontdb](https://github.com/RazrFalcon/fontdb) by Yevhenii Reizner | `src/render/svg-text.ts` (font matching: CSS Fonts' algorithm as fontdb's queries do it, the fallback's style check) | MIT |
31
+ | [kurbo](https://github.com/linebender/kurbo) by Raph Levien | `src/render/svg-text.ts` (arc lengths of cubics: adaptive Legendre-Gauss quadrature; parameters at arc lengths: the ITP method) | MIT (or Apache-2.0) |
32
+ | [tiny-skia](https://github.com/linebender/tiny-skia) by Yevhenii Reizner (from [Skia](https://skia.org) by Google) | `src/render/blend.ts` (the blend modes of feBlend and mix-blend-mode) | BSD-3-Clause |
30
33
  | [gaussianiir](http://www.getreuer.info/home/gaussianiir) by Pascal Getreuer | `src/render/filter.ts` (the IIR blur for small deviations, through resvg) | BSD-2-Clause (Simplified BSD) |
31
34
  | [Unicode Character Database](https://www.unicode.org/ucd/) | `src/render/unicode-data.ts` (character properties, generated by `scripts/unicode.js`) | Unicode License v3 |
32
35
 
@@ -523,6 +526,62 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
523
526
  DEALINGS IN THE SOFTWARE.
524
527
  ```
525
528
 
529
+ ## fontdb
530
+
531
+ ```
532
+ The MIT License (MIT)
533
+
534
+ Copyright (c) 2020 Yevhenii Reizner
535
+
536
+ Permission is hereby granted, free of charge, to any person obtaining a copy
537
+ of this software and associated documentation files (the "Software"), to deal
538
+ in the Software without restriction, including without limitation the rights
539
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
540
+ copies of the Software, and to permit persons to whom the Software is
541
+ furnished to do so, subject to the following conditions:
542
+
543
+ The above copyright notice and this permission notice shall be included in all
544
+ copies or substantial portions of the Software.
545
+
546
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
547
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
548
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
549
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
550
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
551
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
552
+ SOFTWARE.
553
+ ```
554
+
555
+ ## kurbo
556
+
557
+ ```
558
+ Copyright (c) 2018 Raph Levien
559
+
560
+ Permission is hereby granted, free of charge, to any
561
+ person obtaining a copy of this software and associated
562
+ documentation files (the "Software"), to deal in the
563
+ Software without restriction, including without
564
+ limitation the rights to use, copy, modify, merge,
565
+ publish, distribute, sublicense, and/or sell copies of
566
+ the Software, and to permit persons to whom the Software
567
+ is furnished to do so, subject to the following
568
+ conditions:
569
+
570
+ The above copyright notice and this permission notice
571
+ shall be included in all copies or substantial portions
572
+ of the Software.
573
+
574
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
575
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
576
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
577
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
578
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
579
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
580
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
581
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
582
+ DEALINGS IN THE SOFTWARE.
583
+ ```
584
+
526
585
  ## tiny-skia
527
586
 
528
587
  ```
@@ -21,6 +21,8 @@ export interface WebPAnimationEncoderOptions extends AnimationEncoderOptions {
21
21
  effort?: number;
22
22
  /** Lossy frames: libwebp's sharp YUV conversion, see {@link WebPEncodeOptions.sharpYuv}. Default: `false` */
23
23
  sharpYuv?: boolean;
24
+ /** Lossy frames: the alpha planes' quality (0-100), see {@link WebPEncodeOptions.alphaQuality}. Default: `100` */
25
+ alphaQuality?: number;
24
26
  }
25
27
  /** Options of {@link Animation.gifEncoder} */
26
28
  export interface GIFAnimationEncoderOptions extends AnimationEncoderOptions {
@@ -66,27 +66,21 @@ export class AnimationEncoder {
66
66
  this.optimizer = null;
67
67
  return this.format.file(optimizer);
68
68
  }
69
- static __webp__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false }) {
69
+ static __webp__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }) {
70
70
  canvas(width, height, loopCount);
71
71
  if (width > 1 << 24 || height > 1 << 24)
72
72
  throw new RangeError('WebP: canvas too large');
73
- if (quality !== undefined) {
74
- const q = finite(quality, 'quality');
75
- if (q < 0 || q > 100)
76
- throw new RangeError(`quality must be 0-100, not ${q}`);
77
- if (!Number.isInteger(effort) || effort < 0 || effort > 6)
78
- throw new RangeError(`effort must be an integer 0-6, not ${effort}`);
79
- }
73
+ const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
80
74
  const resolved = resolveMetadata(metadata), chunks = [];
81
75
  let alpha = false;
82
76
  const compositor = optimize ? null : new Compositor(width, height);
83
77
  let full = false;
84
- const add = (f) => {
78
+ const add = async (f) => {
85
79
  alpha ||= webp.needsAlpha(f, !chunks.length, width, height);
86
- chunks.push(webp.frameChunk(f, quality, effort, sharpYuv));
80
+ chunks.push(await webp.frameChunk(f, lossy));
87
81
  };
88
82
  return new AnimationEncoder(width, height, {
89
- optimize: { replace: true, even: true, alpha: 'frame', tolerance: quality === undefined ? undefined : webp.lossyTolerance(quality) },
83
+ optimize: { replace: true, even: true, alpha: 'frame', tolerance: lossy ? webp.lossyTolerance(lossy.quality) : undefined },
90
84
  async frame(f, optimized) {
91
85
  if (optimized)
92
86
  return add(f);
@@ -95,7 +89,7 @@ export class AnimationEncoder {
95
89
  full ||= input.dispose === 2 || (input.dispose === 1 && !!(input.x & 1 || input.y & 1));
96
90
  if (full)
97
91
  return add({ x: 0, y: 0, width, height, duration: input.duration, dispose: true, blend: false, pixels: shown });
98
- add(webpFrame(input));
92
+ await add(webpFrame(input));
99
93
  },
100
94
  file: () => webp.animationFile(chunks, width, height, toPlays(loopCount), alpha, exifData(resolved))
101
95
  }, optimize);
@@ -18,6 +18,10 @@ export interface AnimationDecodeOptions {
18
18
  * bombs) can't exhaust the memory. Default: `268402689` (16383², like sharp), `Infinity` for no limit
19
19
  */
20
20
  maxPixels?: number;
21
+ /** Whether to convert the colors of frames with an embedded ICC profile (APNGs, WebPs) to sRGB, like `applyColorProfile` of {@link Image.decode}. Default: `true` */
22
+ applyColorProfile?: boolean;
23
+ /** At most this many worker threads decode in parallel, like `threads` of {@link Image.decode}. Default: the processors available, at most 8 */
24
+ threads?: number;
21
25
  }
22
26
  /** The options all animation encoders have */
23
27
  export interface AnimationEncodeOptions {
@@ -42,6 +46,8 @@ export interface WebPAnimationEncodeOptions extends AnimationEncodeOptions {
42
46
  effort?: number;
43
47
  /** Lossy frames: libwebp's sharp YUV conversion, see {@link WebPEncodeOptions.sharpYuv}. Default: `false` */
44
48
  sharpYuv?: boolean;
49
+ /** Lossy frames: the alpha planes' quality (0-100), see {@link WebPEncodeOptions.alphaQuality}. Default: `100` */
50
+ alphaQuality?: number;
45
51
  }
46
52
  /** Options of {@link Animation.encodeGIF} */
47
53
  export interface GIFEncodeOptions extends AnimationEncodeOptions {
@@ -145,7 +151,7 @@ export declare class Animation extends Array<Frame> {
145
151
  * shows the same animation, but doesn't necessarily decode to the same frames
146
152
  * @param options See {@link WebPAnimationEncodeOptions}
147
153
  */
148
- encodeWebP({ metadata, optimize, quality, effort, sharpYuv }?: WebPAnimationEncodeOptions): Promise<Uint8Array>;
154
+ encodeWebP({ metadata, optimize, quality, effort, sharpYuv, alphaQuality }?: WebPAnimationEncodeOptions): Promise<Uint8Array>;
149
155
  /**
150
156
  * An encoder that makes an animated WebP a frame at a time, like {@link Animation.encodeWebP} (the same file),
151
157
  * without keeping the frames in memory: `await encoder.add(frame)` for each frame (a {@link Frame}, or an image
package/dist/animation.js CHANGED
@@ -1,7 +1,9 @@
1
+ import { profileTransform } from "./util/icc.js";
1
2
  import * as gifCodec from "./codecs/gif.js";
2
3
  import * as png from "./codecs/png.js";
3
4
  import * as webp from "./codecs/webp.js";
4
5
  import * as jxl from "./codecs/jxl.js";
6
+ import { availableThreads } from "./util/threads.js";
5
7
  import { view } from "./util/mem.js";
6
8
  import { Image } from "./image.js";
7
9
  import { Frame } from "./frame.js";
@@ -125,20 +127,14 @@ export class Animation extends Array {
125
127
  : this.__apngFrames__().map(({ blend: _, ...f }) => f);
126
128
  return png.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), compression, pngText(resolveMetadata(metadata)));
127
129
  }
128
- async encodeWebP({ metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false } = {}) {
130
+ async encodeWebP({ metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 } = {}) {
129
131
  this.__validate__();
130
132
  if (!this.length)
131
133
  throw new Error('An animation needs at least one frame');
132
- if (quality !== undefined) {
133
- const q = finite(quality, 'quality');
134
- if (q < 0 || q > 100)
135
- throw new RangeError(`quality must be 0-100, not ${q}`);
136
- if (!Number.isInteger(effort) || effort < 0 || effort > 6)
137
- throw new RangeError(`effort must be an integer 0-6, not ${effort}`);
138
- }
139
- const tolerance = quality === undefined ? undefined : webp.lossyTolerance(quality);
134
+ const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
135
+ const tolerance = lossy ? webp.lossyTolerance(lossy.quality) : undefined;
140
136
  const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame', tolerance }) : this.__webpFrames__();
141
- return webp.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), exifData(resolveMetadata(metadata)), quality, effort, sharpYuv);
137
+ return webp.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), exifData(resolveMetadata(metadata)), lossy);
142
138
  }
143
139
  __webpFrames__() {
144
140
  const width = this.width, height = this.height;
@@ -192,29 +188,38 @@ export class Animation extends Array {
192
188
  return decoding(() => Animation.__decode__(input, onlyFirstFrameOrOptions));
193
189
  }
194
190
  static async __decode__(input, onlyFirstFrameOrOptions) {
195
- const { onlyFirstFrame: onlyExtractFirstFrame = false, maxPixels = MAX_PIXELS } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions };
191
+ const { onlyFirstFrame: onlyExtractFirstFrame = false, maxPixels = MAX_PIXELS, applyColorProfile = true, threads = Math.max(1, Math.min(availableThreads(), 8)) } = isOptions(onlyFirstFrameOrOptions) ? onlyFirstFrameOrOptions : { onlyFirstFrame: onlyFirstFrameOrOptions };
192
+ if (!Number.isInteger(threads) || threads < 1)
193
+ throw new RangeError(`threads must be a positive integer, not ${threads}`);
194
+ const profile = (frames, icc) => {
195
+ const transform = applyColorProfile && icc ? profileTransform(icc) : null;
196
+ if (transform)
197
+ for (const frame of frames)
198
+ transform(frame.bitmap);
199
+ return frames;
200
+ };
196
201
  const data = view(input);
197
202
  const type = ImageType.getType(data);
198
203
  if (type === 'gif')
199
204
  return Animation.__fromGIF__(data, onlyExtractFirstFrame, Animation, maxPixels);
200
205
  if (type === 'webp') {
201
206
  const decoded = webp.decodeAnimation(data, onlyExtractFirstFrame, maxPixels);
202
- const frames = canvasFrames(decoded.width, decoded.height, webp.composite(decoded));
207
+ const frames = profile(canvasFrames(decoded.width, decoded.height, webp.composite(decoded)), decoded.icc);
203
208
  return new Animation(frames, fromPlays(decoded.loopCount));
204
209
  }
205
210
  if (type === 'png' && !png.isAnimated(data)) {
206
- const image = await Image.decode(data, { maxPixels, applyOrientation: false });
211
+ const image = await Image.decode(data, { maxPixels, applyOrientation: false, applyColorProfile });
207
212
  return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 0 }]), -1);
208
213
  }
209
214
  if (type === 'png') {
210
215
  const decoded = await png.decodeAnimation(data, onlyExtractFirstFrame, maxPixels);
211
- const frames = canvasFrames(decoded.width, decoded.height, png.compositeAnimation(decoded));
216
+ const frames = profile(canvasFrames(decoded.width, decoded.height, png.compositeAnimation(decoded)), decoded.icc);
212
217
  return new Animation(frames, decoded.frames.length > 1 ? fromPlays(decoded.plays) : -1);
213
218
  }
214
219
  if (type === 'jxl') {
215
220
  const frames = [];
216
221
  let loopCount = -1;
217
- for (const decoded of jxl.frames(data, maxPixels)) {
222
+ for await (const decoded of jxl.frames(data, maxPixels, 'reinhard', threads)) {
218
223
  const frame = new Frame(decoded.width, decoded.height, decoded.duration, 0, 0, Frame.DISPOSAL_BACKGROUND);
219
224
  frame.bitmap = decoded.pixels;
220
225
  frames.push(frame.__orient__(decoded.orientation));
@@ -225,7 +230,7 @@ export class Animation extends Array {
225
230
  return new Animation(frames, frames.length > 1 ? loopCount : -1);
226
231
  }
227
232
  if (type)
228
- return new Animation([Frame.from(await Image.decode(data, { maxPixels }), 0)]);
233
+ return new Animation([Frame.from(await Image.decode(data, { maxPixels, applyColorProfile }), 0)]);
229
234
  throw new Error('Unsupported image type');
230
235
  }
231
236
  static __fromGIF__(data, onlyExtractFirstFrame, Class, maxPixels = MAX_PIXELS) {
@@ -79,7 +79,11 @@ class TileEncoder {
79
79
  pairCounts = new Uint32Array(65536);
80
80
  bits = 0;
81
81
  coded = false;
82
- constructor(f, src, params) {
82
+ static aboveBytes(f) {
83
+ const n = f.b4Stride + 32;
84
+ return 10 * n + (n >> 1) + 1 + 48 * n;
85
+ }
86
+ constructor(f, src, params, above) {
83
87
  this.f = f;
84
88
  this.src = src;
85
89
  this.params = params;
@@ -87,17 +91,19 @@ class TileEncoder {
87
91
  this.hdr = f.hdr;
88
92
  this.ssx = f.ssx;
89
93
  this.ssy = f.ssy;
90
- const n = f.b4Stride + 32;
91
- this.aMode = new Uint8Array(n);
92
- this.aLcoef = new Uint8Array(n);
93
- this.aCcoef = [new Uint8Array(n), new Uint8Array(n)];
94
- this.aSkip = new Uint8Array(n);
95
- this.aUvmode = new Uint8Array(n);
96
- this.aPartition = new Uint8Array(n >> 1);
97
- this.aPalSz = new Uint8Array(n);
98
- this.aPalSzUv = new Uint8Array(n);
99
- this.aPal = new Uint16Array(n * 24);
100
- this.aTxIntra = new Int8Array(n);
94
+ const n = f.b4Stride + 32, buffer = above ?? new ArrayBuffer(TileEncoder.aboveBytes(f));
95
+ let o = 0;
96
+ const bytes = (length) => new Uint8Array(buffer, (o += length) - length, length);
97
+ this.aMode = bytes(n);
98
+ this.aLcoef = bytes(n);
99
+ this.aCcoef = [bytes(n), bytes(n)];
100
+ this.aSkip = bytes(n);
101
+ this.aUvmode = bytes(n);
102
+ this.aPartition = bytes(n >> 1);
103
+ this.aPalSz = bytes(n);
104
+ this.aPalSzUv = bytes(n);
105
+ this.aTxIntra = new Int8Array(buffer, (o += n) - n, n);
106
+ this.aPal = new Uint16Array(buffer, o + 1 & ~1, n * 24);
101
107
  this.cdefChoice = new Int8Array(f.cdefIdx.length);
102
108
  this.lossless = this.hdr.allLossless;
103
109
  const q = this.hdr.quant;
@@ -147,6 +153,29 @@ class TileEncoder {
147
153
  }
148
154
  return nodes;
149
155
  }
156
+ startTile(tileRow, tileCol) {
157
+ this.tile(tileRow, tileCol);
158
+ this.resetAbove();
159
+ return this.rowEnd - this.rowStart + 15 >> 4;
160
+ }
161
+ searchRow(tileRow, tileCol, row, progress) {
162
+ this.tile(tileRow, tileCol);
163
+ const root = edgeTree(false), nodes = [], n = this.colEnd - this.colStart + 15 >> 4;
164
+ this.by = this.rowStart + row * 16;
165
+ this.resetLeft();
166
+ for (let k = 0; k < n; k++) {
167
+ if (row) {
168
+ const need = Math.min(k + 2, n);
169
+ for (let v; (v = Atomics.load(progress, row - 1)) < need;)
170
+ Atomics.wait(progress, row - 1, v);
171
+ }
172
+ this.bx = this.colStart + k * 16;
173
+ nodes.push(this.search(BL_64X64, root).node);
174
+ Atomics.store(progress, row, k + 1);
175
+ Atomics.notify(progress, row);
176
+ }
177
+ return nodes;
178
+ }
150
179
  storeTile(tileRow, tileCol, nodes) {
151
180
  this.tile(tileRow, tileCol);
152
181
  let i = 0;
@@ -1446,7 +1475,7 @@ function level(width, height) {
1446
1475
  return 16;
1447
1476
  return 31;
1448
1477
  }
1449
- export function encodeAV1(image, params) {
1478
+ function setup(image, params, shared) {
1450
1479
  const { width, height, layout } = image;
1451
1480
  const bitsFor = (v) => Math.max(1, 32 - Math.clz32(v - 1));
1452
1481
  const seq = {
@@ -1494,22 +1523,89 @@ export function encodeAV1(image, params) {
1494
1523
  const f = new Frame(seq, hdr);
1495
1524
  const src = f.planes.map((plane, p) => {
1496
1525
  const sx = p && layout === 1 ? 1 : 0, w = width + sx >> sx, h = height + sx >> sx, stride = f.strides[p];
1497
- const pw = f.bw * 4 >> sx, ph = f.bh * 4 >> sx, out = new Uint16Array(plane.length), inp = image.planes[p];
1526
+ const pw = f.bw * 4 >> sx, ph = f.bh * 4 >> sx, inp = image.planes[p];
1527
+ const out = shared ? new Uint16Array(new SharedArrayBuffer(plane.length * 2)) : new Uint16Array(plane.length);
1498
1528
  for (let y = 0; y < ph; y++)
1499
1529
  for (let x = 0; x < pw; x++)
1500
1530
  out[y * stride + x] = inp[Math.min(y, h - 1) * w + Math.min(x, w - 1)];
1501
1531
  return out;
1502
1532
  });
1533
+ if (shared)
1534
+ f.planes = f.planes.map(plane => new Uint16Array(new SharedArrayBuffer(plane.length * 2)));
1535
+ return { seq, hdr, f, src, rows, cols };
1536
+ }
1537
+ export function encodeAV1(image, params) {
1538
+ const { seq, hdr, f, src, rows, cols } = setup(image, params, false);
1503
1539
  const encoder = new TileEncoder(f, src, params);
1504
1540
  const nodes = [];
1505
1541
  for (let r = 0; r < rows; r++)
1506
1542
  for (let c = 0; c < cols; c++)
1507
1543
  nodes.push(encoder.searchTile(r, c));
1544
+ const g = finish(encoder, seq, hdr, f, params, nodes, rows, cols), dirs = new Int32Array(f.b4Stride * (f.bh + 1)).fill(-1);
1545
+ for (let step = g.next();; step = g.next(runFilterTrials(f, src, step.value, dirs)))
1546
+ if (step.done)
1547
+ return step.value;
1548
+ }
1549
+ export function searchRows(task, post) {
1550
+ const f = new Frame(task.seq, task.hdr);
1551
+ f.planes = task.planes;
1552
+ const encoder = new TileEncoder(f, task.src, task.params, task.above.buffer);
1553
+ for (let row; (row = Atomics.add(task.counter, 0, 1)) < task.progress.length;)
1554
+ post({ row, nodes: encoder.searchRow(task.tileRow, task.tileCol, row, task.progress) });
1555
+ }
1556
+ const BLOCK_ARRAYS = ['lfLevels', 'txW', 'txH', 'uvTxW', 'uvTxH', 'skip', 'segMap', 'cdefIdx'];
1557
+ export function filterTrials(task) {
1558
+ const f = new Frame(task.seq, task.hdr);
1559
+ for (const name of BLOCK_ARRAYS)
1560
+ f[name] = task.blocks[name];
1561
+ return runFilterTrials(f, task.src, task, new Int32Array(f.b4Stride * (f.bh + 1)).fill(-1));
1562
+ }
1563
+ async function threadTrials(threads, f, src, t) {
1564
+ const planes = t.planes.map(p => {
1565
+ const s = new Uint16Array(new SharedArrayBuffer(p.length * 2));
1566
+ s.set(p);
1567
+ return s;
1568
+ });
1569
+ const blocks = {};
1570
+ for (const name of BLOCK_ARRAYS)
1571
+ blocks[name] = f[name];
1572
+ const out = new Array(t.values.length), used = threads.slice(0, t.values.length);
1573
+ await Promise.all(used.map(async (thread, k) => {
1574
+ const values = t.values.filter((_, i) => i % used.length === k);
1575
+ const errors = await thread.run({ task: 'av1-filter', kind: t.kind, values, planes, seq: f.seq, hdr: f.hdr, src, blocks });
1576
+ errors.forEach((e, j) => out[k + j * used.length] = e);
1577
+ }));
1578
+ return out;
1579
+ }
1580
+ export async function encodeAV1Threaded(image, params, threads) {
1581
+ const { seq, hdr, f, src, rows, cols } = setup(image, params, true);
1582
+ const above = new Uint8Array(new SharedArrayBuffer(TileEncoder.aboveBytes(f)));
1583
+ const encoder = new TileEncoder(f, src, params, above.buffer);
1584
+ const nodes = [];
1585
+ for (let r = 0; r < rows; r++) {
1586
+ for (let c = 0; c < cols; c++) {
1587
+ const sbRows = encoder.startTile(r, c), rowNodes = new Array(sbRows);
1588
+ const counter = new Int32Array(new SharedArrayBuffer(4)), progress = new Int32Array(new SharedArrayBuffer(4 * sbRows));
1589
+ const task = { task: 'av1-search', seq, hdr, params, planes: f.planes, src, above, counter, progress, tileRow: r, tileCol: c };
1590
+ await Promise.all(threads.map(t => t.run(task, m => {
1591
+ const { row, nodes } = m;
1592
+ rowNodes[row] = nodes;
1593
+ })));
1594
+ nodes.push(rowNodes.flat());
1595
+ }
1596
+ }
1597
+ const g = finish(encoder, seq, hdr, f, params, nodes, rows, cols);
1598
+ for (let step = g.next();; step = g.next(await threadTrials(threads, f, src, step.value)))
1599
+ if (step.done)
1600
+ return step.value;
1601
+ }
1602
+ function* finish(encoder, seq, hdr, f, params, nodes, rows, cols) {
1603
+ const { width, height } = f, qidx = hdr.quant.yac;
1508
1604
  for (let r = 0; r < rows; r++)
1509
1605
  for (let c = 0; c < cols; c++)
1510
1606
  encoder.storeTile(r, c, nodes[r * cols + c]);
1511
1607
  if (qidx)
1512
- chooseFilters(f, src, qidx, params.effort, encoder.cdefChoice);
1608
+ yield* chooseFilters(f, qidx, params.effort, encoder.cdefChoice);
1513
1609
  f.cdefIdx.fill(-1);
1514
1610
  const tiles = [];
1515
1611
  for (let r = 0; r < rows; r++)
@@ -1560,47 +1656,56 @@ function blockErrors(f, planes, src, ey, euv) {
1560
1656
  });
1561
1657
  }
1562
1658
  const sum = (a) => a.reduce((s, v) => s + v, 0);
1563
- function chooseFilters(f, src, qidx, effort, choice) {
1659
+ function setLevel(f, level) {
1660
+ f.hdr.loopFilter.levelY = [level, level];
1661
+ f.hdr.loopFilter.levelU = f.hdr.loopFilter.levelV = level;
1662
+ for (let i = 0; i < f.lfLevels.length; i += 4)
1663
+ f.lfLevels.set([level, level, level, level], i);
1664
+ }
1665
+ export function runFilterTrials(f, src, t, dirs) {
1666
+ const n = f.cdefIdx.length, planes = f.planes, coded = Int8Array.from(f.cdefIdx, i => i >= 0 ? 0 : -1);
1667
+ const out = t.values.map(value => {
1668
+ const e = [new Float64Array(n), new Float64Array(n)];
1669
+ f.planes = t.planes.map(p => p.slice());
1670
+ if (t.kind === 'deblock') {
1671
+ setLevel(f, value);
1672
+ deblock(f);
1673
+ }
1674
+ else {
1675
+ f.hdr.cdef.yStrengths = [value];
1676
+ f.hdr.cdef.uvStrengths = [value];
1677
+ f.cdefIdx.set(coded);
1678
+ if (value)
1679
+ cdef(f, t.planes, dirs);
1680
+ }
1681
+ blockErrors(f, f.planes, src, e[0], e[1]);
1682
+ return e;
1683
+ });
1684
+ f.planes = planes;
1685
+ return out;
1686
+ }
1687
+ function* chooseFilters(f, qidx, effort, choice) {
1564
1688
  const hdr = f.hdr, q = dequant(0, qidx, 1), n = f.cdefIdx.length;
1565
1689
  const recon = f.planes.map(p => p.slice());
1566
- const ey = new Float64Array(n), euv = new Float64Array(n);
1567
- const setLevel = (level) => {
1568
- hdr.loopFilter.levelY = [level, level];
1569
- hdr.loopFilter.levelU = hdr.loopFilter.levelV = level;
1570
- for (let i = 0; i < f.lfLevels.length; i += 4)
1571
- f.lfLevels.set([level, level, level, level], i);
1572
- };
1573
1690
  const guess = Math.max(0, Math.min(63, (q * 20723 + 1015158 + (1 << 17) >> 18) - 4));
1691
+ const levels = [[guess], [guess - 4, guess, guess + 4], [guess - 6, guess - 3, guess, guess + 3, guess + 6]][effort].filter(l => l >= 0 && l <= 63);
1692
+ const levelErrors = yield { kind: 'deblock', values: levels, planes: recon };
1574
1693
  let bestLevel = guess, bestError = Infinity;
1575
- for (const level of [[guess], [guess - 4, guess, guess + 4], [guess - 6, guess - 3, guess, guess + 3, guess + 6]][effort]) {
1576
- if (level < 0 || level > 63)
1577
- continue;
1578
- setLevel(level);
1579
- f.planes = recon.map(p => p.slice());
1580
- deblock(f);
1581
- blockErrors(f, f.planes, src, ey, euv);
1582
- const e = sum(ey) + sum(euv);
1694
+ levels.forEach((level, k) => {
1695
+ const e = sum(levelErrors[k][0]) + sum(levelErrors[k][1]);
1583
1696
  if (e < bestError) {
1584
1697
  bestError = e;
1585
1698
  bestLevel = level;
1586
1699
  }
1587
- }
1588
- setLevel(bestLevel);
1700
+ });
1701
+ setLevel(f, bestLevel);
1589
1702
  f.planes = recon.map(p => p.slice());
1590
1703
  deblock(f);
1591
1704
  const deblocked = f.planes;
1592
1705
  const strengths = [[0, 5, 9, 17, 33], [0, 1, 4, 5, 9, 17, 33, 61], [0, 1, 4, 5, 8, 9, 13, 17, 25, 33, 41, 61]][effort];
1593
- const errY = strengths.map(() => new Float64Array(n)), errUv = strengths.map(() => new Float64Array(n));
1594
- const coded = Array.from(f.cdefIdx, i => i >= 0), dirs = new Int32Array(f.b4Stride * (f.bh + 1)).fill(-1);
1595
- strengths.forEach((strength, k) => {
1596
- hdr.cdef.yStrengths = [strength];
1597
- hdr.cdef.uvStrengths = [strength];
1598
- f.planes = deblocked.map(p => p.slice());
1599
- f.cdefIdx.set(Int8Array.from(coded, c => c ? 0 : -1));
1600
- if (strength)
1601
- cdef(f, deblocked, dirs);
1602
- blockErrors(f, f.planes, src, errY[k], errUv[k]);
1603
- });
1706
+ const coded = Array.from(f.cdefIdx, i => i >= 0);
1707
+ const strengthErrors = yield { kind: 'cdef', values: strengths, planes: deblocked };
1708
+ const errY = strengthErrors.map(e => e[0]), errUv = strengthErrors.map(e => e[1]);
1604
1709
  const lambda = 0.08 * (q / 8) ** 2, blocks = coded.filter(c => c).length;
1605
1710
  const pairs = [];
1606
1711
  for (let y = 0; y < strengths.length; y++)