imagescript 3.4.0 → 3.6.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.
@@ -0,0 +1,110 @@
1
+ /*!
2
+ * Palettes of the AV1 encoder: the colors of a block (by k-means, from its most frequent colors), the color indices'
3
+ * contexts and order (like the decoder's readPalIndices, ported from dav1d: Copyright (c) 2018-2021, VideoLAN and
4
+ * dav1d authors, Copyright (c) 2018, Two Orioles, LLC, BSD-2-Clause License, see THIRD_PARTY_NOTICES.md), their bits
5
+ */
6
+ export function paletteColors(colors, weights, k) {
7
+ const order = colors.map((_, i) => i).sort((a, b) => weights[b] - weights[a]);
8
+ let centers = order.slice(0, k).map(i => colors[i].slice());
9
+ if (colors.length > k) {
10
+ const dims = colors[0].length, assign = new Int32Array(colors.length);
11
+ for (let iter = 0; iter < 8; iter++) {
12
+ let changed = false;
13
+ for (let i = 0; i < colors.length; i++) {
14
+ let best = 0, bestD = Infinity;
15
+ for (let c = 0; c < centers.length; c++) {
16
+ let d = 0;
17
+ for (let e = 0; e < dims; e++)
18
+ d += (colors[i][e] - centers[c][e]) ** 2;
19
+ if (d < bestD) {
20
+ bestD = d;
21
+ best = c;
22
+ }
23
+ }
24
+ if (assign[i] !== best || !iter)
25
+ changed = true;
26
+ assign[i] = best;
27
+ }
28
+ if (!changed)
29
+ break;
30
+ const sums = centers.map(() => new Float64Array(dims + 1));
31
+ for (let i = 0; i < colors.length; i++) {
32
+ const s = sums[assign[i]];
33
+ for (let e = 0; e < dims; e++)
34
+ s[e] += colors[i][e] * weights[i];
35
+ s[dims] += weights[i];
36
+ }
37
+ centers = centers.map((c, j) => sums[j][dims] ? Array.from({ length: dims }, (_, e) => Math.round(sums[j][e] / sums[j][dims])) : c);
38
+ }
39
+ }
40
+ centers.sort((a, b) => a[0] - b[0] || (a[1] ?? 0) - (b[1] ?? 0));
41
+ return centers.filter((c, i) => !i || c.some((v, e) => v !== centers[i - 1][e]));
42
+ }
43
+ const ORDER = new Uint8Array(8);
44
+ export function colorRanks(t, stride, w, h, visit) {
45
+ const order = ORDER;
46
+ for (let i = 1; i < w + h - 1; i++) {
47
+ const first = Math.min(i, w - 1), last = Math.max(0, i - h + 1);
48
+ for (let j = first; j >= last; j--) {
49
+ const p = (i - j) * stride + j, v = t[p];
50
+ let ctx, n = 0;
51
+ if (!j) {
52
+ ctx = 0;
53
+ order[n++] = t[p - stride];
54
+ }
55
+ else if (i === j) {
56
+ ctx = 0;
57
+ order[n++] = t[p - 1];
58
+ }
59
+ else {
60
+ const l = t[p - 1], tp = t[p - stride], tl = t[p - stride - 1];
61
+ const sameTL = tp === l, sameTTl = tp === tl, sameLTl = l === tl;
62
+ if (sameTL && sameTTl && sameLTl) {
63
+ ctx = 4;
64
+ order[n++] = tp;
65
+ }
66
+ else if (sameTL) {
67
+ ctx = 3;
68
+ order[n++] = tp;
69
+ order[n++] = tl;
70
+ }
71
+ else if (sameTTl || sameLTl) {
72
+ ctx = 2;
73
+ order[n++] = tl;
74
+ order[n++] = sameTTl ? l : tp;
75
+ }
76
+ else {
77
+ ctx = 1;
78
+ order[n++] = Math.min(tp, l);
79
+ order[n++] = Math.max(tp, l);
80
+ order[n++] = tl;
81
+ }
82
+ }
83
+ let rank = -1;
84
+ for (let r = 0; r < n; r++)
85
+ if (order[r] === v) {
86
+ rank = r;
87
+ break;
88
+ }
89
+ if (rank < 0) {
90
+ rank = n;
91
+ for (let c = 0; c < v; c++) {
92
+ let listed = false;
93
+ for (let r = 0; r < n; r++)
94
+ if (order[r] === c)
95
+ listed = true;
96
+ if (!listed)
97
+ rank++;
98
+ }
99
+ }
100
+ visit(ctx, rank);
101
+ }
102
+ }
103
+ }
104
+ const FIRST_BITS = [0.4, 0.8, 0.5, 0.3, 0.08];
105
+ const RANK_BITS = [0, 2.2, 3.2, 3.8, 4.3, 4.7, 5, 5.3];
106
+ export function colorIndexBits(t, stride, w, h, palSz) {
107
+ let bits = Math.log2(palSz);
108
+ colorRanks(t, stride, w, h, (ctx, rank) => { bits += rank ? RANK_BITS[rank] : FIRST_BITS[ctx]; });
109
+ return bits;
110
+ }
@@ -0,0 +1,224 @@
1
+ import { encodeAV1 } from "./av1/encode.js";
2
+ const QINDEX = [
3
+ 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112,
4
+ 116, 120, 124, 128, 132, 136, 140, 144, 148, 152, 156, 160, 164, 168, 172, 176, 180, 184, 188, 192, 196, 200, 204, 208,
5
+ 212, 216, 220, 224, 228, 232, 236, 240, 244, 249, 255
6
+ ];
7
+ const qindex = (quality) => QINDEX[Math.round((100 - Math.max(0, Math.min(100, quality))) * 63 / 100)];
8
+ const KR = 0.299, KB = 0.114, KG = 1 - KR - KB, CICP = [1, 13, 6];
9
+ function toYUV(rgba, width, height, subsampled) {
10
+ const n = width * height, y = new Uint8Array(n);
11
+ const u = new Float64Array(n), v = new Float64Array(n);
12
+ for (let i = 0; i < n; i++) {
13
+ const r = rgba[4 * i], g = rgba[4 * i + 1], b = rgba[4 * i + 2];
14
+ const l = KR * r + KG * g + KB * b;
15
+ y[i] = Math.round(l);
16
+ u[i] = (b - l) / (2 * (1 - KB)) + 128;
17
+ v[i] = (r - l) / (2 * (1 - KR)) + 128;
18
+ }
19
+ const byte = (x) => x < 0 ? 0 : x > 255 ? 255 : Math.round(x);
20
+ if (!subsampled) {
21
+ const cu = new Uint8Array(n), cv = new Uint8Array(n);
22
+ for (let i = 0; i < n; i++) {
23
+ cu[i] = byte(u[i]);
24
+ cv[i] = byte(v[i]);
25
+ }
26
+ return [y, cu, cv];
27
+ }
28
+ const cw = width + 1 >> 1, ch = height + 1 >> 1, cu = new Uint8Array(cw * ch), cv = new Uint8Array(cw * ch);
29
+ for (let cy = 0; cy < ch; cy++) {
30
+ for (let cx = 0; cx < cw; cx++) {
31
+ let su = 0, sv = 0, k = 0;
32
+ for (let dy = 0; dy < 2 && 2 * cy + dy < height; dy++) {
33
+ for (let dx = 0; dx < 2 && 2 * cx + dx < width; dx++, k++) {
34
+ const i = (2 * cy + dy) * width + 2 * cx + dx;
35
+ su += u[i];
36
+ sv += v[i];
37
+ }
38
+ }
39
+ cu[cy * cw + cx] = byte(su / k);
40
+ cv[cy * cw + cx] = byte(sv / k);
41
+ }
42
+ }
43
+ return [y, cu, cv];
44
+ }
45
+ function fillTransparent(rgba, width, height) {
46
+ const out = rgba.slice();
47
+ const levels = [];
48
+ let w = width, h = height, sum = new Float64Array(w * h * 3), n = new Float64Array(w * h);
49
+ for (let i = 0; i < w * h; i++) {
50
+ if (!rgba[4 * i + 3])
51
+ continue;
52
+ n[i] = 1;
53
+ for (let c = 0; c < 3; c++)
54
+ sum[3 * i + c] = rgba[4 * i + c];
55
+ }
56
+ levels.push({ w, h, sum, n });
57
+ while (w > 1 || h > 1) {
58
+ const pw = w + 1 >> 1, ph = h + 1 >> 1, ps = new Float64Array(pw * ph * 3), pn = new Float64Array(pw * ph);
59
+ for (let y = 0; y < h; y++) {
60
+ for (let x = 0; x < w; x++) {
61
+ const i = y * w + x, j = (y >> 1) * pw + (x >> 1);
62
+ pn[j] += n[i];
63
+ for (let c = 0; c < 3; c++)
64
+ ps[3 * j + c] += sum[3 * i + c];
65
+ }
66
+ }
67
+ levels.push({ w: w = pw, h: h = ph, sum: sum = ps, n: n = pn });
68
+ }
69
+ let colors = new Float64Array(3);
70
+ for (let c = 0; c < 3; c++)
71
+ colors[c] = n[0] ? sum[c] / n[0] : 0;
72
+ for (let l = levels.length - 2; l >= 0; l--) {
73
+ const { w, h, sum, n } = levels[l], pw = levels[l + 1].w, next = new Float64Array(w * h * 3);
74
+ for (let y = 0; y < h; y++) {
75
+ for (let x = 0; x < w; x++) {
76
+ const i = y * w + x, j = (y >> 1) * pw + (x >> 1);
77
+ for (let c = 0; c < 3; c++)
78
+ next[3 * i + c] = n[i] ? sum[3 * i + c] / n[i] : colors[3 * j + c];
79
+ }
80
+ }
81
+ colors = next;
82
+ }
83
+ const unknown = [];
84
+ for (let i = 0; i < width * height; i++)
85
+ if (!rgba[4 * i + 3])
86
+ unknown.push(i);
87
+ for (let pass = 0; pass < 4; pass++) {
88
+ for (const i of unknown) {
89
+ const x = i % width, y = (i - x) / width;
90
+ for (let c = 0; c < 3; c++) {
91
+ let s = colors[3 * i + c], k = 1;
92
+ if (x) {
93
+ s += colors[3 * (i - 1) + c];
94
+ k++;
95
+ }
96
+ if (x + 1 < width) {
97
+ s += colors[3 * (i + 1) + c];
98
+ k++;
99
+ }
100
+ if (y) {
101
+ s += colors[3 * (i - width) + c];
102
+ k++;
103
+ }
104
+ if (y + 1 < height) {
105
+ s += colors[3 * (i + width) + c];
106
+ k++;
107
+ }
108
+ colors[3 * i + c] = s / k;
109
+ }
110
+ }
111
+ }
112
+ for (const i of unknown)
113
+ for (let c = 0; c < 3; c++)
114
+ out[4 * i + c] = Math.round(colors[3 * i + c]);
115
+ return out;
116
+ }
117
+ const ascii = (s) => Array.from(s, c => c.charCodeAt(0));
118
+ const u16 = (v) => [v >> 8 & 255, v & 255];
119
+ const u32 = (v) => [v >>> 24, v >> 16 & 255, v >> 8 & 255, v & 255];
120
+ const box = (type, ...content) => {
121
+ const body = content.flat();
122
+ return [...u32(8 + body.length), ...ascii(type), ...body];
123
+ };
124
+ const fullBox = (type, version, flags, ...content) => box(type, [version, flags >> 16 & 255, flags >> 8 & 255, flags & 255], ...content);
125
+ function av1C(data) {
126
+ let size = 0, i = 1, shift = 0;
127
+ for (;; i++) {
128
+ size += (data[i] & 0x7f) << shift;
129
+ shift += 7;
130
+ if (!(data[i] & 0x80))
131
+ break;
132
+ }
133
+ const seqObu = Array.from(data.subarray(0, i + 1 + size));
134
+ const profile = data[i + 1] >> 5, level = (data[i + 1] & 7) << 2 | data[i + 2] >> 6;
135
+ const monochrome = profile !== 1 && seqMonochrome(data, i + 1);
136
+ return box('av1C', [0x81, profile << 5 | level, (monochrome ? 0x10 : 0) | (profile === 1 ? 0 : 0x0c), 0], seqObu);
137
+ }
138
+ function seqMonochrome(d, o) {
139
+ let bit = o * 8;
140
+ const read = (n) => {
141
+ let v = 0;
142
+ for (let k = 0; k < n; k++, bit++)
143
+ v = v * 2 + (d[bit >> 3] >> (7 - (bit & 7)) & 1);
144
+ return v;
145
+ };
146
+ read(3 + 1 + 1 + 5);
147
+ const wb = read(4) + 1, hb = read(4) + 1;
148
+ read(wb + hb + 6);
149
+ read(1);
150
+ return !!read(1);
151
+ }
152
+ export function encode(rgba, width, height, { quality, alphaQuality, subsampling, effort, exif }) {
153
+ if (width < 1 || height < 1)
154
+ throw new RangeError('AVIF: dimensions must be at least 1');
155
+ if (width > 65536 || height > 65536)
156
+ throw new RangeError('AVIF: dimensions must be at most 65536');
157
+ let opaque = true;
158
+ for (let i = 3; i < rgba.length; i += 4)
159
+ if (rgba[i] !== 255) {
160
+ opaque = false;
161
+ break;
162
+ }
163
+ const original = rgba;
164
+ if (!opaque && qindex(quality))
165
+ rgba = fillTransparent(rgba, width, height);
166
+ let gray = true;
167
+ for (let i = 0; i < rgba.length; i += 4)
168
+ if (rgba[i] !== rgba[i + 1] || rgba[i] !== rgba[i + 2]) {
169
+ gray = false;
170
+ break;
171
+ }
172
+ const lossless = !qindex(quality) && !gray, subsampled = subsampling === '4:2:0' && !lossless && !gray;
173
+ const cicp = lossless ? [1, 13, 0] : CICP;
174
+ const planes = gray ? [Uint8Array.from({ length: width * height }, (_, i) => rgba[4 * i])]
175
+ : lossless ? [1, 2, 0].map(c => Uint8Array.from({ length: width * height }, (_, i) => rgba[4 * i + c])) : toYUV(rgba, width, height, subsampled);
176
+ const color = encodeAV1({ planes, width, height, layout: gray ? 0 : subsampled ? 1 : 3, cicp }, { qidx: qindex(quality), effort });
177
+ let alpha = null;
178
+ if (!opaque) {
179
+ const a = new Uint8Array(width * height);
180
+ for (let i = 0; i < a.length; i++)
181
+ a[i] = original[4 * i + 3];
182
+ alpha = encodeAV1({ planes: [a], width, height, layout: 0, cicp: [2, 2, 2] }, { qidx: qindex(alphaQuality), effort });
183
+ }
184
+ const profile = subsampled || gray ? 'MA1B' : 'MA1A';
185
+ const ftyp = box('ftyp', ascii('avif'), u32(0), ascii('avif'), ascii('mif1'), ascii('miaf'), ascii(profile));
186
+ const hdlr = fullBox('hdlr', 0, 0, u32(0), ascii('pict'), u32(0), u32(0), u32(0), [0]);
187
+ const pitm = fullBox('pitm', 0, 0, u16(1));
188
+ const items = [{ type: 'av01', name: 'Color', data: [color] }];
189
+ if (alpha)
190
+ items.push({ type: 'av01', name: 'Alpha', data: [alpha] });
191
+ if (exif?.length)
192
+ items.push({ type: 'Exif', name: 'Exif', data: [u32(0), exif] });
193
+ const sizes = items.map(item => item.data.reduce((n, d) => n + d.length, 0));
194
+ const infe = (id, type, name) => fullBox('infe', 2, 0, u16(id), u16(0), ascii(type), ascii(name), [0]);
195
+ const iinf = fullBox('iinf', 0, 0, u16(items.length), ...items.map((item, i) => infe(i + 1, item.type, item.name)));
196
+ const exifId = exif?.length ? items.length : 0;
197
+ const iref = alpha || exifId ? fullBox('iref', 0, 0, alpha ? box('auxl', u16(2), u16(1), u16(1)) : [], exifId ? box('cdsc', u16(exifId), u16(1), u16(1)) : []) : [];
198
+ const ispe = fullBox('ispe', 0, 0, u32(width), u32(height));
199
+ const colr = box('colr', ascii('nclx'), u16(cicp[0]), u16(cicp[1]), u16(cicp[2]), [0x80]);
200
+ const pixi = (channels) => fullBox('pixi', 0, 0, [channels], new Array(channels).fill(8));
201
+ const auxC = fullBox('auxC', 0, 0, ascii('urn:mpeg:mpegB:cicp:systems:auxiliary:alpha'), [0]);
202
+ const ipco = box('ipco', ispe, av1C(color), colr, pixi(gray ? 1 : 3), alpha ? av1C(alpha) : [], alpha ? pixi(1) : [], alpha ? auxC : []);
203
+ const ipma = fullBox('ipma', 0, 0, u32(alpha ? 2 : 1), u16(1), [4, 1, 0x82, 3, 4], alpha ? [...u16(2), 4, 1, 0x85, 6, 7] : []);
204
+ const iprp = box('iprp', ipco, ipma);
205
+ const ilocFor = (offset) => fullBox('iloc', 0, 0, [0x44, 0x00], u16(items.length), ...items.map((_, i) => {
206
+ const at = offset + sizes.slice(0, i).reduce((n, size) => n + size, 0);
207
+ return [...u16(i + 1), ...u16(0), ...u16(1), ...u32(at), ...u32(sizes[i])];
208
+ }));
209
+ const metaFor = (offset) => fullBox('meta', 0, 0, hdlr, pitm, ilocFor(offset), iinf, iref, iprp);
210
+ const headerSize = ftyp.length + metaFor(0).length + 8;
211
+ const head = [...ftyp, ...metaFor(headerSize)];
212
+ const mdatSize = 8 + sizes.reduce((n, size) => n + size, 0);
213
+ const out = new Uint8Array(head.length + mdatSize);
214
+ out.set(head);
215
+ out.set([...u32(mdatSize), ...ascii('mdat')], head.length);
216
+ let at = head.length + 8;
217
+ for (const item of items) {
218
+ for (const d of item.data) {
219
+ out.set(d, at);
220
+ at += d.length;
221
+ }
222
+ }
223
+ return out;
224
+ }
@@ -1,6 +1,14 @@
1
1
  import { TF_PQ, TF_HLG, PRI_BT2100, PRI_P3, EXTRA_ALPHA, EXTRA_SPOT, EXTRA_BLACK } from "./headers.js";
2
2
  import { toSRGB, hdrToLinear, REFERENCE_WHITE } from "../hdr.js";
3
- const srgbEncode = (v) => v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055;
3
+ const byte = (v) => v <= 0 ? 0 : v >= 1 ? 255 : Math.round(v * 255);
4
+ const [P0, P1, P2, P3, P4] = [-5.135152395e-04, 5.287254571e-03, 3.903842876e-01, 1.474205315e+00, 7.352629620e-01].map(Math.fround);
5
+ const [Q0, Q1, Q2, Q3, Q4] = [1.004519624e-02, 3.036675394e-01, 1.340816930e+00, 9.258482155e-01, 2.424867759e-02].map(Math.fround);
6
+ const srgbEncode = (v) => {
7
+ if (v <= 0.0031308)
8
+ return 12.92 * v;
9
+ const x = Math.sqrt(v);
10
+ return ((((P4 * x + P3) * x + P2) * x + P1) * x + P0) / ((((Q4 * x + Q3) * x + Q2) * x + Q1) * x + Q0);
11
+ };
4
12
  export class ColorOutput {
5
13
  image;
6
14
  toneMapping;
@@ -99,18 +107,28 @@ export class ColorOutput {
99
107
  }
100
108
  else {
101
109
  out = new Uint8Array(4 * n);
102
- const byte = (v) => v <= 0 ? 0 : v >= 1 ? 255 : Math.round(v * 255);
103
- for (let i = 0; i < n; i++) {
104
- const a = premultiplied ? Math.max(alpha[i], 2 ** -26) : 1;
105
- out[4 * i] = byte(r[i] / a);
106
- out[4 * i + 1] = byte(g[i] / a);
107
- out[4 * i + 2] = byte(b[i] / a);
108
- out[4 * i + 3] = 255;
110
+ if (premultiplied) {
111
+ for (let i = 0, o = 0; i < n; i++, o += 4) {
112
+ const a = Math.max(alpha[i], 2 ** -26);
113
+ out[o] = byte(r[i] / a);
114
+ out[o + 1] = byte(g[i] / a);
115
+ out[o + 2] = byte(b[i] / a);
116
+ }
117
+ }
118
+ else {
119
+ for (let i = 0, o = 0; i < n; i++, o += 4) {
120
+ out[o] = byte(r[i]);
121
+ out[o + 1] = byte(g[i]);
122
+ out[o + 2] = byte(b[i]);
123
+ }
109
124
  }
110
125
  }
111
126
  if (alpha)
112
- for (let i = 0; i < n; i++)
113
- out[4 * i + 3] = alpha[i] <= 0 ? 0 : alpha[i] >= 1 ? 255 : Math.round(alpha[i] * 255);
127
+ for (let i = 0, o = 3; i < n; i++, o += 4)
128
+ out[o] = byte(alpha[i]);
129
+ else
130
+ for (let o = 3; o < out.length; o += 4)
131
+ out[o] = 255;
114
132
  return out;
115
133
  }
116
134
  }
@@ -80,7 +80,7 @@ export function dct(io, o, n, scratch, s, inverse) {
80
80
  }
81
81
  }
82
82
  }
83
- const work = { row: new Float64Array(256), scratch: new Float64Array(256), col: new Float64Array(256 * 2) };
83
+ const work = { row: new Float64Array(256), scratch: new Float64Array(256) };
84
84
  const SEC8 = secHalf(8);
85
85
  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];
@@ -185,43 +185,8 @@ export function dct2d(b, inverse) {
185
185
  }
186
186
  for (let y = 0; y < h; y++)
187
187
  rowDct(y, w);
188
- const size = Math.min(w, h);
189
- const transposeSquares = () => {
190
- for (let by = 0; by < h; by += size) {
191
- for (let bx = 0; bx < w; bx += size) {
192
- for (let dy = 0; dy < size; dy++) {
193
- for (let dx = dy + 1; dx < size; dx++) {
194
- const p = at(bx + dx, by + dy), q = at(bx + dy, by + dx), t = buf[p];
195
- buf[p] = buf[q];
196
- buf[q] = t;
197
- }
198
- }
199
- }
200
- }
201
- };
202
- transposeSquares();
203
- if (size === h) {
204
- for (let y = 0; y < h; y++)
205
- for (let x0 = 0; x0 < w; x0 += h)
206
- rowDct(y, h, x0);
207
- }
208
- else {
209
- const col = work.col, scratch = work.scratch;
210
- for (let y = 0; y < w; y++) {
211
- for (let k = 0; k < h / size; k++) {
212
- const p = at(0, y + k * size);
213
- for (let x = 0; x < w; x++)
214
- col[k * w + x] = buf[p + x];
215
- }
216
- dct(col, 0, h, scratch, 0, inverse);
217
- for (let k = 0; k < h / size; k++) {
218
- const p = at(0, y + k * size);
219
- for (let x = 0; x < w; x++)
220
- buf[p + x] = col[k * w + x];
221
- }
222
- }
223
- }
224
- transposeSquares();
188
+ for (let x = 0; x < w; x++)
189
+ colDct(x, h);
225
190
  }
226
191
  const SCALE_F = [
227
192
  1.0000000000000000, 0.9996047255830407, 0.9984194528776054, 0.9964458326264695, 0.9936866130906366,
@@ -449,6 +449,8 @@ export class EntropyDecoder {
449
449
  const n = (config.splitExponent - inToken + ((token - config.split) >>> inToken)) & 31;
450
450
  const low = token & ((1 << config.lsb) - 1);
451
451
  const high = (token >>> config.lsb) & ((1 << config.msb) - 1) | 1 << config.msb;
452
+ if (n + config.msb + config.lsb < 31)
453
+ return ((high << n | r.bits(n)) << config.lsb) | low;
452
454
  return ((high * 2 ** n + r.bits(n)) * 2 ** config.lsb + low) >>> 0;
453
455
  }
454
456
  read(r, ctx, distMultiplier = 0) {
@@ -457,34 +459,36 @@ export class EntropyDecoder {
457
459
  readClustered(r, cluster, distMultiplier = 0) {
458
460
  if (!this.lz77)
459
461
  return this.uint(r, this.configs[cluster], this.symbol(r, cluster));
462
+ if (this.toCopy === 0)
463
+ return this.readLz77(r, cluster, distMultiplier);
464
+ const window = this.window, v = window[this.copyPos++ & WINDOW_MASK];
465
+ this.toCopy--;
466
+ window[this.decoded++ & WINDOW_MASK] = v;
467
+ return v;
468
+ }
469
+ readLz77(r, cluster, distMultiplier) {
460
470
  const window = this.window ??= new Uint32Array(1 << 20);
461
471
  let v;
462
- if (this.toCopy > 0) {
472
+ const token = this.symbol(r, cluster);
473
+ if (token >= this.minSymbol) {
474
+ if (this.decoded === 0)
475
+ throw new Error('JPEG XL: LZ77 copy before any value');
476
+ const distCluster = this.clusters[this.clusters.length - 1];
477
+ this.toCopy = this.uint(r, this.lenConfig, token - this.minSymbol) + this.minLength;
478
+ let distance = this.uint(r, this.configs[distCluster], this.symbol(r, distCluster));
479
+ if (distMultiplier) {
480
+ if (distance < 120)
481
+ distance = Math.max(SPECIAL_DISTANCES[distance * 2] + distMultiplier * SPECIAL_DISTANCES[distance * 2 + 1] - 1, 0);
482
+ else
483
+ distance -= 120;
484
+ }
485
+ distance = Math.min(Math.min(distance, WINDOW_MASK) + 1, this.decoded);
486
+ this.copyPos = this.decoded - distance;
463
487
  v = window[this.copyPos++ & WINDOW_MASK];
464
488
  this.toCopy--;
465
489
  }
466
- else {
467
- const token = this.symbol(r, cluster);
468
- if (token >= this.minSymbol) {
469
- if (this.decoded === 0)
470
- throw new Error('JPEG XL: LZ77 copy before any value');
471
- const distCluster = this.clusters[this.clusters.length - 1];
472
- this.toCopy = this.uint(r, this.lenConfig, token - this.minSymbol) + this.minLength;
473
- let distance = this.uint(r, this.configs[distCluster], this.symbol(r, distCluster));
474
- if (distMultiplier) {
475
- if (distance < 120)
476
- distance = Math.max(SPECIAL_DISTANCES[distance * 2] + distMultiplier * SPECIAL_DISTANCES[distance * 2 + 1] - 1, 0);
477
- else
478
- distance -= 120;
479
- }
480
- distance = Math.min(Math.min(distance, WINDOW_MASK) + 1, this.decoded);
481
- this.copyPos = this.decoded - distance;
482
- v = window[this.copyPos++ & WINDOW_MASK];
483
- this.toCopy--;
484
- }
485
- else
486
- v = this.uint(r, this.configs[cluster], token);
487
- }
490
+ else
491
+ v = this.uint(r, this.configs[cluster], token);
488
492
  window[this.decoded++ & WINDOW_MASK] = v;
489
493
  return v;
490
494
  }