imagescript 3.4.0 → 3.5.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,1512 @@
1
+ import { SymbolEncoder } from "./msac-enc.js";
2
+ import { RESTORATION_NONE } from "./obu.js";
3
+ import { HeaderWriter, obu, writeSequenceHeader, writeFrameHeader, OBU_FRAME } from "./obu-enc.js";
4
+ import { Frame } from "./decode.js";
5
+ import { CDF, BLOCK_DIMENSIONS, TXFM_DIMENSIONS, MAX_TXFM_SIZE_FOR_BS, AL_PART_CTX, BLOCK_SIZES, PARTITION_TYPE_COUNT, INTRA_MODE_CONTEXT, TXTP_FROM_UVMODE, TX_TYPES_PER_SET, LO_CTX_OFFSETS, SKIP_CTX, CFL_ALLOWED_MASK, BL_64X64, BL_8X8, PARTITION_NONE, PARTITION_H, PARTITION_V, PARTITION_SPLIT, PARTITION_T_TOP_SPLIT, PARTITION_T_LEFT_SPLIT, PARTITION_T_RIGHT_SPLIT, PARTITION_H4, PARTITION_V4, DC_PRED, VERT_PRED, HOR_PRED, VERT_LEFT_PRED, SMOOTH_PRED, SMOOTH_V_PRED, SMOOTH_H_PRED, PAETH_PRED, CFL_PRED, TX_4X4, TX_64X64, TX_16X16, RTX_4X8, DCT_DCT, IDTX, WHT_WHT, EDGE_I444_TOP_HAS_RIGHT, EDGE_I444_LEFT_HAS_BOTTOM, EDGE_I420_TOP_HAS_RIGHT, EDGE_I420_LEFT_HAS_BOTTOM, edgeTree, defaultCdfs, scan, dequant } from "./tables.js";
6
+ import { prepareEdges, predict, preparedAngle, cflAc, cflPredict, ANGLE_USE_EDGE_FILTER, ANGLE_SMOOTH_EDGE } from "./ipred.js";
7
+ import { inverseTransformAdd } from "./itx.js";
8
+ import { forwardTransform, forwardWht, pixelEnergy } from "./fdct.js";
9
+ import { deblock } from "./loopfilter.js";
10
+ import { cdef } from "./cdef.js";
11
+ import { paletteColors, colorRanks, colorIndexBits } from "./palette.js";
12
+ const ADST_DCT = 1, DCT_ADST = 2, ADST_ADST = 3;
13
+ const bdim = (bs, i) => BLOCK_DIMENSIONS[bs * 4 + i];
14
+ const tdim = (tx, i) => TXFM_DIMENSIONS[tx * 8 + i];
15
+ const W = 0, H = 1, LW = 2, LH = 3, MIN = 4, MAX = 5, CTX = 7;
16
+ const isDirectional = (mode) => mode >= VERT_PRED && mode <= VERT_LEFT_PRED;
17
+ const smFlag = (mode) => mode === SMOOTH_PRED || mode === SMOOTH_H_PRED || mode === SMOOTH_V_PRED ? ANGLE_SMOOTH_EDGE : 0;
18
+ const ZERO_BITS = 0.6;
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
+ const mostlyFew = (counts, n) => {
22
+ if (counts.length <= 8)
23
+ return true;
24
+ const top = counts.slice().sort((a, b) => b - a);
25
+ let sum = 0;
26
+ for (let i = 0; i < 8; i++)
27
+ sum += top[i];
28
+ return sum >= n * 0.7;
29
+ };
30
+ class TileEncoder {
31
+ f;
32
+ src;
33
+ params;
34
+ seq;
35
+ hdr;
36
+ ssx;
37
+ ssy;
38
+ cdf;
39
+ w = null;
40
+ bx = 0;
41
+ by = 0;
42
+ colStart = 0;
43
+ colEnd = 0;
44
+ rowStart = 0;
45
+ rowEnd = 0;
46
+ dq;
47
+ lambda;
48
+ aMode;
49
+ lMode = new Uint8Array(32);
50
+ aLcoef;
51
+ lLcoef = new Uint8Array(32);
52
+ aCcoef;
53
+ lCcoef = [new Uint8Array(32), new Uint8Array(32)];
54
+ aSkip;
55
+ lSkip = new Uint8Array(32);
56
+ aUvmode;
57
+ lUvmode = new Uint8Array(32);
58
+ aPartition;
59
+ lPartition = new Uint8Array(16);
60
+ aPalSz;
61
+ lPalSz = new Uint8Array(32);
62
+ aPalSzUv;
63
+ lPalSzUv = new Uint8Array(32);
64
+ aPal;
65
+ lPal = new Uint16Array(32 * 24);
66
+ cf = new Int32Array(32 * 32);
67
+ coefs = new Float64Array(32 * 32);
68
+ q = new Int32Array(32 * 32);
69
+ res = new Float64Array(64 * 64);
70
+ levels = new Uint8Array(36 * 36);
71
+ rdoKeep = new Float64Array(32 * 32);
72
+ whtRes = new Int32Array(16);
73
+ whtOut = new Int32Array(16);
74
+ lossless;
75
+ cdefChoice;
76
+ rdoDrop = new Float64Array(32 * 32);
77
+ ac = new Int16Array(32 * 32);
78
+ pairCounts = new Uint32Array(65536);
79
+ bits = 0;
80
+ coded = false;
81
+ constructor(f, src, params) {
82
+ this.f = f;
83
+ this.src = src;
84
+ this.params = params;
85
+ this.seq = f.seq;
86
+ this.hdr = f.hdr;
87
+ this.ssx = f.ssx;
88
+ this.ssy = f.ssy;
89
+ const n = f.b4Stride + 32;
90
+ this.aMode = new Uint8Array(n);
91
+ this.aLcoef = new Uint8Array(n);
92
+ this.aCcoef = [new Uint8Array(n), new Uint8Array(n)];
93
+ this.aSkip = new Uint8Array(n);
94
+ this.aUvmode = new Uint8Array(n);
95
+ this.aPartition = new Uint8Array(n >> 1);
96
+ this.aPalSz = new Uint8Array(n);
97
+ this.aPalSzUv = new Uint8Array(n);
98
+ this.aPal = new Uint16Array(n * 24);
99
+ this.cdefChoice = new Int8Array(f.cdefIdx.length);
100
+ this.lossless = this.hdr.allLossless;
101
+ const q = this.hdr.quant;
102
+ this.dq = [[dequant(0, q.yac, 0), dequant(0, q.yac, 1)], [dequant(0, q.yac + q.udcDelta, 0), dequant(0, q.yac + q.uacDelta, 1)], [dequant(0, q.yac + q.vdcDelta, 0), dequant(0, q.yac + q.vacDelta, 1)]];
103
+ const step = this.dq[0][1] / 8;
104
+ this.lambda = 0.08 * step * step;
105
+ }
106
+ resetAbove() {
107
+ this.aUvmode.fill(DC_PRED);
108
+ this.aMode.fill(DC_PRED);
109
+ this.aPartition.fill(0);
110
+ this.aSkip.fill(0);
111
+ this.aLcoef.fill(0x40);
112
+ this.aCcoef[0].fill(0x40);
113
+ this.aCcoef[1].fill(0x40);
114
+ this.aPalSz.fill(0);
115
+ this.aPalSzUv.fill(0);
116
+ }
117
+ resetLeft() {
118
+ this.lUvmode.fill(DC_PRED);
119
+ this.lMode.fill(DC_PRED);
120
+ this.lPartition.fill(0);
121
+ this.lSkip.fill(0);
122
+ this.lLcoef.fill(0x40);
123
+ this.lCcoef[0].fill(0x40);
124
+ this.lCcoef[1].fill(0x40);
125
+ this.lPalSz.fill(0);
126
+ this.lPalSzUv.fill(0);
127
+ }
128
+ tile(tileRow, tileCol) {
129
+ const f = this.f, t = this.hdr.tiles;
130
+ this.colStart = t.colStarts[tileCol] << 4;
131
+ this.colEnd = Math.min(t.colStarts[tileCol + 1] << 4, f.bw);
132
+ this.rowStart = t.rowStarts[tileRow] << 4;
133
+ this.rowEnd = Math.min(t.rowStarts[tileRow + 1] << 4, f.bh);
134
+ }
135
+ searchTile(tileRow, tileCol) {
136
+ this.tile(tileRow, tileCol);
137
+ const root = edgeTree(false), nodes = [];
138
+ this.resetAbove();
139
+ for (this.by = this.rowStart; this.by < this.rowEnd; this.by += 16) {
140
+ this.resetLeft();
141
+ for (this.bx = this.colStart; this.bx < this.colEnd; this.bx += 16)
142
+ nodes.push(this.search(BL_64X64, root).node);
143
+ }
144
+ return nodes;
145
+ }
146
+ storeTile(tileRow, tileCol, nodes) {
147
+ this.tile(tileRow, tileCol);
148
+ let i = 0;
149
+ for (this.by = this.rowStart; this.by < this.rowEnd; this.by += 16) {
150
+ for (this.bx = this.colStart; this.bx < this.colEnd; this.bx += 16)
151
+ this.walk(BL_64X64, nodes[i++]);
152
+ }
153
+ }
154
+ walk(bl, n) {
155
+ if (n.bp === PARTITION_NONE) {
156
+ const b = n.b, f = this.f;
157
+ this.storeBlock(BLOCK_SIZES[(bl * 10 + PARTITION_NONE) * 2], b);
158
+ if (!b.skip)
159
+ f.cdefIdx[(this.by >> 4) * (f.b4Stride >> 4) + (this.bx >> 4)] = 0;
160
+ return;
161
+ }
162
+ const hsz = 16 >> bl;
163
+ for (let k = 0; k < 4; k++) {
164
+ if (!n.kids[k])
165
+ continue;
166
+ const dx = k & 1 ? hsz : 0, dy = k & 2 ? hsz : 0;
167
+ this.bx += dx;
168
+ this.by += dy;
169
+ this.walk(bl + 1, n.kids[k]);
170
+ this.bx -= dx;
171
+ this.by -= dy;
172
+ }
173
+ }
174
+ writeTile(tileRow, tileCol, nodes) {
175
+ this.tile(tileRow, tileCol);
176
+ const root = edgeTree(false);
177
+ this.cdf = defaultCdfs(this.hdr.quant.yac);
178
+ this.w = new SymbolEncoder(!this.hdr.disableCdfUpdate);
179
+ this.resetAbove();
180
+ let i = 0;
181
+ for (this.by = this.rowStart; this.by < this.rowEnd; this.by += 16) {
182
+ this.resetLeft();
183
+ for (this.bx = this.colStart; this.bx < this.colEnd; this.bx += 16) {
184
+ this.writeSb(BL_64X64, root, nodes[i++]);
185
+ }
186
+ }
187
+ const data = this.w.finish();
188
+ this.w = null;
189
+ return data;
190
+ }
191
+ search(bl, node) {
192
+ const f = this.f, hsz = 16 >> bl;
193
+ const haveH = f.bw > this.bx + hsz, haveV = f.bh > this.by + hsz;
194
+ const split = (quarters) => {
195
+ const kids = [null, null, null, null];
196
+ let cost = 0;
197
+ for (const k of quarters) {
198
+ const dx = k & 1 ? hsz : 0, dy = k & 2 ? hsz : 0;
199
+ this.bx += dx;
200
+ this.by += dy;
201
+ const r = this.search(bl + 1, node.split[k]);
202
+ this.bx -= dx;
203
+ this.by -= dy;
204
+ kids[k] = r.node;
205
+ cost += r.cost;
206
+ }
207
+ return { node: { bp: PARTITION_SPLIT, b: null, kids }, cost };
208
+ };
209
+ if (!haveH && !haveV)
210
+ return split([0]);
211
+ if (!haveH)
212
+ return split([0, 2]);
213
+ if (!haveV)
214
+ return split([0, 1]);
215
+ const bs = BLOCK_SIZES[(bl * 10 + PARTITION_NONE) * 2];
216
+ if (bl === BL_8X8) {
217
+ const r = this.searchBlock(bs, node.o);
218
+ return { node: { bp: PARTITION_NONE, b: r.b, kids: [] }, cost: r.cost };
219
+ }
220
+ const saved = this.saveArea(bl);
221
+ if (bl <= BL_64X64 + 1) {
222
+ const sp = split([0, 1, 2, 3]);
223
+ const deeper = sp.node.kids.filter(k => k && k.bp === PARTITION_SPLIT).length;
224
+ if (this.params.effort < 2 && deeper >= (bl === BL_64X64 ? 2 : 4))
225
+ return { node: sp.node, cost: sp.cost + this.lambda * 2 };
226
+ const spArea = this.saveArea(bl), contexts = this.saveContexts(bs);
227
+ this.restoreArea(bl, saved);
228
+ const none = this.searchBlock(bs, node.o);
229
+ if (none.cost + this.lambda < sp.cost + this.lambda * 2)
230
+ return { node: { bp: PARTITION_NONE, b: none.b, kids: [] }, cost: none.cost + this.lambda };
231
+ this.restoreArea(bl, spArea);
232
+ this.restoreContexts(contexts);
233
+ return { node: sp.node, cost: sp.cost + this.lambda * 2 };
234
+ }
235
+ const none = this.searchBlock(bs, node.o);
236
+ if (none.b.skip && this.params.effort < 2)
237
+ return { node: { bp: PARTITION_NONE, b: none.b, kids: [] }, cost: none.cost + this.lambda };
238
+ const noneArea = this.saveArea(bl);
239
+ this.restoreArea(bl, saved);
240
+ const sp = split([0, 1, 2, 3]);
241
+ if (none.cost + this.lambda < sp.cost + this.lambda * 2) {
242
+ this.restoreArea(bl, noneArea);
243
+ this.modeContexts(bs, none.b);
244
+ return { node: { bp: PARTITION_NONE, b: none.b, kids: [] }, cost: none.cost + this.lambda };
245
+ }
246
+ return { node: sp.node, cost: sp.cost + this.lambda * 2 };
247
+ }
248
+ saveArea(bl) {
249
+ const f = this.f, n = 64 >> (bl - 1);
250
+ return f.planes.map((plane, p) => {
251
+ const sx = p ? this.ssx : 0, sy = p ? this.ssy : 0, stride = f.strides[p];
252
+ const w = n >> sx, h = n >> sy, x0 = this.bx * 4 >> sx, y0 = this.by * 4 >> sy, out = new Uint16Array(w * h);
253
+ for (let y = 0; y < h; y++)
254
+ out.set(plane.subarray((y0 + y) * stride + x0, (y0 + y) * stride + x0 + w), y * w);
255
+ return out;
256
+ });
257
+ }
258
+ restoreArea(bl, saved) {
259
+ const f = this.f, n = 64 >> (bl - 1);
260
+ f.planes.forEach((plane, p) => {
261
+ const sx = p ? this.ssx : 0, sy = p ? this.ssy : 0, stride = f.strides[p];
262
+ const w = n >> sx, h = n >> sy, x0 = this.bx * 4 >> sx, y0 = this.by * 4 >> sy;
263
+ for (let y = 0; y < h; y++)
264
+ plane.set(saved[p].subarray(y * w, y * w + w), (y0 + y) * stride + x0);
265
+ });
266
+ }
267
+ searchBlock(bs, edgeFlags) {
268
+ const f = this.f, layout = f.layout;
269
+ const lw4 = bdim(bs, 2), lh4 = bdim(bs, 3);
270
+ const b = {
271
+ skip: 0, yMode: DC_PRED, yAngle: 0, uvMode: DC_PRED, uvAngle: 0, cflAlpha: [0, 0],
272
+ tx: this.lossless ? TX_4X4 : MAX_TXFM_SIZE_FOR_BS[bs * 4], txtp: this.lossless ? WHT_WHT : DCT_DCT,
273
+ uvtx: this.lossless ? TX_4X4 : MAX_TXFM_SIZE_FOR_BS[bs * 4 + layout],
274
+ palSz: [0, 0], pal: new Uint16Array(24), palIdx: null, palIdxUv: null
275
+ };
276
+ const palAllowed = this.hdr.allowScreenContentTools && Math.max(bdim(bs, 0), bdim(bs, 1)) <= 16 && bdim(bs, 0) + bdim(bs, 1) >= 4;
277
+ const lambda = this.lambda, sadLambda = Math.sqrt(lambda);
278
+ const angles = lw4 + lh4 >= 2 && this.params.effort > 1 ? [-3, -2, -1, 0, 1, 2, 3] : [0];
279
+ const candidates = [];
280
+ for (let mode = DC_PRED; mode <= PAETH_PRED; mode++) {
281
+ for (const angle of isDirectional(mode) ? angles : [0]) {
282
+ b.yMode = mode;
283
+ b.yAngle = angle;
284
+ this.predictLuma(bs, edgeFlags, b);
285
+ candidates.push({ mode, angle, est: this.satd(0, bs) + sadLambda * (mode === DC_PRED ? 2 : 4.5 + (isDirectional(mode) && lw4 + lh4 >= 2 ? 1.5 : 0)) });
286
+ }
287
+ }
288
+ const directional = candidates.filter(c => isDirectional(c.mode)).sort((x, y) => x.est - y.est)[0];
289
+ if (this.params.effort === 1 && lw4 + lh4 >= 2 && directional && directional.est <= 1.2 * Math.min(...candidates.map(c => c.est))) {
290
+ for (const angle of [-3, -2, -1, 1, 2, 3]) {
291
+ b.yMode = directional.mode;
292
+ b.yAngle = angle;
293
+ this.predictLuma(bs, edgeFlags, b);
294
+ candidates.push({ mode: directional.mode, angle, est: this.satd(0, bs) + sadLambda * 6 });
295
+ }
296
+ }
297
+ candidates.sort((x, y) => x.est - y.est);
298
+ let best = Infinity, bestMode = candidates[0], dist = 0, bits = 0, coded = false, kept = null, bestTx = DCT_DCT;
299
+ const close = this.params.effort < 2 ? 1.1 : Infinity;
300
+ const tries = candidates.slice(0, [1, 2, 3][this.params.effort]).filter(c => c.est <= candidates[0].est * close);
301
+ for (const [i, c] of tries.entries()) {
302
+ b.yMode = c.mode;
303
+ b.yAngle = c.angle;
304
+ const d = this.codeLuma(bs, edgeFlags, b);
305
+ const cost = d + lambda * (this.bits + (c.mode === DC_PRED ? 2 : 4.5));
306
+ if (cost < best) {
307
+ best = cost;
308
+ bestMode = c;
309
+ dist = d;
310
+ bits = this.bits;
311
+ coded = this.coded;
312
+ if (i < tries.length - 1)
313
+ kept = this.savePlane(0, bs);
314
+ else
315
+ kept = null;
316
+ }
317
+ }
318
+ b.yMode = bestMode.mode;
319
+ b.yAngle = bestMode.angle;
320
+ if (kept)
321
+ this.restorePlane(0, bs, kept);
322
+ if (tdim(b.tx, MAX) <= TX_16X16 && this.params.effort && coded && !this.lossless) {
323
+ let keptTx = this.savePlane(0, bs), bestTxCost = best + lambda;
324
+ for (const txtp of [ADST_ADST, ADST_DCT, DCT_ADST, IDTX]) {
325
+ b.txtp = txtp;
326
+ const d = this.codeLuma(bs, edgeFlags, b);
327
+ const cost = d + lambda * (this.bits + 2.5 + (b.yMode === DC_PRED ? 2 : 4.5));
328
+ if (cost < bestTxCost) {
329
+ bestTxCost = cost;
330
+ dist = d;
331
+ bits = this.bits + 1.5;
332
+ coded = this.coded;
333
+ keptTx = this.savePlane(0, bs);
334
+ bestTx = txtp;
335
+ }
336
+ }
337
+ b.txtp = bestTx;
338
+ this.restorePlane(0, bs, keptTx);
339
+ }
340
+ if (palAllowed) {
341
+ const r = this.paletteLuma(bs, edgeFlags, b, dist + lambda * (bits + (b.yMode === DC_PRED ? 2 : 4.5)));
342
+ if (r) {
343
+ dist = r.dist;
344
+ bits = r.bits;
345
+ coded = r.coded;
346
+ }
347
+ }
348
+ if (layout) {
349
+ const cflAllowed = this.cflAllowed(bs);
350
+ const uvCandidates = [];
351
+ for (let mode = DC_PRED; mode <= (cflAllowed ? CFL_PRED : PAETH_PRED); mode++) {
352
+ if (mode === CFL_PRED) {
353
+ const alpha = this.cflAlphas(bs, b);
354
+ if (!alpha[0] && !alpha[1])
355
+ continue;
356
+ b.uvMode = CFL_PRED;
357
+ b.cflAlpha = alpha;
358
+ this.predictChroma(bs, edgeFlags, b);
359
+ uvCandidates.push({ mode, angle: 0, alpha, est: this.satd(1, bs) + this.satd(2, bs) + sadLambda * 7 });
360
+ continue;
361
+ }
362
+ if (this.params.effort < 2 && mode !== b.yMode && mode !== DC_PRED && mode !== VERT_PRED && mode !== HOR_PRED && mode !== SMOOTH_PRED && mode !== PAETH_PRED)
363
+ continue;
364
+ b.uvMode = mode;
365
+ b.uvAngle = 0;
366
+ this.predictChroma(bs, edgeFlags, b);
367
+ uvCandidates.push({ mode, angle: 0, alpha: [0, 0], est: this.satd(1, bs) + this.satd(2, bs) + sadLambda * (mode === DC_PRED ? 1.5 : 4) });
368
+ }
369
+ const uvDirectional = uvCandidates.filter(c => isDirectional(c.mode)).sort((x, y) => x.est - y.est)[0];
370
+ const uvNear = this.params.effort < 2 ? 1.2 : Infinity;
371
+ if (this.params.effort && lw4 + lh4 >= 2 && uvDirectional && uvDirectional.est <= uvNear * Math.min(...uvCandidates.map(c => c.est))) {
372
+ for (const angle of [-3, -2, -1, 1, 2, 3]) {
373
+ b.uvMode = uvDirectional.mode;
374
+ b.uvAngle = angle;
375
+ this.predictChroma(bs, edgeFlags, b);
376
+ uvCandidates.push({ mode: uvDirectional.mode, angle, alpha: [0, 0], est: this.satd(1, bs) + this.satd(2, bs) + sadLambda * 5.5 });
377
+ }
378
+ }
379
+ uvCandidates.sort((x, y) => x.est - y.est);
380
+ let bestUv = Infinity, bestUvMode = uvCandidates[0], uvDist = 0, uvBits = 0, uvCoded = false, keptUv = null;
381
+ const uvClose = this.params.effort < 2 ? 1.2 : Infinity;
382
+ const uvTries = uvCandidates.slice(0, [1, 2, 2][this.params.effort]).filter(c => c.est <= uvCandidates[0].est * uvClose);
383
+ for (const [i, c] of uvTries.entries()) {
384
+ b.uvMode = c.mode;
385
+ b.uvAngle = c.angle;
386
+ b.cflAlpha = c.alpha;
387
+ const d = this.codeChroma(bs, edgeFlags, b);
388
+ const cost = d + lambda * (this.bits + (c.mode === DC_PRED ? 1.5 : 4));
389
+ if (cost < bestUv) {
390
+ bestUv = cost;
391
+ bestUvMode = c;
392
+ uvDist = d;
393
+ uvBits = this.bits;
394
+ uvCoded = this.coded;
395
+ keptUv = i < uvTries.length - 1 ? [this.savePlane(1, bs), this.savePlane(2, bs)] : null;
396
+ }
397
+ }
398
+ b.uvMode = bestUvMode.mode;
399
+ b.uvAngle = bestUvMode.angle;
400
+ b.cflAlpha = bestUvMode.alpha;
401
+ if (keptUv) {
402
+ this.restorePlane(1, bs, keptUv[0]);
403
+ this.restorePlane(2, bs, keptUv[1]);
404
+ }
405
+ if (palAllowed) {
406
+ const r = this.paletteChroma(bs, edgeFlags, b, bestUv);
407
+ if (r) {
408
+ uvDist = r.dist;
409
+ uvBits = r.bits;
410
+ uvCoded = r.coded;
411
+ }
412
+ }
413
+ dist += uvDist;
414
+ bits += uvBits;
415
+ coded ||= uvCoded;
416
+ }
417
+ b.skip = coded ? 0 : 1;
418
+ this.modeContexts(bs, b);
419
+ return { b, cost: dist + lambda * (bits + 1 + 3) };
420
+ }
421
+ paletteLuma(bs, edgeFlags, b, cost) {
422
+ const f = this.f, stride = f.strides[0], src = this.src[0];
423
+ const bw = bdim(bs, 0) * 4, bh = bdim(bs, 1) * 4;
424
+ const w = Math.min(bw, (f.bw - this.bx) * 4), h = Math.min(bh, (f.bh - this.by) * 4), o = this.by * 4 * stride + this.bx * 4;
425
+ const counts = new Uint32Array(256);
426
+ for (let y = 0; y < h; y++)
427
+ for (let x = 0; x < w; x++)
428
+ counts[src[o + y * stride + x]]++;
429
+ const values = [], weights = [];
430
+ for (let v = 0; v < 256; v++)
431
+ if (counts[v]) {
432
+ values.push([v]);
433
+ weights.push(counts[v]);
434
+ }
435
+ if (values.length < 2 || values.length > (this.params.effort ? 64 : 8) || !mostlyFew(weights, w * h))
436
+ return null;
437
+ if (this.lambda * (15 + 5 * Math.min(values.length - 1, 7) + 0.08 * w * h) >= cost)
438
+ return null;
439
+ const colors = paletteColors(values, weights, 8).map(c => c[0]), k = colors.length;
440
+ if (k < 2)
441
+ return null;
442
+ const idx = new Uint8Array(bw * bh);
443
+ for (let y = 0; y < bh; y++) {
444
+ for (let x = 0; x < bw; x++) {
445
+ const v = src[o + Math.min(y, h - 1) * stride + Math.min(x, w - 1)];
446
+ let best = 0;
447
+ for (let c = 1; c < k; c++)
448
+ if (Math.abs(colors[c] - v) < Math.abs(colors[best] - v))
449
+ best = c;
450
+ idx[y * bw + x] = best;
451
+ }
452
+ }
453
+ let maxDelta = 0;
454
+ for (let c = 1; c < k; c++)
455
+ maxDelta = Math.max(maxDelta, colors[c] - colors[c - 1] - 1);
456
+ const overhead = 3 + 10 + (k - 1) * Math.max(5, 32 - Math.clz32(maxDelta)) + colorIndexBits(idx, bw, w, h, k);
457
+ if (this.lambda * (overhead + 2) >= cost)
458
+ return null;
459
+ const kept = this.savePlane(0, bs), mode = [b.yMode, b.yAngle, b.txtp];
460
+ b.yMode = DC_PRED;
461
+ b.yAngle = 0;
462
+ b.palSz[0] = k;
463
+ b.pal.set(colors);
464
+ b.palIdx = idx;
465
+ let best = null, bestCost = cost;
466
+ const txtps = tdim(b.tx, MAX) <= TX_16X16 && this.params.effort && !this.lossless ? [DCT_DCT, IDTX] : [this.lossless ? WHT_WHT : DCT_DCT];
467
+ let keptPal = null, bestTx = DCT_DCT;
468
+ for (const txtp of txtps) {
469
+ b.txtp = txtp;
470
+ const d = this.codeLuma(bs, edgeFlags, b);
471
+ const bits = this.bits + overhead + (txtp === DCT_DCT || this.lossless ? 0 : 1.5);
472
+ const c = d + this.lambda * (bits + 2);
473
+ if (c < bestCost) {
474
+ bestCost = c;
475
+ best = { dist: d, bits, coded: this.coded };
476
+ bestTx = txtp;
477
+ keptPal = txtps.length > 1 && txtp !== txtps[txtps.length - 1] ? this.savePlane(0, bs) : null;
478
+ }
479
+ else if (best && keptPal)
480
+ this.restorePlane(0, bs, keptPal);
481
+ }
482
+ if (best) {
483
+ b.txtp = bestTx;
484
+ return best;
485
+ }
486
+ [b.yMode, b.yAngle, b.txtp] = mode;
487
+ b.palSz[0] = 0;
488
+ b.palIdx = null;
489
+ this.restorePlane(0, bs, kept);
490
+ return null;
491
+ }
492
+ paletteChroma(bs, edgeFlags, b, cost) {
493
+ const f = this.f, ssx = this.ssx, ssy = this.ssy, stride = f.strides[1], su = this.src[1], sv = this.src[2];
494
+ const w4 = Math.min(bdim(bs, 0), f.bw - this.bx), h4 = Math.min(bdim(bs, 1), f.bh - this.by);
495
+ const bw = (bdim(bs, 0) + ssx >> ssx) * 4, bh = (bdim(bs, 1) + ssy >> ssy) * 4;
496
+ const w = (w4 + ssx >> ssx) * 4, h = (h4 + ssy >> ssy) * 4, o = (this.by * 4 >> ssy) * stride + (this.bx * 4 >> ssx);
497
+ const counts = this.pairCounts, keys = [], limit = this.params.effort ? 64 : 8;
498
+ for (let y = 0; y < h && keys.length <= limit; y++) {
499
+ for (let x = 0; x < w; x++) {
500
+ const key = su[o + y * stride + x] << 8 | sv[o + y * stride + x];
501
+ if (!counts[key]++)
502
+ keys.push(key);
503
+ }
504
+ }
505
+ const weights = keys.map(key => counts[key]);
506
+ for (const key of keys)
507
+ counts[key] = 0;
508
+ if (keys.length < 2 || keys.length > limit || !mostlyFew(weights, w * h))
509
+ return null;
510
+ if (this.lambda * (13.5 + 13 * Math.min(keys.length - 1, 7) + 8 + 0.08 * w * h) >= cost)
511
+ return null;
512
+ const colors = paletteColors(keys.map(key => [key >> 8, key & 255]), weights, 8), k = colors.length;
513
+ if (k < 2)
514
+ return null;
515
+ const idx = new Uint8Array(bw * bh);
516
+ for (let y = 0; y < bh; y++) {
517
+ for (let x = 0; x < bw; x++) {
518
+ const p = o + Math.min(y, h - 1) * stride + Math.min(x, w - 1), u = su[p], v = sv[p];
519
+ let best = 0, bestD = Infinity;
520
+ for (let c = 0; c < k; c++) {
521
+ const d = (colors[c][0] - u) ** 2 + (colors[c][1] - v) ** 2;
522
+ if (d < bestD) {
523
+ bestD = d;
524
+ best = c;
525
+ }
526
+ }
527
+ idx[y * bw + x] = best;
528
+ }
529
+ }
530
+ let maxDelta = 0;
531
+ for (let c = 1; c < k; c++)
532
+ maxDelta = Math.max(maxDelta, colors[c][0] - colors[c - 1][0]);
533
+ const overhead = 1 + 2 + 10 + (k - 1) * Math.max(5, 32 - Math.clz32(maxDelta)) + 8 * k + colorIndexBits(idx, bw, w, h, k);
534
+ if (this.lambda * (overhead + 1.5) >= cost)
535
+ return null;
536
+ const kept = [this.savePlane(1, bs), this.savePlane(2, bs)], mode = [b.uvMode, b.uvAngle], alpha = b.cflAlpha;
537
+ b.uvMode = DC_PRED;
538
+ b.uvAngle = 0;
539
+ b.cflAlpha = [0, 0];
540
+ b.palSz[1] = k;
541
+ for (let c = 0; c < k; c++) {
542
+ b.pal[8 + c] = colors[c][0];
543
+ b.pal[16 + c] = colors[c][1];
544
+ }
545
+ b.palIdxUv = idx;
546
+ const d = this.codeChroma(bs, edgeFlags, b), bits = this.bits + overhead;
547
+ if (d + this.lambda * (bits + 1.5) < cost)
548
+ return { dist: d, bits, coded: this.coded };
549
+ [b.uvMode, b.uvAngle] = mode;
550
+ b.cflAlpha = alpha;
551
+ b.palSz[1] = 0;
552
+ b.palIdxUv = null;
553
+ this.restorePlane(1, bs, kept[0]);
554
+ this.restorePlane(2, bs, kept[1]);
555
+ return null;
556
+ }
557
+ modeContexts(bs, b) {
558
+ const bx4 = this.bx, by4 = this.by & 31, aw = 1 << bdim(bs, 2), lh = 1 << bdim(bs, 3);
559
+ this.aMode.fill(b.yMode, bx4, bx4 + aw);
560
+ this.lMode.fill(b.yMode, by4, by4 + lh);
561
+ if (this.f.layout) {
562
+ const cbx4 = bx4 >> this.ssx, cby4 = by4 >> this.ssy;
563
+ this.aUvmode.fill(b.uvMode, cbx4, cbx4 + (bdim(bs, 0) + this.ssx >> this.ssx));
564
+ this.lUvmode.fill(b.uvMode, cby4, cby4 + (bdim(bs, 1) + this.ssy >> this.ssy));
565
+ }
566
+ }
567
+ saveContexts(bs) {
568
+ const bx4 = this.bx, by4 = this.by & 31, aw = bdim(bs, 0), lh = bdim(bs, 1);
569
+ const cbx4 = bx4 >> this.ssx, cby4 = by4 >> this.ssy, cw = aw + this.ssx >> this.ssx, ch = lh + this.ssy >> this.ssy;
570
+ return [this.aMode.slice(bx4, bx4 + aw), this.lMode.slice(by4, by4 + lh), this.aUvmode.slice(cbx4, cbx4 + cw), this.lUvmode.slice(cby4, cby4 + ch)];
571
+ }
572
+ restoreContexts(c) {
573
+ const bx4 = this.bx, by4 = this.by & 31, cbx4 = bx4 >> this.ssx, cby4 = by4 >> this.ssy;
574
+ this.aMode.set(c[0], bx4);
575
+ this.lMode.set(c[1], by4);
576
+ this.aUvmode.set(c[2], cbx4);
577
+ this.lUvmode.set(c[3], cby4);
578
+ }
579
+ cflAllowed(bs) {
580
+ if (!this.lossless)
581
+ return !!(CFL_ALLOWED_MASK & 1 << bs);
582
+ return (bdim(bs, 0) + this.ssx >> this.ssx) === 1 && (bdim(bs, 1) + this.ssy >> this.ssy) === 1;
583
+ }
584
+ savePlane(p, bs) {
585
+ const f = this.f, sx = p ? this.ssx : 0, sy = p ? this.ssy : 0, stride = f.strides[p];
586
+ const w = bdim(bs, 0) * 4 >> sx, h = bdim(bs, 1) * 4 >> sy, o = (this.by * 4 >> sy) * stride + (this.bx * 4 >> sx);
587
+ const out = new Uint16Array(w * h);
588
+ for (let y = 0; y < h; y++)
589
+ out.set(f.planes[p].subarray(o + y * stride, o + y * stride + w), y * w);
590
+ return out;
591
+ }
592
+ restorePlane(p, bs, saved) {
593
+ const f = this.f, sx = p ? this.ssx : 0, sy = p ? this.ssy : 0, stride = f.strides[p];
594
+ const w = bdim(bs, 0) * 4 >> sx, h = bdim(bs, 1) * 4 >> sy, o = (this.by * 4 >> sy) * stride + (this.bx * 4 >> sx);
595
+ for (let y = 0; y < h; y++)
596
+ f.planes[p].set(saved.subarray(y * w, y * w + w), o + y * stride);
597
+ }
598
+ satd(p, bs) {
599
+ const f = this.f, sx = p ? this.ssx : 0, sy = p ? this.ssy : 0, stride = f.strides[p];
600
+ const w = bdim(bs, 0) * 4 >> sx, h = bdim(bs, 1) * 4 >> sy, x0 = this.bx * 4 >> sx, y0 = this.by * 4 >> sy;
601
+ const pred = f.planes[p], src = this.src[p], d = SATD_BLOCK;
602
+ let sum = 0;
603
+ for (let by = 0; by < h; by += 4) {
604
+ for (let bx = 0; bx < w; bx += 4) {
605
+ for (let y = 0; y < 4; y++) {
606
+ const o = (y0 + by + y) * stride + x0 + bx;
607
+ for (let x = 0; x < 4; x++)
608
+ d[y * 4 + x] = src[o + x] - pred[o + x];
609
+ }
610
+ for (let y = 0; y < 4; y++) {
611
+ 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];
612
+ d[y * 4] = a + c;
613
+ d[y * 4 + 1] = b + e;
614
+ d[y * 4 + 2] = a - c;
615
+ d[y * 4 + 3] = b - e;
616
+ }
617
+ for (let x = 0; x < 4; x++) {
618
+ 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];
619
+ sum += Math.abs(a + c) + Math.abs(b + e) + Math.abs(a - c) + Math.abs(b - e);
620
+ }
621
+ }
622
+ }
623
+ return sum / 4;
624
+ }
625
+ cflAlphas(bs, b) {
626
+ const f = this.f, ssx = this.ssx, ssy = this.ssy, stride = f.strides[0];
627
+ const bw4 = bdim(bs, 0), bh4 = bdim(bs, 1);
628
+ const w4 = Math.min(bw4, f.bw - this.bx), h4 = Math.min(bh4, f.bh - this.by);
629
+ const cbw4 = bw4 + ssx >> ssx, cbh4 = bh4 + ssy >> ssy, cw4 = w4 + ssx >> ssx, ch4 = h4 + ssy >> ssy;
630
+ const tw = tdim(b.tx, W), th = tdim(b.tx, H);
631
+ const yo = 4 * (this.bx & ~ssx) + 4 * (this.by & ~ssy) * stride;
632
+ const furthestR = ((cw4 << ssx) + tw - 1) & ~(tw - 1), furthestB = ((ch4 << ssy) + th - 1) & ~(th - 1);
633
+ cflAc(this.ac, f.planes[0], yo, stride, cbw4 - (furthestR >> ssx), cbh4 - (furthestB >> ssy), cbw4 * 4, cbh4 * 4, ssx, ssy);
634
+ const alphas = [0, 0], w = cbw4 * 4, h = cbh4 * 4, cstride = f.strides[1];
635
+ const x0 = this.bx * 4 >> ssx, y0 = this.by * 4 >> ssy;
636
+ for (let pl = 0; pl < 2; pl++) {
637
+ const src = this.src[1 + pl];
638
+ let mean = 0;
639
+ for (let y = 0; y < h; y++)
640
+ for (let x = 0; x < w; x++)
641
+ mean += src[(y0 + y) * cstride + x0 + x];
642
+ mean /= w * h;
643
+ let sxy = 0, sxx = 0;
644
+ for (let y = 0; y < h; y++) {
645
+ for (let x = 0; x < w; x++) {
646
+ const a = this.ac[y * w + x];
647
+ sxy += a * (src[(y0 + y) * cstride + x0 + x] - mean);
648
+ sxx += a * a;
649
+ }
650
+ }
651
+ alphas[pl] = sxx ? Math.max(-16, Math.min(16, Math.round(sxy / sxx * 64 / 8))) : 0;
652
+ }
653
+ return alphas;
654
+ }
655
+ predictLuma(bs, edgeFlags, b) {
656
+ this.codeLuma(bs, edgeFlags, b, true);
657
+ }
658
+ predictChroma(bs, edgeFlags, b) {
659
+ this.codeChroma(bs, edgeFlags, b, true);
660
+ }
661
+ codeLuma(bs, edgeFlags, b, predictOnly = false) {
662
+ const f = this.f, seq = this.seq;
663
+ const bx = this.bx, by = this.by, bx4 = bx, by4 = by & 31;
664
+ const bw4 = bdim(bs, 0), bh4 = bdim(bs, 1);
665
+ const w4 = Math.min(bw4, f.bw - bx), h4 = Math.min(bh4, f.bh - by);
666
+ const tx = b.tx, tw = tdim(tx, W), th = tdim(tx, H);
667
+ const filterFlag = seq.intraEdgeFilter ? ANGLE_USE_EDGE_FILTER : 0;
668
+ const pic = f.planes[0], stride = f.strides[0];
669
+ let dist = 0;
670
+ this.bits = 0;
671
+ this.coded = false;
672
+ for (let initY = 0; initY < h4; initY += 16) {
673
+ const subH4 = Math.min(h4, 16 + initY);
674
+ for (let initX = 0; initX < w4; initX += 16) {
675
+ const palIdx = b.palSz[0] ? b.palIdx : null;
676
+ if (palIdx) {
677
+ const d = 4 * (by * stride + bx), bw = bw4 * 4;
678
+ for (let y = 0; y < bh4 * 4; y++)
679
+ for (let x = 0; x < bw; x++)
680
+ pic[d + y * stride + x] = b.pal[palIdx[y * bw + x]];
681
+ }
682
+ const intraFlags = smFlag(this.aMode[bx4]) | smFlag(this.lMode[by4]) | filterFlag;
683
+ const sbHasTr = initX + 16 < w4 ? 1 : initY ? 0 : edgeFlags & EDGE_I444_TOP_HAS_RIGHT;
684
+ const sbHasBl = initX ? 0 : initY + 16 < h4 ? 1 : edgeFlags & EDGE_I444_LEFT_HAS_BOTTOM;
685
+ const subW4 = Math.min(w4, initX + 16);
686
+ for (let y = initY; y < subH4; y += th) {
687
+ const ty = by + y;
688
+ let d = 4 * (ty * stride + bx + initX);
689
+ for (let x = initX; x < subW4; x += tw, d += 4 * tw) {
690
+ const tx4 = bx + x;
691
+ const flags = (((y > initY || !sbHasTr) && x + tw >= subW4) ? 0 : EDGE_I444_TOP_HAS_RIGHT) |
692
+ ((x > initX || (!sbHasBl && y + th >= subH4)) ? 0 : EDGE_I444_LEFT_HAS_BOTTOM);
693
+ if (!palIdx) {
694
+ 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);
695
+ predict(mode, pic, d, stride, tw * 4, th * 4, preparedAngle | intraFlags, 4 * f.bw - 4 * tx4, 4 * f.bh - 4 * ty, f.bitdepthMax);
696
+ }
697
+ if (predictOnly)
698
+ continue;
699
+ dist += this.codeTx(0, d, stride, tx, b.txtp, b, bs, this.aLcoef, bx4 + x, this.lLcoef, by4 + y, Math.min(tw, f.bw - tx4), Math.min(th, f.bh - ty), 4 * tx4, 4 * ty);
700
+ }
701
+ }
702
+ }
703
+ }
704
+ return dist;
705
+ }
706
+ codeChroma(bs, edgeFlags, b, predictOnly = false) {
707
+ const f = this.f, seq = this.seq, ssx = this.ssx, ssy = this.ssy;
708
+ const bx = this.bx, by = this.by, bx4 = bx, by4 = by & 31;
709
+ const cbx4 = bx4 >> ssx, cby4 = by4 >> ssy;
710
+ const bw4 = bdim(bs, 0), bh4 = bdim(bs, 1);
711
+ const w4 = Math.min(bw4, f.bw - bx), h4 = Math.min(bh4, f.bh - by);
712
+ const cw4 = w4 + ssx >> ssx, ch4 = h4 + ssy >> ssy, cbw4 = bw4 + ssx >> ssx, cbh4 = bh4 + ssy >> ssy;
713
+ const tx = b.tx, uvtx = b.uvtx, tw = tdim(tx, W), th = tdim(tx, H), uvtw = tdim(uvtx, W), uvth = tdim(uvtx, H);
714
+ const filterFlag = seq.intraEdgeFilter ? ANGLE_USE_EDGE_FILTER : 0;
715
+ const stride = f.strides[0], cstride = f.strides[1];
716
+ let dist = 0;
717
+ this.bits = 0;
718
+ this.coded = false;
719
+ for (let initY = 0; initY < h4; initY += 16) {
720
+ const subCh4 = Math.min(ch4, initY + 16 >> ssy);
721
+ for (let initX = 0; initX < w4; initX += 16) {
722
+ if (b.uvMode === CFL_PRED) {
723
+ const yo = 4 * (bx & ~ssx) + 4 * (by & ~ssy) * stride;
724
+ const furthestR = ((cw4 << ssx) + tw - 1) & ~(tw - 1), furthestB = ((ch4 << ssy) + th - 1) & ~(th - 1);
725
+ cflAc(this.ac, f.planes[0], yo, stride, cbw4 - (furthestR >> ssx), cbh4 - (furthestB >> ssy), cbw4 * 4, cbh4 * 4, ssx, ssy);
726
+ const uvOff = 4 * ((bx >> ssx) + (by >> ssy) * cstride);
727
+ for (let pl = 0; pl < 2; pl++) {
728
+ if (!b.cflAlpha[pl])
729
+ continue;
730
+ const xpos = bx >> ssx, ypos = by >> ssy;
731
+ const mode = prepareEdges(xpos, xpos > this.colStart >> ssx, ypos, ypos > this.rowStart >> ssy, this.colEnd >> ssx, this.rowEnd >> ssy, 0, f.planes[1 + pl], uvOff, cstride, DC_PRED, 0, uvtw, uvth, false, f.bitdepth);
732
+ cflPredict(mode, f.planes[1 + pl], uvOff, cstride, uvtw * 4, uvth * 4, this.ac, b.cflAlpha[pl], f.bitdepthMax);
733
+ }
734
+ }
735
+ else if (b.palSz[1]) {
736
+ const uvOff = 4 * ((bx >> ssx) + (by >> ssy) * cstride), bw = cbw4 * 4, idx = b.palIdxUv;
737
+ for (let pl = 1; pl <= 2; pl++) {
738
+ const plane = f.planes[pl];
739
+ for (let y = 0; y < cbh4 * 4; y++)
740
+ for (let x = 0; x < bw; x++)
741
+ plane[uvOff + y * cstride + x] = b.pal[pl * 8 + idx[y * bw + x]];
742
+ }
743
+ }
744
+ const smUv = smFlag(this.aUvmode[cbx4]) | smFlag(this.lUvmode[cby4]);
745
+ const edge = f.layout === 1 ? [EDGE_I420_TOP_HAS_RIGHT, EDGE_I420_LEFT_HAS_BOTTOM] : [1, 8];
746
+ const uvSbHasTr = (initX + 16 >> ssx) < cw4 ? 1 : initY ? 0 : edgeFlags & edge[0];
747
+ const uvSbHasBl = initX ? 0 : (initY + 16 >> ssy) < ch4 ? 1 : edgeFlags & edge[1];
748
+ const subCw4 = Math.min(cw4, initX + 16 >> ssx);
749
+ const txtp = this.lossless ? WHT_WHT : tdim(uvtx, MAX) + 1 >= TX_64X64 ? DCT_DCT : TXTP_FROM_UVMODE[b.uvMode];
750
+ for (let pl = 0; pl < 2; pl++) {
751
+ const plane = f.planes[1 + pl];
752
+ const aC = this.aCcoef[pl], lC = this.lCcoef[pl];
753
+ for (let y = initY >> ssy, tyl = by + initY; y < subCh4; y += uvth, tyl += uvth << ssy) {
754
+ let d = 4 * ((tyl >> ssy) * cstride + (bx + initX >> ssx));
755
+ for (let x = initX >> ssx, txl = bx + initX; x < subCw4; x += uvtw, txl += uvtw << ssx, d += uvtw * 4) {
756
+ if (!(b.uvMode === CFL_PRED && b.cflAlpha[pl]) && !b.palSz[1]) {
757
+ const flags = (((y > (initY >> ssy) || !uvSbHasTr) && x + uvtw >= subCw4) ? 0 : EDGE_I444_TOP_HAS_RIGHT) |
758
+ ((x > (initX >> ssx) || (!uvSbHasBl && y + uvth >= subCh4)) ? 0 : EDGE_I444_LEFT_HAS_BOTTOM);
759
+ const uvMode = b.uvMode === CFL_PRED ? DC_PRED : b.uvMode;
760
+ const xpos = txl >> ssx, ypos = tyl >> ssy;
761
+ const mode = prepareEdges(xpos, xpos > this.colStart >> ssx, ypos, ypos > this.rowStart >> ssy, this.colEnd >> ssx, this.rowEnd >> ssy, flags, plane, d, cstride, uvMode, b.uvAngle, uvtw, uvth, seq.intraEdgeFilter, f.bitdepth);
762
+ predict(mode, plane, d, cstride, uvtw * 4, uvth * 4, preparedAngle | filterFlag | smUv, (4 * f.bw + ssx - 4 * (txl & ~ssx)) >> ssx, (4 * f.bh + ssy - 4 * (tyl & ~ssy)) >> ssy, f.bitdepthMax);
763
+ }
764
+ if (predictOnly)
765
+ continue;
766
+ const ctw = Math.min(uvtw, (f.bw - txl + ssx) >> ssx), cth = Math.min(uvth, (f.bh - tyl + ssy) >> ssy);
767
+ dist += this.codeTx(1 + pl, d, cstride, uvtx, txtp, b, bs, aC, cbx4 + x, lC, cby4 + y, ctw, cth, 4 * txl >> ssx, 4 * tyl >> ssy);
768
+ }
769
+ }
770
+ }
771
+ }
772
+ }
773
+ return dist;
774
+ }
775
+ codeTx(plane, d, stride, tx, txtp, b, bs, aArr, a, lArr, l, ctw, cth, px, py) {
776
+ const f = this.f, pic = f.planes[plane], src = this.src[plane];
777
+ const w = tdim(tx, W) * 4, h = tdim(tx, H) * 4, sw = Math.min(w, 32), sh = Math.min(h, 32);
778
+ const sx = plane ? this.ssx : 0, sy = plane ? this.ssy : 0;
779
+ const vw = Math.max(0, Math.min(w, (f.width + sx >> sx) - px)), vh = Math.max(0, Math.min(h, (f.height + sy >> sy) - py));
780
+ let eob = -1;
781
+ if (!(this.w && b.skip)) {
782
+ const res = this.res, coefs = this.coefs, q = this.q;
783
+ let sse = 0;
784
+ for (let y = 0; y < h; y++) {
785
+ for (let x = 0; x < w; x++) {
786
+ const e = res[y * w + x] = src[d + y * stride + x] - pic[d + y * stride + x];
787
+ sse += e * e;
788
+ }
789
+ }
790
+ if (this.lossless)
791
+ eob = this.whtCoefs(res, q);
792
+ else if (sse < this.zeroBound(plane, tx))
793
+ eob = -1;
794
+ else {
795
+ forwardTransform(res, tx, txtp, coefs);
796
+ eob = this.quantize(plane, tx, txtp, coefs, q, sw * sh);
797
+ }
798
+ if (eob >= 0)
799
+ this.coded = true;
800
+ if (this.w)
801
+ this.writeCoefs(aArr, a, lArr, l, tx, txtp, bs, b, plane, eob, ctw, cth);
802
+ else
803
+ this.bits += this.estimateBits(tx, q, eob);
804
+ if (eob >= 0) {
805
+ this.dequantize(plane, tx, txtp, q, eob);
806
+ inverseTransformAdd(pic, d, stride, this.cf, eob, tx, txtp, f.bitdepthMax);
807
+ }
808
+ }
809
+ else {
810
+ aArr.fill(0x40, a, a + tdim(tx, W));
811
+ lArr.fill(0x40, l, l + tdim(tx, H));
812
+ }
813
+ let dist = 0;
814
+ for (let y = 0; y < vh; y++) {
815
+ for (let x = 0; x < vw; x++) {
816
+ const e = src[d + y * stride + x] - pic[d + y * stride + x];
817
+ dist += e * e;
818
+ }
819
+ }
820
+ return dist;
821
+ }
822
+ zeroBound(plane, tx) {
823
+ const step = Math.min(this.dq[plane][0], this.dq[plane][1]) / 2 ** Math.max(0, tdim(tx, CTX) - 2);
824
+ return 0.2 * pixelEnergy(tx) * step * step;
825
+ }
826
+ whtCoefs(res, q) {
827
+ const r = this.whtRes, out = this.whtOut;
828
+ for (let i = 0; i < 16; i++)
829
+ r[i] = res[i];
830
+ forwardWht(r, out);
831
+ for (let y = 0; y < 4; y++)
832
+ for (let x = 0; x < 4; x++)
833
+ q[x * 4 + y] = out[y * 4 + x];
834
+ const order = scan(TX_4X4);
835
+ let eob = -1;
836
+ for (let i = 0; i < 16; i++)
837
+ if (q[order[i]])
838
+ eob = i;
839
+ return eob;
840
+ }
841
+ quantize(plane, tx, txtp, coefs, q, n) {
842
+ const dqShift = Math.max(0, tdim(tx, CTX) - 2), [dcq, acq] = this.dq[plane];
843
+ const order = scan(tx), energy = pixelEnergy(tx), lambda = this.lambda;
844
+ const keep = this.rdoKeep, drop = this.rdoDrop;
845
+ void txtp;
846
+ let last = -1, total = 0;
847
+ for (let i = 0; i < n; i++) {
848
+ const rc = order[i], step = (rc ? acq : dcq) / 2 ** dqShift, v = Math.abs(coefs[rc]) / step;
849
+ const e = energy * step * step, dropped = e * v * v;
850
+ drop[i] = dropped;
851
+ total += dropped;
852
+ if (v < 0.5) {
853
+ q[rc] = 0;
854
+ keep[i] = dropped + lambda * ZERO_BITS;
855
+ continue;
856
+ }
857
+ let m = Math.floor(v + 0.5);
858
+ const dm = v - m, dl = v - m + 1;
859
+ if (e * dl * dl + lambda * coefBits(m - 1) < e * dm * dm + lambda * coefBits(m))
860
+ m--;
861
+ q[rc] = coefs[rc] < 0 ? -m : m;
862
+ keep[i] = e * (v - m) * (v - m) + lambda * coefBits(m);
863
+ if (m)
864
+ last = i;
865
+ }
866
+ if (last < 0)
867
+ return -1;
868
+ let best = total + lambda, bestEob = -1, prefix = 0;
869
+ let rest = best - lambda;
870
+ for (let i = 0; i <= last; i++) {
871
+ prefix += keep[i];
872
+ rest -= drop[i];
873
+ if (!q[order[i]])
874
+ continue;
875
+ const cost = prefix + rest + lambda * (2 + 1.5 * Math.log2(i + 2));
876
+ if (cost < best) {
877
+ best = cost;
878
+ bestEob = i;
879
+ }
880
+ }
881
+ for (let i = bestEob + 1; i <= last; i++)
882
+ q[order[i]] = 0;
883
+ return bestEob;
884
+ }
885
+ dequantize(plane, tx, txtp, q, eob) {
886
+ const dqShift = Math.max(0, tdim(tx, CTX) - 2), [dcq, acq] = this.dq[plane];
887
+ const cfMax = (128 << 8) - 1, order = scan(tx), cf = this.cf;
888
+ void txtp;
889
+ for (let i = 0; i <= eob; i++) {
890
+ const rc = order[i], v = q[rc];
891
+ if (!v) {
892
+ cf[rc] = 0;
893
+ continue;
894
+ }
895
+ const m = Math.abs(v), dq = rc ? acq : dcq;
896
+ let c;
897
+ if (m >= 15)
898
+ c = Math.min((dq * m & 0xffffff) >> dqShift, cfMax + (v < 0 ? 1 : 0));
899
+ else
900
+ c = (dq * m) >> dqShift;
901
+ cf[rc] = v < 0 ? -c : c;
902
+ }
903
+ }
904
+ estimateBits(tx, q, eob) {
905
+ if (eob < 0)
906
+ return 1;
907
+ const order = scan(tx);
908
+ let bits = 2 + 1.5 * Math.log2(eob + 2);
909
+ for (let i = 0; i <= eob; i++)
910
+ bits += coefBits(Math.abs(q[order[i]]));
911
+ return bits;
912
+ }
913
+ writeSb(bl, node, n) {
914
+ const f = this.f, w = this.w, cdf = this.cdf;
915
+ const hsz = 16 >> bl;
916
+ const haveH = f.bw > this.bx + hsz, haveV = f.bh > this.by + hsz;
917
+ if (!haveH && !haveV)
918
+ return this.writeSb(bl + 1, node.split[0], n.kids[0]);
919
+ const bx8 = this.bx >> 1, by8 = (this.by & 31) >> 1;
920
+ const ctx = (this.aPartition[bx8] >> (4 - bl) & 1) + ((this.lPartition[by8] >> (4 - bl) & 1) << 1);
921
+ const pc = CDF.partition + (bl * 4 + ctx) * 16;
922
+ const bp = n.bp;
923
+ const quarter = (k) => {
924
+ const dx = k & 1 ? hsz : 0, dy = k & 2 ? hsz : 0;
925
+ this.bx += dx;
926
+ this.by += dy;
927
+ this.writeSb(bl + 1, node.split[k], n.kids[k]);
928
+ this.bx -= dx;
929
+ this.by -= dy;
930
+ };
931
+ if (haveH && haveV) {
932
+ w.symbol(cdf, pc, PARTITION_TYPE_COUNT[bl], bp);
933
+ if (bp === PARTITION_NONE)
934
+ this.writeB(BLOCK_SIZES[(bl * 10 + bp) * 2], node.o, n.b);
935
+ else
936
+ for (let k = 0; k < 4; k++)
937
+ quarter(k);
938
+ }
939
+ else if (haveH) {
940
+ let prob = cdf[pc + PARTITION_V - 1] - cdf[pc + PARTITION_T_TOP_SPLIT];
941
+ prob += cdf[pc + PARTITION_T_LEFT_SPLIT - 1];
942
+ prob += cdf[pc + PARTITION_V4 - 1] - cdf[pc + PARTITION_T_RIGHT_SPLIT];
943
+ w.boolProb(prob, 1);
944
+ quarter(0);
945
+ quarter(1);
946
+ }
947
+ else {
948
+ let prob = cdf[pc + PARTITION_H - 1] - cdf[pc + PARTITION_H];
949
+ prob += cdf[pc + PARTITION_SPLIT - 1] - cdf[pc + PARTITION_T_LEFT_SPLIT];
950
+ prob += cdf[pc + PARTITION_H4 - 1] - cdf[pc + PARTITION_H4];
951
+ w.boolProb(prob, 1);
952
+ quarter(0);
953
+ quarter(2);
954
+ }
955
+ const p = haveH && haveV ? bp : PARTITION_SPLIT;
956
+ if (p !== PARTITION_SPLIT || bl === BL_8X8) {
957
+ this.aPartition.fill(AL_PART_CTX[bl * 10 + p], bx8, bx8 + hsz);
958
+ this.lPartition.fill(AL_PART_CTX[50 + bl * 10 + p], by8, by8 + hsz);
959
+ }
960
+ }
961
+ writeB(bs, edgeFlags, b) {
962
+ const f = this.f, w = this.w, cdf = this.cdf;
963
+ const bx = this.bx, by = this.by, bx4 = bx, by4 = by & 31;
964
+ const ssx = this.ssx, ssy = this.ssy;
965
+ const cbx4 = bx4 >> ssx, cby4 = by4 >> ssy;
966
+ const bw4 = bdim(bs, 0), bh4 = bdim(bs, 1), lw4 = bdim(bs, 2), lh4 = bdim(bs, 3);
967
+ const cbw4 = bw4 + ssx >> ssx, cbh4 = bh4 + ssy >> ssy;
968
+ const hasChroma = f.layout !== 0;
969
+ w.boolAdapt(cdf, CDF.skip + (this.aSkip[bx4] + this.lSkip[by4]) * 2, b.skip);
970
+ if (!b.skip) {
971
+ const idx = (by >> 4) * (f.b4Stride >> 4) + (bx >> 4);
972
+ if (f.cdefIdx[idx] === -1) {
973
+ f.cdefIdx[idx] = this.cdefChoice[idx];
974
+ w.bools(this.hdr.cdef.bits, this.cdefChoice[idx]);
975
+ }
976
+ }
977
+ w.symbol(cdf, CDF.kfYMode + (INTRA_MODE_CONTEXT[this.aMode[bx4]] * 5 + INTRA_MODE_CONTEXT[this.lMode[by4]]) * 16, 12, b.yMode);
978
+ if (lw4 + lh4 >= 2 && isDirectional(b.yMode))
979
+ w.symbol(cdf, CDF.angleDelta + (b.yMode - VERT_PRED) * 8, 6, b.yAngle + 3);
980
+ if (hasChroma) {
981
+ const cflAllowed = this.cflAllowed(bs);
982
+ w.symbol(cdf, CDF.uvMode + ((cflAllowed ? 1 : 0) * 13 + b.yMode) * 16, cflAllowed ? 13 : 12, b.uvMode);
983
+ if (b.uvMode === CFL_PRED) {
984
+ const signU = b.cflAlpha[0] ? b.cflAlpha[0] < 0 ? 1 : 2 : 0, signV = b.cflAlpha[1] ? b.cflAlpha[1] < 0 ? 1 : 2 : 0;
985
+ w.symbol(cdf, CDF.cflSign, 7, signU * 3 + signV - 1);
986
+ if (signU)
987
+ w.symbol(cdf, CDF.cflAlpha + ((signU === 2 ? 3 : 0) + signV) * 16, 15, Math.abs(b.cflAlpha[0]) - 1);
988
+ if (signV)
989
+ w.symbol(cdf, CDF.cflAlpha + ((signV === 2 ? 3 : 0) + signU) * 16, 15, Math.abs(b.cflAlpha[1]) - 1);
990
+ }
991
+ else if (lw4 + lh4 >= 2 && isDirectional(b.uvMode)) {
992
+ w.symbol(cdf, CDF.angleDelta + (b.uvMode - VERT_PRED) * 8, 6, b.uvAngle + 3);
993
+ }
994
+ }
995
+ if (this.hdr.allowScreenContentTools && Math.max(bw4, bh4) <= 16 && bw4 + bh4 >= 4) {
996
+ const szCtx = lw4 + lh4 - 2;
997
+ if (b.yMode === DC_PRED) {
998
+ const palCtx = (this.aPalSz[bx4] > 0 ? 1 : 0) + (this.lPalSz[by4] > 0 ? 1 : 0);
999
+ w.boolAdapt(cdf, CDF.palY + (szCtx * 3 + palCtx) * 2, b.palSz[0] ? 1 : 0);
1000
+ if (b.palSz[0])
1001
+ this.writePalPlane(b, 0, szCtx, bx4, by4);
1002
+ }
1003
+ if (hasChroma && b.uvMode === DC_PRED) {
1004
+ w.boolAdapt(cdf, CDF.palUv + (b.palSz[0] > 0 ? 2 : 0), b.palSz[1] ? 1 : 0);
1005
+ if (b.palSz[1])
1006
+ this.writePalUv(b, szCtx, bx4, by4);
1007
+ }
1008
+ }
1009
+ const w4 = Math.min(bw4, f.bw - bx), h4 = Math.min(bh4, f.bh - by);
1010
+ if (b.palSz[0])
1011
+ this.writeColorIndices(b.palIdx, b.palSz[0], 0, w4 * 4, h4 * 4, bw4 * 4);
1012
+ if (hasChroma && b.palSz[1])
1013
+ this.writeColorIndices(b.palIdxUv, b.palSz[1], 1, (w4 + ssx >> ssx) * 4, (h4 + ssy >> ssy) * 4, cbw4 * 4);
1014
+ this.codeLuma(bs, edgeFlags, b);
1015
+ if (hasChroma)
1016
+ this.codeChroma(bs, edgeFlags, b);
1017
+ this.storeBlock(bs, b);
1018
+ const aw = 1 << lw4, lh = 1 << lh4;
1019
+ this.aMode.fill(b.yMode, bx4, bx4 + aw);
1020
+ this.lMode.fill(b.yMode, by4, by4 + lh);
1021
+ this.aSkip.fill(b.skip, bx4, bx4 + aw);
1022
+ this.lSkip.fill(b.skip, by4, by4 + lh);
1023
+ this.aPalSz.fill(b.palSz[0], bx4, bx4 + aw);
1024
+ this.lPalSz.fill(b.palSz[0], by4, by4 + lh);
1025
+ this.aPalSzUv.fill(hasChroma ? b.palSz[1] : 0, bx4, bx4 + aw);
1026
+ this.lPalSzUv.fill(hasChroma ? b.palSz[1] : 0, by4, by4 + lh);
1027
+ for (let pl = 0; pl < 3; pl++) {
1028
+ if (!b.palSz[pl ? 1 : 0] || pl && !hasChroma)
1029
+ continue;
1030
+ const colors = b.pal.subarray(pl * 8, pl * 8 + 8);
1031
+ for (let x = 0; x < bw4; x++)
1032
+ this.aPal.set(colors, (bx4 + x) * 24 + pl * 8);
1033
+ for (let y = 0; y < bh4; y++)
1034
+ this.lPal.set(colors, (by4 + y) * 24 + pl * 8);
1035
+ }
1036
+ if (hasChroma) {
1037
+ this.aUvmode.fill(b.uvMode, cbx4, cbx4 + cbw4);
1038
+ this.lUvmode.fill(b.uvMode, cby4, cby4 + cbh4);
1039
+ }
1040
+ }
1041
+ writePalPlane(b, pl, szCtx, bx4, by4) {
1042
+ const w = this.w, palSz = b.palSz[pl];
1043
+ w.symbol(this.cdf, CDF.palSize + (pl * 7 + szCtx) * 8, 6, palSz - 2);
1044
+ const cache = [];
1045
+ let lCache = pl ? this.lPalSzUv[by4] : this.lPalSz[by4];
1046
+ let aCache = by4 & 15 ? pl ? this.aPalSzUv[bx4] : this.aPalSz[bx4] : 0;
1047
+ let l = by4 * 24 + pl * 8, a = bx4 * 24 + pl * 8;
1048
+ const L = this.lPal, A = this.aPal;
1049
+ const push = (v) => {
1050
+ if (!cache.length || cache[cache.length - 1] !== v)
1051
+ cache.push(v);
1052
+ };
1053
+ while (lCache && aCache) {
1054
+ if (L[l] < A[a]) {
1055
+ push(L[l++]);
1056
+ lCache--;
1057
+ }
1058
+ else {
1059
+ if (A[a] === L[l]) {
1060
+ l++;
1061
+ lCache--;
1062
+ }
1063
+ push(A[a++]);
1064
+ aCache--;
1065
+ }
1066
+ }
1067
+ while (lCache-- > 0)
1068
+ push(L[l++]);
1069
+ while (aCache-- > 0)
1070
+ push(A[a++]);
1071
+ const rest = Array.from(b.pal.subarray(pl * 8, pl * 8 + palSz));
1072
+ for (let n = 0, used = 0; n < cache.length && used < palSz; n++) {
1073
+ const i = rest.indexOf(cache[n]);
1074
+ w.bool(i >= 0 ? 1 : 0);
1075
+ if (i >= 0) {
1076
+ rest.splice(i, 1);
1077
+ used++;
1078
+ }
1079
+ }
1080
+ if (!rest.length)
1081
+ return;
1082
+ const max = 255, minus = pl ? 0 : 1;
1083
+ w.bools(8, rest[0]);
1084
+ if (rest.length === 1)
1085
+ return;
1086
+ let maxDelta = 0;
1087
+ for (let i = 1; i < rest.length; i++)
1088
+ maxDelta = Math.max(maxDelta, rest[i] - rest[i - 1] - minus);
1089
+ const extra = Math.max(0, 32 - Math.clz32(maxDelta) - 5);
1090
+ w.bools(2, extra);
1091
+ let bits = 5 + extra, prev = rest[0];
1092
+ for (let i = 1; i < rest.length; i++) {
1093
+ w.bools(bits, rest[i] - prev - minus);
1094
+ prev = rest[i];
1095
+ if (prev + minus >= max)
1096
+ break;
1097
+ bits = Math.min(bits, 1 + (31 - Math.clz32(max - prev - minus)));
1098
+ }
1099
+ }
1100
+ writePalUv(b, szCtx, bx4, by4) {
1101
+ this.writePalPlane(b, 1, szCtx, bx4, by4);
1102
+ const w = this.w, palSz = b.palSz[1], v = b.pal.subarray(16, 16 + palSz);
1103
+ const deltas = [];
1104
+ let maxMag = 0;
1105
+ for (let i = 1; i < palSz; i++) {
1106
+ const d = (v[i] - v[i - 1] + 128 & 255) - 128;
1107
+ deltas.push(d);
1108
+ maxMag = Math.max(maxMag, Math.abs(d));
1109
+ }
1110
+ const bits = Math.max(4, 32 - Math.clz32(maxMag));
1111
+ const deltaBits = bits <= 7 ? 2 + 8 + deltas.reduce((s, d) => s + bits + (d ? 1 : 0), 0) : Infinity;
1112
+ if (deltaBits < 8 * palSz) {
1113
+ w.bool(1);
1114
+ w.bools(2, bits - 4);
1115
+ w.bools(8, v[0]);
1116
+ for (const d of deltas) {
1117
+ w.bools(bits, Math.abs(d));
1118
+ if (d)
1119
+ w.bool(d < 0 ? 1 : 0);
1120
+ }
1121
+ }
1122
+ else {
1123
+ w.bool(0);
1124
+ for (let i = 0; i < palSz; i++)
1125
+ w.bools(8, v[i]);
1126
+ }
1127
+ }
1128
+ writeColorIndices(t, palSz, pl, w, h, bw) {
1129
+ const enc = this.w, cdf = this.cdf, o = CDF.colorMap + (pl * 7 + palSz - 2) * 5 * 8;
1130
+ enc.uniform(palSz, t[0]);
1131
+ colorRanks(t, bw, w, h, (ctx, rank) => enc.symbol(cdf, o + ctx * 8, palSz - 1, rank));
1132
+ }
1133
+ storeBlock(bs, b) {
1134
+ const f = this.f, bx = this.bx, by = this.by, ssx = this.ssx, ssy = this.ssy;
1135
+ const bw4 = bdim(bs, 0), bh4 = bdim(bs, 1);
1136
+ const w4 = Math.min(bw4, f.bw - bx), h4 = Math.min(bh4, f.bh - by);
1137
+ const lf = this.hdr.loopFilter, lvl = [lf.levelY[0], lf.levelY[1], lf.levelU, lf.levelV];
1138
+ const s4 = f.b4Stride;
1139
+ for (let y = 0; y < h4; y++) {
1140
+ for (let x = 0; x < w4; x++) {
1141
+ const o = (by + y) * s4 + bx + x;
1142
+ f.lfLevels.set(lvl, o * 4);
1143
+ f.txW[o] = tdim(b.tx, LW);
1144
+ f.txH[o] = tdim(b.tx, LH);
1145
+ f.skip[o] = b.skip;
1146
+ }
1147
+ }
1148
+ if (f.layout) {
1149
+ const cx = bx >> ssx, cy = by >> ssy, cw4 = w4 + ssx >> ssx, ch4 = h4 + ssy >> ssy;
1150
+ for (let y = 0; y < ch4; y++) {
1151
+ for (let x = 0; x < cw4; x++) {
1152
+ const o = (cy + y) * s4 + cx + x;
1153
+ f.uvTxW[o] = tdim(b.uvtx, LW);
1154
+ f.uvTxH[o] = tdim(b.uvtx, LH);
1155
+ }
1156
+ }
1157
+ }
1158
+ }
1159
+ writeCoefs(aArr, a, lArr, l, tx, txtp, bs, b, plane, eob, ctw, cth) {
1160
+ const w = this.w, cdf = this.cdf, f = this.f, q = this.q;
1161
+ const chroma = plane ? 1 : 0;
1162
+ const tlw = tdim(tx, LW), tlh = tdim(tx, LH), tctx = tdim(tx, CTX), tmin = tdim(tx, MIN), tmax = tdim(tx, MAX);
1163
+ let sctx;
1164
+ const aw = 1 << tlw, lh = 1 << tlh;
1165
+ if (chroma) {
1166
+ const bl2 = bdim(bs, 2), bl3 = bdim(bs, 3);
1167
+ const notOneBlk = bl2 - (bl2 && f.ssx ? 1 : 0) > tlw || bl3 - (bl3 && f.ssy ? 1 : 0) > tlh;
1168
+ let ca = 0, cl = 0;
1169
+ for (let i = 0; i < aw; i++)
1170
+ if (aArr[a + i] !== 0x40) {
1171
+ ca = 1;
1172
+ break;
1173
+ }
1174
+ for (let i = 0; i < lh; i++)
1175
+ if (lArr[l + i] !== 0x40) {
1176
+ cl = 1;
1177
+ break;
1178
+ }
1179
+ sctx = 7 + (notOneBlk ? 3 : 0) + ca + cl;
1180
+ }
1181
+ else if (bdim(bs, 2) === tlw && bdim(bs, 3) === tlh) {
1182
+ sctx = 0;
1183
+ }
1184
+ else {
1185
+ let la = 0, ll = 0;
1186
+ for (let i = 0; i < aw; i++)
1187
+ la |= aArr[a + i];
1188
+ for (let i = 0; i < lh; i++)
1189
+ ll |= lArr[l + i];
1190
+ sctx = SKIP_CTX[Math.min(la & 0x3f, 4) * 5 + Math.min(ll & 0x3f, 4)];
1191
+ }
1192
+ w.boolAdapt(cdf, CDF.coefSkip + (tctx * 13 + sctx) * 2, eob < 0 ? 1 : 0);
1193
+ if (eob < 0) {
1194
+ aArr.fill(0x40, a, a + ctw);
1195
+ lArr.fill(0x40, l, l + cth);
1196
+ return;
1197
+ }
1198
+ if (!chroma && tmax + 1 < TX_64X64 && !this.lossless) {
1199
+ if (tmin === TX_16X16)
1200
+ w.symbol(cdf, CDF.txtpIntra2 + (tmin * 13 + b.yMode) * 8, 4, TX_TYPES_PER_SET.indexOf(txtp));
1201
+ else
1202
+ w.symbol(cdf, CDF.txtpIntra1 + (tmin * 13 + b.yMode) * 8, 6, TX_TYPES_PER_SET.indexOf(txtp, 5) - 5);
1203
+ }
1204
+ const slw = Math.min(tlw, 3), slh = Math.min(tlh, 3), tx2d = slw + slh;
1205
+ const eobBin = eob < 2 ? eob : 32 - Math.clz32(eob);
1206
+ const binCdf = [CDF.eobBin16, CDF.eobBin32, CDF.eobBin64, CDF.eobBin128, CDF.eobBin256, CDF.eobBin512, CDF.eobBin1024][tx2d];
1207
+ const binCtx = tx2d < 4 ? chroma * 2 * 8 : tx2d === 4 ? chroma * 2 * 16 : chroma * 16;
1208
+ w.symbol(cdf, binCdf + binCtx, 4 + tx2d, eobBin);
1209
+ if (eobBin > 1) {
1210
+ w.boolAdapt(cdf, CDF.eobHiBit + ((tctx * 2 + chroma) * 11 + eobBin) * 2, eob >> (eobBin - 2) & 1);
1211
+ w.bools(eobBin - 2, eob & ((1 << (eobBin - 2)) - 1));
1212
+ }
1213
+ const levels = this.levels, order = scan(tx);
1214
+ const eobCdf = CDF.eobBaseTok + (tctx * 2 + chroma) * 16;
1215
+ const hiCdf = CDF.brTok + (Math.min(tctx, 3) * 2 + chroma) * 84;
1216
+ const tokOf = (v) => Math.min(Math.abs(v), 15);
1217
+ if (eob) {
1218
+ const loCdf = CDF.baseTok + (tctx * 2 + chroma) * 164;
1219
+ const nonsquare = tx >= RTX_4X8 ? 1 : 0, offsets = (nonsquare + (tx & nonsquare)) * 25;
1220
+ const stride = 4 << slh, shift = slh + 2, mask = (4 << slh) - 1;
1221
+ levels.fill(0, 0, stride * ((4 << slw) + 2));
1222
+ let hiMag = 0;
1223
+ const loCtx = (lv, x, y) => {
1224
+ let mg = levels[lv + 1] + levels[lv + stride];
1225
+ mg += levels[lv + stride + 1];
1226
+ hiMag = mg;
1227
+ mg += levels[lv + 2] + levels[lv + 2 * stride];
1228
+ const off = LO_CTX_OFFSETS[offsets + Math.min(y, 4) * 5 + Math.min(x, 4)];
1229
+ return off + (mg > 512 ? 4 : mg + 64 >> 7);
1230
+ };
1231
+ let rc = order[eob], x = rc >> shift, y = rc & mask;
1232
+ let tok = tokOf(q[rc]);
1233
+ const ctx = 1 + (eob > 2 << tx2d ? 1 : 0) + (eob > 4 << tx2d ? 1 : 0);
1234
+ w.symbol(cdf, eobCdf + ctx * 4, 2, Math.min(tok, 3) - 1);
1235
+ if (tok >= 3)
1236
+ w.hiTok(cdf, hiCdf + ((x | y) > 1 ? 14 : 7) * 4, tok);
1237
+ levels[x * stride + y] = tok >= 3 ? tok + (3 << 6) : tok * 0x41;
1238
+ for (let i = eob - 1; i > 0; i--) {
1239
+ rc = order[i];
1240
+ x = rc >> shift;
1241
+ y = rc & mask;
1242
+ const lv = x * stride + y;
1243
+ const c = loCtx(lv, x, y);
1244
+ tok = tokOf(q[rc]);
1245
+ w.symbol(cdf, loCdf + c * 4, 3, Math.min(tok, 3));
1246
+ if (tok >= 3) {
1247
+ const mag = hiMag & 63;
1248
+ w.hiTok(cdf, hiCdf + (((y | x) > 1 ? 14 : 7) + (mag > 12 ? 6 : mag + 1 >> 1)) * 4, tok);
1249
+ levels[lv] = tok + (3 << 6);
1250
+ }
1251
+ else
1252
+ levels[lv] = tok * 0x41;
1253
+ }
1254
+ tok = tokOf(q[0]);
1255
+ w.symbol(cdf, loCdf, 3, Math.min(tok, 3));
1256
+ if (tok >= 3) {
1257
+ const mag = levels[1] + levels[stride] + levels[stride + 1] & 63;
1258
+ w.hiTok(cdf, hiCdf + (mag > 12 ? 6 : mag + 1 >> 1) * 4, tok);
1259
+ }
1260
+ }
1261
+ else {
1262
+ const tok = tokOf(q[0]);
1263
+ w.symbol(cdf, eobCdf, 2, Math.min(tok, 3) - 1);
1264
+ if (tok >= 3)
1265
+ w.hiTok(cdf, hiCdf, tok);
1266
+ }
1267
+ let culLevel = 0, dcSignLevel = 1 << 6;
1268
+ if (q[0]) {
1269
+ let sctx2 = 0;
1270
+ for (let i = 0; i < aw; i++)
1271
+ sctx2 += aArr[a + i] >> 6;
1272
+ for (let i = 0; i < lh; i++)
1273
+ sctx2 += lArr[l + i] >> 6;
1274
+ sctx2 -= aw + lh;
1275
+ const dcSignCtx = (sctx2 !== 0 ? 1 : 0) + (sctx2 > 0 ? 1 : 0);
1276
+ const sign = q[0] < 0 ? 1 : 0;
1277
+ w.boolAdapt(cdf, CDF.dcSign + (chroma * 3 + dcSignCtx) * 2, sign);
1278
+ dcSignLevel = sign ? 0 : 2 << 6;
1279
+ if (Math.abs(q[0]) >= 15)
1280
+ w.golomb(Math.abs(q[0]) - 15);
1281
+ culLevel = Math.abs(q[0]);
1282
+ }
1283
+ for (let i = 1; i <= eob; i++) {
1284
+ const v = q[order[i]];
1285
+ if (!v)
1286
+ continue;
1287
+ w.bool(v < 0 ? 1 : 0);
1288
+ if (Math.abs(v) >= 15)
1289
+ w.golomb(Math.abs(v) - 15);
1290
+ culLevel += Math.abs(v);
1291
+ }
1292
+ const resCtx = Math.min(culLevel, 63) | dcSignLevel;
1293
+ aArr.fill(resCtx, a, a + ctw);
1294
+ lArr.fill(resCtx, l, l + cth);
1295
+ }
1296
+ }
1297
+ function level(width, height) {
1298
+ const area = width * height;
1299
+ if (area <= 2228224 && width <= 4096 && height <= 2176)
1300
+ return 8;
1301
+ if (area <= 8912896 && width <= 8192 && height <= 4352)
1302
+ return 12;
1303
+ if (area <= 35651584 && width <= 16384 && height <= 8704)
1304
+ return 16;
1305
+ return 31;
1306
+ }
1307
+ export function encodeAV1(image, params) {
1308
+ const { width, height, layout } = image;
1309
+ const bitsFor = (v) => Math.max(1, 32 - Math.clz32(v - 1));
1310
+ const seq = {
1311
+ profile: layout === 3 ? 1 : 0, reducedStillPicture: true, maxWidth: width, maxHeight: height,
1312
+ widthBits: bitsFor(width), heightBits: bitsFor(height), frameIdBits: 0, deltaFrameIdBits: 0,
1313
+ decoderModelInfo: false, equalPictureInterval: false, bufferRemovalDelayLength: 0, framePresentationDelayLength: 0,
1314
+ operatingPoints: [{ idc: 0, decoderModel: false }], sb128: false, filterIntra: false, intraEdgeFilter: true,
1315
+ screenContentTools: 2, forceIntegerMv: 2, orderHintBits: 0, superres: false, cdef: true, restoration: false,
1316
+ bitDepth: 8, monochrome: layout === 0, colorPrimaries: image.cicp[0], transferCharacteristics: image.cicp[1],
1317
+ matrixCoefficients: image.cicp[2], fullRange: true, ssx: layout === 1 ? 1 : 0, ssy: layout === 1 ? 1 : 0,
1318
+ separateUvDeltaQ: false, filmGrain: false
1319
+ };
1320
+ const sbw = width + 63 >> 6, sbh = height + 63 >> 6;
1321
+ const tileLog2 = (size, target) => {
1322
+ let k = 0;
1323
+ while (size << k < target)
1324
+ k++;
1325
+ return k;
1326
+ };
1327
+ const log2Cols = tileLog2(64, sbw), log2Rows = Math.max(tileLog2(2304, sbw * sbh) - log2Cols, 0);
1328
+ const colStarts = [], rowStarts = [];
1329
+ for (let x = 0; x < sbw; x += 1 + (sbw - 1 >> log2Cols))
1330
+ colStarts.push(x);
1331
+ for (let y = 0; y < sbh; y += 1 + (sbh - 1 >> log2Rows))
1332
+ rowStarts.push(y);
1333
+ const cols = colStarts.length, rows = rowStarts.length;
1334
+ colStarts.push(sbw);
1335
+ rowStarts.push(sbh);
1336
+ const qidx = params.qidx;
1337
+ const hdr = {
1338
+ showExistingFrame: false, existingFrameIdx: 0, frameType: 0, showFrame: true, refreshFrameFlags: 0xff,
1339
+ disableCdfUpdate: false, allowScreenContentTools: true, allowIntrabc: false, width, upscaledWidth: width, height,
1340
+ superresDenominator: 8,
1341
+ tiles: { cols, rows, log2Cols, log2Rows, colStarts, rowStarts, contextUpdateId: 0, sizeBytes: 4 },
1342
+ quant: { yac: qidx, ydcDelta: 0, udcDelta: 0, uacDelta: 0, vdcDelta: 0, vacDelta: 0, qm: false, qmY: 15, qmU: 15, qmV: 15 },
1343
+ segmentation: { enabled: false, updateMap: false, data: [], preskip: false, lastActiveSegId: -1, qidx: new Array(8).fill(qidx), lossless: new Array(8).fill(!qidx) },
1344
+ allLossless: !qidx,
1345
+ deltaQ: { present: false, resLog2: 0 },
1346
+ deltaLf: { present: false, resLog2: 0, multi: false },
1347
+ loopFilter: { levelY: [0, 0], levelU: 0, levelV: 0, sharpness: 0, modeRefDeltaEnabled: false, refDeltas: [1, 0, 0, 0, -1, 0, -1, -1], modeDeltas: [0, 0] },
1348
+ cdef: { damping: 3, bits: 0, yStrengths: [0], uvStrengths: [0] },
1349
+ restoration: { types: [RESTORATION_NONE, RESTORATION_NONE, RESTORATION_NONE], unitSizeLog2: [8, 8] },
1350
+ txMode: qidx ? 1 : 0, reducedTxSet: false, filmGrain: null
1351
+ };
1352
+ const f = new Frame(seq, hdr);
1353
+ const src = f.planes.map((plane, p) => {
1354
+ const sx = p && layout === 1 ? 1 : 0, w = width + sx >> sx, h = height + sx >> sx, stride = f.strides[p];
1355
+ const pw = f.bw * 4 >> sx, ph = f.bh * 4 >> sx, out = new Uint16Array(plane.length), inp = image.planes[p];
1356
+ for (let y = 0; y < ph; y++)
1357
+ for (let x = 0; x < pw; x++)
1358
+ out[y * stride + x] = inp[Math.min(y, h - 1) * w + Math.min(x, w - 1)];
1359
+ return out;
1360
+ });
1361
+ const encoder = new TileEncoder(f, src, params);
1362
+ const nodes = [];
1363
+ for (let r = 0; r < rows; r++)
1364
+ for (let c = 0; c < cols; c++)
1365
+ nodes.push(encoder.searchTile(r, c));
1366
+ for (let r = 0; r < rows; r++)
1367
+ for (let c = 0; c < cols; c++)
1368
+ encoder.storeTile(r, c, nodes[r * cols + c]);
1369
+ if (qidx)
1370
+ chooseFilters(f, src, qidx, params.effort, encoder.cdefChoice);
1371
+ f.cdefIdx.fill(-1);
1372
+ const tiles = [];
1373
+ for (let r = 0; r < rows; r++)
1374
+ for (let c = 0; c < cols; c++)
1375
+ tiles.push(encoder.writeTile(r, c, nodes[r * cols + c]));
1376
+ const w = new HeaderWriter();
1377
+ writeFrameHeader(w, seq, hdr);
1378
+ w.align();
1379
+ if (cols * rows > 1)
1380
+ w.bit(0);
1381
+ w.align();
1382
+ const head = w.data();
1383
+ let size = head.length;
1384
+ for (let i = 0; i < tiles.length; i++)
1385
+ size += tiles[i].length + (i < tiles.length - 1 ? 4 : 0);
1386
+ const payload = new Uint8Array(size);
1387
+ payload.set(head);
1388
+ let o = head.length;
1389
+ for (let i = 0; i < tiles.length; i++) {
1390
+ if (i < tiles.length - 1) {
1391
+ const n = tiles[i].length - 1;
1392
+ payload.set([n & 0xff, n >> 8 & 0xff, n >> 16 & 0xff, n >>> 24], o);
1393
+ o += 4;
1394
+ }
1395
+ payload.set(tiles[i], o);
1396
+ o += tiles[i].length;
1397
+ }
1398
+ const seqObu = writeSequenceHeader(seq, level(width, height)), frameObu = obu(OBU_FRAME, payload);
1399
+ const out = new Uint8Array(seqObu.length + frameObu.length);
1400
+ out.set(seqObu);
1401
+ out.set(frameObu, seqObu.length);
1402
+ return out;
1403
+ }
1404
+ function blockErrors(f, planes, src, ey, euv) {
1405
+ const s64 = f.b4Stride >> 4;
1406
+ ey.fill(0);
1407
+ euv.fill(0);
1408
+ planes.forEach((plane, p) => {
1409
+ const sx = p ? f.ssx : 0, sy = p ? f.ssy : 0, w = f.width + sx >> sx, h = f.height + sy >> sy, stride = f.strides[p];
1410
+ const out = p ? euv : ey;
1411
+ for (let y = 0; y < h; y++) {
1412
+ const row = (y << sy >> 6) * s64;
1413
+ for (let x = 0; x < w; x++) {
1414
+ const d = plane[y * stride + x] - src[p][y * stride + x];
1415
+ out[row + (x << sx >> 6)] += d * d;
1416
+ }
1417
+ }
1418
+ });
1419
+ }
1420
+ const sum = (a) => a.reduce((s, v) => s + v, 0);
1421
+ function chooseFilters(f, src, qidx, effort, choice) {
1422
+ const hdr = f.hdr, q = dequant(0, qidx, 1), n = f.cdefIdx.length;
1423
+ const recon = f.planes.map(p => p.slice());
1424
+ const ey = new Float64Array(n), euv = new Float64Array(n);
1425
+ const setLevel = (level) => {
1426
+ hdr.loopFilter.levelY = [level, level];
1427
+ hdr.loopFilter.levelU = hdr.loopFilter.levelV = level;
1428
+ for (let i = 0; i < f.lfLevels.length; i += 4)
1429
+ f.lfLevels.set([level, level, level, level], i);
1430
+ };
1431
+ const guess = Math.max(0, Math.min(63, (q * 20723 + 1015158 + (1 << 17) >> 18) - 4));
1432
+ let bestLevel = guess, bestError = Infinity;
1433
+ for (const level of [[guess], [guess - 4, guess, guess + 4], [guess - 6, guess - 3, guess, guess + 3, guess + 6]][effort]) {
1434
+ if (level < 0 || level > 63)
1435
+ continue;
1436
+ setLevel(level);
1437
+ f.planes = recon.map(p => p.slice());
1438
+ deblock(f);
1439
+ blockErrors(f, f.planes, src, ey, euv);
1440
+ const e = sum(ey) + sum(euv);
1441
+ if (e < bestError) {
1442
+ bestError = e;
1443
+ bestLevel = level;
1444
+ }
1445
+ }
1446
+ setLevel(bestLevel);
1447
+ f.planes = recon.map(p => p.slice());
1448
+ deblock(f);
1449
+ const deblocked = f.planes;
1450
+ const strengths = [[0, 5, 9, 17, 33], [0, 1, 4, 5, 9, 17, 33, 61], [0, 1, 4, 5, 8, 9, 13, 17, 25, 33, 41, 61]][effort];
1451
+ const errY = strengths.map(() => new Float64Array(n)), errUv = strengths.map(() => new Float64Array(n));
1452
+ const coded = Array.from(f.cdefIdx, i => i >= 0), dirs = new Int32Array(f.b4Stride * (f.bh + 1)).fill(-1);
1453
+ strengths.forEach((strength, k) => {
1454
+ hdr.cdef.yStrengths = [strength];
1455
+ hdr.cdef.uvStrengths = [strength];
1456
+ f.planes = deblocked.map(p => p.slice());
1457
+ f.cdefIdx.set(Int8Array.from(coded, c => c ? 0 : -1));
1458
+ if (strength)
1459
+ cdef(f, deblocked, dirs);
1460
+ blockErrors(f, f.planes, src, errY[k], errUv[k]);
1461
+ });
1462
+ const lambda = 0.08 * (q / 8) ** 2, blocks = coded.filter(c => c).length;
1463
+ const pairs = [];
1464
+ for (let y = 0; y < strengths.length; y++)
1465
+ for (let u = 0; u < strengths.length; u++)
1466
+ pairs.push([y, u]);
1467
+ const costOf = (set) => {
1468
+ let e = 0;
1469
+ for (let i = 0; i < n; i++) {
1470
+ if (!coded[i])
1471
+ continue;
1472
+ let m = Infinity;
1473
+ for (const [y, u] of set)
1474
+ m = Math.min(m, errY[y][i] + errUv[u][i]);
1475
+ e += m;
1476
+ }
1477
+ return e;
1478
+ };
1479
+ let set = [], best = [[0, 0]], bestCost = Infinity;
1480
+ for (let bits = 0; bits <= (effort ? 3 : 1); bits++) {
1481
+ while (set.length < 1 << bits) {
1482
+ let add = pairs[0], addCost = Infinity;
1483
+ for (const pair of pairs) {
1484
+ const c = costOf([...set, pair]);
1485
+ if (c < addCost) {
1486
+ addCost = c;
1487
+ add = pair;
1488
+ }
1489
+ }
1490
+ set = [...set, add];
1491
+ }
1492
+ const cost = costOf(set) + lambda * (bits * blocks + 12 * set.length);
1493
+ if (cost < bestCost) {
1494
+ bestCost = cost;
1495
+ best = set.slice();
1496
+ }
1497
+ }
1498
+ hdr.cdef.bits = Math.log2(best.length);
1499
+ hdr.cdef.yStrengths = best.map(([y]) => strengths[y]);
1500
+ hdr.cdef.uvStrengths = best.map(([, u]) => strengths[u]);
1501
+ for (let i = 0; i < n; i++) {
1502
+ let m = Infinity;
1503
+ best.forEach(([y, u], k) => {
1504
+ const e = errY[y][i] + errUv[u][i];
1505
+ if (e < m) {
1506
+ m = e;
1507
+ choice[i] = k;
1508
+ }
1509
+ });
1510
+ }
1511
+ f.planes = recon;
1512
+ }