imagescript 3.12.0 → 3.12.2

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
@@ -1,7 +1,12 @@
1
- # ImageScript
2
- ##### zero-dependency JavaScript image manipulation
1
+ <h1 align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/matmen/ImageScript/master/media/wordmark-tagline-dark.svg">
4
+ <img alt="ImageScript: Pure TypeScript image processing that runs everywhere" src="https://raw.githubusercontent.com/matmen/ImageScript/master/media/wordmark-tagline.svg" width="640">
5
+ </picture>
6
+ </h1>
7
+
3
8
  [![Discord Server](https://img.shields.io/discord/691713541262147687.svg?label=Discord&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2&style=for-the-badge)](https://discord.gg/8hPrwAH)
4
- [![Documentation](https://img.shields.io/badge/Documentation-informational?style=for-the-badge)](https://imagescript.matmen.dev/)
9
+ [![Documentation](https://img.shields.io/badge/Documentation-informational?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MTIgNTEyIiB3aWR0aD0iNTEyIiBoZWlnaHQ9IjUxMiIgcm9sZT0iaW1nIiBhcmlhLWxhYmVsPSJJbWFnZVNjcmlwdCI+PHRpdGxlPkltYWdlU2NyaXB0PC90aXRsZT48cGF0aCBkPSJNMTMyIDk2aC0xNGEzNCAzNCAwIDAgMC0zNCAzNHY3NGEzMCAzMCAwIDAgMS0zMCAzMGgtNnY0NGg2YTMwIDMwIDAgMCAxIDMwIDMwdjc0YTM0IDM0IDAgMCAwIDM0IDM0aDE0IE0zODAgOTZoMTRhMzQgMzQgMCAwIDEgMzQgMzR2NzRhMzAgMzAgMCAwIDAgMzAgMzBoNnY0NGgtNmEzMCAzMCAwIDAgMC0zMCAzMHY3NGEzNCAzNCAwIDAgMS0zNCAzNGgtMTQiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2ZmZiIgc3Ryb2tlLXdpZHRoPSIzMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+PHJlY3QgeD0iMTY0IiB5PSIxNjQiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjI4IiB5PSIxNjQiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjkyIiB5PSIxNjQiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMTY0IiB5PSIyMjgiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjI4IiB5PSIyMjgiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjkyIiB5PSIyMjgiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMTY0IiB5PSIyOTIiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjI4IiB5PSIyOTIiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PHJlY3QgeD0iMjkyIiB5PSIyOTIiIHdpZHRoPSI1NiIgaGVpZ2h0PSI1NiIgcng9IjEwIiBmaWxsPSIjZmZmIi8+PC9zdmc+Cg==)](https://imagescript.dev/)
5
10
  [![Github](https://img.shields.io/badge/Github-Repository-181717?logo=github&style=for-the-badge)](https://github.com/matmen/ImageScript)
6
11
  [![NPM](https://nodei.co/npm/imagescript.png)](https://www.npmjs.com/package/imagescript)
7
12
 
@@ -50,27 +55,27 @@ Coordinates start at `(0, 0)`, the top left pixel. For a bigger example, see the
50
55
  | BMP, QOI, TGA, Netpbm | ✓ | ✓ |
51
56
  | TIFF, ICO/CUR, Radiance HDR | ✓ | |
52
57
 
53
- [Animations](https://imagescript.matmen.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL,
58
+ [Animations](https://imagescript.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL,
54
59
  and encoded as GIF, APNG or WebP, all at once or
55
- [frame by frame](https://imagescript.matmen.dev/classes/Animation.html#webpencoder). Embedded color profiles (Display
60
+ [frame by frame](https://imagescript.dev/classes/Animation.html#webpencoder). Embedded color profiles (Display
56
61
  P3, Adobe RGB, ...) are converted to sRGB when decoding, so images look the way browsers show them.
57
62
 
58
- - [Text rendering](https://imagescript.matmen.dev/classes/Image.html#rendertext) with TrueType and OpenType fonts:
63
+ - [Text rendering](https://imagescript.dev/classes/Image.html#rendertext) with TrueType and OpenType fonts:
59
64
  all scripts, color emoji, variable fonts
60
- - [SVG rendering](https://imagescript.matmen.dev/classes/Image.html#rendersvg), including text (with fonts you pass
65
+ - [SVG rendering](https://imagescript.dev/classes/Image.html#rendersvg), including text (with fonts you pass
61
66
  or fonts embedded in the SVG)
62
- - [Resizing](https://imagescript.matmen.dev/classes/Image.html#resize),
63
- [cropping](https://imagescript.matmen.dev/classes/Image.html#crop),
64
- [rotating](https://imagescript.matmen.dev/classes/Image.html#rotate),
65
- [trimming](https://imagescript.matmen.dev/classes/Image.html#trim),
66
- [rounded corners](https://imagescript.matmen.dev/classes/Image.html#roundcorners), ...
67
- - [Compositing](https://imagescript.matmen.dev/classes/Image.html#composite) with opacity and blend modes
68
- - Filters and color adjustments: [blur](https://imagescript.matmen.dev/classes/Image.html#blur),
69
- [sharpen](https://imagescript.matmen.dev/classes/Image.html#sharpen),
70
- [brightness](https://imagescript.matmen.dev/classes/Image.html#brightness),
71
- [hueShift](https://imagescript.matmen.dev/classes/Image.html#hueshift), ...
72
-
73
- The [documentation](https://imagescript.matmen.dev/) covers the full API. When upgrading from an older major version,
67
+ - [Resizing](https://imagescript.dev/classes/Image.html#resize),
68
+ [cropping](https://imagescript.dev/classes/Image.html#crop),
69
+ [rotating](https://imagescript.dev/classes/Image.html#rotate),
70
+ [trimming](https://imagescript.dev/classes/Image.html#trim),
71
+ [rounded corners](https://imagescript.dev/classes/Image.html#roundcorners), ...
72
+ - [Compositing](https://imagescript.dev/classes/Image.html#composite) with opacity and blend modes
73
+ - Filters and color adjustments: [blur](https://imagescript.dev/classes/Image.html#blur),
74
+ [sharpen](https://imagescript.dev/classes/Image.html#sharpen),
75
+ [brightness](https://imagescript.dev/classes/Image.html#brightness),
76
+ [hueShift](https://imagescript.dev/classes/Image.html#hueshift), ...
77
+
78
+ The [documentation](https://imagescript.dev/) covers the full API. When upgrading from an older major version,
74
79
  see the [changelog](https://github.com/matmen/ImageScript/blob/master/CHANGELOG.md). [bench/](bench/README.md)
75
80
  compares ImageScript's speed and file sizes with Jimp, sharp and other libraries.
76
81
 
@@ -12,7 +12,7 @@ following projects, under their own licenses. Each derived file says so in its h
12
12
  | [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
13
  | [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) |
14
14
  | [RFC 6386](https://www.rfc-editor.org/rfc/rfc6386) (VP8 Data Format and Decoding Guide, with the libvpx reference decoder) | `src/codecs/vp8-tables.ts` (probability and quantizer tables), `src/codecs/vp8.ts` (decoding procedures) | BSD-3-Clause |
15
- | [libwebp](https://chromium.googlesource.com/webm/libwebp) | `src/codecs/vp8.ts` (YUV to RGB conversion, "fancy" chroma upsampling), `src/codecs/webp.ts` (animation frame blending), `src/codecs/vp8-enc.ts`, `src/codecs/vp8-enc-dsp.ts` (the lossy encoder: RGB to YUV conversion, analysis, segments, rate-distortion optimized mode decisions, quantization, token probabilities, bitstream, alpha filtering), `src/codecs/vp8-enc-tables.ts` (its tables, generated from libwebp by `scripts/vp8-enc-tables.py`), `src/codecs/sharpyuv.ts` (the sharp RGB to YUV conversion, libsharpyuv) | BSD-3-Clause |
15
+ | [libwebp](https://chromium.googlesource.com/webm/libwebp) | `src/codecs/vp8.ts` (YUV to RGB conversion, "fancy" chroma upsampling), `src/codecs/webp.ts` (animation frame blending), `src/codecs/vp8-enc.ts`, `src/codecs/vp8-enc-dsp.ts` (the lossy encoder: RGB to YUV conversion, analysis, segments, rate-distortion optimized mode decisions, quantization, token probabilities, bitstream, alpha filtering), `src/codecs/vp8-enc-tables.ts` (its tables, generated from libwebp by `scripts/vp8-enc-tables.py`), `src/codecs/sharpyuv.ts` (the sharp RGB to YUV conversion, libsharpyuv), `src/codecs/vp8l.ts` (the lossless encoder's entropy analysis and color transform search) | BSD-3-Clause |
16
16
  | [dav1d](https://code.videolan.org/videolan/dav1d) by VideoLAN, the dav1d authors and Two Orioles | `src/codecs/av1/*` (the AV1 decoder, and the encoder's syntax, contexts and reconstruction mirrored from it: bitstream parsing, symbol decoding, prediction, inverse transforms, loop filters, film grain; the tables in `src/codecs/av1/data.ts`, generated from dav1d by `scripts/av1-tables.c`) | BSD-2-Clause |
17
17
  | [libaom](https://aomedia.googlesource.com/aom/) by the Alliance for Open Media | `src/codecs/av1/msac-enc.ts` (the symbol encoder), `src/codecs/av1/fdct.ts` (the forward Walsh-Hadamard transform), `src/codecs/av1/encode.ts` (the loop filter level from the quantizer), `src/codecs/avif-enc.ts` (the quantizer to qindex table) | BSD-2-Clause |
18
18
  | [libavif](https://github.com/AOMediaCodec/libavif) by Joe Drago | `src/codecs/avif.ts` (YUV to RGB conversion with bilinear chroma upsampling, alpha range expansion and unpremultiplication) | BSD-2-Clause |
@@ -1,7 +1,7 @@
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
- * color conversion, progressive refinement and optimal Huffman tables are translated from libjpeg/libjpeg-turbo
4
- * (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 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
5
5
  * (Copyright 2014 Mozilla Foundation, Apache License 2.0). See THIRD_PARTY_NOTICES.md
6
6
  */
7
7
  import { ByteWriter } from "../util/bytes.js";
@@ -540,71 +540,71 @@ function upsample(component, frame) {
540
540
  const hf = frame.hmax / component.h;
541
541
  const vf = frame.vmax / component.v;
542
542
  const w = component.width, h = component.height;
543
- const W = Math.ceil(w * hf), H = Math.ceil(h * vf);
544
- const out = new Uint8Array(W * H);
543
+ const W = Math.ceil(w * hf);
544
+ const out = new Uint8Array(W);
545
545
  const fancy = w > 2;
546
- if (hf === 1 && vf === 1) {
547
- for (let y = 0; y < h; y++)
548
- out.set(plane.subarray(y * stride, y * stride + w), y * W);
549
- }
550
- else if (hf === 2 && vf === 1 && fancy) {
551
- for (let y = 0; y < h; y++) {
552
- const i = y * stride, o = y * W;
553
- out[o] = plane[i];
554
- out[o + 1] = plane[i] * 3 + plane[i + 1] + 2 >> 2;
555
- for (let x = 1; x < w - 1; x++) {
556
- const v = plane[i + x] * 3;
557
- out[o + 2 * x] = v + plane[i + x - 1] + 1 >> 2;
558
- out[o + 2 * x + 1] = v + plane[i + x + 1] + 2 >> 2;
546
+ if (hf === 1 && vf === 1)
547
+ return { samples: plane, stride };
548
+ if (hf === 2 && vf === 1 && fancy)
549
+ return {
550
+ samples: out, stride: 0, fill: y => {
551
+ const i = y * stride;
552
+ out[0] = plane[i];
553
+ out[1] = plane[i] * 3 + plane[i + 1] + 2 >> 2;
554
+ for (let x = 1; x < w - 1; x++) {
555
+ const v = plane[i + x] * 3;
556
+ out[2 * x] = v + plane[i + x - 1] + 1 >> 2;
557
+ out[2 * x + 1] = v + plane[i + x + 1] + 2 >> 2;
558
+ }
559
+ out[2 * w - 2] = plane[i + w - 1] * 3 + plane[i + w - 2] + 1 >> 2;
560
+ out[2 * w - 1] = plane[i + w - 1];
559
561
  }
560
- out[o + 2 * w - 2] = plane[i + w - 1] * 3 + plane[i + w - 2] + 1 >> 2;
561
- out[o + 2 * w - 1] = plane[i + w - 1];
562
- }
563
- }
564
- else if (hf === 1 && vf === 2 && fancy) {
565
- for (let y = 0; y < h; y++) {
566
- const i = y * stride;
567
- const above = Math.max(0, y - 1) * stride;
568
- const below = Math.min(h - 1, y + 1) * stride;
569
- for (let x = 0; x < w; x++) {
570
- const v = plane[i + x] * 3;
571
- out[2 * y * W + x] = v + plane[above + x] + 1 >> 2;
572
- out[(2 * y + 1) * W + x] = v + plane[below + x] + 2 >> 2;
562
+ };
563
+ if (hf === 1 && vf === 2 && fancy)
564
+ return {
565
+ samples: out, stride: 0, fill: y => {
566
+ const i = (y >> 1) * stride;
567
+ if (y & 1) {
568
+ const below = Math.min(h - 1, (y >> 1) + 1) * stride;
569
+ for (let x = 0; x < w; x++)
570
+ out[x] = plane[i + x] * 3 + plane[below + x] + 2 >> 2;
571
+ }
572
+ else {
573
+ const above = Math.max(0, (y >> 1) - 1) * stride;
574
+ for (let x = 0; x < w; x++)
575
+ out[x] = plane[i + x] * 3 + plane[above + x] + 1 >> 2;
576
+ }
573
577
  }
574
- }
575
- }
576
- else if (hf === 2 && vf === 2 && fancy) {
577
- for (let y = 0; y < h; y++) {
578
- const i = y * stride;
579
- for (let pass = 0; pass < 2; pass++) {
580
- const other = (pass === 0 ? Math.max(0, y - 1) : Math.min(h - 1, y + 1)) * stride;
581
- const o = (2 * y + pass) * W;
578
+ };
579
+ if (hf === 2 && vf === 2 && fancy)
580
+ return {
581
+ samples: out, stride: 0, fill: y => {
582
+ const i = (y >> 1) * stride;
583
+ const other = (y & 1 ? Math.min(h - 1, (y >> 1) + 1) : Math.max(0, (y >> 1) - 1)) * stride;
582
584
  let thisSum = plane[i] * 3 + plane[other];
583
585
  let nextSum = plane[i + 1] * 3 + plane[other + 1];
584
- out[o] = thisSum * 4 + 8 >> 4;
585
- out[o + 1] = thisSum * 3 + nextSum + 7 >> 4;
586
+ out[0] = thisSum * 4 + 8 >> 4;
587
+ out[1] = thisSum * 3 + nextSum + 7 >> 4;
586
588
  let lastSum = thisSum;
587
589
  thisSum = nextSum;
588
590
  for (let x = 1; x < w - 1; x++) {
589
591
  nextSum = plane[i + x + 1] * 3 + plane[other + x + 1];
590
- out[o + 2 * x] = thisSum * 3 + lastSum + 8 >> 4;
591
- out[o + 2 * x + 1] = thisSum * 3 + nextSum + 7 >> 4;
592
+ out[2 * x] = thisSum * 3 + lastSum + 8 >> 4;
593
+ out[2 * x + 1] = thisSum * 3 + nextSum + 7 >> 4;
592
594
  lastSum = thisSum;
593
595
  thisSum = nextSum;
594
596
  }
595
- out[o + 2 * w - 2] = thisSum * 3 + lastSum + 8 >> 4;
596
- out[o + 2 * w - 1] = thisSum * 4 + 7 >> 4;
597
+ out[2 * w - 2] = thisSum * 3 + lastSum + 8 >> 4;
598
+ out[2 * w - 1] = thisSum * 4 + 7 >> 4;
597
599
  }
598
- }
599
- }
600
- else {
601
- for (let y = 0; y < H; y++) {
600
+ };
601
+ return {
602
+ samples: out, stride: 0, fill: y => {
602
603
  const i = Math.min(h - 1, y / vf | 0) * stride;
603
604
  for (let x = 0; x < W; x++)
604
- out[y * W + x] = plane[i + Math.min(w - 1, x / hf | 0)];
605
+ out[x] = plane[i + Math.min(w - 1, x / hf | 0)];
605
606
  }
606
- }
607
- return { samples: out, stride: W };
607
+ };
608
608
  }
609
609
  const crR = new Int32Array(256);
610
610
  const cbB = new Int32Array(256);
@@ -648,6 +648,8 @@ function output(frame, adobe, jfif, override) {
648
648
  const grey = transform === 'grey', ycc = transform === 'ycc';
649
649
  const words = littleEndian ? new Uint32Array(pixels.buffer) : null;
650
650
  for (let y = 0, o = 0; y < height; y++, o = y * width * 4) {
651
+ for (const p of planes)
652
+ p.fill?.(y);
651
653
  const r0 = y * p0.stride, r1 = p1 ? y * p1.stride : r0, r2 = p2 ? y * p2.stride : r0;
652
654
  if (grey)
653
655
  for (let x = 0; x < width; x++, o += 4) {
@@ -678,6 +680,8 @@ function output(frame, adobe, jfif, override) {
678
680
  return pixels;
679
681
  }
680
682
  for (let y = 0, o = 0; y < height; y++) {
683
+ for (const p of planes)
684
+ p.fill?.(y);
681
685
  const r0 = y * p0.stride, r1 = y * p1.stride, r2 = y * p2.stride, r3 = y * p3.stride;
682
686
  for (let x = 0; x < width; x++, o += 4) {
683
687
  pixels[o + 3] = 0xff;
@@ -717,94 +721,144 @@ const CHROMA_QUANTIZATION = [
717
721
  99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
718
722
  99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99
719
723
  ];
720
- const AAN_SCALE = [1, 1.387039845, 1.306562965, 1.175875602, 1, 0.785694958, 0.5411961, 0.275899379];
724
+ const fix16 = (x) => Math.round(x * 65536);
725
+ const Y_R = new Int32Array(256), Y_G = new Int32Array(256), Y_B = new Int32Array(256);
726
+ const CB_R = new Int32Array(256), CB_G = new Int32Array(256), CB_B = new Int32Array(256);
727
+ const CR_G = new Int32Array(256), CR_B = new Int32Array(256);
728
+ for (let i = 0; i < 256; i++) {
729
+ Y_R[i] = fix16(0.299) * i;
730
+ Y_G[i] = fix16(0.587) * i;
731
+ Y_B[i] = fix16(0.114) * i + 32768;
732
+ CB_R[i] = -fix16(0.16874) * i;
733
+ CB_G[i] = -fix16(0.33126) * i;
734
+ CB_B[i] = fix16(0.5) * i + (128 << 16) + 32767;
735
+ CR_G[i] = -fix16(0.41869) * i;
736
+ CR_B[i] = -fix16(0.08131) * i;
737
+ }
738
+ function reciprocals(table) {
739
+ const r = new Int32Array(3 * 64);
740
+ for (let i = 0; i < 64; i++) {
741
+ const divisor = table[i] * 8;
742
+ const b = 31 - Math.clz32(divisor), shift = 16 + b;
743
+ let fq = Math.floor(2 ** shift / divisor), c = divisor >> 1, bits = shift;
744
+ const fr = 2 ** shift % divisor;
745
+ if (fr === 0) {
746
+ fq >>= 1;
747
+ bits--;
748
+ }
749
+ else if (fr <= divisor >> 1)
750
+ c++;
751
+ else
752
+ fq++;
753
+ r[i] = fq;
754
+ r[64 + i] = c;
755
+ r[128 + i] = bits;
756
+ }
757
+ return r;
758
+ }
721
759
  export function encode(pixels, width, height, quality = 90, { exif, comment } = {}) {
722
760
  if (!width || !height || width > 0xffff || height > 0xffff)
723
761
  throw new RangeError('JPEG: invalid dimensions');
724
762
  quality = Math.min(100, Math.max(1, Math.round(quality)));
725
- const scale = quality < 50 ? 5000 / quality : 200 - quality * 2;
763
+ const scale = quality < 50 ? Math.floor(5000 / quality) : 200 - quality * 2;
726
764
  const scaleTable = (base) => base.map(v => Math.min(255, Math.max(1, Math.floor((v * scale + 50) / 100))));
727
765
  const tables = [scaleTable(LUMA_QUANTIZATION), scaleTable(CHROMA_QUANTIZATION)];
728
- const divisors = tables.map(table => {
729
- const d = new Float64Array(64);
730
- for (let i = 0; i < 64; i++)
731
- d[i] = 1 / (table[i] * AAN_SCALE[i >> 3] * AAN_SCALE[i & 7] * 8);
732
- return d;
733
- });
766
+ const divisors = tables.map(reciprocals);
734
767
  const subsample = quality <= 90;
735
768
  const hmax = subsample ? 2 : 1;
736
769
  const mcuSize = 8 * hmax;
737
770
  const mcusPerLine = Math.ceil(width / mcuSize);
738
771
  const mcusPerColumn = Math.ceil(height / mcuSize);
739
- const W = mcusPerLine * mcuSize, H = mcusPerColumn * mcuSize;
740
- const Y = new Float32Array(W * H), Cb = new Float32Array(W * H), Cr = new Float32Array(W * H);
772
+ const chromaWidth = Math.ceil(width / hmax), chromaHeight = Math.ceil(height / hmax);
773
+ const lumaBlocksX = Math.ceil(width / 8), lumaBlocksY = Math.ceil(height / 8);
774
+ const chromaBlocksX = Math.ceil(chromaWidth / 8), chromaBlocksY = Math.ceil(chromaHeight / 8);
775
+ const W = lumaBlocksX * 8, CW = chromaBlocksX * 8;
776
+ const Y = new Uint8Array(W * lumaBlocksY * 8), Cb = new Uint8Array(CW * chromaBlocksY * 8), Cr = new Uint8Array(CW * chromaBlocksY * 8);
777
+ const rowWidth = CW * hmax;
778
+ const cbRows = subsample ? new Uint8Array(2 * rowWidth) : Cb, crRows = subsample ? new Uint8Array(2 * rowWidth) : Cr;
779
+ const words = littleEndian && pixels.byteOffset % 4 === 0 ? new Uint32Array(pixels.buffer, pixels.byteOffset, width * height) : null;
741
780
  for (let y = 0; y < height; y++) {
742
- let i = y * width * 4, o = y * W;
743
- for (let x = 0; x < width; x++, i += 4, o++) {
744
- const r = pixels[i], g = pixels[i + 1], b = pixels[i + 2];
745
- Y[o] = 0.299 * r + 0.587 * g + 0.114 * b - 128;
746
- Cb[o] = -0.168735892 * r - 0.331264108 * g + 0.5 * b;
747
- Cr[o] = 0.5 * r - 0.418687589 * g - 0.081312411 * b;
748
- }
781
+ const row = subsample ? (y & 1) * rowWidth : y * CW;
782
+ let i = y * width * 4, o = y * W, c = row;
783
+ if (words)
784
+ for (let x = 0, w = i >> 2; x < width; x++, w++, o++, c++) {
785
+ const p = words[w], r = p & 255, g = p >> 8 & 255, b = p >> 16 & 255;
786
+ Y[o] = Y_R[r] + Y_G[g] + Y_B[b] >> 16;
787
+ cbRows[c] = CB_R[r] + CB_G[g] + CB_B[b] >> 16;
788
+ crRows[c] = CB_B[r] + CR_G[g] + CR_B[b] >> 16;
789
+ }
790
+ else
791
+ for (let x = 0; x < width; x++, i += 4, o++, c++) {
792
+ const r = pixels[i], g = pixels[i + 1], b = pixels[i + 2];
793
+ Y[o] = Y_R[r] + Y_G[g] + Y_B[b] >> 16;
794
+ cbRows[c] = CB_R[r] + CB_G[g] + CB_B[b] >> 16;
795
+ crRows[c] = CB_B[r] + CR_G[g] + CR_B[b] >> 16;
796
+ }
749
797
  Y.fill(Y[o - 1], o, (y + 1) * W);
750
- Cb.fill(Cb[o - 1], o, (y + 1) * W);
751
- Cr.fill(Cr[o - 1], o, (y + 1) * W);
798
+ cbRows.fill(cbRows[c - 1], c, row + rowWidth);
799
+ crRows.fill(crRows[c - 1], c, row + rowWidth);
800
+ if (subsample && (y & 1 || y === height - 1)) {
801
+ if (!(y & 1)) {
802
+ cbRows.copyWithin(rowWidth, 0, rowWidth);
803
+ crRows.copyWithin(rowWidth, 0, rowWidth);
804
+ }
805
+ for (let x = 0, o = (y >> 1) * CW, bias = 1; x < rowWidth; x += 2, o++, bias ^= 3) {
806
+ Cb[o] = cbRows[x] + cbRows[x + 1] + cbRows[x + rowWidth] + cbRows[x + rowWidth + 1] + bias >> 2;
807
+ Cr[o] = crRows[x] + crRows[x + 1] + crRows[x + rowWidth] + crRows[x + rowWidth + 1] + bias >> 2;
808
+ }
809
+ }
752
810
  }
753
- for (let y = height; y < H; y++) {
811
+ for (let y = height; y < lumaBlocksY * 8; y++)
754
812
  Y.copyWithin(y * W, (height - 1) * W, height * W);
755
- Cb.copyWithin(y * W, (height - 1) * W, height * W);
756
- Cr.copyWithin(y * W, (height - 1) * W, height * W);
813
+ for (let y = chromaHeight; y < chromaBlocksY * 8; y++) {
814
+ Cb.copyWithin(y * CW, (chromaHeight - 1) * CW, chromaHeight * CW);
815
+ Cr.copyWithin(y * CW, (chromaHeight - 1) * CW, chromaHeight * CW);
757
816
  }
758
- const downsample = (plane) => {
759
- const out = new Float32Array(W * H / 4);
760
- for (let y = 0, o = 0; y < H; y += 2)
761
- for (let x = 0; x < W; x += 2, o++) {
762
- const i = y * W + x;
763
- out[o] = (plane[i] + plane[i + 1] + plane[i + W] + plane[i + W + 1]) * 0.25;
764
- }
765
- return out;
766
- };
767
- const chromaStride = subsample ? W / 2 : W;
768
817
  const components = [
769
- { plane: Y, stride: W, h: hmax, v: hmax, table: 0 },
770
- { plane: subsample ? downsample(Cb) : Cb, stride: chromaStride, h: 1, v: 1, table: 1 },
771
- { plane: subsample ? downsample(Cr) : Cr, stride: chromaStride, h: 1, v: 1, table: 1 }
818
+ { plane: Y, stride: W, h: hmax, v: hmax, blocksX: lumaBlocksX, blocksY: lumaBlocksY, table: 0 },
819
+ { plane: Cb, stride: CW, h: 1, v: 1, blocksX: chromaBlocksX, blocksY: chromaBlocksY, table: 1 },
820
+ { plane: Cr, stride: CW, h: 1, v: 1, blocksX: chromaBlocksX, blocksY: chromaBlocksY, table: 1 }
772
821
  ];
773
822
  const blocksPerMcu = hmax * hmax + 2;
774
823
  const count = mcusPerLine * mcusPerColumn * blocksPerMcu;
775
824
  const coefficients = new Int16Array(count * 64);
776
825
  const owners = new Uint8Array(count), ends = new Uint8Array(count);
777
- const block = new Float64Array(64);
826
+ const block = new Int32Array(64);
778
827
  let n = 0;
779
828
  for (let my = 0; my < mcusPerColumn; my++)
780
829
  for (let mx = 0; mx < mcusPerLine; mx++)
781
830
  for (let c = 0; c < 3; c++) {
782
- const { plane, stride, h: ch, v: cv, table } = components[c];
783
- const d = divisors[table];
784
- for (let v = 0; v < cv; v++)
831
+ const { plane, stride, h: ch, v: cv, blocksX, blocksY, table } = components[c];
832
+ const reciprocal = divisors[table];
833
+ for (let v = 0; v < cv; v++) {
834
+ const by = my * cv + v, rowStart = n;
785
835
  for (let h = 0; h < ch; h++, n++) {
786
- const x0 = (mx * ch + h) * 8, y0 = (my * cv + v) * 8;
787
- for (let y = 0; y < 8; y++) {
788
- const row = (y0 + y) * stride + x0;
789
- for (let x = 0; x < 8; x++)
790
- block[y * 8 + x] = plane[row + x];
836
+ const bx = mx * ch + h, o = n * 64;
837
+ owners[n] = c;
838
+ if (by >= blocksY) {
839
+ coefficients[o] = coefficients[(rowStart - 1) * 64];
840
+ continue;
841
+ }
842
+ if (bx >= blocksX) {
843
+ coefficients[o] = coefficients[o - 64];
844
+ continue;
791
845
  }
792
- fdct(block);
793
- const o = n * 64;
846
+ fdct(plane, by * 8 * stride + bx * 8, stride, block);
794
847
  let end = 0;
795
848
  for (let k = 0; k < 64; k++) {
796
- const i = ZIGZAG[k], value = (block[i] * d[i] + 16384.5 | 0) - 16384;
849
+ const i = ZIGZAG[k], t = block[i], sign = t >> 31;
850
+ const value = (Math.imul((t ^ sign) - sign + reciprocal[64 + i], reciprocal[i]) >>> reciprocal[128 + i] ^ sign) - sign;
797
851
  coefficients[o + k] = value;
798
852
  if (value)
799
853
  end = k;
800
854
  }
801
- owners[n] = c;
802
855
  ends[n] = end;
803
856
  }
857
+ }
804
858
  }
805
859
  const blocks = { coefficients, owners, ends, count };
806
860
  const frequencies = [new Int32Array(257), new Int32Array(257), new Int32Array(257), new Int32Array(257)];
807
- encodeBlocks(blocks, (table, symbol) => frequencies[table][symbol]++, () => { });
861
+ countSymbols(blocks, frequencies);
808
862
  const huffman = frequencies.map(buildOptimalTable);
809
863
  const writer = new BitWriter(width * height);
810
864
  writer.bytes(0xff, 0xd8);
@@ -820,9 +874,8 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
820
874
  segment(0xe1, concat([[0x45, 0x78, 0x69, 0x66, 0, 0], exif]));
821
875
  if (comment)
822
876
  segment(0xfe, comment);
823
- writer.bytes(0xff, 0xdb, 0x00, 0x84);
824
877
  for (let t = 0; t < 2; t++) {
825
- writer.bytes(t);
878
+ writer.bytes(0xff, 0xdb, 0x00, 0x43, t);
826
879
  for (let k = 0; k < 64; k++)
827
880
  writer.bytes(tables[t][ZIGZAG[k]]);
828
881
  }
@@ -838,24 +891,64 @@ export function encode(pixels, width, height, quality = 90, { exif, comment } =
838
891
  writer.bytes(value);
839
892
  }
840
893
  writer.bytes(0xff, 0xda, 0x00, 0x0c, 0x03, 1, 0x00, 2, 0x11, 3, 0x11, 0x00, 0x3f, 0x00);
841
- encodeBlocks(blocks, (table, symbol) => writer.write(huffman[table].codes[symbol], huffman[table].sizes[symbol]), (value, size) => writer.write(value, size));
894
+ writeBlocks(blocks, huffman, writer);
842
895
  writer.flush();
843
896
  writer.bytes(0xff, 0xd9);
844
897
  return writer.finish();
845
898
  }
846
- function encodeBlocks({ coefficients, owners, ends, count }, symbol, bits) {
899
+ function countSymbols({ coefficients, owners, ends, count }, frequencies) {
847
900
  const pred = [0, 0, 0];
848
901
  for (let n = 0; n < count; n++) {
849
- const component = owners[n];
850
- const o = n * 64;
851
- const dcTable = component === 0 ? 0 : 2;
852
- const acTable = dcTable + 1;
902
+ const component = owners[n], o = n * 64;
903
+ const dc = frequencies[component === 0 ? 0 : 2], ac = frequencies[component === 0 ? 1 : 3];
904
+ dc[magnitude(coefficients[o] - pred[component])]++;
905
+ pred[component] = coefficients[o];
906
+ let run = 0;
907
+ for (let k = 1, end = ends[n]; k <= end; k++) {
908
+ const value = coefficients[o + k];
909
+ if (value === 0) {
910
+ run++;
911
+ continue;
912
+ }
913
+ for (; run > 15; run -= 16)
914
+ ac[0xf0]++;
915
+ ac[run << 4 | magnitude(value)]++;
916
+ run = 0;
917
+ }
918
+ if (ends[n] < 63)
919
+ ac[0]++;
920
+ }
921
+ }
922
+ function writeBlocks({ coefficients, owners, ends, count }, huffman, writer) {
923
+ const pred = [0, 0, 0];
924
+ let { bits, count: pending, buffer, length } = writer;
925
+ const put = (value, size) => {
926
+ bits = bits << size | value & (1 << size) - 1;
927
+ pending += size;
928
+ while (pending >= 8) {
929
+ pending -= 8;
930
+ const byte = bits >>> pending & 0xff;
931
+ if (length + 2 > buffer.length) {
932
+ writer.length = length;
933
+ writer.reserve(2);
934
+ buffer = writer.buffer;
935
+ }
936
+ buffer[length++] = byte;
937
+ if (byte === 0xff)
938
+ buffer[length++] = 0x00;
939
+ }
940
+ bits &= (1 << pending) - 1;
941
+ };
942
+ for (let n = 0; n < count; n++) {
943
+ const component = owners[n], o = n * 64;
944
+ const dc = huffman[component === 0 ? 0 : 2], ac = huffman[component === 0 ? 1 : 3];
945
+ const dcCodes = dc.codes, dcSizes = dc.sizes, acCodes = ac.codes, acSizes = ac.sizes;
853
946
  const diff = coefficients[o] - pred[component];
854
947
  pred[component] = coefficients[o];
855
948
  const size = magnitude(diff);
856
- symbol(dcTable, size);
949
+ put(dcCodes[size], dcSizes[size]);
857
950
  if (size)
858
- bits(diff < 0 ? diff - 1 & (1 << size) - 1 : diff, size);
951
+ put(diff < 0 ? diff - 1 : diff, size);
859
952
  let run = 0;
860
953
  for (let k = 1, end = ends[n]; k <= end; k++) {
861
954
  const value = coefficients[o + k];
@@ -863,18 +956,19 @@ function encodeBlocks({ coefficients, owners, ends, count }, symbol, bits) {
863
956
  run++;
864
957
  continue;
865
958
  }
866
- while (run > 15) {
867
- symbol(acTable, 0xf0);
868
- run -= 16;
869
- }
870
- const s = magnitude(value);
871
- symbol(acTable, run << 4 | s);
872
- bits(value < 0 ? value - 1 & (1 << s) - 1 : value, s);
959
+ for (; run > 15; run -= 16)
960
+ put(acCodes[0xf0], acSizes[0xf0]);
961
+ const s = magnitude(value), symbol = run << 4 | s;
962
+ put(acCodes[symbol], acSizes[symbol]);
963
+ put(value < 0 ? value - 1 : value, s);
873
964
  run = 0;
874
965
  }
875
966
  if (ends[n] < 63)
876
- symbol(acTable, 0x00);
967
+ put(acCodes[0], acSizes[0]);
877
968
  }
969
+ writer.bits = bits;
970
+ writer.count = pending;
971
+ writer.length = length;
878
972
  }
879
973
  function magnitude(value) {
880
974
  return 32 - Math.clz32(Math.abs(value));
@@ -948,37 +1042,60 @@ function buildOptimalTable(frequencies) {
948
1042
  }
949
1043
  return { bits: bits.subarray(0, 17), values, codes, sizes };
950
1044
  }
951
- function fdct(d) {
952
- for (let p = 0; p < 64; p += 8)
953
- fdctPass(d, p, 1);
954
- for (let p = 0; p < 8; p++)
955
- fdctPass(d, p, 8);
956
- }
957
- function fdctPass(d, o, s) {
958
- const tmp0 = d[o] + d[o + 7 * s], tmp7 = d[o] - d[o + 7 * s];
959
- const tmp1 = d[o + s] + d[o + 6 * s], tmp6 = d[o + s] - d[o + 6 * s];
960
- const tmp2 = d[o + 2 * s] + d[o + 5 * s], tmp5 = d[o + 2 * s] - d[o + 5 * s];
961
- const tmp3 = d[o + 3 * s] + d[o + 4 * s], tmp4 = d[o + 3 * s] - d[o + 4 * s];
962
- let tmp10 = tmp0 + tmp3;
963
- const tmp13 = tmp0 - tmp3;
964
- let tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
965
- d[o] = tmp10 + tmp11;
966
- d[o + 4 * s] = tmp10 - tmp11;
967
- const z1 = (tmp12 + tmp13) * 0.707106781;
968
- d[o + 2 * s] = tmp13 + z1;
969
- d[o + 6 * s] = tmp13 - z1;
970
- tmp10 = tmp4 + tmp5;
971
- tmp11 = tmp5 + tmp6;
972
- tmp12 = tmp6 + tmp7;
973
- const z5 = (tmp10 - tmp12) * 0.382683433;
974
- const z2 = 0.5411961 * tmp10 + z5;
975
- const z4 = 1.306562965 * tmp12 + z5;
976
- const z3 = tmp11 * 0.707106781;
977
- const z11 = tmp7 + z3, z13 = tmp7 - z3;
978
- d[o + 5 * s] = z13 + z2;
979
- d[o + 3 * s] = z13 - z2;
980
- d[o + s] = z11 + z4;
981
- d[o + 7 * s] = z11 - z4;
1045
+ function fdct(plane, offset, stride, d) {
1046
+ const P1 = CONST_BITS - PASS1_BITS, R1 = 1 << P1 - 1;
1047
+ for (let row = 0; row < 64; row += 8, offset += stride) {
1048
+ const s0 = plane[offset] - 128, s1 = plane[offset + 1] - 128, s2 = plane[offset + 2] - 128, s3 = plane[offset + 3] - 128;
1049
+ const s4 = plane[offset + 4] - 128, s5 = plane[offset + 5] - 128, s6 = plane[offset + 6] - 128, s7 = plane[offset + 7] - 128;
1050
+ let tmp4 = s3 - s4, tmp5 = s2 - s5, tmp6 = s1 - s6, tmp7 = s0 - s7;
1051
+ const tmp0 = s0 + s7, tmp1 = s1 + s6, tmp2 = s2 + s5, tmp3 = s3 + s4;
1052
+ const tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
1053
+ d[row] = tmp10 + tmp11 << PASS1_BITS;
1054
+ d[row + 4] = tmp10 - tmp11 << PASS1_BITS;
1055
+ const z1 = (tmp12 + tmp13) * FIX_0_541196100;
1056
+ d[row + 2] = z1 + tmp13 * FIX_0_765366865 + R1 >> P1;
1057
+ d[row + 6] = z1 - tmp12 * FIX_1_847759065 + R1 >> P1;
1058
+ let o1 = tmp4 + tmp7, o2 = tmp5 + tmp6, o3 = tmp4 + tmp6, o4 = tmp5 + tmp7;
1059
+ const z5 = (o3 + o4) * FIX_1_175875602;
1060
+ tmp4 *= FIX_0_298631336;
1061
+ tmp5 *= FIX_2_053119869;
1062
+ tmp6 *= FIX_3_072711026;
1063
+ tmp7 *= FIX_1_501321110;
1064
+ o1 *= -FIX_0_899976223;
1065
+ o2 *= -FIX_2_562915447;
1066
+ o3 = o3 * -FIX_1_961570560 + z5;
1067
+ o4 = o4 * -FIX_0_390180644 + z5;
1068
+ d[row + 7] = tmp4 + o1 + o3 + R1 >> P1;
1069
+ d[row + 5] = tmp5 + o2 + o4 + R1 >> P1;
1070
+ d[row + 3] = tmp6 + o2 + o3 + R1 >> P1;
1071
+ d[row + 1] = tmp7 + o1 + o4 + R1 >> P1;
1072
+ }
1073
+ const P2 = CONST_BITS + PASS1_BITS, R2 = 1 << P2 - 1;
1074
+ for (let c = 0; c < 8; c++) {
1075
+ const s0 = d[c], s1 = d[c + 8], s2 = d[c + 16], s3 = d[c + 24], s4 = d[c + 32], s5 = d[c + 40], s6 = d[c + 48], s7 = d[c + 56];
1076
+ let tmp4 = s3 - s4, tmp5 = s2 - s5, tmp6 = s1 - s6, tmp7 = s0 - s7;
1077
+ const tmp0 = s0 + s7, tmp1 = s1 + s6, tmp2 = s2 + s5, tmp3 = s3 + s4;
1078
+ const tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
1079
+ d[c] = tmp10 + tmp11 + (1 << PASS1_BITS - 1) >> PASS1_BITS;
1080
+ d[c + 32] = tmp10 - tmp11 + (1 << PASS1_BITS - 1) >> PASS1_BITS;
1081
+ const z1 = (tmp12 + tmp13) * FIX_0_541196100;
1082
+ d[c + 16] = z1 + tmp13 * FIX_0_765366865 + R2 >> P2;
1083
+ d[c + 48] = z1 - tmp12 * FIX_1_847759065 + R2 >> P2;
1084
+ let o1 = tmp4 + tmp7, o2 = tmp5 + tmp6, o3 = tmp4 + tmp6, o4 = tmp5 + tmp7;
1085
+ const z5 = (o3 + o4) * FIX_1_175875602;
1086
+ tmp4 *= FIX_0_298631336;
1087
+ tmp5 *= FIX_2_053119869;
1088
+ tmp6 *= FIX_3_072711026;
1089
+ tmp7 *= FIX_1_501321110;
1090
+ o1 *= -FIX_0_899976223;
1091
+ o2 *= -FIX_2_562915447;
1092
+ o3 = o3 * -FIX_1_961570560 + z5;
1093
+ o4 = o4 * -FIX_0_390180644 + z5;
1094
+ d[c + 56] = tmp4 + o1 + o3 + R2 >> P2;
1095
+ d[c + 40] = tmp5 + o2 + o4 + R2 >> P2;
1096
+ d[c + 24] = tmp6 + o2 + o3 + R2 >> P2;
1097
+ d[c + 8] = tmp7 + o1 + o4 + R2 >> P2;
1098
+ }
982
1099
  }
983
1100
  class BitWriter extends ByteWriter {
984
1101
  bits = 0;
@@ -1,7 +1,9 @@
1
1
  /*!
2
2
  * WebP lossless (VP8L) bitstream, as specified in RFC 9649 ("WebP Image Format") section 3 onwards, including its
3
3
  * table of short distance codes. Copyright (c) 2024 IETF Trust and the persons identified as the document authors,
4
- * Revised BSD License (see THIRD_PARTY_NOTICES.md)
4
+ * Revised BSD License (see THIRD_PARTY_NOTICES.md). The encoder's choice of transforms follows libwebp's entropy
5
+ * analysis (src/enc/vp8l_enc.c, AnalyzeEntropy), its color transform search libwebp's (src/enc/predictor_enc.c).
6
+ * Copyright (c) 2012 Google Inc., BSD-3-Clause License
5
7
  */
6
8
  import { ByteWriter } from "../util/bytes.js";
7
9
  import { MAX_PIXELS, checkPixels } from "../util/limits.js";
@@ -1177,6 +1179,202 @@ async function writeImage(w, pixels, width, isMain, threads = null) {
1177
1179
  const subPixels = (a, b) => ((a | 0x00ff00ff) - (b & 0xff00ff00) & 0xff00ff00 | (a | 0xff00ff00) - (b & 0x00ff00ff) & 0x00ff00ff) >>> 0;
1178
1180
  const BYTE_COST = Uint8Array.from({ length: 256 }, (_, c) => c < 128 ? c : 256 - c);
1179
1181
  const residualCost = (r) => BYTE_COST[r & 255] + BYTE_COST[r >>> 8 & 255] + BYTE_COST[r >>> 16 & 255] + BYTE_COST[r >>> 24];
1182
+ function redBlueBits(p) {
1183
+ const red = new Uint32Array(256), blue = new Uint32Array(256);
1184
+ for (let i = 0; i < p.length; i++) {
1185
+ red[p[i] >> 16 & 255]++;
1186
+ blue[p[i] & 255]++;
1187
+ }
1188
+ let bits = 0;
1189
+ for (const h of [red, blue])
1190
+ for (const n of h)
1191
+ if (n)
1192
+ bits += n * Math.log2(p.length / n);
1193
+ return bits;
1194
+ }
1195
+ const slog = (v) => v ? v * Math.log2(v) : 0;
1196
+ let SLOG;
1197
+ function crossColorCost(accumulated, accumulatedSlogs, accumulatedLogs, counts, touched, n, accumulatedSum, accumulatedSlog) {
1198
+ const table = SLOG;
1199
+ let sum = accumulatedSlog, sumX = 0;
1200
+ for (let k = 0; k < n; k++) {
1201
+ const i = touched[k], x = counts[i], y = accumulated[i];
1202
+ sumX += x;
1203
+ if (x + y < table.length)
1204
+ sum += table[x] + table[x + y] - accumulatedSlogs[i];
1205
+ else {
1206
+ const t = x / y;
1207
+ sum += table[x] + x * accumulatedLogs[i] + (x + y) * (t - t * t / 2 + t * t * t / 3) * Math.LOG2E;
1208
+ }
1209
+ }
1210
+ let bias = 3 * counts[0], weight = 240;
1211
+ for (let i = 1; i < 16; i++) {
1212
+ bias += weight * (counts[i] + counts[256 - i]) / 100;
1213
+ weight *= 0.6;
1214
+ }
1215
+ return slog(sumX) + slog(sumX + accumulatedSum) - sum - bias / 10;
1216
+ }
1217
+ function colorTransform(p, width, height, bits) {
1218
+ const size = 1 << bits, blocksX = subSize(width, bits), blocksY = subSize(height, bits);
1219
+ const image = new Uint32Array(blocksX * blocksY);
1220
+ const accumulatedRed = new Uint32Array(256), accumulatedBlue = new Uint32Array(256), histo = new Uint32Array(256), touched = new Int32Array(256);
1221
+ const green = new Int32Array(size * size), red = new Int32Array(size * size), redByte = new Int32Array(size * size), blue = new Int32Array(size * size);
1222
+ const s8 = (v) => v << 24 >> 24;
1223
+ SLOG ??= Float64Array.from({ length: 65536 }, (_, v) => slog(v));
1224
+ const redSlogs = new Float64Array(256), blueSlogs = new Float64Array(256), redLogs = new Float64Array(256), blueLogs = new Float64Array(256);
1225
+ const sums = (h, slogs, logs) => {
1226
+ let total = 0, entropy = 0;
1227
+ for (let i = 0; i < 256; i++) {
1228
+ total += h[i];
1229
+ entropy += slogs[i] = slog(h[i]);
1230
+ logs[i] = h[i] ? Math.log2(h[i]) : 0;
1231
+ }
1232
+ return [total, entropy];
1233
+ };
1234
+ let prevX = [0, 0, 0], prevY = [0, 0, 0];
1235
+ for (let by = 0; by < blocksY; by++) {
1236
+ for (let bx = 0; bx < blocksX; bx++) {
1237
+ const x0 = bx * size, y0 = by * size, x1 = Math.min(width, x0 + size), y1 = Math.min(height, y0 + size);
1238
+ if (by) {
1239
+ const above = image[(by - 1) * blocksX + bx];
1240
+ prevY = [above & 255, above >> 8 & 255, above >> 16 & 255];
1241
+ }
1242
+ let count = 0;
1243
+ for (let y = y0; y < y1; y++)
1244
+ for (let i = y * width + x0 + (y & 3), end = y * width + x1; i < end; i += 4, count++) {
1245
+ const v = p[i];
1246
+ green[count] = s8(v >> 8);
1247
+ red[count] = s8(v >> 16);
1248
+ redByte[count] = v >> 16 & 255;
1249
+ blue[count] = v & 255;
1250
+ }
1251
+ const [redSum, redSlog] = sums(accumulatedRed, redSlogs, redLogs);
1252
+ const redCost = (gtr) => {
1253
+ const m = s8(gtr);
1254
+ let n = 0;
1255
+ for (let k = 0; k < count; k++) {
1256
+ const v = redByte[k] - (m * green[k] >> 5) & 255;
1257
+ if (!histo[v]++)
1258
+ touched[n++] = v;
1259
+ }
1260
+ let cost = crossColorCost(accumulatedRed, redSlogs, redLogs, histo, touched, n, redSum, redSlog);
1261
+ for (let k = 0; k < n; k++)
1262
+ histo[touched[k]] = 0;
1263
+ if ((gtr & 255) === prevX[0])
1264
+ cost -= 3;
1265
+ if ((gtr & 255) === prevY[0])
1266
+ cost -= 3;
1267
+ if (gtr === 0)
1268
+ cost -= 3;
1269
+ return cost;
1270
+ };
1271
+ let gtr = 0, best = redCost(0);
1272
+ for (let iter = 0; iter < 6; iter++) {
1273
+ const step = 32 >> iter;
1274
+ for (const offset of [-step, step]) {
1275
+ const cost = redCost(gtr + offset);
1276
+ if (cost < best)
1277
+ [best, gtr] = [cost, gtr + offset];
1278
+ }
1279
+ }
1280
+ const [blueSum, blueSlog] = sums(accumulatedBlue, blueSlogs, blueLogs);
1281
+ const blueCost = (gtb, rtb) => {
1282
+ const mg = s8(gtb), mr = s8(rtb);
1283
+ let n = 0;
1284
+ for (let k = 0; k < count; k++) {
1285
+ const v = blue[k] - (mg * green[k] >> 5) - (mr * red[k] >> 5) & 255;
1286
+ if (!histo[v]++)
1287
+ touched[n++] = v;
1288
+ }
1289
+ let cost = crossColorCost(accumulatedBlue, blueSlogs, blueLogs, histo, touched, n, blueSum, blueSlog);
1290
+ for (let k = 0; k < n; k++)
1291
+ histo[touched[k]] = 0;
1292
+ if ((gtb & 255) === prevX[1])
1293
+ cost -= 3;
1294
+ if ((gtb & 255) === prevY[1])
1295
+ cost -= 3;
1296
+ if ((rtb & 255) === prevX[2])
1297
+ cost -= 3;
1298
+ if ((rtb & 255) === prevY[2])
1299
+ cost -= 3;
1300
+ if (gtb === 0)
1301
+ cost -= 3;
1302
+ if (rtb === 0)
1303
+ cost -= 3;
1304
+ return cost;
1305
+ };
1306
+ let gtb = 0, rtb = 0;
1307
+ best = blueCost(0, 0);
1308
+ for (const step of [16, 8, 4]) {
1309
+ for (const [dg, dr] of [[0, -1], [0, 1], [-1, 0], [1, 0], [-1, -1], [-1, 1], [1, -1], [1, 1]]) {
1310
+ const cost = blueCost(gtb + dg * step, rtb + dr * step);
1311
+ if (cost < best)
1312
+ [best, gtb, rtb] = [cost, gtb + dg * step, rtb + dr * step];
1313
+ }
1314
+ }
1315
+ prevX = [gtr & 255, gtb & 255, rtb & 255];
1316
+ image[by * blocksX + bx] = (0xff000000 | prevX[2] << 16 | prevX[1] << 8 | prevX[0]) >>> 0;
1317
+ const mgr = s8(gtr), mgb = s8(gtb), mrb = s8(rtb);
1318
+ for (let y = y0; y < y1; y++)
1319
+ for (let i = y * width + x0, end = y * width + x1; i < end; i++) {
1320
+ const v = p[i], g = s8(v >> 8), rs = s8(v >> 16);
1321
+ const r = (v >> 16) - (mgr * g >> 5) & 255, b = v - (mgb * g >> 5) - (mrb * rs >> 5) & 255;
1322
+ p[i] = (v & 0xff00ff00 | r << 16 | b) >>> 0;
1323
+ }
1324
+ for (let y = y0; y < y1; y++)
1325
+ for (let i = y * width + x0, end = y * width + x1; i < end; i++) {
1326
+ const v = p[i];
1327
+ if (i >= 2 && v === p[i - 2] && v === p[i - 1])
1328
+ continue;
1329
+ if (i >= width + 2 && p[i - 2] === p[i - width - 2] && p[i - 1] === p[i - width - 1] && v === p[i - width])
1330
+ continue;
1331
+ accumulatedRed[v >> 16 & 255]++;
1332
+ accumulatedBlue[v & 255]++;
1333
+ }
1334
+ }
1335
+ }
1336
+ return image;
1337
+ }
1338
+ function analyze(argb, width, height, bits) {
1339
+ const h = Array.from({ length: 12 }, () => new Uint32Array(256));
1340
+ let prev = argb[0];
1341
+ for (let i = 0; i < argb.length; i++) {
1342
+ const p = argb[i], d = subPixels(p, prev);
1343
+ prev = p;
1344
+ if (d === 0 || (i >= width && p === argb[i - width]))
1345
+ continue;
1346
+ h[0][p >>> 24]++;
1347
+ h[1][p >> 16 & 255]++;
1348
+ h[2][p >> 8 & 255]++;
1349
+ h[3][p & 255]++;
1350
+ h[4][d >>> 24]++;
1351
+ h[5][d >> 16 & 255]++;
1352
+ h[6][d >> 8 & 255]++;
1353
+ h[7][d & 255]++;
1354
+ h[8][(p >> 16) - (p >> 8) & 255]++;
1355
+ h[9][p - (p >> 8) & 255]++;
1356
+ h[10][(d >> 16) - (d >> 8) & 255]++;
1357
+ h[11][d - (d >> 8) & 255]++;
1358
+ }
1359
+ for (const k of [4, 5, 6, 7, 10, 11])
1360
+ h[k][0]++;
1361
+ const bitsOf = (counts) => {
1362
+ let total = 0, sum = 0;
1363
+ for (const n of counts)
1364
+ total += n;
1365
+ for (const n of counts)
1366
+ if (n)
1367
+ sum += n * Math.log2(total / n);
1368
+ return sum;
1369
+ };
1370
+ const e = h.map(bitsOf), blocks = subSize(width, bits) * subSize(height, bits);
1371
+ const entropy = [
1372
+ e[0] + e[1] + e[2] + e[3], e[4] + e[5] + e[6] + e[7] + blocks * Math.log2(14),
1373
+ e[0] + e[8] + e[2] + e[9], e[4] + e[10] + e[6] + e[11] + blocks * Math.log2(24),
1374
+ ];
1375
+ const best = entropy.indexOf(Math.min(...entropy));
1376
+ return { predict: best === 1 || best === 3, subtractGreen: best >= 2 };
1377
+ }
1180
1378
  async function applyPredictor(p, width, height, bits, threads) {
1181
1379
  const blocksX = subSize(width, bits), blocksY = subSize(height, bits);
1182
1380
  const task = {
@@ -1283,7 +1481,8 @@ async function encodeWith(argb, width, height, colors, threads) {
1283
1481
  for (let i = 0; i < pixels.length && !redBlue; i++)
1284
1482
  if (pixels[i] & 0x00ff00ff)
1285
1483
  redBlue = true;
1286
- if (redBlue) {
1484
+ const { predict, subtractGreen } = analyze(argb, width, height, 4);
1485
+ if (redBlue && subtractGreen) {
1287
1486
  w.write(1, 1);
1288
1487
  w.write(2, 2);
1289
1488
  for (let i = 0; i < pixels.length; i++) {
@@ -1292,11 +1491,25 @@ async function encodeWith(argb, width, height, colors, threads) {
1292
1491
  }
1293
1492
  }
1294
1493
  const bits = 4;
1295
- w.write(1, 1);
1296
- w.write(0, 2);
1297
- w.write(bits - 2, 3);
1298
- const modes = await applyPredictor(pixels, width, height, bits, threads);
1299
- await writeImage(w, modes, subSize(width, bits), false);
1494
+ if (predict) {
1495
+ w.write(1, 1);
1496
+ w.write(0, 2);
1497
+ w.write(bits - 2, 3);
1498
+ const modes = await applyPredictor(pixels, width, height, bits, threads);
1499
+ await writeImage(w, modes, subSize(width, bits), false);
1500
+ if (redBlue) {
1501
+ const colorBits = 5, before = pixels.slice(), multipliers = colorTransform(pixels, width, height, colorBits);
1502
+ const changed = multipliers.reduce((n, m) => n + (m !== 0xff000000 ? 1 : 0), 0);
1503
+ if (changed && redBlueBits(pixels) + 12 * changed >= redBlueBits(before))
1504
+ pixels.set(before);
1505
+ else if (changed) {
1506
+ w.write(1, 1);
1507
+ w.write(1, 2);
1508
+ w.write(colorBits - 2, 3);
1509
+ await writeImage(w, multipliers, subSize(width, colorBits), false);
1510
+ }
1511
+ }
1512
+ }
1300
1513
  }
1301
1514
  w.write(0, 1);
1302
1515
  await writeImage(w, pixels, codedWidth, true, threads);
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '3.12.0';
1
+ export const VERSION = '3.12.2';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "imagescript",
3
- "version": "3.12.0",
4
- "description": "zero-dependency javascript image manipulation",
3
+ "version": "3.12.2",
4
+ "description": "Pure TypeScript image processing that runs everywhere",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "exports": {
@@ -39,6 +39,14 @@
39
39
  "image",
40
40
  "image processing",
41
41
  "image manipulation",
42
+ "typescript",
43
+ "zero-dependency",
44
+ "browser",
45
+ "deno",
46
+ "bun",
47
+ "edge",
48
+ "cloudflare-workers",
49
+ "serverless",
42
50
  "png",
43
51
  "jpeg",
44
52
  "jpg",
@@ -79,7 +87,7 @@
79
87
  "bugs": {
80
88
  "url": "https://github.com/matmen/ImageScript/issues"
81
89
  },
82
- "homepage": "https://github.com/matmen/ImageScript#readme",
90
+ "homepage": "https://imagescript.dev/",
83
91
  "engines": {
84
92
  "node": ">=22.13.0"
85
93
  },