imagescript 3.13.2 → 3.15.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
@@ -23,6 +23,19 @@ npm install imagescript # Node.js, Bun and bundlers
23
23
  deno add jsr:@matmen/imagescript # Deno
24
24
  ```
25
25
 
26
+ Without a bundler, import it from jsDelivr in the browser:
27
+
28
+ ```html
29
+ <script type="module">
30
+ import { Image } from 'https://cdn.jsdelivr.net/npm/imagescript@3/+esm';
31
+
32
+ const image = await Image.decode(await fetch('photo.jpg').then(r => r.arrayBuffer()));
33
+ image.resize(256, Image.RESIZE_AUTO);
34
+ const url = URL.createObjectURL(new Blob([await image.encode()], { type: 'image/png' }));
35
+ document.body.append(Object.assign(document.createElement('img'), { src: url }));
36
+ </script>
37
+ ```
38
+
26
39
  ---
27
40
 
28
41
  ### Example
@@ -17,7 +17,7 @@ export interface AnimationEncoderOptions {
17
17
  export interface WebPAnimationEncoderOptions extends AnimationEncoderOptions {
18
18
  /** Lossy frames (0-100), see {@link WebPAnimationEncodeOptions.quality}. Without it the frames are lossless */
19
19
  quality?: number;
20
- /** How much effort lossy frames take (0-6), see {@link WebPEncodeOptions.effort}. Default: `2` */
20
+ /** How much effort the frames take (0-6, lossy and lossless), see {@link WebPEncodeOptions.effort}. Default: `2` */
21
21
  effort?: number;
22
22
  /** Lossy frames: libwebp's sharp YUV conversion, see {@link WebPEncodeOptions.sharpYuv}. Default: `false` */
23
23
  sharpYuv?: boolean;
@@ -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;
@@ -77,7 +77,7 @@ export class AnimationEncoder {
77
77
  let full = false;
78
78
  const add = async (f) => {
79
79
  alpha ||= webp.needsAlpha(f, !chunks.length, width, height);
80
- chunks.push(await webp.frameChunk(f, lossy));
80
+ chunks.push(await webp.frameChunk(f, lossy, effort));
81
81
  };
82
82
  return new AnimationEncoder(width, height, {
83
83
  optimize: { replace: true, even: true, alpha: 'frame', tolerance: lossy ? webp.lossyTolerance(lossy.quality) : undefined },
@@ -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 = [];
@@ -42,7 +42,7 @@ export interface WebPAnimationEncodeOptions extends AnimationEncodeOptions {
42
42
  * up to 3 per channel at quality 85, 1 at 100)
43
43
  */
44
44
  quality?: number;
45
- /** How much effort lossy frames take (0-6), see {@link WebPEncodeOptions.effort}. Default: `2` */
45
+ /** How much effort the frames take (0-6, lossy and lossless), see {@link WebPEncodeOptions.effort}. Default: `2` */
46
46
  effort?: number;
47
47
  /** Lossy frames: libwebp's sharp YUV conversion, see {@link WebPEncodeOptions.sharpYuv}. Default: `false` */
48
48
  sharpYuv?: boolean;
package/dist/animation.js CHANGED
@@ -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__();
@@ -134,7 +134,7 @@ export class Animation extends Array {
134
134
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
135
135
  const tolerance = lossy ? webp.lossyTolerance(lossy.quality) : undefined;
136
136
  const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame', tolerance }) : this.__webpFrames__();
137
- return webp.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), exifData(resolveMetadata(metadata)), lossy);
137
+ return webp.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), exifData(resolveMetadata(metadata)), lossy, effort);
138
138
  }
139
139
  __webpFrames__() {
140
140
  const width = this.width, height = this.height;
@@ -185,12 +185,17 @@ 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
199
  const profile = (frames, icc, space) => {
195
200
  const transform = !applyColorProfile ? null : icc ? profileTransform(icc) : space ? colorSpaceTransform(space.xy, space.curve) : null;
196
201
  if (transform)
@@ -187,7 +187,9 @@ function createFrame(progressive, height, width, componentData) {
187
187
  blocksPerColumn: Math.ceil(componentHeight / 8),
188
188
  blocksPerLineForMcu,
189
189
  blocksPerColumnForMcu,
190
- coefficients: new Int16Array(blocksPerLineForMcu * blocksPerColumnForMcu * 64),
190
+ coefficients: new Int16Array(blocksPerLineForMcu * (progressive ? blocksPerColumnForMcu : c.v) * 64),
191
+ plane: progressive ? undefined : new Uint8Array(blocksPerLineForMcu * 8 * blocksPerColumnForMcu * 8),
192
+ done: progressive ? undefined : new Uint8Array(blocksPerColumnForMcu),
191
193
  pred: 0
192
194
  };
193
195
  });
@@ -374,6 +376,15 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
374
376
  ? components[0].blocksPerLine * components[0].blocksPerColumn
375
377
  : frame.mcusPerLine * frame.mcusPerColumn;
376
378
  const interval = restartInterval || total;
379
+ const sequential = !frame.progressive;
380
+ let pending = -1;
381
+ const finish = () => {
382
+ if (pending < 0)
383
+ return;
384
+ for (const component of components)
385
+ render(component, single ? pending : pending * component.v, single ? 1 : component.v);
386
+ pending = -1;
387
+ };
377
388
  for (const component of components)
378
389
  component.pred = 0;
379
390
  for (let unit = 0; unit < total;) {
@@ -382,18 +393,29 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
382
393
  const component = components[0];
383
394
  const row = unit / component.blocksPerLine | 0;
384
395
  const column = unit % component.blocksPerLine;
385
- decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
396
+ if (sequential) {
397
+ pending = row;
398
+ decodeBlock(component, column * 64);
399
+ if (column === component.blocksPerLine - 1)
400
+ finish();
401
+ }
402
+ else
403
+ decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
386
404
  }
387
405
  else {
388
406
  const mcuRow = unit / frame.mcusPerLine | 0;
389
407
  const mcuColumn = unit % frame.mcusPerLine;
408
+ if (sequential)
409
+ pending = mcuRow;
390
410
  for (const component of components)
391
411
  for (let v = 0; v < component.v; v++)
392
412
  for (let h = 0; h < component.h; h++) {
393
- const row = mcuRow * component.v + v;
413
+ const row = sequential ? v : mcuRow * component.v + v;
394
414
  const column = mcuColumn * component.h + h;
395
415
  decodeBlock(component, (row * component.blocksPerLineForMcu + column) * 64);
396
416
  }
417
+ if (sequential && mcuColumn === frame.mcusPerLine - 1)
418
+ finish();
397
419
  }
398
420
  }
399
421
  if (unit >= total)
@@ -401,19 +423,40 @@ function decodeScan(data, offset, frame, components, restartInterval, ss, se, ah
401
423
  bits = 0;
402
424
  buffer = 0;
403
425
  while (pos + 1 < data.length && !(data[pos] === 0xff && data[pos + 1] >= 0xd0 && data[pos + 1] <= 0xd7)) {
404
- if (data[pos] === 0xff && data[pos + 1] !== 0x00 && data[pos + 1] !== 0xff)
426
+ if (data[pos] === 0xff && data[pos + 1] !== 0x00 && data[pos + 1] !== 0xff) {
427
+ finish();
405
428
  return pos;
429
+ }
406
430
  pos++;
407
431
  }
408
- if (pos + 1 >= data.length)
432
+ if (pos + 1 >= data.length) {
433
+ finish();
409
434
  return pos;
435
+ }
410
436
  pos += 2;
411
437
  eobrun = 0;
412
438
  for (const component of components)
413
439
  component.pred = 0;
414
440
  }
441
+ finish();
415
442
  return pos;
416
443
  }
444
+ function render(component, row, count) {
445
+ const { plane, done, coefficients, blocksPerLineForMcu: line } = component;
446
+ if (!plane || !done)
447
+ return;
448
+ const stride = line * 8, workspace = new Int32Array(64);
449
+ const quantization = component.quantization || new Int32Array(64);
450
+ for (let r = 0; r < count; r++) {
451
+ const blockRow = row + r;
452
+ if (blockRow < component.blocksPerColumn) {
453
+ for (let column = 0; column < component.blocksPerLine; column++)
454
+ idct(coefficients, (r * line + column) * 64, quantization, workspace, plane, blockRow * 8 * stride + column * 8, stride);
455
+ done[blockRow] = 1;
456
+ }
457
+ }
458
+ coefficients.fill(0, 0, count * line * 64);
459
+ }
417
460
  const CONST_BITS = 13;
418
461
  const PASS1_BITS = 2;
419
462
  const FIX_0_298631336 = 2446;
@@ -527,6 +570,14 @@ function idct(coefficients, offset, quantization, workspace, out, outOffset, str
527
570
  }
528
571
  function buildPlane(component) {
529
572
  const stride = component.blocksPerLineForMcu * 8;
573
+ if (component.plane && component.done) {
574
+ const { plane, done } = component;
575
+ for (let row = 0; row < component.blocksPerColumn; row++)
576
+ if (!done[row])
577
+ for (let y = row * 8; y < row * 8 + 8; y++)
578
+ plane.fill(128, y * stride, y * stride + component.blocksPerLine * 8);
579
+ return { plane, stride };
580
+ }
530
581
  const plane = new Uint8Array(stride * component.blocksPerColumnForMcu * 8);
531
582
  const workspace = new Int32Array(64);
532
583
  const quantization = component.quantization || new Int32Array(64);
@@ -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,