imagescript 3.9.0 → 3.11.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.
@@ -8,6 +8,7 @@ import { parseProfile } from "../util/icc.js";
8
8
  import { MAX_PIXELS, checkPixels } from "../util/limits.js";
9
9
  import { decodeAV1 } from "./av1/frame.js";
10
10
  import { toSRGB, hdrToLinear } from "./hdr.js";
11
+ import { runChunks, sharedOf, startThreads } from "../util/threads.js";
11
12
  const fourcc = (d, o) => String.fromCharCode(d[o], d[o + 1], d[o + 2], d[o + 3]);
12
13
  function* boxes(d, start, end) {
13
14
  const view = new DataView(d.buffer, d.byteOffset, d.byteLength);
@@ -182,7 +183,7 @@ function fromFrame(f) {
182
183
  primaries: f.seq.colorPrimaries
183
184
  };
184
185
  }
185
- function decodeAV1Item(d, it, idat, maxPixels) {
186
+ function av1Input(d, it, idat) {
186
187
  let data = itemData(d, it, idat);
187
188
  const av1C = property(it, 'av1C');
188
189
  if (av1C && av1C.end - av1C.start > 4 && (data[0] >> 3 & 15) !== 1) {
@@ -192,18 +193,25 @@ function decodeAV1Item(d, it, idat, maxPixels) {
192
193
  joined.set(data, config.length);
193
194
  data = joined;
194
195
  }
195
- const a1op = property(it, 'a1op'), lsel = property(it, 'lsel');
196
+ const a1op = property(it, 'a1op'), lsel = property(it, 'lsel'), ispe = property(it, 'ispe');
196
197
  const layer = lsel ? d[lsel.start] << 8 | d[lsel.start + 1] : 0xffff;
197
- const frame = decodeAV1(data, 0, data.length, { maxPixels, operatingPoint: a1op ? d[a1op.start] : 0, layer: layer === 0xffff ? -1 : layer });
198
- if (frame.incomplete) {
199
- const ispe = property(it, 'ispe');
200
- const view = new DataView(d.buffer, d.byteOffset, d.byteLength);
201
- if (!ispe || view.getUint32(ispe.start + 4) !== frame.hdr.upscaledWidth || view.getUint32(ispe.start + 8) !== frame.height)
202
- throw new Error('AVIF: layered images with inter predicted layers are not supported');
203
- }
198
+ const view = new DataView(d.buffer, d.byteOffset, d.byteLength);
199
+ return {
200
+ data, operatingPoint: a1op ? d[a1op.start] : 0, layer: layer === 0xffff ? -1 : layer,
201
+ size: ispe ? [view.getUint32(ispe.start + 4), view.getUint32(ispe.start + 8)] : null
202
+ };
203
+ }
204
+ function decodeAV1Input({ data, operatingPoint, layer, size }, maxPixels) {
205
+ const frame = decodeAV1(data, 0, data.length, { maxPixels, operatingPoint, layer });
206
+ if (frame.incomplete && (!size || size[0] !== frame.hdr.upscaledWidth || size[1] !== frame.height))
207
+ throw new Error('AVIF: layered images with inter predicted layers are not supported');
204
208
  return fromFrame(frame);
205
209
  }
206
- function decodeGrid(d, it, items, idat, maxPixels, tiles = it.refs.get('dimg') ?? []) {
210
+ const decodeAV1Item = (d, it, idat, maxPixels) => decodeAV1Input(av1Input(d, it, idat), maxPixels);
211
+ export function tileChunks({ inputs, maxPixels }) {
212
+ return i => decodeAV1Input(inputs[i], maxPixels);
213
+ }
214
+ async function decodeGrid(d, it, items, idat, maxPixels, threads, tiles = it.refs.get('dimg') ?? []) {
207
215
  const g = itemData(d, it, idat);
208
216
  const view = new DataView(g.buffer, g.byteOffset, g.byteLength);
209
217
  const wide = g[1] & 1;
@@ -214,47 +222,64 @@ function decodeGrid(d, it, items, idat, maxPixels, tiles = it.refs.get('dimg') ?
214
222
  throw new Error('AVIF: the grid has the wrong number of tiles');
215
223
  if (new Set(tiles).size !== tiles.length)
216
224
  throw new Error('AVIF: the grid repeats tiles');
217
- let out = null;
218
- for (let r = 0; r < rows; r++) {
219
- for (let c = 0; c < cols; c++) {
220
- const tileItem = items.get(tiles[r * cols + c]);
221
- if (!tileItem || tileItem.type !== 'av01')
222
- throw new Error('AVIF: invalid grid tile');
223
- const tile = decodeAV1Item(d, tileItem, idat, maxPixels);
224
- if (!out) {
225
- if (tile.width * cols < width || tile.height * rows < height)
226
- throw new Error('AVIF: the grid\'s tiles are too small');
227
- out = { ...tile, width, height, planes: [], strides: [] };
228
- for (let p = 0; p < tile.planes.length; p++) {
229
- const sx = p && tile.layout < 3 ? 1 : 0, sy = p && tile.layout === 1 ? 1 : 0;
230
- const stride = (width + sx) >> sx;
231
- out.strides.push(stride);
232
- out.planes.push(new Uint16Array(stride * ((height + sy) >> sy)));
233
- }
225
+ const inputs = tiles.map(id => {
226
+ const tileItem = items.get(id);
227
+ if (!tileItem || tileItem.type !== 'av01')
228
+ throw new Error('AVIF: invalid grid tile');
229
+ return av1Input(d, tileItem, idat);
230
+ });
231
+ const place = (grid, k, tile) => {
232
+ const r = Math.floor(k / cols), c = k % cols;
233
+ let out = grid;
234
+ if (!out) {
235
+ if (tile.width * cols < width || tile.height * rows < height)
236
+ throw new Error('AVIF: the grid\'s tiles are too small');
237
+ out = { ...tile, width, height, planes: [], strides: [] };
238
+ for (let p = 0; p < tile.planes.length; p++) {
239
+ const sx = p && tile.layout < 3 ? 1 : 0, sy = p && tile.layout === 1 ? 1 : 0;
240
+ const stride = (width + sx) >> sx;
241
+ out.strides.push(stride);
242
+ out.planes.push(new Uint16Array(stride * ((height + sy) >> sy)));
234
243
  }
235
- else if (tile.layout !== out.layout || tile.bitdepth !== out.bitdepth)
236
- throw new Error('AVIF: the grid\'s tiles differ');
237
- for (let p = 0; p < out.planes.length; p++) {
238
- const sx = p && out.layout < 3 ? 1 : 0, sy = p && out.layout === 1 ? 1 : 0;
239
- const tw = (tile.width + sx) >> sx, th = (tile.height + sy) >> sy;
240
- const x0 = c * tw, y0 = r * th;
241
- const pw = (width + sx) >> sx, ph = (height + sy) >> sy;
242
- for (let y = 0; y < th && y0 + y < ph; y++) {
243
- const n = Math.min(tw, pw - x0);
244
- if (n <= 0)
245
- break;
246
- out.planes[p].set(tile.planes[p].subarray(y * tile.strides[p], y * tile.strides[p] + n), (y0 + y) * out.strides[p] + x0);
247
- }
244
+ }
245
+ else if (tile.layout !== out.layout || tile.bitdepth !== out.bitdepth)
246
+ throw new Error('AVIF: the grid\'s tiles differ');
247
+ for (let p = 0; p < out.planes.length; p++) {
248
+ const sx = p && out.layout < 3 ? 1 : 0, sy = p && out.layout === 1 ? 1 : 0;
249
+ const tw = (tile.width + sx) >> sx, th = (tile.height + sy) >> sy;
250
+ const x0 = c * tw, y0 = r * th;
251
+ const pw = (width + sx) >> sx, ph = (height + sy) >> sy;
252
+ for (let y = 0; y < th && y0 + y < ph; y++) {
253
+ const n = Math.min(tw, pw - x0);
254
+ if (n <= 0)
255
+ break;
256
+ out.planes[p].set(tile.planes[p].subarray(y * tile.strides[p], y * tile.strides[p] + n), (y0 + y) * out.strides[p] + x0);
248
257
  }
249
258
  }
259
+ return out;
260
+ };
261
+ let decoded = null;
262
+ const n = threads ? Math.min(threads.length, Math.ceil(inputs.length / TILES_PER_THREAD)) : 0;
263
+ if (threads && n > 1) {
264
+ const data = new Uint8Array(new SharedArrayBuffer(inputs.reduce((n, i) => n + i.data.length, 0)));
265
+ let o = 0;
266
+ for (const input of inputs) {
267
+ data.set(input.data, o);
268
+ input.data = data.subarray(o, o += input.data.length);
269
+ }
270
+ const task = { task: 'avif-tiles', inputs, maxPixels };
271
+ decoded = await runChunks(threads.slice(0, n), task, inputs.length, tileChunks(task)).catch(() => null);
250
272
  }
273
+ let out = null;
274
+ for (let k = 0; k < inputs.length; k++)
275
+ out = place(out, k, decoded ? decoded[k] : decodeAV1Input(inputs[k], maxPixels));
251
276
  return out;
252
277
  }
253
- function decodeItem(d, it, items, idat, maxPixels) {
278
+ async function decodeItem(d, it, items, idat, maxPixels, threads) {
254
279
  if (it.type === 'av01')
255
280
  return decodeAV1Item(d, it, idat, maxPixels);
256
281
  if (it.type === 'grid')
257
- return decodeGrid(d, it, items, idat, maxPixels);
282
+ return decodeGrid(d, it, items, idat, maxPixels, threads);
258
283
  throw new Error(`AVIF: unsupported item type ${it.type}`);
259
284
  }
260
285
  function coefficients(matrix) {
@@ -281,6 +306,21 @@ function convertRow444(c, j) {
281
306
  out[p + 3] = 255;
282
307
  }
283
308
  }
309
+ function convertRowSubsampled(c, j) {
310
+ const { width, height, layout, Y, U, V, cs, sy, tableY, out, cr2, cb2, crg, cbg, kgInverse } = c, [w9, w3, w1] = c.weighted;
311
+ const uvRow = (j >> sy) * cs, yRow = j * c.ys;
312
+ const adjRow = layout === 1 && !(j === 0 || j === height - 1 && j % 2) ? j % 2 ? cs : -cs : 0;
313
+ for (let i = 0, p = j * width * 4; i < width; i++, p += 4) {
314
+ const lum = tableY[Y[yRow + i]];
315
+ const o = uvRow + (i >> 1), adjCol = i === 0 || i === width - 1 && i % 2 ? 0 : i % 2 ? 1 : -1;
316
+ const cb = f32(f32(f32(w9[U[o]] + w3[U[o + adjCol]]) + w3[U[o + adjRow]]) + w1[U[o + adjCol + adjRow]]);
317
+ const cr = f32(f32(f32(w9[V[o]] + w3[V[o + adjCol]]) + w3[V[o + adjRow]]) + w1[V[o + adjCol + adjRow]]);
318
+ out[p] = toByte(f32(lum + f32(cr2 * cr)));
319
+ out[p + 1] = toByte(f32(lum - f32(f32(2 * f32(f32(crg * cr) + f32(cbg * cb))) * kgInverse)));
320
+ out[p + 2] = toByte(f32(lum + f32(cb2 * cb)));
321
+ out[p + 3] = 255;
322
+ }
323
+ }
284
324
  function convertRow(c, j) {
285
325
  const { width, height, layout, color, identity, ycgco, Y, U, V, cs, sx, sy, tableY, tableUV, out, rgb, unmultiply, cr2, cb2, crg, cbg, kgInverse } = c;
286
326
  const uvRow = (j >> sy) * cs, yRow = j * c.ys;
@@ -349,7 +389,14 @@ function convertRow(c, j) {
349
389
  out[p + 2] = toByte(b);
350
390
  }
351
391
  }
352
- function toRgba(y, alpha, toneMapping, premultiplied = false) {
392
+ export function conversionChunks(c) {
393
+ const row = c.red ? convertRow444 : c.weighted ? convertRowSubsampled : convertRow;
394
+ return band => {
395
+ for (let j = band * 64; j < Math.min(c.height, band * 64 + 64); j++)
396
+ row(c, j);
397
+ };
398
+ }
399
+ async function toRgba(y, alpha, toneMapping, premultiplied = false, threads = null) {
353
400
  const { width, height, bitdepth, layout } = y;
354
401
  const max = (1 << bitdepth) - 1;
355
402
  const [kr, kb] = coefficients(y.matrix).map(f32), kg = f32(f32(1 - kr) - kb);
@@ -361,14 +408,16 @@ function toRgba(y, alpha, toneMapping, premultiplied = false) {
361
408
  tableY[i] = (i - biasY) / rangeY;
362
409
  tableUV[i] = identity ? tableY[i] : (i - biasUV) / rangeUV;
363
410
  }
364
- let out = new Uint8Array(width * height * 4);
411
+ const array = (Type, bytes, length) => new Type(threads ? new SharedArrayBuffer(bytes * length) : new ArrayBuffer(bytes * length));
412
+ let out = array(Uint8Array, 1, width * height * 4);
365
413
  const hdr = y.transfer === TRANSFER_PQ || y.transfer === TRANSFER_HLG;
366
- const rgb = hdr ? new Float32Array(width * height * 3) : null;
367
- const Y = y.planes[0], ys = y.strides[0];
368
- const color = layout !== 0 && y.planes.length === 3;
369
- const U = y.planes[1], V = y.planes[2], cs = y.strides[1];
414
+ const rgb = hdr ? array(Float32Array, 4, width * height * 3) : null;
415
+ const planes = threads ? y.planes.map(sharedOf) : y.planes;
416
+ const Y = planes[0], ys = y.strides[0];
417
+ const color = layout !== 0 && planes.length === 3;
418
+ const U = planes[1], V = planes[2], cs = y.strides[1];
370
419
  const sx = layout < 3 ? 1 : 0, sy = layout === 1 ? 1 : 0;
371
- const alphas = alpha ? new Float32Array(width * height).fill(1) : null;
420
+ const alphas = alpha ? array(Float32Array, 4, width * height).fill(1) : null;
372
421
  if (alpha && alphas) {
373
422
  const A = alpha.planes[0], as = alpha.strides[0], amax = (1 << alpha.bitdepth) - 1;
374
423
  const lo = 16 << (alpha.bitdepth - 8), span = 219 << (alpha.bitdepth - 8);
@@ -385,11 +434,11 @@ function toRgba(y, alpha, toneMapping, premultiplied = false) {
385
434
  const c = {
386
435
  width, height, layout, color, identity, ycgco, Y, U, V, ys, cs, sx, sy, tableY, tableUV, out, rgb, unmultiply,
387
436
  cr2: f32(2 * f32(1 - kr)), cb2: f32(2 * f32(1 - kb)), crg: f32(kr * f32(1 - kr)), cbg: f32(kb * f32(1 - kb)), kgInverse: 1 / kg,
388
- n: max + 1, red: null, blue: null, gTerm: null
437
+ n: max + 1, red: null, blue: null, gTerm: null, weighted: null
389
438
  };
390
439
  const n = max + 1;
391
440
  if (layout === 3 && color && !identity && !ycgco && !rgb && !unmultiply && n * n * 2 <= width * height) {
392
- const red = c.red = new Uint8Array(n * n), blue = c.blue = new Uint8Array(n * n), gTerm = c.gTerm = new Float32Array(n * n);
441
+ const red = c.red = array(Uint8Array, 1, n * n), blue = c.blue = array(Uint8Array, 1, n * n), gTerm = c.gTerm = array(Float32Array, 4, n * n);
393
442
  for (let v = 0; v < n; v++) {
394
443
  const rTerm = f32(c.cr2 * tableUV[v]), bTerm = f32(c.cb2 * tableUV[v]);
395
444
  for (let y = 0; y < n; y++) {
@@ -402,12 +451,18 @@ function toRgba(y, alpha, toneMapping, premultiplied = false) {
402
451
  for (let v = 0; v < n; v++)
403
452
  gTerm[u * n + v] = f32(f32(2 * f32(f32(c.crg * tableUV[v]) + cbTerm)) * c.kgInverse);
404
453
  }
405
- for (let j = 0; j < height; j++)
406
- convertRow444(c, j);
407
454
  }
408
- else
409
- for (let j = 0; j < height; j++)
410
- convertRow(c, j);
455
+ else if (layout < 3 && color && !identity && !ycgco && !rgb && !unmultiply)
456
+ c.weighted = [0.5625, 0.1875, 0.0625].map(w => tableUV.map(v => f32(v * w)));
457
+ const task = { ...c, task: 'avif-convert' };
458
+ try {
459
+ await runChunks(threads, task, Math.ceil(height / 64), conversionChunks(task));
460
+ }
461
+ catch {
462
+ await runChunks(null, task, Math.ceil(height / 64), conversionChunks(task));
463
+ }
464
+ if (threads && !rgb)
465
+ out = new Uint8Array(out);
411
466
  if (rgb)
412
467
  out = toSRGB(hdrToLinear(rgb, y.transfer, y.primaries), toneMapping);
413
468
  if (alphas)
@@ -415,7 +470,9 @@ function toRgba(y, alpha, toneMapping, premultiplied = false) {
415
470
  out[i * 4 + 3] = Math.round(alphas[i] * 255);
416
471
  return out;
417
472
  }
418
- export function decode(d, maxPixels = MAX_PIXELS, toneMapping = 'reinhard') {
473
+ const MIN_THREADED_PIXELS = 4 << 20, PIXELS_PER_THREAD = 1 << 20;
474
+ const TILES_PER_THREAD = 4;
475
+ export async function decode(d, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = 1) {
419
476
  if (!isAVIF(d))
420
477
  throw new Error('AVIF: invalid header');
421
478
  let meta, moov;
@@ -441,36 +498,50 @@ export function decode(d, maxPixels = MAX_PIXELS, toneMapping = 'reinhard') {
441
498
  return undefined;
442
499
  };
443
500
  const alphaItem = alphaOf(primary);
444
- const color = decodeItem(d, it, items, idat, maxPixels);
445
- applyColr(d, it, color);
446
- const icc = iccOf(d, it);
447
- if (icc && parseProfile(icc)) {
448
- color.primaries = 1;
449
- color.transfer = 13;
450
- }
451
- let alpha = alphaItem ? decodeItem(d, alphaItem, items, idat, maxPixels) : null;
452
- if (!alphaItem && it.type === 'grid') {
453
- const tiles = (it.refs.get('dimg') ?? []).map(alphaOf);
454
- if (tiles.length && tiles.every(t => t))
455
- alpha = decodeGrid(d, it, items, idat, maxPixels, tiles.map(t => t.id));
501
+ const ispe = property(it, 'ispe'), view = new DataView(d.buffer, d.byteOffset, d.byteLength);
502
+ const pixels = ispe && ispe.end - ispe.start >= 12 ? view.getUint32(ispe.start + 4) * view.getUint32(ispe.start + 8) : 0;
503
+ const n = Math.min(threads, Math.floor(pixels / PIXELS_PER_THREAD));
504
+ const pool = n > 1 && pixels >= MIN_THREADED_PIXELS && pixels <= maxPixels ? startThreads(n) : null;
505
+ try {
506
+ return await decodeImage(d, it, items, idat, alphaItem, alphaOf, maxPixels, toneMapping, pool);
456
507
  }
457
- let pixels = toRgba(color, alpha, toneMapping, alphaItem && (it.refs.get('prem') ?? []).includes(alphaItem.id));
458
- let { width, height } = color;
459
- for (const { box } of it.props) {
460
- if (box.type === 'clap')
461
- ({ width, height, pixels } = clap(d, box, width, height, pixels));
462
- else if (box.type === 'irot')
463
- ({ width, height, pixels } = rotate(pixels, width, height, d[box.start] & 3));
464
- else if (box.type === 'imir')
465
- pixels = mirror(pixels, width, height, d[box.start] & 1);
508
+ finally {
509
+ if (pool)
510
+ for (const t of pool)
511
+ t.terminate();
466
512
  }
467
- return { width, height, pixels, icc };
468
513
  }
469
514
  }
470
515
  if (moov)
471
516
  return decodeSequence(d, moov, maxPixels, toneMapping);
472
517
  throw new Error('AVIF: no image');
473
518
  }
519
+ async function decodeImage(d, it, items, idat, alphaItem, alphaOf, maxPixels, toneMapping, threads) {
520
+ const color = await decodeItem(d, it, items, idat, maxPixels, threads);
521
+ applyColr(d, it, color);
522
+ const icc = iccOf(d, it);
523
+ if (icc && parseProfile(icc)) {
524
+ color.primaries = 1;
525
+ color.transfer = 13;
526
+ }
527
+ let alpha = alphaItem ? await decodeItem(d, alphaItem, items, idat, maxPixels, threads) : null;
528
+ if (!alphaItem && it.type === 'grid') {
529
+ const tiles = (it.refs.get('dimg') ?? []).map(alphaOf);
530
+ if (tiles.length && tiles.every(t => t))
531
+ alpha = await decodeGrid(d, it, items, idat, maxPixels, threads, tiles.map(t => t.id));
532
+ }
533
+ let pixels = await toRgba(color, alpha, toneMapping, alphaItem && (it.refs.get('prem') ?? []).includes(alphaItem.id), threads);
534
+ let { width, height } = color;
535
+ for (const { box } of it.props) {
536
+ if (box.type === 'clap')
537
+ ({ width, height, pixels } = clap(d, box, width, height, pixels));
538
+ else if (box.type === 'irot')
539
+ ({ width, height, pixels } = rotate(pixels, width, height, d[box.start] & 3));
540
+ else if (box.type === 'imir')
541
+ pixels = mirror(pixels, width, height, d[box.start] & 1);
542
+ }
543
+ return { width, height, pixels, icc };
544
+ }
474
545
  function iccOf(d, it) {
475
546
  for (const { box } of it.props) {
476
547
  const type = box.type === 'colr' && box.end - box.start > 4 ? fourcc(d, box.start) : '';
@@ -541,7 +612,7 @@ function mirror(pixels, width, height, axis) {
541
612
  }
542
613
  return out;
543
614
  }
544
- function decodeSequence(d, moov, maxPixels, toneMapping) {
615
+ async function decodeSequence(d, moov, maxPixels, toneMapping) {
545
616
  const view = new DataView(d.buffer, d.byteOffset, d.byteLength);
546
617
  const tracks = [];
547
618
  for (const trak of boxes(d, moov.start, moov.end)) {
@@ -591,5 +662,5 @@ function decodeSequence(d, moov, maxPixels, toneMapping) {
591
662
  return fromFrame(decodeAV1(data, 0, data.length, { maxPixels }));
592
663
  };
593
664
  const color = frame(colorTrack);
594
- return { width: color.width, height: color.height, pixels: toRgba(color, alphaTrack ? frame(alphaTrack) : null, toneMapping) };
665
+ return { width: color.width, height: color.height, pixels: await toRgba(color, alphaTrack ? frame(alphaTrack) : null, toneMapping) };
595
666
  }
@@ -1,3 +1,4 @@
1
+ import { runChunks, shared, sharedOf } from "../../util/threads.js";
1
2
  import { forwardTransform } from "./transforms-enc.js";
2
3
  import { inverseTransform } from "./dct.js";
3
4
  import { defaultDequant, MATRIX_INDEX } from "./quant.js";
@@ -94,10 +95,10 @@ class Strategy {
94
95
  bw;
95
96
  bh;
96
97
  types;
97
- constructor(bw, bh) {
98
+ constructor(bw, bh, types) {
98
99
  this.bw = bw;
99
100
  this.bh = bh;
100
- this.types = new Int8Array(bw * bh);
101
+ this.types = types ?? new Int8Array(bw * bh);
101
102
  }
102
103
  set(bx, by, type) {
103
104
  const w8 = SIZES[2 * type], h8 = SIZES[2 * type + 1];
@@ -278,7 +279,17 @@ function processRect(bx, by, w, h, speed, cfg, s) {
278
279
  }
279
280
  }
280
281
  }
281
- export function chooseVarblocks(planes, stride, bw, bh, field, distance, speed) {
282
+ export async function chooseVarblocks(planes, stride, bw, bh, field, distance, speed, threads) {
283
+ const types = new Int8Array(threads ? new SharedArrayBuffer(bw * bh) : new ArrayBuffer(bw * bh));
284
+ const task = {
285
+ task: 'jxl-varblocks', stride, bw, bh, distance, speed, types,
286
+ planes: threads ? planes.map(sharedOf) : planes,
287
+ field: threads ? { quant: shared(field.quant), mask: shared(field.mask), mask1x1: sharedOf(field.mask1x1) } : field,
288
+ };
289
+ await runChunks(threads, task, Math.ceil(bh / 8), varblockChunks(task));
290
+ return types;
291
+ }
292
+ export function varblockChunks({ planes, stride, bw, bh, field, distance, speed, types }) {
282
293
  const ratio = (distance + 0.13731742964354549) / (1 + 0.13731742964354549);
283
294
  const cfg = {
284
295
  planes, stride, bw, field, distance,
@@ -286,9 +297,10 @@ export function chooseVarblocks(planes, stride, bw, bh, field, distance, speed)
286
297
  zerosMul: 9.3089059022677905 * ratio ** 0.50990926717963703,
287
298
  costDelta: 10.833273317067883 * ratio ** 0.36702940662370243
288
299
  };
289
- const s = new Strategy(bw, bh);
290
- for (let by = 0; by < bh; by += 8)
300
+ const s = new Strategy(bw, bh, types);
301
+ return row => {
302
+ const by = row * 8;
291
303
  for (let bx = 0; bx < bw; bx += 8)
292
304
  processRect(bx, by, Math.min(8, bw - bx), Math.min(8, bh - by), speed, cfg, s);
293
- return s.types;
305
+ };
294
306
  }
@@ -1,9 +1,4 @@
1
- /*!
2
- * The adaptive quantization field of the lossy JPEG XL encoder, for its varblock search: libjxl's initial quantization
3
- * field and masking (lib/jxl/enc_adaptive_quantization.cc: InitialQuantField, AdaptiveQuantizationMap, FuzzyErosion,
4
- * PerBlockModulations, Blur1x1Masking), on the whole image instead of tiles. Copyright (c) the JPEG XL Project Authors, BSD-3-Clause
5
- * License (see THIRD_PARTY_NOTICES.md)
6
- */
1
+ import { runChunks } from "../../util/threads.js";
7
2
  const SG_MUL = 226.77216153508914, SG_MUL2 = 1 / 73.377132366608819, LOG2 = 0.693147181;
8
3
  const SG_RET_MUL = SG_MUL2 * 18.6580932135 * LOG2, SG_V_OFFSET = 7.7825991679894591;
9
4
  const NUM_MUL = SG_RET_MUL * 3 * SG_MUL, V_OFFSET = SG_V_OFFSET * LOG2 + 1e-2, DEN_MUL = LOG2 * SG_MUL;
@@ -22,31 +17,44 @@ function computeMask(v) {
22
17
  return -0.7647 + 9.4708735624378946 / (v1 * v1 + 0.25 * offset3) + 17.35036561631863 / (v1 + 302.59587815579727) + 6.7943250517376494 / (v1 * v1 + offset3);
23
18
  }
24
19
  const maskingSqrt = (v) => 0.25 * Math.sqrt(v * Math.sqrt(211.66567973503678 * 1e8) + 27.505837037000106);
25
- export function initialQuantField(distance, planes, w, h, scale) {
26
- const [px, py, pb] = planes, bw = w / 8, bh = h / 8;
27
- const MATCH_GAMMA_OFFSET = 0.019, LIMIT = 0.2;
28
- const mask1x1 = new Float32Array(w * h), preErosion = new Float32Array((w / 4) * (h / 4)), rowSum = new Float32Array(w);
29
- for (let y = 0; y < h; y++) {
30
- const r = y * w, r1 = (y > 0 ? y - 1 : y) * w, r2 = (y + 1 < h ? y + 1 : y) * w;
31
- for (let x = 0; x < w; x++) {
32
- const x1 = x > 0 ? x - 1 : x, x2 = x + 1 < w ? x + 1 : x;
33
- const base = 0.25 * (py[r2 + x] + py[r1 + x] + py[r + x1] + py[r + x2]);
34
- const gammac = gammaRatio(py[r + x] + MATCH_GAMMA_OFFSET);
35
- const d = gammac * (py[r + x] - base);
36
- mask1x1[r + x] = 1 / (Math.log1p(Math.abs(d)) + 0.01);
37
- const v = maskingSqrt(Math.min(d * d, LIMIT));
38
- rowSum[x] = y % 4 ? rowSum[x] + v : v;
39
- }
40
- if (y % 4 === 3) {
41
- const out = (y >> 2) * (w / 4);
42
- for (let x = 0; x < w / 4; x++)
43
- preErosion[out + x] = (rowSum[4 * x] + rowSum[4 * x + 1] + rowSum[4 * x + 2] + rowSum[4 * x + 3]) * 0.25;
20
+ export function maskingChunks({ y: py, w, h, mask1x1, preErosion }) {
21
+ const MATCH_GAMMA_OFFSET = 0.019, LIMIT = 0.2, rowSum = new Float32Array(w);
22
+ return band => {
23
+ for (let y = band * 64; y < Math.min(h, band * 64 + 64); y++) {
24
+ const r = y * w, r1 = (y > 0 ? y - 1 : y) * w, r2 = (y + 1 < h ? y + 1 : y) * w;
25
+ for (let x = 0; x < w; x++) {
26
+ const x1 = x > 0 ? x - 1 : x, x2 = x + 1 < w ? x + 1 : x;
27
+ const base = 0.25 * (py[r2 + x] + py[r1 + x] + py[r + x1] + py[r + x2]);
28
+ const gammac = gammaRatio(py[r + x] + MATCH_GAMMA_OFFSET);
29
+ const d = gammac * (py[r + x] - base);
30
+ mask1x1[r + x] = 1 / (Math.log1p(Math.abs(d)) + 0.01);
31
+ const v = maskingSqrt(Math.min(d * d, LIMIT));
32
+ rowSum[x] = y % 4 ? rowSum[x] + v : v;
33
+ }
34
+ if (y % 4 === 3) {
35
+ const out = (y >> 2) * (w / 4);
36
+ for (let x = 0; x < w / 4; x++)
37
+ preErosion[out + x] = (rowSum[4 * x] + rowSum[4 * x + 1] + rowSum[4 * x + 2] + rowSum[4 * x + 3]) * 0.25;
38
+ }
44
39
  }
45
- }
46
- const aq = fuzzyErosion(distance, preErosion, w / 4, h / 4);
40
+ };
41
+ }
42
+ export function maskBlurChunks({ w, h, mask1x1, blurred }) {
43
+ const k = [0.25647067633737225, 0.2050056912354399, 0.1540820486684973, 0.08149576591362004, 0.05127501048123085];
44
+ const n = 1 / Math.max(1 + 4 * (k[0] + k[1] + k[2] + k[4] + 2 * k[3]), 1e-5);
45
+ const weights = [n, n * k[0], n * k[2], n * k[1], n * k[4], n * k[3]];
46
+ return band => symmetric5(mask1x1, w, h, weights, blurred, band * 64, Math.min(h, band * 64 + 64));
47
+ }
48
+ export async function initialQuantField(distance, planes, w, h, scale, threads) {
49
+ const [px, py, pb] = planes, bw = w / 8, bh = h / 8, bands = Math.ceil(h / 64);
50
+ const array = (n) => new Float32Array(threads ? new SharedArrayBuffer(4 * n) : new ArrayBuffer(4 * n));
51
+ const task = { task: 'jxl-masking', y: py, w, h, mask1x1: array(w * h), blurred: array(w * h), preErosion: array((w / 4) * (h / 4)) };
52
+ await runChunks(threads, task, bands, maskingChunks(task));
53
+ const aq = fuzzyErosion(distance, task.preErosion, w / 4, h / 4);
47
54
  const mask = Float32Array.from(aq, v => 1 / (v + 0.001));
48
55
  perBlockModulations(distance, px, py, pb, w, bw, bh, scale, aq);
49
- return { quant: aq, mask, mask1x1: blur1x1(mask1x1, w, h) };
56
+ await runChunks(threads, { ...task, task: 'jxl-mask-blur' }, bands, maskBlurChunks(task));
57
+ return { quant: aq, mask, mask1x1: task.blurred };
50
58
  }
51
59
  function fuzzyErosion(distance, from, w, h) {
52
60
  const mul = distance < 2 ? (2 - distance) / 2 : 0;
@@ -147,15 +155,14 @@ function perBlockModulations(distance, px, py, pb, w, bw, bh, scale, aq) {
147
155
  }
148
156
  }
149
157
  }
150
- function symmetric5(m, w, h, [c, r, R, d, D, L]) {
158
+ function symmetric5(m, w, h, [c, r, R, d, D, L], out, y0, y1) {
151
159
  const weights = [D, L, R, L, D, L, d, r, d, L, R, r, c, r, R, L, d, r, d, L, D, L, R, L, D];
152
160
  const mirror = (v, n) => {
153
161
  while (v < 0 || v >= n)
154
162
  v = v < 0 ? -v - 1 : 2 * n - 1 - v;
155
163
  return v;
156
164
  };
157
- const out = new Float32Array(w * h);
158
- for (let y = 0; y < h; y++) {
165
+ for (let y = y0; y < y1; y++) {
159
166
  const rows = [-2, -1, 0, 1, 2].map(dy => mirror(y + dy, h) * w);
160
167
  for (let x = 0; x < w; x++) {
161
168
  let sum = 0;
@@ -167,10 +174,4 @@ function symmetric5(m, w, h, [c, r, R, d, D, L]) {
167
174
  out[y * w + x] = sum;
168
175
  }
169
176
  }
170
- return out;
171
- }
172
- function blur1x1(m, w, h) {
173
- const k = [0.25647067633737225, 0.2050056912354399, 0.1540820486684973, 0.08149576591362004, 0.05127501048123085];
174
- const n = 1 / Math.max(1 + 4 * (k[0] + k[1] + k[2] + k[4] + 2 * k[3]), 1e-5);
175
- return symmetric5(m, w, h, [n, n * k[0], n * k[2], n * k[1], n * k[4], n * k[3]]);
176
177
  }
@@ -1,6 +1,6 @@
1
1
  import { TF_PQ, TF_HLG, PRI_BT2100, PRI_P3, EXTRA_ALPHA, EXTRA_SPOT, EXTRA_BLACK } from "./headers.js";
2
2
  import { toSRGB, hdrToLinear, REFERENCE_WHITE } from "../hdr.js";
3
- const byte = (v) => v <= 0 ? 0 : v >= 1 ? 255 : Math.round(v * 255);
3
+ export const byte = (v) => v <= 0 ? 0 : v >= 1 ? 255 : Math.round(v * 255);
4
4
  const [P0, P1, P2, P3, P4] = [-5.135152395e-04, 5.287254571e-03, 3.903842876e-01, 1.474205315e+00, 7.352629620e-01].map(Math.fround);
5
5
  const [Q0, Q1, Q2, Q3, Q4] = [1.004519624e-02, 3.036675394e-01, 1.340816930e+00, 9.258482155e-01, 2.424867759e-02].map(Math.fround);
6
6
  const srgbEncode = (v) => {
@@ -43,10 +43,10 @@ const linearByte = (v) => {
43
43
  k++;
44
44
  return k;
45
45
  };
46
- function xybToBytes(x, y, b, m, bias, k, out) {
46
+ export function xybToBytes(x, y, b, m, bias, k, out, from = 0, to = x.length) {
47
47
  const m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], m4 = m[4], m5 = m[5], m6 = m[6], m7 = m[7], m8 = m[8];
48
48
  const b0 = bias[0], b1 = bias[1], b2 = bias[2], c0 = Math.cbrt(b0), c1 = Math.cbrt(b1), c2 = Math.cbrt(b2);
49
- for (let i = 0, o = 0; i < x.length; i++, o += 4) {
49
+ for (let i = from, o = 4 * from; i < to; i++, o += 4) {
50
50
  const gr = y[i] + x[i] - c0, gg = y[i] - x[i] - c1, gb = b[i] - c2;
51
51
  const mr = gr * gr * gr + b0, mg = gg * gg * gg + b1, mb = gb * gb * gb + b2;
52
52
  out[o] = linearByte((m0 * mr + m1 * mg + m2 * mb) * k);
@@ -69,6 +69,8 @@ export class ColorOutput {
69
69
  this.scale = this.linear ? image.toneMapping.intensityTarget / REFERENCE_WHITE : 1;
70
70
  }
71
71
  transform(p, ycbcr, final = false) {
72
+ if (p.rgba)
73
+ return p;
72
74
  const image = this.image, n = p.width * p.height, ch = p.channels.slice();
73
75
  if (ycbcr) {
74
76
  const [cb, y, cr] = ch, r = new Float32Array(n), g = new Float32Array(n), b = new Float32Array(n);
@@ -106,6 +108,15 @@ export class ColorOutput {
106
108
  }
107
109
  return { width: p.width, height: p.height, channels: ch };
108
110
  }
111
+ bytesOfSamples() {
112
+ return !this.image.xybEncoded && !this.hdrSignal;
113
+ }
114
+ bytesParams(ycbcr, final) {
115
+ const image = this.image;
116
+ if (ycbcr || !image.xybEncoded || !final || this.linear)
117
+ return null;
118
+ return { m: image.opsinInverse, bias: image.opsinBias, k: 255 / image.toneMapping.intensityTarget * this.scale };
119
+ }
109
120
  toRGBA(p) {
110
121
  const n = p.width * p.height, ch = p.channels, image = this.image;
111
122
  if (p.rgba) {