imagescript 4.0.1 → 4.1.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.
package/README.md CHANGED
@@ -121,7 +121,7 @@ compares ImageScript's speed and file sizes with Jimp, sharp and other libraries
121
121
  ### Credits
122
122
 
123
123
  ImageScript builds on [fflate](https://github.com/101arrowz/fflate), libjpeg, [pdf.js](https://github.com/mozilla/pdf.js),
124
- [font-rs](https://github.com/raphlinus/font-rs), [libwebp](https://chromium.googlesource.com/webm/libwebp),
124
+ [font-rs](https://github.com/raphlinus/font-rs), [mozjpeg](https://github.com/mozilla/mozjpeg), [libwebp](https://chromium.googlesource.com/webm/libwebp),
125
125
  [HarfBuzz](https://github.com/harfbuzz/harfbuzz), [dav1d](https://code.videolan.org/videolan/dav1d),
126
126
  [libavif](https://github.com/AOMediaCodec/libavif), libaom, [jxl-oxide](https://github.com/tirr-c/jxl-oxide) and
127
127
  [libjxl](https://github.com/libjxl/libjxl). The TrueType hinting follows [FreeType](https://freetype.org): portions of
@@ -7,7 +7,8 @@ following projects, under their own licenses. Each derived file says so in its h
7
7
  |---|---|---|
8
8
  | [fflate](https://github.com/101arrowz/fflate) by Arjun Barrett | `src/codecs/zlib.ts` (deflate/inflate) | MIT |
9
9
  | [Fast CRC32 in JavaScript](https://gist.github.com/101arrowz/e58695f7ccfdf74f60ba22018093edea) by Arjun Barrett | `src/codecs/crc.ts` (slice-by-16 CRC-32) | MIT |
10
- | [libjpeg](https://ijg.org/) / [libjpeg-turbo](https://libjpeg-turbo.org/) by the Independent JPEG Group | `src/codecs/jpeg.ts` (IDCT, FDCT, upsampling, color conversion, progressive refinement, optimal Huffman tables) | IJG |
10
+ | [libjpeg](https://ijg.org/) / [libjpeg-turbo](https://libjpeg-turbo.org/) by the Independent JPEG Group | `src/codecs/jpeg.ts` (IDCT, FDCT, upsampling, color conversion, progressive decoding and encoding, optimal Huffman tables) | IJG |
11
+ | [mozjpeg](https://github.com/mozilla/mozjpeg) by Mozilla | `src/codecs/jpeg.ts` (the scans of progressive files, chosen from its scan search) | IJG |
11
12
  | [pdf.js](https://github.com/mozilla/pdf.js) (forked from [jpgjs](https://github.com/notmasteryet/jpgjs) by notmasteryet) | `src/codecs/jpeg.ts` (structure of the scan decoder) | Apache-2.0 |
12
13
  | [font-rs](https://github.com/raphlinus/font-rs) by Raph Levien | `src/render/text.ts` (the `Rasterizer` class, also used for SVGs) | Apache-2.0 |
13
14
  | [RFC 9649](https://www.rfc-editor.org/rfc/rfc9649) (WebP Image Format) | `src/codecs/vp8l.ts` (lossless bitstream, short distance code table), `src/codecs/webp.ts` (container) | BSD-3-Clause (Revised BSD) |
@@ -66,9 +67,10 @@ This software is based in part on the work of the Independent JPEG Group.
66
67
 
67
68
  The JPEG codec translates parts of libjpeg (as shipped by libjpeg-turbo) to TypeScript: the integer inverse DCT
68
69
  (`jidctint.c`), the floating point forward DCT (`jfdctflt.c`), fancy upsampling (`jdsample.c`), the YCbCr to RGB
69
- tables (`jdcolor.c`), the progressive AC refinement (`jdphuff.c`) and the optimal Huffman table generation
70
- (`jcphuff.c`/`jchuff.c`). The translations were rewritten for TypeScript's numbers and typed arrays; the rest of the
71
- codec is ImageScript's own. libjpeg's README with its copyright and terms is included unaltered as
70
+ tables (`jdcolor.c`), the progressive AC refinement (`jdphuff.c`), the progressive encoder (`jcphuff.c`) and the
71
+ optimal Huffman table generation (`jchuff.c`). The scans of progressive files are a fixed choice from
72
+ the ones mozjpeg's `jpeg_search_progression` tries (`jcparam.c`). The translations were rewritten for TypeScript's numbers and typed arrays; the
73
+ rest of the codec is ImageScript's own. libjpeg's README with its copyright and terms is included unaltered as
72
74
  [licenses/README.ijg](licenses/README.ijg).
73
75
 
74
76
  ## pdf.js, font-rs
@@ -1,3 +1,4 @@
1
+ import { availableThreads } from "./util/threads.js";
1
2
  import * as gifCodec from "./codecs/gif.js";
2
3
  import { paletteOptions } from "./codecs/quantize.js";
3
4
  import * as png from "./codecs/png.js";
@@ -7,7 +8,7 @@ import { Frame } from "./frame.js";
7
8
  import { Optimizer, Compositor, coverCanvas, fillUnchanged } from "./util/optimize.js";
8
9
  import { compressAsync, decompressAsync } from "./codecs/zlib.js";
9
10
  import { resolveMetadata, pngText, exifData, gifComments } from "./metadata.js";
10
- import { instance, checkOptions, finite, nonNegative, canvasSize, compressionLevel, loopCount, toPlays, fitLoops, fitDuration, maxDuration, boolean } from "./util/options.js";
11
+ import { instance, checkOptions, finite, nonNegative, canvasSize, compressionLevel, checkThreads, loopCount, toPlays, fitLoops, fitDuration, maxDuration, boolean } from "./util/options.js";
11
12
  import { checkFormatSize } from "./util/limits.js";
12
13
  function clipToCanvas(frame, width, height) {
13
14
  const { x, y, width: w, height: h } = frame;
@@ -143,8 +144,11 @@ export class AnimationEncoder {
143
144
  }
144
145
  }, optimize);
145
146
  }
146
- static __apng__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, compression: compressionOption = 4 }) {
147
+ static __apng__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, compression: compressionOption = 4, threads = Math.max(1, Math.min(availableThreads(), 8)), colors, dither = 'floyd-steinberg', ditherStrength = 0.85 }) {
147
148
  const compression = compressionLevel(compressionOption);
149
+ checkThreads(threads);
150
+ const palette = paletteOptions(colors, dither, ditherStrength);
151
+ const lossy = palette.colors === undefined ? undefined : { colors: palette.colors, dither: palette.dither, strength: palette.strength };
148
152
  boolean(optimize, 'optimize');
149
153
  const loops = fitLoops(loopCount(count), 'APNG');
150
154
  [width, height] = canvas(width, height, 'APNG');
@@ -154,7 +158,7 @@ export class AnimationEncoder {
154
158
  let blended = false;
155
159
  return new AnimationEncoder(width, height, {
156
160
  name: 'APNG',
157
- optimize: { replace: true, even: false, alpha: () => cost.cost(), maxDuration: maxDuration('APNG') },
161
+ optimize: { replace: true, even: false, alpha: () => lossy ? 1 : cost.cost(), maxDuration: maxDuration('APNG') },
158
162
  async frame(f, optimized) {
159
163
  let frame;
160
164
  if (optimized) {
@@ -171,7 +175,7 @@ export class AnimationEncoder {
171
175
  stored.push({ frame: rest, packed: await compressAsync(pixels, 1) });
172
176
  },
173
177
  async file(optimizer) {
174
- const fill = !!optimizer && optimizer.opaque && blended && optimizer.denseTotal < optimizer.chosenTotal * cost.cost();
178
+ const fill = !!optimizer && optimizer.opaque && blended && optimizer.denseTotal < optimizer.chosenTotal * (lossy ? 1 : cost.cost());
175
179
  const frames = async function* () {
176
180
  const shown32 = new Int32Array(width * height);
177
181
  for (const [i, { frame, packed }] of stored.entries()) {
@@ -183,12 +187,14 @@ export class AnimationEncoder {
183
187
  yield f;
184
188
  }
185
189
  };
186
- const scanner = new png.FormatScanner();
187
- for await (const f of frames())
188
- scanner.add(f.pixels);
189
- const format = scanner.format(), encoded = [];
190
+ const each = async function* () {
191
+ for await (const f of frames())
192
+ yield f.pixels;
193
+ };
194
+ const { format, plan } = await png.chooseFormat(each, lossy);
195
+ const encoded = [];
190
196
  for await (const { pixels, ...f } of frames())
191
- encoded.push({ ...f, data: await png.frameData(pixels, f.width, f.height, format, compression) });
197
+ encoded.push({ ...f, data: await png.frameData(plan ? png.quantizePixels(pixels, f.width, f.height, plan) : pixels, f.width, f.height, format, compression, threads) });
192
198
  return png.animationFile(encoded, width, height, toPlays(loops), format, text);
193
199
  }
194
200
  }, optimize);
@@ -202,10 +202,11 @@ export declare class Animation {
202
202
  */
203
203
  encodeGIF(options?: GIFAnimationEncodeOptions): Promise<Uint8Array<ArrayBuffer>>;
204
204
  /**
205
- * Encodes the animation as APNG (animated PNG, lossless and with full alpha). Viewers without APNG support show
205
+ * Encodes the animation as APNG (animated PNG, lossless and with full alpha, unless `colors` makes it a palette
206
+ * shared by all frames). Viewers without APNG support show
206
207
  * the first frame. Each frame is stored as the area that changed since the frame before, identical frames are
207
- * merged (unless the `optimize` option is false): the file shows exactly the same animation, but doesn't
208
- * necessarily decode to the same frames
208
+ * merged (unless the `optimize` option is false): the file shows the same animation, but doesn't necessarily decode
209
+ * to the same frames (with `colors`, the same up to the palette)
209
210
  * @param options See {@link APNGEncodeOptions}; the loop count is the animation's {@link loopCount} (the streaming
210
211
  * {@link apngEncoder} takes it as an option)
211
212
  * @throws `RangeError` if the animation has no frames, the loop count or a frame's duration is more than APNG stores
package/dist/animation.js CHANGED
@@ -334,14 +334,16 @@ export class Animation {
334
334
  }
335
335
  async encodeAPNG(options = {}) {
336
336
  checkOptions(options, 'encodeAPNG({ compression: 9 })');
337
- const { compression = 4, metadata = {}, optimize = true } = options;
337
+ const { compression = 4, threads = Math.max(1, Math.min(availableThreads(), 8)), colors, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {}, optimize = true } = options;
338
+ checkThreads(threads);
339
+ const palette = paletteOptions(colors, dither, ditherStrength);
338
340
  boolean(optimize, 'optimize');
339
341
  const loops = fitLoops(this.loopCount, 'APNG');
340
342
  this.__validate__('APNG');
341
343
  const frames = optimize
342
- ? this.__optimized__({ replace: true, even: false, alpha: frames => png.alphaCost(frames.map(f => f.pixels)), maxDuration: maxDuration('APNG') }).map(f => ({ ...f, dispose: f.dispose ? 1 : 0 }))
344
+ ? this.__optimized__({ replace: true, even: false, alpha: frames => palette.colors === undefined ? png.alphaCost(frames.map(f => f.pixels)) : 1, maxDuration: maxDuration('APNG') }).map(f => ({ ...f, dispose: f.dispose ? 1 : 0 }))
343
345
  : this.__apngFrames__().map(({ blend: _, ...f }) => f);
344
- return png.encodeAnimation(frames, this.width, this.height, toPlays(loops), compressionLevel(compression), pngText(resolveMetadata(metadata)));
346
+ return png.encodeAnimation(frames, this.width, this.height, toPlays(loops), compressionLevel(compression), pngText(resolveMetadata(metadata)), threads, palette.colors === undefined ? undefined : { colors: palette.colors, dither: palette.dither, strength: palette.strength });
345
347
  }
346
348
  async encodeWebP(options = {}) {
347
349
  checkOptions(options, 'animation.encodeWebP({ quality: 80 })');
@@ -1,7 +1,8 @@
1
1
  /*!
2
2
  * JPEG codec. This software is based in part on the work of the Independent JPEG Group: the IDCT, FDCT, upsampling,
3
- * downsampling, color conversion, quantization, progressive refinement and optimal Huffman tables are translated from
4
- * libjpeg/libjpeg-turbo (IJG license, see licenses/README.ijg). The scan decoder follows the structure of pdf.js' jpg.js
3
+ * downsampling, color conversion, quantization, progressive refinement and encoding and optimal Huffman tables are
4
+ * translated from libjpeg/libjpeg-turbo, and the progressive scans are chosen from mozjpeg's scan search (IJG license,
5
+ * see licenses/README.ijg). The scan decoder follows the structure of pdf.js' jpg.js
5
6
  * (Copyright 2014 Mozilla Foundation, Apache License 2.0). See THIRD_PARTY_NOTICES.md
6
7
  */
7
8
  import { ByteWriter } from "../util/bytes.js";
@@ -1369,6 +1370,7 @@ const CHROMA_QUANTIZATION = [
1369
1370
  99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
1370
1371
  99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99
1371
1372
  ];
1373
+ const FLAT_QUANTIZATION = new Array(64).fill(16);
1372
1374
  const fix16 = (x) => Math.round(x * 65536);
1373
1375
  const Y_R = new Int32Array(256), Y_G = new Int32Array(256), Y_B = new Int32Array(256);
1374
1376
  const CB_R = new Int32Array(256), CB_G = new Int32Array(256), CB_B = new Int32Array(256);
@@ -1404,14 +1406,14 @@ function reciprocals(table) {
1404
1406
  }
1405
1407
  return r;
1406
1408
  }
1407
- export function encode(pixels, width, height, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling, rows } = {}) {
1409
+ export function encode(pixels, width, height, quality = 90, { exif, comment, segments, gray = false, fullChroma = false, subsampling, quantization, progressive = false, rows, maxTokens = MAX_TOKENS } = {}) {
1408
1410
  if (!width || !height)
1409
1411
  throw new RangeError('JPEG: invalid dimensions');
1410
1412
  checkFormatSize('JPEG', width, height, 0xffff);
1411
1413
  quality = Math.min(100, Math.max(1, Math.round(quality)));
1412
1414
  const scale = quality < 50 ? Math.floor(5000 / quality) : 200 - quality * 2;
1413
1415
  const scaleTable = (base) => base.map(v => Math.min(255, Math.max(1, Math.floor((v * scale + 50) / 100))));
1414
- const tables = [scaleTable(LUMA_QUANTIZATION), scaleTable(CHROMA_QUANTIZATION)];
1416
+ const tables = quantization === 'flat' ? [scaleTable(FLAT_QUANTIZATION), scaleTable(FLAT_QUANTIZATION)] : [scaleTable(LUMA_QUANTIZATION), scaleTable(CHROMA_QUANTIZATION)];
1415
1417
  const divisors = tables.map(reciprocals);
1416
1418
  const subsample = !gray && !fullChroma && (subsampling ? subsampling === '4:2:0' : quality <= 90);
1417
1419
  const hmax = subsample ? 2 : 1;
@@ -1474,7 +1476,7 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
1474
1476
  const blocksPerMcu = gray ? 1 : hmax * hmax + 2;
1475
1477
  const count = mcusPerLine * mcusPerColumn * blocksPerMcu;
1476
1478
  const coefficients = new Int16Array(count * 64);
1477
- const owners = new Uint8Array(count), ends = new Uint8Array(count);
1479
+ const owners = new Uint8Array(count), ends = new Uint8Array(count), masks = new Uint32Array(count * 2);
1478
1480
  const block = new Int32Array(64);
1479
1481
  let n = 0;
1480
1482
  for (let my = 0; my < mcusPerColumn; my++)
@@ -1496,22 +1498,30 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
1496
1498
  continue;
1497
1499
  }
1498
1500
  fdct(plane, by * 8 * stride + bx * 8, stride, block);
1499
- let end = 0;
1501
+ let end = 0, low = 0, high = 0;
1500
1502
  for (let k = 0; k < 64; k++) {
1501
1503
  const i = ZIGZAG[k], t = block[i], sign = t >> 31;
1502
1504
  const value = (Math.imul((t ^ sign) - sign + reciprocal[64 + i], reciprocal[i]) >>> reciprocal[128 + i] ^ sign) - sign;
1503
1505
  coefficients[o + k] = value;
1504
- if (value)
1506
+ if (value) {
1505
1507
  end = k;
1508
+ if (k < 32)
1509
+ low |= 1 << k;
1510
+ else
1511
+ high |= 1 << k - 32;
1512
+ }
1506
1513
  }
1507
1514
  ends[n] = end;
1515
+ masks[n * 2] = low;
1516
+ masks[n * 2 + 1] = high;
1508
1517
  }
1509
1518
  }
1510
1519
  }
1511
- const blocks = { coefficients, owners, ends, count };
1520
+ const blocks = { coefficients, owners, ends, masks, count };
1512
1521
  const frequencies = [new Int32Array(257), new Int32Array(257), new Int32Array(257), new Int32Array(257)];
1513
- countSymbols(blocks, frequencies);
1514
- const huffman = frequencies.slice(0, gray ? 2 : 4).map(buildOptimalTable);
1522
+ if (!progressive)
1523
+ countSymbols(blocks, frequencies);
1524
+ const huffman = progressive ? [] : frequencies.slice(0, gray ? 2 : 4).map(buildOptimalTable);
1515
1525
  const writer = new BitWriter(width * height);
1516
1526
  writer.bytes(0xff, 0xd8);
1517
1527
  writer.bytes(0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00);
@@ -1535,12 +1545,19 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
1535
1545
  for (let k = 0; k < 64; k++)
1536
1546
  writer.bytes(tables[t][ZIGZAG[k]]);
1537
1547
  }
1548
+ const sof = progressive ? 0xc2 : 0xc0;
1538
1549
  if (gray)
1539
- writer.bytes(0xff, 0xc0, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 1, 0x11, 0);
1550
+ writer.bytes(0xff, sof, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 1, 0x11, 0);
1540
1551
  else {
1541
- writer.bytes(0xff, 0xc0, 0x00, 0x11, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x03);
1552
+ writer.bytes(0xff, sof, 0x00, 0x11, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x03);
1542
1553
  writer.bytes(1, hmax << 4 | hmax, 0, 2, 0x11, 1, 3, 0x11, 1);
1543
1554
  }
1555
+ if (progressive) {
1556
+ const layout = components.slice(0, componentCount).map((component, c) => ({ ...component, offset: c === 0 ? 0 : hmax * hmax + c - 1 }));
1557
+ writeProgressive(writer, progressiveScans(componentCount), blocks, layout, mcusPerLine, blocksPerMcu, maxTokens);
1558
+ writer.bytes(0xff, 0xd9);
1559
+ return writer.finish();
1560
+ }
1544
1561
  for (const [index, id] of [[0, 0x00], [1, 0x10], [2, 0x01], [3, 0x11]].slice(0, gray ? 2 : 4)) {
1545
1562
  const { bits, values } = huffman[index];
1546
1563
  const length = 19 + values.length;
@@ -1559,6 +1576,323 @@ export function encode(pixels, width, height, quality = 90, { exif, comment, seg
1559
1576
  writer.bytes(0xff, 0xd9);
1560
1577
  return writer.finish();
1561
1578
  }
1579
+ function progressiveScans(componentCount) {
1580
+ const dc = { comps: Array.from({ length: componentCount }, (_, c) => c), ss: 0, se: 0, ah: 0, al: 0 };
1581
+ const ac = (comp, ss, se, ah, al) => ({ comps: [comp], ss, se, ah, al });
1582
+ const luma = [ac(0, 1, 2, 0, 1), ac(0, 3, 63, 0, 1), ac(0, 1, 63, 1, 0)];
1583
+ if (componentCount === 1)
1584
+ return [dc, ...luma];
1585
+ return [dc, ...luma, ac(1, 1, 8, 0, 0), ac(1, 9, 63, 0, 0), ac(2, 1, 8, 0, 0), ac(2, 9, 63, 0, 0)];
1586
+ }
1587
+ const MAX_TOKENS = 1 << 24;
1588
+ const MAX_CORR_BITS = 1000;
1589
+ class ScanCoder {
1590
+ eobrun = 0;
1591
+ pending = new Uint8Array(MAX_CORR_BITS);
1592
+ waiting = 0;
1593
+ emitEobrun(table) {
1594
+ if (this.eobrun === 0)
1595
+ return;
1596
+ const nbits = 31 - Math.clz32(this.eobrun);
1597
+ this.symbol(table, nbits << 4);
1598
+ if (nbits)
1599
+ this.bits(this.eobrun, nbits);
1600
+ this.eobrun = 0;
1601
+ this.buffered(0, this.waiting);
1602
+ this.waiting = 0;
1603
+ }
1604
+ dcFirst(coefficients, owners, count, last, al) {
1605
+ for (let n = 0; n < count; n++) {
1606
+ const component = owners[n], table = component === 0 ? 0 : 1;
1607
+ const value = coefficients[n * 64] >> al, diff = value - last[component];
1608
+ last[component] = value;
1609
+ const nbits = 32 - Math.clz32(Math.abs(diff));
1610
+ this.symbol(table, nbits);
1611
+ if (nbits)
1612
+ this.bits(diff < 0 ? diff - 1 : diff, nbits);
1613
+ }
1614
+ }
1615
+ skip(table) {
1616
+ this.eobrun++;
1617
+ if (this.eobrun === 0x7fff)
1618
+ this.emitEobrun(table);
1619
+ }
1620
+ acFirst(coefficients, o, low, high, table, ss, se, al) {
1621
+ let previous = ss - 1;
1622
+ for (let half = 0; half < 2; half++) {
1623
+ let bits = half === 0 ? low : high;
1624
+ while (bits !== 0) {
1625
+ const lowest = bits & -bits;
1626
+ bits ^= lowest;
1627
+ const k = (half << 5) + 31 - Math.clz32(lowest);
1628
+ let value = coefficients[o + k], coded;
1629
+ if (value < 0) {
1630
+ value = -value >> al;
1631
+ coded = ~value;
1632
+ }
1633
+ else {
1634
+ value >>= al;
1635
+ coded = value;
1636
+ }
1637
+ if (value === 0)
1638
+ continue;
1639
+ this.emitEobrun(table);
1640
+ let run = k - previous - 1;
1641
+ for (; run > 15; run -= 16)
1642
+ this.symbol(table, 0xf0);
1643
+ const nbits = 32 - Math.clz32(value);
1644
+ this.symbol(table, run << 4 | nbits);
1645
+ this.bits(coded, nbits);
1646
+ previous = k;
1647
+ }
1648
+ }
1649
+ if (previous < se) {
1650
+ this.eobrun++;
1651
+ if (this.eobrun === 0x7fff)
1652
+ this.emitEobrun(table);
1653
+ }
1654
+ }
1655
+ acRefine(coefficients, o, end, low, high, table, ss, se, al) {
1656
+ const stop = Math.min(se, end);
1657
+ let eob = 0;
1658
+ for (let k = stop; k >= ss; k--) {
1659
+ const value = coefficients[o + k];
1660
+ if ((value < 0 ? -value : value) >> al === 1) {
1661
+ eob = k;
1662
+ break;
1663
+ }
1664
+ }
1665
+ let last = ss - 1, run = 0, start = this.waiting, count = 0;
1666
+ for (let half = 0; half < 2; half++) {
1667
+ let bits = half === 0 ? low : high;
1668
+ while (bits !== 0) {
1669
+ const lowest = bits & -bits;
1670
+ bits ^= lowest;
1671
+ const k = (half << 5) + 31 - Math.clz32(lowest);
1672
+ run += k - last - 1;
1673
+ last = k;
1674
+ const coefficient = coefficients[o + k], value = (coefficient < 0 ? -coefficient : coefficient) >> al;
1675
+ if (value === 0) {
1676
+ run++;
1677
+ continue;
1678
+ }
1679
+ for (; run > 15 && k <= eob; run -= 16) {
1680
+ this.emitEobrun(table);
1681
+ this.symbol(table, 0xf0);
1682
+ this.buffered(start, count);
1683
+ start = 0;
1684
+ count = 0;
1685
+ }
1686
+ if (value > 1) {
1687
+ this.pending[start + count++] = value & 1;
1688
+ continue;
1689
+ }
1690
+ this.emitEobrun(table);
1691
+ this.symbol(table, run << 4 | 1);
1692
+ this.bits(coefficient < 0 ? 0 : 1, 1);
1693
+ this.buffered(start, count);
1694
+ start = 0;
1695
+ count = 0;
1696
+ run = 0;
1697
+ }
1698
+ }
1699
+ run += se - last;
1700
+ if (run > 0 || count > 0) {
1701
+ this.eobrun++;
1702
+ this.waiting += count;
1703
+ if (this.eobrun === 0x7fff || this.waiting > MAX_CORR_BITS - 63)
1704
+ this.emitEobrun(table);
1705
+ }
1706
+ }
1707
+ finish(table) {
1708
+ this.emitEobrun(table);
1709
+ }
1710
+ }
1711
+ class CountingCoder extends ScanCoder {
1712
+ counts = [new Int32Array(257), new Int32Array(257)];
1713
+ tokens;
1714
+ length = 0;
1715
+ overflow;
1716
+ max;
1717
+ constructor(tokens, overflow, max) {
1718
+ super();
1719
+ this.tokens = tokens;
1720
+ this.overflow = overflow;
1721
+ this.max = max;
1722
+ }
1723
+ push(token) {
1724
+ if (this.overflow)
1725
+ return;
1726
+ if (this.length === this.tokens.length) {
1727
+ if (this.length >= this.max) {
1728
+ this.overflow = true;
1729
+ return;
1730
+ }
1731
+ const grown = new Uint32Array(Math.min(this.length * 2, this.max));
1732
+ grown.set(this.tokens);
1733
+ this.tokens = grown;
1734
+ }
1735
+ this.tokens[this.length++] = token;
1736
+ }
1737
+ symbol(table, symbol) {
1738
+ this.counts[table][symbol]++;
1739
+ this.push(table << 8 | symbol);
1740
+ }
1741
+ bits(value, size) {
1742
+ this.push(0x80000000 | size << 16 | value & (1 << size) - 1);
1743
+ }
1744
+ buffered(start, count) {
1745
+ const pending = this.pending;
1746
+ while (count > 0) {
1747
+ const n = Math.min(count, 16);
1748
+ let value = 0;
1749
+ for (let i = 0; i < n; i++)
1750
+ value = value << 1 | pending[start + i];
1751
+ this.push(0x80000000 | n << 16 | value);
1752
+ start += n;
1753
+ count -= n;
1754
+ }
1755
+ }
1756
+ }
1757
+ class WritingCoder extends ScanCoder {
1758
+ writer;
1759
+ tables;
1760
+ acc;
1761
+ pendingBits;
1762
+ out;
1763
+ length;
1764
+ constructor(writer, tables) {
1765
+ super();
1766
+ this.writer = writer;
1767
+ this.tables = tables;
1768
+ this.acc = writer.bits;
1769
+ this.pendingBits = writer.count;
1770
+ this.out = writer.buffer;
1771
+ this.length = writer.length;
1772
+ }
1773
+ put(value, size) {
1774
+ const acc = this.acc << size | value & (1 << size) - 1;
1775
+ let n = this.pendingBits + size;
1776
+ while (n >= 8) {
1777
+ n -= 8;
1778
+ const byte = acc >>> n & 0xff;
1779
+ if (this.length + 2 > this.out.length)
1780
+ this.grow();
1781
+ this.out[this.length++] = byte;
1782
+ if (byte === 0xff)
1783
+ this.out[this.length++] = 0x00;
1784
+ }
1785
+ this.acc = acc & (1 << n) - 1;
1786
+ this.pendingBits = n;
1787
+ }
1788
+ grow() {
1789
+ this.writer.length = this.length;
1790
+ this.writer.reserve(2);
1791
+ this.out = this.writer.buffer;
1792
+ }
1793
+ symbol(table, symbol) {
1794
+ const { codes, sizes } = this.tables[table];
1795
+ this.put(codes[symbol], sizes[symbol]);
1796
+ }
1797
+ bits(value, size) {
1798
+ this.put(value, size);
1799
+ }
1800
+ buffered(start, count) {
1801
+ const pending = this.pending;
1802
+ while (count > 0) {
1803
+ const n = Math.min(count, 16);
1804
+ let value = 0;
1805
+ for (let i = 0; i < n; i++)
1806
+ value = value << 1 | pending[start + i];
1807
+ this.put(value, n);
1808
+ start += n;
1809
+ count -= n;
1810
+ }
1811
+ }
1812
+ replay(tokens, length) {
1813
+ const tables = this.tables;
1814
+ for (let i = 0; i < length; i++) {
1815
+ const token = tokens[i];
1816
+ if (token >= 0x80000000)
1817
+ this.put(token & 0xffff, token >>> 16 & 0x1f);
1818
+ else {
1819
+ const { codes, sizes } = tables[token >> 8];
1820
+ this.put(codes[token & 0xff], sizes[token & 0xff]);
1821
+ }
1822
+ }
1823
+ }
1824
+ done() {
1825
+ this.writer.bits = this.acc;
1826
+ this.writer.count = this.pendingBits;
1827
+ this.writer.length = this.length;
1828
+ }
1829
+ }
1830
+ function writeProgressive(writer, scans, { coefficients, owners, ends, masks, count }, layout, mcusPerLine, blocksPerMcu, maxTokens) {
1831
+ const slot = (comp) => comp === 0 ? 0 : 1;
1832
+ const run = (coder, { comps, ss, se, ah, al }) => {
1833
+ if (ss === 0) {
1834
+ coder.dcFirst(coefficients, owners, count, [0, 0, 0], al);
1835
+ return;
1836
+ }
1837
+ const comp = comps[0], { h, v, blocksX, blocksY, offset } = layout[comp];
1838
+ const table = slot(comp);
1839
+ const lowBand = ss > 31 ? 0 : -1 << ss & (se > 30 ? -1 : (1 << se + 1) - 1);
1840
+ const highBand = se < 32 ? 0 : (ss > 32 ? -1 << ss - 32 : -1) & (se > 62 ? -1 : (1 << se - 31) - 1);
1841
+ const columns = new Int32Array(blocksX);
1842
+ for (let bx = 0; bx < blocksX; bx++)
1843
+ columns[bx] = (bx / h | 0) * blocksPerMcu + bx % h;
1844
+ for (let by = 0; by < blocksY; by++) {
1845
+ const row = (by / v | 0) * mcusPerLine * blocksPerMcu + offset + by % v * h;
1846
+ for (let bx = 0; bx < blocksX; bx++) {
1847
+ const n = row + columns[bx];
1848
+ if (ends[n] < ss)
1849
+ coder.skip(table);
1850
+ else if (ah === 0)
1851
+ coder.acFirst(coefficients, n * 64, masks[n * 2] & lowBand, masks[n * 2 + 1] & highBand, table, ss, se, al);
1852
+ else
1853
+ coder.acRefine(coefficients, n * 64, ends[n], masks[n * 2] & lowBand, masks[n * 2 + 1] & highBand, table, ss, se, al);
1854
+ }
1855
+ }
1856
+ coder.finish(table);
1857
+ };
1858
+ let tokens = new Uint32Array(Math.min(1 << 16, maxTokens));
1859
+ let tooLong = false;
1860
+ for (const scan of scans) {
1861
+ const { comps, ss, se, ah, al } = scan;
1862
+ const dcScan = ss === 0;
1863
+ const counter = new CountingCoder(tokens, tooLong, maxTokens);
1864
+ run(counter, scan);
1865
+ tokens = counter.tokens;
1866
+ tooLong = counter.overflow;
1867
+ const counts = counter.counts;
1868
+ const used = [];
1869
+ for (const comp of comps)
1870
+ if (!used.includes(slot(comp)))
1871
+ used.push(slot(comp));
1872
+ const tables = [];
1873
+ for (const table of used)
1874
+ tables[table] = buildOptimalTable(counts[table]);
1875
+ for (const table of used) {
1876
+ const { bits, values } = tables[table];
1877
+ writer.bytes(0xff, 0xc4, 19 + values.length >> 8, 19 + values.length & 0xff, table | (dcScan ? 0x00 : 0x10));
1878
+ for (let i = 1; i <= 16; i++)
1879
+ writer.bytes(bits[i]);
1880
+ for (const value of values)
1881
+ writer.bytes(value);
1882
+ }
1883
+ writer.bytes(0xff, 0xda, 0x00, 2 * comps.length + 6, comps.length);
1884
+ for (const comp of comps)
1885
+ writer.bytes(comp + 1, dcScan ? slot(comp) << 4 : slot(comp));
1886
+ writer.bytes(ss, se, ah << 4 | al);
1887
+ const coder = new WritingCoder(writer, tables);
1888
+ if (counter.overflow)
1889
+ run(coder, scan);
1890
+ else
1891
+ coder.replay(tokens, counter.length);
1892
+ coder.done();
1893
+ writer.flush();
1894
+ }
1895
+ }
1562
1896
  function countSymbols({ coefficients, owners, ends, count }, frequencies) {
1563
1897
  const pred = [0, 0, 0];
1564
1898
  for (let n = 0; n < count; n++) {
@@ -4,7 +4,8 @@ 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 { compressParallel, decompressAsync, decompress } from "./zlib.js";
7
+ import { RGBAPaletteBuilder, applyRGBAPalette } from "./quantize-rgba.js";
8
+ import { compressParallel, decompressAsync, decompress, limited } from "./zlib.js";
8
9
  const HEAD = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
9
10
  const IHDR = 0x49484452;
10
11
  const PLTE = 0x504c5445;
@@ -24,7 +25,7 @@ const COLOR_TYPE_CHANNELS = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
24
25
  const CHANNELS_TO_COLOR_TYPE = { 1: 0, 2: 4, 3: 2, 4: 6 };
25
26
  const VALID_DEPTHS = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
26
27
  const ADAM7 = [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]];
27
- export async function encode(data, { text, width, height, channels, depth = 8, level = 0, palette, transparency, filter: filterRows = false }) {
28
+ export async function encode(data, { text, width, height, channels, depth = 8, level = 0, threads = Infinity, palette, transparency, filter: filterRows = false }) {
28
29
  const header = new Uint8Array(13);
29
30
  const view = new DataView(header.buffer);
30
31
  view.setUint32(0, width);
@@ -37,7 +38,7 @@ export async function encode(data, { text, width, height, channels, depth = 8, l
37
38
  if (transparency)
38
39
  chunks.push(chunk(tRNS, transparency));
39
40
  chunks.push(...textChunks(text));
40
- chunks.push(chunk(IDAT, await compressRows(data, width, height, channels, depth, level, filterRows)));
41
+ chunks.push(chunk(IDAT, await compressRows(data, width, height, channels, depth, level, filterRows, threads)));
41
42
  chunks.push(chunk(IEND, new Uint8Array(0)));
42
43
  return concat([HEAD, ...chunks]);
43
44
  }
@@ -83,12 +84,12 @@ function prefix(data, rowBytes, y0, y1) {
83
84
  return out;
84
85
  }
85
86
  const SAMPLE_ROWS = 32, SAMPLE_STEP = 512;
86
- async function compressRows(data, width, height, channels, depth, level, filterRows) {
87
+ async function compressRows(data, width, height, channels, depth, level, filterRows, threads) {
87
88
  const rowBytes = Math.ceil(width * channels * depth / 8), bpp = Math.max(1, channels * depth / 8);
88
89
  if (!filterRows)
89
- return compressParallel(prefix(data, rowBytes, 0, height), level);
90
+ return compressParallel(prefix(data, rowBytes, 0, height), level, threads);
90
91
  if (height <= SAMPLE_ROWS) {
91
- const [unfiltered, filtered] = await Promise.all([compressParallel(prefix(data, rowBytes, 0, height), level), compressParallel(filter(data, rowBytes, 0, height, bpp), level)]);
92
+ const [unfiltered, filtered] = await limited(2, threads, i => compressParallel(i ? filter(data, rowBytes, 0, height, bpp) : prefix(data, rowBytes, 0, height), level, Math.max(1, Math.floor(threads / 2))));
92
93
  return unfiltered.length < filtered.length ? unfiltered : filtered;
93
94
  }
94
95
  const unfilteredSamples = [], filteredSamples = [];
@@ -97,8 +98,8 @@ async function compressRows(data, width, height, channels, depth, level, filterR
97
98
  unfilteredSamples.push(prefix(data, rowBytes, y, end));
98
99
  filteredSamples.push(filter(data, rowBytes, y, end, bpp));
99
100
  }
100
- const [unfiltered, filtered] = await Promise.all([compressParallel(concat(unfilteredSamples), level), compressParallel(concat(filteredSamples), level)]);
101
- return compressParallel(unfiltered.length < filtered.length ? prefix(data, rowBytes, 0, height) : filter(data, rowBytes, 0, height, bpp), level);
101
+ const [unfiltered, filtered] = await limited(2, threads, i => compressParallel(concat(i ? filteredSamples : unfilteredSamples), level, Math.max(1, Math.floor(threads / 2))));
102
+ return compressParallel(unfiltered.length < filtered.length ? prefix(data, rowBytes, 0, height) : filter(data, rowBytes, 0, height, bpp), level, threads);
102
103
  }
103
104
  function chunk(type, body) {
104
105
  const out = new Uint8Array(body.length + 12);
@@ -151,12 +152,6 @@ export class AlphaCost {
151
152
  return transparent / opaque;
152
153
  }
153
154
  }
154
- function pixelFormat(images) {
155
- const scanner = new FormatScanner();
156
- for (const rgba of images)
157
- scanner.add(rgba);
158
- return scanner.format();
159
- }
160
155
  export class FormatScanner {
161
156
  opaque = true;
162
157
  gray = true;
@@ -264,24 +259,50 @@ function formatOf(colors, opaque, gray) {
264
259
  }
265
260
  };
266
261
  }
262
+ export { applyRGBAPalette };
263
+ export async function chooseFormat(each, lossy) {
264
+ const scanner = new FormatScanner(), builder = lossy ? new RGBAPaletteBuilder() : null;
265
+ for await (const pixels of each()) {
266
+ scanner.add(pixels);
267
+ builder?.count(pixels);
268
+ }
269
+ const scanned = scanner.format();
270
+ if (!lossy || (scanned.palette && scanned.palette.length / 3 <= lossy.colors))
271
+ return { format: scanned, plan: null };
272
+ for await (const pixels of each())
273
+ builder.sum(pixels);
274
+ const palette = builder.palette(lossy.colors);
275
+ const entries = new Map();
276
+ for (let i = 0; i < palette.length; i += 4)
277
+ entries.set(new Uint32Array(palette.slice(i, i + 4).buffer)[0], i / 4);
278
+ const format = formatOf(entries, false, false);
279
+ return { format, plan: { palette, format, lossy } };
280
+ }
281
+ export function quantizePixels(pixels, width, height, plan) {
282
+ const copy = pixels.slice(0, width * height * 4);
283
+ applyRGBAPalette(copy, width, height, plan.palette, plan.lossy.dither, plan.lossy.strength);
284
+ return copy;
285
+ }
267
286
  const aligned = (rgba) => rgba.byteOffset % 4 ? rgba.slice() : rgba;
268
- export async function encodeRGBA(rgba, width, height, level, text) {
287
+ export async function encodeRGBA(rgba, width, height, level, text, threads = Infinity, lossy) {
269
288
  rgba = aligned(rgba.subarray(0, width * height * 4));
270
- const format = pixelFormat([rgba]);
289
+ const { format, plan } = await chooseFormat(async function* () { yield rgba; }, lossy);
290
+ if (plan)
291
+ rgba = quantizePixels(rgba, width, height, plan);
271
292
  const { channels, depth, palette, transparency } = format;
272
- return encode(format.convert(rgba, width, height), { width, height, level, text, channels, depth, palette, transparency, filter: level > 0 && !palette });
293
+ return encode(format.convert(rgba, width, height), { width, height, level, threads, text, channels, depth, palette, transparency, filter: level > 0 && !palette });
273
294
  }
274
- export async function encodeAnimation(frames, width, height, plays, level, text) {
295
+ export async function encodeAnimation(frames, width, height, plays, level, text, threads = Infinity, lossy) {
275
296
  if (!frames.length)
276
297
  throw new RangeError('PNG: an animation needs at least one frame, not 0');
277
298
  frames = [coverCanvas(frames[0], width, height), ...frames.slice(1)];
278
299
  for (const f of frames)
279
300
  checkFrame(f, width, height);
280
301
  const images = frames.map(f => aligned(f.pixels.subarray(0, f.width * f.height * 4)));
281
- const format = pixelFormat(images);
302
+ const { format, plan } = await chooseFormat(async function* () { yield* images; }, lossy);
282
303
  const encoded = [];
283
304
  for (let i = 0; i < frames.length; i++)
284
- encoded.push({ ...frames[i], data: await frameData(images[i], frames[i].width, frames[i].height, format, level) });
305
+ encoded.push({ ...frames[i], data: await frameData(plan ? quantizePixels(images[i], frames[i].width, frames[i].height, plan) : images[i], frames[i].width, frames[i].height, format, level, threads) });
285
306
  return animationFile(encoded, width, height, plays, format, text);
286
307
  }
287
308
  export const RGBA = { channels: 4, depth: 8, convert: rgba => rgba };
@@ -299,8 +320,8 @@ export function checkFrame(f, width, height) {
299
320
  if (f.x < 0 || f.y < 0 || f.x + f.width > width || f.y + f.height > height || !f.width || !f.height)
300
321
  throw new RangeError('PNG: APNG frames have to lie within the canvas');
301
322
  }
302
- export function frameData(rgba, width, height, format, level) {
303
- return compressRows(format.convert(rgba, width, height), width, height, format.channels, format.depth, level, level > 0 && !format.palette);
323
+ export function frameData(rgba, width, height, format, level, threads = Infinity) {
324
+ return compressRows(format.convert(rgba, width, height), width, height, format.channels, format.depth, level, level > 0 && !format.palette, threads);
304
325
  }
305
326
  export function animationFile(frames, width, height, plays, format, text) {
306
327
  const { channels, depth, palette, transparency } = format;
@@ -0,0 +1,315 @@
1
+ import { cubeRoot } from "./quantize.js";
2
+ const WEIGHTS = [3, 4, 2];
3
+ const SPLIT_WEIGHTS = [3, 4, 2, 9];
4
+ const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
5
+ const FLOYD_STEINBERG = { dx: [1, -1, 0, 1], dy: [0, 1, 1, 1], w: [7 / 16, 3 / 16, 5 / 16, 1 / 16] };
6
+ const ATKINSON = { dx: [1, 2, -1, 0, 1, 0], dy: [0, 0, 1, 1, 1, 2], w: [1 / 8, 1 / 8, 1 / 8, 1 / 8, 1 / 8, 1 / 8] };
7
+ const distance = (pr, pg, pb, pa, qr, qg, qb, qa) => {
8
+ const a = pa - qa, r = pr - qr, g = pg - qg, b = pb - qb;
9
+ return WEIGHTS[0] * (r * r + (r - a) * (r - a)) + WEIGHTS[1] * (g * g + (g - a) * (g - a)) + WEIGHTS[2] * (b * b + (b - a) * (b - a));
10
+ };
11
+ const binOf = (r, g, b, a) => {
12
+ const pr = Math.round(r * a / 255), pg = Math.round(g * a / 255), pb = Math.round(b * a / 255);
13
+ return (pr >> 3) << 15 | (pg >> 3) << 10 | (pb >> 3) << 5 | (a === 255 ? 31 : Math.min(a >> 3, 30));
14
+ };
15
+ export class RGBAPaletteBuilder {
16
+ bins = new Uint32Array(1 << 20);
17
+ summing = false;
18
+ weight = new Float64Array(0);
19
+ mean = new Float64Array(0);
20
+ transparent = false;
21
+ count(pixels) {
22
+ if (this.summing)
23
+ throw new Error('RGBAPaletteBuilder: count after sum');
24
+ for (let i = 0; i < pixels.length; i += 4) {
25
+ const a = pixels[i + 3];
26
+ if (!a)
27
+ this.transparent = true;
28
+ else {
29
+ this.bins[binOf(pixels[i], pixels[i + 1], pixels[i + 2], a)]++;
30
+ }
31
+ }
32
+ }
33
+ sum(pixels) {
34
+ const { bins } = this;
35
+ if (!this.summing) {
36
+ this.summing = true;
37
+ let n = 0;
38
+ for (let bin = 0; bin < bins.length; bin++)
39
+ if (bins[bin])
40
+ n++;
41
+ const weight = this.weight = new Float64Array(n);
42
+ this.mean = new Float64Array(n * 4);
43
+ for (let bin = 0, id = 0; bin < bins.length; bin++)
44
+ if (bins[bin]) {
45
+ weight[id] = bins[bin];
46
+ bins[bin] = ++id;
47
+ }
48
+ }
49
+ const { mean } = this;
50
+ for (let i = 0; i < pixels.length; i += 4) {
51
+ const a = pixels[i + 3];
52
+ if (!a)
53
+ continue;
54
+ const id = (bins[binOf(pixels[i], pixels[i + 1], pixels[i + 2], a)] - 1) * 4;
55
+ mean[id] += pixels[i] * a / 255;
56
+ mean[id + 1] += pixels[i + 1] * a / 255;
57
+ mean[id + 2] += pixels[i + 2] * a / 255;
58
+ mean[id + 3] += a;
59
+ }
60
+ }
61
+ palette(colors) {
62
+ const { weight, transparent } = this;
63
+ const n = weight.length, mean = Float64Array.from(this.mean);
64
+ for (let id = 0; id < n; id++)
65
+ for (let k = 0; k < 4; k++)
66
+ mean[id * 4 + k] /= weight[id];
67
+ const solid = [], soft = [];
68
+ let solidWeight = 0, softWeight = 0;
69
+ for (let i = 0; i < n; i++) {
70
+ if (mean[i * 4 + 3] >= 254.999) {
71
+ solid.push(i);
72
+ solidWeight += weight[i];
73
+ }
74
+ else {
75
+ soft.push(i);
76
+ softWeight += weight[i];
77
+ }
78
+ }
79
+ const budget = colors - (transparent ? 1 : 0);
80
+ let softBudget = Math.min(soft.length, Math.round(budget * softWeight / (solidWeight + softWeight)));
81
+ if (soft.length && budget >= 2)
82
+ softBudget = Math.max(1, softBudget);
83
+ const solidBudget = Math.min(solid.length, budget - softBudget);
84
+ softBudget = Math.min(soft.length, budget - solidBudget);
85
+ const centers = Float64Array.from([...reduce(mean, weight, Int32Array.from(solid), solidBudget), ...reduce(mean, weight, Int32Array.from(soft), softBudget)]);
86
+ const entries = new Map();
87
+ for (let c = 0; c < centers.length; c += 4) {
88
+ const alpha = Math.min(centers[c + 3], 255);
89
+ const a = Math.round(alpha);
90
+ const straight = (v) => Math.min(255, Math.max(0, Math.round(Math.min(v, alpha) * 255 / a)));
91
+ const entry = [straight(centers[c]), straight(centers[c + 1]), straight(centers[c + 2]), a];
92
+ entries.set(entry[0] << 24 | entry[1] << 16 | entry[2] << 8 | entry[3], entry);
93
+ }
94
+ const list = [...entries.values()];
95
+ if (transparent)
96
+ list.push([0, 0, 0, 0]);
97
+ if (!list.length)
98
+ list.push([0, 0, 0, 0]);
99
+ return Uint8Array.from(list.flat());
100
+ }
101
+ }
102
+ function boxOf(mean, weight, members) {
103
+ let total = 0;
104
+ const sum = [0, 0, 0, 0];
105
+ for (const m of members) {
106
+ total += weight[m];
107
+ for (let k = 0; k < 4; k++)
108
+ sum[k] += weight[m] * mean[m * 4 + k];
109
+ }
110
+ let channel = 0, score = 0;
111
+ for (let k = 0; k < 4; k++) {
112
+ const center = sum[k] / total;
113
+ let variance = 0;
114
+ for (const m of members)
115
+ variance += weight[m] * (mean[m * 4 + k] - center) ** 2;
116
+ if (variance * SPLIT_WEIGHTS[k] > score) {
117
+ score = variance * SPLIT_WEIGHTS[k];
118
+ channel = k;
119
+ }
120
+ }
121
+ return { members, channel, score };
122
+ }
123
+ function reduce(mean, weight, points, target) {
124
+ let centers = cut(mean, weight, points, target);
125
+ for (let iteration = 0; iteration < 4 && centers.length / 4 > 1; iteration++)
126
+ centers = refine(mean, weight, points, centers);
127
+ return centers;
128
+ }
129
+ function cut(mean, weight, points, target) {
130
+ const boxes = [];
131
+ if (points.length && target > 0)
132
+ boxes.push(boxOf(mean, weight, points));
133
+ while (boxes.length < target) {
134
+ let best = -1;
135
+ for (let i = 0; i < boxes.length; i++)
136
+ if (boxes[i].members.length > 1 && boxes[i].score > 0 && (best < 0 || boxes[i].score > boxes[best].score))
137
+ best = i;
138
+ if (best < 0)
139
+ break;
140
+ const { members, channel } = boxes[best];
141
+ const keys = new Float64Array(members.length);
142
+ for (let i = 0; i < members.length; i++)
143
+ keys[i] = Math.round(mean[members[i] * 4 + channel] * 16) * 1048576 + i;
144
+ keys.sort();
145
+ let total = 0;
146
+ for (const m of members)
147
+ total += weight[m];
148
+ let half = 0, split = 1;
149
+ for (let i = 0; i < keys.length - 1; i++) {
150
+ half += weight[members[keys[i] % 1048576]];
151
+ split = i + 1;
152
+ if (half >= total / 2)
153
+ break;
154
+ }
155
+ const sorted = Int32Array.from(keys, key => members[key % 1048576]);
156
+ boxes[best] = boxOf(mean, weight, sorted.subarray(0, split));
157
+ boxes.push(boxOf(mean, weight, sorted.subarray(split)));
158
+ }
159
+ const centers = new Float64Array(boxes.length * 4);
160
+ boxes.forEach(({ members }, b) => {
161
+ let total = 0;
162
+ for (const m of members) {
163
+ total += weight[m];
164
+ for (let k = 0; k < 4; k++)
165
+ centers[b * 4 + k] += weight[m] * mean[m * 4 + k];
166
+ }
167
+ for (let k = 0; k < 4; k++)
168
+ centers[b * 4 + k] /= total;
169
+ });
170
+ return centers;
171
+ }
172
+ function refine(mean, weight, points, centers) {
173
+ const count = centers.length / 4;
174
+ const find = searcher(centers, Array.from({ length: count }, (_, i) => i));
175
+ const sums = new Float64Array(count * 4), totals = new Float64Array(count);
176
+ for (const i of points) {
177
+ const c = find(mean[i * 4], mean[i * 4 + 1], mean[i * 4 + 2], mean[i * 4 + 3]);
178
+ totals[c] += weight[i];
179
+ for (let k = 0; k < 4; k++)
180
+ sums[c * 4 + k] += weight[i] * mean[i * 4 + k];
181
+ }
182
+ const next = new Float64Array(count * 4);
183
+ for (let c = 0; c < count; c++)
184
+ for (let k = 0; k < 4; k++)
185
+ next[c * 4 + k] = totals[c] ? sums[c * 4 + k] / totals[c] : centers[c * 4 + k];
186
+ return next;
187
+ }
188
+ function searcher(premultiplied, entries) {
189
+ const order = [...entries].sort((x, y) => premultiplied[x * 4 + 1] - premultiplied[y * 4 + 1]);
190
+ const greens = Float64Array.from(order, e => premultiplied[e * 4 + 1]);
191
+ return (r, g, b, a) => {
192
+ let low = 0, high = order.length;
193
+ while (low < high) {
194
+ const mid = low + high >> 1;
195
+ if (greens[mid] < g)
196
+ low = mid + 1;
197
+ else
198
+ high = mid;
199
+ }
200
+ let best = -1, bestDistance = Infinity, left = low - 1, right = low;
201
+ while (left >= 0 || right < order.length) {
202
+ const goLeft = right >= order.length || left >= 0 && g - greens[left] < greens[right] - g;
203
+ const i = goLeft ? left : right;
204
+ const d = g - greens[i];
205
+ if (WEIGHTS[1] * d * d >= bestDistance) {
206
+ if (goLeft)
207
+ left = -1;
208
+ else
209
+ right = order.length;
210
+ continue;
211
+ }
212
+ const e = order[i];
213
+ const dist = distance(r, g, b, a, premultiplied[e * 4], premultiplied[e * 4 + 1], premultiplied[e * 4 + 2], premultiplied[e * 4 + 3]);
214
+ if (dist < bestDistance) {
215
+ bestDistance = dist;
216
+ best = e;
217
+ }
218
+ if (goLeft)
219
+ left--;
220
+ else
221
+ right++;
222
+ }
223
+ return best;
224
+ };
225
+ }
226
+ export function applyRGBAPalette(rgba, width, height, palette, dither, strength) {
227
+ const count = palette.length / 4;
228
+ const premultiplied = new Float64Array(count * 4);
229
+ const visible = [], solid = [];
230
+ for (let e = 0; e < count; e++) {
231
+ const a = palette[e * 4 + 3];
232
+ for (let k = 0; k < 3; k++)
233
+ premultiplied[e * 4 + k] = palette[e * 4 + k] * a / 255;
234
+ premultiplied[e * 4 + 3] = a;
235
+ if (a)
236
+ visible.push(e);
237
+ if (a === 255)
238
+ solid.push(e);
239
+ }
240
+ if (!visible.length) {
241
+ for (let p = 0; p < rgba.length; p += 4)
242
+ if (!rgba[p + 3])
243
+ rgba[p] = rgba[p + 1] = rgba[p + 2] = 0;
244
+ return;
245
+ }
246
+ const findVisible = searcher(premultiplied, visible);
247
+ const findSolid = solid.length ? searcher(premultiplied, solid) : findVisible;
248
+ const clamp = (v, max) => v < 0 ? 0 : v > max ? max : v;
249
+ const spread = dither === 'ordered' ? strength * 255 / cubeRoot(count) : 0;
250
+ const pattern = dither === 'atkinson' ? ATKINSON : FLOYD_STEINBERG;
251
+ const diffuse = dither === 'floyd-steinberg' || dither === 'atkinson';
252
+ const rows = diffuse ? [new Float32Array(width * 4), new Float32Array(width * 4), new Float32Array(width * 4)] : [];
253
+ const keys = diffuse ? null : new Uint32Array(1 << 16), cells = diffuse ? null : new Uint8Array(1 << 16), found = diffuse ? null : new Uint16Array(1 << 16);
254
+ for (let y = 0; y < height; y++) {
255
+ const direction = y & 1 ? -1 : 1;
256
+ const current = diffuse ? rows[y % 3] : null;
257
+ for (let step = 0; step < width; step++) {
258
+ const x = direction === 1 ? step : width - 1 - step;
259
+ const p = (y * width + x) * 4;
260
+ const a = rgba[p + 3];
261
+ if (!a) {
262
+ rgba[p] = rgba[p + 1] = rgba[p + 2] = 0;
263
+ continue;
264
+ }
265
+ const solidPixel = a === 255 && solid.length > 0;
266
+ let tr = rgba[p] * a / 255, tg = rgba[p + 1] * a / 255, tb = rgba[p + 2] * a / 255, ta = a;
267
+ let entry;
268
+ if (current) {
269
+ const e = x * 4;
270
+ ta = solidPixel ? 255 : clamp(ta + current[e + 3], 255);
271
+ if (!solidPixel && ta < 1)
272
+ ta = 1;
273
+ tr = clamp(tr + current[e], ta);
274
+ tg = clamp(tg + current[e + 1], ta);
275
+ tb = clamp(tb + current[e + 2], ta);
276
+ entry = (solidPixel ? findSolid : findVisible)(tr, tg, tb, ta);
277
+ }
278
+ else {
279
+ const cell = spread ? (y & 3) * 4 + (x & 3) : 0;
280
+ const value = (rgba[p] << 24 | rgba[p + 1] << 16 | rgba[p + 2] << 8 | a) >>> 0;
281
+ const slot = Math.imul(value ^ Math.imul(cell + 1, 0x85ebca6b), 0x9e3779b1) >>> 16;
282
+ if (keys[slot] === value && cells[slot] === cell + 1)
283
+ entry = found[slot];
284
+ else {
285
+ const offset = spread ? ((BAYER[cell] + 0.5) / 16 - 0.5) * spread : 0;
286
+ entry = (solidPixel ? findSolid : findVisible)(clamp(tr + offset, a), clamp(tg + offset, a), clamp(tb + offset, a), a);
287
+ keys[slot] = value;
288
+ cells[slot] = cell + 1;
289
+ found[slot] = entry;
290
+ }
291
+ }
292
+ rgba[p] = palette[entry * 4];
293
+ rgba[p + 1] = palette[entry * 4 + 1];
294
+ rgba[p + 2] = palette[entry * 4 + 2];
295
+ rgba[p + 3] = palette[entry * 4 + 3];
296
+ if (current) {
297
+ const er = tr - premultiplied[entry * 4], eg = tg - premultiplied[entry * 4 + 1], eb = tb - premultiplied[entry * 4 + 2];
298
+ const ea = ta - premultiplied[entry * 4 + 3];
299
+ const { dx, dy, w } = pattern;
300
+ for (let k = 0; k < dx.length; k++) {
301
+ const tx = x + dx[k] * direction, ty = y + dy[k];
302
+ if (tx < 0 || tx >= width || ty >= height)
303
+ continue;
304
+ const target = rows[ty % 3], t = tx * 4, s = w[k] * strength;
305
+ target[t] += er * s;
306
+ target[t + 1] += eg * s;
307
+ target[t + 2] += eb * s;
308
+ target[t + 3] += ea * s;
309
+ }
310
+ }
311
+ }
312
+ if (current)
313
+ current.fill(0);
314
+ }
315
+ }
@@ -1,4 +1,10 @@
1
1
  import { oneOf, finite } from "../util/options.js";
2
+ export function cubeRoot(x) {
3
+ let y = x / 3 + 1;
4
+ for (let i = 0; i < 40; i++)
5
+ y = (2 * y + x / (y * y)) / 3;
6
+ return y;
7
+ }
2
8
  const WR = 3, WG = 4, WB = 2;
3
9
  const DITHER = { 'none': true, 'floyd-steinberg': true, 'atkinson': true, 'ordered': true };
4
10
  export const DITHER_METHODS = Object.keys(DITHER);
@@ -126,7 +132,7 @@ export function applyPalette(pixels, width, height, palette, dither, strength) {
126
132
  const nearest = nearestSearch(palette, entries);
127
133
  const clampFloat = (v) => v < 0 ? 0 : v > 255 ? 255 : v;
128
134
  if (dither === 'none' || dither === 'ordered') {
129
- const spread = dither === 'ordered' ? strength * 255 / Math.cbrt(entries) : 0;
135
+ const spread = dither === 'ordered' ? strength * 255 / cubeRoot(entries) : 0;
130
136
  const slots = new Int32Array(1 << 16).fill(-1), found = new Uint16Array(1 << 16);
131
137
  for (let y = 0, p = 0; y < height; y++) {
132
138
  for (let x = 0; x < width; x++, p++) {
@@ -605,8 +605,17 @@ export async function compressAsync(data, level) {
605
605
  }
606
606
  return compress(data, level);
607
607
  }
608
+ export async function limited(count, limit, run) {
609
+ const results = new Array(count);
610
+ let next = 0;
611
+ await Promise.all(Array.from({ length: Math.min(limit, count) }, async () => {
612
+ for (let i; (i = next++) < count;)
613
+ results[i] = await run(i);
614
+ }));
615
+ return results;
616
+ }
608
617
  const PIECE = 1 << 20, WINDOW = 1 << 15;
609
- export async function compressParallel(data, level) {
618
+ export async function compressParallel(data, level, threads = Infinity) {
610
619
  level = Math.min(9, Math.max(0, level | 0));
611
620
  const zlib = nodeZlib;
612
621
  if (!zlib || !zlib.deflate || !zlib.deflateRaw)
@@ -615,13 +624,13 @@ export async function compressParallel(data, level) {
615
624
  if (data.length < 2 * PIECE)
616
625
  return new Promise((resolve, reject) => zlib.deflate?.(data, { level }, done(resolve, reject)));
617
626
  const count = Math.ceil(data.length / PIECE);
618
- const pieces = await Promise.all(Array.from({ length: count }, (_, i) => {
627
+ const pieces = await limited(count, threads, i => {
619
628
  const start = i * PIECE;
620
629
  const options = { level, finishFlush: i === count - 1 ? zlib.constants.Z_FINISH : zlib.constants.Z_SYNC_FLUSH };
621
630
  if (i)
622
631
  options.dictionary = data.subarray(start - WINDOW, start);
623
632
  return new Promise((resolve, reject) => zlib.deflateRaw?.(data.subarray(start, start + PIECE), options, done(resolve, reject)));
624
- }));
633
+ });
625
634
  let length = 6;
626
635
  for (const piece of pieces)
627
636
  length += piece.length;
package/dist/image.d.ts CHANGED
@@ -296,13 +296,34 @@ export interface GainMapEmbedOptions {
296
296
  */
297
297
  scale?: number;
298
298
  }
299
- /** Options of {@link Image.encodePNG} */
300
- export interface PNGEncodeOptions extends EncodeOptions {
299
+ /** Options of {@link Image.encodePNG}. `dither` and `ditherStrength` are only used with `colors` */
300
+ export interface PNGEncodeOptions extends EncodeOptions, DitherOptions {
301
301
  /**
302
302
  * The compression level (0-9), higher is smaller but slower
303
303
  * @defaultValue `4`
304
304
  */
305
305
  compression?: number;
306
+ /**
307
+ * Maximum threads for compression. Small images (under 2 MiB of pixel data) and runtimes without node:zlib (such as
308
+ * browsers) use one thread
309
+ * @remarks
310
+ * The image is compressed in pieces of 1 MiB on node:zlib's thread pool, not in workers, so the file is the same
311
+ * for any number of threads. Node's pool has 4 threads unless `UV_THREADPOOL_SIZE` says otherwise
312
+ * @defaultValue The available processors, up to 8
313
+ */
314
+ threads?: number;
315
+ /**
316
+ * Lossy: the maximum colors in the palette (2-256, including transparency), each with its own transparency, so soft
317
+ * edges and shadows stay soft. Makes photos with transparency and graphics with gradients much smaller. Images with
318
+ * no more colors keep them exactly (the file is the same as without this option); otherwise ImageScript chooses
319
+ * representative colors and applies `dither`. Fully transparent pixels lose their hidden color. The image itself
320
+ * stays unchanged
321
+ * @defaultValue None: the PNG is lossless
322
+ * @remarks
323
+ * Flat or smoothly shaded graphics without noise can be smaller as lossless PNGs, and dithering makes them larger:
324
+ * try `dither: 'none'`, and compare
325
+ */
326
+ colors?: number;
306
327
  }
307
328
  /** Options of {@link Image.encodeTGA}: the metadata, which TGA keeps in its extension area */
308
329
  export interface TGAEncodeOptions extends EncodeOptions {
@@ -329,6 +350,24 @@ export interface JPEGEncodeOptions extends EncodeOptions {
329
350
  * @defaultValue `'4:2:0'` up to quality 90, `'4:4:4'` above
330
351
  */
331
352
  subsampling?: '4:4:4' | '4:2:0';
353
+ /**
354
+ * Whether to write a progressive JPEG: the picture first appears blurry as a whole and sharpens while it loads, and
355
+ * the file is about 3% smaller for photos. The pixels are the same, and encoding takes 1.1 to 1.3 times as long.
356
+ * An embedded gain map stays a baseline JPEG
357
+ * @defaultValue `false`
358
+ */
359
+ progressive?: boolean;
360
+ /**
361
+ * The quantization tables, which decide how coarsely each frequency is stored (not the colors, as in
362
+ * {@link Image.quantize}): `'standard'` (the JPEG standard's) stores fine detail more coarsely than smooth areas,
363
+ * which softens sharp edges and text first; `'flat'` uses the same step for every frequency, which keeps edges and
364
+ * text clearer with fewer visible artifacts. At the same PSNR, files with `'flat'` were 3 to 30% smaller in a test of
365
+ * photos and a screenshot; at the same SSIM they ranged from 21% smaller to 15% larger (a photo at a low quality).
366
+ * The same `quality` makes a larger file with `'flat'`: lower it until the size matches (by about 15 to 25 around
367
+ * quality 60 for photos). Qualities 96 to 100 give the same `'flat'` file. Not used for the gain map
368
+ * @defaultValue `'standard'`
369
+ */
370
+ quantization?: 'standard' | 'flat';
332
371
  /**
333
372
  * The background color to combine with transparent pixels, since JPEG doesn't support transparency. Opaque images
334
373
  * are encoded as they are
package/dist/image.js CHANGED
@@ -39,6 +39,7 @@ const TRANSFORM_MODES = ['nearest-neighbor', 'bilinear', 'bicubic'];
39
39
  const RESIZE_FITS = ['fill', 'inside', 'contain', 'cover'];
40
40
  const CIRCLE_FITS = ['contain', 'cover'];
41
41
  const SUBSAMPLINGS = ['4:4:4', '4:2:0'];
42
+ const QUANTIZATIONS = ['standard', 'flat'];
42
43
  export const TONE_MAPPINGS = ['reinhard', 'clamp'];
43
44
  export const FLIP_DIRECTIONS = ['horizontal', 'vertical'];
44
45
  function featureList(features) {
@@ -1200,15 +1201,20 @@ export class Image {
1200
1201
  }
1201
1202
  async encodePNG(options = {}) {
1202
1203
  checkOptions(options, 'encodePNG({ compression: 9, metadata: { author: \'me\' } })');
1203
- const { compression = 4, metadata = {} } = options;
1204
- return png.encodeRGBA(this.__bytes__(), this.width, this.height, compressionLevel(compression), pngText(resolveMetadata(metadata)));
1204
+ const { compression = 4, threads = defaultThreads(), colors, dither = 'floyd-steinberg', ditherStrength = 0.85, metadata = {} } = options;
1205
+ checkThreads(threads);
1206
+ const palette = quantize.paletteOptions(colors, dither, ditherStrength);
1207
+ return png.encodeRGBA(this.__bytes__(), this.width, this.height, compressionLevel(compression), pngText(resolveMetadata(metadata)), threads, palette.colors === undefined ? undefined : { colors: palette.colors, dither: palette.dither, strength: palette.strength });
1205
1208
  }
1206
1209
  async encodeJPEG(options = {}) {
1207
1210
  checkOptions(options, 'encodeJPEG({ quality: 80 })');
1208
- const { quality: qualityOption = 90, subsampling, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options;
1211
+ const { quality: qualityOption = 90, subsampling, quantization, progressive = false, background = 0x000000ff, metadata = {}, gainMap: gainMapOption = true } = options;
1209
1212
  const quality = checkQuality(qualityOption);
1210
1213
  if (subsampling !== undefined)
1211
1214
  oneOf(subsampling, SUBSAMPLINGS, 'subsampling');
1215
+ if (quantization !== undefined)
1216
+ oneOf(quantization, QUANTIZATIONS, 'quantization');
1217
+ boolean(progressive, 'progressive');
1212
1218
  const backgroundColor = checkColor(background, 'background');
1213
1219
  const embed = gainMapEmbed(gainMapOption);
1214
1220
  const m = resolveMetadata(metadata);
@@ -1220,14 +1226,14 @@ export class Image {
1220
1226
  checkFormatSize('JPEG', this.width, this.height, 0xffff);
1221
1227
  if (!this.__gain_map__) {
1222
1228
  const flat = this.__flatRows__(backgroundColor);
1223
- const base = { exif, comment, subsampling };
1229
+ const base = { exif, comment, subsampling, quantization, progressive };
1224
1230
  if (!flat)
1225
1231
  return jpeg.encode(this.__bytes__(), this.width, this.height, quality, { ...base, gray: this.__is_gray__() });
1226
1232
  return jpeg.encode(flat.pixels, this.width, this.height, quality, { ...base, gray: flat.gray(), rows: flat.row });
1227
1233
  }
1228
1234
  const source = this.__flattened__(backgroundColor, embed !== null) ?? this;
1229
1235
  const gainMap = source.__gain_map__;
1230
- const base = { exif, comment, subsampling, gray: source.__is_gray__() };
1236
+ const base = { exif, comment, subsampling, quantization, progressive, gray: source.__is_gray__() };
1231
1237
  if (!gainMap || !embed)
1232
1238
  return jpeg.encode(source.__bytes__(), source.width, source.height, quality, base);
1233
1239
  const { quality: mapQuality, scale } = embed;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imagescript",
3
- "version": "4.0.1",
3
+ "version": "4.1.0",
4
4
  "description": "Pure TypeScript image processing that runs everywhere",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",