imagescript 3.13.1 → 3.14.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,10 +5,11 @@
5
5
  </picture>
6
6
  </h1>
7
7
 
8
- [![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)
9
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
+
10
11
  [![Github](https://img.shields.io/badge/Github-Repository-181717?logo=github&style=for-the-badge)](https://github.com/imagescript/ImageScript)
11
- [![NPM](https://nodei.co/npm/imagescript.png)](https://www.npmjs.com/package/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)
12
13
 
13
14
  ---
14
15
 
@@ -35,8 +36,11 @@ image.resize(256, Image.RESIZE_AUTO).roundCorners(16);
35
36
  await writeFile('output.png', await image.encode());
36
37
  ```
37
38
 
38
- Coordinates start at `(0, 0)`, the top left pixel. For a bigger example, see the
39
- [script that generates this image](https://github.com/imagescript/ImageScript/blob/master/tests/readme.js):
39
+ <p align="center">
40
+ <a href="https://try.imagescript.dev/">
41
+ <img src="https://github.com/imagescript/ImageScript/raw/master/media/playground-cta.svg" alt="Try ImageScript in the Playground" width="440">
42
+ </a>
43
+ </p>
40
44
 
41
45
  [![Example](https://github.com/imagescript/ImageScript/raw/master/tests/targets/readme.png)](https://github.com/imagescript/ImageScript/blob/master/tests/readme.js)
42
46
 
@@ -6,7 +6,7 @@ import { Frame } from "./frame.js";
6
6
  import { Optimizer, Compositor, coverCanvas, fillUnchanged } from "./util/optimize.js";
7
7
  import { compressAsync, decompressAsync } from "./codecs/zlib.js";
8
8
  import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
9
- import { finite } from "./util/options.js";
9
+ import { finite, compressionLevel } from "./util/options.js";
10
10
  const toPlays = (loopCount) => loopCount < 0 ? 0 : loopCount + 1;
11
11
  export class AnimationEncoder {
12
12
  width;
@@ -94,7 +94,8 @@ export class AnimationEncoder {
94
94
  file: () => webp.animationFile(chunks, width, height, toPlays(loopCount), alpha, exifData(resolved))
95
95
  }, optimize);
96
96
  }
97
- static __gif__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality = 95 }) {
97
+ static __gif__(width, height, { loopCount = -1, metadata = {}, optimize = true, quality: qualityOption = 95 }) {
98
+ const quality = finite(qualityOption, 'quality');
98
99
  canvas(width, height, loopCount);
99
100
  const comments = gifComments(resolveMetadata(metadata));
100
101
  let first = null, restores = false;
@@ -119,7 +120,8 @@ export class AnimationEncoder {
119
120
  }
120
121
  }, optimize);
121
122
  }
122
- static __apng__(width, height, { loopCount = -1, metadata = {}, optimize = true, compression = 4 }) {
123
+ static __apng__(width, height, { loopCount = -1, metadata = {}, optimize = true, compression: compressionOption = 4 }) {
124
+ const compression = compressionLevel(compressionOption);
123
125
  canvas(width, height, loopCount);
124
126
  const text = pngText(resolveMetadata(metadata));
125
127
  const stored = [];
package/dist/animation.js CHANGED
@@ -1,4 +1,4 @@
1
- import { profileTransform } from "./util/icc.js";
1
+ import { colorSpaceTransform, profileTransform } from "./util/icc.js";
2
2
  import * as gifCodec from "./codecs/gif.js";
3
3
  import * as png from "./codecs/png.js";
4
4
  import * as webp from "./codecs/webp.js";
@@ -10,7 +10,7 @@ import { Frame } from "./frame.js";
10
10
  import { ImageType } from "./image-type.js";
11
11
  import { optimize } from "./util/optimize.js";
12
12
  import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
13
- import { isOptions, finite } from "./util/options.js";
13
+ import { isOptions, finite, compressionLevel } from "./util/options.js";
14
14
  import { MAX_PIXELS, decoding } from "./util/limits.js";
15
15
  import { AnimationEncoder } from "./animation-encoder.js";
16
16
  const toPlays = (loopCount) => loopCount < 0 ? 0 : loopCount + 1;
@@ -32,8 +32,8 @@ export class Animation extends Array {
32
32
  for (let i = 0; i < this.length; i++)
33
33
  if (!(this[i] instanceof Frame))
34
34
  throw new TypeError(`Frame ${i} is not an instance of Frame`);
35
- if (finite(loopCount, 'loop count') < -1)
36
- throw new RangeError('Invalid loop count');
35
+ if (finite(loopCount, 'loop count') < -1 || !Number.isInteger(Number(loopCount)))
36
+ throw new RangeError(`Invalid loop count: ${loopCount}`);
37
37
  this.loopCount = loopCount;
38
38
  }
39
39
  static get [Symbol.species]() {
@@ -115,7 +115,7 @@ export class Animation extends Array {
115
115
  pixels: new Uint8Array(frame.bitmap.buffer, frame.bitmap.byteOffset, frame.bitmap.byteLength)
116
116
  }));
117
117
  const gifFrames = frames.map(({ duration, ...f }) => ({ ...f, delay: Math.round(duration / 10) }));
118
- return gifCodec.encode({ width: this.width, height: this.height, loopCount: this.loopCount, frames: gifFrames }, quality, gifComments(resolveMetadata(metadata)));
118
+ return gifCodec.encode({ width: this.width, height: this.height, loopCount: this.loopCount, frames: gifFrames }, finite(quality, 'quality'), gifComments(resolveMetadata(metadata)));
119
119
  }
120
120
  async encodeAPNG(compressionOrOptions = 4) {
121
121
  const { compression = 4, metadata = {}, optimize = true } = isOptions(compressionOrOptions) ? compressionOrOptions : { compression: compressionOrOptions };
@@ -125,7 +125,7 @@ export class Animation extends Array {
125
125
  const frames = optimize
126
126
  ? this.__optimized__({ replace: true, even: false, alpha: frames => png.alphaCost(frames.map(f => f.pixels)) }).map(f => ({ ...f, dispose: f.dispose ? 1 : 0 }))
127
127
  : this.__apngFrames__().map(({ blend: _, ...f }) => f);
128
- return png.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), compression, pngText(resolveMetadata(metadata)));
128
+ return png.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), compressionLevel(compression), pngText(resolveMetadata(metadata)));
129
129
  }
130
130
  async encodeWebP({ metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 } = {}) {
131
131
  this.__validate__();
@@ -185,14 +185,19 @@ export class Animation extends Array {
185
185
  return AnimationEncoder.__apng__(width, height, options);
186
186
  }
187
187
  static async decode(input, onlyFirstFrameOrOptions = false) {
188
+ if (isOptions(onlyFirstFrameOrOptions)) {
189
+ const { maxPixels = MAX_PIXELS, threads = 1 } = onlyFirstFrameOrOptions;
190
+ if (!Number.isInteger(threads) || threads < 1)
191
+ throw new RangeError(`threads must be a positive integer, not ${threads}`);
192
+ if (!(Number(maxPixels) > 0))
193
+ throw new RangeError(`maxPixels must be a positive number, not ${maxPixels}`);
194
+ }
188
195
  return decoding(() => Animation.__decode__(input, onlyFirstFrameOrOptions));
189
196
  }
190
197
  static async __decode__(input, onlyFirstFrameOrOptions) {
191
198
  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;
199
+ const profile = (frames, icc, space) => {
200
+ const transform = !applyColorProfile ? null : icc ? profileTransform(icc) : space ? colorSpaceTransform(space.xy, space.curve) : null;
196
201
  if (transform)
197
202
  for (const frame of frames)
198
203
  transform(frame.bitmap);
@@ -218,17 +223,18 @@ export class Animation extends Array {
218
223
  }
219
224
  if (type === 'jxl') {
220
225
  const frames = [];
221
- let loopCount = -1, icc;
226
+ let loopCount = -1, icc, space;
222
227
  for await (const decoded of jxl.frames(data, maxPixels, 'reinhard', threads)) {
223
228
  const frame = new Frame(decoded.width, decoded.height, decoded.duration, 0, 0, Frame.DISPOSAL_BACKGROUND);
224
229
  frame.bitmap = decoded.pixels;
225
230
  frames.push(frame.__orient__(decoded.orientation));
226
231
  loopCount = fromPlays(decoded.loopCount);
227
232
  icc = decoded.icc;
233
+ space = decoded.colorSpace;
228
234
  if (onlyExtractFirstFrame)
229
235
  break;
230
236
  }
231
- return new Animation(profile(frames, icc), frames.length > 1 ? loopCount : -1);
237
+ return new Animation(profile(frames, icc, space), frames.length > 1 ? loopCount : -1);
232
238
  }
233
239
  if (type)
234
240
  return new Animation([Frame.from(await Image.decode(data, { maxPixels, applyColorProfile }), 0)]);
@@ -1,8 +1,9 @@
1
1
  import { runChunks, shared, sharedOf } from "../../util/threads.js";
2
2
  import { forwardTransform } from "./transforms-enc.js";
3
- import { inverseTransform } from "./dct.js";
3
+ import { idct8, inverseTransform } from "./dct.js";
4
+ import { idct16, idct32, idct64 } from "./idct.js";
4
5
  import { defaultDequant, MATRIX_INDEX } from "./quant.js";
5
- import { SIZES, transposed } from "./vardct.js";
6
+ import { SIZES, single, transposed } from "./vardct.js";
6
7
  const DCT8 = 0, IDENTITY = 1, DCT2X2 = 2, DCT4X4 = 3, DCT16X16 = 4, DCT32X32 = 5, DCT16X8 = 6, DCT8X16 = 7;
7
8
  const DCT32X16 = 10, DCT16X32 = 11, DCT4X8 = 12, DCT8X4 = 13, DCT64X64 = 18, DCT64X32 = 19, DCT32X64 = 20;
8
9
  const AFV0 = 14, AFV1 = 15, AFV2 = 16, AFV3 = 17;
@@ -17,6 +18,22 @@ function inverseDequant(type) {
17
18
  inverses.set(type, inv = dequant(type).map(m => Float32Array.from(m, v => 1 / v)));
18
19
  return inv;
19
20
  }
21
+ function idct2(buf, w, h) {
22
+ for (let y = 0; y < h; y++)
23
+ idct(buf, y * w, 1, w);
24
+ for (let x = 0; x < w; x++)
25
+ idct(buf, x, w, h);
26
+ }
27
+ function idct(buf, o, step, n) {
28
+ if (n === 8)
29
+ idct8(buf, o, step);
30
+ else if (n === 16)
31
+ idct16(buf, o, step);
32
+ else if (n === 32)
33
+ idct32(buf, o, step);
34
+ else
35
+ idct64(buf, o, step);
36
+ }
20
37
  function estimateEntropy(type, entropyMul, x, y, cfg) {
21
38
  const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1], w = w8 * 8, h = h8 * 8, numBlocks = w8 * h8, size = w * h;
22
39
  for (let c = 0; c < 3; c++)
@@ -43,14 +60,17 @@ function estimateEntropy(type, entropyMul, x, y, cfg) {
43
60
  const src = scratch[c], ys = scratch[1], m = matrices[c], im = inverses[c], cmap = c === 2 ? 1 : 0;
44
61
  let sqrtSum = 0, nonZeros = 0;
45
62
  for (let i = 0; i < size; i++) {
46
- const v = (src[i] - ys[i] * cmap) * im[i] * quant, r = Math.round(v);
63
+ const v = (src[i] - ys[i] * cmap) * im[i] * quant, r = Math.floor(v + 0.5);
47
64
  errors[i] = m[i] * (v - r);
48
- const q = Math.abs(r);
49
- sqrtSum += Math.sqrt(q);
50
- if (q)
65
+ if (r) {
66
+ sqrtSum += Math.sqrt(Math.abs(r));
51
67
  nonZeros++;
68
+ }
52
69
  }
53
- inverseTransform({ buf: errors, offset: 0, stride: w, w, h }, type);
70
+ if (type === 0 || !single(type))
71
+ idct2(errors, w, h);
72
+ else
73
+ inverseTransform({ buf: errors, offset: 0, stride: w, w, h }, type);
54
74
  let lossc = 0;
55
75
  for (let py = 0; py < h; py++) {
56
76
  const mo = (y + py) * stride + x;
@@ -286,7 +306,7 @@ export async function chooseVarblocks(planes, stride, bw, bh, field, distance, s
286
306
  planes: threads ? planes.map(sharedOf) : planes,
287
307
  field: threads ? { quant: shared(field.quant), mask: shared(field.mask), mask1x1: sharedOf(field.mask1x1) } : field,
288
308
  };
289
- await runChunks(threads, task, Math.ceil(bh / 8), varblockChunks(task));
309
+ await runChunks(threads, task, Math.ceil(bh / 8) * Math.ceil(bw / 64), varblockChunks(task));
290
310
  return types;
291
311
  }
292
312
  export function varblockChunks({ planes, stride, bw, bh, field, distance, speed, types }) {
@@ -298,9 +318,10 @@ export function varblockChunks({ planes, stride, bw, bh, field, distance, speed,
298
318
  costDelta: 10.833273317067883 * ratio ** 0.36702940662370243
299
319
  };
300
320
  const s = new Strategy(bw, bh, types);
301
- return row => {
302
- const by = row * 8;
303
- for (let bx = 0; bx < bw; bx += 8)
321
+ const segments = Math.ceil(bw / 64);
322
+ return chunk => {
323
+ const by = Math.floor(chunk / segments) * 8, x0 = (chunk % segments) * 64;
324
+ for (let bx = x0; bx < Math.min(bw, x0 + 64); bx += 8)
304
325
  processRect(bx, by, Math.min(8, bw - bx), Math.min(8, bh - by), speed, cfg, s);
305
326
  };
306
327
  }
@@ -115,62 +115,83 @@ function perBlockModulations(distance, px, py, pb, w, bw, bh, scale, aq) {
115
115
  dampen = Math.max(0, 1 - (distance - 2) / (14 - 2));
116
116
  const mul = scale * dampen, add = (1 - dampen) * baseLevel;
117
117
  for (let by = 0; by < bh; by++) {
118
- for (let bx = 0; bx < bw; bx++) {
119
- const o = by * 8 * w + bx * 8;
120
- let v = computeMask(aq[by * bw + bx]);
121
- let hf = 0;
122
- for (let dy = 0; dy < 8; dy++) {
123
- const r = o + dy * w, next = dy === 7 ? r : r + w;
124
- for (let dx = 0; dx < 8; dx++) {
125
- const p = py[r + dx];
126
- if (dx < 7)
127
- hf += Math.min(0.0206, Math.abs(p - py[r + dx + 1]));
128
- hf += Math.min(0.0206, Math.abs(p - py[next + dx]));
129
- }
130
- }
131
- v += hf * -0.38 + 0.42;
132
- let ratio = 0;
133
- for (let dy = 0; dy < 8; dy++) {
134
- for (let dx = 0; dx < 8; dx++) {
135
- const iny = py[o + dy * w + dx] + 0.16, inx = px[o + dy * w + dx];
136
- ratio += gammaRatioInverse(iny - inx) + gammaRatioInverse(iny + inx);
137
- }
138
- }
139
- v += 0.1005613337192697 * Math.log2(ratio * (0.5 / 64));
140
- const LIMIT = 0.027121074570634722;
141
- let blue = 0;
142
- for (let dy = 0; dy < 8; dy++) {
143
- for (let dx = 0; dx < 8; dx++) {
144
- const i = o + dy * w + dx, eff = py[i] + 0.084381641171960495 + Math.abs(px[i]);
145
- if (pb[i] > eff)
146
- blue += Math.min(pb[i] - eff, LIMIT);
147
- }
148
- }
149
- if (blue >= 32 * LIMIT)
150
- blue = 64 * LIMIT - blue;
151
- if (blue >= 15.398788439047934 * LIMIT)
152
- blue = 15.398788439047934 * LIMIT;
153
- v += blue * 0.14207000358439159;
154
- aq[by * bw + bx] = Math.exp(v) * mul + add;
118
+ for (let bx = 0; bx < bw; bx++)
119
+ aq[by * bw + bx] = Math.exp(blockModulation(px, py, pb, by * 8 * w + bx * 8, w, aq[by * bw + bx])) * mul + add;
120
+ }
121
+ }
122
+ function blockModulation(px, py, pb, o, w, e) {
123
+ let v = computeMask(e);
124
+ let hf = 0;
125
+ for (let dy = 0; dy < 8; dy++) {
126
+ const r = o + dy * w, next = dy === 7 ? r : r + w;
127
+ for (let dx = 0; dx < 8; dx++) {
128
+ const p = py[r + dx];
129
+ if (dx < 7)
130
+ hf += Math.min(0.0206, Math.abs(p - py[r + dx + 1]));
131
+ hf += Math.min(0.0206, Math.abs(p - py[next + dx]));
132
+ }
133
+ }
134
+ v += hf * -0.38 + 0.42;
135
+ let ratio = 0;
136
+ for (let dy = 0; dy < 8; dy++) {
137
+ for (let dx = 0; dx < 8; dx++) {
138
+ const iny = py[o + dy * w + dx] + 0.16, inx = px[o + dy * w + dx];
139
+ ratio += gammaRatioInverse(iny - inx) + gammaRatioInverse(iny + inx);
155
140
  }
156
141
  }
142
+ v += 0.1005613337192697 * Math.log2(ratio * (0.5 / 64));
143
+ const LIMIT = 0.027121074570634722;
144
+ let blue = 0;
145
+ for (let dy = 0; dy < 8; dy++) {
146
+ for (let dx = 0; dx < 8; dx++) {
147
+ const i = o + dy * w + dx, eff = py[i] + 0.084381641171960495 + Math.abs(px[i]);
148
+ if (pb[i] > eff)
149
+ blue += Math.min(pb[i] - eff, LIMIT);
150
+ }
151
+ }
152
+ if (blue >= 32 * LIMIT)
153
+ blue = 64 * LIMIT - blue;
154
+ if (blue >= 15.398788439047934 * LIMIT)
155
+ blue = 15.398788439047934 * LIMIT;
156
+ return v + blue * 0.14207000358439159;
157
157
  }
158
158
  function symmetric5(m, w, h, [c, r, R, d, D, L], out, y0, y1) {
159
- const weights = [D, L, R, L, D, L, d, r, d, L, R, r, c, r, R, L, d, r, d, L, D, L, R, L, D];
160
159
  const mirror = (v, n) => {
161
160
  while (v < 0 || v >= n)
162
161
  v = v < 0 ? -v - 1 : 2 * n - 1 - v;
163
162
  return v;
164
163
  };
165
164
  for (let y = y0; y < y1; y++) {
166
- const rows = [-2, -1, 0, 1, 2].map(dy => mirror(y + dy, h) * w);
165
+ const r0 = mirror(y - 2, h) * w, r1 = mirror(y - 1, h) * w, r2 = y * w, r3 = mirror(y + 1, h) * w, r4 = mirror(y + 2, h) * w;
167
166
  for (let x = 0; x < w; x++) {
167
+ const inside = x >= 2 && x + 2 < w;
168
+ const c0 = inside ? x - 2 : mirror(x - 2, w), c1 = inside ? x - 1 : mirror(x - 1, w), c3 = inside ? x + 1 : mirror(x + 1, w), c4 = inside ? x + 2 : mirror(x + 2, w);
168
169
  let sum = 0;
169
- for (let dx = -2; dx <= 2; dx++) {
170
- const col = x + dx >= 0 && x + dx < w ? x + dx : mirror(x + dx, w);
171
- for (let k = 0; k < 5; k++)
172
- sum += weights[k * 5 + dx + 2] * m[rows[k] + col];
173
- }
170
+ sum += D * m[r0 + c0];
171
+ sum += L * m[r1 + c0];
172
+ sum += R * m[r2 + c0];
173
+ sum += L * m[r3 + c0];
174
+ sum += D * m[r4 + c0];
175
+ sum += L * m[r0 + c1];
176
+ sum += d * m[r1 + c1];
177
+ sum += r * m[r2 + c1];
178
+ sum += d * m[r3 + c1];
179
+ sum += L * m[r4 + c1];
180
+ sum += R * m[r0 + x];
181
+ sum += r * m[r1 + x];
182
+ sum += c * m[r2 + x];
183
+ sum += r * m[r3 + x];
184
+ sum += R * m[r4 + x];
185
+ sum += L * m[r0 + c3];
186
+ sum += d * m[r1 + c3];
187
+ sum += r * m[r2 + c3];
188
+ sum += d * m[r3 + c3];
189
+ sum += L * m[r4 + c3];
190
+ sum += D * m[r0 + c4];
191
+ sum += L * m[r1 + c4];
192
+ sum += R * m[r2 + c4];
193
+ sum += L * m[r3 + c4];
194
+ sum += D * m[r4 + c4];
174
195
  out[y * w + x] = sum;
175
196
  }
176
197
  }
@@ -82,7 +82,7 @@ export function dct(io, o, n, scratch, s, inverse) {
82
82
  }
83
83
  const work = { row: new Float64Array(256), scratch: new Float64Array(256) };
84
84
  const SEC8 = secHalf(8);
85
- function idct8(buf, o, step) {
85
+ export function idct8(buf, o, step) {
86
86
  const v0 = buf[o], v1 = buf[o + step], v2 = buf[o + 2 * step], v3 = buf[o + 3 * step];
87
87
  const v4 = buf[o + 4 * step], v5 = buf[o + 5 * step], v6 = buf[o + 6 * step], v7 = buf[o + 7 * step];
88
88
  let t0 = v2 * Math.SQRT2, t1 = v2 + v6;
@@ -204,7 +204,27 @@ const set = (b, x, y, v) => {
204
204
  b.buf[b.offset + y * b.stride + x] = v;
205
205
  };
206
206
  const tmp = { a: new Float32Array(64), b: new Float32Array(64) };
207
- const blockOf = (buf, offset, w, h, stride = w) => ({ buf, offset, stride, w, h });
207
+ function idct4(buf, o, step) {
208
+ const i0 = buf[o], i1 = buf[o + step], i2 = buf[o + 2 * step], i3 = buf[o + 3 * step];
209
+ const t0 = i1 * Math.SQRT2, t1 = i1 + i3, out0 = (t0 + t1) * SEC0, out1 = (t0 - t1) * SEC1;
210
+ const sum02 = i0 + i2, sub02 = i0 - i2;
211
+ buf[o] = sum02 + out0;
212
+ buf[o + step] = sub02 + out1;
213
+ buf[o + 2 * step] = sub02 - out1;
214
+ buf[o + 3 * step] = sum02 - out0;
215
+ }
216
+ function idct8x4(buf, o) {
217
+ for (let y = 0; y < 4; y++)
218
+ idct8(buf, o + y * 8, 1);
219
+ for (let x = 0; x < 8; x++)
220
+ idct4(buf, o + x, 8);
221
+ }
222
+ function idct4x4(buf, o) {
223
+ for (let y = 0; y < 4; y++)
224
+ idct4(buf, o + y * 4, 1);
225
+ for (let x = 0; x < 4; x++)
226
+ idct4(buf, o + x, 4);
227
+ }
208
228
  function idct2InPlace(b, size) {
209
229
  const half = size / 2, s = tmp.a;
210
230
  for (let y = 0; y < half; y++) {
@@ -234,7 +254,7 @@ function dct4x4(b) {
234
254
  for (let iy = 0; iy < 4; iy++)
235
255
  for (let ix = 0; ix < 4; ix++)
236
256
  s[o + ix * 4 + iy] = get(b, x + ix * 2, y + iy * 2);
237
- dct2d(blockOf(s, o, 4, 4), true);
257
+ idct4x4(s, o);
238
258
  }
239
259
  }
240
260
  for (let y = 0; y < 2; y++)
@@ -277,7 +297,7 @@ function dct4x8(b, transposed) {
277
297
  for (let iy = 0; iy < 4; iy++)
278
298
  for (let ix = 0; ix < 8; ix++)
279
299
  s[i * 32 + iy * 8 + ix] = get(b, ix, iy * 2 + i);
280
- dct2d(blockOf(s, i * 32, 8, 4), true);
300
+ idct8x4(s, i * 32);
281
301
  }
282
302
  for (let y = 0; y < 8; y++)
283
303
  for (let x = 0; x < 8; x++) {
@@ -287,28 +307,28 @@ function dct4x8(b, transposed) {
287
307
  set(b, x, y, s[y * 8 + x]);
288
308
  }
289
309
  }
310
+ const afvScratch = { coeffs: new Float64Array(16), samples: new Float64Array(16), s4: new Float32Array(16), s8: new Float32Array(32) };
290
311
  function afv(b, n) {
291
312
  const flipX = n % 2, flipY = n >> 1;
292
- const coeffs = new Float64Array(16), samples = new Float64Array(16);
313
+ const coeffs = afvScratch.coeffs, samples = afvScratch.samples.fill(0), s4 = afvScratch.s4, s8 = afvScratch.s8;
293
314
  coeffs[0] = (get(b, 0, 0) + get(b, 1, 0) + get(b, 0, 1)) * 4;
294
315
  for (let i = 1; i < 16; i++)
295
316
  coeffs[i] = get(b, 2 * (i % 4), 2 * (i >> 2));
296
317
  for (let i = 0; i < 16; i++)
297
318
  for (let k = 0; k < 16; k++)
298
319
  samples[k] += coeffs[i] * AFV_BASIS[i * 16 + k];
299
- const s4 = new Float32Array(16), s8 = new Float32Array(32);
300
320
  s4[0] = get(b, 0, 0) - get(b, 1, 0) + get(b, 0, 1);
301
321
  for (let iy = 0; iy < 4; iy++)
302
322
  for (let ix = 0; ix < 4; ix++)
303
323
  if (ix | iy)
304
324
  s4[ix * 4 + iy] = get(b, 2 * ix + 1, 2 * iy);
305
- dct2d(blockOf(s4, 0, 4, 4), true);
325
+ idct4x4(s4, 0);
306
326
  s8[0] = get(b, 0, 0) - get(b, 0, 1);
307
327
  for (let iy = 0; iy < 4; iy++)
308
328
  for (let ix = 0; ix < 8; ix++)
309
329
  if (ix | iy)
310
330
  s8[iy * 8 + ix] = get(b, ix, 2 * iy + 1);
311
- dct2d(blockOf(s8, 0, 8, 4), true);
331
+ idct8x4(s8, 0);
312
332
  for (let iy = 0; iy < 4; iy++) {
313
333
  const ay = flipY ? 3 - iy : iy;
314
334
  for (let ix = 0; ix < 4; ix++)
@@ -349,7 +369,7 @@ export function inverseTransform(b, type) {
349
369
  }
350
370
  }
351
371
  export { sub as subBlock };
352
- const AFV_BASIS = [
372
+ export const AFV_BASIS = [
353
373
  0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25,
354
374
  0.876902929799142, 0.2206518106944235, -0.10140050393753763, -0.1014005039375375, 0.2206518106944236, -0.10140050393753777, -0.10140050393753772, -0.10140050393753763, -0.10140050393753758, -0.10140050393753769, -0.1014005039375375, -0.10140050393753768, -0.10140050393753768, -0.10140050393753759, -0.10140050393753763, -0.10140050393753741,
355
375
  0.0, 0.0, 0.40670075830260755, 0.44444816619734445, 0.0, 0.0, 0.19574399372042936, 0.2929100136981264, -0.40670075830260716, -0.19574399372042872, 0.0, 0.11379074460448091, -0.44444816619734384, -0.29291001369812636, -0.1137907446044814, 0.0,
@@ -25,6 +25,11 @@ const token = (v) => {
25
25
  const n = 31 - Math.clz32(v), m = v - (1 << n);
26
26
  return SPLIT + ((n - SPLIT_EXPONENT) << (MSB + LSB)) + ((m >>> (n - MSB)) << LSB) + (m & ((1 << LSB) - 1));
27
27
  };
28
+ export const MAX_TOKEN = token(0xffffffff) + 1;
29
+ export function countTokens(counts, ctx, value, from, to) {
30
+ for (let i = from; i < to; i++)
31
+ counts[ctx[i] * MAX_TOKEN + token(value[i])]++;
32
+ }
28
33
  const ANS_LOG_TAB_SIZE = 12, ANS_TAB_SIZE = 1 << ANS_LOG_TAB_SIZE, LOG_ALPHABET_SIZE = 8;
29
34
  const floorLog2 = (v) => 31 - Math.clz32(v);
30
35
  const precision = (logcount, shift) => Math.max(0, Math.min(logcount, shift - ((ANS_LOG_TAB_SIZE - logcount) >> 1)));
@@ -224,21 +229,20 @@ export class EntropyCode {
224
229
  ans;
225
230
  constructor(streams, numContexts, { maxClusters = 64 } = {}) {
226
231
  this.numContexts = numContexts;
227
- let alphabet = 1;
228
- for (const t of streams) {
229
- for (let i = 0; i < t.length; i++) {
230
- const tk = token(t.value[i]);
231
- if (tk + 1 > alphabet)
232
- alphabet = tk + 1;
233
- }
234
- }
235
- const hist = Array.from({ length: numContexts }, () => new Float64Array(alphabet)), totals = new Float64Array(numContexts);
236
- for (const t of streams) {
237
- for (let i = 0; i < t.length; i++) {
238
- hist[t.ctx[i]][token(t.value[i])]++;
239
- totals[t.ctx[i]]++;
240
- }
232
+ let counts;
233
+ if (streams instanceof Float64Array)
234
+ counts = streams;
235
+ else {
236
+ counts = new Float64Array(numContexts * MAX_TOKEN);
237
+ for (const t of streams)
238
+ countTokens(counts, t.ctx, t.value, 0, t.length);
241
239
  }
240
+ let alphabet = 1;
241
+ for (let i = 0; i < counts.length; i++)
242
+ if (counts[i] && i % MAX_TOKEN + 1 > alphabet)
243
+ alphabet = i % MAX_TOKEN + 1;
244
+ const hist = Array.from({ length: numContexts }, (_, c) => counts.slice(c * MAX_TOKEN, c * MAX_TOKEN + alphabet));
245
+ const totals = Float64Array.from(hist, h => h.reduce((sum, v) => sum + v, 0));
242
246
  this.ctxMap = new Uint8Array(numContexts);
243
247
  const clusters = cluster(hist, totals, Math.min(maxClusters, 255, numContexts), this.ctxMap).map(h => {
244
248
  let size = h.length;
@@ -263,28 +267,33 @@ export class EntropyCode {
263
267
  c.write(w);
264
268
  }
265
269
  writeTokens(w, t) {
266
- const map = this.ctxMap;
267
- const codes = this.ans, n = t.length, chunks = new Int32Array(n);
268
- let state = 0x130000;
269
- for (let i = n - 1; i >= 0; i--) {
270
- const code = codes[map[t.ctx[i]]], tk = token(t.value[i]), freq = code.freq[tk];
271
- chunks[i] = -1;
272
- if (state >>> 20 >= freq) {
273
- chunks[i] = state & 0xffff;
274
- state >>>= 16;
275
- }
276
- const v = Math.floor(state / freq);
277
- state = v * ANS_TAB_SIZE + code.reverse[tk][state - v * freq];
270
+ writeTokens(w, this.tables(), t.ctx, t.value, 0, t.length);
271
+ }
272
+ tables() {
273
+ return { ctxMap: this.ctxMap, freq: this.ans.map(c => c.freq), reverse: this.ans.map(c => c.reverse) };
274
+ }
275
+ }
276
+ export function writeTokens(w, { ctxMap: map, freq: freqs, reverse }, ctx, value, from, to) {
277
+ const chunks = new Int32Array(to - from);
278
+ let state = 0x130000;
279
+ for (let i = to - 1; i >= from; i--) {
280
+ const c = map[ctx[i]], tk = token(value[i]), freq = freqs[c][tk];
281
+ chunks[i - from] = -1;
282
+ if (state >>> 20 >= freq) {
283
+ chunks[i - from] = state & 0xffff;
284
+ state >>>= 16;
278
285
  }
279
- w.write(32, state);
280
- for (let i = 0; i < n; i++) {
281
- if (chunks[i] >= 0)
282
- w.write(16, chunks[i]);
283
- const v = t.value[i];
284
- if (v >= SPLIT) {
285
- const nbits = 31 - Math.clz32(v) - MSB - LSB;
286
- w.write(nbits, (v >>> LSB) & ((1 << nbits) - 1));
287
- }
286
+ const v = Math.floor(state / freq);
287
+ state = v * ANS_TAB_SIZE + reverse[c][tk][state - v * freq];
288
+ }
289
+ w.write(32, state);
290
+ for (let i = from; i < to; i++) {
291
+ if (chunks[i - from] >= 0)
292
+ w.write(16, chunks[i - from]);
293
+ const v = value[i];
294
+ if (v >= SPLIT) {
295
+ const nbits = 31 - Math.clz32(v) - MSB - LSB;
296
+ w.write(nbits, (v >>> LSB) & ((1 << nbits) - 1));
288
297
  }
289
298
  }
290
299
  }
@@ -673,7 +673,7 @@ export function encode(px, width, height, numChans, chunkSize = 16) {
673
673
  }
674
674
  return w.bytes().slice();
675
675
  }
676
- function frameHeader(w, alpha) {
676
+ export function frameHeader(w, alpha) {
677
677
  w.write(1, 0);
678
678
  w.write(2, 0b00);
679
679
  w.write(1, 1);