imagescript 3.5.0 → 3.6.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.
@@ -36,7 +36,7 @@ export interface WebPAnimationEncodeOptions extends AnimationEncodeOptions {
36
36
  * frames are lossless
37
37
  */
38
38
  quality?: number;
39
- /** How much effort lossy frames take (0-6), see {@link WebPEncodeOptions.effort}. Default: `4` */
39
+ /** How much effort lossy frames take (0-6), see {@link WebPEncodeOptions.effort}. Default: `2` */
40
40
  effort?: number;
41
41
  }
42
42
  /** Options of {@link Animation.encodeGIF} */
package/dist/animation.js CHANGED
@@ -124,7 +124,7 @@ export class Animation extends Array {
124
124
  : this.__apngFrames__().map(({ blend: _, ...f }) => f);
125
125
  return png.encodeAnimation(frames, this.width, this.height, toPlays(this.loopCount), compression, pngText(resolveMetadata(metadata)));
126
126
  }
127
- async encodeWebP({ metadata = {}, optimize = true, quality, effort = 4 } = {}) {
127
+ async encodeWebP({ metadata = {}, optimize = true, quality, effort = 2 } = {}) {
128
128
  this.__validate__();
129
129
  if (!this.length)
130
130
  throw new Error('An animation needs at least one frame');
@@ -12,7 +12,7 @@ import { paletteColors, colorRanks, colorIndexBits } from "./palette.js";
12
12
  const ADST_DCT = 1, DCT_ADST = 2, ADST_ADST = 3;
13
13
  const bdim = (bs, i) => BLOCK_DIMENSIONS[bs * 4 + i];
14
14
  const tdim = (tx, i) => TXFM_DIMENSIONS[tx * 8 + i];
15
- const W = 0, H = 1, LW = 2, LH = 3, MIN = 4, MAX = 5, CTX = 7;
15
+ const W = 0, H = 1, LW = 2, LH = 3, MIN = 4, MAX = 5, SUB = 6, CTX = 7;
16
16
  const isDirectional = (mode) => mode >= VERT_PRED && mode <= VERT_LEFT_PRED;
17
17
  const smFlag = (mode) => mode === SMOOTH_PRED || mode === SMOOTH_H_PRED || mode === SMOOTH_V_PRED ? ANGLE_SMOOTH_EDGE : 0;
18
18
  const ZERO_BITS = 0.6;
@@ -63,6 +63,8 @@ class TileEncoder {
63
63
  lPalSzUv = new Uint8Array(32);
64
64
  aPal;
65
65
  lPal = new Uint16Array(32 * 24);
66
+ aTxIntra;
67
+ lTxIntra = new Int8Array(32);
66
68
  cf = new Int32Array(32 * 32);
67
69
  coefs = new Float64Array(32 * 32);
68
70
  q = new Int32Array(32 * 32);
@@ -96,6 +98,7 @@ class TileEncoder {
96
98
  this.aPalSz = new Uint8Array(n);
97
99
  this.aPalSzUv = new Uint8Array(n);
98
100
  this.aPal = new Uint16Array(n * 24);
101
+ this.aTxIntra = new Int8Array(n);
99
102
  this.cdefChoice = new Int8Array(f.cdefIdx.length);
100
103
  this.lossless = this.hdr.allLossless;
101
104
  const q = this.hdr.quant;
@@ -113,6 +116,7 @@ class TileEncoder {
113
116
  this.aCcoef[1].fill(0x40);
114
117
  this.aPalSz.fill(0);
115
118
  this.aPalSzUv.fill(0);
119
+ this.aTxIntra.fill(-1);
116
120
  }
117
121
  resetLeft() {
118
122
  this.lUvmode.fill(DC_PRED);
@@ -124,6 +128,7 @@ class TileEncoder {
124
128
  this.lCcoef[1].fill(0x40);
125
129
  this.lPalSz.fill(0);
126
130
  this.lPalSzUv.fill(0);
131
+ this.lTxIntra.fill(-1);
127
132
  }
128
133
  tile(tileRow, tileCol) {
129
134
  const f = this.f, t = this.hdr.tiles;
@@ -152,14 +157,28 @@ class TileEncoder {
152
157
  }
153
158
  }
154
159
  walk(bl, n) {
160
+ const f = this.f, hsz = 16 >> bl;
155
161
  if (n.bp === PARTITION_NONE) {
156
- const b = n.b, f = this.f;
162
+ const b = n.b;
157
163
  this.storeBlock(BLOCK_SIZES[(bl * 10 + PARTITION_NONE) * 2], b);
158
164
  if (!b.skip)
159
165
  f.cdefIdx[(this.by >> 4) * (f.b4Stride >> 4) + (this.bx >> 4)] = 0;
160
166
  return;
161
167
  }
162
- const hsz = 16 >> bl;
168
+ if (n.bp === PARTITION_H || n.bp === PARTITION_V) {
169
+ const bs = BLOCK_SIZES[(bl * 10 + n.bp) * 2], dx = n.bp === PARTITION_V ? hsz : 0, dy = n.bp === PARTITION_H ? hsz : 0;
170
+ for (let k = 0; k < 2; k++) {
171
+ const b = n.kids[k].b;
172
+ this.storeBlock(bs, b);
173
+ if (!b.skip)
174
+ f.cdefIdx[(this.by >> 4) * (f.b4Stride >> 4) + (this.bx >> 4)] = 0;
175
+ this.bx += dx;
176
+ this.by += dy;
177
+ }
178
+ this.bx -= 2 * dx;
179
+ this.by -= 2 * dy;
180
+ return;
181
+ }
163
182
  for (let k = 0; k < 4; k++) {
164
183
  if (!n.kids[k])
165
184
  continue;
@@ -217,7 +236,8 @@ class TileEncoder {
217
236
  const r = this.searchBlock(bs, node.o);
218
237
  return { node: { bp: PARTITION_NONE, b: r.b, kids: [] }, cost: r.cost };
219
238
  }
220
- const saved = this.saveArea(bl);
239
+ const saved = this.saveArea(bl), entryContexts = this.saveContexts(bs);
240
+ let result, noneCost, splitCost;
221
241
  if (bl <= BL_64X64 + 1) {
222
242
  const sp = split([0, 1, 2, 3]);
223
243
  const deeper = sp.node.kids.filter(k => k && k.bp === PARTITION_SPLIT).length;
@@ -226,24 +246,78 @@ class TileEncoder {
226
246
  const spArea = this.saveArea(bl), contexts = this.saveContexts(bs);
227
247
  this.restoreArea(bl, saved);
228
248
  const none = this.searchBlock(bs, node.o);
229
- if (none.cost + this.lambda < sp.cost + this.lambda * 2)
249
+ noneCost = none.cost + this.lambda;
250
+ splitCost = sp.cost + this.lambda * 2;
251
+ if (noneCost < splitCost)
252
+ result = { node: { bp: PARTITION_NONE, b: none.b, kids: [] }, cost: noneCost };
253
+ else {
254
+ this.restoreArea(bl, spArea);
255
+ this.restoreContexts(contexts);
256
+ result = { node: sp.node, cost: splitCost };
257
+ }
258
+ }
259
+ else {
260
+ const none = this.searchBlock(bs, node.o);
261
+ if (none.b.skip && this.params.effort < 2)
230
262
  return { node: { bp: PARTITION_NONE, b: none.b, kids: [] }, cost: none.cost + this.lambda };
231
- this.restoreArea(bl, spArea);
232
- this.restoreContexts(contexts);
233
- return { node: sp.node, cost: sp.cost + this.lambda * 2 };
234
- }
235
- const none = this.searchBlock(bs, node.o);
236
- if (none.b.skip && this.params.effort < 2)
237
- return { node: { bp: PARTITION_NONE, b: none.b, kids: [] }, cost: none.cost + this.lambda };
238
- const noneArea = this.saveArea(bl);
239
- this.restoreArea(bl, saved);
240
- const sp = split([0, 1, 2, 3]);
241
- if (none.cost + this.lambda < sp.cost + this.lambda * 2) {
242
- this.restoreArea(bl, noneArea);
243
- this.modeContexts(bs, none.b);
244
- return { node: { bp: PARTITION_NONE, b: none.b, kids: [] }, cost: none.cost + this.lambda };
245
- }
246
- return { node: sp.node, cost: sp.cost + this.lambda * 2 };
263
+ const noneArea = this.saveArea(bl);
264
+ this.restoreArea(bl, saved);
265
+ const sp = split([0, 1, 2, 3]);
266
+ noneCost = none.cost + this.lambda;
267
+ splitCost = sp.cost + this.lambda * 2;
268
+ if (noneCost < splitCost) {
269
+ this.restoreArea(bl, noneArea);
270
+ this.modeContexts(bs, none.b);
271
+ result = { node: { bp: PARTITION_NONE, b: none.b, kids: [] }, cost: noneCost };
272
+ }
273
+ else
274
+ result = { node: sp.node, cost: splitCost };
275
+ }
276
+ const ratio = noneCost / splitCost, deeper = result.node.bp === PARTITION_SPLIT ? result.node.kids.filter(k => k && k.bp !== PARTITION_NONE).length : 0;
277
+ if (this.params.effort && ratio >= 0.9 && ratio < 1.3 && deeper <= 1) {
278
+ let bestArea = this.saveArea(bl), bestContexts = this.saveContexts(bs);
279
+ for (const bp of this.params.effort > 1 ? [PARTITION_H, PARTITION_V] : [this.halvesDirection(bs)]) {
280
+ this.restoreArea(bl, saved);
281
+ this.restoreContexts(entryContexts);
282
+ const r = this.halves(bl, bp, node);
283
+ if (r.cost < result.cost) {
284
+ result = r;
285
+ bestArea = this.saveArea(bl);
286
+ bestContexts = this.saveContexts(bs);
287
+ }
288
+ }
289
+ this.restoreArea(bl, bestArea);
290
+ this.restoreContexts(bestContexts);
291
+ }
292
+ return result;
293
+ }
294
+ halvesDirection(bs) {
295
+ const f = this.f, stride = f.strides[0], src = this.src[0];
296
+ const w = Math.min(bdim(bs, 0), f.bw - this.bx) * 4, h = Math.min(bdim(bs, 1), f.bh - this.by) * 4, o = this.by * 4 * stride + this.bx * 4;
297
+ let top = 0, left = 0, all = 0;
298
+ for (let y = 0; y < h; y++) {
299
+ for (let x = 0; x < w; x++) {
300
+ const v = src[o + y * stride + x];
301
+ all += v;
302
+ if (y < h >> 1)
303
+ top += v;
304
+ if (x < w >> 1)
305
+ left += v;
306
+ }
307
+ }
308
+ return Math.abs(2 * top - all) >= Math.abs(2 * left - all) ? PARTITION_H : PARTITION_V;
309
+ }
310
+ halves(bl, bp, node) {
311
+ const hsz = 16 >> bl, bs = BLOCK_SIZES[(bl * 10 + bp) * 2], edges = bp === PARTITION_H ? node.h : node.v;
312
+ const dx = bp === PARTITION_V ? hsz : 0, dy = bp === PARTITION_H ? hsz : 0;
313
+ const first = this.searchBlock(bs, edges[0]);
314
+ this.bx += dx;
315
+ this.by += dy;
316
+ const second = this.searchBlock(bs, edges[1]);
317
+ this.bx -= dx;
318
+ this.by -= dy;
319
+ const leaf = (b) => ({ bp: PARTITION_NONE, b, kids: [] });
320
+ return { node: { bp, b: null, kids: [leaf(first.b), leaf(second.b)] }, cost: first.cost + second.cost + this.lambda * 3 };
247
321
  }
248
322
  saveArea(bl) {
249
323
  const f = this.f, n = 64 >> (bl - 1);
@@ -319,6 +393,30 @@ class TileEncoder {
319
393
  b.yAngle = bestMode.angle;
320
394
  if (kept)
321
395
  this.restorePlane(0, bs, kept);
396
+ if (this.hdr.txMode === 2 && tdim(b.tx, MAX) > TX_4X4) {
397
+ const modeBits = b.yMode === DC_PRED ? 2 : 4.5, maxDepth = Math.min(tdim(b.tx, MAX), 2);
398
+ let keptDepth = null, bestDepthCost = best + lambda, bestTxSize = b.tx;
399
+ for (let depth = 1, tx = b.tx; depth <= maxDepth; depth++) {
400
+ tx = tdim(tx, SUB);
401
+ if (!keptDepth)
402
+ keptDepth = this.savePlane(0, bs);
403
+ b.tx = tx;
404
+ const d = this.codeLuma(bs, edgeFlags, b);
405
+ const cost = d + lambda * (this.bits + modeBits + 2 + depth);
406
+ if (cost < bestDepthCost) {
407
+ bestDepthCost = best = cost;
408
+ dist = d;
409
+ bits = this.bits + 1;
410
+ coded = this.coded;
411
+ bestTxSize = tx;
412
+ if (depth < maxDepth)
413
+ keptDepth = this.savePlane(0, bs);
414
+ }
415
+ else if (depth === maxDepth && keptDepth)
416
+ this.restorePlane(0, bs, keptDepth);
417
+ }
418
+ b.tx = bestTxSize;
419
+ }
322
420
  if (tdim(b.tx, MAX) <= TX_16X16 && this.params.effort && coded && !this.lossless) {
323
421
  let keptTx = this.savePlane(0, bs), bestTxCost = best + lambda;
324
422
  for (const txtp of [ADST_ADST, ADST_DCT, DCT_ADST, IDTX]) {
@@ -932,6 +1030,16 @@ class TileEncoder {
932
1030
  w.symbol(cdf, pc, PARTITION_TYPE_COUNT[bl], bp);
933
1031
  if (bp === PARTITION_NONE)
934
1032
  this.writeB(BLOCK_SIZES[(bl * 10 + bp) * 2], node.o, n.b);
1033
+ else if (bp === PARTITION_H || bp === PARTITION_V) {
1034
+ const bs = BLOCK_SIZES[(bl * 10 + bp) * 2], edges = bp === PARTITION_H ? node.h : node.v;
1035
+ const dx = bp === PARTITION_V ? hsz : 0, dy = bp === PARTITION_H ? hsz : 0;
1036
+ this.writeB(bs, edges[0], n.kids[0].b);
1037
+ this.bx += dx;
1038
+ this.by += dy;
1039
+ this.writeB(bs, edges[1], n.kids[1].b);
1040
+ this.bx -= dx;
1041
+ this.by -= dy;
1042
+ }
935
1043
  else
936
1044
  for (let k = 0; k < 4; k++)
937
1045
  quarter(k);
@@ -1011,6 +1119,14 @@ class TileEncoder {
1011
1119
  this.writeColorIndices(b.palIdx, b.palSz[0], 0, w4 * 4, h4 * 4, bw4 * 4);
1012
1120
  if (hasChroma && b.palSz[1])
1013
1121
  this.writeColorIndices(b.palIdxUv, b.palSz[1], 1, (w4 + ssx >> ssx) * 4, (h4 + ssy >> ssy) * 4, cbw4 * 4);
1122
+ const maxTx = MAX_TXFM_SIZE_FOR_BS[bs * 4];
1123
+ if (this.hdr.txMode === 2 && tdim(maxTx, MAX) > TX_4X4) {
1124
+ const tctx = (this.lTxIntra[by4] >= tdim(maxTx, LH) ? 1 : 0) + (this.aTxIntra[bx4] >= tdim(maxTx, LW) ? 1 : 0);
1125
+ let depth = 0;
1126
+ for (let tx = maxTx; tx !== b.tx; tx = tdim(tx, SUB))
1127
+ depth++;
1128
+ w.symbol(cdf, CDF.txSize + ((tdim(maxTx, MAX) - 1) * 3 + tctx) * 4, Math.min(tdim(maxTx, MAX), 2), depth);
1129
+ }
1014
1130
  this.codeLuma(bs, edgeFlags, b);
1015
1131
  if (hasChroma)
1016
1132
  this.codeChroma(bs, edgeFlags, b);
@@ -1022,6 +1138,8 @@ class TileEncoder {
1022
1138
  this.lSkip.fill(b.skip, by4, by4 + lh);
1023
1139
  this.aPalSz.fill(b.palSz[0], bx4, bx4 + aw);
1024
1140
  this.lPalSz.fill(b.palSz[0], by4, by4 + lh);
1141
+ this.aTxIntra.fill(tdim(b.tx, LW), bx4, bx4 + aw);
1142
+ this.lTxIntra.fill(tdim(b.tx, LH), by4, by4 + lh);
1025
1143
  this.aPalSzUv.fill(hasChroma ? b.palSz[1] : 0, bx4, bx4 + aw);
1026
1144
  this.lPalSzUv.fill(hasChroma ? b.palSz[1] : 0, by4, by4 + lh);
1027
1145
  for (let pl = 0; pl < 3; pl++) {
@@ -1347,7 +1465,7 @@ export function encodeAV1(image, params) {
1347
1465
  loopFilter: { levelY: [0, 0], levelU: 0, levelV: 0, sharpness: 0, modeRefDeltaEnabled: false, refDeltas: [1, 0, 0, 0, -1, 0, -1, -1], modeDeltas: [0, 0] },
1348
1466
  cdef: { damping: 3, bits: 0, yStrengths: [0], uvStrengths: [0] },
1349
1467
  restoration: { types: [RESTORATION_NONE, RESTORATION_NONE, RESTORATION_NONE], unitSizeLog2: [8, 8] },
1350
- txMode: qidx ? 1 : 0, reducedTxSet: false, filmGrain: null
1468
+ txMode: qidx ? params.effort > 1 ? 2 : 1 : 0, reducedTxSet: false, filmGrain: null
1351
1469
  };
1352
1470
  const f = new Frame(seq, hdr);
1353
1471
  const src = f.planes.map((plane, p) => {
@@ -149,7 +149,7 @@ function seqMonochrome(d, o) {
149
149
  read(1);
150
150
  return !!read(1);
151
151
  }
152
- export function encode(rgba, width, height, { quality, alphaQuality, subsampling, effort }) {
152
+ export function encode(rgba, width, height, { quality, alphaQuality, subsampling, effort, exif }) {
153
153
  if (width < 1 || height < 1)
154
154
  throw new RangeError('AVIF: dimensions must be at least 1');
155
155
  if (width > 65536 || height > 65536)
@@ -183,11 +183,18 @@ export function encode(rgba, width, height, { quality, alphaQuality, subsampling
183
183
  }
184
184
  const profile = subsampled || gray ? 'MA1B' : 'MA1A';
185
185
  const ftyp = box('ftyp', ascii('avif'), u32(0), ascii('avif'), ascii('mif1'), ascii('miaf'), ascii(profile));
186
- const hdlr = fullBox('hdlr', 0, 0, u32(0), ascii('pict'), u32(0), u32(0), u32(0), ascii('ImageScript'), [0]);
186
+ const hdlr = fullBox('hdlr', 0, 0, u32(0), ascii('pict'), u32(0), u32(0), u32(0), [0]);
187
187
  const pitm = fullBox('pitm', 0, 0, u16(1));
188
- const infe = (id, name) => fullBox('infe', 2, 0, u16(id), u16(0), ascii('av01'), ascii(name), [0]);
189
- const iinf = fullBox('iinf', 0, 0, u16(alpha ? 2 : 1), infe(1, 'Color'), alpha ? infe(2, 'Alpha') : []);
190
- const iref = alpha ? fullBox('iref', 0, 0, box('auxl', u16(2), u16(1), u16(1))) : [];
188
+ const items = [{ type: 'av01', name: 'Color', data: [color] }];
189
+ if (alpha)
190
+ items.push({ type: 'av01', name: 'Alpha', data: [alpha] });
191
+ if (exif?.length)
192
+ items.push({ type: 'Exif', name: 'Exif', data: [u32(0), exif] });
193
+ const sizes = items.map(item => item.data.reduce((n, d) => n + d.length, 0));
194
+ const infe = (id, type, name) => fullBox('infe', 2, 0, u16(id), u16(0), ascii(type), ascii(name), [0]);
195
+ const iinf = fullBox('iinf', 0, 0, u16(items.length), ...items.map((item, i) => infe(i + 1, item.type, item.name)));
196
+ const exifId = exif?.length ? items.length : 0;
197
+ const iref = alpha || exifId ? fullBox('iref', 0, 0, alpha ? box('auxl', u16(2), u16(1), u16(1)) : [], exifId ? box('cdsc', u16(exifId), u16(1), u16(1)) : []) : [];
191
198
  const ispe = fullBox('ispe', 0, 0, u32(width), u32(height));
192
199
  const colr = box('colr', ascii('nclx'), u16(cicp[0]), u16(cicp[1]), u16(cicp[2]), [0x80]);
193
200
  const pixi = (channels) => fullBox('pixi', 0, 0, [channels], new Array(channels).fill(8));
@@ -195,16 +202,23 @@ export function encode(rgba, width, height, { quality, alphaQuality, subsampling
195
202
  const ipco = box('ipco', ispe, av1C(color), colr, pixi(gray ? 1 : 3), alpha ? av1C(alpha) : [], alpha ? pixi(1) : [], alpha ? auxC : []);
196
203
  const ipma = fullBox('ipma', 0, 0, u32(alpha ? 2 : 1), u16(1), [4, 1, 0x82, 3, 4], alpha ? [...u16(2), 4, 1, 0x85, 6, 7] : []);
197
204
  const iprp = box('iprp', ipco, ipma);
198
- const ilocFor = (offset) => fullBox('iloc', 0, 0, [0x44, 0x00], u16(alpha ? 2 : 1), u16(1), u16(0), u16(1), u32(offset), u32(color.length), alpha ? [...u16(2), ...u16(0), ...u16(1), ...u32(offset + color.length), ...u32(alpha.length)] : []);
205
+ const ilocFor = (offset) => fullBox('iloc', 0, 0, [0x44, 0x00], u16(items.length), ...items.map((_, i) => {
206
+ const at = offset + sizes.slice(0, i).reduce((n, size) => n + size, 0);
207
+ return [...u16(i + 1), ...u16(0), ...u16(1), ...u32(at), ...u32(sizes[i])];
208
+ }));
199
209
  const metaFor = (offset) => fullBox('meta', 0, 0, hdlr, pitm, ilocFor(offset), iinf, iref, iprp);
200
210
  const headerSize = ftyp.length + metaFor(0).length + 8;
201
211
  const head = [...ftyp, ...metaFor(headerSize)];
202
- const mdatSize = 8 + color.length + (alpha ? alpha.length : 0);
212
+ const mdatSize = 8 + sizes.reduce((n, size) => n + size, 0);
203
213
  const out = new Uint8Array(head.length + mdatSize);
204
214
  out.set(head);
205
215
  out.set([...u32(mdatSize), ...ascii('mdat')], head.length);
206
- out.set(color, head.length + 8);
207
- if (alpha)
208
- out.set(alpha, head.length + 8 + color.length);
216
+ let at = head.length + 8;
217
+ for (const item of items) {
218
+ for (const d of item.data) {
219
+ out.set(d, at);
220
+ at += d.length;
221
+ }
222
+ }
209
223
  return out;
210
224
  }
@@ -4,13 +4,25 @@ import { imageHeader, skipICC } from "./jxl/headers.js";
4
4
  import { frameHeader, toc } from "./jxl/frame-header.js";
5
5
  import { decodeFrame } from "./jxl/frame.js";
6
6
  import { ColorOutput } from "./jxl/color.js";
7
- export { encodeRGBA as encode } from "./jxl/fast-lossless.js";
7
+ import { encodeRGBA } from "./jxl/fast-lossless.js";
8
+ import { concat } from "../util/mem.js";
8
9
  const CONTAINER = [0, 0, 0, 12, 0x4a, 0x58, 0x4c, 0x20, 0x0d, 0x0a, 0x87, 0x0a];
9
10
  export function isJXL(d) {
10
11
  if (d.length >= 2 && d[0] === 0xff && d[1] === 0x0a)
11
12
  return true;
12
13
  return d.length >= 12 && CONTAINER.every((v, i) => d[i] === v);
13
14
  }
15
+ export function encode(rgba, width, height, exif) {
16
+ const stream = encodeRGBA(rgba, width, height);
17
+ if (!exif?.length)
18
+ return stream;
19
+ const jxl = [0x6a, 0x78, 0x6c, 0x20];
20
+ return concat([CONTAINER, ...box('ftyp', jxl, [0, 0, 0, 0], jxl), ...box('Exif', [0, 0, 0, 0], exif), ...box('jxlc', stream)]);
21
+ }
22
+ const box = (type, ...content) => {
23
+ const size = 8 + content.reduce((n, c) => n + c.length, 0);
24
+ return [[size >>> 24, size >> 16 & 255, size >> 8 & 255, size & 255, ...Array.from(type, c => c.charCodeAt(0))], ...content];
25
+ };
14
26
  const fourcc = (d, o) => String.fromCharCode(d[o], d[o + 1], d[o + 2], d[o + 3]);
15
27
  function codestream(d) {
16
28
  if (d[0] === 0xff)
@@ -22,15 +22,6 @@ const CHANNELS_TO_COLOR_TYPE = { 1: 0, 2: 4, 3: 2, 4: 6 };
22
22
  const VALID_DEPTHS = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
23
23
  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]];
24
24
  export async function encode(data, { text, width, height, channels, depth = 8, level = 0, palette, transparency, filter: filterRows = false }) {
25
- const rowBytes = Math.ceil(width * channels * depth / 8);
26
- let filtered;
27
- if (filterRows)
28
- filtered = filter(data, rowBytes, height, Math.max(1, channels * depth / 8));
29
- else {
30
- filtered = new Uint8Array(height * (rowBytes + 1));
31
- for (let y = 0; y < height; y++)
32
- filtered.set(data.subarray(y * rowBytes, (y + 1) * rowBytes), y * (rowBytes + 1) + 1);
33
- }
34
25
  const header = new Uint8Array(13);
35
26
  const view = new DataView(header.buffer);
36
27
  view.setUint32(0, width);
@@ -43,7 +34,7 @@ export async function encode(data, { text, width, height, channels, depth = 8, l
43
34
  if (transparency)
44
35
  chunks.push(chunk(tRNS, transparency));
45
36
  chunks.push(...textChunks(text));
46
- chunks.push(chunk(IDAT, await compressAsync(filtered, level)));
37
+ chunks.push(chunk(IDAT, await compressRows(data, width, height, channels, depth, level, filterRows)));
47
38
  chunks.push(chunk(IEND, new Uint8Array(0)));
48
39
  return concat([HEAD, ...chunks]);
49
40
  }
@@ -61,10 +52,10 @@ function textChunks(text) {
61
52
  }
62
53
  return chunks;
63
54
  }
64
- function filter(data, rowBytes, height, bpp) {
65
- const out = new Uint8Array(height * (rowBytes + 1));
66
- for (let y = 0; y < height; y++) {
67
- const row = y * rowBytes, o = y * (rowBytes + 1) + 1;
55
+ function filter(data, rowBytes, y0, y1, bpp) {
56
+ const out = new Uint8Array((y1 - y0) * (rowBytes + 1));
57
+ for (let y = y0; y < y1; y++) {
58
+ const row = y * rowBytes, o = (y - y0) * (rowBytes + 1) + 1;
68
59
  out[o - 1] = 4;
69
60
  if (y === 0) {
70
61
  for (let i = 0; i < rowBytes; i++)
@@ -82,6 +73,30 @@ function filter(data, rowBytes, height, bpp) {
82
73
  }
83
74
  return out;
84
75
  }
76
+ function prefix(data, rowBytes, y0, y1) {
77
+ const out = new Uint8Array((y1 - y0) * (rowBytes + 1));
78
+ for (let y = y0; y < y1; y++)
79
+ out.set(data.subarray(y * rowBytes, (y + 1) * rowBytes), (y - y0) * (rowBytes + 1) + 1);
80
+ return out;
81
+ }
82
+ const SAMPLE_ROWS = 32, SAMPLE_STEP = 512;
83
+ async function compressRows(data, width, height, channels, depth, level, filterRows) {
84
+ const rowBytes = Math.ceil(width * channels * depth / 8), bpp = Math.max(1, channels * depth / 8);
85
+ if (!filterRows)
86
+ return compressAsync(prefix(data, rowBytes, 0, height), level);
87
+ if (height <= SAMPLE_ROWS) {
88
+ const [unfiltered, filtered] = await Promise.all([compressAsync(prefix(data, rowBytes, 0, height), level), compressAsync(filter(data, rowBytes, 0, height, bpp), level)]);
89
+ return unfiltered.length < filtered.length ? unfiltered : filtered;
90
+ }
91
+ const unfilteredSamples = [], filteredSamples = [];
92
+ for (let y = Math.min((SAMPLE_STEP - SAMPLE_ROWS) >> 1, (height - SAMPLE_ROWS) >> 1); y < height; y += SAMPLE_STEP) {
93
+ const end = Math.min(height, y + SAMPLE_ROWS);
94
+ unfilteredSamples.push(prefix(data, rowBytes, y, end));
95
+ filteredSamples.push(filter(data, rowBytes, y, end, bpp));
96
+ }
97
+ const [unfiltered, filtered] = await Promise.all([compressAsync(concat(unfilteredSamples), level), compressAsync(concat(filteredSamples), level)]);
98
+ return compressAsync(unfiltered.length < filtered.length ? prefix(data, rowBytes, 0, height) : filter(data, rowBytes, 0, height, bpp), level);
99
+ }
85
100
  function chunk(type, body) {
86
101
  const out = new Uint8Array(body.length + 12);
87
102
  const view = new DataView(out.buffer);
@@ -211,18 +226,6 @@ export async function encodeRGBA(rgba, width, height, level, text) {
211
226
  const { channels, depth, palette, transparency } = format;
212
227
  return encode(format.convert(rgba, width, height), { width, height, level, text, channels, depth, palette, transparency, filter: level > 0 && !palette });
213
228
  }
214
- async function compressRows(data, width, height, channels, depth, level, filterRows) {
215
- const rowBytes = Math.ceil(width * channels * depth / 8);
216
- let filtered;
217
- if (filterRows)
218
- filtered = filter(data, rowBytes, height, Math.max(1, channels * depth / 8));
219
- else {
220
- filtered = new Uint8Array(height * (rowBytes + 1));
221
- for (let y = 0; y < height; y++)
222
- filtered.set(data.subarray(y * rowBytes, (y + 1) * rowBytes), y * (rowBytes + 1) + 1);
223
- }
224
- return compressAsync(filtered, level);
225
- }
226
229
  export async function encodeAnimation(frames, width, height, plays, level, text) {
227
230
  if (!frames.length)
228
231
  throw new Error('PNG: an animation needs at least one frame');
@@ -817,19 +817,26 @@ export function sse16(a, ao, b, bo, h) {
817
817
  return count;
818
818
  }
819
819
  export function tTransform(input, i, w) {
820
- let sum = 0;
821
- for (let k = 0; k < 4; k++, i += BPS) {
822
- const a0 = input[i] + input[i + 2], a1 = input[i + 1] + input[i + 3], a2 = input[i + 1] - input[i + 3], a3 = input[i] - input[i + 2];
823
- ftmp[k * 4] = a0 + a1;
824
- ftmp[k * 4 + 1] = a3 + a2;
825
- ftmp[k * 4 + 2] = a3 - a2;
826
- ftmp[k * 4 + 3] = a0 - a1;
827
- }
828
- for (let k = 0; k < 4; k++) {
829
- const a0 = ftmp[k] + ftmp[8 + k], a1 = ftmp[4 + k] + ftmp[12 + k], a2 = ftmp[4 + k] - ftmp[12 + k], a3 = ftmp[k] - ftmp[8 + k];
830
- sum += w[k] * Math.abs(a0 + a1) + w[k + 4] * Math.abs(a3 + a2) + w[k + 8] * Math.abs(a3 - a2) + w[k + 12] * Math.abs(a0 - a1);
831
- }
832
- return sum;
820
+ const r00 = input[i], r01 = input[i + 1], r02 = input[i + 2], r03 = input[i + 3];
821
+ const a00 = r00 + r02, a01 = r01 + r03, a02 = r01 - r03, a03 = r00 - r02;
822
+ const h00 = a00 + a01, h01 = a03 + a02, h02 = a03 - a02, h03 = a00 - a01;
823
+ const r10 = input[i + 1 * BPS], r11 = input[i + 1 * BPS + 1], r12 = input[i + 1 * BPS + 2], r13 = input[i + 1 * BPS + 3];
824
+ const a10 = r10 + r12, a11 = r11 + r13, a12 = r11 - r13, a13 = r10 - r12;
825
+ const h10 = a10 + a11, h11 = a13 + a12, h12 = a13 - a12, h13 = a10 - a11;
826
+ const r20 = input[i + 2 * BPS], r21 = input[i + 2 * BPS + 1], r22 = input[i + 2 * BPS + 2], r23 = input[i + 2 * BPS + 3];
827
+ const a20 = r20 + r22, a21 = r21 + r23, a22 = r21 - r23, a23 = r20 - r22;
828
+ const h20 = a20 + a21, h21 = a23 + a22, h22 = a23 - a22, h23 = a20 - a21;
829
+ const r30 = input[i + 3 * BPS], r31 = input[i + 3 * BPS + 1], r32 = input[i + 3 * BPS + 2], r33 = input[i + 3 * BPS + 3];
830
+ const a30 = r30 + r32, a31 = r31 + r33, a32 = r31 - r33, a33 = r30 - r32;
831
+ const h30 = a30 + a31, h31 = a33 + a32, h32 = a33 - a32, h33 = a30 - a31;
832
+ const b00 = h00 + h20, b01 = h10 + h30, b02 = h10 - h30, b03 = h00 - h20;
833
+ const b10 = h01 + h21, b11 = h11 + h31, b12 = h11 - h31, b13 = h01 - h21;
834
+ const b20 = h02 + h22, b21 = h12 + h32, b22 = h12 - h32, b23 = h02 - h22;
835
+ const b30 = h03 + h23, b31 = h13 + h33, b32 = h13 - h33, b33 = h03 - h23;
836
+ return w[0] * Math.abs(b00 + b01) + w[4] * Math.abs(b03 + b02) + w[8] * Math.abs(b03 - b02) + w[12] * Math.abs(b00 - b01) +
837
+ w[1] * Math.abs(b10 + b11) + w[5] * Math.abs(b13 + b12) + w[9] * Math.abs(b13 - b12) + w[13] * Math.abs(b10 - b11) +
838
+ w[2] * Math.abs(b20 + b21) + w[6] * Math.abs(b23 + b22) + w[10] * Math.abs(b23 - b22) + w[14] * Math.abs(b20 - b21) +
839
+ w[3] * Math.abs(b30 + b31) + w[7] * Math.abs(b33 + b32) + w[11] * Math.abs(b33 - b32) + w[15] * Math.abs(b30 - b31);
833
840
  }
834
841
  export function tDisto4x4(source, b, bo, w) {
835
842
  return Math.abs(tTransform(b, bo, w) - source) >> 5;
@@ -1146,7 +1146,17 @@ function reconstructIntra4(it, levels, lo, src, s, out, o, mode) {
1146
1146
  fTransform(src, s, it.yuvP, r, tmpLevels, 0);
1147
1147
  const nz = it.doTrellis ? trellisQuantize(it.enc, tmpLevels, 0, levels, lo, it.topNz[it.i4 & 3] + it.leftNz[it.i4 >> 2], TYPE_I4_AC, dqm.y1, dqm.lambdaTrellisI4)
1148
1148
  : quantizeBlock(tmpLevels, 0, levels, lo, dqm.y1) ? 1 : 0;
1149
- iTransform(it.yuvP, r, tmpLevels, 0, out, o, false);
1149
+ if (nz)
1150
+ iTransform(it.yuvP, r, tmpLevels, 0, out, o, false);
1151
+ else {
1152
+ const p = it.yuvP;
1153
+ for (let k = 0; k < 4 * BPS; k += BPS) {
1154
+ out[o + k] = p[r + k];
1155
+ out[o + k + 1] = p[r + k + 1];
1156
+ out[o + k + 2] = p[r + k + 2];
1157
+ out[o + k + 3] = p[r + k + 3];
1158
+ }
1159
+ }
1150
1160
  return nz;
1151
1161
  }
1152
1162
  function quantizeSingle(v, i, m) {
@@ -1219,16 +1229,19 @@ function pickBestIntra16(it, rd) {
1219
1229
  rdCur.modeI16 = mode;
1220
1230
  rdCur.nz = reconstructIntra16(it, rdCur, dst, Y_OFF, mode);
1221
1231
  rdCur.D = sse16(it.yuvIn, Y_OFF, dst, Y_OFF, 16);
1222
- rdCur.SD = tlambda ? (tlambda * tDisto16x16(sourceSpectra, dst, Y_OFF, WEIGHT_Y) + 128) >> 8 : 0;
1223
1232
  rdCur.H = FIXED_COSTS_I16[mode];
1224
- rdCur.R = costLuma16(it, rdCur);
1225
- if (flat) {
1233
+ if (flat)
1226
1234
  flat = isFlat(rdCur.yAcLevels, 0, 16, FLATNESS_LIMIT_I16);
1227
- if (flat) {
1228
- rdCur.D *= 2;
1229
- rdCur.SD *= 2;
1230
- }
1231
- }
1235
+ if (flat)
1236
+ rdCur.D *= 2;
1237
+ rdCur.SD = rdCur.R = 0;
1238
+ rdCur.setRDScore(lambda);
1239
+ if (mode > 0 && rdCur.score >= rdBest.score)
1240
+ continue;
1241
+ rdCur.SD = tlambda ? (tlambda * tDisto16x16(sourceSpectra, dst, Y_OFF, WEIGHT_Y) + 128) >> 8 : 0;
1242
+ if (flat)
1243
+ rdCur.SD *= 2;
1244
+ rdCur.R = costLuma16(it, rdCur);
1232
1245
  rdCur.setRDScore(lambda);
1233
1246
  if (mode === 0 || rdCur.score < rdBest.score) {
1234
1247
  const swap = rdCur;
@@ -1277,11 +1290,17 @@ function pickBestIntra4(it, rd) {
1277
1290
  const spectrum = tlambda ? tTransform(it.yuvIn, src, WEIGHT_Y) : 0;
1278
1291
  for (let mode = 0; mode < 10; mode++) {
1279
1292
  const r = rdTmpI4;
1293
+ r.H = costs[modeCosts + mode];
1294
+ if (bestMode >= 0 && r.H * lambda >= rdI4.score)
1295
+ continue;
1280
1296
  r.nz = reconstructIntra4(it, tmpLevels2, 0, it.yuvIn, src, tmpDst, td, mode) << it.i4;
1281
1297
  r.D = sse4x4(it.yuvIn, src, tmpDst, td);
1282
- r.SD = tlambda ? (tlambda * tDisto4x4(spectrum, tmpDst, td, WEIGHT_Y) + 128) >> 8 : 0;
1283
- r.H = costs[modeCosts + mode];
1284
1298
  r.R = mode > 0 && isFlat(tmpLevels2, 0, 1, FLATNESS_LIMIT_I4) ? FLATNESS_PENALTY : 0;
1299
+ r.SD = 0;
1300
+ r.setRDScore(lambda);
1301
+ if (bestMode >= 0 && r.score >= rdI4.score)
1302
+ continue;
1303
+ r.SD = tlambda ? (tlambda * tDisto4x4(spectrum, tmpDst, td, WEIGHT_Y) + 128) >> 8 : 0;
1285
1304
  r.setRDScore(lambda);
1286
1305
  if (bestMode >= 0 && r.score >= rdI4.score)
1287
1306
  continue;
@@ -1337,9 +1356,11 @@ function pickBestUv(it, rd) {
1337
1356
  r.D = sse16(it.yuvIn, U_OFF, tmpDst, U_OFF, 8);
1338
1357
  r.SD = 0;
1339
1358
  r.H = FIXED_COSTS_UV[mode];
1340
- r.R = costUv(it, r);
1341
- if (mode > 0 && isFlat(r.uvLevels, 0, 8, FLATNESS_LIMIT_UV))
1342
- r.R += FLATNESS_PENALTY * 8;
1359
+ r.R = mode > 0 && isFlat(r.uvLevels, 0, 8, FLATNESS_LIMIT_UV) ? FLATNESS_PENALTY * 8 : 0;
1360
+ r.setRDScore(lambda);
1361
+ if (mode > 0 && r.score >= rdBestUv.score)
1362
+ continue;
1363
+ r.R += costUv(it, r);
1343
1364
  r.setRDScore(lambda);
1344
1365
  if (mode === 0 || r.score < rdBestUv.score) {
1345
1366
  rdBestUv.copyScore(r);
package/dist/image.d.ts CHANGED
@@ -70,19 +70,19 @@ export interface JPEGEncodeOptions {
70
70
  export interface WebPEncodeOptions {
71
71
  /**
72
72
  * Lossy compression (0-100, like libwebp's quality: 75 is its default): the image is encoded like cwebp encodes it
73
- * with its default settings, much smaller than lossless. Without it the image is encoded losslessly
73
+ * (with `-m` set to the effort), much smaller than lossless. Without it the image is encoded losslessly
74
74
  */
75
75
  quality?: number;
76
76
  /**
77
77
  * How much effort lossy compression takes (0-6, libwebp's method): higher is smaller but slower. 0-2 pick the
78
78
  * predictions by how close they are, 3 and up also by how many bits they take, 5 and 6 also optimize the
79
- * quantized values. Default: `4` (like cwebp)
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
82
  /** Metadata to include, see {@link Metadata} */
83
83
  metadata?: Metadata;
84
84
  }
85
- /** Options of {@link Image.encodeTGA} */
85
+ /** Options of {@link Image.encodeTGA} and {@link Image.encodeJXL} */
86
86
  export interface EncodeOptions {
87
87
  /** Metadata to include, see {@link Metadata} */
88
88
  metadata?: Metadata;
@@ -142,6 +142,8 @@ export interface AVIFEncodeOptions {
142
142
  subsampling?: '4:4:4' | '4:2:0';
143
143
  /** How hard the encoder searches for the best modes: 0-2, faster to smaller. Default: `1` */
144
144
  effort?: number;
145
+ /** Metadata to include, see {@link Metadata} */
146
+ metadata?: Metadata;
145
147
  }
146
148
  /** Text style options of {@link Image.renderText} */
147
149
  export interface TextStyle {
@@ -769,13 +771,15 @@ export declare class Image {
769
771
  * Encodes the image as AVIF (AV1, with an alpha image if the image has transparency)
770
772
  * @param options See {@link AVIFEncodeOptions}
771
773
  */
772
- encodeAVIF({ quality, alphaQuality, subsampling, effort }?: AVIFEncodeOptions): Promise<Uint8Array>;
774
+ encodeAVIF({ quality, alphaQuality, subsampling, effort, metadata }?: AVIFEncodeOptions): Promise<Uint8Array>;
773
775
  /**
774
- * Encodes the image as lossless JPEG XL, byte for byte like libjxl's `cjxl -e 1` on CPUs with AVX2 or NEON (its
775
- * fast lossless mode: the gradient predictor, a palette if the image has at most 511 colors besides black, else
776
- * YCoCg); greyscale if the image is, with alpha if it has transparency
776
+ * Encodes the image as lossless JPEG XL, the codestream byte for byte like libjxl's `cjxl -e 1` on CPUs with AVX2
777
+ * or NEON (its fast lossless mode: the gradient predictor, a palette if the image has at most 511 colors besides
778
+ * black, else YCoCg); greyscale if the image is, with alpha if it has transparency. The codestream is in the
779
+ * container, with the metadata as Exif
780
+ * @param options See {@link EncodeOptions}
777
781
  */
778
- encodeJXL(): Promise<Uint8Array>;
782
+ encodeJXL({ metadata }?: EncodeOptions): Promise<Uint8Array>;
779
783
  /**
780
784
  * Encodes the image as the smallest fitting Netpbm format: PBM for black and white images, PGM for greyscale ones,
781
785
  * PPM for others, PAM if the image has transparency
package/dist/image.js CHANGED
@@ -1004,7 +1004,7 @@ export class Image {
1004
1004
  const m = resolveMetadata(metadata);
1005
1005
  return jpeg.encode(this.__bytes__(), this.width, this.height, finite(quality, 'quality'), { exif: exifData(m), comment: m.comment ? utf8(m.comment) : undefined });
1006
1006
  }
1007
- async encodeWebP({ quality, effort = 4, metadata = {} } = {}) {
1007
+ async encodeWebP({ quality, effort = 2, metadata = {} } = {}) {
1008
1008
  const exif = exifData(resolveMetadata(metadata));
1009
1009
  if (quality === undefined)
1010
1010
  return webp.encode(this.__bytes__(), this.width, this.height, exif);
@@ -1025,11 +1025,12 @@ export class Image {
1025
1025
  async encodeQOI() {
1026
1026
  return qoi.encode(this.__bytes__(), this.width, this.height);
1027
1027
  }
1028
- async encodeAVIF({ quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1 } = {}) {
1029
- return avifEnc.encode(this.__bytes__(), this.width, this.height, { quality: finite(quality, 'quality'), alphaQuality: finite(alphaQuality, 'alphaQuality'), subsampling, effort });
1028
+ async encodeAVIF({ quality = 60, alphaQuality = 100, subsampling = '4:4:4', effort = 1, metadata = {} } = {}) {
1029
+ const exif = exifData(resolveMetadata(metadata));
1030
+ return avifEnc.encode(this.__bytes__(), this.width, this.height, { quality: finite(quality, 'quality'), alphaQuality: finite(alphaQuality, 'alphaQuality'), subsampling, effort, exif });
1030
1031
  }
1031
- async encodeJXL() {
1032
- return jxl.encode(this.__bytes__(), this.width, this.height);
1032
+ async encodeJXL({ metadata = {} } = {}) {
1033
+ return jxl.encode(this.__bytes__(), this.width, this.height, exifData(resolveMetadata(metadata)));
1033
1034
  }
1034
1035
  async encodePNM() {
1035
1036
  return netpbm.encode(this.__bytes__(), this.width, this.height);
@@ -5,7 +5,7 @@
5
5
  * |---|---|
6
6
  * | PNG, APNG | all (as text chunks) |
7
7
  * | JPEG | author, description, copyright, creation time, software (Exif); comment (comment marker) |
8
- * | WebP | author, description, copyright, creation time, software (Exif) |
8
+ * | WebP, AVIF, JPEG XL | author, description, copyright, creation time, software (Exif) |
9
9
  * | GIF | software, comment (comment extensions) |
10
10
  * | TGA | author, comment, creation time, software (extension area) |
11
11
  *
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '3.5.0';
1
+ export const VERSION = '3.6.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imagescript",
3
- "version": "3.5.0",
3
+ "version": "3.6.0",
4
4
  "description": "zero-dependency javascript image manipulation",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",