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,4 +1,6 @@
1
- import { encodeAV1 } from "./av1/encode.js";
1
+ import { encodeAV1, encodeAV1Threaded } from "./av1/encode.js";
2
+ import { startThreads } from "../util/threads.js";
3
+ const MIN_THREADED_PIXELS = [640 * 640, 448 * 448, 320 * 320], PIXELS_PER_THREAD = [512 << 10, 256 << 10, 256 << 10];
2
4
  const QINDEX = [
3
5
  0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112,
4
6
  116, 120, 124, 128, 132, 136, 140, 144, 148, 152, 156, 160, 164, 168, 172, 176, 180, 184, 188, 192, 196, 200, 204, 208,
@@ -149,7 +151,7 @@ function seqMonochrome(d, o) {
149
151
  read(1);
150
152
  return !!read(1);
151
153
  }
152
- export function encode(rgba, width, height, { quality, alphaQuality, subsampling, effort, exif }) {
154
+ export async function encode(rgba, width, height, { quality, alphaQuality, subsampling, effort, exif, threads: maxThreads }) {
153
155
  if (width < 1 || height < 1)
154
156
  throw new RangeError('AVIF: dimensions must be at least 1');
155
157
  if (width > 65536 || height > 65536)
@@ -173,13 +175,37 @@ export function encode(rgba, width, height, { quality, alphaQuality, subsampling
173
175
  const cicp = lossless ? [1, 13, 0] : CICP;
174
176
  const planes = gray ? [Uint8Array.from({ length: width * height }, (_, i) => rgba[4 * i])]
175
177
  : lossless ? [1, 2, 0].map(c => Uint8Array.from({ length: width * height }, (_, i) => rgba[4 * i + c])) : toYUV(rgba, width, height, subsampled);
176
- const color = encodeAV1({ planes, width, height, layout: gray ? 0 : subsampled ? 1 : 3, cicp }, { qidx: qindex(quality), effort });
177
- let alpha = null;
178
- if (!opaque) {
179
- const a = new Uint8Array(width * height);
180
- for (let i = 0; i < a.length; i++)
181
- a[i] = original[4 * i + 3];
182
- alpha = encodeAV1({ planes: [a], width, height, layout: 0, cicp: [2, 2, 2] }, { qidx: qindex(alphaQuality), effort });
178
+ const n = Math.min(maxThreads, height + 63 >> 6, Math.ceil((width + 63 >> 6) / 2), Math.max(4, Math.floor(width * height / PIXELS_PER_THREAD[effort])));
179
+ let threads = n > 1 && width * height >= MIN_THREADED_PIXELS[effort] ? startThreads(n) : null;
180
+ const stop = () => {
181
+ if (threads)
182
+ for (const t of threads)
183
+ t.terminate();
184
+ threads = null;
185
+ };
186
+ const av1 = async (image, params) => {
187
+ if (threads) {
188
+ try {
189
+ return await encodeAV1Threaded(image, params, threads);
190
+ }
191
+ catch {
192
+ stop();
193
+ }
194
+ }
195
+ return encodeAV1(image, params);
196
+ };
197
+ let color, alpha = null;
198
+ try {
199
+ color = await av1({ planes, width, height, layout: gray ? 0 : subsampled ? 1 : 3, cicp }, { qidx: qindex(quality), effort });
200
+ if (!opaque) {
201
+ const a = new Uint8Array(width * height);
202
+ for (let i = 0; i < a.length; i++)
203
+ a[i] = original[4 * i + 3];
204
+ alpha = await av1({ planes: [a], width, height, layout: 0, cicp: [2, 2, 2] }, { qidx: qindex(alphaQuality), effort });
205
+ }
206
+ }
207
+ finally {
208
+ stop();
183
209
  }
184
210
  const profile = subsampled || gray ? 'MA1B' : 'MA1A';
185
211
  const ftyp = box('ftyp', ascii('avif'), u32(0), ascii('avif'), ascii('mif1'), ascii('miaf'), ascii(profile));
@@ -4,9 +4,11 @@
4
4
  * libavif converts (its reference path, src/reformat.c, with bilinear chroma upsampling; src/read.c, src/alpha.c), HDR
5
5
  * (PQ, HLG) tone mapped. Copyright 2019 Joe Drago, BSD-2-Clause License (see THIRD_PARTY_NOTICES.md)
6
6
  */
7
+ import { parseProfile } from "../util/icc.js";
7
8
  import { MAX_PIXELS, checkPixels } from "../util/limits.js";
8
9
  import { decodeAV1 } from "./av1/frame.js";
9
10
  import { toSRGB, hdrToLinear } from "./hdr.js";
11
+ import { runChunks, sharedOf, startThreads } from "../util/threads.js";
10
12
  const fourcc = (d, o) => String.fromCharCode(d[o], d[o + 1], d[o + 2], d[o + 3]);
11
13
  function* boxes(d, start, end) {
12
14
  const view = new DataView(d.buffer, d.byteOffset, d.byteLength);
@@ -181,7 +183,7 @@ function fromFrame(f) {
181
183
  primaries: f.seq.colorPrimaries
182
184
  };
183
185
  }
184
- function decodeAV1Item(d, it, idat, maxPixels) {
186
+ function av1Input(d, it, idat) {
185
187
  let data = itemData(d, it, idat);
186
188
  const av1C = property(it, 'av1C');
187
189
  if (av1C && av1C.end - av1C.start > 4 && (data[0] >> 3 & 15) !== 1) {
@@ -191,18 +193,25 @@ function decodeAV1Item(d, it, idat, maxPixels) {
191
193
  joined.set(data, config.length);
192
194
  data = joined;
193
195
  }
194
- const a1op = property(it, 'a1op'), lsel = property(it, 'lsel');
196
+ const a1op = property(it, 'a1op'), lsel = property(it, 'lsel'), ispe = property(it, 'ispe');
195
197
  const layer = lsel ? d[lsel.start] << 8 | d[lsel.start + 1] : 0xffff;
196
- const frame = decodeAV1(data, 0, data.length, { maxPixels, operatingPoint: a1op ? d[a1op.start] : 0, layer: layer === 0xffff ? -1 : layer });
197
- if (frame.incomplete) {
198
- const ispe = property(it, 'ispe');
199
- const view = new DataView(d.buffer, d.byteOffset, d.byteLength);
200
- if (!ispe || view.getUint32(ispe.start + 4) !== frame.hdr.upscaledWidth || view.getUint32(ispe.start + 8) !== frame.height)
201
- throw new Error('AVIF: layered images with inter predicted layers are not supported');
202
- }
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');
203
208
  return fromFrame(frame);
204
209
  }
205
- 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') ?? []) {
206
215
  const g = itemData(d, it, idat);
207
216
  const view = new DataView(g.buffer, g.byteOffset, g.byteLength);
208
217
  const wide = g[1] & 1;
@@ -213,47 +222,64 @@ function decodeGrid(d, it, items, idat, maxPixels, tiles = it.refs.get('dimg') ?
213
222
  throw new Error('AVIF: the grid has the wrong number of tiles');
214
223
  if (new Set(tiles).size !== tiles.length)
215
224
  throw new Error('AVIF: the grid repeats tiles');
216
- let out = null;
217
- for (let r = 0; r < rows; r++) {
218
- for (let c = 0; c < cols; c++) {
219
- const tileItem = items.get(tiles[r * cols + c]);
220
- if (!tileItem || tileItem.type !== 'av01')
221
- throw new Error('AVIF: invalid grid tile');
222
- const tile = decodeAV1Item(d, tileItem, idat, maxPixels);
223
- if (!out) {
224
- if (tile.width * cols < width || tile.height * rows < height)
225
- throw new Error('AVIF: the grid\'s tiles are too small');
226
- out = { ...tile, width, height, planes: [], strides: [] };
227
- for (let p = 0; p < tile.planes.length; p++) {
228
- const sx = p && tile.layout < 3 ? 1 : 0, sy = p && tile.layout === 1 ? 1 : 0;
229
- const stride = (width + sx) >> sx;
230
- out.strides.push(stride);
231
- out.planes.push(new Uint16Array(stride * ((height + sy) >> sy)));
232
- }
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)));
233
243
  }
234
- else if (tile.layout !== out.layout || tile.bitdepth !== out.bitdepth)
235
- throw new Error('AVIF: the grid\'s tiles differ');
236
- for (let p = 0; p < out.planes.length; p++) {
237
- const sx = p && out.layout < 3 ? 1 : 0, sy = p && out.layout === 1 ? 1 : 0;
238
- const tw = (tile.width + sx) >> sx, th = (tile.height + sy) >> sy;
239
- const x0 = c * tw, y0 = r * th;
240
- const pw = (width + sx) >> sx, ph = (height + sy) >> sy;
241
- for (let y = 0; y < th && y0 + y < ph; y++) {
242
- const n = Math.min(tw, pw - x0);
243
- if (n <= 0)
244
- break;
245
- out.planes[p].set(tile.planes[p].subarray(y * tile.strides[p], y * tile.strides[p] + n), (y0 + y) * out.strides[p] + x0);
246
- }
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);
247
257
  }
248
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);
249
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));
250
276
  return out;
251
277
  }
252
- function decodeItem(d, it, items, idat, maxPixels) {
278
+ async function decodeItem(d, it, items, idat, maxPixels, threads) {
253
279
  if (it.type === 'av01')
254
280
  return decodeAV1Item(d, it, idat, maxPixels);
255
281
  if (it.type === 'grid')
256
- return decodeGrid(d, it, items, idat, maxPixels);
282
+ return decodeGrid(d, it, items, idat, maxPixels, threads);
257
283
  throw new Error(`AVIF: unsupported item type ${it.type}`);
258
284
  }
259
285
  function coefficients(matrix) {
@@ -280,6 +306,21 @@ function convertRow444(c, j) {
280
306
  out[p + 3] = 255;
281
307
  }
282
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
+ }
283
324
  function convertRow(c, j) {
284
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;
285
326
  const uvRow = (j >> sy) * cs, yRow = j * c.ys;
@@ -348,7 +389,14 @@ function convertRow(c, j) {
348
389
  out[p + 2] = toByte(b);
349
390
  }
350
391
  }
351
- 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) {
352
400
  const { width, height, bitdepth, layout } = y;
353
401
  const max = (1 << bitdepth) - 1;
354
402
  const [kr, kb] = coefficients(y.matrix).map(f32), kg = f32(f32(1 - kr) - kb);
@@ -360,14 +408,16 @@ function toRgba(y, alpha, toneMapping, premultiplied = false) {
360
408
  tableY[i] = (i - biasY) / rangeY;
361
409
  tableUV[i] = identity ? tableY[i] : (i - biasUV) / rangeUV;
362
410
  }
363
- 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);
364
413
  const hdr = y.transfer === TRANSFER_PQ || y.transfer === TRANSFER_HLG;
365
- const rgb = hdr ? new Float32Array(width * height * 3) : null;
366
- const Y = y.planes[0], ys = y.strides[0];
367
- const color = layout !== 0 && y.planes.length === 3;
368
- 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];
369
419
  const sx = layout < 3 ? 1 : 0, sy = layout === 1 ? 1 : 0;
370
- const alphas = alpha ? new Float32Array(width * height).fill(1) : null;
420
+ const alphas = alpha ? array(Float32Array, 4, width * height).fill(1) : null;
371
421
  if (alpha && alphas) {
372
422
  const A = alpha.planes[0], as = alpha.strides[0], amax = (1 << alpha.bitdepth) - 1;
373
423
  const lo = 16 << (alpha.bitdepth - 8), span = 219 << (alpha.bitdepth - 8);
@@ -384,11 +434,11 @@ function toRgba(y, alpha, toneMapping, premultiplied = false) {
384
434
  const c = {
385
435
  width, height, layout, color, identity, ycgco, Y, U, V, ys, cs, sx, sy, tableY, tableUV, out, rgb, unmultiply,
386
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,
387
- n: max + 1, red: null, blue: null, gTerm: null
437
+ n: max + 1, red: null, blue: null, gTerm: null, weighted: null
388
438
  };
389
439
  const n = max + 1;
390
440
  if (layout === 3 && color && !identity && !ycgco && !rgb && !unmultiply && n * n * 2 <= width * height) {
391
- 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);
392
442
  for (let v = 0; v < n; v++) {
393
443
  const rTerm = f32(c.cr2 * tableUV[v]), bTerm = f32(c.cb2 * tableUV[v]);
394
444
  for (let y = 0; y < n; y++) {
@@ -401,12 +451,18 @@ function toRgba(y, alpha, toneMapping, premultiplied = false) {
401
451
  for (let v = 0; v < n; v++)
402
452
  gTerm[u * n + v] = f32(f32(2 * f32(f32(c.crg * tableUV[v]) + cbTerm)) * c.kgInverse);
403
453
  }
404
- for (let j = 0; j < height; j++)
405
- convertRow444(c, j);
406
454
  }
407
- else
408
- for (let j = 0; j < height; j++)
409
- 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);
410
466
  if (rgb)
411
467
  out = toSRGB(hdrToLinear(rgb, y.transfer, y.primaries), toneMapping);
412
468
  if (alphas)
@@ -414,7 +470,9 @@ function toRgba(y, alpha, toneMapping, premultiplied = false) {
414
470
  out[i * 4 + 3] = Math.round(alphas[i] * 255);
415
471
  return out;
416
472
  }
417
- 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) {
418
476
  if (!isAVIF(d))
419
477
  throw new Error('AVIF: invalid header');
420
478
  let meta, moov;
@@ -440,31 +498,58 @@ export function decode(d, maxPixels = MAX_PIXELS, toneMapping = 'reinhard') {
440
498
  return undefined;
441
499
  };
442
500
  const alphaItem = alphaOf(primary);
443
- const color = decodeItem(d, it, items, idat, maxPixels);
444
- applyColr(d, it, color);
445
- let alpha = alphaItem ? decodeItem(d, alphaItem, items, idat, maxPixels) : null;
446
- if (!alphaItem && it.type === 'grid') {
447
- const tiles = (it.refs.get('dimg') ?? []).map(alphaOf);
448
- if (tiles.length && tiles.every(t => t))
449
- 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);
450
507
  }
451
- let pixels = toRgba(color, alpha, toneMapping, alphaItem && (it.refs.get('prem') ?? []).includes(alphaItem.id));
452
- let { width, height } = color;
453
- for (const { box } of it.props) {
454
- if (box.type === 'clap')
455
- ({ width, height, pixels } = clap(d, box, width, height, pixels));
456
- else if (box.type === 'irot')
457
- ({ width, height, pixels } = rotate(pixels, width, height, d[box.start] & 3));
458
- else if (box.type === 'imir')
459
- pixels = mirror(pixels, width, height, d[box.start] & 1);
508
+ finally {
509
+ if (pool)
510
+ for (const t of pool)
511
+ t.terminate();
460
512
  }
461
- return { width, height, pixels };
462
513
  }
463
514
  }
464
515
  if (moov)
465
516
  return decodeSequence(d, moov, maxPixels, toneMapping);
466
517
  throw new Error('AVIF: no image');
467
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
+ }
545
+ function iccOf(d, it) {
546
+ for (const { box } of it.props) {
547
+ const type = box.type === 'colr' && box.end - box.start > 4 ? fourcc(d, box.start) : '';
548
+ if (type === 'prof' || type === 'rICC')
549
+ return d.subarray(box.start + 4, box.end);
550
+ }
551
+ return undefined;
552
+ }
468
553
  function applyColr(d, it, yuv) {
469
554
  for (const { box } of it.props) {
470
555
  if (box.type !== 'colr' || fourcc(d, box.start) !== 'nclx')
@@ -527,7 +612,7 @@ function mirror(pixels, width, height, axis) {
527
612
  }
528
613
  return out;
529
614
  }
530
- function decodeSequence(d, moov, maxPixels, toneMapping) {
615
+ async function decodeSequence(d, moov, maxPixels, toneMapping) {
531
616
  const view = new DataView(d.buffer, d.byteOffset, d.byteLength);
532
617
  const tracks = [];
533
618
  for (const trak of boxes(d, moov.start, moov.end)) {
@@ -577,5 +662,5 @@ function decodeSequence(d, moov, maxPixels, toneMapping) {
577
662
  return fromFrame(decodeAV1(data, 0, data.length, { maxPixels }));
578
663
  };
579
664
  const color = frame(colorTrack);
580
- 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) };
581
666
  }
@@ -23,6 +23,7 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
23
23
  let adobe = null;
24
24
  let jfif = false;
25
25
  let orientation = 1;
26
+ const profile = [];
26
27
  let restartInterval = 0;
27
28
  let pos = 2;
28
29
  const u16 = (offset) => data[offset] << 8 | data[offset + 1];
@@ -112,6 +113,10 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
112
113
  if (orientation === 1)
113
114
  orientation = exifOrientation(data.subarray(start, end));
114
115
  break;
116
+ case 0xe2:
117
+ if (length >= 16 && String.fromCharCode(...data.subarray(start, start + 12)) === 'ICC_PROFILE\0' && data[start + 12] >= 1)
118
+ profile[data[start + 12] - 1] ??= data.subarray(start + 14, end);
119
+ break;
115
120
  case 0xee:
116
121
  if (length >= 14 && data[start] === 0x41 && data[start + 1] === 0x64 && data[start + 2] === 0x6f && data[start + 3] === 0x62 && data[start + 4] === 0x65)
117
122
  adobe = { transform: data[start + 11] };
@@ -151,7 +156,8 @@ export function decode(data, { transform, maxPixels = MAX_PIXELS } = {}) {
151
156
  }
152
157
  if (!frame)
153
158
  throw new Error('JPEG: missing frame header');
154
- return { width: frame.width, height: frame.height, pixels: output(frame, adobe, jfif, transform), orientation };
159
+ const icc = profile.length && Array.from(profile).every(Boolean) ? concat(profile) : undefined;
160
+ return { width: frame.width, height: frame.height, pixels: output(frame, adobe, jfif, transform), orientation, icc };
155
161
  }
156
162
  function createFrame(progressive, height, width, componentData) {
157
163
  const count = componentData[0];
@@ -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
  }