imagescript 3.6.0 → 3.8.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.
Files changed (45) hide show
  1. package/README.md +46 -97
  2. package/THIRD_PARTY_NOTICES.md +104 -3
  3. package/dist/animation-encoder.d.ts +62 -0
  4. package/dist/animation-encoder.js +204 -0
  5. package/dist/animation.d.ts +32 -2
  6. package/dist/animation.js +14 -3
  7. package/dist/codecs/av1/encode.js +47 -23
  8. package/dist/codecs/gif.js +37 -24
  9. package/dist/codecs/jxl/acs-enc.js +294 -0
  10. package/dist/codecs/jxl/aq-enc.js +176 -0
  11. package/dist/codecs/jxl/bit-writer.js +46 -0
  12. package/dist/codecs/jxl/color.js +61 -1
  13. package/dist/codecs/jxl/dct.js +7 -7
  14. package/dist/codecs/jxl/entropy-enc.js +589 -0
  15. package/dist/codecs/jxl/entropy.js +1 -1
  16. package/dist/codecs/jxl/fast-lossless.js +2 -107
  17. package/dist/codecs/jxl/fdct.js +1114 -0
  18. package/dist/codecs/jxl/filters.js +49 -2
  19. package/dist/codecs/jxl/frame.js +4 -1
  20. package/dist/codecs/jxl/headers-enc.js +60 -0
  21. package/dist/codecs/jxl/idct.js +804 -2
  22. package/dist/codecs/jxl/modular-enc.js +100 -0
  23. package/dist/codecs/jxl/modular.js +3 -2
  24. package/dist/codecs/jxl/quant.js +1 -0
  25. package/dist/codecs/jxl/transforms-enc.js +188 -0
  26. package/dist/codecs/jxl/vardct-enc.js +397 -0
  27. package/dist/codecs/jxl/vardct.js +6 -6
  28. package/dist/codecs/jxl.js +3 -2
  29. package/dist/codecs/png.js +77 -37
  30. package/dist/codecs/sharpyuv.js +150 -0
  31. package/dist/codecs/vp8-enc-dsp.js +9 -1
  32. package/dist/codecs/vp8l.js +357 -59
  33. package/dist/codecs/webp.js +36 -26
  34. package/dist/codecs/zlib.js +20 -0
  35. package/dist/image.d.ts +50 -10
  36. package/dist/image.js +65 -17
  37. package/dist/index.d.ts +3 -1
  38. package/dist/index.js +1 -0
  39. package/dist/render/filter.js +939 -0
  40. package/dist/render/shape.js +12 -6
  41. package/dist/render/svg.js +1140 -36
  42. package/dist/render/text.js +9 -9
  43. package/dist/util/optimize.js +208 -62
  44. package/dist/version.js +1 -1
  45. package/package.json +1 -1
package/dist/animation.js CHANGED
@@ -10,6 +10,7 @@ import { optimize } from "./util/optimize.js";
10
10
  import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
11
11
  import { isOptions, finite } from "./util/options.js";
12
12
  import { MAX_PIXELS, decoding } from "./util/limits.js";
13
+ import { AnimationEncoder } from "./animation-encoder.js";
13
14
  const toPlays = (loopCount) => loopCount < 0 ? 0 : loopCount + 1;
14
15
  const fromPlays = (plays) => plays === 0 ? -1 : plays - 1;
15
16
  function canvasFrames(width, height, frames) {
@@ -124,7 +125,7 @@ export class Animation extends Array {
124
125
  : this.__apngFrames__().map(({ blend: _, ...f }) => f);
125
126
  return png.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), compression, pngText(resolveMetadata(metadata)));
126
127
  }
127
- async encodeWebP({ metadata = {}, optimize = true, quality, effort = 2 } = {}) {
128
+ async encodeWebP({ metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false } = {}) {
128
129
  this.__validate__();
129
130
  if (!this.length)
130
131
  throw new Error('An animation needs at least one frame');
@@ -135,8 +136,9 @@ export class Animation extends Array {
135
136
  if (!Number.isInteger(effort) || effort < 0 || effort > 6)
136
137
  throw new RangeError(`effort must be an integer 0-6, not ${effort}`);
137
138
  }
138
- const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame' }) : this.__webpFrames__();
139
- return webp.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), exifData(resolveMetadata(metadata)), quality, effort);
139
+ const tolerance = quality === undefined ? undefined : webp.lossyTolerance(quality);
140
+ 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);
140
142
  }
141
143
  __webpFrames__() {
142
144
  const width = this.width, height = this.height;
@@ -177,6 +179,15 @@ export class Animation extends Array {
177
179
  pixels: new Uint8Array(frame.bitmap.buffer, frame.bitmap.byteOffset, frame.bitmap.byteLength)
178
180
  }));
179
181
  }
182
+ static webpEncoder(width, height, options = {}) {
183
+ return AnimationEncoder.__webp__(width, height, options);
184
+ }
185
+ static gifEncoder(width, height, options = {}) {
186
+ return AnimationEncoder.__gif__(width, height, options);
187
+ }
188
+ static apngEncoder(width, height, options = {}) {
189
+ return AnimationEncoder.__apng__(width, height, options);
190
+ }
180
191
  static async decode(input, onlyFirstFrameOrOptions = false) {
181
192
  return decoding(() => Animation.__decode__(input, onlyFirstFrameOrOptions));
182
193
  }
@@ -17,7 +17,6 @@ const isDirectional = (mode) => mode >= VERT_PRED && mode <= VERT_LEFT_PRED;
17
17
  const smFlag = (mode) => mode === SMOOTH_PRED || mode === SMOOTH_H_PRED || mode === SMOOTH_V_PRED ? ANGLE_SMOOTH_EDGE : 0;
18
18
  const ZERO_BITS = 0.6;
19
19
  const coefBits = (q) => q === 0 ? ZERO_BITS : q === 1 ? 2.2 : q === 2 ? 3.4 : q < 15 ? 4.6 + Math.log2(q - 2) : 9 + 2 * Math.log2(q - 14);
20
- const SATD_BLOCK = new Int32Array(16);
21
20
  const mostlyFew = (counts, n) => {
22
21
  if (counts.length <= 8)
23
22
  return true;
@@ -258,7 +257,7 @@ class TileEncoder {
258
257
  }
259
258
  else {
260
259
  const none = this.searchBlock(bs, node.o);
261
- if (none.b.skip && this.params.effort < 2)
260
+ if ((none.b.skip || none.bits < 30) && this.params.effort < 2)
262
261
  return { node: { bp: PARTITION_NONE, b: none.b, kids: [] }, cost: none.cost + this.lambda };
263
262
  const noneArea = this.saveArea(bl);
264
263
  this.restoreArea(bl, saved);
@@ -419,9 +418,17 @@ class TileEncoder {
419
418
  }
420
419
  if (tdim(b.tx, MAX) <= TX_16X16 && this.params.effort && coded && !this.lossless) {
421
420
  let keptTx = this.savePlane(0, bs), bestTxCost = best + lambda;
421
+ const single = tdim(b.tx, W) >= Math.min(bdim(bs, 0), this.f.bw - this.bx) && tdim(b.tx, H) >= Math.min(bdim(bs, 1), this.f.bh - this.by);
422
+ let prediction = null;
423
+ if (single) {
424
+ this.codeLuma(bs, edgeFlags, b, true);
425
+ prediction = this.savePlane(0, bs);
426
+ }
422
427
  for (const txtp of [ADST_ADST, ADST_DCT, DCT_ADST, IDTX]) {
423
428
  b.txtp = txtp;
424
- const d = this.codeLuma(bs, edgeFlags, b);
429
+ if (prediction)
430
+ this.restorePlane(0, bs, prediction);
431
+ const d = this.codeLuma(bs, edgeFlags, b, false, prediction !== null);
425
432
  const cost = d + lambda * (this.bits + 2.5 + (b.yMode === DC_PRED ? 2 : 4.5));
426
433
  if (cost < bestTxCost) {
427
434
  bestTxCost = cost;
@@ -514,7 +521,7 @@ class TileEncoder {
514
521
  }
515
522
  b.skip = coded ? 0 : 1;
516
523
  this.modeContexts(bs, b);
517
- return { b, cost: dist + lambda * (bits + 1 + 3) };
524
+ return { b, cost: dist + lambda * (bits + 1 + 3), bits };
518
525
  }
519
526
  paletteLuma(bs, edgeFlags, b, cost) {
520
527
  const f = this.f, stride = f.strides[0], src = this.src[0];
@@ -696,26 +703,43 @@ class TileEncoder {
696
703
  satd(p, bs) {
697
704
  const f = this.f, sx = p ? this.ssx : 0, sy = p ? this.ssy : 0, stride = f.strides[p];
698
705
  const w = bdim(bs, 0) * 4 >> sx, h = bdim(bs, 1) * 4 >> sy, x0 = this.bx * 4 >> sx, y0 = this.by * 4 >> sy;
699
- const pred = f.planes[p], src = this.src[p], d = SATD_BLOCK;
706
+ const pred = f.planes[p], src = this.src[p];
700
707
  let sum = 0;
701
708
  for (let by = 0; by < h; by += 4) {
702
709
  for (let bx = 0; bx < w; bx += 4) {
703
- for (let y = 0; y < 4; y++) {
704
- const o = (y0 + by + y) * stride + x0 + bx;
705
- for (let x = 0; x < 4; x++)
706
- d[y * 4 + x] = src[o + x] - pred[o + x];
707
- }
708
- for (let y = 0; y < 4; y++) {
709
- const a = d[y * 4] + d[y * 4 + 1], b = d[y * 4] - d[y * 4 + 1], c = d[y * 4 + 2] + d[y * 4 + 3], e = d[y * 4 + 2] - d[y * 4 + 3];
710
- d[y * 4] = a + c;
711
- d[y * 4 + 1] = b + e;
712
- d[y * 4 + 2] = a - c;
713
- d[y * 4 + 3] = b - e;
714
- }
715
- for (let x = 0; x < 4; x++) {
716
- const a = d[x] + d[4 + x], b = d[x] - d[4 + x], c = d[8 + x] + d[12 + x], e = d[8 + x] - d[12 + x];
717
- sum += Math.abs(a + c) + Math.abs(b + e) + Math.abs(a - c) + Math.abs(b - e);
718
- }
710
+ let o = (y0 + by) * stride + x0 + bx;
711
+ const d00 = src[o] - pred[o], d01 = src[o + 1] - pred[o + 1], d02 = src[o + 2] - pred[o + 2], d03 = src[o + 3] - pred[o + 3];
712
+ o += stride;
713
+ const d10 = src[o] - pred[o], d11 = src[o + 1] - pred[o + 1], d12 = src[o + 2] - pred[o + 2], d13 = src[o + 3] - pred[o + 3];
714
+ o += stride;
715
+ const d20 = src[o] - pred[o], d21 = src[o + 1] - pred[o + 1], d22 = src[o + 2] - pred[o + 2], d23 = src[o + 3] - pred[o + 3];
716
+ o += stride;
717
+ const d30 = src[o] - pred[o], d31 = src[o + 1] - pred[o + 1], d32 = src[o + 2] - pred[o + 2], d33 = src[o + 3] - pred[o + 3];
718
+ const a0 = d00 + d01, b0 = d00 - d01, c0 = d02 + d03, e0 = d02 - d03;
719
+ const r00 = a0 + c0, r01 = b0 + e0, r02 = a0 - c0, r03 = b0 - e0;
720
+ const a1 = d10 + d11, b1 = d10 - d11, c1 = d12 + d13, e1 = d12 - d13;
721
+ const r10 = a1 + c1, r11 = b1 + e1, r12 = a1 - c1, r13 = b1 - e1;
722
+ const a2 = d20 + d21, b2 = d20 - d21, c2 = d22 + d23, e2 = d22 - d23;
723
+ const r20 = a2 + c2, r21 = b2 + e2, r22 = a2 - c2, r23 = b2 - e2;
724
+ const a3 = d30 + d31, b3 = d30 - d31, c3 = d32 + d33, e3 = d32 - d33;
725
+ const r30 = a3 + c3, r31 = b3 + e3, r32 = a3 - c3, r33 = b3 - e3;
726
+ let a = r00 + r10, b = r00 - r10, c = r20 + r30, e = r20 - r30;
727
+ sum += Math.abs(a + c) + Math.abs(b + e) + Math.abs(a - c) + Math.abs(b - e);
728
+ a = r01 + r11;
729
+ b = r01 - r11;
730
+ c = r21 + r31;
731
+ e = r21 - r31;
732
+ sum += Math.abs(a + c) + Math.abs(b + e) + Math.abs(a - c) + Math.abs(b - e);
733
+ a = r02 + r12;
734
+ b = r02 - r12;
735
+ c = r22 + r32;
736
+ e = r22 - r32;
737
+ sum += Math.abs(a + c) + Math.abs(b + e) + Math.abs(a - c) + Math.abs(b - e);
738
+ a = r03 + r13;
739
+ b = r03 - r13;
740
+ c = r23 + r33;
741
+ e = r23 - r33;
742
+ sum += Math.abs(a + c) + Math.abs(b + e) + Math.abs(a - c) + Math.abs(b - e);
719
743
  }
720
744
  }
721
745
  return sum / 4;
@@ -756,7 +780,7 @@ class TileEncoder {
756
780
  predictChroma(bs, edgeFlags, b) {
757
781
  this.codeChroma(bs, edgeFlags, b, true);
758
782
  }
759
- codeLuma(bs, edgeFlags, b, predictOnly = false) {
783
+ codeLuma(bs, edgeFlags, b, predictOnly = false, predicted = false) {
760
784
  const f = this.f, seq = this.seq;
761
785
  const bx = this.bx, by = this.by, bx4 = bx, by4 = by & 31;
762
786
  const bw4 = bdim(bs, 0), bh4 = bdim(bs, 1);
@@ -788,7 +812,7 @@ class TileEncoder {
788
812
  const tx4 = bx + x;
789
813
  const flags = (((y > initY || !sbHasTr) && x + tw >= subW4) ? 0 : EDGE_I444_TOP_HAS_RIGHT) |
790
814
  ((x > initX || (!sbHasBl && y + th >= subH4)) ? 0 : EDGE_I444_LEFT_HAS_BOTTOM);
791
- if (!palIdx) {
815
+ if (!palIdx && !predicted) {
792
816
  const mode = prepareEdges(tx4, tx4 > this.colStart, ty, ty > this.rowStart, this.colEnd, this.rowEnd, flags, pic, d, stride, b.yMode, b.yAngle, tw, th, seq.intraEdgeFilter, f.bitdepth);
793
817
  predict(mode, pic, d, stride, tw * 4, th * 4, preparedAngle | intraFlags, 4 * f.bw - 4 * tx4, 4 * f.bh - 4 * ty, f.bitdepthMax);
794
818
  }
@@ -6,6 +6,20 @@ const DISPOSAL_FROM_GIF = [0, 1, 3, 2, 0, 0, 0, 0];
6
6
  const MAX_CODE = 4095;
7
7
  const UNEXPECTED_END = new Error('GIF: unexpected end of data');
8
8
  export function encode({ width, height, loopCount = -1, frames }, quality = 95, comments = []) {
9
+ const restores = frames.some(frame => frame.dispose === 3);
10
+ const parts = [header(width, height, loopCount, comments)];
11
+ for (const [i, frame] of frames.entries())
12
+ parts.push(encodeFrame(frame, quality, frame.dispose === 3 || (i === 0 && restores)));
13
+ parts.push(new Uint8Array([0x3b]));
14
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
15
+ let offset = 0;
16
+ for (const p of parts) {
17
+ out.set(p, offset);
18
+ offset += p.length;
19
+ }
20
+ return out;
21
+ }
22
+ export function header(width, height, loopCount, comments) {
9
23
  const out = new GIFWriter();
10
24
  out.bytes(0x47, 0x49, 0x46, 0x38, 0x39, 0x61);
11
25
  out.u16(width);
@@ -22,30 +36,29 @@ export function encode({ width, height, loopCount = -1, frames }, quality = 95,
22
36
  out.bytes(0x21, 0xfe);
23
37
  writeSubBlocks(out, comment);
24
38
  }
25
- const restores = frames.some(frame => frame.dispose === 3);
26
- for (const [i, frame] of frames.entries()) {
27
- const transparent = frame.dispose === 3 || (i === 0 && restores);
28
- const { palette, indices, transparentIndex } = quantize(frame.pixels, frame.width, { quality, transparent });
29
- const entries = palette.length / 3;
30
- const bits = Math.max(1, Math.ceil(Math.log2(entries)));
31
- out.bytes(0x21, 0xf9, 0x04);
32
- out.bytes(DISPOSAL_TO_GIF[frame.dispose] << 2 | (transparentIndex === -1 ? 0 : 1));
33
- out.u16(Math.min(0xffff, Math.max(0, Math.round(frame.delay))));
34
- out.bytes(transparentIndex === -1 ? 0 : transparentIndex, 0x00);
35
- out.bytes(0x2c);
36
- out.u16(frame.x);
37
- out.u16(frame.y);
38
- out.u16(frame.width);
39
- out.u16(frame.height);
40
- out.bytes(0x80 | bits - 1);
41
- const table = new Uint8Array(3 << bits);
42
- table.set(palette);
43
- out.array(table);
44
- const minCodeSize = Math.max(2, bits);
45
- out.bytes(minCodeSize);
46
- writeSubBlocks(out, lzwEncode(indices, minCodeSize));
47
- }
48
- out.bytes(0x3b);
39
+ return out.finish();
40
+ }
41
+ export function encodeFrame(frame, quality, transparent) {
42
+ const out = new GIFWriter();
43
+ const { palette, indices, transparentIndex } = quantize(frame.pixels, frame.width, { quality, transparent });
44
+ const entries = palette.length / 3;
45
+ const bits = Math.max(1, Math.ceil(Math.log2(entries)));
46
+ out.bytes(0x21, 0xf9, 0x04);
47
+ out.bytes(DISPOSAL_TO_GIF[frame.dispose] << 2 | (transparentIndex === -1 ? 0 : 1));
48
+ out.u16(Math.min(0xffff, Math.max(0, Math.round(frame.delay))));
49
+ out.bytes(transparentIndex === -1 ? 0 : transparentIndex, 0x00);
50
+ out.bytes(0x2c);
51
+ out.u16(frame.x);
52
+ out.u16(frame.y);
53
+ out.u16(frame.width);
54
+ out.u16(frame.height);
55
+ out.bytes(0x80 | bits - 1);
56
+ const table = new Uint8Array(3 << bits);
57
+ table.set(palette);
58
+ out.array(table);
59
+ const minCodeSize = Math.max(2, bits);
60
+ out.bytes(minCodeSize);
61
+ writeSubBlocks(out, lzwEncode(indices, minCodeSize));
49
62
  return out.finish();
50
63
  }
51
64
  function lzwEncode(indices, minCodeSize) {
@@ -0,0 +1,294 @@
1
+ import { forwardTransform } from "./transforms-enc.js";
2
+ import { inverseTransform } from "./dct.js";
3
+ import { defaultDequant, MATRIX_INDEX } from "./quant.js";
4
+ import { SIZES, transposed } from "./vardct.js";
5
+ const DCT8 = 0, IDENTITY = 1, DCT2X2 = 2, DCT4X4 = 3, DCT16X16 = 4, DCT32X32 = 5, DCT16X8 = 6, DCT8X16 = 7;
6
+ const DCT32X16 = 10, DCT16X32 = 11, DCT4X8 = 12, DCT8X4 = 13, DCT64X64 = 18, DCT64X32 = 19, DCT32X64 = 20;
7
+ const AFV0 = 14, AFV1 = 15, AFV2 = 16, AFV3 = 17;
8
+ const ceilLog2 = (x) => x <= 1 ? 0 : 32 - Math.clz32(x - 1);
9
+ const CHANNEL_MUL = [10.2 ** 8, 1, 1.03 ** 8];
10
+ const scratch = [0, 1, 2].map(() => new Float32Array(64 * 64)), errors = new Float32Array(64 * 64), lfScratch = new Float32Array(64);
11
+ const dequant = (type) => defaultDequant(MATRIX_INDEX[type])[transposed(type) ? 1 : 0];
12
+ const inverses = new Map();
13
+ function inverseDequant(type) {
14
+ let inv = inverses.get(type);
15
+ if (!inv)
16
+ inverses.set(type, inv = dequant(type).map(m => Float32Array.from(m, v => 1 / v)));
17
+ return inv;
18
+ }
19
+ function estimateEntropy(type, entropyMul, x, y, cfg) {
20
+ const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1], w = w8 * 8, h = h8 * 8, numBlocks = w8 * h8, size = w * h;
21
+ for (let c = 0; c < 3; c++)
22
+ forwardTransform(type, cfg.planes[c], y * cfg.stride + x, cfg.stride, scratch[c], lfScratch);
23
+ const qf = cfg.field.quant, bw = cfg.bw, bx = x >> 3, by = y >> 3;
24
+ let quant = 0;
25
+ if (numBlocks === 1)
26
+ quant = qf[by * bw + bx];
27
+ else if (numBlocks === 2)
28
+ quant = h8 === 2 ? Math.max(qf[by * bw + bx], qf[(by + 1) * bw + bx]) : Math.max(qf[by * bw + bx], qf[by * bw + bx + 1]);
29
+ else {
30
+ for (let iy = 0; iy < h8; iy++) {
31
+ for (let ix = 0; ix < w8; ix++) {
32
+ const v = qf[(by + iy) * bw + bx + ix] ** 8;
33
+ quant += v * v;
34
+ }
35
+ }
36
+ quant = (quant / numBlocks) ** (1 / 16);
37
+ }
38
+ const matrices = dequant(type), inverses = inverseDequant(type);
39
+ const mask = cfg.field.mask1x1, stride = cfg.stride;
40
+ let entropy = 0, loss = 0;
41
+ for (let c = 0; c < 3; c++) {
42
+ const src = scratch[c], ys = scratch[1], m = matrices[c], im = inverses[c], cmap = c === 2 ? 1 : 0;
43
+ let sqrtSum = 0, nonZeros = 0;
44
+ for (let i = 0; i < size; i++) {
45
+ const v = (src[i] - ys[i] * cmap) * im[i] * quant, r = Math.round(v);
46
+ errors[i] = m[i] * (v - r);
47
+ const q = Math.abs(r);
48
+ sqrtSum += Math.sqrt(q);
49
+ if (q)
50
+ nonZeros++;
51
+ }
52
+ inverseTransform({ buf: errors, offset: 0, stride: w, w, h }, type);
53
+ let lossc = 0;
54
+ for (let py = 0; py < h; py++) {
55
+ const mo = (y + py) * stride + x;
56
+ for (let px = 0; px < w; px++) {
57
+ const e = Math.abs(mask[mo + px]) * errors[py * w + px], e2 = e * e, e4 = e2 * e2;
58
+ lossc += e4 * e4;
59
+ }
60
+ }
61
+ loss += CHANNEL_MUL[c] * lossc;
62
+ entropy += cfg.costDelta * sqrtSum;
63
+ const nbits = ceilLog2(nonZeros + 1) + 1;
64
+ entropy += cfg.zerosMul * (ceilLog2(nbits + 17) + nbits);
65
+ }
66
+ const lossScalar = (loss / (numBlocks * 64)) ** (1 / 8) * (numBlocks * 64) / quant;
67
+ return entropy * entropyMul + cfg.infoLossMul * lossScalar;
68
+ }
69
+ const TRANSFORMS_8X8 = [
70
+ [DCT8, 9, 0.8], [DCT4X4, 5, 1.08], [DCT2X2, 5, 0.95], [DCT4X8, 4, 0.85931637428340035], [DCT8X4, 4, 0.85931637428340035],
71
+ [IDENTITY, 5, 1.0427542510634957], [AFV0, 4, 0.81779489591359944], [AFV1, 4, 0.81779489591359944], [AFV2, 4, 0.81779489591359944],
72
+ [AFV3, 4, 0.81779489591359944]
73
+ ];
74
+ function best8x8(x, y, speed, cfg) {
75
+ let best = Infinity, bestType = DCT8;
76
+ const d = cfg.distance;
77
+ for (const [type, limit, mul] of TRANSFORMS_8X8) {
78
+ if (limit < speed)
79
+ continue;
80
+ let entropyMul = mul / TRANSFORMS_8X8[0][2];
81
+ if ((type === DCT2X2 || type === IDENTITY) && d < 5)
82
+ entropyMul -= 0.4 * ((5 - d) / 5) ** 2;
83
+ if (type !== DCT8 && type !== DCT2X2 && type !== IDENTITY && d > 4)
84
+ entropyMul += 0.5 * (d < 12 ? (12 - 4) / (d - 4) : 1);
85
+ const e = estimateEntropy(type, entropyMul, x, y, cfg);
86
+ if (e < best) {
87
+ best = e;
88
+ bestType = type;
89
+ }
90
+ }
91
+ return [bestType, best];
92
+ }
93
+ class Strategy {
94
+ bw;
95
+ bh;
96
+ types;
97
+ constructor(bw, bh) {
98
+ this.bw = bw;
99
+ this.bh = bh;
100
+ this.types = new Int8Array(bw * bh);
101
+ }
102
+ set(bx, by, type) {
103
+ const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1];
104
+ for (let y = 0; y < h8; y++)
105
+ for (let x = 0; x < w8; x++)
106
+ this.types[(by + y) * this.bw + bx + x] = -1;
107
+ this.types[by * this.bw + bx] = type;
108
+ }
109
+ type(bx, by) {
110
+ return this.types[by * this.bw + bx];
111
+ }
112
+ crossesHorizontal(x0, y, x1) {
113
+ if (x0 >= this.bw || y >= this.bh || y % 8 === 0)
114
+ return false;
115
+ x1 = Math.min(x1, this.bw);
116
+ const limit = x0 & ~7;
117
+ while (x0 !== limit && this.type(x0, y) < 0)
118
+ x0--;
119
+ for (let x = x0; x < x1;) {
120
+ const t = this.type(x, y);
121
+ if (t < 0)
122
+ return true;
123
+ x += SIZES[2 * t];
124
+ }
125
+ return false;
126
+ }
127
+ crossesVertical(x, y0, y1) {
128
+ if (x >= this.bw || y0 >= this.bh || x % 8 === 0)
129
+ return false;
130
+ y1 = Math.min(y1, this.bh);
131
+ const limit = y0 & ~7;
132
+ while (y0 !== limit && this.type(x, y0) < 0)
133
+ y0--;
134
+ for (let y = y0; y < y1;) {
135
+ const t = this.type(x, y);
136
+ if (t < 0)
137
+ return true;
138
+ y += SIZES[2 * t + 1];
139
+ }
140
+ return false;
141
+ }
142
+ }
143
+ const square = (blocks) => blocks === 2 ? DCT16X16 : blocks === 4 ? DCT32X32 : DCT64X64;
144
+ const verticalSplit = (blocks) => blocks === 2 ? DCT16X8 : blocks === 4 ? DCT32X16 : DCT64X32;
145
+ const horizontalSplit = (blocks) => blocks === 2 ? DCT8X16 : blocks === 4 ? DCT16X32 : DCT32X64;
146
+ function bestDivision(blocks, allowSquare, bx, by, cx, cy, cfg, s, mulJxK, mulJxJ, est) {
147
+ const half = blocks / 2, jxk = verticalSplit(blocks), kxj = horizontalSplit(blocks), jxj = square(blocks);
148
+ const x = bx + cx, y = by + cy;
149
+ if (s.crossesHorizontal(x, y, x + blocks) || s.crossesHorizontal(x, y + blocks, x + blocks) || s.crossesVertical(x, y, y + blocks) || s.crossesVertical(x + blocks, y, y + blocks))
150
+ return;
151
+ const allowJxK = !s.crossesVertical(x + half, y, y + blocks), allowKxJ = !s.crossesHorizontal(x, y + half, x + blocks);
152
+ const e = [[0, 0], [0, 0]];
153
+ for (let dy = 0; dy < blocks; dy++)
154
+ for (let dx = 0; dx < blocks; dx++)
155
+ e[Math.floor(dy / half)][Math.floor(dx / half)] += est[(cy + dy) * 8 + cx + dx];
156
+ let jxkLeft = Infinity, jxkRight = Infinity, kxjTop = Infinity, kxjBottom = Infinity, jxjCost = Infinity;
157
+ if (allowJxK) {
158
+ if (s.type(x, y) !== jxk)
159
+ jxkLeft = estimateEntropy(jxk, mulJxK, x * 8, y * 8, cfg);
160
+ if (s.type(x + half, y) !== jxk)
161
+ jxkRight = estimateEntropy(jxk, mulJxK, (x + half) * 8, y * 8, cfg);
162
+ }
163
+ if (allowKxJ) {
164
+ if (s.type(x, y) !== kxj)
165
+ kxjTop = estimateEntropy(kxj, mulJxK, x * 8, y * 8, cfg);
166
+ if (s.type(x, y + half) !== kxj)
167
+ kxjBottom = estimateEntropy(kxj, mulJxK, x * 8, (y + half) * 8, cfg);
168
+ }
169
+ if (allowSquare)
170
+ jxjCost = estimateEntropy(jxj, mulJxJ, x * 8, y * 8, cfg);
171
+ const costJxN = Math.min(jxkLeft, e[0][0] + e[1][0]) + Math.min(jxkRight, e[0][1] + e[1][1]);
172
+ const costNxJ = Math.min(kxjTop, e[0][0] + e[0][1]) + Math.min(kxjBottom, e[1][0] + e[1][1]);
173
+ const setEntropy = (ex, ey, type, entropy) => {
174
+ for (let dy = 0; dy < SIZES[2 * type + 1]; dy++)
175
+ for (let dx = 0; dx < SIZES[2 * type]; dx++)
176
+ est[(ey + dy) * 8 + ex + dx] = 0;
177
+ est[ey * 8 + ex] = entropy;
178
+ };
179
+ if (jxjCost < costJxN && jxjCost < costNxJ) {
180
+ s.set(x, y, jxj);
181
+ setEntropy(cx, cy, jxj, jxjCost);
182
+ }
183
+ else if (costJxN < costNxJ) {
184
+ if (jxkLeft < e[0][0] + e[1][0]) {
185
+ s.set(x, y, jxk);
186
+ setEntropy(cx, cy, jxk, jxkLeft);
187
+ }
188
+ if (jxkRight < e[0][1] + e[1][1]) {
189
+ s.set(x + half, y, jxk);
190
+ setEntropy(cx + half, cy, jxk, jxkRight);
191
+ }
192
+ }
193
+ else {
194
+ if (kxjTop < e[0][0] + e[0][1]) {
195
+ s.set(x, y, kxj);
196
+ setEntropy(cx, cy, kxj, kxjTop);
197
+ }
198
+ if (kxjBottom < e[1][0] + e[1][1]) {
199
+ s.set(x, y + half, kxj);
200
+ setEntropy(cx, cy + half, kxj, kxjBottom);
201
+ }
202
+ }
203
+ }
204
+ function tryMerge(type, bx, by, cx, cy, cfg, s, mul, prio, priority, est) {
205
+ const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1];
206
+ let current = 0;
207
+ for (let iy = 0; iy < h8; iy++) {
208
+ for (let ix = 0; ix < w8; ix++) {
209
+ if (priority[(cy + iy) * 8 + cx + ix] >= prio)
210
+ return;
211
+ current += est[(cy + iy) * 8 + cx + ix];
212
+ }
213
+ }
214
+ const candidate = estimateEntropy(type, mul, (bx + cx) * 8, (by + cy) * 8, cfg);
215
+ if (candidate >= current)
216
+ return;
217
+ for (let iy = 0; iy < h8; iy++) {
218
+ for (let ix = 0; ix < w8; ix++) {
219
+ est[(cy + iy) * 8 + cx + ix] = 0;
220
+ priority[(cy + iy) * 8 + cx + ix] = prio;
221
+ }
222
+ }
223
+ s.set(bx + cx, by + cy, type);
224
+ est[cy * 8 + cx] = candidate;
225
+ }
226
+ const MERGES = [
227
+ [DCT16X8, 2, 1.25], [DCT8X16, 2, 1.25], [DCT16X32, 4, 1.5], [DCT32X16, 4, 1.5], [DCT64X32, 6, 2.26], [DCT32X64, 6, 2.26]
228
+ ];
229
+ function processRect(bx, by, w, h, speed, cfg, s) {
230
+ const est = new Float32Array(64), priority = new Uint8Array(64);
231
+ const mul8x8 = 1 - 0.4 / (cfg.distance + 1.4);
232
+ for (let iy = 0; iy < h; iy++) {
233
+ for (let ix = 0; ix < w; ix++) {
234
+ const [type, entropy] = best8x8(8 * (bx + ix), 8 * (by + iy), speed, cfg);
235
+ s.set(bx + ix, by + iy, type);
236
+ est[iy * 8 + ix] = entropy * mul8x8;
237
+ }
238
+ }
239
+ for (const [type, prio, mul] of MERGES) {
240
+ const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1];
241
+ for (let cy = 0; cy + h8 - 1 < h; cy += h8) {
242
+ for (let cx = 0; cx + w8 - 1 < w; cx += w8) {
243
+ if (cy + 7 < h && cx + 7 < w) {
244
+ if (type === DCT32X64) {
245
+ if ((cy | cx) % 8 === 0)
246
+ bestDivision(8, true, bx, by, cx, cy, cfg, s, mul, 2.26, est);
247
+ continue;
248
+ }
249
+ else if (type === DCT64X32)
250
+ continue;
251
+ }
252
+ if ((type === DCT16X32 && cy % 4 !== 0) || (type === DCT32X16 && cx % 4 !== 0))
253
+ continue;
254
+ if (cy + 3 < h && cx + 3 < w) {
255
+ if (type === DCT16X32) {
256
+ if ((cy | cx) % 4 === 0)
257
+ bestDivision(4, true, bx, by, cx, cy, cfg, s, mul, 1.5, est);
258
+ continue;
259
+ }
260
+ else if (type === DCT32X16)
261
+ continue;
262
+ }
263
+ if ((type === DCT16X32 && cy % 4 !== 0) || (type === DCT32X16 && cx % 4 !== 0))
264
+ continue;
265
+ if (cy + 1 < h && cx + 1 < w) {
266
+ if (type === DCT8X16) {
267
+ if ((cy | cx) % 2 === 0)
268
+ bestDivision(2, true, bx, by, cx, cy, cfg, s, mul, 1.35, est);
269
+ continue;
270
+ }
271
+ else if (type === DCT16X8)
272
+ continue;
273
+ }
274
+ if ((type === DCT8X16 && cy % 2 === 1) || (type === DCT16X8 && cx % 2 === 1))
275
+ continue;
276
+ tryMerge(type, bx, by, cx, cy, cfg, s, mul, prio, priority, est);
277
+ }
278
+ }
279
+ }
280
+ }
281
+ export function chooseVarblocks(planes, stride, bw, bh, field, distance, speed) {
282
+ const ratio = (distance + 0.13731742964354549) / (1 + 0.13731742964354549);
283
+ const cfg = {
284
+ planes, stride, bw, field, distance,
285
+ infoLossMul: 1.2 * ratio ** 0.33677806662454718,
286
+ zerosMul: 9.3089059022677905 * ratio ** 0.50990926717963703,
287
+ costDelta: 10.833273317067883 * ratio ** 0.36702940662370243
288
+ };
289
+ const s = new Strategy(bw, bh);
290
+ for (let by = 0; by < bh; by += 8)
291
+ for (let bx = 0; bx < bw; bx += 8)
292
+ processRect(bx, by, Math.min(8, bw - bx), Math.min(8, bh - by), speed, cfg, s);
293
+ return s.types;
294
+ }