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.
@@ -4,7 +4,7 @@ import { concat } from "../util/mem.js";
4
4
  import { littleEndian } from "../util/alpha.js";
5
5
  import { encode as utf8, decode as utf8Decode } from "../util/utf8.js";
6
6
  import { orientation as exifOrientation, xmpOrientation } from "./exif.js";
7
- import { compressAsync, decompressAsync } from "./zlib.js";
7
+ import { compressAsync, decompressAsync, decompress } from "./zlib.js";
8
8
  const HEAD = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
9
9
  const IHDR = 0x49484452;
10
10
  const PLTE = 0x504c5445;
@@ -12,6 +12,8 @@ const tRNS = 0x74524e53;
12
12
  const IDAT = 0x49444154;
13
13
  const IEND = 0x49454e44;
14
14
  const eXIf = 0x65584966;
15
+ const iCCP = 0x69434350;
16
+ const sRGB = 0x73524742;
15
17
  const tEXt = 0x74455874;
16
18
  const zTXt = 0x7a545874;
17
19
  const iTXt = 0x69545874;
@@ -346,6 +348,7 @@ function parse(array) {
346
348
  let transparency = null;
347
349
  const idat = [];
348
350
  let exif = null;
351
+ let iccp = null, srgb = false;
349
352
  const text = [];
350
353
  let animation = null;
351
354
  const frames = [];
@@ -429,6 +432,10 @@ function parse(array) {
429
432
  }
430
433
  else if (type === eXIf)
431
434
  exif ??= chunk;
435
+ else if (type === iCCP)
436
+ iccp ??= chunk;
437
+ else if (type === sRGB)
438
+ srgb = true;
432
439
  else if (type === tEXt || type === zTXt || type === iTXt)
433
440
  text.push({ type, chunk });
434
441
  else if (type === IEND)
@@ -455,23 +462,30 @@ function parse(array) {
455
462
  if (!frames.length || frames.length < animation.frames || frames.some(f => !f.data.length))
456
463
  animationError = true;
457
464
  }
458
- return { header, palette, transparency, idat, exif, text, animation, frames, animationError };
465
+ return { header, palette, transparency, idat, exif, iccp: srgb ? null : iccp, text, animation, frames, animationError };
459
466
  }
460
- async function decodeImageData(p, chunks, width, height) {
461
- const { depth, colorType, interlace } = p.header;
462
- const channels = COLOR_TYPE_CHANNELS[colorType];
463
- const bitsPerPixel = channels * depth;
464
- const bpp = Math.max(1, bitsPerPixel >> 3);
465
- const passes = interlace ? ADAM7.map(([xs, ys, dx, dy]) => [xs, ys, dx, dy, Math.ceil((width - xs) / dx), Math.ceil((height - ys) / dy)]) : [[0, 0, 1, 1, width, height]];
467
+ function passesOf(p, width, height) {
468
+ const bitsPerPixel = COLOR_TYPE_CHANNELS[p.header.colorType] * p.header.depth;
469
+ const passes = p.header.interlace ? ADAM7.map(([xs, ys, dx, dy]) => [xs, ys, dx, dy, Math.ceil((width - xs) / dx), Math.ceil((height - ys) / dy)]) : [[0, 0, 1, 1, width, height]];
466
470
  let expected = 0;
467
471
  for (const pass of passes) {
468
472
  const [, , , , pw, ph] = pass;
469
473
  if (pw > 0 && ph > 0)
470
474
  expected += ph * (1 + Math.ceil(pw * bitsPerPixel / 8));
471
475
  }
476
+ return { passes, expected };
477
+ }
478
+ async function decodeImageData(p, chunks, width, height) {
479
+ const { expected } = passesOf(p, width, height);
472
480
  if (!chunks.length)
473
481
  throw new Error('PNG: missing image data');
474
- const data = await decompressAsync(chunks.length === 1 ? chunks[0] : concat(chunks), expected);
482
+ return imagePixels(p, await decompressAsync(chunks.length === 1 ? chunks[0] : concat(chunks), expected), width, height);
483
+ }
484
+ function imagePixels(p, data, width, height) {
485
+ const { depth, colorType, interlace } = p.header;
486
+ const bitsPerPixel = COLOR_TYPE_CHANNELS[colorType] * depth;
487
+ const bpp = Math.max(1, bitsPerPixel >> 3);
488
+ const { passes, expected } = passesOf(p, width, height);
475
489
  if (data.length < expected)
476
490
  throw new Error('PNG: image data is truncated');
477
491
  const rgba = new Uint8Array(width * height * 4);
@@ -493,7 +507,29 @@ export async function decode(array, maxPixels = MAX_PIXELS) {
493
507
  const { width, height } = p.header;
494
508
  checkPixels(width, height, maxPixels);
495
509
  const pixels = await decodeImageData(p, p.idat, width, height);
496
- return { width, height, pixels, orientation: p.exif ? exifOrientation(p.exif) : await textOrientation(p.text) };
510
+ return { width, height, pixels, orientation: p.exif ? exifOrientation(p.exif) : await textOrientation(p.text), icc: await profile(p.iccp) };
511
+ }
512
+ async function profile(chunk) {
513
+ if (!chunk)
514
+ return undefined;
515
+ const separator = chunk.indexOf(0);
516
+ if (separator < 1 || separator > 79 || chunk[separator + 1] !== 0)
517
+ return undefined;
518
+ try {
519
+ return await decompressAsync(chunk.subarray(separator + 2), 1 << 26);
520
+ }
521
+ catch {
522
+ return undefined;
523
+ }
524
+ }
525
+ export function decodeSync(array, maxPixels = MAX_PIXELS) {
526
+ const p = parse(array);
527
+ const { width, height } = p.header;
528
+ checkPixels(width, height, maxPixels);
529
+ if (!p.idat.length)
530
+ throw new Error('PNG: missing image data');
531
+ const { expected } = passesOf(p, width, height);
532
+ return { width, height, pixels: imagePixels(p, decompress(p.idat.length === 1 ? p.idat[0] : concat(p.idat), expected), width, height) };
497
533
  }
498
534
  export function isAnimated(array) {
499
535
  try {
@@ -510,7 +546,7 @@ export async function decodeAnimation(array, onlyFirstFrame = false, maxPixels =
510
546
  checkPixels(width, height, maxPixels, !p.animation || p.animationError || onlyFirstFrame ? 1 : Math.max(1, p.frames.length));
511
547
  if (!p.animation || p.animationError) {
512
548
  const pixels = await decodeImageData(p, p.idat, width, height);
513
- return { width, height, plays: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, dispose: 0, blend: 0, pixels }] };
549
+ return { width, height, plays: 0, frames: [{ x: 0, y: 0, width, height, duration: 0, dispose: 0, blend: 0, pixels }], icc: await profile(p.iccp) };
514
550
  }
515
551
  const frames = [];
516
552
  for (const { control: c, data } of p.frames) {
@@ -525,7 +561,7 @@ export async function decodeAnimation(array, onlyFirstFrame = false, maxPixels =
525
561
  if (onlyFirstFrame)
526
562
  break;
527
563
  }
528
- return { width, height, plays: p.animation.plays, frames };
564
+ return { width, height, plays: p.animation.plays, frames, icc: await profile(p.iccp) };
529
565
  }
530
566
  export function compositeAnimation({ width, height, frames }) {
531
567
  const canvas = new Uint8Array(width * height * 4);
@@ -107,6 +107,8 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
107
107
  const v = values(tag);
108
108
  return v && v.length ? v[0] : fallback;
109
109
  }
110
+ const profileTag = tags.get(34675);
111
+ const icc = profileTag && TYPE_SIZES[profileTag.type] === 1 ? data.subarray(profileTag.offset, profileTag.offset + profileTag.count) : undefined;
110
112
  const orientationTag = value(TAGS.Orientation, 1);
111
113
  const orientation = orientationTag >= 1 && orientationTag <= 8 ? orientationTag : 1;
112
114
  const width = value(TAGS.ImageWidth);
@@ -174,7 +176,7 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
174
176
  const decoded = jpeg.decode(stream, { transform });
175
177
  blitRGBA(decoded.pixels, decoded.width, decoded.height, pixels, width, height, (s % segmentsAcross) * segmentWidth, (s / segmentsAcross | 0) * segmentHeight);
176
178
  }
177
- return { width, height, pixels, orientation };
179
+ return { width, height, pixels, orientation, icc };
178
180
  }
179
181
  const samplesPerRow = planar ? 1 : samplesPerPixel;
180
182
  const planes = planar ? samplesPerPixel : 1;
@@ -195,7 +197,7 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
195
197
  written += expected;
196
198
  }
197
199
  ycbcrUnitsToRGBA(units, width, height, h, v, ycbcrConversion(values), pixels);
198
- return { width, height, pixels, orientation };
200
+ return { width, height, pixels, orientation, icc };
199
201
  }
200
202
  const rowBytes = Math.ceil(width * samplesPerRow * bps / 8);
201
203
  const planeBytes = rowBytes * height;
@@ -274,7 +276,7 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
274
276
  }
275
277
  }
276
278
  }
277
- return { width, height, pixels, orientation };
279
+ return { width, height, pixels, orientation, icc };
278
280
  }
279
281
  function sampleReader(raw, bps, sampleFormat, little, range) {
280
282
  const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
@@ -1,7 +1,7 @@
1
1
  /*!
2
2
  * Lossy WebP (VP8) encoding, ported from libwebp's encoder (src/enc: analysis_enc.c, quant_enc.c, frame_enc.c,
3
3
  * iterator_enc.c, cost_enc.c, token_enc.c, tree_enc.c, syntax_enc.c, filter_enc.c, alpha_enc.c; src/utils:
4
- * bit_writer_utils.c, filters_utils.c) with its default settings and any method (effort: 0-2 decide modes by
4
+ * bit_writer_utils.c, filters_utils.c, quant_levels_utils.c) with its default settings and any method (effort: 0-2 decide modes by
5
5
  * distortion, 3-6 by rate and distortion, 5-6 with trellis quantization), so the output is the same as cwebp's.
6
6
  * Copyright (c) 2010 Google Inc., BSD-3-Clause License (see THIRD_PARTY_NOTICES.md)
7
7
  */
@@ -1849,6 +1849,57 @@ function partition0(enc) {
1849
1849
  codeIntraModes(enc, bw);
1850
1850
  return bw.finish();
1851
1851
  }
1852
+ function quantizeLevels(a, levels) {
1853
+ const freq = new Int32Array(256), qLevel = new Int32Array(256), invQLevel = new Float64Array(256);
1854
+ let minS = 255, maxS = 0, levelsIn = 0;
1855
+ for (let n = 0; n < a.length; n++) {
1856
+ const v = a[n];
1857
+ if (!freq[v])
1858
+ levelsIn++;
1859
+ if (v < minS)
1860
+ minS = v;
1861
+ if (v > maxS)
1862
+ maxS = v;
1863
+ freq[v]++;
1864
+ }
1865
+ if (levelsIn <= levels)
1866
+ return;
1867
+ for (let i = 0; i < levels; i++)
1868
+ invQLevel[i] = minS + (maxS - minS) * i / (levels - 1);
1869
+ qLevel[maxS] = levels - 1;
1870
+ const threshold = 1e-4 * a.length;
1871
+ const qSum = new Float64Array(256), qCount = new Float64Array(256);
1872
+ let lastErr = 1e38;
1873
+ for (let iter = 0; iter < 6; iter++) {
1874
+ qSum.fill(0);
1875
+ qCount.fill(0);
1876
+ for (let s = minS, slot = 0; s <= maxS; s++) {
1877
+ while (slot < levels - 1 && 2 * s > invQLevel[slot] + invQLevel[slot + 1])
1878
+ slot++;
1879
+ if (freq[s] > 0) {
1880
+ qSum[slot] += s * freq[s];
1881
+ qCount[slot] += freq[s];
1882
+ }
1883
+ qLevel[s] = slot;
1884
+ }
1885
+ for (let slot = 1; slot < levels - 1; slot++)
1886
+ if (qCount[slot] > 0)
1887
+ invQLevel[slot] = qSum[slot] / qCount[slot];
1888
+ let err = 0;
1889
+ for (let s = minS; s <= maxS; s++) {
1890
+ const e = s - invQLevel[qLevel[s]];
1891
+ err += freq[s] * e * e;
1892
+ }
1893
+ if (lastErr - err < threshold)
1894
+ break;
1895
+ lastErr = err;
1896
+ }
1897
+ const map = new Uint8Array(256);
1898
+ for (let s = minS; s <= maxS; s++)
1899
+ map[s] = Math.trunc(invQLevel[qLevel[s]] + 0.5);
1900
+ for (let n = 0; n < a.length; n++)
1901
+ a[n] = map[a[n]];
1902
+ }
1852
1903
  function filterAlpha(a, width, height, filter) {
1853
1904
  const out = new Uint8Array(a.length);
1854
1905
  for (let y = 0; y < height; y++) {
@@ -1899,7 +1950,12 @@ function estimateBestFilter(a, width, height) {
1899
1950
  }
1900
1951
  return best;
1901
1952
  }
1902
- export function encodeAlpha(a, width, height, method = 4) {
1953
+ export async function encodeAlpha(a, width, height, method = 4, quality = 100) {
1954
+ const reduce = quality < 100;
1955
+ if (reduce) {
1956
+ a = a.slice();
1957
+ quantizeLevels(a, quality <= 70 ? 2 + Math.trunc(quality / 5) : 16 + (quality - 70) * 8);
1958
+ }
1903
1959
  let colors = 0;
1904
1960
  const seen = new Uint8Array(256);
1905
1961
  for (let i = 0; i < a.length; i++)
@@ -1916,13 +1972,13 @@ export function encodeAlpha(a, width, height, method = 4) {
1916
1972
  const argb = new Uint32Array(a.length);
1917
1973
  for (let i = 0; i < a.length; i++)
1918
1974
  argb[i] = data[i] << 8;
1919
- let stream = vp8l.encode(argb, width, height).subarray(5), method = 1;
1975
+ let stream = (await vp8l.encode(argb, width, height)).subarray(5), method = 1;
1920
1976
  if (stream.length > a.length) {
1921
1977
  stream = data;
1922
1978
  method = 0;
1923
1979
  }
1924
1980
  const out = new Uint8Array(1 + stream.length);
1925
- out[0] = method | filter << 2;
1981
+ out[0] = method | filter << 2 | (reduce ? 1 << 4 : 0);
1926
1982
  out.set(stream, 1);
1927
1983
  if (!best || out.length < best.length)
1928
1984
  best = out;
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { ByteWriter } from "../util/bytes.js";
7
7
  import { MAX_PIXELS, checkPixels } from "../util/limits.js";
8
+ import { runChunks, shared } from "../util/threads.js";
8
9
  const SIGNATURE = 0x2f;
9
10
  const CODE_LENGTH_ORDER = [17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
10
11
  const DISTANCE_MAP = Int8Array.of(0, 1, 1, 0, 1, 1, -1, 1, 0, 2, 2, 0, 1, 2, -1, 2, 2, 1, -2, 1, 2, 2, -2, 2, 0, 3, 3, 0, 1, 3, -1, 3, 3, 1, -3, 1, 2, 3, -2, 3, 3, 2, -3, 2, 0, 4, 4, 0, 1, 4, -1, 4, 4, 1, -4, 1, 3, 3, -3, 3, 2, 4, -2, 4, 4, 2, -4, 2, 0, 5, 3, 4, -3, 4, 4, 3, -4, 3, 5, 0, 1, 5, -1, 5, 5, 1, -5, 1, 2, 5, -2, 5, 5, 2, -5, 2, 4, 4, -4, 4, 3, 5, -3, 5, 5, 3, -5, 3, 0, 6, 6, 0, 1, 6, -1, 6, 6, 1, -6, 1, 2, 6, -2, 6, 6, 2, -6, 2, 4, 5, -4, 5, 5, 4, -5, 4, 3, 6, -3, 6, 6, 3, -6, 3, 0, 7, 7, 0, 1, 7, -1, 7, 5, 5, -5, 5, 7, 1, -7, 1, 4, 6, -4, 6, 6, 4, -6, 4, 2, 7, -2, 7, 7, 2, -7, 2, 3, 7, -3, 7, 7, 3, -7, 3, 5, 6, -5, 6, 6, 5, -6, 5, 8, 0, 4, 7, -4, 7, 7, 4, -7, 4, 8, 1, 8, 2, 6, 6, -6, 6, 8, 3, 5, 7, -5, 7, 7, 5, -7, 5, 8, 4, 6, 7, -6, 7, 7, 6, -7, 6, 8, 5, 7, 7, -7, 7, 8, 6, 8, 7);
@@ -958,7 +959,7 @@ function tokenSymbols(stream, k, out) {
958
959
  else
959
960
  out[0] = NUM_LITERAL_CODES + NUM_LENGTH_CODES + v;
960
961
  }
961
- function prefixGroups(stream, width, height, cacheBits, bits) {
962
+ async function prefixGroups(stream, width, height, cacheBits, bits, threads) {
962
963
  const bw = subSize(width, bits), bh = subSize(height, bits), nb = bw * bh;
963
964
  const greenSize = NUM_LITERAL_CODES + NUM_LENGTH_CODES + (cacheBits ? 1 << cacheBits : 0);
964
965
  const sizes = [greenSize, 256, 256, 256, NUM_DISTANCE_CODES], offsets = [0, greenSize, greenSize + 256, greenSize + 512, greenSize + 768];
@@ -988,7 +989,10 @@ function prefixGroups(stream, width, height, cacheBits, bits) {
988
989
  }
989
990
  while (blk < nb)
990
991
  starts[++blk] = sparse.length;
991
- const entries = Float64Array.from(sparse);
992
+ const array = (Type, bytes, length) => new Type(threads ? new SharedArrayBuffer(bytes * length) : new ArrayBuffer(bytes * length));
993
+ const entries = array(Float64Array, 8, sparse.length);
994
+ entries.set(sparse);
995
+ const sharedStarts = threads ? shared(starts) : starts;
992
996
  const logs = (cl) => {
993
997
  const t = totals(cl), out = new Float64Array(total);
994
998
  for (let c = 0; c < 5; c++) {
@@ -998,12 +1002,6 @@ function prefixGroups(stream, width, height, cacheBits, bits) {
998
1002
  }
999
1003
  return out;
1000
1004
  };
1001
- const cost = (blk, log) => {
1002
- let bitsSum = 0;
1003
- for (let e = starts[blk]; e < starts[blk + 1]; e += 2)
1004
- bitsSum += entries[e + 1] * log[entries[e]];
1005
- return bitsSum;
1006
- };
1007
1005
  const totals = (cl) => Float64Array.from(offsets, (o, c) => {
1008
1006
  let t = 0;
1009
1007
  for (let s = 0; s < sizes[c]; s++)
@@ -1022,7 +1020,13 @@ function prefixGroups(stream, width, height, cacheBits, bits) {
1022
1020
  }
1023
1021
  return b;
1024
1022
  };
1025
- const used = Array.from({ length: nb }, (_, i) => i).filter(i => starts[i + 1] > starts[i]);
1023
+ const used = Int32Array.from(Array.from({ length: nb }, (_, i) => i).filter(i => starts[i + 1] > starts[i]));
1024
+ const sharedUsed = threads ? shared(used) : used;
1025
+ const costs = array(Float64Array, 8, used.length), nearest = array(Int32Array, 4, used.length);
1026
+ const blockCosts = async (logs) => {
1027
+ const task = { task: 'vp8l-costs', entries, starts: sharedStarts, used: sharedUsed, logs, costs, nearest };
1028
+ await runChunks(threads, task, Math.ceil(used.length / COST_BLOCKS), costChunks(task));
1029
+ };
1026
1030
  const single = new Float64Array(total);
1027
1031
  for (const blk of used)
1028
1032
  for (let e = starts[blk]; e < starts[blk + 1]; e += 2)
@@ -1041,10 +1045,11 @@ function prefixGroups(stream, width, height, cacheBits, bits) {
1041
1045
  const centers = [blockHistogram(used[0])];
1042
1046
  const dist = new Float64Array(nb).fill(Infinity);
1043
1047
  while (centers.length < k) {
1044
- const log = logs(centers[centers.length - 1]);
1048
+ await blockCosts([logs(centers[centers.length - 1])]);
1045
1049
  let far = -1;
1046
- for (const blk of used) {
1047
- dist[blk] = Math.min(dist[blk], cost(blk, log));
1050
+ for (let u = 0; u < used.length; u++) {
1051
+ const blk = used[u];
1052
+ dist[blk] = Math.min(dist[blk], costs[u]);
1048
1053
  if (far < 0 || dist[blk] > dist[far])
1049
1054
  far = blk;
1050
1055
  }
@@ -1052,18 +1057,9 @@ function prefixGroups(stream, width, height, cacheBits, bits) {
1052
1057
  }
1053
1058
  let clusters = centers;
1054
1059
  for (let iter = 0; iter < 3; iter++) {
1055
- const ls = clusters.map(logs);
1056
- for (const blk of used) {
1057
- let bc = 0, bv = Infinity;
1058
- for (let j = 0; j < ls.length; j++) {
1059
- const v = cost(blk, ls[j]);
1060
- if (v < bv) {
1061
- bv = v;
1062
- bc = j;
1063
- }
1064
- }
1065
- assign[blk] = bc;
1066
- }
1060
+ await blockCosts(clusters.map(logs));
1061
+ for (let u = 0; u < used.length; u++)
1062
+ assign[used[u]] = nearest[u];
1067
1063
  clusters = clusters.map(() => new Float64Array(total));
1068
1064
  for (const blk of used) {
1069
1065
  const cl = clusters[assign[blk]];
@@ -1093,7 +1089,34 @@ function prefixGroups(stream, width, height, cacheBits, bits) {
1093
1089
  const [groups, kept] = best;
1094
1090
  return [groups, kept.map(cl => sizes.map((size, c) => Int32Array.from(cl.subarray(offsets[c], offsets[c] + size)))), bestBits];
1095
1091
  }
1096
- function writeImage(w, pixels, width, isMain) {
1092
+ const COST_BLOCKS = 1024;
1093
+ export function costChunks({ entries, starts, used, logs, costs, nearest }) {
1094
+ const cost = (blk, log) => {
1095
+ let bitsSum = 0;
1096
+ for (let e = starts[blk]; e < starts[blk + 1]; e += 2)
1097
+ bitsSum += entries[e + 1] * log[entries[e]];
1098
+ return bitsSum;
1099
+ };
1100
+ return chunk => {
1101
+ for (let u = chunk * COST_BLOCKS; u < Math.min(used.length, (chunk + 1) * COST_BLOCKS); u++) {
1102
+ const blk = used[u];
1103
+ if (logs.length === 1) {
1104
+ costs[u] = cost(blk, logs[0]);
1105
+ continue;
1106
+ }
1107
+ let bc = 0, bv = Infinity;
1108
+ for (let j = 0; j < logs.length; j++) {
1109
+ const v = cost(blk, logs[j]);
1110
+ if (v < bv) {
1111
+ bv = v;
1112
+ bc = j;
1113
+ }
1114
+ }
1115
+ nearest[u] = bc;
1116
+ }
1117
+ };
1118
+ }
1119
+ async function writeImage(w, pixels, width, isMain, threads = null) {
1097
1120
  const tokens = tokenize(pixels, width);
1098
1121
  const cacheBits = isMain ? bestCacheBits(tokens, pixels) : 0;
1099
1122
  const stream = withCache(tokens, pixels, cacheBits), counts = histograms(stream, cacheBits);
@@ -1101,7 +1124,7 @@ function writeImage(w, pixels, width, isMain) {
1101
1124
  const height = pixels.length / width;
1102
1125
  let groups = null, groupCounts = [counts], prefixBits = 0;
1103
1126
  if (isMain && pixels.length > 4096) {
1104
- const r = prefixGroups(stream, width, height, cacheBits, 4);
1127
+ const r = await prefixGroups(stream, width, height, cacheBits, 4, threads);
1105
1128
  if (r && r[2] < best) {
1106
1129
  [groups, groupCounts] = r;
1107
1130
  prefixBits = 4;
@@ -1117,7 +1140,7 @@ function writeImage(w, pixels, width, isMain) {
1117
1140
  w.write(groups ? 1 : 0, 1);
1118
1141
  if (groups) {
1119
1142
  w.write(prefixBits - 2, 3);
1120
- writeImage(w, Uint32Array.from(groups, g => g << 8), subSize(width, prefixBits), false);
1143
+ await writeImage(w, Uint32Array.from(groups, g => g << 8), subSize(width, prefixBits), false);
1121
1144
  }
1122
1145
  }
1123
1146
  const { ops, values, distances, count } = stream;
@@ -1154,11 +1177,19 @@ function writeImage(w, pixels, width, isMain) {
1154
1177
  const subPixels = (a, b) => ((a | 0x00ff00ff) - (b & 0xff00ff00) & 0xff00ff00 | (a | 0xff00ff00) - (b & 0x00ff00ff) & 0x00ff00ff) >>> 0;
1155
1178
  const BYTE_COST = Uint8Array.from({ length: 256 }, (_, c) => c < 128 ? c : 256 - c);
1156
1179
  const residualCost = (r) => BYTE_COST[r & 255] + BYTE_COST[r >>> 8 & 255] + BYTE_COST[r >>> 16 & 255] + BYTE_COST[r >>> 24];
1157
- function applyPredictor(p, width, height, bits) {
1180
+ async function applyPredictor(p, width, height, bits, threads) {
1158
1181
  const blocksX = subSize(width, bits), blocksY = subSize(height, bits);
1159
- const modes = new Uint32Array(blocksX * blocksY);
1160
- const size = 1 << bits;
1161
- const src = p.slice(), predicted = new Uint32Array(size);
1182
+ const task = {
1183
+ task: 'vp8l-predictor', p, src: threads ? shared(p) : p.slice(), width, height, bits,
1184
+ modes: new Uint32Array(threads ? new SharedArrayBuffer(4 * blocksX * blocksY) : new ArrayBuffer(4 * blocksX * blocksY)),
1185
+ };
1186
+ await runChunks(threads, task, Math.ceil(blocksY / PREDICTOR_ROWS), predictorChunks(task));
1187
+ return task.modes;
1188
+ }
1189
+ const PREDICTOR_ROWS = 4;
1190
+ export function predictorChunks({ p, src, modes, width, height, bits }) {
1191
+ const blocksX = subSize(width, bits), blocksY = subSize(height, bits), size = 1 << bits;
1192
+ const predicted = new Uint32Array(size);
1162
1193
  const predictRow = (mode, x0, x1, y) => {
1163
1194
  const row = y * width;
1164
1195
  if (y === 0) {
@@ -1171,32 +1202,33 @@ function applyPredictor(p, width, height, bits) {
1171
1202
  predicted[x++] = src[row - width];
1172
1203
  predictRun(mode, src, row + x, x1 - x, width, predicted, x - x0);
1173
1204
  };
1174
- for (let by = 0; by < blocksY; by++)
1175
- for (let bx = 0; bx < blocksX; bx++) {
1176
- let best = 0, bestCost = Infinity;
1177
- const x0 = bx * size, y0 = by * size, x1 = Math.min(width, x0 + size), y1 = Math.min(height, y0 + size);
1178
- for (let mode = 0; mode < 14; mode++) {
1179
- let cost = 0;
1180
- for (let y = y0; y < y1 && cost < bestCost; y++) {
1181
- predictRow(mode, x0, x1, y);
1182
- for (let x = x0, i = y * width + x0; x < x1; x++, i++)
1183
- cost += residualCost(subPixels(src[i], predicted[x - x0]));
1205
+ return chunk => {
1206
+ for (let by = chunk * PREDICTOR_ROWS; by < Math.min(blocksY, (chunk + 1) * PREDICTOR_ROWS); by++)
1207
+ for (let bx = 0; bx < blocksX; bx++) {
1208
+ let best = 0, bestCost = Infinity;
1209
+ const x0 = bx * size, y0 = by * size, x1 = Math.min(width, x0 + size), y1 = Math.min(height, y0 + size);
1210
+ for (let mode = 0; mode < 14; mode++) {
1211
+ let cost = 0;
1212
+ for (let y = y0; y < y1 && cost < bestCost; y++) {
1213
+ predictRow(mode, x0, x1, y);
1214
+ for (let x = x0, i = y * width + x0; x < x1; x++, i++)
1215
+ cost += residualCost(subPixels(src[i], predicted[x - x0]));
1216
+ }
1217
+ if (cost < bestCost) {
1218
+ bestCost = cost;
1219
+ best = mode;
1220
+ }
1184
1221
  }
1185
- if (cost < bestCost) {
1186
- bestCost = cost;
1187
- best = mode;
1222
+ modes[by * blocksX + bx] = (0xff000000 | best << 8) >>> 0;
1223
+ for (let y = y0; y < y1; y++) {
1224
+ predictRow(best, x0, x1, y);
1225
+ for (let x = x0, i = y * width + x0; x < x1; x++, i++)
1226
+ p[i] = subPixels(src[i], predicted[x - x0]);
1188
1227
  }
1189
1228
  }
1190
- modes[by * blocksX + bx] = (0xff000000 | best << 8) >>> 0;
1191
- for (let y = y0; y < y1; y++) {
1192
- predictRow(best, x0, x1, y);
1193
- for (let x = x0, i = y * width + x0; x < x1; x++, i++)
1194
- p[i] = subPixels(src[i], predicted[x - x0]);
1195
- }
1196
- }
1197
- return modes;
1229
+ };
1198
1230
  }
1199
- export function encode(argb, width, height) {
1231
+ export async function encode(argb, width, height, threads = null) {
1200
1232
  if (width < 1 || height < 1 || width > 16384 || height > 16384)
1201
1233
  throw new RangeError('VP8L: dimensions must be 1-16384');
1202
1234
  const colors = new Map();
@@ -1204,14 +1236,14 @@ export function encode(argb, width, height) {
1204
1236
  if (!colors.has(argb[i]))
1205
1237
  colors.set(argb[i], colors.size);
1206
1238
  if (colors.size > 256)
1207
- return encodeWith(argb, width, height, null);
1208
- const indexed = encodeWith(argb, width, height, colors);
1239
+ return encodeWith(argb, width, height, null, threads);
1240
+ const indexed = await encodeWith(argb, width, height, colors, threads);
1209
1241
  if (colors.size <= 16)
1210
1242
  return indexed;
1211
- const predicted = encodeWith(argb, width, height, null);
1243
+ const predicted = await encodeWith(argb, width, height, null, threads);
1212
1244
  return predicted.length < indexed.length ? predicted : indexed;
1213
1245
  }
1214
- function encodeWith(argb, width, height, colors) {
1246
+ async function encodeWith(argb, width, height, colors, threads) {
1215
1247
  const w = new BitWriter();
1216
1248
  let hasAlpha = false;
1217
1249
  for (let i = 0; i < argb.length; i++)
@@ -1235,7 +1267,7 @@ function encodeWith(argb, width, height, colors) {
1235
1267
  const deltas = palette.slice();
1236
1268
  for (let i = palette.length - 1; i > 0; i--)
1237
1269
  deltas[i] = subPixels(palette[i], palette[i - 1]);
1238
- writeImage(w, deltas, palette.length, false);
1270
+ await writeImage(w, deltas, palette.length, false);
1239
1271
  codedWidth = subSize(width, bits);
1240
1272
  pixels = new Uint32Array(codedWidth * height);
1241
1273
  const perPixel = 8 >> bits;
@@ -1246,7 +1278,7 @@ function encodeWith(argb, width, height, colors) {
1246
1278
  }
1247
1279
  }
1248
1280
  else {
1249
- pixels = argb.slice();
1281
+ pixels = threads ? shared(argb) : argb.slice();
1250
1282
  let redBlue = false;
1251
1283
  for (let i = 0; i < pixels.length && !redBlue; i++)
1252
1284
  if (pixels[i] & 0x00ff00ff)
@@ -1263,10 +1295,10 @@ function encodeWith(argb, width, height, colors) {
1263
1295
  w.write(1, 1);
1264
1296
  w.write(0, 2);
1265
1297
  w.write(bits - 2, 3);
1266
- const modes = applyPredictor(pixels, width, height, bits);
1267
- writeImage(w, modes, subSize(width, bits), false);
1298
+ const modes = await applyPredictor(pixels, width, height, bits, threads);
1299
+ await writeImage(w, modes, subSize(width, bits), false);
1268
1300
  }
1269
1301
  w.write(0, 1);
1270
- writeImage(w, pixels, codedWidth, true);
1302
+ await writeImage(w, pixels, codedWidth, true, threads);
1271
1303
  return w.finish();
1272
1304
  }