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
@@ -0,0 +1,150 @@
1
+ /*!
2
+ * libwebp's sharp RGB to YUV 4:2:0 conversion (sharpyuv/sharpyuv.c, sharpyuv_dsp.c, sharpyuv_gamma.c), ported for 8
3
+ * bit RGB to 8 bit YUV with the WebP matrix: luma and chroma are chosen iteratively so that the picture upsampled
4
+ * again matches the original better, sharper at color edges than averaging the chroma. Copyright (c) 2022 Google
5
+ * Inc., BSD-3-Clause License (see THIRD_PARTY_NOTICES.md)
6
+ */
7
+ const ITERATIONS = 4;
8
+ const SHIFT = 2, BITS = 10, MAX = (1 << BITS) - 1;
9
+ const TO_LINEAR = new Uint32Array(1024 + 2), FROM_LINEAR = new Uint32Array(512 + 2);
10
+ {
11
+ const a = 0.09929682680944, thresh = 0.018053968510807, gamma = 1 / 0.45;
12
+ for (let v = 0; v <= 1024; v++) {
13
+ const g = v / 1024;
14
+ TO_LINEAR[v] = Math.trunc((g <= thresh * 4.5 ? g / 4.5 : Math.pow((g + a) / (1 + a), gamma)) * 65536 + 0.5);
15
+ }
16
+ TO_LINEAR[1025] = TO_LINEAR[1024];
17
+ for (let v = 0; v <= 512; v++) {
18
+ const g = v / 512;
19
+ FROM_LINEAR[v] = Math.trunc(65536 * (g <= thresh ? 4.5 * g : (1 + a) * Math.pow(g, 1 / gamma) - a) + 0.5);
20
+ }
21
+ FROM_LINEAR[513] = FROM_LINEAR[512];
22
+ }
23
+ const toLinear = (v) => TO_LINEAR[v];
24
+ function fromLinear(value) {
25
+ const pos = value >>> 7, x = value - (pos << 7);
26
+ const v0 = FROM_LINEAR[pos] >>> 6, v1 = FROM_LINEAR[pos + 1] >>> 6;
27
+ return v0 + (((v1 - v0) * x + 64) >>> 7);
28
+ }
29
+ const gray = (r, g, b) => Math.floor((13933 * r + 46871 * g + 4732 * b + 32768) / 65536);
30
+ const clip = (v) => v < 0 ? 0 : v > MAX ? MAX : v;
31
+ function updateW(src, s, dst, d, w) {
32
+ for (let i = 0; i < w; i++)
33
+ dst[d + i] = fromLinear(gray(toLinear(src[s + i]), toLinear(src[s + w + i]), toLinear(src[s + 2 * w + i])));
34
+ }
35
+ const scaleDown = (a, b, c, d) => fromLinear((toLinear(a) + toLinear(b) + toLinear(c) + toLinear(d) + 2) >> 2);
36
+ function updateChroma(src, s1, s2, dst, d, uvWidth) {
37
+ const w = 2 * uvWidth;
38
+ for (let i = 0; i < uvWidth; i++) {
39
+ const o = 2 * i;
40
+ const r = scaleDown(src[s1 + o], src[s1 + o + 1], src[s2 + o], src[s2 + o + 1]);
41
+ const g = scaleDown(src[s1 + w + o], src[s1 + w + o + 1], src[s2 + w + o], src[s2 + w + o + 1]);
42
+ const b = scaleDown(src[s1 + 2 * w + o], src[s1 + 2 * w + o + 1], src[s2 + 2 * w + o], src[s2 + 2 * w + o + 1]);
43
+ const W = gray(r, g, b);
44
+ dst[d + i] = r - W;
45
+ dst[d + uvWidth + i] = g - W;
46
+ dst[d + 2 * uvWidth + i] = b - W;
47
+ }
48
+ }
49
+ function storeGray(rgb, s, y, d, w) {
50
+ for (let i = 0; i < w; i++)
51
+ y[d + i] = gray(rgb[s + i], rgb[s + w + i], rgb[s + 2 * w + i]);
52
+ }
53
+ function importRow(rgba, o, width, w, dst, d) {
54
+ for (let i = 0; i < width; i++, o += 4) {
55
+ dst[d + i] = rgba[o] << SHIFT;
56
+ dst[d + w + i] = rgba[o + 1] << SHIFT;
57
+ dst[d + 2 * w + i] = rgba[o + 2] << SHIFT;
58
+ }
59
+ if (width & 1)
60
+ for (let c = 0; c < 3; c++)
61
+ dst[d + c * w + width] = dst[d + c * w + width - 1];
62
+ }
63
+ function interpolateTwoRows(bestY, y, uv, prev, cur, next, w, out, o1, o2) {
64
+ const uvWidth = w >> 1, len = (w - 1) >> 1;
65
+ const filter2 = (a, b, w0) => clip(((a * 3 + b + 2) >> 2) + w0);
66
+ const filterRow = (a, b, by, o) => {
67
+ for (let i = 0; i < len; i++, a++, b++) {
68
+ const v0 = (uv[a] * 9 + uv[a + 1] * 3 + uv[b] * 3 + uv[b + 1] + 8) >> 4;
69
+ const v1 = (uv[a + 1] * 9 + uv[a] * 3 + uv[b + 1] * 3 + uv[b] + 8) >> 4;
70
+ out[o + 2 * i] = clip(bestY[by + 2 * i] + v0);
71
+ out[o + 2 * i + 1] = clip(bestY[by + 2 * i + 1] + v1);
72
+ }
73
+ };
74
+ for (let k = 0; k < 3; k++) {
75
+ out[o1] = filter2(uv[cur], uv[prev], bestY[y]);
76
+ out[o2] = filter2(uv[cur], uv[next], bestY[y + w]);
77
+ filterRow(cur, prev, y + 1, o1 + 1);
78
+ filterRow(cur, next, y + w + 1, o2 + 1);
79
+ if (!(w & 1)) {
80
+ out[o1 + w - 1] = filter2(uv[cur + uvWidth - 1], uv[prev + uvWidth - 1], bestY[y + w - 1]);
81
+ out[o2 + w - 1] = filter2(uv[cur + uvWidth - 1], uv[next + uvWidth - 1], bestY[y + 2 * w - 1]);
82
+ }
83
+ o1 += w;
84
+ o2 += w;
85
+ prev += uvWidth;
86
+ cur += uvWidth;
87
+ next += uvWidth;
88
+ }
89
+ }
90
+ const yuv = (r, g, b, c0, c1, c2, offset) => (c0 * r + c1 * g + c2 * b + (offset << 18) + (1 << 17)) >> 18;
91
+ const clip8 = (v) => v < 0 ? 0 : v > 255 ? 255 : v;
92
+ export function sharpYUV(rgba, width, height, y, u, v) {
93
+ const w = (width + 1) & ~1, h = (height + 1) & ~1, uvWidth = w >> 1, uvHeight = h >> 1;
94
+ const tmp = new Uint16Array(w * 6), bestY = new Uint16Array(w * h), targetY = new Uint16Array(w * h), bestRGBY = new Uint16Array(w * 2);
95
+ const bestUV = new Int16Array(uvWidth * 3 * uvHeight), targetUV = new Int16Array(uvWidth * 3 * uvHeight), bestRGBUV = new Int16Array(uvWidth * 3);
96
+ const stride = width * 4;
97
+ for (let j = 0, uvRow = 0; j < height; j += 2, uvRow += 3 * uvWidth) {
98
+ importRow(rgba, j * stride, width, w, tmp, 0);
99
+ if (j < height - 1)
100
+ importRow(rgba, (j + 1) * stride, width, w, tmp, 3 * w);
101
+ else
102
+ tmp.copyWithin(3 * w, 0, 3 * w);
103
+ storeGray(tmp, 0, bestY, j * w, w);
104
+ storeGray(tmp, 3 * w, bestY, (j + 1) * w, w);
105
+ updateW(tmp, 0, targetY, j * w, w);
106
+ updateW(tmp, 3 * w, targetY, (j + 1) * w, w);
107
+ updateChroma(tmp, 0, 3 * w, targetUV, uvRow, uvWidth);
108
+ bestUV.set(targetUV.subarray(uvRow, uvRow + 3 * uvWidth), uvRow);
109
+ }
110
+ const threshold = Math.trunc(3 * w * h);
111
+ let previousSum = Infinity;
112
+ for (let iteration = 0; iteration < ITERATIONS; iteration++) {
113
+ let cur = 0, prev = 0, sum = 0;
114
+ for (let j = 0; j < h; j += 2) {
115
+ const next = cur + (j < h - 2 ? 3 * uvWidth : 0);
116
+ interpolateTwoRows(bestY, j * w, bestUV, prev, cur, next, w, tmp, 0, 3 * w);
117
+ prev = cur;
118
+ cur = next;
119
+ updateW(tmp, 0, bestRGBY, 0, w);
120
+ updateW(tmp, 3 * w, bestRGBY, w, w);
121
+ updateChroma(tmp, 0, 3 * w, bestRGBUV, 0, uvWidth);
122
+ for (let i = 0; i < 2 * w; i++) {
123
+ const diff = targetY[j * w + i] - bestRGBY[i];
124
+ bestY[j * w + i] = clip(bestY[j * w + i] + diff);
125
+ sum += Math.abs(diff);
126
+ }
127
+ const uvRow = (j >> 1) * 3 * uvWidth;
128
+ for (let i = 0; i < 3 * uvWidth; i++)
129
+ bestUV[uvRow + i] += targetUV[uvRow + i] - bestRGBUV[i];
130
+ }
131
+ if (iteration > 0 && (sum < threshold || sum > previousSum))
132
+ break;
133
+ previousSum = sum;
134
+ }
135
+ for (let j = 0; j < height; j++) {
136
+ const uvRow = (j >> 1) * 3 * uvWidth;
137
+ for (let i = 0; i < width; i++) {
138
+ const W = bestY[j * w + i], o = uvRow + (i >> 1);
139
+ const r = bestUV[o] + W, g = bestUV[o + uvWidth] + W, b = bestUV[o + 2 * uvWidth] + W;
140
+ y[j * width + i] = clip8(yuv(r, g, b, 16839, 33059, 6420, 16));
141
+ }
142
+ }
143
+ for (let j = 0; j < uvHeight; j++)
144
+ for (let i = 0; i < uvWidth; i++) {
145
+ const o = j * 3 * uvWidth + i;
146
+ const r = bestUV[o], g = bestUV[o + uvWidth], b = bestUV[o + 2 * uvWidth];
147
+ u[j * uvWidth + i] = clip8(yuv(r, g, b, -9719, -19081, 28800, 128));
148
+ v[j * uvWidth + i] = clip8(yuv(r, g, b, 28800, -24116, -4684, 128));
149
+ }
150
+ }
@@ -1,4 +1,5 @@
1
1
  import { littleEndian } from "../util/alpha.js";
2
+ import { sharpYUV } from "./sharpyuv.js";
2
3
  export const BPS = 32;
3
4
  export const Y_OFF = 0, U_OFF = 16, V_OFF = 24;
4
5
  export const YUV_SIZE = BPS * 16, PRED_SIZE = 56 * BPS;
@@ -43,7 +44,7 @@ function weighted(rgba, o, step, next, total) {
43
44
  const sum = rgba[a] * g[rgba[o]] + rgba[a + step] * g[rgba[o + step]] + rgba[a + next] * g[rgba[o + next]] + rgba[a + next + step] * g[rgba[o + next + step]];
44
45
  return linearToGamma((sum * INV_ALPHA[total]) >>> 17, 0);
45
46
  }
46
- export function rgbaToYUV(rgba, width, height) {
47
+ export function rgbaToYUV(rgba, width, height, sharp = false) {
47
48
  const uvWidth = (width + 1) >> 1, uvHeight = (height + 1) >> 1;
48
49
  const y = new Uint8Array(width * height), u = new Uint8Array(uvWidth * uvHeight), v = new Uint8Array(uvWidth * uvHeight);
49
50
  let hasAlpha = false;
@@ -57,6 +58,13 @@ export function rgbaToYUV(rgba, width, height) {
57
58
  if (a)
58
59
  for (let j = 0; j < height; j++)
59
60
  alphaRow(rgba, j * stride, a, j * width, width);
61
+ if (sharp && width >= 4 && height >= 4) {
62
+ sharpYUV(rgba, width, height, y, u, v);
63
+ const picture = { width, height, y, u, v, a, uvStride: uvWidth };
64
+ if (a)
65
+ cleanupTransparentArea(picture);
66
+ return picture;
67
+ }
60
68
  const words = littleEndian && rgba.byteOffset % 4 === 0 ? new Uint32Array(rgba.buffer, rgba.byteOffset, width * height) : null;
61
69
  for (let j = 0; j < uvHeight; j++) {
62
70
  const row = 2 * j * stride;
@@ -719,7 +719,7 @@ function writeCode(w, counts) {
719
719
  else if (t === 18)
720
720
  w.write(extras[i], 7);
721
721
  }
722
- return code;
722
+ return used.length === 1 ? { lengths: code.lengths, codes: new Uint16Array(0) } : code;
723
723
  }
724
724
  function prefixEncode(value) {
725
725
  const d = value - 1;
@@ -729,7 +729,7 @@ function prefixEncode(value) {
729
729
  const second = d >> h - 1 & 1;
730
730
  return { symbol: 2 * h + second, bits: h - 1, extra: d & (1 << h - 1) - 1 };
731
731
  }
732
- function tokenize(pixels, width, cacheBits) {
732
+ function tokenize(pixels, width) {
733
733
  const n = pixels.length;
734
734
  const ops = new Uint8Array(n), values = new Uint32Array(n), distances = new Uint32Array(n);
735
735
  let count = 0;
@@ -746,12 +746,15 @@ function tokenize(pixels, width, cacheBits) {
746
746
  const hashes = new Int32Array(n);
747
747
  for (let i = 0; i + 1 < n; i++)
748
748
  hashes[i] = Math.imul(Math.imul(pixels[i], 0x1e35a7bd) ^ pixels[i + 1], 0x9e3779b1) >>> 32 - HASH_BITS;
749
- const insert = (i) => {
750
- if (i + 1 >= n)
751
- return;
752
- const h = hashes[i];
753
- chain[i] = head[h];
754
- head[h] = i;
749
+ let inserted = 0;
750
+ const insertUpTo = (end) => {
751
+ for (; inserted < end && inserted + 1 < n; inserted++) {
752
+ const h = hashes[inserted];
753
+ chain[inserted] = head[h];
754
+ head[h] = inserted;
755
+ }
756
+ if (inserted < end)
757
+ inserted = end;
755
758
  };
756
759
  const matchLength = (i, j) => {
757
760
  const max = Math.min(MAX_LENGTH, n - i);
@@ -760,11 +763,10 @@ function tokenize(pixels, width, cacheBits) {
760
763
  l++;
761
764
  return l;
762
765
  };
763
- const cache = cacheBits ? new Uint32Array(1 << cacheBits) : null;
764
- const cacheShift = 32 - cacheBits;
765
- let cached = 0;
766
- for (let i = 0; i < n;) {
767
- let bestLength = 0, bestDistance = 0;
766
+ let bestLength = 0, bestDistance = 0;
767
+ const find = (i) => {
768
+ bestLength = 0;
769
+ bestDistance = 0;
768
770
  if (i >= 1) {
769
771
  const l = matchLength(i, i - 1);
770
772
  if (l > bestLength) {
@@ -792,44 +794,56 @@ function tokenize(pixels, width, cacheBits) {
792
794
  break;
793
795
  }
794
796
  }
797
+ };
798
+ for (let i = 0; i < n;) {
799
+ insertUpTo(i);
800
+ find(i);
801
+ if (bestLength >= MIN_LENGTH && bestLength < MAX_LENGTH && i + 1 < n) {
802
+ const length = bestLength, distance = bestDistance;
803
+ insertUpTo(i + 1);
804
+ find(i + 1);
805
+ if (bestLength > length + 1) {
806
+ ops[count] = 0;
807
+ values[count++] = pixels[i++];
808
+ continue;
809
+ }
810
+ bestLength = length;
811
+ bestDistance = distance;
812
+ }
795
813
  if (bestLength >= MIN_LENGTH) {
796
814
  ops[count] = 1;
797
815
  values[count] = bestLength;
798
816
  distances[count++] = distanceCode(bestDistance);
799
- for (let k = 0; k < bestLength; k++)
800
- insert(i + k);
801
817
  i += bestLength;
802
818
  continue;
803
819
  }
804
- const argb = pixels[i];
805
- if (cache) {
806
- for (; cached < i; cached++)
807
- cache[Math.imul(pixels[cached], 0x1e35a7bd) >>> cacheShift] = pixels[cached];
808
- const key = Math.imul(argb, 0x1e35a7bd) >>> cacheShift;
809
- if (cache[key] === argb) {
810
- ops[count] = 2;
811
- values[count++] = key;
812
- insert(i++);
813
- continue;
814
- }
815
- }
816
820
  ops[count] = 0;
817
- values[count++] = argb;
818
- insert(i++);
821
+ values[count++] = pixels[i++];
819
822
  }
820
823
  return { ops, values, distances, count };
821
824
  }
822
- function writeImage(w, pixels, width, isMain) {
823
- const cacheBits = isMain && pixels.length > 4096 ? 10 : 0;
824
- const stream = tokenize(pixels, width, cacheBits);
825
- if (cacheBits) {
826
- w.write(1, 1);
827
- w.write(cacheBits, 4);
825
+ function withCache(stream, pixels, bits) {
826
+ if (!bits)
827
+ return stream;
828
+ const { ops, values, distances, count } = stream;
829
+ const out = { ops: ops.slice(0, count), values: values.slice(0, count), distances, count };
830
+ const cache = new Uint32Array(1 << bits), shift = 32 - bits;
831
+ for (let k = 0, i = 0; k < count; k++) {
832
+ if (ops[k] === 1) {
833
+ for (const end = i + values[k]; i < end; i++)
834
+ cache[Math.imul(pixels[i], 0x1e35a7bd) >>> shift] = pixels[i];
835
+ continue;
836
+ }
837
+ const argb = pixels[i++], key = Math.imul(argb, 0x1e35a7bd) >>> shift;
838
+ if (cache[key] === argb) {
839
+ out.ops[k] = 2;
840
+ out.values[k] = key;
841
+ }
842
+ cache[key] = argb;
828
843
  }
829
- else
830
- w.write(0, 1);
831
- if (isMain)
832
- w.write(0, 1);
844
+ return out;
845
+ }
846
+ function histograms(stream, cacheBits) {
833
847
  const greenSize = NUM_LITERAL_CODES + NUM_LENGTH_CODES + (cacheBits ? 1 << cacheBits : 0);
834
848
  const counts = [new Int32Array(greenSize), new Int32Array(256), new Int32Array(256), new Int32Array(256), new Int32Array(NUM_DISTANCE_CODES)];
835
849
  const { ops, values, distances, count } = stream;
@@ -848,24 +862,293 @@ function writeImage(w, pixels, width, isMain) {
848
862
  else
849
863
  counts[0][NUM_LITERAL_CODES + NUM_LENGTH_CODES + v]++;
850
864
  }
851
- const codes = counts.map(c => writeCode(w, c));
852
- for (let k = 0; k < count; k++) {
865
+ return counts;
866
+ }
867
+ function bestCacheBits(stream, pixels) {
868
+ const { ops, values, count } = stream;
869
+ const caches = Array.from({ length: 11 }, (_, b) => new Uint32Array(1 << b));
870
+ const literals = Array.from({ length: 11 }, () => [0, 1, 2, 3].map(() => new Float64Array(256)));
871
+ const hits = Array.from({ length: 11 }, (_, b) => new Float64Array(1 << b));
872
+ for (let k = 0, i = 0; k < count; k++) {
873
+ if (ops[k] === 1) {
874
+ for (const end = i + values[k]; i < end; i++) {
875
+ const p = pixels[i], h = Math.imul(p, 0x1e35a7bd);
876
+ for (let b = 1; b <= 10; b++)
877
+ caches[b][h >>> 32 - b] = p;
878
+ }
879
+ continue;
880
+ }
881
+ const p = pixels[i++], h = Math.imul(p, 0x1e35a7bd);
882
+ const l0 = literals[0];
883
+ l0[0][p >> 8 & 255]++;
884
+ l0[1][p >> 16 & 255]++;
885
+ l0[2][p & 255]++;
886
+ l0[3][p >>> 24]++;
887
+ for (let b = 1; b <= 10; b++) {
888
+ const key = h >>> 32 - b, cache = caches[b];
889
+ if (cache[key] === p)
890
+ hits[b][key]++;
891
+ else {
892
+ const l = literals[b];
893
+ l[0][p >> 8 & 255]++;
894
+ l[1][p >> 16 & 255]++;
895
+ l[2][p & 255]++;
896
+ l[3][p >>> 24]++;
897
+ cache[key] = p;
898
+ }
899
+ }
900
+ }
901
+ const bitsOf = (h, total) => {
902
+ let bits = 0;
903
+ for (let i = 0; i < h.length; i++)
904
+ if (h[i])
905
+ bits += 5 - h[i] * Math.log2(h[i] / total);
906
+ return bits;
907
+ };
908
+ let best = 0, bestBits = Infinity;
909
+ for (let b = 0; b <= 10; b++) {
910
+ const l = literals[b];
911
+ let n = 0;
912
+ for (let i = 0; i < 256; i++)
913
+ n += l[0][i];
914
+ let hitCount = 0;
915
+ for (let i = 0; i < hits[b].length; i++)
916
+ hitCount += hits[b][i];
917
+ const green = n + hitCount;
918
+ let bits = bitsOf(l[1], n) + bitsOf(l[2], n) + bitsOf(l[3], n);
919
+ for (let i = 0; i < 256; i++)
920
+ if (l[0][i])
921
+ bits += 5 - l[0][i] * Math.log2(l[0][i] / green);
922
+ if (b)
923
+ for (let i = 0; i < hits[b].length; i++)
924
+ if (hits[b][i])
925
+ bits += 5 - hits[b][i] * Math.log2(hits[b][i] / green);
926
+ if (bits < bestBits) {
927
+ bestBits = bits;
928
+ best = b;
929
+ }
930
+ }
931
+ return best;
932
+ }
933
+ function entropyBits(counts) {
934
+ let bits = 0;
935
+ for (const c of counts) {
936
+ let total = 0;
937
+ for (let i = 0; i < c.length; i++)
938
+ total += c[i];
939
+ for (let i = 0; i < c.length; i++)
940
+ if (c[i])
941
+ bits += 5 - c[i] * Math.log2(c[i] / total);
942
+ }
943
+ return bits;
944
+ }
945
+ function tokenSymbols(stream, k, out) {
946
+ const v = stream.values[k], op = stream.ops[k];
947
+ out[1] = out[2] = out[3] = out[4] = -1;
948
+ if (op === 0) {
949
+ out[0] = v >> 8 & 255;
950
+ out[1] = v >> 16 & 255;
951
+ out[2] = v & 255;
952
+ out[3] = v >>> 24;
953
+ }
954
+ else if (op === 1) {
955
+ out[0] = NUM_LITERAL_CODES + prefixEncode(v).symbol;
956
+ out[4] = prefixEncode(stream.distances[k]).symbol;
957
+ }
958
+ else
959
+ out[0] = NUM_LITERAL_CODES + NUM_LENGTH_CODES + v;
960
+ }
961
+ function prefixGroups(stream, width, height, cacheBits, bits) {
962
+ const bw = subSize(width, bits), bh = subSize(height, bits), nb = bw * bh;
963
+ const greenSize = NUM_LITERAL_CODES + NUM_LENGTH_CODES + (cacheBits ? 1 << cacheBits : 0);
964
+ const sizes = [greenSize, 256, 256, 256, NUM_DISTANCE_CODES], offsets = [0, greenSize, greenSize + 256, greenSize + 512, greenSize + 768];
965
+ const total = greenSize + 768 + NUM_DISTANCE_CODES;
966
+ const syms = new Int32Array(5), keys = [];
967
+ for (let k = 0, i = 0; k < stream.count; k++) {
968
+ const x = i % width, y = (i / width) | 0, blk = (y >> bits) * bw + (x >> bits);
969
+ tokenSymbols(stream, k, syms);
970
+ for (let c = 0; c < 5; c++)
971
+ if (syms[c] >= 0)
972
+ keys.push(blk * total + offsets[c] + syms[c]);
973
+ i += stream.ops[k] === 1 ? stream.values[k] : 1;
974
+ }
975
+ const sorted = Int32Array.from(keys).sort();
976
+ const starts = new Int32Array(nb + 1), sparse = [];
977
+ let blk = 0;
978
+ for (let e = 0; e < sorted.length;) {
979
+ const key = sorted[e], b = Math.floor(key / total);
980
+ while (blk < b)
981
+ starts[++blk] = sparse.length;
982
+ let n = 0;
983
+ while (e < sorted.length && sorted[e] === key) {
984
+ n++;
985
+ e++;
986
+ }
987
+ sparse.push(key - b * total, n);
988
+ }
989
+ while (blk < nb)
990
+ starts[++blk] = sparse.length;
991
+ const entries = Float64Array.from(sparse);
992
+ const logs = (cl) => {
993
+ const t = totals(cl), out = new Float64Array(total);
994
+ for (let c = 0; c < 5; c++) {
995
+ const o = offsets[c], d = t[c] + 0.5 * sizes[c];
996
+ for (let s = 0; s < sizes[c]; s++)
997
+ out[o + s] = -Math.log2((cl[o + s] + 0.5) / d);
998
+ }
999
+ return out;
1000
+ };
1001
+ const cost = (blk, log) => {
1002
+ let bitsSum = 0;
1003
+ for (let e = starts[blk]; e < starts[blk + 1]; e += 2)
1004
+ bitsSum += entries[e + 1] * log[entries[e]];
1005
+ return bitsSum;
1006
+ };
1007
+ const totals = (cl) => Float64Array.from(offsets, (o, c) => {
1008
+ let t = 0;
1009
+ for (let s = 0; s < sizes[c]; s++)
1010
+ t += cl[o + s];
1011
+ return t;
1012
+ });
1013
+ const clusterBits = (cl) => {
1014
+ let b = 0;
1015
+ const t = totals(cl);
1016
+ for (let c = 0; c < 5; c++) {
1017
+ for (let s = 0; s < sizes[c]; s++) {
1018
+ const n = cl[offsets[c] + s];
1019
+ if (n)
1020
+ b += 5 - n * Math.log2(n / t[c]);
1021
+ }
1022
+ }
1023
+ return b;
1024
+ };
1025
+ const used = Array.from({ length: nb }, (_, i) => i).filter(i => starts[i + 1] > starts[i]);
1026
+ const single = new Float64Array(total);
1027
+ for (const blk of used)
1028
+ for (let e = starts[blk]; e < starts[blk + 1]; e += 2)
1029
+ single[entries[e]] += entries[e + 1];
1030
+ let bestBits = clusterBits(single), best = null;
1031
+ const assign = new Int32Array(nb);
1032
+ for (const k of [4, 8, 16]) {
1033
+ if (k > used.length)
1034
+ break;
1035
+ const blockHistogram = (blk) => {
1036
+ const h = new Float64Array(total);
1037
+ for (let e = starts[blk]; e < starts[blk + 1]; e += 2)
1038
+ h[entries[e]] = entries[e + 1];
1039
+ return h;
1040
+ };
1041
+ const centers = [blockHistogram(used[0])];
1042
+ const dist = new Float64Array(nb).fill(Infinity);
1043
+ while (centers.length < k) {
1044
+ const log = logs(centers[centers.length - 1]);
1045
+ let far = -1;
1046
+ for (const blk of used) {
1047
+ dist[blk] = Math.min(dist[blk], cost(blk, log));
1048
+ if (far < 0 || dist[blk] > dist[far])
1049
+ far = blk;
1050
+ }
1051
+ centers.push(blockHistogram(far));
1052
+ }
1053
+ let clusters = centers;
1054
+ for (let iter = 0; iter < 3; iter++) {
1055
+ const ls = clusters.map(logs);
1056
+ for (const blk of used) {
1057
+ let bc = 0, bv = Infinity;
1058
+ for (let j = 0; j < ls.length; j++) {
1059
+ const v = cost(blk, ls[j]);
1060
+ if (v < bv) {
1061
+ bv = v;
1062
+ bc = j;
1063
+ }
1064
+ }
1065
+ assign[blk] = bc;
1066
+ }
1067
+ clusters = clusters.map(() => new Float64Array(total));
1068
+ for (const blk of used) {
1069
+ const cl = clusters[assign[blk]];
1070
+ for (let e = starts[blk]; e < starts[blk + 1]; e += 2)
1071
+ cl[entries[e]] += entries[e + 1];
1072
+ }
1073
+ }
1074
+ const remap = new Int32Array(k).fill(-1), kept = [];
1075
+ for (const blk of used)
1076
+ if (remap[assign[blk]] < 0) {
1077
+ remap[assign[blk]] = kept.length;
1078
+ kept.push(clusters[assign[blk]]);
1079
+ }
1080
+ const groups = new Int32Array(nb);
1081
+ for (const blk of used)
1082
+ groups[blk] = remap[assign[blk]];
1083
+ const b = kept.reduce((sum, cl) => sum + clusterBits(cl), 0) + nb;
1084
+ if (b < bestBits) {
1085
+ bestBits = b;
1086
+ best = [groups, kept];
1087
+ }
1088
+ else
1089
+ break;
1090
+ }
1091
+ if (!best)
1092
+ return null;
1093
+ const [groups, kept] = best;
1094
+ return [groups, kept.map(cl => sizes.map((size, c) => Int32Array.from(cl.subarray(offsets[c], offsets[c] + size)))), bestBits];
1095
+ }
1096
+ function writeImage(w, pixels, width, isMain) {
1097
+ const tokens = tokenize(pixels, width);
1098
+ const cacheBits = isMain ? bestCacheBits(tokens, pixels) : 0;
1099
+ const stream = withCache(tokens, pixels, cacheBits), counts = histograms(stream, cacheBits);
1100
+ const best = entropyBits(counts);
1101
+ const height = pixels.length / width;
1102
+ let groups = null, groupCounts = [counts], prefixBits = 0;
1103
+ if (isMain && pixels.length > 4096) {
1104
+ const r = prefixGroups(stream, width, height, cacheBits, 4);
1105
+ if (r && r[2] < best) {
1106
+ [groups, groupCounts] = r;
1107
+ prefixBits = 4;
1108
+ }
1109
+ }
1110
+ if (cacheBits) {
1111
+ w.write(1, 1);
1112
+ w.write(cacheBits, 4);
1113
+ }
1114
+ else
1115
+ w.write(0, 1);
1116
+ if (isMain) {
1117
+ w.write(groups ? 1 : 0, 1);
1118
+ if (groups) {
1119
+ w.write(prefixBits - 2, 3);
1120
+ writeImage(w, Uint32Array.from(groups, g => g << 8), subSize(width, prefixBits), false);
1121
+ }
1122
+ }
1123
+ const { ops, values, distances, count } = stream;
1124
+ const codes = groupCounts.map(g => g.map(c => writeCode(w, c)));
1125
+ const bw = subSize(width, prefixBits);
1126
+ let group = codes[0];
1127
+ for (let k = 0, i = 0; k < count; k++) {
1128
+ if (groups) {
1129
+ const x = i % width, y = (i / width) | 0;
1130
+ group = codes[groups[(y >> prefixBits) * bw + (x >> prefixBits)]];
1131
+ }
853
1132
  const v = values[k];
854
1133
  if (ops[k] === 0) {
855
- writeSymbol(w, codes[0], v >> 8 & 255);
856
- writeSymbol(w, codes[1], v >> 16 & 255);
857
- writeSymbol(w, codes[2], v & 255);
858
- writeSymbol(w, codes[3], v >>> 24);
1134
+ writeSymbol(w, group[0], v >> 8 & 255);
1135
+ writeSymbol(w, group[1], v >> 16 & 255);
1136
+ writeSymbol(w, group[2], v & 255);
1137
+ writeSymbol(w, group[3], v >>> 24);
1138
+ i++;
859
1139
  }
860
1140
  else if (ops[k] === 1) {
861
1141
  const length = prefixEncode(v), distance = prefixEncode(distances[k]);
862
- writeSymbol(w, codes[0], NUM_LITERAL_CODES + length.symbol);
1142
+ writeSymbol(w, group[0], NUM_LITERAL_CODES + length.symbol);
863
1143
  w.write(length.extra, length.bits);
864
- writeSymbol(w, codes[4], distance.symbol);
1144
+ writeSymbol(w, group[4], distance.symbol);
865
1145
  w.write(distance.extra, distance.bits);
1146
+ i += v;
1147
+ }
1148
+ else {
1149
+ writeSymbol(w, group[0], NUM_LITERAL_CODES + NUM_LENGTH_CODES + v);
1150
+ i++;
866
1151
  }
867
- else
868
- writeSymbol(w, codes[0], NUM_LITERAL_CODES + NUM_LENGTH_CODES + v);
869
1152
  }
870
1153
  }
871
1154
  const subPixels = (a, b) => ((a | 0x00ff00ff) - (b & 0xff00ff00) & 0xff00ff00 | (a | 0xff00ff00) - (b & 0x00ff00ff) & 0x00ff00ff) >>> 0;
@@ -916,6 +1199,19 @@ function applyPredictor(p, width, height, bits) {
916
1199
  export function encode(argb, width, height) {
917
1200
  if (width < 1 || height < 1 || width > 16384 || height > 16384)
918
1201
  throw new RangeError('VP8L: dimensions must be 1-16384');
1202
+ const colors = new Map();
1203
+ for (let i = 0; i < argb.length && colors.size <= 256; i++)
1204
+ if (!colors.has(argb[i]))
1205
+ colors.set(argb[i], colors.size);
1206
+ if (colors.size > 256)
1207
+ return encodeWith(argb, width, height, null);
1208
+ const indexed = encodeWith(argb, width, height, colors);
1209
+ if (colors.size <= 16)
1210
+ return indexed;
1211
+ const predicted = encodeWith(argb, width, height, null);
1212
+ return predicted.length < indexed.length ? predicted : indexed;
1213
+ }
1214
+ function encodeWith(argb, width, height, colors) {
919
1215
  const w = new BitWriter();
920
1216
  let hasAlpha = false;
921
1217
  for (let i = 0; i < argb.length; i++)
@@ -928,12 +1224,8 @@ export function encode(argb, width, height) {
928
1224
  w.write(height - 1, 14);
929
1225
  w.write(hasAlpha ? 1 : 0, 1);
930
1226
  w.write(0, 3);
931
- const colors = new Map();
932
- for (let i = 0; i < argb.length && colors.size <= 256; i++)
933
- if (!colors.has(argb[i]))
934
- colors.set(argb[i], colors.size);
935
1227
  let pixels, codedWidth = width;
936
- if (colors.size <= 256) {
1228
+ if (colors) {
937
1229
  const palette = Uint32Array.from([...colors.keys()].sort((a, b) => a - b));
938
1230
  palette.forEach((c, i) => colors.set(c, i));
939
1231
  const bits = palette.length <= 2 ? 3 : palette.length <= 4 ? 2 : palette.length <= 16 ? 1 : 0;
@@ -955,11 +1247,17 @@ export function encode(argb, width, height) {
955
1247
  }
956
1248
  else {
957
1249
  pixels = argb.slice();
958
- w.write(1, 1);
959
- w.write(2, 2);
960
- for (let i = 0; i < pixels.length; i++) {
961
- const p = pixels[i], green = p >> 8 & 255;
962
- pixels[i] = (p & 0xff00ff00 | (p | 0x0000ff00) - (green << 16 | green) & 0x00ff00ff) >>> 0;
1250
+ let redBlue = false;
1251
+ for (let i = 0; i < pixels.length && !redBlue; i++)
1252
+ if (pixels[i] & 0x00ff00ff)
1253
+ redBlue = true;
1254
+ if (redBlue) {
1255
+ w.write(1, 1);
1256
+ w.write(2, 2);
1257
+ for (let i = 0; i < pixels.length; i++) {
1258
+ const p = pixels[i], green = p >> 8 & 255;
1259
+ pixels[i] = (p & 0xff00ff00 | (p | 0x0000ff00) - (green << 16 | green) & 0x00ff00ff) >>> 0;
1260
+ }
963
1261
  }
964
1262
  const bits = 4;
965
1263
  w.write(1, 1);