imagescript 3.14.0 → 3.16.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.
@@ -10,29 +10,37 @@ import { encodeModular } from "./jxl/modular-lossless.js";
10
10
  import { encodeVarDCT } from "./jxl/vardct-enc.js";
11
11
  import { concat } from "../util/mem.js";
12
12
  import { srgbDecode } from "../util/icc.js";
13
+ import { readISO, writeISO } from "./gainmap.js";
13
14
  const CONTAINER = [0, 0, 0, 12, 0x4a, 0x58, 0x4c, 0x20, 0x0d, 0x0a, 0x87, 0x0a];
14
15
  export function isJXL(d) {
15
16
  if (d.length >= 2 && d[0] === 0xff && d[1] === 0x0a)
16
17
  return true;
17
18
  return d.length >= 12 && CONTAINER.every((v, i) => d[i] === v);
18
19
  }
19
- export async function encode(rgba, width, height, exif, distance = 0, effort = 1, threads = 1) {
20
- const stream = distance > 0 ? await encodeVarDCT(rgba, width, height, { distance, effort, threads })
21
- : effort ? await encodeModular(rgba, width, height, threads) : encodeRGBA(rgba, width, height);
22
- if (!exif?.length)
20
+ export async function encode(rgba, width, height, exif, distance = 0, effort = 1, threads = 1, gainMap) {
21
+ const codestreamOf = (pixels, w, h, d) => d > 0 ? encodeVarDCT(pixels, w, h, { distance: d, effort, threads })
22
+ : effort ? encodeModular(pixels, w, h, threads) : encodeRGBA(pixels, w, h);
23
+ const stream = await codestreamOf(rgba, width, height, distance);
24
+ if (!exif?.length && !gainMap)
23
25
  return stream;
24
26
  const jxl = [0x6a, 0x78, 0x6c, 0x20];
25
- return concat([CONTAINER, ...box('ftyp', jxl, [0, 0, 0, 0], jxl), ...box('Exif', [0, 0, 0, 0], exif), ...box('jxlc', stream)]);
27
+ const boxes = [...box('ftyp', jxl, [0, 0, 0, 0], jxl)];
28
+ if (exif?.length)
29
+ boxes.push(...box('Exif', [0, 0, 0, 0], exif));
30
+ if (gainMap) {
31
+ const metadata = writeISO(gainMap.params);
32
+ const map = await codestreamOf(gainMap.pixels, gainMap.width, gainMap.height, gainMap.distance);
33
+ boxes.push(...box('jhgm', [0, metadata.length >> 8, metadata.length & 255], metadata, [0, 0, 0, 0, 0], map));
34
+ }
35
+ return concat([CONTAINER, ...boxes, ...box('jxlc', stream)]);
26
36
  }
27
37
  const box = (type, ...content) => {
28
38
  const size = 8 + content.reduce((n, c) => n + c.length, 0);
29
39
  return [[size >>> 24, size >> 16 & 255, size >> 8 & 255, size & 255, ...Array.from(type, c => c.charCodeAt(0))], ...content];
30
40
  };
31
41
  const fourcc = (d, o) => String.fromCharCode(d[o], d[o + 1], d[o + 2], d[o + 3]);
32
- function codestream(d) {
33
- if (d[0] === 0xff)
34
- return d;
35
- const view = new DataView(d.buffer, d.byteOffset, d.byteLength), parts = [];
42
+ function* boxesOf(d) {
43
+ const view = new DataView(d.buffer, d.byteOffset, d.byteLength);
36
44
  for (let o = 0; o + 8 <= d.length;) {
37
45
  let size = view.getUint32(o), header = 8;
38
46
  const type = fourcc(d, o + 4);
@@ -46,11 +54,19 @@ function codestream(d) {
46
54
  size = d.length - o;
47
55
  if (size < header || o + size > d.length)
48
56
  throw new Error(`JPEG XL: invalid ${type} box`);
57
+ yield { type, content: d.subarray(o + header, o + size) };
58
+ o += size;
59
+ }
60
+ }
61
+ function codestream(d) {
62
+ if (d[0] === 0xff)
63
+ return d;
64
+ const parts = [];
65
+ for (const { type, content } of boxesOf(d)) {
49
66
  if (type === 'jxlc')
50
- return d.subarray(o + header, o + size);
67
+ return content;
51
68
  if (type === 'jxlp')
52
- parts.push(d.subarray(o + header + 4, o + size));
53
- o += size;
69
+ parts.push(content.subarray(4));
54
70
  }
55
71
  if (!parts.length)
56
72
  throw new Error('JPEG XL: no codestream');
@@ -133,8 +149,34 @@ export async function* frames(data, maxPixels = MAX_PIXELS, toneMapping = 'reinh
133
149
  t.terminate();
134
150
  }
135
151
  }
136
- export async function decode(data, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = 1) {
137
- for await (const frame of frames(data, maxPixels, toneMapping, threads))
138
- return frame;
152
+ export async function decode(data, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = 1, gainMap = false) {
153
+ for await (const frame of frames(data, maxPixels, toneMapping, threads)) {
154
+ if (!gainMap || data[0] === 0xff)
155
+ return frame;
156
+ return { ...frame, gainMap: await decodeGainMap(data, maxPixels).catch(() => undefined) };
157
+ }
139
158
  throw new Error('JPEG XL: no frame shown');
140
159
  }
160
+ async function decodeGainMap(data, maxPixels) {
161
+ for (const { type, content: c } of boxesOf(data)) {
162
+ if (type !== 'jhgm')
163
+ continue;
164
+ if (c.length < 3 || c[0] !== 0)
165
+ return undefined;
166
+ const metadataSize = c[1] << 8 | c[2];
167
+ let o = 3 + metadataSize;
168
+ if (o + 1 > c.length)
169
+ return undefined;
170
+ const metadata = c.subarray(3, o);
171
+ const params = readISO(metadata) ?? (metadata[0] === 0 ? readISO(metadata.subarray(1)) : null);
172
+ o += 1 + c[o];
173
+ if (!params || o + 4 > c.length)
174
+ return undefined;
175
+ o += 4 + (c[o] << 24 >>> 0) + (c[o + 1] << 16 | c[o + 2] << 8 | c[o + 3]);
176
+ if (o >= c.length)
177
+ return undefined;
178
+ for await (const { width, height, pixels } of frames(c.subarray(o), maxPixels, 'clamp', 1))
179
+ return { width, height, pixels, params };
180
+ }
181
+ return undefined;
182
+ }
@@ -732,7 +732,13 @@ function prefixEncode(value) {
732
732
  const second = d >> h - 1 & 1;
733
733
  return { symbol: 2 * h + second, bits: h - 1, extra: d & (1 << h - 1) - 1 };
734
734
  }
735
- function tokenize(pixels, width) {
735
+ const ALL_MODES = Array.from({ length: 14 }, (_, i) => i);
736
+ export const TUNING = [
737
+ { chain: 4, predictedChain: 0, lazy: false, cacheSearch: false, groups: false, colorTransform: false, analyze: true, modes: [1, 2, 11], tryPredicted: false },
738
+ { chain: 8, nearOnly: true, lazy: true, cacheSearch: true, groups: true, colorTransform: false, analyze: true, modes: ALL_MODES, tryPredicted: false },
739
+ { chain: 24, nearOnly: true, lazy: true, cacheSearch: true, groups: true, colorTransform: true, analyze: true, modes: ALL_MODES, tryPredicted: true },
740
+ ];
741
+ function tokenize(pixels, width, tuning = TUNING[2]) {
736
742
  const n = pixels.length;
737
743
  const ops = new Uint8Array(n), values = new Uint32Array(n), distances = new Uint32Array(n);
738
744
  let count = 0;
@@ -743,7 +749,7 @@ function tokenize(pixels, width) {
743
749
  shortCodes.set(d, c + 1);
744
750
  }
745
751
  const distanceCode = (d) => shortCodes.get(d) ?? d + 120;
746
- const HASH_BITS = 15, CHAIN = 24, MAX_LENGTH = 4096, MIN_LENGTH = 3, WINDOW = (1 << 20) - 120;
752
+ const HASH_BITS = 15, CHAIN = tuning.chain, MAX_LENGTH = 4096, MIN_LENGTH = 3, WINDOW = (1 << 20) - 120;
747
753
  const head = new Int32Array(1 << HASH_BITS).fill(-1);
748
754
  const chain = new Int32Array(n);
749
755
  const hashes = new Int32Array(n);
@@ -801,7 +807,7 @@ function tokenize(pixels, width) {
801
807
  for (let i = 0; i < n;) {
802
808
  insertUpTo(i);
803
809
  find(i);
804
- if (bestLength >= MIN_LENGTH && bestLength < MAX_LENGTH && i + 1 < n) {
810
+ if (tuning.lazy && bestLength >= MIN_LENGTH && bestLength < MAX_LENGTH && i + 1 < n) {
805
811
  const length = bestLength, distance = bestDistance;
806
812
  insertUpTo(i + 1);
807
813
  find(i + 1);
@@ -933,6 +939,15 @@ function bestCacheBits(stream, pixels) {
933
939
  }
934
940
  return best;
935
941
  }
942
+ function streamBits(stream, pixels) {
943
+ const cacheBits = 10;
944
+ let bits = entropyBits(histograms(withCache(stream, pixels, cacheBits), cacheBits));
945
+ const { ops, values, distances, count } = stream;
946
+ for (let k = 0; k < count; k++)
947
+ if (ops[k] === 1)
948
+ bits += prefixEncode(values[k]).bits + prefixEncode(distances[k]).bits;
949
+ return bits;
950
+ }
936
951
  function entropyBits(counts) {
937
952
  let bits = 0;
938
953
  for (const c of counts) {
@@ -1118,14 +1133,34 @@ export function costChunks({ entries, starts, used, logs, costs, nearest }) {
1118
1133
  }
1119
1134
  };
1120
1135
  }
1121
- async function writeImage(w, pixels, width, isMain, threads = null) {
1122
- const tokens = tokenize(pixels, width);
1123
- const cacheBits = isMain ? bestCacheBits(tokens, pixels) : 0;
1136
+ async function writeImage(w, pixels, width, isMain, threads = null, tuning = TUNING[2]) {
1137
+ let chain = tuning.chain, tokens = null;
1138
+ if (isMain && tuning.nearOnly && chain) {
1139
+ const near = { ...tuning, chain: 0 };
1140
+ if (pixels.length <= 1 << 20) {
1141
+ const a = tokenize(pixels, width, near), b = tokenize(pixels, width, tuning);
1142
+ tokens = streamBits(a, pixels) < streamBits(b, pixels) ? a : b;
1143
+ }
1144
+ else {
1145
+ const height = pixels.length / width, rows = Math.max(8, Math.floor(height / 24));
1146
+ let nearBits = 0, farBits = 0;
1147
+ for (let k = 0; k < 3; k++) {
1148
+ const top = Math.max(0, Math.min(height - rows, Math.floor((k + 0.5) * height / 3 - rows / 2)));
1149
+ const band = pixels.subarray(top * width, (top + rows) * width);
1150
+ nearBits += streamBits(tokenize(band, width, near), band);
1151
+ farBits += streamBits(tokenize(band, width, tuning), band);
1152
+ }
1153
+ if (nearBits < farBits)
1154
+ chain = 0;
1155
+ }
1156
+ }
1157
+ tokens ??= tokenize(pixels, width, chain === tuning.chain ? tuning : { ...tuning, chain });
1158
+ const cacheBits = !isMain ? 0 : tuning.cacheSearch ? bestCacheBits(tokens, pixels) : pixels.length > 4096 ? 10 : 0;
1124
1159
  const stream = withCache(tokens, pixels, cacheBits), counts = histograms(stream, cacheBits);
1125
1160
  const best = entropyBits(counts);
1126
1161
  const height = pixels.length / width;
1127
1162
  let groups = null, groupCounts = [counts], prefixBits = 0;
1128
- if (isMain && pixels.length > 4096) {
1163
+ if (isMain && tuning.groups && pixels.length > 4096) {
1129
1164
  const r = await prefixGroups(stream, width, height, cacheBits, 4, threads);
1130
1165
  if (r && r[2] < best) {
1131
1166
  [groups, groupCounts] = r;
@@ -1142,7 +1177,7 @@ async function writeImage(w, pixels, width, isMain, threads = null) {
1142
1177
  w.write(groups ? 1 : 0, 1);
1143
1178
  if (groups) {
1144
1179
  w.write(prefixBits - 2, 3);
1145
- await writeImage(w, Uint32Array.from(groups, g => g << 8), subSize(width, prefixBits), false);
1180
+ await writeImage(w, Uint32Array.from(groups, g => g << 8), subSize(width, prefixBits), false, null, tuning);
1146
1181
  }
1147
1182
  }
1148
1183
  const { ops, values, distances, count } = stream;
@@ -1375,17 +1410,17 @@ function analyze(argb, width, height, bits) {
1375
1410
  const best = entropy.indexOf(Math.min(...entropy));
1376
1411
  return { predict: best === 1 || best === 3, subtractGreen: best >= 2 };
1377
1412
  }
1378
- async function applyPredictor(p, width, height, bits, threads) {
1413
+ async function applyPredictor(p, width, height, bits, threads, candidates = ALL_MODES) {
1379
1414
  const blocksX = subSize(width, bits), blocksY = subSize(height, bits);
1380
1415
  const task = {
1381
- task: 'vp8l-predictor', p, src: threads ? shared(p) : p.slice(), width, height, bits,
1416
+ task: 'vp8l-predictor', p, src: threads ? shared(p) : p.slice(), width, height, bits, candidates,
1382
1417
  modes: new Uint32Array(threads ? new SharedArrayBuffer(4 * blocksX * blocksY) : new ArrayBuffer(4 * blocksX * blocksY)),
1383
1418
  };
1384
1419
  await runChunks(threads, task, Math.ceil(blocksY / PREDICTOR_ROWS), predictorChunks(task));
1385
1420
  return task.modes;
1386
1421
  }
1387
1422
  const PREDICTOR_ROWS = 4;
1388
- export function predictorChunks({ p, src, modes, width, height, bits }) {
1423
+ export function predictorChunks({ p, src, modes, width, height, bits, candidates }) {
1389
1424
  const blocksX = subSize(width, bits), blocksY = subSize(height, bits), size = 1 << bits;
1390
1425
  const predicted = new Uint32Array(size);
1391
1426
  const predictRow = (mode, x0, x1, y) => {
@@ -1403,9 +1438,9 @@ export function predictorChunks({ p, src, modes, width, height, bits }) {
1403
1438
  return chunk => {
1404
1439
  for (let by = chunk * PREDICTOR_ROWS; by < Math.min(blocksY, (chunk + 1) * PREDICTOR_ROWS); by++)
1405
1440
  for (let bx = 0; bx < blocksX; bx++) {
1406
- let best = 0, bestCost = Infinity;
1441
+ let best = candidates[0], bestCost = Infinity;
1407
1442
  const x0 = bx * size, y0 = by * size, x1 = Math.min(width, x0 + size), y1 = Math.min(height, y0 + size);
1408
- for (let mode = 0; mode < 14; mode++) {
1443
+ for (const mode of candidates) {
1409
1444
  let cost = 0;
1410
1445
  for (let y = y0; y < y1 && cost < bestCost; y++) {
1411
1446
  predictRow(mode, x0, x1, y);
@@ -1426,22 +1461,23 @@ export function predictorChunks({ p, src, modes, width, height, bits }) {
1426
1461
  }
1427
1462
  };
1428
1463
  }
1429
- export async function encode(argb, width, height, threads = null) {
1464
+ export async function encode(argb, width, height, threads = null, effort = 2) {
1430
1465
  if (width < 1 || height < 1 || width > 16384 || height > 16384)
1431
1466
  throw new RangeError('VP8L: dimensions must be 1-16384');
1467
+ const tuning = TUNING[Math.min(2, effort)];
1432
1468
  const colors = new Map();
1433
1469
  for (let i = 0; i < argb.length && colors.size <= 256; i++)
1434
1470
  if (!colors.has(argb[i]))
1435
1471
  colors.set(argb[i], colors.size);
1436
1472
  if (colors.size > 256)
1437
- return encodeWith(argb, width, height, null, threads);
1438
- const indexed = await encodeWith(argb, width, height, colors, threads);
1439
- if (colors.size <= 16)
1473
+ return encodeWith(argb, width, height, null, threads, tuning);
1474
+ const indexed = await encodeWith(argb, width, height, colors, threads, tuning);
1475
+ if (colors.size <= 16 || !tuning.tryPredicted)
1440
1476
  return indexed;
1441
- const predicted = await encodeWith(argb, width, height, null, threads);
1477
+ const predicted = await encodeWith(argb, width, height, null, threads, tuning);
1442
1478
  return predicted.length < indexed.length ? predicted : indexed;
1443
1479
  }
1444
- async function encodeWith(argb, width, height, colors, threads) {
1480
+ async function encodeWith(argb, width, height, colors, threads, tuning) {
1445
1481
  const w = new BitWriter();
1446
1482
  let hasAlpha = false;
1447
1483
  for (let i = 0; i < argb.length; i++)
@@ -1454,7 +1490,7 @@ async function encodeWith(argb, width, height, colors, threads) {
1454
1490
  w.write(height - 1, 14);
1455
1491
  w.write(hasAlpha ? 1 : 0, 1);
1456
1492
  w.write(0, 3);
1457
- let pixels, codedWidth = width;
1493
+ let pixels, codedWidth = width, predicted = false;
1458
1494
  if (colors) {
1459
1495
  const palette = Uint32Array.from([...colors.keys()].sort((a, b) => a - b));
1460
1496
  palette.forEach((c, i) => colors.set(c, i));
@@ -1465,7 +1501,7 @@ async function encodeWith(argb, width, height, colors, threads) {
1465
1501
  const deltas = palette.slice();
1466
1502
  for (let i = palette.length - 1; i > 0; i--)
1467
1503
  deltas[i] = subPixels(palette[i], palette[i - 1]);
1468
- await writeImage(w, deltas, palette.length, false);
1504
+ await writeImage(w, deltas, palette.length, false, null, tuning);
1469
1505
  codedWidth = subSize(width, bits);
1470
1506
  pixels = new Uint32Array(codedWidth * height);
1471
1507
  const perPixel = 8 >> bits;
@@ -1481,7 +1517,7 @@ async function encodeWith(argb, width, height, colors, threads) {
1481
1517
  for (let i = 0; i < pixels.length && !redBlue; i++)
1482
1518
  if (pixels[i] & 0x00ff00ff)
1483
1519
  redBlue = true;
1484
- const { predict, subtractGreen } = analyze(argb, width, height, 4);
1520
+ const { predict, subtractGreen } = tuning.analyze ? analyze(argb, width, height, 4) : { predict: true, subtractGreen: true };
1485
1521
  if (redBlue && subtractGreen) {
1486
1522
  w.write(1, 1);
1487
1523
  w.write(2, 2);
@@ -1492,12 +1528,13 @@ async function encodeWith(argb, width, height, colors, threads) {
1492
1528
  }
1493
1529
  const bits = 4;
1494
1530
  if (predict) {
1531
+ predicted = true;
1495
1532
  w.write(1, 1);
1496
1533
  w.write(0, 2);
1497
1534
  w.write(bits - 2, 3);
1498
- const modes = await applyPredictor(pixels, width, height, bits, threads);
1499
- await writeImage(w, modes, subSize(width, bits), false);
1500
- if (redBlue) {
1535
+ const modes = await applyPredictor(pixels, width, height, bits, threads, tuning.modes);
1536
+ await writeImage(w, modes, subSize(width, bits), false, null, tuning);
1537
+ if (redBlue && tuning.colorTransform) {
1501
1538
  const colorBits = 5, before = pixels.slice(), multipliers = colorTransform(pixels, width, height, colorBits);
1502
1539
  const changed = multipliers.reduce((n, m) => n + (m !== 0xff000000 ? 1 : 0), 0);
1503
1540
  if (changed && redBlueBits(pixels) + 12 * changed >= redBlueBits(before))
@@ -1506,12 +1543,13 @@ async function encodeWith(argb, width, height, colors, threads) {
1506
1543
  w.write(1, 1);
1507
1544
  w.write(1, 2);
1508
1545
  w.write(colorBits - 2, 3);
1509
- await writeImage(w, multipliers, subSize(width, colorBits), false);
1546
+ await writeImage(w, multipliers, subSize(width, colorBits), false, null, tuning);
1510
1547
  }
1511
1548
  }
1512
1549
  }
1513
1550
  }
1514
1551
  w.write(0, 1);
1515
- await writeImage(w, pixels, codedWidth, true, threads);
1552
+ const chain = predicted && tuning.predictedChain !== undefined ? tuning.predictedChain : tuning.chain;
1553
+ await writeImage(w, pixels, codedWidth, true, threads, { ...tuning, chain });
1516
1554
  return w.finish();
1517
1555
  }
@@ -262,17 +262,17 @@ const hasAlpha = (rgba) => {
262
262
  return false;
263
263
  };
264
264
  const MIN_THREADED_PIXELS = 1536 << 10, PIXELS_PER_THREAD = 512 << 10;
265
- export async function encode(rgba, width, height, exif, threads = 1) {
265
+ export async function encode(rgba, width, height, exif, threads = 1, effort = 2) {
266
266
  const n = Math.min(threads, Math.floor(width * height / PIXELS_PER_THREAD));
267
267
  const pool = n > 1 && width * height >= MIN_THREADED_PIXELS ? startThreads(n) : null;
268
268
  let stream;
269
269
  try {
270
- stream = await vp8l.encode(toARGB(rgba, width * height), width, height, pool);
270
+ stream = await vp8l.encode(toARGB(rgba, width * height), width, height, pool, effort);
271
271
  }
272
272
  catch (e) {
273
273
  if (!pool)
274
274
  throw e;
275
- stream = await vp8l.encode(toARGB(rgba, width * height), width, height);
275
+ stream = await vp8l.encode(toARGB(rgba, width * height), width, height, null, effort);
276
276
  }
277
277
  finally {
278
278
  if (pool)
@@ -321,7 +321,7 @@ export function lossyTolerance(quality) {
321
321
  const value = Math.sqrt(quality / 100);
322
322
  return Math.max(1, Math.round(31 * (1 - value) + value));
323
323
  }
324
- export async function encodeAnimation(frames, width, height, plays, exif, lossy) {
324
+ export async function encodeAnimation(frames, width, height, plays, exif, lossy, effort = 2) {
325
325
  if (!frames.length)
326
326
  throw new Error('WebP: an animation needs at least one frame');
327
327
  if (width > 1 << 24 || height > 1 << 24)
@@ -331,16 +331,16 @@ export async function encodeAnimation(frames, width, height, plays, exif, lossy)
331
331
  alpha ||= needsAlpha(f, i === 0, width, height);
332
332
  const chunks = [];
333
333
  for (const f of frames)
334
- chunks.push(await frameChunk(f, lossy));
334
+ chunks.push(await frameChunk(f, lossy, effort));
335
335
  return animationFile(chunks, width, height, plays, alpha, exif);
336
336
  }
337
337
  export function needsAlpha(f, first, width, height) {
338
338
  return (first && (f.x > 0 || f.y > 0 || f.width < width || f.height < height)) || f.dispose || hasAlpha(f.pixels);
339
339
  }
340
- export async function frameChunk(f, lossy) {
340
+ export async function frameChunk(f, lossy, effort = 2) {
341
341
  if (f.x & 1 || f.y & 1)
342
342
  throw new RangeError('WebP: frame offsets have to be even');
343
- const bitstream = !lossy ? riffChunk('VP8L', await vp8l.encode(toARGB(f.pixels, f.width * f.height), f.width, f.height))
343
+ const bitstream = !lossy ? riffChunk('VP8L', await vp8l.encode(toARGB(f.pixels, f.width * f.height), f.width, f.height, null, effort))
344
344
  : concat((await lossyChunks(f.pixels, f.width, f.height, lossy)).chunks);
345
345
  const header = new Uint8Array(16);
346
346
  set24(header, 0, f.x >> 1);
package/dist/frame.js CHANGED
@@ -75,4 +75,8 @@ export class Frame extends Image {
75
75
  this.yOffset = Math.round(this.yOffset * this.height / originalHeight);
76
76
  return this;
77
77
  }
78
+ __rescaled__(width, height) {
79
+ this.xOffset = Math.round(this.xOffset * width / this.width);
80
+ this.yOffset = Math.round(this.yOffset * height / this.height);
81
+ }
78
82
  }
@@ -0,0 +1,82 @@
1
+ import { Image } from './image.js';
2
+ import { BinaryData } from './util/mem.js';
3
+ /** Options of the {@link GainMap} constructor: per channel values can be one number for all three or [r, g, b] */
4
+ export interface GainMapOptions {
5
+ /** log2 of the boost of the map's value 0 (`-1`: half as bright). Default: `0` */
6
+ gainMapMin?: number | number[];
7
+ /** log2 of the boost of the map's value 255 (`2`: 4 times as bright). Default: `2` */
8
+ gainMapMax?: number | number[];
9
+ /** the gamma the map's values are stored with. Default: `1` */
10
+ gamma?: number | number[];
11
+ /** added to the SDR image's linear values before the boost (keeps black from being boosted forever). Default: `1/64` */
12
+ offsetSDR?: number | number[];
13
+ /** subtracted from the HDR result. Default: `1/64` */
14
+ offsetHDR?: number | number[];
15
+ /** log2 of the display headroom from which on the map starts to apply. Default: `0` */
16
+ hdrCapacityMin?: number;
17
+ /** log2 of the display headroom at which it applies fully. Default: `gainMapMax`'s largest value */
18
+ hdrCapacityMax?: number;
19
+ /** whether the boost applies in the SDR image's color space (`false`: in the HDR image's). Default: `true` */
20
+ useBaseColorSpace?: boolean;
21
+ }
22
+ /**
23
+ * A gain map: a small image saying how much brighter each part of an image gets on an HDR display, as Ultra HDR
24
+ * (JPEG-R) photos from phones carry it. HDR displays show the image boosted by it, the others the image as it is.
25
+ *
26
+ * {@link Image.decode} reads the gain maps of JPEGs, AVIFs and JPEG XLs into {@link Image.gainMap},
27
+ * {@link Image.encodeJPEG}, {@link Image.encodeAVIF} and {@link Image.encodeJXL} write them. The map covers the whole image, at any resolution (phones
28
+ * write a quarter of the width and height). Its value `v` (0-255, per channel or one for all) boosts the linear
29
+ * light of the image by `2^(gainMapMin + (gainMapMax - gainMapMin) * (v / 255)^(1 / gamma))`
30
+ */
31
+ export declare class GainMap {
32
+ /** log2 of the boost of the map's value 0, per channel (red, green, blue) */
33
+ gainMapMin: number[];
34
+ /** log2 of the boost of the map's value 255, per channel */
35
+ gainMapMax: number[];
36
+ /** the gamma the map's values are stored with, per channel */
37
+ gamma: number[];
38
+ /** added to the SDR image's linear values before the boost, per channel */
39
+ offsetSDR: number[];
40
+ /** subtracted from the HDR result, per channel */
41
+ offsetHDR: number[];
42
+ /** log2 of the display headroom from which on the map starts to apply */
43
+ hdrCapacityMin: number;
44
+ /** log2 of the display headroom at which it applies fully */
45
+ hdrCapacityMax: number;
46
+ /** whether the boost applies in the SDR image's color space (else in the HDR image's) */
47
+ useBaseColorSpace: boolean;
48
+ /** its pixels */
49
+ private __pixels__;
50
+ /**
51
+ * Creates a gain map
52
+ * @param image The map's pixels: grey (red, green and blue the same) for one map for all channels. Its alpha is
53
+ * ignored
54
+ * @param options See {@link GainMapOptions}
55
+ */
56
+ constructor(image: Image, options?: GainMapOptions);
57
+ private __set_params__;
58
+ private __check__;
59
+ /** The map's pixels. Changes to them are written when the image is encoded */
60
+ get image(): Image;
61
+ set image(image: Image);
62
+ /** The map's width */
63
+ get width(): number;
64
+ /** The map's height */
65
+ get height(): number;
66
+ /** `1` for a grey map (one boost for red, green and blue), `3` for one per channel */
67
+ get channels(): 1 | 3;
68
+ /** Clones the gain map (its pixels too) */
69
+ clone(): GainMap;
70
+ /**
71
+ * Encodes the gain map alone: a JPEG with its parameters (hdrgm XMP and ISO 21496-1), like the second image in an
72
+ * Ultra HDR JPEG
73
+ * @param quality The JPEG quality (1-100). Default: `90`
74
+ */
75
+ encode(quality?: number): Promise<Uint8Array>;
76
+ /**
77
+ * Decodes a gain map JPEG with its parameters (hdrgm XMP or ISO 21496-1), like the second image in an Ultra HDR
78
+ * JPEG, or the gain map of an Ultra HDR JPEG (or an iPhone's JPEG: its values converted to these parameters)
79
+ * @param data The JPEG
80
+ */
81
+ static decode(data: BinaryData): Promise<GainMap>;
82
+ }
@@ -0,0 +1,195 @@
1
+ import { Image } from "./image.js";
2
+ import * as jpeg from "./codecs/jpeg.js";
3
+ import * as codec from "./codecs/gainmap.js";
4
+ import { view } from "./util/mem.js";
5
+ import { finite, quality as checkQuality } from "./util/options.js";
6
+ const perChannel = (value, name) => {
7
+ const values = typeof value === 'number' ? [value, value, value] : Array.from(value);
8
+ if (values.length === 1)
9
+ values.push(values[0], values[0]);
10
+ if (values.length !== 3)
11
+ throw new RangeError(`${name} must be a number or an array of 3 numbers`);
12
+ return values.map(v => finite(v, name));
13
+ };
14
+ export class GainMap {
15
+ gainMapMin;
16
+ gainMapMax;
17
+ gamma;
18
+ offsetSDR;
19
+ offsetHDR;
20
+ hdrCapacityMin;
21
+ hdrCapacityMax;
22
+ useBaseColorSpace;
23
+ __pixels__ = null;
24
+ constructor(image, options = {}) {
25
+ if (!(image instanceof Image))
26
+ throw new TypeError('The gain map has to be an Image');
27
+ const { gainMapMin = 0, gainMapMax = 2, gamma = 1, offsetSDR = 1 / 64, offsetHDR = 1 / 64, hdrCapacityMin = 0, useBaseColorSpace = true } = options;
28
+ this.gainMapMin = perChannel(gainMapMin, 'gainMapMin');
29
+ this.gainMapMax = perChannel(gainMapMax, 'gainMapMax');
30
+ this.gamma = perChannel(gamma, 'gamma');
31
+ this.offsetSDR = perChannel(offsetSDR, 'offsetSDR');
32
+ this.offsetHDR = perChannel(offsetHDR, 'offsetHDR');
33
+ this.hdrCapacityMin = finite(hdrCapacityMin, 'hdrCapacityMin');
34
+ this.hdrCapacityMax = finite(options.hdrCapacityMax ?? Math.max(...this.gainMapMax), 'hdrCapacityMax');
35
+ this.useBaseColorSpace = Boolean(useBaseColorSpace);
36
+ this.__pixels__ = image;
37
+ this.__check__();
38
+ }
39
+ static __from_jpeg__(map, params, apple = 0) {
40
+ const { width, height, pixels } = jpeg.decode(map);
41
+ const image = new Image(width, height);
42
+ image.bitmap = pixels;
43
+ if (apple) {
44
+ const table = new Uint8Array(256);
45
+ for (let v = 0; v < 256; v++)
46
+ table[v] = Math.round(255 * codec.appleValue(v / 255, apple));
47
+ for (let i = 0; i < pixels.length; i += 4) {
48
+ pixels[i] = table[pixels[i]];
49
+ pixels[i + 1] = table[pixels[i + 1]];
50
+ pixels[i + 2] = table[pixels[i + 2]];
51
+ }
52
+ }
53
+ return GainMap.__from_pixels__(image, params, false);
54
+ }
55
+ static __from_pixels__(image, params, grey = true) {
56
+ const px = image.bitmap;
57
+ if (grey) {
58
+ let spread = 0;
59
+ for (let i = 0; i < px.length && spread <= 2; i += 4)
60
+ spread = Math.max(spread, Math.abs(px[i] - px[i + 1]), Math.abs(px[i] - px[i + 2]));
61
+ if (spread > 0 && spread <= 2)
62
+ for (let i = 0; i < px.length; i += 4)
63
+ px[i] = px[i + 1] = px[i + 2] = Math.round((px[i] + px[i + 1] + px[i + 2]) / 3);
64
+ }
65
+ const gainMap = Object.create(GainMap.prototype);
66
+ gainMap.__pixels__ = image;
67
+ gainMap.__set_params__(params);
68
+ return gainMap;
69
+ }
70
+ __set_params__(p) {
71
+ this.gainMapMin = p.min.slice();
72
+ this.gainMapMax = p.max.slice();
73
+ this.gamma = p.gamma.slice();
74
+ this.offsetSDR = p.offsetSDR.slice();
75
+ this.offsetHDR = p.offsetHDR.slice();
76
+ this.hdrCapacityMin = p.capacityMin;
77
+ this.hdrCapacityMax = p.capacityMax;
78
+ this.useBaseColorSpace = p.useBaseColorSpace;
79
+ }
80
+ __params__() {
81
+ this.__check__();
82
+ return {
83
+ min: this.gainMapMin.slice(), max: this.gainMapMax.slice(), gamma: this.gamma.slice(), offsetSDR: this.offsetSDR.slice(),
84
+ offsetHDR: this.offsetHDR.slice(), capacityMin: this.hdrCapacityMin, capacityMax: this.hdrCapacityMax, useBaseColorSpace: this.useBaseColorSpace
85
+ };
86
+ }
87
+ __check__() {
88
+ const p = {
89
+ min: perChannel(this.gainMapMin, 'gainMapMin'), max: perChannel(this.gainMapMax, 'gainMapMax'), gamma: perChannel(this.gamma, 'gamma'),
90
+ offsetSDR: perChannel(this.offsetSDR, 'offsetSDR'), offsetHDR: perChannel(this.offsetHDR, 'offsetHDR'),
91
+ capacityMin: finite(this.hdrCapacityMin, 'hdrCapacityMin'), capacityMax: finite(this.hdrCapacityMax, 'hdrCapacityMax'), useBaseColorSpace: this.useBaseColorSpace
92
+ };
93
+ for (let c = 0; c < 3; c++) {
94
+ if (p.gamma[c] <= 0)
95
+ throw new RangeError('The gain map\'s gamma must be above 0');
96
+ if (p.max[c] < p.min[c])
97
+ throw new RangeError('The gain map\'s gainMapMax must be at least its gainMapMin');
98
+ }
99
+ if (p.capacityMin < 0 || p.capacityMax <= p.capacityMin)
100
+ throw new RangeError('The gain map\'s hdrCapacityMax must be above its hdrCapacityMin, which can\'t be negative');
101
+ }
102
+ get image() {
103
+ return this.__pixels__;
104
+ }
105
+ set image(image) {
106
+ if (!(image instanceof Image))
107
+ throw new TypeError('The gain map has to be an Image');
108
+ this.__pixels__ = image;
109
+ }
110
+ get width() {
111
+ return this.__pixels__.width;
112
+ }
113
+ get height() {
114
+ return this.__pixels__.height;
115
+ }
116
+ get channels() {
117
+ const bitmap = this.__pixels__.bitmap;
118
+ for (let i = 0; i < bitmap.length; i += 4)
119
+ if (bitmap[i] !== bitmap[i + 1] || bitmap[i] !== bitmap[i + 2])
120
+ return 3;
121
+ return 1;
122
+ }
123
+ clone() {
124
+ const copy = Object.create(GainMap.prototype);
125
+ copy.__set_params__(this.__params__());
126
+ copy.__pixels__ = this.__pixels__.clone();
127
+ return copy;
128
+ }
129
+ __body__(quality, width, height) {
130
+ let image = this.image;
131
+ if (width !== undefined && height !== undefined && (width !== image.width || height !== image.height))
132
+ image = image.clone().resize(width, height);
133
+ const bitmap = image.bitmap;
134
+ const pixels = new Uint8Array(bitmap.buffer, bitmap.byteOffset, bitmap.byteLength);
135
+ const grey = this.channels === 1;
136
+ return jpeg.encode(pixels, image.width, image.height, quality ?? 90, { grey, fullChroma: !grey });
137
+ }
138
+ __neutral__() {
139
+ return [0, 1, 2].map(c => {
140
+ const min = this.gainMapMin[c], max = this.gainMapMax[c];
141
+ const t = max > min ? Math.min(1, Math.max(0, -min / (max - min))) : 0;
142
+ return Math.round(255 * t ** this.gamma[c]);
143
+ });
144
+ }
145
+ __rescale__(oldWidth, oldHeight, width, height) {
146
+ const mapWidth = Math.max(1, Math.round(width * this.width / oldWidth)), mapHeight = Math.max(1, Math.round(height * this.height / oldHeight));
147
+ if (mapWidth === this.width && mapHeight === this.height)
148
+ return;
149
+ this.image = this.image.clone().resize(mapWidth, mapHeight);
150
+ }
151
+ __transform__(oldWidth, oldHeight, width, height, toOld, zoom = 1) {
152
+ let map = this.image;
153
+ const mapWidth = Math.max(1, Math.round(width * map.width / oldWidth)), mapHeight = Math.max(1, Math.round(height * map.height / oldHeight));
154
+ if (zoom < 0.5)
155
+ map = map.clone().resize(Math.max(1, Math.round(map.width * zoom * 2)), Math.max(1, Math.round(map.height * zoom * 2)));
156
+ const sx = map.width / oldWidth, sy = map.height / oldHeight;
157
+ const src = map.bitmap, mw = map.width, mh = map.height;
158
+ const out = new Image(mapWidth, mapHeight), dst = out.bitmap;
159
+ const neutral = this.__neutral__();
160
+ for (let j = 0, d = 0; j < mapHeight; j++) {
161
+ for (let i = 0; i < mapWidth; i++, d += 4) {
162
+ dst[d + 3] = 255;
163
+ const old = toOld((i + 0.5) * width / mapWidth, (j + 0.5) * height / mapHeight);
164
+ if (!old || !(old[0] >= 0 && old[0] <= oldWidth && old[1] >= 0 && old[1] <= oldHeight)) {
165
+ dst[d] = neutral[0];
166
+ dst[d + 1] = neutral[1];
167
+ dst[d + 2] = neutral[2];
168
+ continue;
169
+ }
170
+ const u = Math.min(mw - 1, Math.max(0, old[0] * sx - 0.5)), v = Math.min(mh - 1, Math.max(0, old[1] * sy - 0.5));
171
+ const x0 = Math.floor(u), y0 = Math.floor(v), x1 = Math.min(mw - 1, x0 + 1), y1 = Math.min(mh - 1, y0 + 1);
172
+ const fx = u - x0, fy = v - y0;
173
+ const a = 4 * (y0 * mw + x0), b = 4 * (y0 * mw + x1), c = 4 * (y1 * mw + x0), e = 4 * (y1 * mw + x1);
174
+ for (let k = 0; k < 3; k++)
175
+ dst[d + k] = (src[a + k] * (1 - fx) + src[b + k] * fx) * (1 - fy) + (src[c + k] * (1 - fx) + src[e + k] * fx) * fy;
176
+ }
177
+ }
178
+ this.image = out;
179
+ }
180
+ async encode(quality) {
181
+ if (quality !== undefined)
182
+ quality = Math.max(1, checkQuality(quality));
183
+ return codec.mapWithMetadata(this.__body__(quality), this.__params__());
184
+ }
185
+ static async decode(data) {
186
+ const bytes = view(data);
187
+ const found = codec.find(bytes);
188
+ if (found)
189
+ return GainMap.__from_jpeg__(found.map, found.params, found.apple);
190
+ const params = codec.readParams(bytes);
191
+ if (!params)
192
+ throw new Error('No gain map (or no gain map parameters) found');
193
+ return GainMap.__from_jpeg__(bytes, params);
194
+ }
195
+ }