imagescript 3.9.0 → 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,4 @@
1
+ import { runChunks, shared, startThreads } from "../../util/threads.js";
1
2
  import { findPatches } from "./patches-enc.js";
2
3
  import { BitWriter } from "./bit-writer.js";
3
4
  import { imageHeader, u32 } from "./headers-enc.js";
@@ -8,6 +9,7 @@ import { initialQuantField } from "./aq-enc.js";
8
9
  import { chooseVarblocks } from "./acs-enc.js";
9
10
  import { defaultDequant, MATRIX_INDEX } from "./quant.js";
10
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];
11
13
  const OPSIN = [
12
14
  0.30, 0.622, 0.078,
13
15
  0.23, 0.692, 0.078,
@@ -18,9 +20,8 @@ const LINEAR = Float64Array.from({ length: 256 }, (_, i) => {
18
20
  const v = i / 255;
19
21
  return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
20
22
  });
21
- function toXYB(rgba, width, height, pw, ph) {
22
- const x = new Float32Array(pw * ph), y = new Float32Array(pw * ph), b = new Float32Array(pw * ph);
23
- 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++) {
24
25
  const sy = Math.min(py, height - 1);
25
26
  for (let px = 0; px < pw; px++) {
26
27
  const s = 4 * (sy * width + Math.min(px, width - 1));
@@ -34,7 +35,6 @@ function toXYB(rgba, width, height, pw, ph) {
34
35
  b[i] = s3;
35
36
  }
36
37
  }
37
- return [x, y, b];
38
38
  }
39
39
  function quantizer(distance) {
40
40
  const dcDistance = Math.max(0.5 * distance, Math.min(distance, 0.3 * (distance / 0.3) ** 0.83));
@@ -78,53 +78,185 @@ function inverseMatrices(type) {
78
78
  inverses.set(type, inv = defaultDequant(MATRIX_INDEX[type])[transposed(type) ? 1 : 0].map(m => Float32Array.from(m, v => 1 / v)));
79
79
  return inv;
80
80
  }
81
- function chromaFromLuma(raw, types, muls, pw, bw, bh, globalScale, xFromY, bFromY) {
81
+ function chromaFromLuma(raw, types, muls, pw, bw, bh, globalScale, xFromY, bFromY, ty) {
82
82
  const tilesPerRow = Math.ceil(bw / 8);
83
- for (let ty = 0; ty < bh; ty += 8) {
84
- for (let tx = 0; tx < bw; tx += 8) {
85
- const sums = [0, 0, 0, 0];
86
- let num = 0;
87
- for (let by = ty; by < Math.min(ty + 8, bh); by++) {
88
- for (let bx = tx; bx < Math.min(tx + 8, bw); bx++) {
89
- const type = types[by * bw + bx];
90
- if (type < 0)
91
- continue;
92
- 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);
93
- const inv = inverseMatrices(type), q = globalScale / 65536 * 128 * muls[by * bw + bx];
94
- 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;
95
165
  for (let y = 0; y < h; y++) {
96
166
  for (let x = 0; x < w; x++) {
97
- 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)
98
169
  continue;
99
- const k = y * w + x, yv = raw[1][o + y * pw + x];
100
- for (let c = 0; c < 2; c++) {
101
- const ch = c ? 2 : 0, qm = q * inv[ch][k], base = c;
102
- const a = yv * qm / 84, b = base * yv * qm - raw[ch][o + y * pw + x] * qm;
103
- sums[2 * c] += a * a;
104
- 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;
105
176
  }
106
177
  }
107
178
  }
108
179
  }
109
180
  }
110
- const factor = (aa, ab) => {
111
- if (!num)
112
- return 0;
113
- let x = -ab / (aa + num * 1e-9 * 0.5);
114
- x = x >= 2.6 ? x - 2.6 : x <= -2.6 ? x + 2.6 : 0;
115
- return Math.max(-128, Math.min(127, Math.round(x)));
116
- };
117
- const t = (ty >> 3) * tilesPerRow + (tx >> 3);
118
- xFromY[t] = factor(sums[0], sums[1]);
119
- bFromY[t] = factor(sums[2], sums[3]);
120
181
  }
121
- }
182
+ };
183
+ }
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
+ };
122
223
  }
123
- export function encodeVarDCT(rgba, width, height, { distance, effort }) {
224
+ export async function encodeVarDCT(rgba, width, height, options) {
124
225
  if (width < 1 || height < 1)
125
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) {
126
239
  const bw = Math.ceil(width / 8), bh = Math.ceil(height / 8), pw = bw * 8;
127
- 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
+ }
128
260
  let alpha = null;
129
261
  for (let i = 3; i < rgba.length; i += 4) {
130
262
  if (rgba[i] === 255)
@@ -140,66 +272,21 @@ export function encodeVarDCT(rgba, width, height, { distance, effort }) {
140
272
  const epfIters = [0.7, 1.5, 4].filter(t => distance >= t).length;
141
273
  const lfStep = LF_DEQUANT.map(m => m * 512 / (globalScale * quantLf));
142
274
  const patches = effort >= 2 ? findPatches(planes, pw, width, height, distance, alpha ? 1 : 0) : null;
143
- 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);
144
- const muls = new Int32Array(bw * bh).fill(mul);
145
- const lfValues = [0, 1, 2].map(() => new Float32Array(bw * bh));
146
- const raw = [0, 1, 2].map(() => new Float32Array(pw * bh * 8));
147
- const coeffs = new Float32Array(MAX_COEFFS), lfBlock = new Float32Array(MAX_COEFFS / 64);
148
- for (let by = 0; by < bh; by++) {
149
- for (let bx = 0; bx < bw; bx++) {
150
- const type = types[by * bw + bx];
151
- if (type < 0)
152
- continue;
153
- const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1], w = w8 * 8, h = h8 * 8, o = by * 8 * pw + bx * 8;
154
- for (let c = 0; c < 3; c++) {
155
- forwardTransform(type, planes[c], o, pw, coeffs, lfBlock);
156
- for (let y = 0; y < h; y++)
157
- raw[c].set(coeffs.subarray(y * w, (y + 1) * w), o + y * pw);
158
- for (let y = 0; y < h8; y++)
159
- for (let x = 0; x < w8; x++)
160
- lfValues[c][(by + y) * bw + bx + x] = lfBlock[y * w8 + x];
161
- }
162
- }
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));
163
279
  }
280
+ const muls = array(Int32Array, 4, bw * bh).fill(mul);
164
281
  const tilesPerRow = Math.ceil(bw / 8), tileRows = Math.ceil(bh / 8);
165
- const xFromY = new Int32Array(tilesPerRow * tileRows), bFromY = new Int32Array(tilesPerRow * tileRows);
166
- if (effort)
167
- chromaFromLuma(raw, types, muls, pw, bw, bh, globalScale, xFromY, bFromY);
168
- const hf = [0, 1, 2].map(() => new Int32Array(pw * bh * 8));
169
- const yDequant = new Float32Array(MAX_COEFFS);
170
- for (let by = 0; by < bh; by++) {
171
- for (let bx = 0; bx < bw; bx++) {
172
- const bi = by * bw + bx, type = types[bi];
173
- if (type < 0)
174
- continue;
175
- const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1], w = w8 * 8, h = h8 * 8, o = by * 8 * pw + bx * 8;
176
- const tile = (by >> 3) * tilesPerRow + (bx >> 3), cfl = [xFromY[tile] / 84, 0, 1 + bFromY[tile] / 84];
177
- const [m0, m1] = defaultDequant(MATRIX_INDEX[type]), matrices = transposed(type) ? m1 : m0;
178
- const hfStep = 65536 / (globalScale * muls[bi]), one = single(type);
179
- for (const c of [1, 0, 2]) {
180
- const src = raw[c], m = matrices[c], out = hf[c], k0 = cfl[c];
181
- const thresholds = c === 1 ? [0.56, 0.62, 0.62, 0.62] : [0.58, 0.62, 0.62, 0.62];
182
- if (c !== 1 && w8 * h8 >= 4)
183
- for (let i = 0; i < 4; i++)
184
- thresholds[i] = Math.max(0.5, thresholds[i] - 0.00744 * w8 * h8);
185
- const scale = qmMul[c] / hfStep;
186
- for (let y = 0; y < h; y++) {
187
- for (let x = 0; x < w; x++) {
188
- const k = y * w + x;
189
- if (one ? k === 0 : x < w8 && y < h8)
190
- continue;
191
- const v = (c === 1 ? src[o + y * pw + x] : src[o + y * pw + x] - k0 * yDequant[k]) / m[k] * scale;
192
- const q = Math.abs(v) >= thresholds[(y >= h / 2 ? 2 : 0) + (x >= w / 2 ? 1 : 0)] ? Math.round(v) : 0;
193
- out[o + y * pw + x] = q;
194
- if (c === 1) {
195
- const d = q === 0 ? 0 : Math.abs(q) <= 1 ? q * QUANT_BIAS[1] : q - QUANT_BIAS_NUMERATOR / q;
196
- yDequant[k] = d * m[k] * hfStep;
197
- }
198
- }
199
- }
200
- }
201
- }
202
- }
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;
203
290
  const lf = [0, 1, 2].map(() => new Int32Array(bw * bh));
204
291
  for (let i = 0; i < bw * bh; i++) {
205
292
  const ly = Math.round(lfValues[1][i] / lfStep[1]);
@@ -258,45 +345,8 @@ export function encodeVarDCT(rgba, width, height, { distance, effort }) {
258
345
  }
259
346
  }
260
347
  const modularCode = new EntropyCode([...lfTokens, ...alphaTokens], tree.numLeaves);
261
- const hfTokens = [];
262
- for (let g = 0; g < numGroups; g++) {
263
- const bx0 = (g % groupsPerRow) * 32, by0 = Math.floor(g / groupsPerRow) * 32;
264
- const gw = Math.min(32, bw - bx0), gh = Math.min(32, bh - by0), t = new Tokens();
265
- const nonZeros = [0, 1, 2].map(() => new Uint32Array(gw));
266
- for (let y = 0; y < gh; y++) {
267
- for (let x = 0; x < gw; x++) {
268
- const type = types[(by0 + y) * bw + bx0 + x];
269
- if (type < 0)
270
- continue;
271
- const w8 = SIZES[2 * type], numBlocks = w8 * SIZES[2 * type + 1], log = 31 - Math.clz32(numBlocks);
272
- const orderId = ORDER_ID[type], order = naturalOrder(orderId), n = order.length / 2, tr = transposed(type);
273
- const o = (by0 + y) * 8 * pw + (bx0 + x) * 8;
274
- const at = (i) => tr ? o + order[2 * i] * pw + order[2 * i + 1] : o + order[2 * i + 1] * pw + order[2 * i];
275
- for (let k = 0; k < 3; k++) {
276
- const c = [1, 0, 2][k], q = hf[c], nz = nonZeros[c], blockCtx = DEFAULT_CTX_MAP[k * 13 + orderId];
277
- let count = 0;
278
- for (let i = numBlocks; i < n; i++)
279
- if (q[at(i)])
280
- count++;
281
- const predicted = y === 0 ? (x === 0 ? 32 : nz[x - 1]) : x === 0 ? nz[x] : (nz[x] + nz[x - 1] + 1) >> 1;
282
- t.push(blockCtx + (predicted >= 8 ? 4 + (predicted >> 1) : predicted) * NUM_BLOCK_CTX, count);
283
- const value = (count + numBlocks - 1) >> log;
284
- for (let dx = 0; dx < w8; dx++)
285
- nz[x + dx] = value;
286
- let prevNonZero = count <= numBlocks * 4 ? 1 : 0;
287
- const ctxBase = blockCtx * 458 + 37 * NUM_BLOCK_CTX;
288
- for (let i = numBlocks; i < n && count > 0; i++) {
289
- const v = q[at(i)];
290
- t.push(ctxBase + (NUM_NONZERO_CONTEXT[(count - 1) >> log] + FREQ_CONTEXT[(i - numBlocks) >> log]) * 2 + prevNonZero, packSigned(v));
291
- prevNonZero = v ? 1 : 0;
292
- if (v)
293
- count--;
294
- }
295
- }
296
- }
297
- }
298
- hfTokens.push(t);
299
- }
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));
300
350
  const hfCode = new EntropyCode(hfTokens, 495 * NUM_BLOCK_CTX);
301
351
  const sections = [];
302
352
  {
@@ -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
  }
@@ -1950,7 +1950,7 @@ function estimateBestFilter(a, width, height) {
1950
1950
  }
1951
1951
  return best;
1952
1952
  }
1953
- export function encodeAlpha(a, width, height, method = 4, quality = 100) {
1953
+ export async function encodeAlpha(a, width, height, method = 4, quality = 100) {
1954
1954
  const reduce = quality < 100;
1955
1955
  if (reduce) {
1956
1956
  a = a.slice();
@@ -1972,7 +1972,7 @@ export function encodeAlpha(a, width, height, method = 4, quality = 100) {
1972
1972
  const argb = new Uint32Array(a.length);
1973
1973
  for (let i = 0; i < a.length; i++)
1974
1974
  argb[i] = data[i] << 8;
1975
- let stream = vp8l.encode(argb, width, height).subarray(5), method = 1;
1975
+ let stream = (await vp8l.encode(argb, width, height)).subarray(5), method = 1;
1976
1976
  if (stream.length > a.length) {
1977
1977
  stream = data;
1978
1978
  method = 0;