imagescript 3.8.1 → 3.10.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.
@@ -1,3 +1,5 @@
1
+ import { runChunks, shared, startThreads } from "../../util/threads.js";
2
+ import { findPatches } from "./patches-enc.js";
1
3
  import { BitWriter } from "./bit-writer.js";
2
4
  import { imageHeader, u32 } from "./headers-enc.js";
3
5
  import { EntropyCode, Tokens, packSigned } from "./entropy-enc.js";
@@ -7,6 +9,7 @@ import { initialQuantField } from "./aq-enc.js";
7
9
  import { chooseVarblocks } from "./acs-enc.js";
8
10
  import { defaultDequant, MATRIX_INDEX } from "./quant.js";
9
11
  import { naturalOrder, DEFAULT_CTX_MAP, ORDER_ID, SIZES, single, transposed } from "./vardct.js";
12
+ const MIN_THREADED_PIXELS = [1536 << 10, 512 * 512, 384 * 384], PIXELS_PER_THREAD = [1 << 20, 256 << 10, 256 << 10];
10
13
  const OPSIN = [
11
14
  0.30, 0.622, 0.078,
12
15
  0.23, 0.692, 0.078,
@@ -17,9 +20,8 @@ const LINEAR = Float64Array.from({ length: 256 }, (_, i) => {
17
20
  const v = i / 255;
18
21
  return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
19
22
  });
20
- function toXYB(rgba, width, height, pw, ph) {
21
- const x = new Float32Array(pw * ph), y = new Float32Array(pw * ph), b = new Float32Array(pw * ph);
22
- for (let py = 0; py < ph; py++) {
23
+ function toXYB(rgba, width, height, pw, [x, y, b], y0, y1) {
24
+ for (let py = y0; py < y1; py++) {
23
25
  const sy = Math.min(py, height - 1);
24
26
  for (let px = 0; px < pw; px++) {
25
27
  const s = 4 * (sy * width + Math.min(px, width - 1));
@@ -33,7 +35,6 @@ function toXYB(rgba, width, height, pw, ph) {
33
35
  b[i] = s3;
34
36
  }
35
37
  }
36
- return [x, y, b];
37
38
  }
38
39
  function quantizer(distance) {
39
40
  const dcDistance = Math.max(0.5 * distance, Math.min(distance, 0.3 * (distance / 0.3) ** 0.83));
@@ -77,53 +78,185 @@ function inverseMatrices(type) {
77
78
  inverses.set(type, inv = defaultDequant(MATRIX_INDEX[type])[transposed(type) ? 1 : 0].map(m => Float32Array.from(m, v => 1 / v)));
78
79
  return inv;
79
80
  }
80
- function chromaFromLuma(raw, types, muls, pw, bw, bh, globalScale, xFromY, bFromY) {
81
+ function chromaFromLuma(raw, types, muls, pw, bw, bh, globalScale, xFromY, bFromY, ty) {
81
82
  const tilesPerRow = Math.ceil(bw / 8);
82
- for (let ty = 0; ty < bh; ty += 8) {
83
- for (let tx = 0; tx < bw; tx += 8) {
84
- const sums = [0, 0, 0, 0];
85
- let num = 0;
86
- for (let by = ty; by < Math.min(ty + 8, bh); by++) {
87
- for (let bx = tx; bx < Math.min(tx + 8, bw); bx++) {
88
- const type = types[by * bw + bx];
89
- if (type < 0)
90
- continue;
91
- const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1], w = w8 * 8, h = h8 * 8, o = by * 8 * pw + bx * 8, one = single(type);
92
- const inv = inverseMatrices(type), q = globalScale / 65536 * 128 * muls[by * bw + bx];
93
- num += w * h;
83
+ for (let tx = 0; tx < bw; tx += 8) {
84
+ const sums = [0, 0, 0, 0];
85
+ let num = 0;
86
+ for (let by = ty; by < Math.min(ty + 8, bh); by++) {
87
+ for (let bx = tx; bx < Math.min(tx + 8, bw); bx++) {
88
+ const type = types[by * bw + bx];
89
+ if (type < 0)
90
+ continue;
91
+ const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1], w = w8 * 8, h = h8 * 8, o = (by - ty) * 8 * pw + bx * 8, one = single(type);
92
+ const inv = inverseMatrices(type), q = globalScale / 65536 * 128 * muls[by * bw + bx];
93
+ num += w * h;
94
+ for (let y = 0; y < h; y++) {
95
+ for (let x = 0; x < w; x++) {
96
+ if (one ? x === 0 && y === 0 : x < w8 && y < h8)
97
+ continue;
98
+ const k = y * w + x, yv = raw[1][o + y * pw + x];
99
+ for (let c = 0; c < 2; c++) {
100
+ const ch = c ? 2 : 0, qm = q * inv[ch][k], base = c;
101
+ const a = yv * qm / 84, b = base * yv * qm - raw[ch][o + y * pw + x] * qm;
102
+ sums[2 * c] += a * a;
103
+ sums[2 * c + 1] += a * b;
104
+ }
105
+ }
106
+ }
107
+ }
108
+ }
109
+ const factor = (aa, ab) => {
110
+ if (!num)
111
+ return 0;
112
+ let x = -ab / (aa + num * 1e-9 * 0.5);
113
+ x = x >= 2.6 ? x - 2.6 : x <= -2.6 ? x + 2.6 : 0;
114
+ return Math.max(-128, Math.min(127, Math.round(x)));
115
+ };
116
+ const t = (ty >> 3) * tilesPerRow + (tx >> 3);
117
+ xFromY[t] = factor(sums[0], sums[1]);
118
+ bFromY[t] = factor(sums[2], sums[3]);
119
+ }
120
+ }
121
+ export function xybChunks({ rgba, width, height, pw, planes }) {
122
+ const ph = planes[0].length / pw;
123
+ return band => toXYB(rgba, width, height, pw, planes, band * 64, Math.min(ph, band * 64 + 64));
124
+ }
125
+ export function coefficientChunks({ planes, pw, bw, bh, types, muls, globalScale, qmMul, cfl, lfValues, xFromY, bFromY, hf }) {
126
+ const tilesPerRow = Math.ceil(bw / 8);
127
+ const raw = [0, 1, 2].map(() => new Float32Array(pw * 64));
128
+ const coeffs = new Float32Array(MAX_COEFFS), lfBlock = new Float32Array(MAX_COEFFS / 64), yDequant = new Float32Array(MAX_COEFFS);
129
+ return row => {
130
+ const ty = row * 8, rows = Math.min(8, bh - ty);
131
+ for (let by = ty; by < ty + rows; by++) {
132
+ for (let bx = 0; bx < bw; bx++) {
133
+ const type = types[by * bw + bx];
134
+ if (type < 0)
135
+ continue;
136
+ const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1], w = w8 * 8, h = h8 * 8, o = (by - ty) * 8 * pw + bx * 8;
137
+ for (let c = 0; c < 3; c++) {
138
+ forwardTransform(type, planes[c], by * 8 * pw + bx * 8, pw, coeffs, lfBlock);
139
+ for (let y = 0; y < h; y++)
140
+ raw[c].set(coeffs.subarray(y * w, (y + 1) * w), o + y * pw);
141
+ for (let y = 0; y < h8; y++)
142
+ for (let x = 0; x < w8; x++)
143
+ lfValues[c][(by + y) * bw + bx + x] = lfBlock[y * w8 + x];
144
+ }
145
+ }
146
+ }
147
+ if (cfl)
148
+ chromaFromLuma(raw, types, muls, pw, bw, bh, globalScale, xFromY, bFromY, ty);
149
+ for (let by = ty; by < ty + rows; by++) {
150
+ for (let bx = 0; bx < bw; bx++) {
151
+ const bi = by * bw + bx, type = types[bi];
152
+ if (type < 0)
153
+ continue;
154
+ const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1], w = w8 * 8, h = h8 * 8, o = (by - ty) * 8 * pw + bx * 8, go = by * 8 * pw + bx * 8;
155
+ const tile = row * tilesPerRow + (bx >> 3), k0s = [xFromY[tile] / 84, 0, 1 + bFromY[tile] / 84];
156
+ const [m0, m1] = defaultDequant(MATRIX_INDEX[type]), matrices = transposed(type) ? m1 : m0;
157
+ const hfStep = 65536 / (globalScale * muls[bi]), one = single(type);
158
+ for (const c of [1, 0, 2]) {
159
+ const src = raw[c], m = matrices[c], out = hf[c], k0 = k0s[c];
160
+ const thresholds = c === 1 ? [0.56, 0.62, 0.62, 0.62] : [0.58, 0.62, 0.62, 0.62];
161
+ if (c !== 1 && w8 * h8 >= 4)
162
+ for (let i = 0; i < 4; i++)
163
+ thresholds[i] = Math.max(0.5, thresholds[i] - 0.00744 * w8 * h8);
164
+ const scale = qmMul[c] / hfStep;
94
165
  for (let y = 0; y < h; y++) {
95
166
  for (let x = 0; x < w; x++) {
96
- if (one ? x === 0 && y === 0 : x < w8 && y < h8)
167
+ const k = y * w + x;
168
+ if (one ? k === 0 : x < w8 && y < h8)
97
169
  continue;
98
- const k = y * w + x, yv = raw[1][o + y * pw + x];
99
- for (let c = 0; c < 2; c++) {
100
- const ch = c ? 2 : 0, qm = q * inv[ch][k], base = c;
101
- const a = yv * qm / 84, b = base * yv * qm - raw[ch][o + y * pw + x] * qm;
102
- sums[2 * c] += a * a;
103
- sums[2 * c + 1] += a * b;
170
+ const v = (c === 1 ? src[o + y * pw + x] : src[o + y * pw + x] - k0 * yDequant[k]) / m[k] * scale;
171
+ const q = Math.abs(v) >= thresholds[(y >= h / 2 ? 2 : 0) + (x >= w / 2 ? 1 : 0)] ? Math.round(v) : 0;
172
+ out[go + y * pw + x] = q;
173
+ if (c === 1) {
174
+ const d = q === 0 ? 0 : Math.abs(q) <= 1 ? q * QUANT_BIAS[1] : q - QUANT_BIAS_NUMERATOR / q;
175
+ yDequant[k] = d * m[k] * hfStep;
104
176
  }
105
177
  }
106
178
  }
107
179
  }
108
180
  }
109
- const factor = (aa, ab) => {
110
- if (!num)
111
- return 0;
112
- let x = -ab / (aa + num * 1e-9 * 0.5);
113
- x = x >= 2.6 ? x - 2.6 : x <= -2.6 ? x + 2.6 : 0;
114
- return Math.max(-128, Math.min(127, Math.round(x)));
115
- };
116
- const t = (ty >> 3) * tilesPerRow + (tx >> 3);
117
- xFromY[t] = factor(sums[0], sums[1]);
118
- bFromY[t] = factor(sums[2], sums[3]);
119
181
  }
120
- }
182
+ };
121
183
  }
122
- export function encodeVarDCT(rgba, width, height, { distance, effort }) {
184
+ export function hfTokenChunks({ types, hf, pw, bw, bh, groupsPerRow }) {
185
+ return g => {
186
+ const bx0 = (g % groupsPerRow) * 32, by0 = Math.floor(g / groupsPerRow) * 32;
187
+ const gw = Math.min(32, bw - bx0), gh = Math.min(32, bh - by0), t = new Tokens();
188
+ const nonZeros = [0, 1, 2].map(() => new Uint32Array(gw));
189
+ for (let y = 0; y < gh; y++) {
190
+ for (let x = 0; x < gw; x++) {
191
+ const type = types[(by0 + y) * bw + bx0 + x];
192
+ if (type < 0)
193
+ continue;
194
+ const w8 = SIZES[2 * type], numBlocks = w8 * SIZES[2 * type + 1], log = 31 - Math.clz32(numBlocks);
195
+ const orderId = ORDER_ID[type], order = naturalOrder(orderId), n = order.length / 2, tr = transposed(type);
196
+ const o = (by0 + y) * 8 * pw + (bx0 + x) * 8;
197
+ const at = (i) => tr ? o + order[2 * i] * pw + order[2 * i + 1] : o + order[2 * i + 1] * pw + order[2 * i];
198
+ for (let k = 0; k < 3; k++) {
199
+ const c = [1, 0, 2][k], q = hf[c], nz = nonZeros[c], blockCtx = DEFAULT_CTX_MAP[k * 13 + orderId];
200
+ let count = 0;
201
+ for (let i = numBlocks; i < n; i++)
202
+ if (q[at(i)])
203
+ count++;
204
+ const predicted = y === 0 ? (x === 0 ? 32 : nz[x - 1]) : x === 0 ? nz[x] : (nz[x] + nz[x - 1] + 1) >> 1;
205
+ t.push(blockCtx + (predicted >= 8 ? 4 + (predicted >> 1) : predicted) * NUM_BLOCK_CTX, count);
206
+ const value = (count + numBlocks - 1) >> log;
207
+ for (let dx = 0; dx < w8; dx++)
208
+ nz[x + dx] = value;
209
+ let prevNonZero = count <= numBlocks * 4 ? 1 : 0;
210
+ const ctxBase = blockCtx * 458 + 37 * NUM_BLOCK_CTX;
211
+ for (let i = numBlocks; i < n && count > 0; i++) {
212
+ const v = q[at(i)];
213
+ t.push(ctxBase + (NUM_NONZERO_CONTEXT[(count - 1) >> log] + FREQ_CONTEXT[(i - numBlocks) >> log]) * 2 + prevNonZero, packSigned(v));
214
+ prevNonZero = v ? 1 : 0;
215
+ if (v)
216
+ count--;
217
+ }
218
+ }
219
+ }
220
+ }
221
+ return { ctx: t.ctx.slice(0, t.length), value: t.value.slice(0, t.length), length: t.length };
222
+ };
223
+ }
224
+ export async function encodeVarDCT(rgba, width, height, options) {
123
225
  if (width < 1 || height < 1)
124
226
  throw new RangeError('JPEG XL: dimensions must be at least 1');
227
+ const n = Math.min(options.threads, Math.ceil(height / 64), Math.max(4, Math.floor(width * height / PIXELS_PER_THREAD[options.effort])));
228
+ const pool = { threads: n > 1 && width * height >= MIN_THREADED_PIXELS[options.effort] ? startThreads(n) : null };
229
+ try {
230
+ return await encode(rgba, width, height, options, pool);
231
+ }
232
+ finally {
233
+ if (pool.threads)
234
+ for (const t of pool.threads)
235
+ t.terminate();
236
+ }
237
+ }
238
+ async function encode(rgba, width, height, { distance, effort }, pool) {
125
239
  const bw = Math.ceil(width / 8), bh = Math.ceil(height / 8), pw = bw * 8;
126
- const planes = toXYB(rgba, width, height, pw, bh * 8);
240
+ const parallel = async (run) => {
241
+ if (pool.threads) {
242
+ try {
243
+ return await run(pool.threads);
244
+ }
245
+ catch {
246
+ for (const t of pool.threads)
247
+ t.terminate();
248
+ pool.threads = null;
249
+ }
250
+ }
251
+ return run(null);
252
+ };
253
+ const threaded = !!pool.threads;
254
+ const array = (Type, bytes, length) => new Type(threaded ? new SharedArrayBuffer(bytes * length) : new ArrayBuffer(bytes * length));
255
+ const planes = [0, 1, 2].map(() => array(Float32Array, 4, pw * bh * 8));
256
+ {
257
+ const task = { task: 'jxl-xyb', rgba: threaded ? shared(rgba) : rgba, width, height, pw, planes };
258
+ await parallel(t => runChunks(t, task, bh + 7 >> 3, xybChunks(task)));
259
+ }
127
260
  let alpha = null;
128
261
  for (let i = 3; i < rgba.length; i += 4) {
129
262
  if (rgba[i] === 255)
@@ -138,66 +271,22 @@ export function encodeVarDCT(rgba, width, height, { distance, effort }) {
138
271
  const qmMul = [1.25 ** (xqmScale - 2), 1, 1.25 ** (bqmScale - 2)];
139
272
  const epfIters = [0.7, 1.5, 4].filter(t => distance >= t).length;
140
273
  const lfStep = LF_DEQUANT.map(m => m * 512 / (globalScale * quantLf));
141
- const types = effort ? chooseVarblocks(planes, pw, bw, bh, initialQuantField(distance * 0.62, planes, pw, bh * 8, 0.725 / (distance * 0.62)), distance, effort === 1 ? 5 : 4) : new Int8Array(bw * bh);
142
- const muls = new Int32Array(bw * bh).fill(mul);
143
- const lfValues = [0, 1, 2].map(() => new Float32Array(bw * bh));
144
- const raw = [0, 1, 2].map(() => new Float32Array(pw * bh * 8));
145
- const coeffs = new Float32Array(MAX_COEFFS), lfBlock = new Float32Array(MAX_COEFFS / 64);
146
- for (let by = 0; by < bh; by++) {
147
- for (let bx = 0; bx < bw; bx++) {
148
- const type = types[by * bw + bx];
149
- if (type < 0)
150
- continue;
151
- const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1], w = w8 * 8, h = h8 * 8, o = by * 8 * pw + bx * 8;
152
- for (let c = 0; c < 3; c++) {
153
- forwardTransform(type, planes[c], o, pw, coeffs, lfBlock);
154
- for (let y = 0; y < h; y++)
155
- raw[c].set(coeffs.subarray(y * w, (y + 1) * w), o + y * pw);
156
- for (let y = 0; y < h8; y++)
157
- for (let x = 0; x < w8; x++)
158
- lfValues[c][(by + y) * bw + bx + x] = lfBlock[y * w8 + x];
159
- }
160
- }
274
+ const patches = effort >= 2 ? findPatches(planes, pw, width, height, distance, alpha ? 1 : 0) : null;
275
+ let types = array(Int8Array, 1, bw * bh);
276
+ if (effort) {
277
+ const field = await parallel(t => initialQuantField(distance * 0.62, planes, pw, bh * 8, 0.725 / (distance * 0.62), t));
278
+ types = await parallel(t => chooseVarblocks(planes, pw, bw, bh, field, distance, effort === 1 ? 5 : 4, t));
161
279
  }
280
+ const muls = array(Int32Array, 4, bw * bh).fill(mul);
162
281
  const tilesPerRow = Math.ceil(bw / 8), tileRows = Math.ceil(bh / 8);
163
- const xFromY = new Int32Array(tilesPerRow * tileRows), bFromY = new Int32Array(tilesPerRow * tileRows);
164
- if (effort)
165
- chromaFromLuma(raw, types, muls, pw, bw, bh, globalScale, xFromY, bFromY);
166
- const hf = [0, 1, 2].map(() => new Int32Array(pw * bh * 8));
167
- const yDequant = new Float32Array(MAX_COEFFS);
168
- for (let by = 0; by < bh; by++) {
169
- for (let bx = 0; bx < bw; bx++) {
170
- const bi = by * bw + bx, type = types[bi];
171
- if (type < 0)
172
- continue;
173
- const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1], w = w8 * 8, h = h8 * 8, o = by * 8 * pw + bx * 8;
174
- const tile = (by >> 3) * tilesPerRow + (bx >> 3), cfl = [xFromY[tile] / 84, 0, 1 + bFromY[tile] / 84];
175
- const [m0, m1] = defaultDequant(MATRIX_INDEX[type]), matrices = transposed(type) ? m1 : m0;
176
- const hfStep = 65536 / (globalScale * muls[bi]), one = single(type);
177
- for (const c of [1, 0, 2]) {
178
- const src = raw[c], m = matrices[c], out = hf[c], k0 = cfl[c];
179
- const thresholds = c === 1 ? [0.56, 0.62, 0.62, 0.62] : [0.58, 0.62, 0.62, 0.62];
180
- if (c !== 1 && w8 * h8 >= 4)
181
- for (let i = 0; i < 4; i++)
182
- thresholds[i] = Math.max(0.5, thresholds[i] - 0.00744 * w8 * h8);
183
- const scale = qmMul[c] / hfStep;
184
- for (let y = 0; y < h; y++) {
185
- for (let x = 0; x < w; x++) {
186
- const k = y * w + x;
187
- if (one ? k === 0 : x < w8 && y < h8)
188
- continue;
189
- const v = (c === 1 ? src[o + y * pw + x] : src[o + y * pw + x] - k0 * yDequant[k]) / m[k] * scale;
190
- const q = Math.abs(v) >= thresholds[(y >= h / 2 ? 2 : 0) + (x >= w / 2 ? 1 : 0)] ? Math.round(v) : 0;
191
- out[o + y * pw + x] = q;
192
- if (c === 1) {
193
- const d = q === 0 ? 0 : Math.abs(q) <= 1 ? q * QUANT_BIAS[1] : q - QUANT_BIAS_NUMERATOR / q;
194
- yDequant[k] = d * m[k] * hfStep;
195
- }
196
- }
197
- }
198
- }
199
- }
200
- }
282
+ const coefficients = {
283
+ task: 'jxl-coefficients', planes, pw, bw, bh, types, muls, globalScale, qmMul, cfl: effort > 0,
284
+ lfValues: [0, 1, 2].map(() => array(Float32Array, 4, bw * bh)),
285
+ xFromY: array(Int32Array, 4, tilesPerRow * tileRows), bFromY: array(Int32Array, 4, tilesPerRow * tileRows),
286
+ hf: [0, 1, 2].map(() => array(Int32Array, 4, pw * bh * 8)),
287
+ };
288
+ await parallel(t => runChunks(t, coefficients, tileRows, coefficientChunks(coefficients)));
289
+ const { lfValues, xFromY, bFromY, hf } = coefficients;
201
290
  const lf = [0, 1, 2].map(() => new Int32Array(bw * bh));
202
291
  for (let i = 0; i < bw * bh; i++) {
203
292
  const ly = Math.round(lfValues[1][i] / lfStep[1]);
@@ -256,49 +345,13 @@ export function encodeVarDCT(rgba, width, height, { distance, effort }) {
256
345
  }
257
346
  }
258
347
  const modularCode = new EntropyCode([...lfTokens, ...alphaTokens], tree.numLeaves);
259
- const hfTokens = [];
260
- for (let g = 0; g < numGroups; g++) {
261
- const bx0 = (g % groupsPerRow) * 32, by0 = Math.floor(g / groupsPerRow) * 32;
262
- const gw = Math.min(32, bw - bx0), gh = Math.min(32, bh - by0), t = new Tokens();
263
- const nonZeros = [0, 1, 2].map(() => new Uint32Array(gw));
264
- for (let y = 0; y < gh; y++) {
265
- for (let x = 0; x < gw; x++) {
266
- const type = types[(by0 + y) * bw + bx0 + x];
267
- if (type < 0)
268
- continue;
269
- const w8 = SIZES[2 * type], numBlocks = w8 * SIZES[2 * type + 1], log = 31 - Math.clz32(numBlocks);
270
- const orderId = ORDER_ID[type], order = naturalOrder(orderId), n = order.length / 2, tr = transposed(type);
271
- const o = (by0 + y) * 8 * pw + (bx0 + x) * 8;
272
- const at = (i) => tr ? o + order[2 * i] * pw + order[2 * i + 1] : o + order[2 * i + 1] * pw + order[2 * i];
273
- for (let k = 0; k < 3; k++) {
274
- const c = [1, 0, 2][k], q = hf[c], nz = nonZeros[c], blockCtx = DEFAULT_CTX_MAP[k * 13 + orderId];
275
- let count = 0;
276
- for (let i = numBlocks; i < n; i++)
277
- if (q[at(i)])
278
- count++;
279
- const predicted = y === 0 ? (x === 0 ? 32 : nz[x - 1]) : x === 0 ? nz[x] : (nz[x] + nz[x - 1] + 1) >> 1;
280
- t.push(blockCtx + (predicted >= 8 ? 4 + (predicted >> 1) : predicted) * NUM_BLOCK_CTX, count);
281
- const value = (count + numBlocks - 1) >> log;
282
- for (let dx = 0; dx < w8; dx++)
283
- nz[x + dx] = value;
284
- let prevNonZero = count <= numBlocks * 4 ? 1 : 0;
285
- const ctxBase = blockCtx * 458 + 37 * NUM_BLOCK_CTX;
286
- for (let i = numBlocks; i < n && count > 0; i++) {
287
- const v = q[at(i)];
288
- t.push(ctxBase + (NUM_NONZERO_CONTEXT[(count - 1) >> log] + FREQ_CONTEXT[(i - numBlocks) >> log]) * 2 + prevNonZero, packSigned(v));
289
- prevNonZero = v ? 1 : 0;
290
- if (v)
291
- count--;
292
- }
293
- }
294
- }
295
- }
296
- hfTokens.push(t);
297
- }
348
+ const tokens = { task: 'jxl-hf-tokens', types, hf, pw, bw, bh, groupsPerRow };
349
+ const hfTokens = (await parallel(t => runChunks(t, tokens, numGroups, hfTokenChunks(tokens)))).map(r => Object.assign(new Tokens(), r));
298
350
  const hfCode = new EntropyCode(hfTokens, 495 * NUM_BLOCK_CTX);
299
351
  const sections = [];
300
352
  {
301
353
  const w = new BitWriter();
354
+ patches?.writeDictionary(w);
302
355
  w.write(1, 1);
303
356
  u32(w, globalScale, [[11, 1], [11, 2049], [12, 4097], [16, 8193]]);
304
357
  u32(w, quantLf, [[0, 16], [5, 1], [8, 1], [16, 1]]);
@@ -343,7 +396,9 @@ export function encodeVarDCT(rgba, width, height, { distance, effort }) {
343
396
  }
344
397
  const out = new BitWriter();
345
398
  imageHeader(out, width, height, alpha ? 4 : 3, true);
346
- frameHeader(out, xqmScale, bqmScale, epfIters, alpha !== null);
399
+ if (patches)
400
+ out.append(patches.frame);
401
+ frameHeader(out, xqmScale, bqmScale, epfIters, alpha !== null, !!patches);
347
402
  if (numGroups === 1) {
348
403
  const all = new BitWriter();
349
404
  for (const s of sections)
@@ -367,11 +422,16 @@ export function encodeVarDCT(rgba, width, height, { distance, effort }) {
367
422
  }
368
423
  return bytes;
369
424
  }
370
- function frameHeader(w, xqmScale, bqmScale, epfIters, alpha) {
425
+ function frameHeader(w, xqmScale, bqmScale, epfIters, alpha, patches) {
371
426
  w.write(1, 0);
372
427
  w.write(2, 0);
373
428
  w.write(1, 0);
374
- w.write(2, 0);
429
+ if (patches) {
430
+ w.write(2, 1);
431
+ w.write(4, 1);
432
+ }
433
+ else
434
+ w.write(2, 0);
375
435
  w.write(2, 0);
376
436
  if (alpha)
377
437
  w.write(2, 0);
@@ -101,8 +101,11 @@ export class VarDCT {
101
101
  tilesPerRow;
102
102
  lfQuant;
103
103
  lf;
104
- coeffs;
105
104
  matrices = null;
105
+ renderLf = [];
106
+ planes = [];
107
+ quantBias = [];
108
+ quantBiasNumerator = 0;
106
109
  numPresets = 1;
107
110
  passes = [];
108
111
  hasLfQuant = false;
@@ -130,7 +133,6 @@ export class VarDCT {
130
133
  this.bFromY = new Int32Array(this.tilesPerRow * Math.ceil(bh / 8));
131
134
  this.lfQuant = [0, 1, 2].map(c => new Int32Array((bw >> this.hs[c]) * (bh >> this.vs[c])));
132
135
  this.lf = [0, 1, 2].map(c => new Float32Array((bw >> this.hs[c]) * (bh >> this.vs[c])));
133
- this.coeffs = [0, 1, 2].map(c => new Int32Array((bw >> this.hs[c]) * (bh >> this.vs[c]) * 64));
134
136
  }
135
137
  lfGroupBlocks(g) {
136
138
  const dim = this.f.groupDim, x0 = (g % this.f.lfGroupsPerRow) * dim, y0 = Math.floor(g / this.f.lfGroupsPerRow) * dim;
@@ -246,7 +248,7 @@ export class VarDCT {
246
248
  this.passes.push({ orders, dist: new EntropyDecoder(r, 495 * this.numPresets * this.g.ctx.numClusters) });
247
249
  }
248
250
  }
249
- readPassGroup(r, pass, group) {
251
+ readPassGroup(r, pass, group, coeffs) {
250
252
  const f = this.f, ctx = this.g.ctx, hp = this.passes[pass];
251
253
  const gdim = f.groupDim / 8, bx0 = (group % f.groupsPerRow) * gdim, by0 = Math.floor(group / f.groupsPerRow) * gdim;
252
254
  const width = Math.min(gdim, this.bw - bx0), height = Math.min(gdim, this.bh - by0);
@@ -305,8 +307,8 @@ export class VarDCT {
305
307
  nz[sx + dx] = value;
306
308
  if (!count)
307
309
  continue;
308
- const out = this.coeffs[c], stride = (bw >> hs[c]) * 8;
309
- const base = (((by0 >> vs[c]) + sy) * 8) * stride + ((bx0 >> hs[c]) + sx) * 8;
310
+ const out = coeffs[c], stride = this.groupStride(c);
311
+ const base = sy * 8 * stride + sx * 8;
310
312
  const order = hp.orders[orderId][c], tr = transposed(type);
311
313
  let prevNonZero = count <= numBlocks * 4 ? 1 : 0;
312
314
  const ctxBase = blockCtx * 458 + 37 * nc, n = order.length / 2;
@@ -332,7 +334,7 @@ export class VarDCT {
332
334
  }
333
335
  dist.finish();
334
336
  }
335
- render(quantBias, quantBiasNumerator, lfFrame) {
337
+ prepare(quantBias, quantBiasNumerator, lfFrame, planes) {
336
338
  const f = this.f, g = this.g, bw = this.bw, bh = this.bh, hs = this.hs, vs = this.vs;
337
339
  let lf = this.lf;
338
340
  if (lfFrame)
@@ -351,22 +353,55 @@ export class VarDCT {
351
353
  lf = smoothLf(lf, [0, 1, 2].map(c => bw >> hs[c]), [0, 1, 2].map(c => bh >> vs[c]), this.lfDequant.map(m => m * sc), hs, vs);
352
354
  }
353
355
  }
356
+ this.renderLf = lf;
357
+ this.planes = planes ?? [0, 1, 2].map(c => new Float32Array((bw >> hs[c]) * (bh >> vs[c]) * 64));
358
+ this.quantBias = quantBias;
359
+ this.quantBiasNumerator = quantBiasNumerator;
360
+ }
361
+ share() {
362
+ return {
363
+ type: this.type, hfMul: this.hfMul, xFromY: this.xFromY, bFromY: this.bFromY, lfQuant: this.lfQuant, hasLfQuant: this.hasLfQuant,
364
+ renderLf: this.renderLf, quantBias: this.quantBias, quantBiasNumerator: this.quantBiasNumerator,
365
+ };
366
+ }
367
+ adopt(s, planes) {
368
+ this.type.set(s.type);
369
+ this.hfMul.set(s.hfMul);
370
+ this.xFromY.set(s.xFromY);
371
+ this.bFromY.set(s.bFromY);
372
+ s.lfQuant.forEach((q, c) => this.lfQuant[c].set(q));
373
+ this.hasLfQuant = s.hasLfQuant;
374
+ this.renderLf = s.renderLf;
375
+ this.quantBias = s.quantBias;
376
+ this.quantBiasNumerator = s.quantBiasNumerator;
377
+ this.planes = planes;
378
+ }
379
+ get rendered() {
380
+ return this.planes;
381
+ }
382
+ groupStride(c) {
383
+ return (this.f.groupDim >> this.hs[c]);
384
+ }
385
+ renderGroup(group, coeffs) {
386
+ const f = this.f, g = this.g, bw = this.bw, hs = this.hs, vs = this.vs, planes = this.planes, lf = this.renderLf;
387
+ const gdim = f.groupDim / 8, bx0 = (group % f.groupsPerRow) * gdim, by0 = Math.floor(group / f.groupsPerRow) * gdim;
388
+ const width = Math.min(gdim, bw - bx0), height = Math.min(gdim, this.bh - by0);
354
389
  const m = this.matrices;
355
390
  const qmScale = [0.8 ** (f.xqmScale - 2), 1, 0.8 ** (f.bqmScale - 2)];
356
- const planes = [0, 1, 2].map(c => new Float32Array(this.coeffs[c].length));
357
391
  for (let c = 0; c < 3; c++) {
358
- const q = this.coeffs[c], out = planes[c], stride = (bw >> hs[c]) * 8, bias = quantBias[c];
359
- this.forEachVarblock(c, (sbx, sby, type, mul) => {
392
+ const q = coeffs[c], out = planes[c], stride = (bw >> hs[c]) * 8, bias = this.quantBias[c], qbn = this.quantBiasNumerator;
393
+ const qStride = this.groupStride(c), gx = bx0 >> hs[c], gy = by0 >> vs[c];
394
+ this.forEachVarblock(c, bx0, by0, width, height, (sbx, sby, type, mul) => {
360
395
  const w = SIZES[2 * type] * 8, h = SIZES[2 * type + 1] * 8, idx = MATRIX_INDEX[type];
361
396
  const matrix = transposed(type) ? m.transposed[idx][c] : m.matrices[idx][c];
362
397
  const k = 65536 / (g.globalScale * mul) * qmScale[c];
363
398
  for (let y = 0; y < h; y++) {
364
- const o = (sby * 8 + y) * stride + sbx * 8;
399
+ const o = (sby * 8 + y) * stride + sbx * 8, oq = ((sby - gy) * 8 + y) * qStride + (sbx - gx) * 8;
365
400
  for (let x = 0; x < w; x++) {
366
- let v = q[o + x];
401
+ let v = q[oq + x];
367
402
  if (v === 0)
368
403
  continue;
369
- v = Math.abs(v) <= 1 ? v * bias : v - quantBiasNumerator / v;
404
+ v = Math.abs(v) <= 1 ? v * bias : v - qbn / v;
370
405
  out[o + x] = v * matrix[y * w + x] * k;
371
406
  }
372
407
  }
@@ -374,8 +409,8 @@ export class VarDCT {
374
409
  }
375
410
  if (!this.subsampled) {
376
411
  const [x, y, b] = planes, stride = bw * 8;
377
- for (let py = 0; py < bh * 8; py++) {
378
- for (let tx = 0; tx < this.tilesPerRow; tx++) {
412
+ for (let py = by0 * 8; py < (by0 + height) * 8; py++) {
413
+ for (let tx = bx0 >> 3; tx < (bx0 + width + 7) >> 3; tx++) {
379
414
  const t = (py >> 6) * this.tilesPerRow + tx;
380
415
  const kx = g.baseX + this.xFromY[t] / g.colourFactor, kb = g.baseB + this.bFromY[t] / g.colourFactor;
381
416
  const end = Math.min(tx * 64 + 64, stride);
@@ -388,7 +423,7 @@ export class VarDCT {
388
423
  }
389
424
  for (let c = 0; c < 3; c++) {
390
425
  const out = planes[c], stride = (bw >> hs[c]) * 8, lfc = lf[c], lfStride = bw >> hs[c];
391
- this.forEachVarblock(c, (sbx, sby, type) => {
426
+ this.forEachVarblock(c, bx0, by0, width, height, (sbx, sby, type) => {
392
427
  const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1];
393
428
  const llf = { buf: out, offset: sby * 8 * stride + sbx * 8, stride, w: w8, h: h8 };
394
429
  if (single(type))
@@ -406,15 +441,14 @@ export class VarDCT {
406
441
  inverseTransform({ buf: out, offset: llf.offset, stride, w: w8 * 8, h: h8 * 8 }, type);
407
442
  });
408
443
  }
409
- return planes;
410
444
  }
411
445
  stride(c) {
412
446
  return (this.bw >> this.hs[c]) * 8;
413
447
  }
414
- forEachVarblock(c, fn) {
448
+ forEachVarblock(c, bx0, by0, w, h, fn) {
415
449
  const bw = this.bw, hs = this.hs[c], vs = this.vs[c], gdim = this.f.groupDim / 8;
416
- for (let by = 0; by < this.bh; by++) {
417
- for (let bx = 0; bx < bw; bx++) {
450
+ for (let by = by0; by < by0 + h; by++) {
451
+ for (let bx = bx0; bx < bx0 + w; bx++) {
418
452
  const type = this.type[by * bw + bx];
419
453
  if (type < 0)
420
454
  continue;
@@ -1,3 +1,4 @@
1
+ import { startThreads } from "../util/threads.js";
1
2
  import { MAX_PIXELS, checkPixels } from "../util/limits.js";
2
3
  import { BitReader } from "./jxl/bits.js";
3
4
  import { imageHeader, skipICC } from "./jxl/headers.js";
@@ -13,8 +14,8 @@ export function isJXL(d) {
13
14
  return true;
14
15
  return d.length >= 12 && CONTAINER.every((v, i) => d[i] === v);
15
16
  }
16
- export function encode(rgba, width, height, exif, distance = 0, effort = 1) {
17
- const stream = distance > 0 ? encodeVarDCT(rgba, width, height, { distance, effort }) : encodeRGBA(rgba, width, height);
17
+ export async function encode(rgba, width, height, exif, distance = 0, effort = 1, threads = 1) {
18
+ const stream = distance > 0 ? await encodeVarDCT(rgba, width, height, { distance, effort, threads }) : encodeRGBA(rgba, width, height);
18
19
  if (!exif?.length)
19
20
  return stream;
20
21
  const jxl = [0x6a, 0x78, 0x6c, 0x20];
@@ -58,7 +59,7 @@ function codestream(d) {
58
59
  }
59
60
  return out;
60
61
  }
61
- export function* frames(data, maxPixels = MAX_PIXELS, toneMapping = 'reinhard') {
62
+ export async function* frames(data, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = 1) {
62
63
  const d = codestream(data);
63
64
  const r = new BitReader(d);
64
65
  const image = imageHeader(r);
@@ -76,28 +77,38 @@ export function* frames(data, maxPixels = MAX_PIXELS, toneMapping = 'reinhard')
76
77
  lfFrames: [null, null, null, null], visible: 0, invisible: 0
77
78
  };
78
79
  const a = image.animation, tick = a ? 1000 * a.tpsDenominator / a.tpsNumerator : 0;
79
- let shown = 0;
80
- for (;;) {
81
- if (at >= d.length) {
82
- if (shown)
80
+ const pixels = image.width * image.height;
81
+ const n = Math.min(threads, image.xybEncoded ? Math.floor(pixels / (2 << 20)) : pixels >= 1536 << 10 && d.length >= 512 << 10 ? Math.floor(pixels / (512 << 10)) : 1);
82
+ const pool = { threads: n > 1 ? startThreads(n) : null, data: null };
83
+ try {
84
+ let shown = 0;
85
+ for (;;) {
86
+ if (at >= d.length) {
87
+ if (shown)
88
+ return;
89
+ throw new Error('JPEG XL: no frame shown');
90
+ }
91
+ const frame = await decodeFrame(d, new BitReader(d, at), state, at, pool);
92
+ at = frame.end;
93
+ if (frame.canvas && (frame.header.isLast || frame.header.duration !== 0)) {
94
+ shown++;
95
+ yield {
96
+ width: image.width, height: image.height, pixels: state.output.toRGBA(frame.canvas), duration: frame.header.duration * tick,
97
+ orientation: image.orientation, loopCount: a ? a.numLoops : 1
98
+ };
99
+ }
100
+ if (frame.header.isLast)
83
101
  return;
84
- throw new Error('JPEG XL: no frame shown');
85
102
  }
86
- const frame = decodeFrame(d, new BitReader(d, at), state);
87
- at = frame.end;
88
- if (frame.canvas && (frame.header.isLast || frame.header.duration !== 0)) {
89
- shown++;
90
- yield {
91
- width: image.width, height: image.height, pixels: state.output.toRGBA(frame.canvas), duration: frame.header.duration * tick,
92
- orientation: image.orientation, loopCount: a ? a.numLoops : 1
93
- };
94
- }
95
- if (frame.header.isLast)
96
- return;
103
+ }
104
+ finally {
105
+ if (pool.threads)
106
+ for (const t of pool.threads)
107
+ t.terminate();
97
108
  }
98
109
  }
99
- export function decode(data, maxPixels = MAX_PIXELS, toneMapping = 'reinhard') {
100
- for (const frame of frames(data, maxPixels, toneMapping))
110
+ export async function decode(data, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = 1) {
111
+ for await (const frame of frames(data, maxPixels, toneMapping, threads))
101
112
  return frame;
102
113
  throw new Error('JPEG XL: no frame shown');
103
114
  }