imagescript 3.7.0 → 3.8.1

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.
@@ -0,0 +1,150 @@
1
+ /*!
2
+ * libwebp's sharp RGB to YUV 4:2:0 conversion (sharpyuv/sharpyuv.c, sharpyuv_dsp.c, sharpyuv_gamma.c), ported for 8
3
+ * bit RGB to 8 bit YUV with the WebP matrix: luma and chroma are chosen iteratively so that the picture upsampled
4
+ * again matches the original better, sharper at color edges than averaging the chroma. Copyright (c) 2022 Google
5
+ * Inc., BSD-3-Clause License (see THIRD_PARTY_NOTICES.md)
6
+ */
7
+ const ITERATIONS = 4;
8
+ const SHIFT = 2, BITS = 10, MAX = (1 << BITS) - 1;
9
+ const TO_LINEAR = new Uint32Array(1024 + 2), FROM_LINEAR = new Uint32Array(512 + 2);
10
+ {
11
+ const a = 0.09929682680944, thresh = 0.018053968510807, gamma = 1 / 0.45;
12
+ for (let v = 0; v <= 1024; v++) {
13
+ const g = v / 1024;
14
+ TO_LINEAR[v] = Math.trunc((g <= thresh * 4.5 ? g / 4.5 : Math.pow((g + a) / (1 + a), gamma)) * 65536 + 0.5);
15
+ }
16
+ TO_LINEAR[1025] = TO_LINEAR[1024];
17
+ for (let v = 0; v <= 512; v++) {
18
+ const g = v / 512;
19
+ FROM_LINEAR[v] = Math.trunc(65536 * (g <= thresh ? 4.5 * g : (1 + a) * Math.pow(g, 1 / gamma) - a) + 0.5);
20
+ }
21
+ FROM_LINEAR[513] = FROM_LINEAR[512];
22
+ }
23
+ const toLinear = (v) => TO_LINEAR[v];
24
+ function fromLinear(value) {
25
+ const pos = value >>> 7, x = value - (pos << 7);
26
+ const v0 = FROM_LINEAR[pos] >>> 6, v1 = FROM_LINEAR[pos + 1] >>> 6;
27
+ return v0 + (((v1 - v0) * x + 64) >>> 7);
28
+ }
29
+ const gray = (r, g, b) => Math.floor((13933 * r + 46871 * g + 4732 * b + 32768) / 65536);
30
+ const clip = (v) => v < 0 ? 0 : v > MAX ? MAX : v;
31
+ function updateW(src, s, dst, d, w) {
32
+ for (let i = 0; i < w; i++)
33
+ dst[d + i] = fromLinear(gray(toLinear(src[s + i]), toLinear(src[s + w + i]), toLinear(src[s + 2 * w + i])));
34
+ }
35
+ const scaleDown = (a, b, c, d) => fromLinear((toLinear(a) + toLinear(b) + toLinear(c) + toLinear(d) + 2) >> 2);
36
+ function updateChroma(src, s1, s2, dst, d, uvWidth) {
37
+ const w = 2 * uvWidth;
38
+ for (let i = 0; i < uvWidth; i++) {
39
+ const o = 2 * i;
40
+ const r = scaleDown(src[s1 + o], src[s1 + o + 1], src[s2 + o], src[s2 + o + 1]);
41
+ const g = scaleDown(src[s1 + w + o], src[s1 + w + o + 1], src[s2 + w + o], src[s2 + w + o + 1]);
42
+ const b = scaleDown(src[s1 + 2 * w + o], src[s1 + 2 * w + o + 1], src[s2 + 2 * w + o], src[s2 + 2 * w + o + 1]);
43
+ const W = gray(r, g, b);
44
+ dst[d + i] = r - W;
45
+ dst[d + uvWidth + i] = g - W;
46
+ dst[d + 2 * uvWidth + i] = b - W;
47
+ }
48
+ }
49
+ function storeGray(rgb, s, y, d, w) {
50
+ for (let i = 0; i < w; i++)
51
+ y[d + i] = gray(rgb[s + i], rgb[s + w + i], rgb[s + 2 * w + i]);
52
+ }
53
+ function importRow(rgba, o, width, w, dst, d) {
54
+ for (let i = 0; i < width; i++, o += 4) {
55
+ dst[d + i] = rgba[o] << SHIFT;
56
+ dst[d + w + i] = rgba[o + 1] << SHIFT;
57
+ dst[d + 2 * w + i] = rgba[o + 2] << SHIFT;
58
+ }
59
+ if (width & 1)
60
+ for (let c = 0; c < 3; c++)
61
+ dst[d + c * w + width] = dst[d + c * w + width - 1];
62
+ }
63
+ function interpolateTwoRows(bestY, y, uv, prev, cur, next, w, out, o1, o2) {
64
+ const uvWidth = w >> 1, len = (w - 1) >> 1;
65
+ const filter2 = (a, b, w0) => clip(((a * 3 + b + 2) >> 2) + w0);
66
+ const filterRow = (a, b, by, o) => {
67
+ for (let i = 0; i < len; i++, a++, b++) {
68
+ const v0 = (uv[a] * 9 + uv[a + 1] * 3 + uv[b] * 3 + uv[b + 1] + 8) >> 4;
69
+ const v1 = (uv[a + 1] * 9 + uv[a] * 3 + uv[b + 1] * 3 + uv[b] + 8) >> 4;
70
+ out[o + 2 * i] = clip(bestY[by + 2 * i] + v0);
71
+ out[o + 2 * i + 1] = clip(bestY[by + 2 * i + 1] + v1);
72
+ }
73
+ };
74
+ for (let k = 0; k < 3; k++) {
75
+ out[o1] = filter2(uv[cur], uv[prev], bestY[y]);
76
+ out[o2] = filter2(uv[cur], uv[next], bestY[y + w]);
77
+ filterRow(cur, prev, y + 1, o1 + 1);
78
+ filterRow(cur, next, y + w + 1, o2 + 1);
79
+ if (!(w & 1)) {
80
+ out[o1 + w - 1] = filter2(uv[cur + uvWidth - 1], uv[prev + uvWidth - 1], bestY[y + w - 1]);
81
+ out[o2 + w - 1] = filter2(uv[cur + uvWidth - 1], uv[next + uvWidth - 1], bestY[y + 2 * w - 1]);
82
+ }
83
+ o1 += w;
84
+ o2 += w;
85
+ prev += uvWidth;
86
+ cur += uvWidth;
87
+ next += uvWidth;
88
+ }
89
+ }
90
+ const yuv = (r, g, b, c0, c1, c2, offset) => (c0 * r + c1 * g + c2 * b + (offset << 18) + (1 << 17)) >> 18;
91
+ const clip8 = (v) => v < 0 ? 0 : v > 255 ? 255 : v;
92
+ export function sharpYUV(rgba, width, height, y, u, v) {
93
+ const w = (width + 1) & ~1, h = (height + 1) & ~1, uvWidth = w >> 1, uvHeight = h >> 1;
94
+ const tmp = new Uint16Array(w * 6), bestY = new Uint16Array(w * h), targetY = new Uint16Array(w * h), bestRGBY = new Uint16Array(w * 2);
95
+ const bestUV = new Int16Array(uvWidth * 3 * uvHeight), targetUV = new Int16Array(uvWidth * 3 * uvHeight), bestRGBUV = new Int16Array(uvWidth * 3);
96
+ const stride = width * 4;
97
+ for (let j = 0, uvRow = 0; j < height; j += 2, uvRow += 3 * uvWidth) {
98
+ importRow(rgba, j * stride, width, w, tmp, 0);
99
+ if (j < height - 1)
100
+ importRow(rgba, (j + 1) * stride, width, w, tmp, 3 * w);
101
+ else
102
+ tmp.copyWithin(3 * w, 0, 3 * w);
103
+ storeGray(tmp, 0, bestY, j * w, w);
104
+ storeGray(tmp, 3 * w, bestY, (j + 1) * w, w);
105
+ updateW(tmp, 0, targetY, j * w, w);
106
+ updateW(tmp, 3 * w, targetY, (j + 1) * w, w);
107
+ updateChroma(tmp, 0, 3 * w, targetUV, uvRow, uvWidth);
108
+ bestUV.set(targetUV.subarray(uvRow, uvRow + 3 * uvWidth), uvRow);
109
+ }
110
+ const threshold = Math.trunc(3 * w * h);
111
+ let previousSum = Infinity;
112
+ for (let iteration = 0; iteration < ITERATIONS; iteration++) {
113
+ let cur = 0, prev = 0, sum = 0;
114
+ for (let j = 0; j < h; j += 2) {
115
+ const next = cur + (j < h - 2 ? 3 * uvWidth : 0);
116
+ interpolateTwoRows(bestY, j * w, bestUV, prev, cur, next, w, tmp, 0, 3 * w);
117
+ prev = cur;
118
+ cur = next;
119
+ updateW(tmp, 0, bestRGBY, 0, w);
120
+ updateW(tmp, 3 * w, bestRGBY, w, w);
121
+ updateChroma(tmp, 0, 3 * w, bestRGBUV, 0, uvWidth);
122
+ for (let i = 0; i < 2 * w; i++) {
123
+ const diff = targetY[j * w + i] - bestRGBY[i];
124
+ bestY[j * w + i] = clip(bestY[j * w + i] + diff);
125
+ sum += Math.abs(diff);
126
+ }
127
+ const uvRow = (j >> 1) * 3 * uvWidth;
128
+ for (let i = 0; i < 3 * uvWidth; i++)
129
+ bestUV[uvRow + i] += targetUV[uvRow + i] - bestRGBUV[i];
130
+ }
131
+ if (iteration > 0 && (sum < threshold || sum > previousSum))
132
+ break;
133
+ previousSum = sum;
134
+ }
135
+ for (let j = 0; j < height; j++) {
136
+ const uvRow = (j >> 1) * 3 * uvWidth;
137
+ for (let i = 0; i < width; i++) {
138
+ const W = bestY[j * w + i], o = uvRow + (i >> 1);
139
+ const r = bestUV[o] + W, g = bestUV[o + uvWidth] + W, b = bestUV[o + 2 * uvWidth] + W;
140
+ y[j * width + i] = clip8(yuv(r, g, b, 16839, 33059, 6420, 16));
141
+ }
142
+ }
143
+ for (let j = 0; j < uvHeight; j++)
144
+ for (let i = 0; i < uvWidth; i++) {
145
+ const o = j * 3 * uvWidth + i;
146
+ const r = bestUV[o], g = bestUV[o + uvWidth], b = bestUV[o + 2 * uvWidth];
147
+ u[j * uvWidth + i] = clip8(yuv(r, g, b, -9719, -19081, 28800, 128));
148
+ v[j * uvWidth + i] = clip8(yuv(r, g, b, 28800, -24116, -4684, 128));
149
+ }
150
+ }
@@ -1,4 +1,5 @@
1
1
  import { littleEndian } from "../util/alpha.js";
2
+ import { sharpYUV } from "./sharpyuv.js";
2
3
  export const BPS = 32;
3
4
  export const Y_OFF = 0, U_OFF = 16, V_OFF = 24;
4
5
  export const YUV_SIZE = BPS * 16, PRED_SIZE = 56 * BPS;
@@ -43,7 +44,7 @@ function weighted(rgba, o, step, next, total) {
43
44
  const sum = rgba[a] * g[rgba[o]] + rgba[a + step] * g[rgba[o + step]] + rgba[a + next] * g[rgba[o + next]] + rgba[a + next + step] * g[rgba[o + next + step]];
44
45
  return linearToGamma((sum * INV_ALPHA[total]) >>> 17, 0);
45
46
  }
46
- export function rgbaToYUV(rgba, width, height) {
47
+ export function rgbaToYUV(rgba, width, height, sharp = false) {
47
48
  const uvWidth = (width + 1) >> 1, uvHeight = (height + 1) >> 1;
48
49
  const y = new Uint8Array(width * height), u = new Uint8Array(uvWidth * uvHeight), v = new Uint8Array(uvWidth * uvHeight);
49
50
  let hasAlpha = false;
@@ -57,6 +58,13 @@ export function rgbaToYUV(rgba, width, height) {
57
58
  if (a)
58
59
  for (let j = 0; j < height; j++)
59
60
  alphaRow(rgba, j * stride, a, j * width, width);
61
+ if (sharp && width >= 4 && height >= 4) {
62
+ sharpYUV(rgba, width, height, y, u, v);
63
+ const picture = { width, height, y, u, v, a, uvStride: uvWidth };
64
+ if (a)
65
+ cleanupTransparentArea(picture);
66
+ return picture;
67
+ }
60
68
  const words = littleEndian && rgba.byteOffset % 4 === 0 ? new Uint32Array(rgba.buffer, rgba.byteOffset, width * height) : null;
61
69
  for (let j = 0; j < uvHeight; j++) {
62
70
  const row = 2 * j * stride;
@@ -1,5 +1,6 @@
1
1
  import { KF_BMODE_PROBS, COEFF_UPDATE_PROBS, DEFAULT_COEFF_PROBS, DC_QLOOKUP, AC_QLOOKUP, PCAT } from "./vp8-tables.js";
2
2
  import { MAX_PIXELS, checkPixels } from "../util/limits.js";
3
+ import { littleEndian } from "../util/alpha.js";
3
4
  class BoolDecoder {
4
5
  data;
5
6
  pos;
@@ -661,43 +662,46 @@ function loopFilter(h, Y, U, V, ys, cs, mbw, mbh, segments, inner, bpred) {
661
662
  }
662
663
  const multHi = (v, coeff) => v * coeff >> 8;
663
664
  const clip8 = (v) => (v & ~16383) === 0 ? v >> 6 : v < 0 ? 0 : 255;
664
- function yuvToRGBA(y, u, v, out, o) {
665
+ function yuvToWord(y, u, v) {
665
666
  const yy = multHi(y, 19077);
666
- out[o] = clip8(yy + multHi(v, 26149) - 14234);
667
- out[o + 1] = clip8(yy - multHi(u, 6419) - multHi(v, 13320) + 8708);
668
- out[o + 2] = clip8(yy + multHi(u, 33050) - 17685);
669
- out[o + 3] = 255;
667
+ return (clip8(yy + multHi(v, 26149) - 14234) | clip8(yy - multHi(u, 6419) - multHi(v, 13320) + 8708) << 8
668
+ | clip8(yy + multHi(u, 33050) - 17685) << 16 | 0xff000000) >>> 0;
670
669
  }
671
670
  function toRGBA(Y, U, V, ys, cs, width, height) {
672
- const out = new Uint8Array(width * height * 4);
671
+ const out = new Uint32Array(width * height);
673
672
  const yRow = (y) => (y + 1) * ys + 1;
674
673
  const cRow = (y) => (y + 1) * cs + 1;
675
674
  const lastChroma = (height + 1 >> 1) - 1;
676
675
  upsamplePair(Y, U, V, yRow(0), -1, cRow(0), cRow(0), out, 0, -1, width);
677
676
  for (let y = 1; y + 1 < height; y += 2) {
678
677
  const k = y + 1 >> 1;
679
- upsamplePair(Y, U, V, yRow(y), yRow(y + 1), cRow(k - 1), cRow(k), out, y * width * 4, (y + 1) * width * 4, width);
678
+ upsamplePair(Y, U, V, yRow(y), yRow(y + 1), cRow(k - 1), cRow(k), out, y * width, (y + 1) * width, width);
680
679
  }
681
680
  if (!(height & 1))
682
- upsamplePair(Y, U, V, yRow(height - 1), -1, cRow(lastChroma), cRow(lastChroma), out, (height - 1) * width * 4, -1, width);
683
- return out;
681
+ upsamplePair(Y, U, V, yRow(height - 1), -1, cRow(lastChroma), cRow(lastChroma), out, (height - 1) * width, -1, width);
682
+ if (!littleEndian)
683
+ for (let i = 0; i < out.length; i++) {
684
+ const w = out[i];
685
+ out[i] = (w << 24 | (w & 0xff00) << 8 | w >>> 8 & 0xff00 | w >>> 24) >>> 0;
686
+ }
687
+ return new Uint8Array(out.buffer);
684
688
  }
685
689
  function upsamplePair(Y, U, V, topY, bottomY, topC, curC, out, topOut, bottomOut, width) {
686
690
  let tlu = U[topC], tlv = V[topC], lu = U[curC], lv = V[curC];
687
- yuvToRGBA(Y[topY], 3 * tlu + lu + 2 >> 2, 3 * tlv + lv + 2 >> 2, out, topOut);
691
+ out[topOut] = yuvToWord(Y[topY], 3 * tlu + lu + 2 >> 2, 3 * tlv + lv + 2 >> 2);
688
692
  if (bottomY >= 0)
689
- yuvToRGBA(Y[bottomY], 3 * lu + tlu + 2 >> 2, 3 * lv + tlv + 2 >> 2, out, bottomOut);
693
+ out[bottomOut] = yuvToWord(Y[bottomY], 3 * lu + tlu + 2 >> 2, 3 * lv + tlv + 2 >> 2);
690
694
  const pairs = width - 1 >> 1;
691
695
  for (let x = 1; x <= pairs; x++) {
692
696
  const tu = U[topC + x], tv = V[topC + x], u = U[curC + x], v = V[curC + x];
693
697
  const avgU = tlu + tu + lu + u + 8, avgV = tlv + tv + lv + v + 8;
694
698
  const d12u = avgU + 2 * (tu + lu) >> 3, d03u = avgU + 2 * (tlu + u) >> 3;
695
699
  const d12v = avgV + 2 * (tv + lv) >> 3, d03v = avgV + 2 * (tlv + v) >> 3;
696
- yuvToRGBA(Y[topY + 2 * x - 1], d12u + tlu >> 1, d12v + tlv >> 1, out, topOut + (2 * x - 1) * 4);
697
- yuvToRGBA(Y[topY + 2 * x], d03u + tu >> 1, d03v + tv >> 1, out, topOut + 2 * x * 4);
700
+ out[topOut + 2 * x - 1] = yuvToWord(Y[topY + 2 * x - 1], d12u + tlu >> 1, d12v + tlv >> 1);
701
+ out[topOut + 2 * x] = yuvToWord(Y[topY + 2 * x], d03u + tu >> 1, d03v + tv >> 1);
698
702
  if (bottomY >= 0) {
699
- yuvToRGBA(Y[bottomY + 2 * x - 1], d03u + lu >> 1, d03v + lv >> 1, out, bottomOut + (2 * x - 1) * 4);
700
- yuvToRGBA(Y[bottomY + 2 * x], d12u + u >> 1, d12v + v >> 1, out, bottomOut + 2 * x * 4);
703
+ out[bottomOut + 2 * x - 1] = yuvToWord(Y[bottomY + 2 * x - 1], d03u + lu >> 1, d03v + lv >> 1);
704
+ out[bottomOut + 2 * x] = yuvToWord(Y[bottomY + 2 * x], d12u + u >> 1, d12v + v >> 1);
701
705
  }
702
706
  tlu = tu;
703
707
  tlv = tv;
@@ -706,8 +710,8 @@ function upsamplePair(Y, U, V, topY, bottomY, topC, curC, out, topOut, bottomOut
706
710
  }
707
711
  if (!(width & 1)) {
708
712
  const x = width - 1;
709
- yuvToRGBA(Y[topY + x], 3 * tlu + lu + 2 >> 2, 3 * tlv + lv + 2 >> 2, out, topOut + x * 4);
713
+ out[topOut + x] = yuvToWord(Y[topY + x], 3 * tlu + lu + 2 >> 2, 3 * tlv + lv + 2 >> 2);
710
714
  if (bottomY >= 0)
711
- yuvToRGBA(Y[bottomY + x], 3 * lu + tlu + 2 >> 2, 3 * lv + tlv + 2 >> 2, out, bottomOut + x * 4);
715
+ out[bottomOut + x] = yuvToWord(Y[bottomY + x], 3 * lu + tlu + 2 >> 2, 3 * lv + tlv + 2 >> 2);
712
716
  }
713
717
  }
@@ -719,7 +719,7 @@ function writeCode(w, counts) {
719
719
  else if (t === 18)
720
720
  w.write(extras[i], 7);
721
721
  }
722
- return code;
722
+ return used.length === 1 ? { lengths: code.lengths, codes: new Uint16Array(0) } : code;
723
723
  }
724
724
  function prefixEncode(value) {
725
725
  const d = value - 1;
@@ -268,8 +268,8 @@ export function encode(rgba, width, height, exif) {
268
268
  set24(vp8x, 7, height - 1);
269
269
  return riff([riffChunk('VP8X', vp8x), bitstream, riffChunk('EXIF', exif)]);
270
270
  }
271
- export function encodeLossy(rgba, width, height, quality, exif, method = 4) {
272
- const { alpha, chunks } = lossyChunks(rgba, width, height, quality, method);
271
+ export function encodeLossy(rgba, width, height, quality, exif, method = 4, sharp = false) {
272
+ const { alpha, chunks } = lossyChunks(rgba, width, height, quality, method, sharp);
273
273
  if (!alpha && !exif)
274
274
  return riff(chunks);
275
275
  const vp8x = new Uint8Array(10);
@@ -278,10 +278,10 @@ export function encodeLossy(rgba, width, height, quality, exif, method = 4) {
278
278
  set24(vp8x, 7, height - 1);
279
279
  return riff([riffChunk('VP8X', vp8x), ...chunks, ...exif ? [riffChunk('EXIF', exif)] : []]);
280
280
  }
281
- function lossyChunks(rgba, width, height, quality, method) {
281
+ function lossyChunks(rgba, width, height, quality, method, sharp = false) {
282
282
  if (width > 16383 || height > 16383)
283
283
  throw new RangeError('WebP: lossy images can be at most 16383 pixels wide and high');
284
- const picture = rgbaToYUV(rgba, width, height);
284
+ const picture = rgbaToYUV(rgba, width, height, sharp);
285
285
  const frame = encodeVP8(picture, quality, method);
286
286
  const padded = new Uint8Array(frame.length + (frame.length & 1));
287
287
  padded.set(frame);
@@ -290,14 +290,41 @@ function lossyChunks(rgba, width, height, quality, method) {
290
290
  chunks.unshift(riffChunk('ALPH', encodeAlpha(picture.a, width, height, method)));
291
291
  return { alpha: !!picture.a, chunks };
292
292
  }
293
- export function encodeAnimation(frames, width, height, plays, exif, quality, method = 4) {
293
+ export function lossyTolerance(quality) {
294
+ const value = Math.sqrt(quality / 100);
295
+ return Math.max(1, Math.round(31 * (1 - value) + value));
296
+ }
297
+ export function encodeAnimation(frames, width, height, plays, exif, quality, method = 4, sharp = false) {
294
298
  if (!frames.length)
295
299
  throw new Error('WebP: an animation needs at least one frame');
296
300
  if (width > 1 << 24 || height > 1 << 24)
297
301
  throw new RangeError('WebP: canvas too large');
298
- const first = frames[0];
299
- const alpha = first.x > 0 || first.y > 0 || first.width < width || first.height < height
300
- || frames.some(f => f.dispose || hasAlpha(f.pixels));
302
+ let alpha = false;
303
+ for (const [i, f] of frames.entries())
304
+ alpha ||= needsAlpha(f, i === 0, width, height);
305
+ return animationFile(frames.map(f => frameChunk(f, quality, method, sharp)), width, height, plays, alpha, exif);
306
+ }
307
+ export function needsAlpha(f, first, width, height) {
308
+ return (first && (f.x > 0 || f.y > 0 || f.width < width || f.height < height)) || f.dispose || hasAlpha(f.pixels);
309
+ }
310
+ export function frameChunk(f, quality, method = 4, sharp = false) {
311
+ if (f.x & 1 || f.y & 1)
312
+ throw new RangeError('WebP: frame offsets have to be even');
313
+ const bitstream = quality === undefined ? riffChunk('VP8L', vp8l.encode(toARGB(f.pixels, f.width * f.height), f.width, f.height))
314
+ : concat(lossyChunks(f.pixels, f.width, f.height, quality, method, sharp).chunks);
315
+ const header = new Uint8Array(16);
316
+ set24(header, 0, f.x >> 1);
317
+ set24(header, 3, f.y >> 1);
318
+ set24(header, 6, f.width - 1);
319
+ set24(header, 9, f.height - 1);
320
+ set24(header, 12, Math.min(0xffffff, Math.max(0, Math.round(f.duration))));
321
+ header[15] = (f.blend === false ? 2 : 0) | (f.dispose ? 1 : 0);
322
+ const body = new Uint8Array(16 + bitstream.length);
323
+ body.set(header);
324
+ body.set(bitstream, 16);
325
+ return riffChunk('ANMF', body);
326
+ }
327
+ export function animationFile(frames, width, height, plays, alpha, exif) {
301
328
  const vp8x = new Uint8Array(10);
302
329
  vp8x[0] = 2 | (alpha ? 16 : 0) | (exif ? 8 : 0);
303
330
  set24(vp8x, 4, width - 1);
@@ -305,24 +332,7 @@ export function encodeAnimation(frames, width, height, plays, exif, quality, met
305
332
  const anim = new Uint8Array(6);
306
333
  anim[4] = plays & 255;
307
334
  anim[5] = plays >> 8 & 255;
308
- const chunks = [riffChunk('VP8X', vp8x), riffChunk('ANIM', anim)];
309
- for (const f of frames) {
310
- if (f.x & 1 || f.y & 1)
311
- throw new RangeError('WebP: frame offsets have to be even');
312
- const bitstream = quality === undefined ? riffChunk('VP8L', vp8l.encode(toARGB(f.pixels, f.width * f.height), f.width, f.height))
313
- : concat(lossyChunks(f.pixels, f.width, f.height, quality, method).chunks);
314
- const header = new Uint8Array(16);
315
- set24(header, 0, f.x >> 1);
316
- set24(header, 3, f.y >> 1);
317
- set24(header, 6, f.width - 1);
318
- set24(header, 9, f.height - 1);
319
- set24(header, 12, Math.min(0xffffff, Math.max(0, Math.round(f.duration))));
320
- header[15] = (f.blend === false ? 2 : 0) | (f.dispose ? 1 : 0);
321
- const body = new Uint8Array(16 + bitstream.length);
322
- body.set(header);
323
- body.set(bitstream, 16);
324
- chunks.push(riffChunk('ANMF', body));
325
- }
335
+ const chunks = [riffChunk('VP8X', vp8x), riffChunk('ANIM', anim), ...frames];
326
336
  if (exif)
327
337
  chunks.push(riffChunk('EXIF', exif));
328
338
  return riff(chunks);
@@ -553,6 +553,26 @@ export function decompress(data, limit) {
553
553
  throw new Error('zlib: preset dictionaries are not supported');
554
554
  return inflate(data.subarray(2), new u8(limit));
555
555
  }
556
+ export function gunzip(data, limit) {
557
+ if (data.length < 18 || data[0] !== 0x1f || data[1] !== 0x8b || data[2] !== 8)
558
+ throw new Error('gzip: invalid header');
559
+ const flags = data[3];
560
+ let o = 10;
561
+ if (flags & 4)
562
+ o += 2 + (data[o] | data[o + 1] << 8);
563
+ if (flags & 8)
564
+ while (o < data.length && data[o++])
565
+ ;
566
+ if (flags & 16)
567
+ while (o < data.length && data[o++])
568
+ ;
569
+ if (flags & 2)
570
+ o += 2;
571
+ const end = data.length - 4, size = (data[end] | data[end + 1] << 8 | data[end + 2] << 16 | data[end + 3] << 24) >>> 0;
572
+ if (o > end - 4 || size > limit)
573
+ throw new Error('gzip: invalid or too large');
574
+ return inflate(data.subarray(o, end - 4), new u8(size));
575
+ }
556
576
  const { process: runtime, CompressionStream: NativeCompression, DecompressionStream: NativeDecompression, Blob: NativeBlob } = globalThis;
557
577
  export const nodeZlib = (() => {
558
578
  try {
package/dist/image.d.ts CHANGED
@@ -79,6 +79,13 @@ export interface WebPEncodeOptions {
79
79
  * quantized values. Default: `2`: about a quarter of the time of 4 (cwebp's default) for files about 5% larger
80
80
  */
81
81
  effort?: number;
82
+ /**
83
+ * For lossy compression: convert to YUV like libwebp's sharp conversion (cwebp's `-sharp_yuv`, the same file),
84
+ * which picks the color planes so that colored edges (red text on blue, thin colored lines) stay sharp instead of
85
+ * bleeding. It takes about twice the time at the default effort; photos get about as large, images with many
86
+ * hard color edges a lot larger (1200x800 red and blue squares: 2.7 times). Default: `false`
87
+ */
88
+ sharpYuv?: boolean;
82
89
  /** Metadata to include, see {@link Metadata} */
83
90
  metadata?: Metadata;
84
91
  }
@@ -172,6 +179,12 @@ export interface TextStyle {
172
179
  * pixels. Fonts without instructions (and CFF/OpenType outlines) aren't affected. Default: `true`
173
180
  */
174
181
  hinting?: boolean;
182
+ /**
183
+ * OpenType features by their tags, for the whole text: `true` turns one on (like `tnum` for tabular numbers,
184
+ * `smcp` for small caps, `ss01` for a stylistic set), `false` off (also the ones on by default, like `liga` or
185
+ * `kern`), a number picks an alternate (`salt: 2`). Fonts without a feature ignore it. Default: `{}`
186
+ */
187
+ features?: Record<string, boolean | number>;
175
188
  }
176
189
  /** Options of {@link Image.cropCircle} */
177
190
  export interface CropCircleOptions {
@@ -463,6 +476,16 @@ export declare class Image {
463
476
  * @param height The new images height
464
477
  */
465
478
  crop(x: number, y: number, width: number, height: number): this;
479
+ /**
480
+ * Copies a region of the image into a new image, this one stays unchanged (like {@link Image.crop} on a clone,
481
+ * without copying the whole image). The region is clipped to the image, so the result can be smaller than the
482
+ * requested size
483
+ * @param x The x offset (0-based)
484
+ * @param y The y offset (0-based)
485
+ * @param width The region's width
486
+ * @param height The region's height
487
+ */
488
+ region(x: number, y: number, width: number, height: number): Image;
466
489
  /**
467
490
  * Removes borders of one color, e.g. the empty space around rendered text or around a logo on a solid background.
468
491
  * Frames keep their position: their offsets move by the trimmed amount. An image that only has the color stays
@@ -767,7 +790,7 @@ export declare class Image {
767
790
  * quality
768
791
  * @param options See {@link WebPEncodeOptions}
769
792
  */
770
- encodeWebP({ quality, effort, metadata }?: WebPEncodeOptions): Promise<Uint8Array>;
793
+ encodeWebP({ quality, effort, sharpYuv, metadata }?: WebPEncodeOptions): Promise<Uint8Array>;
771
794
  /**
772
795
  * Encodes the image as run length encoded TGA (32 bit, or 24 bit if the image is opaque)
773
796
  * @param options See {@link EncodeOptions}
@@ -826,8 +849,9 @@ export declare class Image {
826
849
  static get SVG_MODE_HEIGHT(): 3;
827
850
  /**
828
851
  * Creates a new image from the given SVG
829
- * Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, strokes, clip paths, masks and opacity;
830
- * text, images, filters and patterns are not rendered
852
+ * Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, patterns, strokes, markers, clip paths,
853
+ * masks, opacity, filters (all primitives and the filter functions) and images embedded as data URIs (PNG, JPEG,
854
+ * GIF, WebP, SVG); text is not rendered
831
855
  * @param svg The SVG content
832
856
  * @param options See {@link SVGOptions}
833
857
  * @return The rendered SVG graphic
package/dist/image.js CHANGED
@@ -2,6 +2,7 @@ import * as png from "./codecs/png.js";
2
2
  import * as jpeg from "./codecs/jpeg.js";
3
3
  import * as tiff from "./codecs/tiff.js";
4
4
  import * as webp from "./codecs/webp.js";
5
+ import * as gif from "./codecs/gif.js";
5
6
  import * as tga from "./codecs/tga.js";
6
7
  import * as bmp from "./codecs/bmp.js";
7
8
  import * as ico from "./codecs/ico.js";
@@ -24,6 +25,19 @@ import { rotateBilinear } from "./util/rotate.js";
24
25
  import { gaussianBlur, boxBlurRGBA, premultiply, unpremultiply } from "./util/blur.js";
25
26
  import { isOptions, finite, color as checkColor } from "./util/options.js";
26
27
  import { MAX_PIXELS, decoding } from "./util/limits.js";
28
+ function featureList(features) {
29
+ if (typeof features !== 'object' || features === null)
30
+ throw new TypeError('Features must be an object');
31
+ return Object.entries(features).map(([tag, value]) => {
32
+ if (!/^[\x20-\x7e]{4}$/.test(tag))
33
+ throw new RangeError(`Invalid OpenType feature tag: ${JSON.stringify(tag)}`);
34
+ if (typeof value === 'boolean')
35
+ return [tag, value ? 1 : 0];
36
+ if (!Number.isInteger(value) || value < 0 || value > 255)
37
+ throw new RangeError(`Invalid value of the OpenType feature ${tag}: ${value}`);
38
+ return [tag, value];
39
+ });
40
+ }
27
41
  export class Image {
28
42
  __width__;
29
43
  __height__;
@@ -301,6 +315,12 @@ export class Image {
301
315
  return image;
302
316
  }
303
317
  crop(x, y, width, height) {
318
+ return this.__apply__(this.__crop__(...this.__crop_bounds__(x, y, width, height)));
319
+ }
320
+ region(x, y, width, height) {
321
+ return this.__crop__(...this.__crop_bounds__(x, y, width, height));
322
+ }
323
+ __crop_bounds__(x, y, width, height) {
304
324
  x = ~~finite(x, 'x');
305
325
  y = ~~finite(y, 'y');
306
326
  width = ~~finite(width, 'width');
@@ -309,7 +329,7 @@ export class Image {
309
329
  const right = Math.min(this.width, x + width), bottom = Math.min(this.height, y + height);
310
330
  if (right <= left || bottom <= top)
311
331
  throw new RangeError('Crop region does not overlap the image');
312
- return this.__apply__(this.__crop__(left, top, right - left, bottom - top));
332
+ return [left, top, right - left, bottom - top];
313
333
  }
314
334
  trim(color, options = {}) {
315
335
  const bounds = this.__trim_bounds__(color, options);
@@ -510,26 +530,27 @@ export class Image {
510
530
  const blend = BLEND_MODES[mode];
511
531
  if (!blend || !Object.prototype.hasOwnProperty.call(BLEND_MODES, mode))
512
532
  throw new RangeError(`Invalid blend mode: ${mode}`);
513
- if (opacity !== 1 || mode !== 'normal')
533
+ if (mode !== 'normal')
514
534
  return this.__blend__(source, x, y, opacity, blend);
535
+ if (opacity === 0)
536
+ return this;
515
537
  const left = Math.max(0, x), top = Math.max(0, y);
516
538
  const right = Math.min(this.width, x + source.width), bottom = Math.min(this.height, y + source.height);
517
539
  const dst = this.bitmap, src = source.bitmap;
518
- const dst32 = new Uint32Array(dst.buffer, dst.byteOffset, dst.length >> 2);
519
- const src32 = new Uint32Array(src.buffer, src.byteOffset, src.length >> 2);
520
540
  for (let row = top; row < bottom; row++) {
521
- for (let column = left; column < right; column++) {
522
- const sp = (row - y) * source.width + column - x, s = 4 * sp;
541
+ for (let column = left, s = 4 * ((row - y) * source.width + left - x), d = 4 * (row * this.width + left); column < right; column++, s += 4, d += 4) {
523
542
  const sa = src[s + 3];
524
543
  if (sa === 0)
525
544
  continue;
526
- const dp = row * this.width + column, d = 4 * dp;
527
545
  const da = dst[d + 3];
528
- if (sa === 255 || da === 0) {
529
- dst32[dp] = src32[sp];
546
+ if ((sa === 255 && opacity === 1) || da === 0) {
547
+ dst[d] = src[s];
548
+ dst[d + 1] = src[s + 1];
549
+ dst[d + 2] = src[s + 2];
550
+ dst[d + 3] = sa * opacity;
530
551
  continue;
531
552
  }
532
- const fa = sa / 255, ba = da / 255 * (1 - fa);
553
+ const fa = sa / 255 * opacity, ba = da / 255 * (1 - fa);
533
554
  const a = fa + ba;
534
555
  dst[d] = (src[s] * fa + dst[d] * ba) / a;
535
556
  dst[d + 1] = (src[s + 1] * fa + dst[d + 1] * ba) / a;
@@ -1004,7 +1025,7 @@ export class Image {
1004
1025
  const m = resolveMetadata(metadata);
1005
1026
  return jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined });
1006
1027
  }
1007
- async encodeWebP({ quality, effort = 2, metadata = {} } = {}) {
1028
+ async encodeWebP({ quality, effort = 2, sharpYuv = false, metadata = {} } = {}) {
1008
1029
  const exif = exifData(resolveMetadata(metadata));
1009
1030
  if (quality === undefined)
1010
1031
  return webp.encode(this.__bytes__(), this.width, this.height, exif);
@@ -1013,7 +1034,7 @@ export class Image {
1013
1034
  throw new RangeError(`quality must be 0-100, not ${q}`);
1014
1035
  if (!Number.isInteger(effort) || effort < 0 || effort > 6)
1015
1036
  throw new RangeError(`effort must be an integer 0-6, not ${effort}`);
1016
- return webp.encodeLossy(this.__bytes__(), this.width, this.height, q, exif, effort);
1037
+ return webp.encodeLossy(this.__bytes__(), this.width, this.height, q, exif, effort, sharpYuv);
1017
1038
  }
1018
1039
  async encodeTGA({ metadata = {} } = {}) {
1019
1040
  const { author, comment, creationTime: time, software } = resolveMetadata(metadata);
@@ -1153,14 +1174,32 @@ export class Image {
1153
1174
  throw new RangeError('SVG scale must be > 0');
1154
1175
  if (mode !== Image.SVG_MODE_SCALE && size < 1)
1155
1176
  throw new RangeError('SVG size must be >= 1');
1156
- const { width, height, pixels } = svgRenderer.render(typeof svg === 'string' ? svg : view(svg), mode, size);
1177
+ const source = typeof svg === 'string' ? svg : view(svg);
1178
+ const images = new Map();
1179
+ for (const { href, data } of svgRenderer.embeddedImages(source)) {
1180
+ if (images.has(href))
1181
+ continue;
1182
+ try {
1183
+ if (ImageType.getType(data) === 'gif') {
1184
+ const decoded = gif.decode(data, true);
1185
+ images.set(href, { width: decoded.width, height: decoded.height, pixels: gif.composite(decoded)[0].pixels });
1186
+ }
1187
+ else {
1188
+ const image = await Image.decode(data);
1189
+ images.set(href, { width: image.width, height: image.height, pixels: image.bitmap });
1190
+ }
1191
+ }
1192
+ catch {
1193
+ }
1194
+ }
1195
+ const { width, height, pixels } = svgRenderer.render(source, mode, size, images);
1157
1196
  const image = new Image(width, height);
1158
1197
  image.bitmap.set(pixels);
1159
1198
  return image;
1160
1199
  }
1161
1200
  static async renderText(font, size, text, colorOrOptions = 0xffffffff, layoutArgument, styleArgument = {}) {
1162
1201
  const options = isOptions(colorOrOptions) ? colorOrOptions : { ...styleArgument, color: colorOrOptions, layout: layoutArgument };
1163
- const { color = 0xffffffff, layout = new TextLayout(), strokeWidth = 0, strokeColor = 0x000000ff, hinting = true } = options;
1202
+ const { color = 0xffffffff, layout = new TextLayout(), strokeWidth = 0, strokeColor = 0x000000ff, hinting = true, features = {} } = options;
1164
1203
  size = finite(size, 'font size');
1165
1204
  if (finite(strokeWidth, 'stroke width') < 0)
1166
1205
  throw new RangeError('Invalid stroke width');
@@ -1168,7 +1207,7 @@ export class Image {
1168
1207
  if (!fonts.length)
1169
1208
  throw new RangeError('No font given');
1170
1209
  const [r, g, b, a] = Image.colorToRGBA(color);
1171
- const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0);
1210
+ const rendered = await textRenderer.render(fonts.map(view), size, text, layout, hinting, (r << 24 | g << 16 | b << 8 | 255) >>> 0, featureList(features));
1172
1211
  const pad = Math.ceil(strokeWidth);
1173
1212
  const width = rendered.width + 2 * pad, height = rendered.height + 2 * pad;
1174
1213
  const coverage = new Uint8Array(width * height);
package/dist/index.d.ts CHANGED
@@ -9,6 +9,8 @@ export type { FrameDisposalModeName, FrameDisposalModeId, FrameOptions } from '.
9
9
  export { GIF } from './gif.js';
10
10
  export { Animation } from './animation.js';
11
11
  export type { AnimationOptions, AnimationDecodeOptions, AnimationEncodeOptions, WebPAnimationEncodeOptions, GIFEncodeOptions, APNGEncodeOptions } from './animation.js';
12
+ export { AnimationEncoder } from './animation-encoder.js';
13
+ export type { AnimationEncoderOptions, WebPAnimationEncoderOptions, GIFAnimationEncoderOptions, APNGAnimationEncoderOptions } from './animation-encoder.js';
12
14
  export { TextLayout } from './text-layout.js';
13
15
  export type { TextLayoutOptions, WrapStyle, HorizontalAlign, VerticalAlign } from './text-layout.js';
14
16
  export { ImageType } from './image-type.js';
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ export { Image } from "./image.js";
9
9
  export { Frame } from "./frame.js";
10
10
  export { GIF } from "./gif.js";
11
11
  export { Animation } from "./animation.js";
12
+ export { AnimationEncoder } from "./animation-encoder.js";
12
13
  export { TextLayout } from "./text-layout.js";
13
14
  export { ImageType } from "./image-type.js";
14
15
  export function decode(data, onlyFirstFrameOrOptions = false) {