imagescript 3.9.0 → 3.11.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.
@@ -49,6 +49,7 @@ const DEFAULTS = {
49
49
  'writing-mode': 'lr-tb', 'text-rendering': 'auto'
50
50
  };
51
51
  const SAMPLES = 16;
52
+ const OFFSETS = Float64Array.from({ length: SAMPLES }, (_, s) => (s + 0.5) / SAMPLES);
52
53
  export function render(source, mode, size, images = new Map(), fonts = []) {
53
54
  if (typeof source !== 'string')
54
55
  source = decodeUTF8(source);
@@ -2662,6 +2663,16 @@ class Layer {
2662
2663
  return new Uint8Array(out.buffer);
2663
2664
  }
2664
2665
  }
2666
+ const scratch = (() => {
2667
+ const arrays = { f64: [], f32: [], i32: [] };
2668
+ const get = (kind, Type) => (slot, n) => {
2669
+ const list = arrays[kind];
2670
+ if (!list[slot] || list[slot].length < n)
2671
+ list[slot] = new Type(Math.max(n, 2 * (list[slot]?.length ?? 0), 64));
2672
+ return list[slot];
2673
+ };
2674
+ return { f64: get('f64', Float64Array), f32: get('f32', Float32Array), i32: get('i32', Int32Array) };
2675
+ })();
2665
2676
  function crisp(coverage, style) {
2666
2677
  if (style['shape-rendering'] !== 'crispEdges' && style['shape-rendering'] !== 'optimizeSpeed')
2667
2678
  return coverage;
@@ -2671,8 +2682,11 @@ function crisp(coverage, style) {
2671
2682
  return coverage;
2672
2683
  }
2673
2684
  function rasterize(polygons, evenOdd, width, height) {
2674
- const edges = [];
2675
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
2685
+ let numPoints = 0;
2686
+ for (const points of polygons)
2687
+ numPoints += points.length >> 1;
2688
+ const tops = scratch.f64(0, numPoints), bottoms = scratch.f64(1, numPoints), xs = scratch.f64(2, numPoints), slopes = scratch.f64(3, numPoints), dirs = scratch.i32(0, numPoints);
2689
+ let numEdges = 0, minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
2676
2690
  for (const points of polygons) {
2677
2691
  const n = points.length >> 1;
2678
2692
  if (n < 2)
@@ -2685,15 +2699,18 @@ function rasterize(polygons, evenOdd, width, height) {
2685
2699
  continue;
2686
2700
  const down = ay < by;
2687
2701
  const top = down ? ay : by, bottom = down ? by : ay;
2688
- const topX = down ? ax : bx;
2689
- edges.push({ top, bottom, x: topX, slope: (down ? bx - ax : ax - bx) / (bottom - top), dir: down ? 1 : -1 });
2702
+ tops[numEdges] = top;
2703
+ bottoms[numEdges] = bottom;
2704
+ xs[numEdges] = down ? ax : bx;
2705
+ slopes[numEdges] = (down ? bx - ax : ax - bx) / (bottom - top);
2706
+ dirs[numEdges++] = down ? 1 : -1;
2690
2707
  minY = Math.min(minY, top);
2691
2708
  maxY = Math.max(maxY, bottom);
2692
2709
  minX = Math.min(minX, ax, bx);
2693
2710
  maxX = Math.max(maxX, ax, bx);
2694
2711
  }
2695
2712
  }
2696
- if (!edges.length)
2713
+ if (!numEdges)
2697
2714
  return null;
2698
2715
  const x0 = Math.max(0, Math.floor(minX)), x1 = Math.min(width, Math.ceil(maxX));
2699
2716
  const y0 = Math.max(0, Math.floor(minY)), y1 = Math.min(height, Math.ceil(maxY));
@@ -2701,13 +2718,24 @@ function rasterize(polygons, evenOdd, width, height) {
2701
2718
  return null;
2702
2719
  const w = x1 - x0, h = y1 - y0;
2703
2720
  const data = new Float32Array(w * h);
2704
- const row = new Float32Array(w + 2);
2705
- const steps = new Float32Array(w + 2);
2721
+ const row = scratch.f32(0, w + 2);
2722
+ const steps = scratch.f32(1, w + 2);
2706
2723
  const weight = 1 / SAMPLES;
2707
- edges.sort((a, b) => a.top - b.top);
2708
- let next = 0;
2709
- let active = [];
2710
- const crossings = [];
2724
+ const rowStarts = scratch.i32(1, h + 1).fill(0, 0, h + 1), order = scratch.i32(2, numEdges);
2725
+ const startRow = (e) => Math.max(0, Math.floor(tops[e]) - y0);
2726
+ for (let e = 0; e < numEdges; e++)
2727
+ if (startRow(e) < h)
2728
+ rowStarts[startRow(e) + 1]++;
2729
+ for (let r = 0; r < h; r++)
2730
+ rowStarts[r + 1] += rowStarts[r];
2731
+ const placed = scratch.i32(3, h);
2732
+ placed.set(rowStarts.subarray(0, h));
2733
+ for (let e = 0; e < numEdges; e++)
2734
+ if (startRow(e) < h)
2735
+ order[placed[startRow(e)]++] = e;
2736
+ let numActive = 0;
2737
+ const active = scratch.i32(4, numEdges), keys = scratch.f64(4, numEdges), firsts = scratch.i32(5, numEdges), lasts = scratch.i32(6, numEdges);
2738
+ const counts = new Int32Array(SAMPLES), starts = new Int32Array(SAMPLES), ends = new Int32Array(SAMPLES);
2711
2739
  const span = (a, b) => {
2712
2740
  a = Math.max(a, x0) - x0;
2713
2741
  b = Math.min(b, x1) - x0;
@@ -2724,23 +2752,69 @@ function rasterize(polygons, evenOdd, width, height) {
2724
2752
  }
2725
2753
  };
2726
2754
  for (let py = y0; py < y1; py++) {
2727
- row.fill(0);
2728
- steps.fill(0);
2729
- while (next < edges.length && edges[next].top < py + 1)
2730
- active.push(edges[next++]);
2731
- active = active.filter(edge => edge.bottom > py);
2755
+ row.fill(0, 0, w + 2);
2756
+ steps.fill(0, 0, w + 2);
2757
+ let kept = 0;
2758
+ for (let k = 0; k < numActive; k++)
2759
+ if (bottoms[active[k]] > py)
2760
+ active[kept++] = active[k];
2761
+ numActive = kept;
2762
+ for (let k = rowStarts[py - y0]; k < rowStarts[py - y0 + 1]; k++)
2763
+ active[numActive++] = order[k];
2764
+ const mid = py + 0.5;
2765
+ for (let k = 0; k < numActive; k++) {
2766
+ const e = active[k], key = xs[e] + (Math.min(Math.max(mid, tops[e]), bottoms[e]) - tops[e]) * slopes[e];
2767
+ let j = k - 1;
2768
+ for (; j >= 0 && keys[j] > key; j--) {
2769
+ keys[j + 1] = keys[j];
2770
+ active[j + 1] = active[j];
2771
+ }
2772
+ keys[j + 1] = key;
2773
+ active[j + 1] = e;
2774
+ }
2775
+ counts.fill(0);
2776
+ let total = 0;
2777
+ for (let k = 0; k < numActive; k++) {
2778
+ const e = active[k], top = tops[e], bottom = bottoms[e];
2779
+ let s0 = Math.max(0, Math.ceil((top - py) * SAMPLES - 0.5)), s1 = Math.min(SAMPLES - 1, Math.ceil((bottom - py) * SAMPLES - 0.5) - 1);
2780
+ while (s0 > 0 && py + OFFSETS[s0 - 1] >= top)
2781
+ s0--;
2782
+ while (s0 < SAMPLES && !(py + OFFSETS[s0] >= top))
2783
+ s0++;
2784
+ while (s1 < SAMPLES - 1 && py + OFFSETS[s1 + 1] < bottom)
2785
+ s1++;
2786
+ while (s1 >= 0 && !(py + OFFSETS[s1] < bottom))
2787
+ s1--;
2788
+ firsts[k] = s0;
2789
+ lasts[k] = s1;
2790
+ for (let s = s0; s <= s1; s++)
2791
+ counts[s]++;
2792
+ if (s1 >= s0)
2793
+ total += s1 - s0 + 1;
2794
+ }
2795
+ const crossings = scratch.f64(5, 2 * total);
2796
+ for (let s = 0, at = 0; s < SAMPLES; s++) {
2797
+ starts[s] = at;
2798
+ at += 2 * counts[s];
2799
+ }
2800
+ for (let s = 0; s < SAMPLES; s++)
2801
+ ends[s] = starts[s];
2802
+ for (let k = 0; k < numActive; k++) {
2803
+ const e = active[k];
2804
+ for (let s = firsts[k]; s <= lasts[k]; s++) {
2805
+ const sy = py + OFFSETS[s];
2806
+ crossings[ends[s]++] = xs[e] + (sy - tops[e]) * slopes[e];
2807
+ crossings[ends[s]++] = dirs[e];
2808
+ }
2809
+ }
2732
2810
  for (let s = 0; s < SAMPLES; s++) {
2733
- const sy = py + (s + 0.5) / SAMPLES;
2734
- crossings.length = 0;
2735
- for (const edge of active)
2736
- if (sy >= edge.top && sy < edge.bottom)
2737
- crossings.push(edge.x + (sy - edge.top) * edge.slope, edge.dir);
2738
- if (crossings.length < 4)
2811
+ const base = starts[s], end = ends[s];
2812
+ if (end - base < 4)
2739
2813
  continue;
2740
- for (let i = 2; i < crossings.length; i += 2) {
2814
+ for (let i = base + 2; i < end; i += 2) {
2741
2815
  const x = crossings[i], dir = crossings[i + 1];
2742
2816
  let j = i - 2;
2743
- for (; j >= 0 && crossings[j] > x; j -= 2) {
2817
+ for (; j >= base && crossings[j] > x; j -= 2) {
2744
2818
  crossings[j + 2] = crossings[j];
2745
2819
  crossings[j + 3] = crossings[j + 1];
2746
2820
  }
@@ -2748,7 +2822,7 @@ function rasterize(polygons, evenOdd, width, height) {
2748
2822
  crossings[j + 3] = dir;
2749
2823
  }
2750
2824
  let winding = 0;
2751
- for (let i = 0; i < crossings.length - 2; i += 2) {
2825
+ for (let i = base; i < end - 2; i += 2) {
2752
2826
  winding += crossings[i + 1];
2753
2827
  if (evenOdd ? winding & 1 : winding !== 0)
2754
2828
  span(crossings[i], crossings[i + 2]);
@@ -0,0 +1,102 @@
1
+ const globals = globalThis;
2
+ function builtin(id) {
3
+ try {
4
+ return globals.process?.getBuiltinModule?.(id) ?? null;
5
+ }
6
+ catch {
7
+ return null;
8
+ }
9
+ }
10
+ function thread(post, listen, terminate) {
11
+ let current = null;
12
+ listen(m => {
13
+ if (!current)
14
+ return;
15
+ if ('message' in m)
16
+ current.onMessage?.(m.message);
17
+ else {
18
+ const c = current;
19
+ current = null;
20
+ if (m.error !== undefined)
21
+ c.reject(new Error(m.error));
22
+ else
23
+ c.resolve(m.result);
24
+ }
25
+ }, e => {
26
+ const c = current;
27
+ current = null;
28
+ c?.reject(e);
29
+ });
30
+ return {
31
+ run: (task, onMessage) => new Promise((resolve, reject) => {
32
+ current = { resolve, reject, onMessage };
33
+ post(task);
34
+ }),
35
+ terminate,
36
+ };
37
+ }
38
+ export function availableThreads() {
39
+ if (typeof SharedArrayBuffer === 'undefined' || typeof Atomics === 'undefined' || globals.crossOriginIsolated === false)
40
+ return 0;
41
+ if (!globals.Worker && !builtin('node:worker_threads'))
42
+ return 0;
43
+ const os = builtin('node:os');
44
+ const n = os ? os.availableParallelism ? os.availableParallelism() : os.cpus().length : globals.navigator?.hardwareConcurrency ?? 1;
45
+ return Math.max(1, n | 0);
46
+ }
47
+ export function startThreads(n) {
48
+ if (n < 1 || !availableThreads())
49
+ return null;
50
+ const threads = [];
51
+ try {
52
+ for (let i = 0; i < n; i++) {
53
+ if (globals.Worker) {
54
+ const w = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
55
+ threads.push(thread(m => w.postMessage(m), (message, error) => {
56
+ w.onmessage = e => message(e.data);
57
+ w.onerror = e => {
58
+ e.preventDefault?.();
59
+ error(new Error(e.message ?? 'worker failed'));
60
+ };
61
+ }, () => w.terminate()));
62
+ }
63
+ else {
64
+ const { Worker } = builtin('node:worker_threads');
65
+ const url = import.meta.url;
66
+ const w = new Worker(new URL(url.endsWith('.ts') ? './worker.ts' : './worker.js', url));
67
+ w.unref();
68
+ threads.push(thread(m => w.postMessage(m), (message, error) => {
69
+ w.on('message', m => message(m));
70
+ w.on('error', e => error(e));
71
+ }, () => void w.terminate()));
72
+ }
73
+ }
74
+ return threads;
75
+ }
76
+ catch {
77
+ for (const t of threads)
78
+ t.terminate();
79
+ return null;
80
+ }
81
+ }
82
+ export async function runChunks(threads, task, count, local) {
83
+ const results = new Array(count);
84
+ if (!threads || count < 2) {
85
+ for (let i = 0; i < count; i++)
86
+ results[i] = local(i);
87
+ return results;
88
+ }
89
+ const counter = new Int32Array(new SharedArrayBuffer(4));
90
+ await Promise.all(threads.slice(0, count).map(t => t.run({ ...task, counter, chunks: count }, m => {
91
+ const { chunk, result } = m;
92
+ results[chunk] = result;
93
+ })));
94
+ return results;
95
+ }
96
+ export const sharedOf = (array) => array.buffer instanceof SharedArrayBuffer ? array : shared(array);
97
+ export function shared(array) {
98
+ const Type = array.constructor;
99
+ const copy = new Type(new SharedArrayBuffer(array.byteLength));
100
+ copy.set(array);
101
+ return copy;
102
+ }
@@ -0,0 +1,52 @@
1
+ import { searchRows, filterTrials } from "../codecs/av1/encode.js";
2
+ import { conversionChunks, tileChunks } from "../codecs/avif.js";
3
+ import { costChunks, predictorChunks } from "../codecs/vp8l.js";
4
+ import { varblockChunks } from "../codecs/jxl/acs-enc.js";
5
+ import { maskBlurChunks, maskingChunks } from "../codecs/jxl/aq-enc.js";
6
+ import { coefficientChunks, hfTokenChunks, xybChunks } from "../codecs/jxl/vardct-enc.js";
7
+ import { groupChunks, postChunks } from "../codecs/jxl/frame.js";
8
+ const chunkTasks = {
9
+ 'avif-convert': conversionChunks,
10
+ 'avif-tiles': tileChunks,
11
+ 'vp8l-predictor': predictorChunks,
12
+ 'vp8l-costs': costChunks,
13
+ 'jxl-xyb': xybChunks,
14
+ 'jxl-masking': maskingChunks,
15
+ 'jxl-mask-blur': maskBlurChunks,
16
+ 'jxl-varblocks': varblockChunks,
17
+ 'jxl-coefficients': coefficientChunks,
18
+ 'jxl-hf-tokens': hfTokenChunks,
19
+ 'jxl-groups': groupChunks,
20
+ 'jxl-post': postChunks,
21
+ };
22
+ const globals = globalThis;
23
+ function handle(port, task) {
24
+ try {
25
+ const message = (m) => port.post({ message: m });
26
+ let result;
27
+ if (task.task === 'av1-search')
28
+ result = searchRows(task, message);
29
+ else if (task.task === 'av1-filter')
30
+ result = filterTrials(task);
31
+ else if (task.task in chunkTasks) {
32
+ const { counter, chunks } = task, run = chunkTasks[task.task](task);
33
+ for (let chunk; (chunk = Atomics.add(counter, 0, 1)) < chunks;)
34
+ message({ chunk, result: run(chunk) });
35
+ }
36
+ else
37
+ throw new Error(`unknown task ${task.task}`);
38
+ port.post({ result });
39
+ }
40
+ catch (e) {
41
+ port.post({ error: String(e.stack ?? e) });
42
+ }
43
+ }
44
+ if (typeof globals.postMessage === 'function' && 'onmessage' in globals) {
45
+ const port = { post: (m) => globals.postMessage(m) };
46
+ globals.onmessage = e => handle(port, e.data);
47
+ }
48
+ else {
49
+ const { parentPort } = globals.process?.getBuiltinModule?.('node:worker_threads');
50
+ const port = { post: (m) => parentPort.postMessage(m) };
51
+ parentPort.on('message', m => handle(port, m));
52
+ }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = '3.9.0';
1
+ export const VERSION = '3.11.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imagescript",
3
- "version": "3.9.0",
3
+ "version": "3.11.0",
4
4
  "description": "zero-dependency javascript image manipulation",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",