imagescript 4.0.0 → 4.1.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.
@@ -4,7 +4,8 @@ import { concat } from "../util/mem.js";
4
4
  import { littleEndian } from "../util/alpha.js";
5
5
  import { encode as utf8, decode as utf8Decode } from "../util/utf8.js";
6
6
  import { orientation as exifOrientation, xmpOrientation } from "./exif.js";
7
- import { compressAsync, decompressAsync, decompress } from "./zlib.js";
7
+ import { RGBAPaletteBuilder, applyRGBAPalette } from "./quantize-rgba.js";
8
+ import { compressParallel, decompressAsync, decompress, limited } from "./zlib.js";
8
9
  const HEAD = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);
9
10
  const IHDR = 0x49484452;
10
11
  const PLTE = 0x504c5445;
@@ -24,7 +25,7 @@ const COLOR_TYPE_CHANNELS = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
24
25
  const CHANNELS_TO_COLOR_TYPE = { 1: 0, 2: 4, 3: 2, 4: 6 };
25
26
  const VALID_DEPTHS = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
26
27
  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]];
27
- export async function encode(data, { text, width, height, channels, depth = 8, level = 0, palette, transparency, filter: filterRows = false }) {
28
+ export async function encode(data, { text, width, height, channels, depth = 8, level = 0, threads = Infinity, palette, transparency, filter: filterRows = false }) {
28
29
  const header = new Uint8Array(13);
29
30
  const view = new DataView(header.buffer);
30
31
  view.setUint32(0, width);
@@ -37,7 +38,7 @@ export async function encode(data, { text, width, height, channels, depth = 8, l
37
38
  if (transparency)
38
39
  chunks.push(chunk(tRNS, transparency));
39
40
  chunks.push(...textChunks(text));
40
- chunks.push(chunk(IDAT, await compressRows(data, width, height, channels, depth, level, filterRows)));
41
+ chunks.push(chunk(IDAT, await compressRows(data, width, height, channels, depth, level, filterRows, threads)));
41
42
  chunks.push(chunk(IEND, new Uint8Array(0)));
42
43
  return concat([HEAD, ...chunks]);
43
44
  }
@@ -83,12 +84,12 @@ function prefix(data, rowBytes, y0, y1) {
83
84
  return out;
84
85
  }
85
86
  const SAMPLE_ROWS = 32, SAMPLE_STEP = 512;
86
- async function compressRows(data, width, height, channels, depth, level, filterRows) {
87
+ async function compressRows(data, width, height, channels, depth, level, filterRows, threads) {
87
88
  const rowBytes = Math.ceil(width * channels * depth / 8), bpp = Math.max(1, channels * depth / 8);
88
89
  if (!filterRows)
89
- return compressAsync(prefix(data, rowBytes, 0, height), level);
90
+ return compressParallel(prefix(data, rowBytes, 0, height), level, threads);
90
91
  if (height <= SAMPLE_ROWS) {
91
- const [unfiltered, filtered] = await Promise.all([compressAsync(prefix(data, rowBytes, 0, height), level), compressAsync(filter(data, rowBytes, 0, height, bpp), level)]);
92
+ const [unfiltered, filtered] = await limited(2, threads, i => compressParallel(i ? filter(data, rowBytes, 0, height, bpp) : prefix(data, rowBytes, 0, height), level, Math.max(1, Math.floor(threads / 2))));
92
93
  return unfiltered.length < filtered.length ? unfiltered : filtered;
93
94
  }
94
95
  const unfilteredSamples = [], filteredSamples = [];
@@ -97,8 +98,8 @@ async function compressRows(data, width, height, channels, depth, level, filterR
97
98
  unfilteredSamples.push(prefix(data, rowBytes, y, end));
98
99
  filteredSamples.push(filter(data, rowBytes, y, end, bpp));
99
100
  }
100
- const [unfiltered, filtered] = await Promise.all([compressAsync(concat(unfilteredSamples), level), compressAsync(concat(filteredSamples), level)]);
101
- return compressAsync(unfiltered.length < filtered.length ? prefix(data, rowBytes, 0, height) : filter(data, rowBytes, 0, height, bpp), level);
101
+ 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);
102
103
  }
103
104
  function chunk(type, body) {
104
105
  const out = new Uint8Array(body.length + 12);
@@ -151,12 +152,6 @@ export class AlphaCost {
151
152
  return transparent / opaque;
152
153
  }
153
154
  }
154
- function pixelFormat(images) {
155
- const scanner = new FormatScanner();
156
- for (const rgba of images)
157
- scanner.add(rgba);
158
- return scanner.format();
159
- }
160
155
  export class FormatScanner {
161
156
  opaque = true;
162
157
  gray = true;
@@ -180,8 +175,23 @@ export class FormatScanner {
180
175
  else
181
176
  this.colors.set(value, this.colors.size);
182
177
  }
183
- if (!this.colors && !this.opaque && !this.gray)
178
+ if (!this.colors && !this.gray) {
179
+ if (!this.opaque)
180
+ return;
181
+ if (littleEndian) {
182
+ let all = -1;
183
+ for (let j = i + 1; j < pixels.length; j++)
184
+ all &= pixels[j];
185
+ this.opaque = all >>> 24 === 255;
186
+ }
187
+ else
188
+ for (let j = (i + 1) * 4 + 3; j < rgba.length; j += 4)
189
+ if (rgba[j] !== 255) {
190
+ this.opaque = false;
191
+ break;
192
+ }
184
193
  return;
194
+ }
185
195
  }
186
196
  }
187
197
  format() {
@@ -249,24 +259,50 @@ function formatOf(colors, opaque, gray) {
249
259
  }
250
260
  };
251
261
  }
262
+ export { applyRGBAPalette };
263
+ export async function chooseFormat(each, lossy) {
264
+ const scanner = new FormatScanner(), builder = lossy ? new RGBAPaletteBuilder() : null;
265
+ for await (const pixels of each()) {
266
+ scanner.add(pixels);
267
+ builder?.count(pixels);
268
+ }
269
+ const scanned = scanner.format();
270
+ if (!lossy || (scanned.palette && scanned.palette.length / 3 <= lossy.colors))
271
+ return { format: scanned, plan: null };
272
+ for await (const pixels of each())
273
+ builder.sum(pixels);
274
+ const palette = builder.palette(lossy.colors);
275
+ const entries = new Map();
276
+ for (let i = 0; i < palette.length; i += 4)
277
+ entries.set(new Uint32Array(palette.slice(i, i + 4).buffer)[0], i / 4);
278
+ const format = formatOf(entries, false, false);
279
+ return { format, plan: { palette, format, lossy } };
280
+ }
281
+ export function quantizePixels(pixels, width, height, plan) {
282
+ const copy = pixels.slice(0, width * height * 4);
283
+ applyRGBAPalette(copy, width, height, plan.palette, plan.lossy.dither, plan.lossy.strength);
284
+ return copy;
285
+ }
252
286
  const aligned = (rgba) => rgba.byteOffset % 4 ? rgba.slice() : rgba;
253
- export async function encodeRGBA(rgba, width, height, level, text) {
287
+ export async function encodeRGBA(rgba, width, height, level, text, threads = Infinity, lossy) {
254
288
  rgba = aligned(rgba.subarray(0, width * height * 4));
255
- const format = pixelFormat([rgba]);
289
+ const { format, plan } = await chooseFormat(async function* () { yield rgba; }, lossy);
290
+ if (plan)
291
+ rgba = quantizePixels(rgba, width, height, plan);
256
292
  const { channels, depth, palette, transparency } = format;
257
- return encode(format.convert(rgba, width, height), { width, height, level, text, channels, depth, palette, transparency, filter: level > 0 && !palette });
293
+ return encode(format.convert(rgba, width, height), { width, height, level, threads, text, channels, depth, palette, transparency, filter: level > 0 && !palette });
258
294
  }
259
- export async function encodeAnimation(frames, width, height, plays, level, text) {
295
+ export async function encodeAnimation(frames, width, height, plays, level, text, threads = Infinity, lossy) {
260
296
  if (!frames.length)
261
297
  throw new RangeError('PNG: an animation needs at least one frame, not 0');
262
298
  frames = [coverCanvas(frames[0], width, height), ...frames.slice(1)];
263
299
  for (const f of frames)
264
300
  checkFrame(f, width, height);
265
301
  const images = frames.map(f => aligned(f.pixels.subarray(0, f.width * f.height * 4)));
266
- const format = pixelFormat(images);
302
+ const { format, plan } = await chooseFormat(async function* () { yield* images; }, lossy);
267
303
  const encoded = [];
268
304
  for (let i = 0; i < frames.length; i++)
269
- encoded.push({ ...frames[i], data: await frameData(images[i], frames[i].width, frames[i].height, format, level) });
305
+ encoded.push({ ...frames[i], data: await frameData(plan ? quantizePixels(images[i], frames[i].width, frames[i].height, plan) : images[i], frames[i].width, frames[i].height, format, level, threads) });
270
306
  return animationFile(encoded, width, height, plays, format, text);
271
307
  }
272
308
  export const RGBA = { channels: 4, depth: 8, convert: rgba => rgba };
@@ -284,8 +320,8 @@ export function checkFrame(f, width, height) {
284
320
  if (f.x < 0 || f.y < 0 || f.x + f.width > width || f.y + f.height > height || !f.width || !f.height)
285
321
  throw new RangeError('PNG: APNG frames have to lie within the canvas');
286
322
  }
287
- export function frameData(rgba, width, height, format, level) {
288
- return compressRows(format.convert(rgba, width, height), width, height, format.channels, format.depth, level, level > 0 && !format.palette);
323
+ export function frameData(rgba, width, height, format, level, threads = Infinity) {
324
+ return compressRows(format.convert(rgba, width, height), width, height, format.channels, format.depth, level, level > 0 && !format.palette, threads);
289
325
  }
290
326
  export function animationFile(frames, width, height, plays, format, text) {
291
327
  const { channels, depth, palette, transparency } = format;
@@ -795,7 +831,23 @@ function createConverter(colorType, depth, palette, transparency) {
795
831
  }
796
832
  lut[i * 4 + 3] = transparency && i < transparency.length ? transparency[i] : 0xff;
797
833
  }
834
+ const words = new Uint32Array(lut.buffer);
798
835
  return (pixels, rowBytes, w, h, out, place) => {
836
+ if (place.step === 4 && !(out.byteOffset & 3)) {
837
+ const target = new Uint32Array(out.buffer, out.byteOffset, out.length >> 2);
838
+ for (let y = 0; y < h; y++) {
839
+ const s = y * rowBytes, o = place.row(y) >> 2;
840
+ if (depth === 8)
841
+ for (let x = 0; x < w; x++)
842
+ target[o + x] = words[pixels[s + x]];
843
+ else {
844
+ const row = pixels.subarray(s, s + rowBytes);
845
+ for (let x = 0; x < w; x++)
846
+ target[o + x] = words[sample(row, x)];
847
+ }
848
+ }
849
+ return;
850
+ }
799
851
  for (let y = 0; y < h; y++) {
800
852
  const row = pixels.subarray(y * rowBytes, (y + 1) * rowBytes);
801
853
  for (let x = 0, o = place.row(y); x < w; x++, o += place.step) {
@@ -810,7 +862,32 @@ function createConverter(colorType, depth, palette, transparency) {
810
862
  }
811
863
  if (colorType === 0) {
812
864
  const key = transparency && transparency.length >= 2 ? (transparency[0] << 8 | transparency[1]) & maxValue : -1;
865
+ let words = null;
866
+ if (depth <= 8) {
867
+ const lut = new Uint8Array(256 * 4);
868
+ for (let raw = 0; raw <= maxValue; raw++) {
869
+ const v = scale(raw);
870
+ lut[raw * 4] = lut[raw * 4 + 1] = lut[raw * 4 + 2] = v;
871
+ lut[raw * 4 + 3] = raw === key ? 0 : 0xff;
872
+ }
873
+ words = new Uint32Array(lut.buffer);
874
+ }
813
875
  return (pixels, rowBytes, w, h, out, place) => {
876
+ if (words && place.step === 4 && !(out.byteOffset & 3)) {
877
+ const target = new Uint32Array(out.buffer, out.byteOffset, out.length >> 2);
878
+ for (let y = 0; y < h; y++) {
879
+ const s = y * rowBytes, o = place.row(y) >> 2;
880
+ if (depth === 8)
881
+ for (let x = 0; x < w; x++)
882
+ target[o + x] = words[pixels[s + x]];
883
+ else {
884
+ const row = pixels.subarray(s, s + rowBytes);
885
+ for (let x = 0; x < w; x++)
886
+ target[o + x] = words[sample(row, x)];
887
+ }
888
+ }
889
+ return;
890
+ }
814
891
  for (let y = 0; y < h; y++) {
815
892
  const row = pixels.subarray(y * rowBytes, (y + 1) * rowBytes);
816
893
  for (let x = 0, o = place.row(y); x < w; x++, o += place.step) {
@@ -0,0 +1,315 @@
1
+ import { cubeRoot } from "./quantize.js";
2
+ const WEIGHTS = [3, 4, 2];
3
+ const SPLIT_WEIGHTS = [3, 4, 2, 9];
4
+ const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
5
+ const FLOYD_STEINBERG = { dx: [1, -1, 0, 1], dy: [0, 1, 1, 1], w: [7 / 16, 3 / 16, 5 / 16, 1 / 16] };
6
+ const ATKINSON = { dx: [1, 2, -1, 0, 1, 0], dy: [0, 0, 1, 1, 1, 2], w: [1 / 8, 1 / 8, 1 / 8, 1 / 8, 1 / 8, 1 / 8] };
7
+ const distance = (pr, pg, pb, pa, qr, qg, qb, qa) => {
8
+ const a = pa - qa, r = pr - qr, g = pg - qg, b = pb - qb;
9
+ return WEIGHTS[0] * (r * r + (r - a) * (r - a)) + WEIGHTS[1] * (g * g + (g - a) * (g - a)) + WEIGHTS[2] * (b * b + (b - a) * (b - a));
10
+ };
11
+ const binOf = (r, g, b, a) => {
12
+ const pr = Math.round(r * a / 255), pg = Math.round(g * a / 255), pb = Math.round(b * a / 255);
13
+ return (pr >> 3) << 15 | (pg >> 3) << 10 | (pb >> 3) << 5 | (a === 255 ? 31 : Math.min(a >> 3, 30));
14
+ };
15
+ export class RGBAPaletteBuilder {
16
+ bins = new Uint32Array(1 << 20);
17
+ summing = false;
18
+ weight = new Float64Array(0);
19
+ mean = new Float64Array(0);
20
+ transparent = false;
21
+ count(pixels) {
22
+ if (this.summing)
23
+ throw new Error('RGBAPaletteBuilder: count after sum');
24
+ for (let i = 0; i < pixels.length; i += 4) {
25
+ const a = pixels[i + 3];
26
+ if (!a)
27
+ this.transparent = true;
28
+ else {
29
+ this.bins[binOf(pixels[i], pixels[i + 1], pixels[i + 2], a)]++;
30
+ }
31
+ }
32
+ }
33
+ sum(pixels) {
34
+ const { bins } = this;
35
+ if (!this.summing) {
36
+ this.summing = true;
37
+ let n = 0;
38
+ for (let bin = 0; bin < bins.length; bin++)
39
+ if (bins[bin])
40
+ n++;
41
+ const weight = this.weight = new Float64Array(n);
42
+ this.mean = new Float64Array(n * 4);
43
+ for (let bin = 0, id = 0; bin < bins.length; bin++)
44
+ if (bins[bin]) {
45
+ weight[id] = bins[bin];
46
+ bins[bin] = ++id;
47
+ }
48
+ }
49
+ const { mean } = this;
50
+ for (let i = 0; i < pixels.length; i += 4) {
51
+ const a = pixels[i + 3];
52
+ if (!a)
53
+ continue;
54
+ const id = (bins[binOf(pixels[i], pixels[i + 1], pixels[i + 2], a)] - 1) * 4;
55
+ mean[id] += pixels[i] * a / 255;
56
+ mean[id + 1] += pixels[i + 1] * a / 255;
57
+ mean[id + 2] += pixels[i + 2] * a / 255;
58
+ mean[id + 3] += a;
59
+ }
60
+ }
61
+ palette(colors) {
62
+ const { weight, transparent } = this;
63
+ const n = weight.length, mean = Float64Array.from(this.mean);
64
+ for (let id = 0; id < n; id++)
65
+ for (let k = 0; k < 4; k++)
66
+ mean[id * 4 + k] /= weight[id];
67
+ const solid = [], soft = [];
68
+ let solidWeight = 0, softWeight = 0;
69
+ for (let i = 0; i < n; i++) {
70
+ if (mean[i * 4 + 3] >= 254.999) {
71
+ solid.push(i);
72
+ solidWeight += weight[i];
73
+ }
74
+ else {
75
+ soft.push(i);
76
+ softWeight += weight[i];
77
+ }
78
+ }
79
+ const budget = colors - (transparent ? 1 : 0);
80
+ let softBudget = Math.min(soft.length, Math.round(budget * softWeight / (solidWeight + softWeight)));
81
+ if (soft.length && budget >= 2)
82
+ softBudget = Math.max(1, softBudget);
83
+ const solidBudget = Math.min(solid.length, budget - softBudget);
84
+ softBudget = Math.min(soft.length, budget - solidBudget);
85
+ const centers = Float64Array.from([...reduce(mean, weight, Int32Array.from(solid), solidBudget), ...reduce(mean, weight, Int32Array.from(soft), softBudget)]);
86
+ const entries = new Map();
87
+ for (let c = 0; c < centers.length; c += 4) {
88
+ const alpha = Math.min(centers[c + 3], 255);
89
+ const a = Math.round(alpha);
90
+ const straight = (v) => Math.min(255, Math.max(0, Math.round(Math.min(v, alpha) * 255 / a)));
91
+ const entry = [straight(centers[c]), straight(centers[c + 1]), straight(centers[c + 2]), a];
92
+ entries.set(entry[0] << 24 | entry[1] << 16 | entry[2] << 8 | entry[3], entry);
93
+ }
94
+ const list = [...entries.values()];
95
+ if (transparent)
96
+ list.push([0, 0, 0, 0]);
97
+ if (!list.length)
98
+ list.push([0, 0, 0, 0]);
99
+ return Uint8Array.from(list.flat());
100
+ }
101
+ }
102
+ function boxOf(mean, weight, members) {
103
+ let total = 0;
104
+ const sum = [0, 0, 0, 0];
105
+ for (const m of members) {
106
+ total += weight[m];
107
+ for (let k = 0; k < 4; k++)
108
+ sum[k] += weight[m] * mean[m * 4 + k];
109
+ }
110
+ let channel = 0, score = 0;
111
+ for (let k = 0; k < 4; k++) {
112
+ const center = sum[k] / total;
113
+ let variance = 0;
114
+ for (const m of members)
115
+ variance += weight[m] * (mean[m * 4 + k] - center) ** 2;
116
+ if (variance * SPLIT_WEIGHTS[k] > score) {
117
+ score = variance * SPLIT_WEIGHTS[k];
118
+ channel = k;
119
+ }
120
+ }
121
+ return { members, channel, score };
122
+ }
123
+ function reduce(mean, weight, points, target) {
124
+ let centers = cut(mean, weight, points, target);
125
+ for (let iteration = 0; iteration < 4 && centers.length / 4 > 1; iteration++)
126
+ centers = refine(mean, weight, points, centers);
127
+ return centers;
128
+ }
129
+ function cut(mean, weight, points, target) {
130
+ const boxes = [];
131
+ if (points.length && target > 0)
132
+ boxes.push(boxOf(mean, weight, points));
133
+ while (boxes.length < target) {
134
+ let best = -1;
135
+ for (let i = 0; i < boxes.length; i++)
136
+ if (boxes[i].members.length > 1 && boxes[i].score > 0 && (best < 0 || boxes[i].score > boxes[best].score))
137
+ best = i;
138
+ if (best < 0)
139
+ break;
140
+ const { members, channel } = boxes[best];
141
+ const keys = new Float64Array(members.length);
142
+ for (let i = 0; i < members.length; i++)
143
+ keys[i] = Math.round(mean[members[i] * 4 + channel] * 16) * 1048576 + i;
144
+ keys.sort();
145
+ let total = 0;
146
+ for (const m of members)
147
+ total += weight[m];
148
+ let half = 0, split = 1;
149
+ for (let i = 0; i < keys.length - 1; i++) {
150
+ half += weight[members[keys[i] % 1048576]];
151
+ split = i + 1;
152
+ if (half >= total / 2)
153
+ break;
154
+ }
155
+ const sorted = Int32Array.from(keys, key => members[key % 1048576]);
156
+ boxes[best] = boxOf(mean, weight, sorted.subarray(0, split));
157
+ boxes.push(boxOf(mean, weight, sorted.subarray(split)));
158
+ }
159
+ const centers = new Float64Array(boxes.length * 4);
160
+ boxes.forEach(({ members }, b) => {
161
+ let total = 0;
162
+ for (const m of members) {
163
+ total += weight[m];
164
+ for (let k = 0; k < 4; k++)
165
+ centers[b * 4 + k] += weight[m] * mean[m * 4 + k];
166
+ }
167
+ for (let k = 0; k < 4; k++)
168
+ centers[b * 4 + k] /= total;
169
+ });
170
+ return centers;
171
+ }
172
+ function refine(mean, weight, points, centers) {
173
+ const count = centers.length / 4;
174
+ const find = searcher(centers, Array.from({ length: count }, (_, i) => i));
175
+ const sums = new Float64Array(count * 4), totals = new Float64Array(count);
176
+ for (const i of points) {
177
+ const c = find(mean[i * 4], mean[i * 4 + 1], mean[i * 4 + 2], mean[i * 4 + 3]);
178
+ totals[c] += weight[i];
179
+ for (let k = 0; k < 4; k++)
180
+ sums[c * 4 + k] += weight[i] * mean[i * 4 + k];
181
+ }
182
+ const next = new Float64Array(count * 4);
183
+ for (let c = 0; c < count; c++)
184
+ for (let k = 0; k < 4; k++)
185
+ next[c * 4 + k] = totals[c] ? sums[c * 4 + k] / totals[c] : centers[c * 4 + k];
186
+ return next;
187
+ }
188
+ function searcher(premultiplied, entries) {
189
+ const order = [...entries].sort((x, y) => premultiplied[x * 4 + 1] - premultiplied[y * 4 + 1]);
190
+ const greens = Float64Array.from(order, e => premultiplied[e * 4 + 1]);
191
+ return (r, g, b, a) => {
192
+ let low = 0, high = order.length;
193
+ while (low < high) {
194
+ const mid = low + high >> 1;
195
+ if (greens[mid] < g)
196
+ low = mid + 1;
197
+ else
198
+ high = mid;
199
+ }
200
+ let best = -1, bestDistance = Infinity, left = low - 1, right = low;
201
+ while (left >= 0 || right < order.length) {
202
+ const goLeft = right >= order.length || left >= 0 && g - greens[left] < greens[right] - g;
203
+ const i = goLeft ? left : right;
204
+ const d = g - greens[i];
205
+ if (WEIGHTS[1] * d * d >= bestDistance) {
206
+ if (goLeft)
207
+ left = -1;
208
+ else
209
+ right = order.length;
210
+ continue;
211
+ }
212
+ const e = order[i];
213
+ const dist = distance(r, g, b, a, premultiplied[e * 4], premultiplied[e * 4 + 1], premultiplied[e * 4 + 2], premultiplied[e * 4 + 3]);
214
+ if (dist < bestDistance) {
215
+ bestDistance = dist;
216
+ best = e;
217
+ }
218
+ if (goLeft)
219
+ left--;
220
+ else
221
+ right++;
222
+ }
223
+ return best;
224
+ };
225
+ }
226
+ export function applyRGBAPalette(rgba, width, height, palette, dither, strength) {
227
+ const count = palette.length / 4;
228
+ const premultiplied = new Float64Array(count * 4);
229
+ const visible = [], solid = [];
230
+ for (let e = 0; e < count; e++) {
231
+ const a = palette[e * 4 + 3];
232
+ for (let k = 0; k < 3; k++)
233
+ premultiplied[e * 4 + k] = palette[e * 4 + k] * a / 255;
234
+ premultiplied[e * 4 + 3] = a;
235
+ if (a)
236
+ visible.push(e);
237
+ if (a === 255)
238
+ solid.push(e);
239
+ }
240
+ if (!visible.length) {
241
+ for (let p = 0; p < rgba.length; p += 4)
242
+ if (!rgba[p + 3])
243
+ rgba[p] = rgba[p + 1] = rgba[p + 2] = 0;
244
+ return;
245
+ }
246
+ const findVisible = searcher(premultiplied, visible);
247
+ const findSolid = solid.length ? searcher(premultiplied, solid) : findVisible;
248
+ const clamp = (v, max) => v < 0 ? 0 : v > max ? max : v;
249
+ const spread = dither === 'ordered' ? strength * 255 / cubeRoot(count) : 0;
250
+ const pattern = dither === 'atkinson' ? ATKINSON : FLOYD_STEINBERG;
251
+ const diffuse = dither === 'floyd-steinberg' || dither === 'atkinson';
252
+ const rows = diffuse ? [new Float32Array(width * 4), new Float32Array(width * 4), new Float32Array(width * 4)] : [];
253
+ const keys = diffuse ? null : new Uint32Array(1 << 16), cells = diffuse ? null : new Uint8Array(1 << 16), found = diffuse ? null : new Uint16Array(1 << 16);
254
+ for (let y = 0; y < height; y++) {
255
+ const direction = y & 1 ? -1 : 1;
256
+ const current = diffuse ? rows[y % 3] : null;
257
+ for (let step = 0; step < width; step++) {
258
+ const x = direction === 1 ? step : width - 1 - step;
259
+ const p = (y * width + x) * 4;
260
+ const a = rgba[p + 3];
261
+ if (!a) {
262
+ rgba[p] = rgba[p + 1] = rgba[p + 2] = 0;
263
+ continue;
264
+ }
265
+ const solidPixel = a === 255 && solid.length > 0;
266
+ let tr = rgba[p] * a / 255, tg = rgba[p + 1] * a / 255, tb = rgba[p + 2] * a / 255, ta = a;
267
+ let entry;
268
+ if (current) {
269
+ const e = x * 4;
270
+ ta = solidPixel ? 255 : clamp(ta + current[e + 3], 255);
271
+ if (!solidPixel && ta < 1)
272
+ ta = 1;
273
+ tr = clamp(tr + current[e], ta);
274
+ tg = clamp(tg + current[e + 1], ta);
275
+ tb = clamp(tb + current[e + 2], ta);
276
+ entry = (solidPixel ? findSolid : findVisible)(tr, tg, tb, ta);
277
+ }
278
+ else {
279
+ const cell = spread ? (y & 3) * 4 + (x & 3) : 0;
280
+ const value = (rgba[p] << 24 | rgba[p + 1] << 16 | rgba[p + 2] << 8 | a) >>> 0;
281
+ const slot = Math.imul(value ^ Math.imul(cell + 1, 0x85ebca6b), 0x9e3779b1) >>> 16;
282
+ if (keys[slot] === value && cells[slot] === cell + 1)
283
+ entry = found[slot];
284
+ else {
285
+ const offset = spread ? ((BAYER[cell] + 0.5) / 16 - 0.5) * spread : 0;
286
+ entry = (solidPixel ? findSolid : findVisible)(clamp(tr + offset, a), clamp(tg + offset, a), clamp(tb + offset, a), a);
287
+ keys[slot] = value;
288
+ cells[slot] = cell + 1;
289
+ found[slot] = entry;
290
+ }
291
+ }
292
+ rgba[p] = palette[entry * 4];
293
+ rgba[p + 1] = palette[entry * 4 + 1];
294
+ rgba[p + 2] = palette[entry * 4 + 2];
295
+ rgba[p + 3] = palette[entry * 4 + 3];
296
+ if (current) {
297
+ const er = tr - premultiplied[entry * 4], eg = tg - premultiplied[entry * 4 + 1], eb = tb - premultiplied[entry * 4 + 2];
298
+ const ea = ta - premultiplied[entry * 4 + 3];
299
+ const { dx, dy, w } = pattern;
300
+ for (let k = 0; k < dx.length; k++) {
301
+ const tx = x + dx[k] * direction, ty = y + dy[k];
302
+ if (tx < 0 || tx >= width || ty >= height)
303
+ continue;
304
+ const target = rows[ty % 3], t = tx * 4, s = w[k] * strength;
305
+ target[t] += er * s;
306
+ target[t + 1] += eg * s;
307
+ target[t + 2] += eb * s;
308
+ target[t + 3] += ea * s;
309
+ }
310
+ }
311
+ }
312
+ if (current)
313
+ current.fill(0);
314
+ }
315
+ }
@@ -1,4 +1,10 @@
1
1
  import { oneOf, finite } from "../util/options.js";
2
+ export function cubeRoot(x) {
3
+ let y = x / 3 + 1;
4
+ for (let i = 0; i < 40; i++)
5
+ y = (2 * y + x / (y * y)) / 3;
6
+ return y;
7
+ }
2
8
  const WR = 3, WG = 4, WB = 2;
3
9
  const DITHER = { 'none': true, 'floyd-steinberg': true, 'atkinson': true, 'ordered': true };
4
10
  export const DITHER_METHODS = Object.keys(DITHER);
@@ -126,13 +132,23 @@ export function applyPalette(pixels, width, height, palette, dither, strength) {
126
132
  const nearest = nearestSearch(palette, entries);
127
133
  const clampFloat = (v) => v < 0 ? 0 : v > 255 ? 255 : v;
128
134
  if (dither === 'none' || dither === 'ordered') {
129
- const spread = dither === 'ordered' ? strength * 255 / Math.cbrt(entries) : 0;
135
+ const spread = dither === 'ordered' ? strength * 255 / cubeRoot(entries) : 0;
136
+ const slots = new Int32Array(1 << 16).fill(-1), found = new Uint16Array(1 << 16);
130
137
  for (let y = 0, p = 0; y < height; y++) {
131
138
  for (let x = 0; x < width; x++, p++) {
132
139
  if (!pixels[p * 4 + 3])
133
140
  continue;
134
- const offset = spread ? ((BAYER[(y & 3) * 4 + (x & 3)] + 0.5) / 16 - 0.5) * spread : 0;
135
- const index = nearest(clampFloat(pixels[p * 4] + offset), clampFloat(pixels[p * 4 + 1] + offset), clampFloat(pixels[p * 4 + 2] + offset));
141
+ const cell = spread ? (y & 3) * 4 + (x & 3) : 0;
142
+ const key = (pixels[p * 4] << 16 | pixels[p * 4 + 1] << 8 | pixels[p * 4 + 2]) << 4 | cell;
143
+ const slot = Math.imul(key, 0x9e3779b1) >>> 16;
144
+ let index;
145
+ if (slots[slot] === key)
146
+ index = found[slot];
147
+ else {
148
+ const offset = spread ? ((BAYER[cell] + 0.5) / 16 - 0.5) * spread : 0;
149
+ index = found[slot] = nearest(clampFloat(pixels[p * 4] + offset), clampFloat(pixels[p * 4 + 1] + offset), clampFloat(pixels[p * 4 + 2] + offset));
150
+ slots[slot] = key;
151
+ }
136
152
  pixels[p * 4] = palette[index * 3];
137
153
  pixels[p * 4 + 1] = palette[index * 3 + 1];
138
154
  pixels[p * 4 + 2] = palette[index * 3 + 2];
@@ -155,17 +171,19 @@ export function applyPalette(pixels, width, height, palette, dither, strength) {
155
171
  const g = clampFloat(pixels[p * 4 + 1] + current[e + 1]);
156
172
  const b = clampFloat(pixels[p * 4 + 2] + current[e + 2]);
157
173
  const index = nearest(r, g, b);
158
- const errors = [r - palette[index * 3], g - palette[index * 3 + 1], b - palette[index * 3 + 2]];
174
+ const er = r - palette[index * 3], eg = g - palette[index * 3 + 1], eb = b - palette[index * 3 + 2];
159
175
  pixels[p * 4] = palette[index * 3];
160
176
  pixels[p * 4 + 1] = palette[index * 3 + 1];
161
177
  pixels[p * 4 + 2] = palette[index * 3 + 2];
162
- for (const [dx, dy, weight] of pattern) {
178
+ for (let k = 0; k < pattern.length; k++) {
179
+ const [dx, dy, weight] = pattern[k];
163
180
  const tx = x + dx * direction, ty = y + dy;
164
181
  if (tx < 0 || tx >= width || ty >= height)
165
182
  continue;
166
183
  const target = rows[ty % 3], t = tx * 3;
167
- for (let c = 0; c < 3; c++)
168
- target[t + c] += errors[c] * weight * strength;
184
+ target[t] += er * weight * strength;
185
+ target[t + 1] += eg * weight * strength;
186
+ target[t + 2] += eb * weight * strength;
169
187
  }
170
188
  }
171
189
  current.fill(0);
@@ -319,12 +337,14 @@ function nearestSearch(palette, entries) {
319
337
  const order = Int32Array.from({ length: entries }, (_, i) => i).sort((a, b) => palette[a * 3 + axis] - palette[b * 3 + axis]);
320
338
  const keys = Float64Array.from(order, i => palette[i * 3 + axis]);
321
339
  const weight = weights[axis];
340
+ const sr = Float64Array.from(order, i => palette[i * 3]), sg = Float64Array.from(order, i => palette[i * 3 + 1]), sb = Float64Array.from(order, i => palette[i * 3 + 2]);
322
341
  return (r, g, b) => {
323
342
  const key = axis === 0 ? r : axis === 1 ? g : b;
324
343
  let best = 0, bestDistance = Infinity;
325
- const test = (i) => {
326
- const dr = r - palette[i * 3], dg = g - palette[i * 3 + 1], db = b - palette[i * 3 + 2];
344
+ const test = (k) => {
345
+ const dr = r - sr[k], dg = g - sg[k], db = b - sb[k];
327
346
  const distance = WR * dr * dr + WG * dg * dg + WB * db * db;
347
+ const i = order[k];
328
348
  if (distance < bestDistance || (distance === bestDistance && i < best)) {
329
349
  bestDistance = distance;
330
350
  best = i;
@@ -344,14 +364,14 @@ function nearestSearch(palette, entries) {
344
364
  if (weight * d * d > bestDistance)
345
365
  up = entries;
346
366
  else
347
- test(order[up++]);
367
+ test(up++);
348
368
  }
349
369
  if (down >= 0) {
350
370
  const d = key - keys[down];
351
371
  if (weight * d * d > bestDistance)
352
372
  down = -1;
353
373
  else
354
- test(order[down--]);
374
+ test(down--);
355
375
  }
356
376
  }
357
377
  return best;