imagescript 4.1.0 → 4.2.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.
@@ -84,19 +84,21 @@ export class AnimationEncoder {
84
84
  this.optimizer = null;
85
85
  return this.format.file(optimizer);
86
86
  }
87
- static __webp__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 }) {
87
+ static __webp__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100, threads = Math.max(1, Math.min(availableThreads(false), 8)) }) {
88
88
  boolean(optimize, 'optimize');
89
+ checkThreads(threads);
89
90
  const loops = fitLoops(loopCount(count), 'WebP');
90
91
  [width, height] = canvas(width, height, 'WebP');
91
92
  checkFormatSize('WebP', width, height, 1 << 24);
92
93
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
93
- const resolved = resolveMetadata(metadata), chunks = [];
94
- let alpha = false;
94
+ const resolved = resolveMetadata(metadata), encoder = new webp.FrameEncoder(lossy, effort, threads);
95
+ let alpha = false, first = true;
95
96
  const compositor = optimize ? null : new Compositor(width, height);
96
97
  let full = false;
97
98
  const add = async (f) => {
98
- alpha ||= webp.needsAlpha(f, !chunks.length, width, height);
99
- chunks.push(await webp.frameChunk(f, lossy, effort));
99
+ alpha ||= webp.needsAlpha(f, first, width, height);
100
+ first = false;
101
+ await encoder.add(f);
100
102
  };
101
103
  return new AnimationEncoder(width, height, {
102
104
  name: 'WebP',
@@ -111,7 +113,7 @@ export class AnimationEncoder {
111
113
  return add({ x: 0, y: 0, width, height, duration: input.duration, dispose: true, blend: false, pixels: shown });
112
114
  await add(webpFrame(input));
113
115
  },
114
- file: () => webp.animationFile(chunks, width, height, toPlays(loops), alpha, exifData(resolved))
116
+ file: async () => webp.animationFile(await encoder.finish(), width, height, toPlays(loops), alpha, exifData(resolved))
115
117
  }, optimize);
116
118
  }
117
119
  static __gif__(width, height, { loopCount: count = Infinity, metadata = {}, optimize = true, colors = 256, dither = 'floyd-steinberg', ditherStrength = 0.85 }) {
@@ -40,10 +40,24 @@ export interface AnimationEncodeOptions extends EncodeOptions {
40
40
  }
41
41
  /**
42
42
  * Options of {@link Animation.encodeWebP} and {@link Animation.webpEncoder}: those of {@link WebPEncodeOptions} for every
43
- * frame (but `threads`: the frames are encoded one at a time), and the animation options. Without `quality` the frames
44
- * are lossless
43
+ * frame, and the animation options. Without `quality` the frames are lossless
45
44
  */
46
45
  export interface WebPAnimationEncodeOptions extends Omit<WebPEncodeOptions, 'threads'>, AnimationEncodeOptions {
46
+ /**
47
+ * Maximum threads: lossy and lossless frames are encoded several at a time, one on each thread, and the file is the
48
+ * same for any number. The calling thread is one of them, so `2` starts one worker. {@link Animation.encodeWebP}
49
+ * adds a worker per half megapixel of frames (none for animations of less than a megapixel in all, or of one frame);
50
+ * {@link Animation.webpEncoder}, which can't know how many frames are to come, starts 1 once its `add` calls have
51
+ * taken about 0.15 seconds and twice as many each time that has doubled, and stops them after a second without
52
+ * frames
53
+ * @remarks
54
+ * Unlike other formats' threads this needs no shared memory, so it also works on browser pages that aren't
55
+ * cross-origin isolated. Where workers can't start, the work runs on the calling thread with the same output. That
56
+ * includes pages that load the package from another origin (a CDN such as jsDelivr), which browsers don't allow to
57
+ * start workers
58
+ * @defaultValue The available processors, up to 8
59
+ */
60
+ threads?: number;
47
61
  }
48
62
  /**
49
63
  * Options of {@link Animation.encodeGIF} and {@link Animation.gifEncoder}: those of {@link GIFEncodeOptions} for every
package/dist/animation.js CHANGED
@@ -347,14 +347,15 @@ export class Animation {
347
347
  }
348
348
  async encodeWebP(options = {}) {
349
349
  checkOptions(options, 'animation.encodeWebP({ quality: 80 })');
350
- const { metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100 } = options;
350
+ const { metadata = {}, optimize = true, quality, effort = 2, sharpYuv = false, alphaQuality = 100, threads = Math.max(1, Math.min(availableThreads(false), 8)) } = options;
351
351
  boolean(optimize, 'optimize');
352
+ checkThreads(threads);
352
353
  const loops = fitLoops(this.loopCount, 'WebP');
353
354
  this.__validate__('WebP');
354
355
  const lossy = webp.lossyOptions(quality, effort, sharpYuv, alphaQuality);
355
356
  const tolerance = lossy ? webp.lossyTolerance(lossy.quality) : undefined;
356
357
  const frames = optimize ? this.__optimized__({ replace: true, even: true, alpha: 'frame', tolerance, maxDuration: maxDuration('WebP') }) : this.__webpFrames__();
357
- return webp.encodeAnimation(frames, this.width, this.height, toPlays(loops), exifData(resolveMetadata(metadata)), lossy, effort);
358
+ return webp.encodeAnimation(frames, this.width, this.height, toPlays(loops), exifData(resolveMetadata(metadata)), lossy, effort, threads);
358
359
  }
359
360
  __webpFrames__() {
360
361
  const width = this.width, height = this.height;
@@ -62,11 +62,14 @@ export function encodeFrame(frame, colors, transparent) {
62
62
  writeSubBlocks(out, lzwEncode(indices, minCodeSize));
63
63
  return out.finish();
64
64
  }
65
+ let dictionary;
66
+ const keys = new Int32Array(4096);
67
+ let used = 0;
65
68
  function lzwEncode(indices, minCodeSize) {
66
69
  const out = new GIFWriter(indices.length);
67
70
  const clear = 1 << minCodeSize;
68
71
  const eoi = clear + 1;
69
- const dictionary = new Int16Array(4096 * 256);
72
+ const table = dictionary ??= new Int16Array(4096 * 256);
70
73
  let codeSize = 0, next = 0, buffer = 0, bufferBits = 0;
71
74
  const emit = (code) => {
72
75
  buffer |= code << bufferBits;
@@ -78,7 +81,9 @@ function lzwEncode(indices, minCodeSize) {
78
81
  }
79
82
  };
80
83
  const reset = () => {
81
- dictionary.fill(0);
84
+ for (let i = 0; i < used; i++)
85
+ table[keys[i]] = 0;
86
+ used = 0;
82
87
  codeSize = minCodeSize + 1;
83
88
  next = eoi + 1;
84
89
  };
@@ -94,14 +99,15 @@ function lzwEncode(indices, minCodeSize) {
94
99
  for (let i = 1; i < indices.length; i++) {
95
100
  const index = indices[i];
96
101
  const key = prefix << 8 | index;
97
- const code = dictionary[key];
102
+ const code = table[key];
98
103
  if (code) {
99
104
  prefix = code;
100
105
  continue;
101
106
  }
102
107
  emit(prefix);
103
108
  if (next <= MAX_CODE) {
104
- dictionary[key] = next;
109
+ table[key] = next;
110
+ keys[used++] = key;
105
111
  if (next === 1 << codeSize && codeSize < 12)
106
112
  codeSize++;
107
113
  next++;
@@ -56,8 +56,7 @@ function textChunks(text) {
56
56
  }
57
57
  return chunks;
58
58
  }
59
- function filter(data, rowBytes, y0, y1, bpp) {
60
- const out = new Uint8Array((y1 - y0) * (rowBytes + 1));
59
+ function filter(data, rowBytes, y0, y1, bpp, out = new Uint8Array((y1 - y0) * (rowBytes + 1))) {
61
60
  for (let y = y0; y < y1; y++) {
62
61
  const row = y * rowBytes, o = (y - y0) * (rowBytes + 1) + 1;
63
62
  out[o - 1] = 4;
@@ -68,6 +67,10 @@ function filter(data, rowBytes, y0, y1, bpp) {
68
67
  }
69
68
  for (let i = 0; i < bpp; i++)
70
69
  out[o + i] = data[row + i] - data[row + i - rowBytes];
70
+ if (bpp === 3 || bpp === 4) {
71
+ paethRowFilter(data, row, rowBytes, out, o, bpp);
72
+ continue;
73
+ }
71
74
  for (let i = bpp; i < rowBytes; i++) {
72
75
  const a = data[row + i - bpp], b = data[row + i - rowBytes], c = data[row + i - rowBytes - bpp];
73
76
  const pa = Math.abs(b - c), pb = Math.abs(a - c), pc = Math.abs(a + b - 2 * c);
@@ -77,6 +80,50 @@ function filter(data, rowBytes, y0, y1, bpp) {
77
80
  }
78
81
  return out;
79
82
  }
83
+ function paethRowFilter(data, row, rowBytes, out, o, bpp) {
84
+ const up = row - rowBytes;
85
+ let a0 = data[row], a1 = data[row + 1], a2 = data[row + 2], a3 = bpp === 4 ? data[row + 3] : 0;
86
+ let c0 = data[up], c1 = data[up + 1], c2 = data[up + 2], c3 = bpp === 4 ? data[up + 3] : 0;
87
+ for (let i = bpp; i < rowBytes; i += bpp) {
88
+ let x = data[row + i], b = data[up + i], pa = Math.abs(b - c0), pb = Math.abs(a0 - c0), pc = Math.abs(a0 + b - 2 * c0);
89
+ let notA = (pb - pa | pc - pa) >> 31, takeC = (pc - pb) >> 31;
90
+ out[o + i] = x - (a0 ^ (a0 ^ b ^ (b ^ c0) & takeC) & notA);
91
+ a0 = x;
92
+ c0 = b;
93
+ x = data[row + i + 1];
94
+ b = data[up + i + 1];
95
+ pa = Math.abs(b - c1);
96
+ pb = Math.abs(a1 - c1);
97
+ pc = Math.abs(a1 + b - 2 * c1);
98
+ notA = (pb - pa | pc - pa) >> 31;
99
+ takeC = (pc - pb) >> 31;
100
+ out[o + i + 1] = x - (a1 ^ (a1 ^ b ^ (b ^ c1) & takeC) & notA);
101
+ a1 = x;
102
+ c1 = b;
103
+ x = data[row + i + 2];
104
+ b = data[up + i + 2];
105
+ pa = Math.abs(b - c2);
106
+ pb = Math.abs(a2 - c2);
107
+ pc = Math.abs(a2 + b - 2 * c2);
108
+ notA = (pb - pa | pc - pa) >> 31;
109
+ takeC = (pc - pb) >> 31;
110
+ out[o + i + 2] = x - (a2 ^ (a2 ^ b ^ (b ^ c2) & takeC) & notA);
111
+ a2 = x;
112
+ c2 = b;
113
+ if (bpp === 4) {
114
+ x = data[row + i + 3];
115
+ b = data[up + i + 3];
116
+ pa = Math.abs(b - c3);
117
+ pb = Math.abs(a3 - c3);
118
+ pc = Math.abs(a3 + b - 2 * c3);
119
+ notA = (pb - pa | pc - pa) >> 31;
120
+ takeC = (pc - pb) >> 31;
121
+ out[o + i + 3] = x - (a3 ^ (a3 ^ b ^ (b ^ c3) & takeC) & notA);
122
+ a3 = x;
123
+ c3 = b;
124
+ }
125
+ }
126
+ }
80
127
  function prefix(data, rowBytes, y0, y1) {
81
128
  const out = new Uint8Array((y1 - y0) * (rowBytes + 1));
82
129
  for (let y = y0; y < y1; y++)
@@ -99,7 +146,16 @@ async function compressRows(data, width, height, channels, depth, level, filterR
99
146
  filteredSamples.push(filter(data, rowBytes, y, end, bpp));
100
147
  }
101
148
  const [unfiltered, filtered] = await limited(2, threads, i => compressParallel(concat(i ? filteredSamples : unfilteredSamples), level, Math.max(1, Math.floor(threads / 2))));
102
- return compressParallel(unfiltered.length < filtered.length ? prefix(data, rowBytes, 0, height) : filter(data, rowBytes, 0, height, bpp), level, threads);
149
+ if (unfiltered.length < filtered.length)
150
+ return compressParallel(prefix(data, rowBytes, 0, height), level, threads);
151
+ const stride = rowBytes + 1, all = new Uint8Array(height * stride);
152
+ let rows = 0;
153
+ return compressParallel(all, level, threads, (_from, to) => {
154
+ const end = Math.min(height, Math.ceil(to / stride));
155
+ if (end > rows)
156
+ filter(data, rowBytes, rows, end, bpp, all.subarray(rows * stride, end * stride));
157
+ rows = Math.max(rows, end);
158
+ });
103
159
  }
104
160
  function chunk(type, body) {
105
161
  const out = new Uint8Array(body.length + 12);
@@ -536,6 +592,8 @@ function imagePixels(p, data, width, height) {
536
592
  const { passes, expected } = passesOf(p, width, height);
537
593
  if (data.length < expected)
538
594
  throw new Error('PNG: image data is truncated');
595
+ if (!interlace && colorType === 6 && depth === 8)
596
+ return unfilter(data, 0, height, width * 4, 4, true);
539
597
  const rgba = new Uint8Array(width * height * 4);
540
598
  const toRGBA = createConverter(colorType, depth, p.palette, p.transparency);
541
599
  let dataOffset = 0;
@@ -209,8 +209,29 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
209
209
  }
210
210
  const rowBytes = Math.ceil(width * samplesPerRow * bps / 8);
211
211
  const planeBytes = rowBytes * height;
212
- const raw = new Uint8Array(planeBytes * planes);
213
212
  const segmentRowBytes = Math.ceil(segmentWidth * samplesPerRow * bps / 8);
213
+ const sampleLittle = predictor === 3 ? true : little;
214
+ const common = !planar && (bps === 8 || bps === 16) && sampleFormat !== 2 && sampleFormat !== 3 && photometric <= 2;
215
+ const high = bps === 16 ? (sampleLittle ? 1 : 0) : -1;
216
+ if (common && !tiled) {
217
+ for (let s = 0; s < segmentsPerPlane; s++) {
218
+ const sy = s * segmentHeight, rows = Math.min(segmentHeight, height - sy);
219
+ if (rows <= 0)
220
+ break;
221
+ const expected = rows * rowBytes, stored = segment(s);
222
+ const inPlace = fillOrder === 2 || predictor === 2 || predictor === 3;
223
+ const bytes = compression === 1 && !inPlace && stored.length >= expected ? stored : await decompressSegment(stored, compression, expected);
224
+ if (fillOrder === 2)
225
+ reverseBits(bytes);
226
+ if (predictor === 2)
227
+ undoHorizontalPredictor(bytes, rowBytes, rows, samplesPerRow, bps, little);
228
+ else if (predictor === 3)
229
+ undoFloatingPointPredictor(bytes, rowBytes, rows, samplesPerRow, bps);
230
+ rowsToRGBA(bytes, width, rows, rowBytes, samplesPerPixel, high, photometric, alphaChannel, alphaType === 1, pixels.subarray(sy * width * 4));
231
+ }
232
+ return { width, height, pixels, orientation, icc };
233
+ }
234
+ const raw = new Uint8Array(planeBytes * planes);
214
235
  for (let plane = 0; plane < planes; plane++) {
215
236
  for (let s = 0; s < segmentsPerPlane; s++) {
216
237
  const sx = (s % segmentsAcross) * segmentWidth;
@@ -238,9 +259,8 @@ export async function decode(data, maxPixels = MAX_PIXELS) {
238
259
  }
239
260
  }
240
261
  }
241
- const sampleLittle = predictor === 3 ? true : little;
242
- if (!planar && (bps === 8 || bps === 16) && sampleFormat !== 2 && sampleFormat !== 3 && photometric <= 2) {
243
- rowsToRGBA(raw, width, height, rowBytes, samplesPerPixel, bps === 16 ? (sampleLittle ? 1 : 0) : -1, photometric, alphaChannel, alphaType === 1, pixels);
262
+ if (common) {
263
+ rowsToRGBA(raw, width, height, rowBytes, samplesPerPixel, high, photometric, alphaChannel, alphaType === 1, pixels);
244
264
  return { width, height, pixels, orientation, icc };
245
265
  }
246
266
  const readSample = sampleReader(raw, bps, sampleFormat, sampleLittle, sampleFormat === 3 ? floatRange(raw, bps, sampleLittle) : null);
@@ -329,18 +329,183 @@ export function lossyTolerance(quality) {
329
329
  const value = Math.sqrt(quality / 100);
330
330
  return Math.max(1, Math.round(31 * (1 - value) + value));
331
331
  }
332
- export async function encodeAnimation(frames, width, height, plays, exif, lossy, effort = 2) {
332
+ export async function encodeAnimation(frames, width, height, plays, exif, lossy, effort = 2, threads = 1) {
333
333
  if (!frames.length)
334
334
  throw new RangeError('WebP: an animation needs at least one frame, not 0');
335
335
  checkFormatSize('WebP', width, height, 1 << 24);
336
336
  let alpha = false;
337
337
  for (const [i, f] of frames.entries())
338
338
  alpha ||= needsAlpha(f, i === 0, width, height);
339
- const chunks = [];
339
+ let total = 0;
340
340
  for (const f of frames)
341
- chunks.push(await frameChunk(f, lossy, effort));
342
- return animationFile(chunks, width, height, plays, alpha, exif);
341
+ total += f.width * f.height;
342
+ const encoder = new FrameEncoder(lossy, effort, threads, { frames: frames.length, total });
343
+ for (const f of frames)
344
+ await encoder.add(f);
345
+ return animationFile(await encoder.finish(), width, height, plays, alpha, exif);
346
+ }
347
+ const runtime = globalThis;
348
+ const now = () => runtime.performance ? runtime.performance.now() : Date.now();
349
+ const Channel = globalThis.MessageChannel;
350
+ function nextTask() {
351
+ return new Promise(resolve => {
352
+ if (!Channel)
353
+ return void runtime.setTimeout(resolve, 0);
354
+ const { port1, port2 } = new Channel();
355
+ port1.onmessage = () => {
356
+ port1.close();
357
+ resolve();
358
+ };
359
+ port2.postMessage(null);
360
+ });
361
+ }
362
+ const PIXELS_PER_FRAME_THREAD = 512 << 10, MIN_THREADED_ANIMATION_PIXELS = 2 * PIXELS_PER_FRAME_THREAD, STREAMED_MS_BEFORE_THREADS = 150;
363
+ const IDLE_MS = 1000;
364
+ export class FrameEncoder {
365
+ lossy;
366
+ effort;
367
+ threads;
368
+ known;
369
+ chunks = [];
370
+ spent = 0;
371
+ wasted = false;
372
+ given = false;
373
+ pool = null;
374
+ idle = [];
375
+ broken = false;
376
+ generation = 0;
377
+ running = new Set();
378
+ failure = null;
379
+ adding = false;
380
+ timer = null;
381
+ constructor(lossy, effort, threads, known) {
382
+ this.lossy = lossy;
383
+ this.effort = effort;
384
+ this.threads = threads;
385
+ this.known = known;
386
+ }
387
+ async add(f) {
388
+ if (f.x & 1 || f.y & 1)
389
+ throw new RangeError('WebP: frame offsets have to be even');
390
+ this.check();
391
+ this.adding = true;
392
+ const begin = now();
393
+ try {
394
+ await this.encode(f);
395
+ }
396
+ finally {
397
+ this.spent += now() - begin;
398
+ this.adding = false;
399
+ this.stopIdle();
400
+ }
401
+ }
402
+ async encode(f) {
403
+ const i = this.chunks.length;
404
+ this.chunks.push(new Uint8Array(0));
405
+ if (this.pool && !this.idle.length && !this.broken) {
406
+ await nextTask();
407
+ this.check();
408
+ }
409
+ if (!this.broken && !this.wasted && this.threads > 1)
410
+ this.grow(this.wanted());
411
+ if (!this.idle.length || this.broken) {
412
+ this.chunks[i] = await frameChunk(f, this.lossy, this.effort);
413
+ return;
414
+ }
415
+ const thread = this.idle.pop();
416
+ this.given = true;
417
+ this.track(thread, thread.run({ task: 'webp-frame', frame: f, lossy: this.lossy, effort: this.effort })
418
+ .then(chunk => {
419
+ this.chunks[i] = chunk;
420
+ }, async () => {
421
+ this.chunks[i] = await frameChunk(f, this.lossy, this.effort);
422
+ return false;
423
+ }));
424
+ }
425
+ wanted() {
426
+ if (this.known)
427
+ return this.known.total < MIN_THREADED_ANIMATION_PIXELS || this.known.frames < 2 ? 0 : Math.min(this.threads - 1, this.known.frames, Math.floor(this.known.total / PIXELS_PER_FRAME_THREAD));
428
+ return this.spent < STREAMED_MS_BEFORE_THREADS ? 0 : Math.min(this.threads - 1, 2 ** (1 + Math.floor(Math.log2(this.spent / STREAMED_MS_BEFORE_THREADS))));
429
+ }
430
+ grow(n) {
431
+ const have = this.pool?.length ?? 0;
432
+ if (n <= have)
433
+ return;
434
+ const added = startThreads(n - have, false);
435
+ if (!added) {
436
+ this.broken = true;
437
+ return;
438
+ }
439
+ if (!this.pool)
440
+ this.given = false;
441
+ this.pool = [...this.pool ?? [], ...added];
442
+ const generation = this.generation;
443
+ for (const thread of added)
444
+ void thread.run({ task: 'ready' }).then(() => {
445
+ if (generation === this.generation)
446
+ this.idle.push(thread);
447
+ }, () => {
448
+ this.broken = true;
449
+ });
450
+ }
451
+ track(thread, task) {
452
+ const generation = this.generation;
453
+ const done = task.then(result => {
454
+ if (result === false)
455
+ this.broken = true;
456
+ else if (generation === this.generation)
457
+ this.idle.push(thread);
458
+ }, (e) => {
459
+ this.failure ??= e instanceof Error ? e : new Error(String(e));
460
+ }).finally(() => {
461
+ this.running.delete(done);
462
+ this.stopIdle();
463
+ });
464
+ this.running.add(done);
465
+ }
466
+ async finish() {
467
+ await Promise.all(this.running);
468
+ this.close();
469
+ this.check();
470
+ return this.chunks;
471
+ }
472
+ stopIdle() {
473
+ if (this.timer !== null)
474
+ runtime.clearTimeout(this.timer);
475
+ this.timer = null;
476
+ if (!this.pool || this.running.size || this.adding)
477
+ return;
478
+ const timer = this.timer = runtime.setTimeout(() => {
479
+ if (this.timer !== timer)
480
+ return;
481
+ this.timer = null;
482
+ if (!this.running.size && !this.adding)
483
+ this.close();
484
+ }, IDLE_MS);
485
+ if (typeof timer.unref === 'function')
486
+ timer.unref();
487
+ else
488
+ runtime.Deno?.unrefTimer?.(timer);
489
+ }
490
+ close() {
491
+ if (this.timer !== null)
492
+ runtime.clearTimeout(this.timer);
493
+ this.timer = null;
494
+ if (this.pool && !this.given)
495
+ this.wasted = true;
496
+ if (this.pool)
497
+ for (const t of this.pool)
498
+ t.terminate();
499
+ this.generation++;
500
+ this.pool = null;
501
+ this.idle = [];
502
+ }
503
+ check() {
504
+ if (this.failure)
505
+ throw this.failure;
506
+ }
343
507
  }
508
+ export const frameTask = ({ frame, lossy, effort }) => frameChunk(frame, lossy, effort);
344
509
  export function needsAlpha(f, first, width, height) {
345
510
  return (first && (f.x > 0 || f.y > 0 || f.width < width || f.height < height)) || f.dispose || hasAlpha(f.pixels);
346
511
  }
@@ -518,8 +518,8 @@ function deflate(dat, lvl, plvl, pre, post) {
518
518
  }
519
519
  return o.subarray(0, pre + shft(pos) + post);
520
520
  }
521
- function adler32(data) {
522
- let a = 1, b = 0;
521
+ function adler32(data, previous = 1) {
522
+ let a = previous & 65535, b = previous >>> 16;
523
523
  for (let i = 0; i < data.length;) {
524
524
  const e = Math.min(i + 2655, data.length);
525
525
  for (; i < e; ++i)
@@ -615,17 +615,30 @@ export async function limited(count, limit, run) {
615
615
  return results;
616
616
  }
617
617
  const PIECE = 1 << 20, WINDOW = 1 << 15;
618
- export async function compressParallel(data, level, threads = Infinity) {
618
+ export async function compressParallel(data, level, threads = Infinity, fill) {
619
619
  level = Math.min(9, Math.max(0, level | 0));
620
620
  const zlib = nodeZlib;
621
- if (!zlib || !zlib.deflate || !zlib.deflateRaw)
621
+ if (!zlib || !zlib.deflate || !zlib.deflateRaw) {
622
+ fill?.(0, data.length);
622
623
  return compressAsync(data, level);
624
+ }
623
625
  const done = (resolve, reject) => (error, result) => error ? reject(error) : resolve(plain(result));
624
- if (data.length < 2 * PIECE)
626
+ if (data.length < 2 * PIECE) {
627
+ fill?.(0, data.length);
625
628
  return new Promise((resolve, reject) => zlib.deflate?.(data, { level }, done(resolve, reject)));
629
+ }
626
630
  const count = Math.ceil(data.length / PIECE);
631
+ let made = 0, checksum = 1;
632
+ const make = (end) => {
633
+ if (end <= made)
634
+ return;
635
+ fill?.(made, end);
636
+ checksum = adler32(data.subarray(made, end), checksum);
637
+ made = end;
638
+ };
627
639
  const pieces = await limited(count, threads, i => {
628
640
  const start = i * PIECE;
641
+ make(Math.min(data.length, start + PIECE));
629
642
  const options = { level, finishFlush: i === count - 1 ? zlib.constants.Z_FINISH : zlib.constants.Z_SYNC_FLUSH };
630
643
  if (i)
631
644
  options.dictionary = data.subarray(start - WINDOW, start);
@@ -643,7 +656,6 @@ export async function compressParallel(data, level, threads = Infinity) {
643
656
  out.set(piece, offset);
644
657
  offset += piece.length;
645
658
  }
646
- const checksum = adler32(data);
647
659
  out[offset] = checksum >>> 24;
648
660
  out[offset + 1] = checksum >> 16 & 255;
649
661
  out[offset + 2] = checksum >> 8 & 255;
package/dist/image.js CHANGED
@@ -1263,6 +1263,16 @@ export class Image {
1263
1263
  return null;
1264
1264
  const width = this.width, bgR = background >>> 24, bgG = background >>> 16 & 255, bgB = background >>> 8 & 255;
1265
1265
  const scratch = new Uint8ClampedArray(width * 4);
1266
+ const mixed = new Uint8ClampedArray(3 << 16), known = new Uint8Array(256);
1267
+ const mix = (sa) => {
1268
+ known[sa] = 1;
1269
+ const fa = sa / 255, ba = 1 - fa, a = fa + ba, r = bgR * ba, g = bgG * ba, b = bgB * ba;
1270
+ for (let c = 0, o = sa << 8; c < 256; c++, o++) {
1271
+ mixed[o] = (c * fa + r) / a;
1272
+ mixed[o + 65536] = (c * fa + g) / a;
1273
+ mixed[o + 131072] = (c * fa + b) / a;
1274
+ }
1275
+ };
1266
1276
  const row = (y) => {
1267
1277
  for (let x = 0, s = 4 * y * width, d = 0; x < width; x++, s += 4, d += 4) {
1268
1278
  const sa = src[s + 3];
@@ -1278,10 +1288,12 @@ export class Image {
1278
1288
  scratch[d + 2] = src[s + 2];
1279
1289
  continue;
1280
1290
  }
1281
- const fa = sa / 255, ba = 1 - fa, a = fa + ba;
1282
- scratch[d] = (src[s] * fa + bgR * ba) / a;
1283
- scratch[d + 1] = (src[s + 1] * fa + bgG * ba) / a;
1284
- scratch[d + 2] = (src[s + 2] * fa + bgB * ba) / a;
1291
+ if (!known[sa])
1292
+ mix(sa);
1293
+ const o = sa << 8;
1294
+ scratch[d] = mixed[o | src[s]];
1295
+ scratch[d + 1] = mixed[o + 65536 | src[s + 1]];
1296
+ scratch[d + 2] = mixed[o + 131072 | src[s + 2]];
1285
1297
  }
1286
1298
  };
1287
1299
  const gray = () => {
@@ -35,8 +35,8 @@ function thread(post, listen, terminate) {
35
35
  terminate,
36
36
  };
37
37
  }
38
- export function availableThreads() {
39
- if (typeof SharedArrayBuffer === 'undefined' || typeof Atomics === 'undefined' || globals.crossOriginIsolated === false)
38
+ export function availableThreads(shared = true) {
39
+ if (shared && (typeof SharedArrayBuffer === 'undefined' || typeof Atomics === 'undefined' || globals.crossOriginIsolated === false))
40
40
  return 0;
41
41
  if (!globals.Worker && !builtin('node:worker_threads'))
42
42
  return 0;
@@ -44,8 +44,8 @@ export function availableThreads() {
44
44
  const n = os ? os.availableParallelism ? os.availableParallelism() : os.cpus().length : globals.navigator?.hardwareConcurrency ?? 1;
45
45
  return Math.max(1, n | 0);
46
46
  }
47
- export function startThreads(n) {
48
- if (n < 1 || !availableThreads())
47
+ export function startThreads(n, shared = true) {
48
+ if (n < 1 || !availableThreads(shared))
49
49
  return null;
50
50
  const threads = [];
51
51
  try {
@@ -6,6 +6,7 @@ import { maskBlurChunks, maskingChunks } from "../codecs/jxl/aq-enc.js";
6
6
  import { coefficientChunks, hfTokenChunks, xybChunks } from "../codecs/jxl/vardct-enc.js";
7
7
  import { groupChunks, postChunks } from "../codecs/jxl/frame.js";
8
8
  import { modularGroupChunks, modularWriteChunks } from "../codecs/jxl/modular-lossless.js";
9
+ import { frameTask } from "../codecs/webp.js";
9
10
  const chunkTasks = {
10
11
  'avif-convert': conversionChunks,
11
12
  'avif-tiles': tileChunks,
@@ -23,7 +24,7 @@ const chunkTasks = {
23
24
  'jxl-post': postChunks,
24
25
  };
25
26
  const globals = globalThis;
26
- function handle(port, task) {
27
+ async function handle(port, task) {
27
28
  try {
28
29
  const message = (m) => port.post({ message: m });
29
30
  let result;
@@ -31,6 +32,10 @@ function handle(port, task) {
31
32
  result = searchRows(task, message);
32
33
  else if (task.task === 'av1-filter')
33
34
  result = filterTrials(task);
35
+ else if (task.task === 'webp-frame')
36
+ result = await frameTask(task);
37
+ else if (task.task === 'ready')
38
+ result = null;
34
39
  else if (task.task in chunkTasks) {
35
40
  const { counter, chunks } = task, run = chunkTasks[task.task](task);
36
41
  for (let chunk; (chunk = Atomics.add(counter, 0, 1)) < chunks;)
@@ -46,10 +51,10 @@ function handle(port, task) {
46
51
  }
47
52
  if (typeof globals.postMessage === 'function' && 'onmessage' in globals) {
48
53
  const port = { post: (m) => globals.postMessage(m) };
49
- globals.onmessage = e => handle(port, e.data);
54
+ globals.onmessage = e => void handle(port, e.data);
50
55
  }
51
56
  else {
52
57
  const { parentPort } = globals.process?.getBuiltinModule?.('node:worker_threads');
53
58
  const port = { post: (m) => parentPort.postMessage(m) };
54
- parentPort.on('message', m => handle(port, m));
59
+ parentPort.on('message', m => void handle(port, m));
55
60
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imagescript",
3
- "version": "4.1.0",
3
+ "version": "4.2.1",
4
4
  "description": "Pure TypeScript image processing that runs everywhere",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",