imagescript 3.15.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.
package/README.md CHANGED
@@ -71,6 +71,7 @@ await writeFile('output.png', await image.encode());
71
71
  | GIF, APNG (animations) | ✓ | ✓ |
72
72
  | BMP, QOI, TGA, Netpbm | ✓ | ✓ |
73
73
  | TIFF, ICO/CUR, Radiance HDR | ✓ | |
74
+ | [HDR gain maps](https://imagescript.dev/classes/GainMap.html) (Ultra HDR and iPhone JPEGs, AVIF, JPEG XL) | ✓ | ✓, kept through edits |
74
75
 
75
76
  [Animations](https://imagescript.dev/classes/Animation.html) can be decoded from GIF, APNG, WebP and JPEG XL,
76
77
  and encoded as GIF, APNG or WebP, all at once or
@@ -1,5 +1,6 @@
1
1
  import { encodeAV1, encodeAV1Threaded } from "./av1/encode.js";
2
2
  import { startThreads } from "../util/threads.js";
3
+ import { writeISO } from "./gainmap.js";
3
4
  const MIN_THREADED_PIXELS = [640 * 640, 448 * 448, 320 * 320], PIXELS_PER_THREAD = [512 << 10, 256 << 10, 256 << 10];
4
5
  const QINDEX = [
5
6
  0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112,
@@ -8,6 +9,7 @@ const QINDEX = [
8
9
  ];
9
10
  const qindex = (quality) => QINDEX[Math.round((100 - Math.max(0, Math.min(100, quality))) * 63 / 100)];
10
11
  const KR = 0.299, KB = 0.114, KG = 1 - KR - KB, CICP = [1, 13, 6];
12
+ const MAP_CICP = [2, 2, 6];
11
13
  function toYUV(rgba, width, height, subsampled) {
12
14
  const n = width * height, y = new Uint8Array(n);
13
15
  const u = new Float64Array(n), v = new Float64Array(n);
@@ -151,7 +153,7 @@ function seqMonochrome(d, o) {
151
153
  read(1);
152
154
  return !!read(1);
153
155
  }
154
- export async function encode(rgba, width, height, { quality, alphaQuality, subsampling, effort, exif, threads: maxThreads }) {
156
+ export async function encode(rgba, width, height, { quality, alphaQuality, subsampling, effort, exif, threads: maxThreads, gainMap }) {
155
157
  if (width < 1 || height < 1)
156
158
  throw new RangeError('AVIF: dimensions must be at least 1');
157
159
  if (width > 65536 || height > 65536)
@@ -194,7 +196,14 @@ export async function encode(rgba, width, height, { quality, alphaQuality, subsa
194
196
  }
195
197
  return encodeAV1(image, params);
196
198
  };
197
- let color, alpha = null;
199
+ let color, alpha = null, map = null;
200
+ let mapGray = true;
201
+ if (gainMap)
202
+ for (let i = 0; i < gainMap.pixels.length; i += 4)
203
+ if (gainMap.pixels[i] !== gainMap.pixels[i + 1] || gainMap.pixels[i] !== gainMap.pixels[i + 2]) {
204
+ mapGray = false;
205
+ break;
206
+ }
198
207
  try {
199
208
  color = await av1({ planes, width, height, layout: gray ? 0 : subsampled ? 1 : 3, cicp }, { qidx: qindex(quality), effort });
200
209
  if (!opaque) {
@@ -203,36 +212,56 @@ export async function encode(rgba, width, height, { quality, alphaQuality, subsa
203
212
  a[i] = original[4 * i + 3];
204
213
  alpha = await av1({ planes: [a], width, height, layout: 0, cicp: [2, 2, 2] }, { qidx: qindex(alphaQuality), effort });
205
214
  }
215
+ if (gainMap) {
216
+ const { pixels, width: w, height: h } = gainMap;
217
+ const mapPlanes = mapGray ? [Uint8Array.from({ length: w * h }, (_, i) => pixels[4 * i])] : toYUV(pixels, w, h, false);
218
+ map = await av1({ planes: mapPlanes, width: w, height: h, layout: mapGray ? 0 : 3, cicp: MAP_CICP }, { qidx: qindex(gainMap.quality), effort });
219
+ }
206
220
  }
207
221
  finally {
208
222
  stop();
209
223
  }
210
224
  const profile = subsampled || gray ? 'MA1B' : 'MA1A';
211
- const ftyp = box('ftyp', ascii('avif'), u32(0), ascii('avif'), ascii('mif1'), ascii('miaf'), ascii(profile));
225
+ const ftyp = box('ftyp', ascii('avif'), u32(0), ascii('avif'), ascii('mif1'), ascii('miaf'), ascii(profile), map ? ascii('tmap') : []);
212
226
  const hdlr = fullBox('hdlr', 0, 0, u32(0), ascii('pict'), u32(0), u32(0), u32(0), [0]);
213
227
  const pitm = fullBox('pitm', 0, 0, u16(1));
214
- const items = [{ type: 'av01', name: 'Color', data: [color] }];
215
- if (alpha)
216
- items.push({ type: 'av01', name: 'Alpha', data: [alpha] });
217
- if (exif?.length)
218
- items.push({ type: 'Exif', name: 'Exif', data: [u32(0), exif] });
219
- const sizes = items.map(item => item.data.reduce((n, d) => n + d.length, 0));
220
- const infe = (id, type, name) => fullBox('infe', 2, 0, u16(id), u16(0), ascii(type), ascii(name), [0]);
221
- const iinf = fullBox('iinf', 0, 0, u16(items.length), ...items.map((item, i) => infe(i + 1, item.type, item.name)));
222
- const exifId = exif?.length ? items.length : 0;
223
- const iref = alpha || exifId ? fullBox('iref', 0, 0, alpha ? box('auxl', u16(2), u16(1), u16(1)) : [], exifId ? box('cdsc', u16(exifId), u16(1), u16(1)) : []) : [];
224
- const ispe = fullBox('ispe', 0, 0, u32(width), u32(height));
225
- const colr = box('colr', ascii('nclx'), u16(cicp[0]), u16(cicp[1]), u16(cicp[2]), [0x80]);
228
+ const items = [];
229
+ const properties = [];
230
+ const property = (p) => properties.push(p);
231
+ const nclx = (c) => box('colr', ascii('nclx'), u16(c[0]), u16(c[1]), u16(c[2]), [0x80]);
226
232
  const pixi = (channels) => fullBox('pixi', 0, 0, [channels], new Array(channels).fill(8));
227
- const auxC = fullBox('auxC', 0, 0, ascii('urn:mpeg:mpegB:cicp:systems:auxiliary:alpha'), [0]);
228
- const ipco = box('ipco', ispe, av1C(color), colr, pixi(gray ? 1 : 3), alpha ? av1C(alpha) : [], alpha ? pixi(1) : [], alpha ? auxC : []);
229
- const ipma = fullBox('ipma', 0, 0, u32(alpha ? 2 : 1), u16(1), [4, 1, 0x82, 3, 4], alpha ? [...u16(2), 4, 1, 0x85, 6, 7] : []);
233
+ const ispe = property(fullBox('ispe', 0, 0, u32(width), u32(height)));
234
+ const colorConfig = property(av1C(color)) | 0x80, colr = property(nclx(cicp));
235
+ items.push({ type: 'av01', name: 'Color', data: [color], props: [ispe, colorConfig, colr, property(pixi(gray ? 1 : 3))] });
236
+ const alphaId = alpha ? items.push({
237
+ type: 'av01', name: 'Alpha', data: [alpha],
238
+ props: [ispe, property(av1C(alpha)) | 0x80, property(pixi(1)), property(fullBox('auxC', 0, 0, ascii('urn:mpeg:mpegB:cicp:systems:auxiliary:alpha'), [0]))]
239
+ }) : 0;
240
+ let mapId = 0, tmapId = 0;
241
+ if (map && gainMap) {
242
+ mapId = items.push({
243
+ type: 'av01', name: 'GMap', hidden: true, data: [map],
244
+ props: [property(fullBox('ispe', 0, 0, u32(gainMap.width), u32(gainMap.height))), property(av1C(map)) | 0x80, property(nclx(MAP_CICP)), property(pixi(mapGray ? 1 : 3))]
245
+ });
246
+ tmapId = items.push({ type: 'tmap', name: 'TMap', data: [[0], writeISO(gainMap.params)], props: [ispe, property(nclx([cicp[0], 16, cicp[2]]))] });
247
+ }
248
+ const exifId = exif?.length ? items.push({ type: 'Exif', name: 'Exif', data: [u32(0), exif], props: [] }) : 0;
249
+ const sizes = items.map(item => item.data.reduce((n, d) => n + d.length, 0));
250
+ const infe = (id, item) => fullBox('infe', 2, item.hidden ? 1 : 0, u16(id), u16(0), ascii(item.type), ascii(item.name), [0]);
251
+ const iinf = fullBox('iinf', 0, 0, u16(items.length), ...items.map((item, i) => infe(i + 1, item)));
252
+ const refs = [alphaId ? box('auxl', u16(alphaId), u16(1), u16(1)) : [], tmapId ? box('dimg', u16(tmapId), u16(2), u16(1), u16(mapId)) : [],
253
+ exifId ? box('cdsc', u16(exifId), u16(1), u16(1)) : []];
254
+ const iref = refs.some(r => r.length) ? fullBox('iref', 0, 0, ...refs) : [];
255
+ const ipco = box('ipco', ...properties);
256
+ const associated = items.map((item, i) => [i + 1, item.props]).filter(([, props]) => props.length);
257
+ const ipma = fullBox('ipma', 0, 0, u32(associated.length), ...associated.map(([id, props]) => [...u16(id), props.length, ...props]));
230
258
  const iprp = box('iprp', ipco, ipma);
259
+ const grpl = tmapId ? box('grpl', fullBox('altr', 0, 0, u32(items.length + 1), u32(2), u32(tmapId), u32(1))) : [];
231
260
  const ilocFor = (offset) => fullBox('iloc', 0, 0, [0x44, 0x00], u16(items.length), ...items.map((_, i) => {
232
261
  const at = offset + sizes.slice(0, i).reduce((n, size) => n + size, 0);
233
262
  return [...u16(i + 1), ...u16(0), ...u16(1), ...u32(at), ...u32(sizes[i])];
234
263
  }));
235
- const metaFor = (offset) => fullBox('meta', 0, 0, hdlr, pitm, ilocFor(offset), iinf, iref, iprp);
264
+ const metaFor = (offset) => fullBox('meta', 0, 0, hdlr, pitm, ilocFor(offset), iinf, iref, iprp, grpl);
236
265
  const headerSize = ftyp.length + metaFor(0).length + 8;
237
266
  const head = [...ftyp, ...metaFor(headerSize)];
238
267
  const mdatSize = 8 + sizes.reduce((n, size) => n + size, 0);
@@ -9,6 +9,7 @@ import { MAX_PIXELS, checkPixels } from "../util/limits.js";
9
9
  import { decodeAV1 } from "./av1/frame.js";
10
10
  import { toSRGB, hdrToLinear } from "./hdr.js";
11
11
  import { runChunks, sharedOf, startThreads } from "../util/threads.js";
12
+ import { readISO } from "./gainmap.js";
12
13
  const fourcc = (d, o) => String.fromCharCode(d[o], d[o + 1], d[o + 2], d[o + 3]);
13
14
  function* boxes(d, start, end) {
14
15
  const view = new DataView(d.buffer, d.byteOffset, d.byteLength);
@@ -472,7 +473,7 @@ async function toRgba(y, alpha, toneMapping, premultiplied = false, threads = nu
472
473
  }
473
474
  const MIN_THREADED_PIXELS = 4 << 20, PIXELS_PER_THREAD = 1 << 20;
474
475
  const TILES_PER_THREAD = 4;
475
- export async function decode(d, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = 1) {
476
+ export async function decode(d, maxPixels = MAX_PIXELS, toneMapping = 'reinhard', threads = 1, gainMap = false) {
476
477
  if (!isAVIF(d))
477
478
  throw new Error('AVIF: invalid header');
478
479
  let meta, moov;
@@ -503,7 +504,10 @@ export async function decode(d, maxPixels = MAX_PIXELS, toneMapping = 'reinhard'
503
504
  const n = Math.min(threads, Math.floor(pixels / PIXELS_PER_THREAD));
504
505
  const pool = n > 1 && pixels >= MIN_THREADED_PIXELS && pixels <= maxPixels ? startThreads(n) : null;
505
506
  try {
506
- return await decodeImage(d, it, items, idat, alphaItem, alphaOf, maxPixels, toneMapping, pool);
507
+ const image = await decodeImage(d, it, items, idat, alphaItem, alphaOf, maxPixels, toneMapping, pool);
508
+ if (gainMap)
509
+ image.gainMap = await decodeGainMap(d, primary, items, idat, maxPixels).catch(() => undefined);
510
+ return image;
507
511
  }
508
512
  finally {
509
513
  if (pool)
@@ -531,7 +535,12 @@ async function decodeImage(d, it, items, idat, alphaItem, alphaOf, maxPixels, to
531
535
  alpha = await decodeGrid(d, it, items, idat, maxPixels, threads, tiles.map(t => t.id));
532
536
  }
533
537
  let pixels = await toRgba(color, alpha, toneMapping, alphaItem && (it.refs.get('prem') ?? []).includes(alphaItem.id), threads);
534
- let { width, height } = color;
538
+ const transformed = transform(d, it, color.width, color.height, pixels);
539
+ const { width, height } = transformed;
540
+ pixels = transformed.pixels;
541
+ return { width, height, pixels, icc, cicp: icc ? undefined : [color.primaries, color.transfer] };
542
+ }
543
+ function transform(d, it, width, height, pixels) {
535
544
  for (const { box } of it.props) {
536
545
  if (box.type === 'clap')
537
546
  ({ width, height, pixels } = clap(d, box, width, height, pixels));
@@ -540,7 +549,27 @@ async function decodeImage(d, it, items, idat, alphaItem, alphaOf, maxPixels, to
540
549
  else if (box.type === 'imir')
541
550
  pixels = mirror(pixels, width, height, d[box.start] & 1);
542
551
  }
543
- return { width, height, pixels, icc, cicp: icc ? undefined : [color.primaries, color.transfer] };
552
+ return { width, height, pixels };
553
+ }
554
+ async function decodeGainMap(d, primary, items, idat, maxPixels) {
555
+ for (const tmap of items.values()) {
556
+ const inputs = tmap.refs.get('dimg') ?? [];
557
+ if (tmap.type !== 'tmap' || inputs.length !== 2 || inputs[0] !== primary)
558
+ continue;
559
+ const data = itemData(d, tmap, idat);
560
+ if (data[0] !== 0)
561
+ return undefined;
562
+ const params = readISO(data.subarray(1));
563
+ const mapItem = items.get(inputs[1]);
564
+ if (!params || !mapItem)
565
+ return undefined;
566
+ const yuv = await decodeItem(d, mapItem, items, idat, maxPixels, null);
567
+ applyColr(d, mapItem, yuv);
568
+ yuv.transfer = 13;
569
+ const { width, height, pixels } = transform(d, mapItem, yuv.width, yuv.height, await toRgba(yuv, null, 'clamp'));
570
+ return { width, height, pixels, params };
571
+ }
572
+ return undefined;
544
573
  }
545
574
  function iccOf(d, it) {
546
575
  for (const { box } of it.props) {
@@ -0,0 +1,446 @@
1
+ const XMP_NAMESPACE = 'http://ns.adobe.com/xap/1.0/\0';
2
+ const ISO_NAMESPACE = 'urn:iso:std:iso:ts:21496:-1\0';
3
+ const MPF_SIGNATURE = 'MPF\0';
4
+ const HDRGM_URI = 'http://ns.adobe.com/hdr-gain-map/1.0/';
5
+ const APPLE_GAIN_MAP = 'urn:com:apple:photo:2020:aux:hdrgainmap';
6
+ export const APPLE_GAMMA = 1.961;
7
+ const ascii = (text) => Uint8Array.from(text, c => c.charCodeAt(0));
8
+ const startsWith = (data, offset, text) => {
9
+ if (offset + text.length > data.length)
10
+ return false;
11
+ for (let i = 0; i < text.length; i++)
12
+ if (data[offset + i] !== text.charCodeAt(i))
13
+ return false;
14
+ return true;
15
+ };
16
+ const latin1 = (data) => {
17
+ let text = '';
18
+ for (let i = 0; i < data.length; i += 0x8000)
19
+ text += String.fromCharCode(...data.subarray(i, i + 0x8000));
20
+ return text;
21
+ };
22
+ export function segments(data) {
23
+ const out = [];
24
+ if (data[0] !== 0xff || data[1] !== 0xd8)
25
+ return out;
26
+ let p = 2;
27
+ while (p + 4 <= data.length) {
28
+ if (data[p] !== 0xff)
29
+ break;
30
+ const marker = data[p + 1];
31
+ if (marker === 0xff) {
32
+ p++;
33
+ continue;
34
+ }
35
+ if (marker === 0xda || marker === 0xd9)
36
+ break;
37
+ if (marker >= 0xd0 && marker <= 0xd7 || marker === 0x01) {
38
+ p += 2;
39
+ continue;
40
+ }
41
+ const length = data[p + 2] << 8 | data[p + 3];
42
+ if (length < 2 || p + 2 + length > data.length)
43
+ break;
44
+ out.push({ marker, start: p, end: p + 2 + length, body: data.subarray(p + 4, p + 2 + length) });
45
+ p += 2 + length;
46
+ }
47
+ return out;
48
+ }
49
+ export function componentCount(data) {
50
+ for (const { marker, body } of segments(data))
51
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc)
52
+ return body[5] ?? 0;
53
+ return 0;
54
+ }
55
+ export function dimensions(data) {
56
+ for (const { marker, body } of segments(data))
57
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc && body.length >= 5)
58
+ return { width: body[3] << 8 | body[4], height: body[1] << 8 | body[2] };
59
+ return null;
60
+ }
61
+ function mpfImages(data, primary) {
62
+ const images = [];
63
+ for (const { marker, body, start } of primary) {
64
+ if (marker !== 0xe2 || !startsWith(body, 0, MPF_SIGNATURE))
65
+ continue;
66
+ const tiff = start + 4 + 4;
67
+ const view = new DataView(data.buffer, data.byteOffset + tiff, body.length - 4);
68
+ if (view.byteLength < 8)
69
+ return images;
70
+ const little = view.getUint16(0) === 0x4949;
71
+ const u16 = (o) => view.getUint16(o, little), u32 = (o) => view.getUint32(o, little);
72
+ const ifd = u32(4);
73
+ if (ifd + 2 > view.byteLength)
74
+ return images;
75
+ const count = u16(ifd);
76
+ let entries = -1, imageCount = 0;
77
+ for (let k = 0; k < count; k++) {
78
+ const t = ifd + 2 + 12 * k;
79
+ if (t + 12 > view.byteLength)
80
+ return images;
81
+ const tag = u16(t);
82
+ if (tag === 0xb001)
83
+ imageCount = u32(t + 8);
84
+ if (tag === 0xb002)
85
+ entries = u32(t + 8);
86
+ }
87
+ if (entries < 0 || imageCount < 2)
88
+ return images;
89
+ for (let k = 1; k < imageCount; k++) {
90
+ const e = entries + 16 * k;
91
+ if (e + 16 > view.byteLength)
92
+ return images;
93
+ const size = u32(e + 4), offset = u32(e + 8);
94
+ if (!offset || !size)
95
+ continue;
96
+ const begin = tiff + offset;
97
+ if (begin + size > data.length || data[begin] !== 0xff || data[begin + 1] !== 0xd8)
98
+ continue;
99
+ images.push(data.subarray(begin, begin + size));
100
+ }
101
+ return images;
102
+ }
103
+ return images;
104
+ }
105
+ function containerSecondImage(data, primary) {
106
+ for (const { marker, body } of primary) {
107
+ if (marker !== 0xe1 || !startsWith(body, 0, XMP_NAMESPACE))
108
+ continue;
109
+ const xmp = latin1(body.subarray(XMP_NAMESPACE.length));
110
+ const item = /Item:Semantic\s*=\s*["']GainMap["'][^>]*?Item:Length\s*=\s*["'](\d+)["']|Item:Length\s*=\s*["'](\d+)["'][^>]*?Item:Semantic\s*=\s*["']GainMap["']/.exec(xmp);
111
+ if (!item)
112
+ return null;
113
+ const length = Number(item[1] ?? item[2]), begin = data.length - length;
114
+ if (!(length > 0) || begin <= 0 || data[begin] !== 0xff || data[begin + 1] !== 0xd8)
115
+ return null;
116
+ return data.subarray(begin);
117
+ }
118
+ return null;
119
+ }
120
+ export function find(data) {
121
+ const primary = segments(data);
122
+ const images = mpfImages(data, primary);
123
+ const container = containerSecondImage(data, primary);
124
+ if (container)
125
+ images.push(container);
126
+ for (const map of images) {
127
+ const params = readParams(map);
128
+ if (params)
129
+ return { map, params };
130
+ }
131
+ for (const map of images) {
132
+ const apple = readApple(map, primary);
133
+ if (apple)
134
+ return { map, ...apple };
135
+ }
136
+ return null;
137
+ }
138
+ export const appleValue = (value, headroom) => Math.log2(1 + (headroom - 1) * value ** APPLE_GAMMA) / Math.log2(headroom);
139
+ function readApple(map, primary) {
140
+ let xmp = null;
141
+ for (const { marker, body } of segments(map))
142
+ if (marker === 0xe1 && startsWith(body, 0, XMP_NAMESPACE))
143
+ xmp = latin1(body.subarray(XMP_NAMESPACE.length));
144
+ if (!xmp || !xmp.includes(APPLE_GAIN_MAP) || !/HDRGainMapVersion/.test(xmp))
145
+ return null;
146
+ const value = (name) => {
147
+ const m = new RegExp(`:${name}\\s*(?:=\\s*["']([^"']*)["']|>([^<]*)<)`).exec(xmp);
148
+ return m ? Number((m[1] ?? m[2]).trim()) : null;
149
+ };
150
+ const headroom = value('HDRGainMapHeadroom') ?? makerNoteHeadroom(primary);
151
+ if (!(headroom !== null && headroom > 1 && Number.isFinite(headroom)))
152
+ return null;
153
+ const stops = Math.log2(headroom);
154
+ const params = { min: [0, 0, 0], max: [stops, stops, stops], gamma: [1, 1, 1], offsetSDR: [0, 0, 0], offsetHDR: [0, 0, 0], capacityMin: 0, capacityMax: stops, useBaseColorSpace: true };
155
+ return { params, apple: headroom };
156
+ }
157
+ function makerNoteHeadroom(primary) {
158
+ const exif = primary.find(({ marker, body }) => marker === 0xe1 && startsWith(body, 0, 'Exif\0\0'));
159
+ if (!exif)
160
+ return null;
161
+ const tiff = exif.body.subarray(6);
162
+ if (tiff.length < 8)
163
+ return null;
164
+ const view = new DataView(tiff.buffer, tiff.byteOffset, tiff.byteLength);
165
+ const little = view.getUint16(0) === 0x4949;
166
+ const entries = (v, at, le) => {
167
+ if (at + 2 > v.byteLength)
168
+ return [];
169
+ const out = [];
170
+ for (let k = 0, n = v.getUint16(at, le); k < n && at + 2 + 12 * k + 12 <= v.byteLength; k++) {
171
+ const e = at + 2 + 12 * k;
172
+ out.push({ tag: v.getUint16(e, le), type: v.getUint16(e + 2, le), count: v.getUint32(e + 4, le), value: v.getUint32(e + 8, le) });
173
+ }
174
+ return out;
175
+ };
176
+ const sub = entries(view, view.getUint32(4, little), little).find(e => e.tag === 0x8769);
177
+ const note = sub && entries(view, sub.value, little).find(e => e.tag === 0x927c);
178
+ if (!note || note.value + note.count > tiff.length)
179
+ return null;
180
+ const maker = tiff.subarray(note.value, note.value + note.count);
181
+ if (!startsWith(maker, 0, 'Apple iOS\0\0\x01MM'))
182
+ return null;
183
+ const mv = new DataView(maker.buffer, maker.byteOffset, maker.byteLength);
184
+ let m33 = null, m48 = 0;
185
+ for (const { tag, type, count, value } of entries(mv, 14, false)) {
186
+ if ((tag !== 33 && tag !== 48) || type !== 10 || count < 1 || value + 8 > maker.length)
187
+ continue;
188
+ const d = mv.getUint32(value + 4);
189
+ if (!d)
190
+ continue;
191
+ const r = mv.getInt32(value) / d;
192
+ if (tag === 33)
193
+ m33 = r;
194
+ else
195
+ m48 = r;
196
+ }
197
+ if (m33 === null)
198
+ return null;
199
+ const stops = m33 < 1 ? (m48 <= 0.01 ? -20 * m48 + 1.8 : -0.101 * m48 + 1.601) : (m48 <= 0.01 ? -70 * m48 + 3 : -0.303 * m48 + 2.303);
200
+ return 2 ** Math.max(stops, 0);
201
+ }
202
+ export function readParams(map) {
203
+ const list = segments(map);
204
+ for (const { marker, body } of list)
205
+ if (marker === 0xe2 && startsWith(body, 0, ISO_NAMESPACE)) {
206
+ const params = readISO(body.subarray(ISO_NAMESPACE.length));
207
+ if (params)
208
+ return params;
209
+ }
210
+ for (const { marker, body } of list)
211
+ if (marker === 0xe1 && startsWith(body, 0, XMP_NAMESPACE)) {
212
+ const params = readXMP(latin1(body.subarray(XMP_NAMESPACE.length)));
213
+ if (params)
214
+ return params;
215
+ }
216
+ return null;
217
+ }
218
+ export function valid(p) {
219
+ const ok = (v) => Number.isFinite(v);
220
+ for (let c = 0; c < 3; c++)
221
+ if (!ok(p.min[c]) || !ok(p.max[c]) || !ok(p.gamma[c]) || !ok(p.offsetSDR[c]) || !ok(p.offsetHDR[c]) || p.gamma[c] <= 0 || p.max[c] < p.min[c])
222
+ return false;
223
+ return ok(p.capacityMin) && ok(p.capacityMax) && p.capacityMax > p.capacityMin && p.capacityMin >= 0;
224
+ }
225
+ export function readISO(data) {
226
+ if (data.length < 5)
227
+ return null;
228
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
229
+ if (view.getUint16(0) !== 0)
230
+ return null;
231
+ const flags = data[4];
232
+ if (flags & 4)
233
+ return null;
234
+ const channels = flags & 0x80 ? 3 : 1, common = (flags & 8) !== 0;
235
+ let p = 5;
236
+ const need = (n) => p + n <= data.length;
237
+ let denominator = 1;
238
+ if (common) {
239
+ if (!need(4))
240
+ return null;
241
+ denominator = view.getUint32(p);
242
+ p += 4;
243
+ if (!denominator)
244
+ return null;
245
+ }
246
+ const fraction = (signed) => {
247
+ if (!need(common ? 4 : 8))
248
+ return NaN;
249
+ const n = signed ? view.getInt32(p) : view.getUint32(p);
250
+ const d = common ? denominator : view.getUint32(p + 4);
251
+ p += common ? 4 : 8;
252
+ return d ? n / d : NaN;
253
+ };
254
+ const capacityMin = fraction(false), capacityMax = fraction(false);
255
+ const min = [], max = [], gamma = [], offsetSDR = [], offsetHDR = [];
256
+ for (let c = 0; c < channels; c++) {
257
+ min.push(fraction(true));
258
+ max.push(fraction(true));
259
+ gamma.push(fraction(false));
260
+ offsetSDR.push(fraction(true));
261
+ offsetHDR.push(fraction(true));
262
+ }
263
+ const params = { min: fill3(min), max: fill3(max), gamma: fill3(gamma), offsetSDR: fill3(offsetSDR), offsetHDR: fill3(offsetHDR), capacityMin, capacityMax, useBaseColorSpace: (flags & 0x40) !== 0 };
264
+ return valid(params) ? params : null;
265
+ }
266
+ const fill3 = (values) => values.length === 1 ? [values[0], values[0], values[0]] : values.slice(0, 3);
267
+ function readXMP(xmp) {
268
+ if (!xmp.includes(HDRGM_URI))
269
+ return null;
270
+ const prefix = /xmlns:([\w-]+)\s*=\s*["']http:\/\/ns\.adobe\.com\/hdr-gain-map\/1\.0\/["']/.exec(xmp)?.[1] ?? 'hdrgm';
271
+ const get = (name) => {
272
+ const attribute = new RegExp(`${prefix}:${name}\\s*=\\s*["']([^"']*)["']`).exec(xmp);
273
+ if (attribute)
274
+ return [attribute[1]];
275
+ const element = new RegExp(`<${prefix}:${name}>([\\s\\S]*?)</${prefix}:${name}>`).exec(xmp);
276
+ if (!element)
277
+ return null;
278
+ const items = [...element[1].matchAll(/<rdf:li[^>]*>([^<]*)<\/rdf:li>/g)].map(m => m[1]);
279
+ return items.length ? items : [element[1].trim()];
280
+ };
281
+ const numbers = (name, fallback) => {
282
+ const values = get(name);
283
+ if (!values)
284
+ return fallback === null ? null : [fallback, fallback, fallback];
285
+ if (values.length !== 1 && values.length !== 3)
286
+ return null;
287
+ const parsed = values.map(v => v.trim() === '' ? NaN : Number(v));
288
+ return fill3(parsed);
289
+ };
290
+ if (!get('Version'))
291
+ return null;
292
+ if (/^\s*true\s*$/i.test(get('BaseRenditionIsHDR')?.[0] ?? ''))
293
+ return null;
294
+ const max = numbers('GainMapMax', null), capacityMax = numbers('HDRCapacityMax', null);
295
+ const min = numbers('GainMapMin', 0), gamma = numbers('Gamma', 1);
296
+ const offsetSDR = numbers('OffsetSDR', 1 / 64), offsetHDR = numbers('OffsetHDR', 1 / 64), capacityMin = numbers('HDRCapacityMin', 0);
297
+ if (!max || !capacityMax || !min || !gamma || !offsetSDR || !offsetHDR || !capacityMin)
298
+ return null;
299
+ const params = { min, max, gamma, offsetSDR, offsetHDR, capacityMin: capacityMin[0], capacityMax: capacityMax[0], useBaseColorSpace: true };
300
+ return valid(params) ? params : null;
301
+ }
302
+ const identical = (values) => values[0] === values[1] && values[0] === values[2];
303
+ export function singleChannel(p) {
304
+ return identical(p.min) && identical(p.max) && identical(p.gamma) && identical(p.offsetSDR) && identical(p.offsetHDR);
305
+ }
306
+ function toFraction(value, signed) {
307
+ const limit = signed ? 0x7fffffff : 0xffffffff;
308
+ let d = 1 << 30;
309
+ while (d > 1 && Math.abs(value) * d > limit)
310
+ d /= 2;
311
+ if (!signed && Math.abs(value) * d * 2 <= limit)
312
+ d *= 2;
313
+ return [Math.round(value * d), d];
314
+ }
315
+ export function writeISO(p) {
316
+ const channels = singleChannel(p) ? 1 : 3;
317
+ const out = new Uint8Array(5 + 16 + channels * 40);
318
+ const view = new DataView(out.buffer);
319
+ out[4] = (channels === 3 ? 0x80 : 0) | (p.useBaseColorSpace ? 0x40 : 0);
320
+ let o = 5;
321
+ const write = (value, signed) => {
322
+ const [n, d] = toFraction(value, signed);
323
+ if (signed)
324
+ view.setInt32(o, n);
325
+ else
326
+ view.setUint32(o, n);
327
+ view.setUint32(o + 4, d);
328
+ o += 8;
329
+ };
330
+ write(p.capacityMin, false);
331
+ write(p.capacityMax, false);
332
+ for (let c = 0; c < channels; c++) {
333
+ write(p.min[c], true);
334
+ write(p.max[c], true);
335
+ write(p.gamma[c], false);
336
+ write(p.offsetSDR[c], true);
337
+ write(p.offsetHDR[c], true);
338
+ }
339
+ return out;
340
+ }
341
+ const number = (v) => String(Math.round(v * 1e6) / 1e6);
342
+ export function writeMapXMP(p) {
343
+ const attributes = [`hdrgm:Version="1.0"`];
344
+ const elements = [];
345
+ const add = (name, values) => {
346
+ if (identical(values))
347
+ attributes.push(`hdrgm:${name}="${number(values[0])}"`);
348
+ else
349
+ elements.push(`<hdrgm:${name}><rdf:Seq>${values.map(v => `<rdf:li>${number(v)}</rdf:li>`).join('')}</rdf:Seq></hdrgm:${name}>`);
350
+ };
351
+ add('GainMapMin', p.min);
352
+ add('GainMapMax', p.max);
353
+ add('Gamma', p.gamma);
354
+ add('OffsetSDR', p.offsetSDR);
355
+ add('OffsetHDR', p.offsetHDR);
356
+ attributes.push(`hdrgm:HDRCapacityMin="${number(p.capacityMin)}"`, `hdrgm:HDRCapacityMax="${number(p.capacityMax)}"`, 'hdrgm:BaseRenditionIsHDR="False"');
357
+ const description = `<rdf:Description rdf:about="" xmlns:hdrgm="${HDRGM_URI}" ${attributes.join(' ')}${elements.length ? `>${elements.join('')}</rdf:Description>` : '/>'}`;
358
+ return `<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="ImageScript"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">${description}</rdf:RDF></x:xmpmeta>`;
359
+ }
360
+ export function writePrimaryXMP(mapLength) {
361
+ return '<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="ImageScript"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'
362
+ + `<rdf:Description xmlns:Container="http://ns.google.com/photos/1.0/container/" xmlns:Item="http://ns.google.com/photos/1.0/container/item/" xmlns:hdrgm="${HDRGM_URI}" hdrgm:Version="1.0">`
363
+ + '<Container:Directory><rdf:Seq>'
364
+ + '<rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="Primary" Item:Mime="image/jpeg"/></rdf:li>'
365
+ + `<rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="GainMap" Item:Mime="image/jpeg" Item:Length="${mapLength}"/></rdf:li>`
366
+ + '</rdf:Seq></Container:Directory></rdf:Description></rdf:RDF></x:xmpmeta>';
367
+ }
368
+ const segmentBytes = (marker, body) => {
369
+ if (body.length > 65533)
370
+ throw new RangeError('JPEG: metadata too large');
371
+ const out = new Uint8Array(4 + body.length);
372
+ out.set([0xff, marker, body.length + 2 >> 8, body.length + 2 & 255]);
373
+ out.set(body, 4);
374
+ return out;
375
+ };
376
+ const join = (parts) => {
377
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
378
+ let o = 0;
379
+ for (const p of parts) {
380
+ out.set(p, o);
381
+ o += p.length;
382
+ }
383
+ return out;
384
+ };
385
+ export function stripMetadata(jpeg) {
386
+ const remove = segments(jpeg).filter(({ marker, body }) => marker === 0xe1 && startsWith(body, 0, XMP_NAMESPACE)
387
+ || marker === 0xe2 && (startsWith(body, 0, ISO_NAMESPACE) || startsWith(body, 0, MPF_SIGNATURE)));
388
+ if (!remove.length)
389
+ return jpeg;
390
+ const parts = [];
391
+ let p = 0;
392
+ for (const { start, end } of remove) {
393
+ parts.push(jpeg.subarray(p, start));
394
+ p = end;
395
+ }
396
+ parts.push(jpeg.subarray(p));
397
+ return join(parts);
398
+ }
399
+ function insert(jpeg, added) {
400
+ let at = 2;
401
+ if (jpeg[2] === 0xff && jpeg[3] === 0xe0)
402
+ at = 4 + (jpeg[4] << 8 | jpeg[5]);
403
+ return join([jpeg.subarray(0, at), ...added, jpeg.subarray(at)]);
404
+ }
405
+ export function mapWithMetadata(body, p) {
406
+ const added = [segmentBytes(0xe1, join([ascii(XMP_NAMESPACE), ascii(writeMapXMP(p))])), segmentBytes(0xe2, join([ascii(ISO_NAMESPACE), writeISO(p)]))];
407
+ return insert(stripMetadata(body), added);
408
+ }
409
+ const MPF_LENGTH = 4 + 50 + 32;
410
+ export function primarySegments(mapLength) {
411
+ return [
412
+ segmentBytes(0xe1, join([ascii(XMP_NAMESPACE), ascii(writePrimaryXMP(mapLength))])),
413
+ segmentBytes(0xe2, join([ascii(ISO_NAMESPACE), new Uint8Array(4)])),
414
+ segmentBytes(0xe2, join([ascii(MPF_SIGNATURE), new Uint8Array(MPF_LENGTH - 4)]))
415
+ ];
416
+ }
417
+ export function finish(primary, map) {
418
+ const mpf = segments(primary).find(({ marker, body }) => marker === 0xe2 && startsWith(body, 0, MPF_SIGNATURE));
419
+ if (!mpf)
420
+ throw new Error('JPEG: missing MPF segment');
421
+ const tiff = mpf.start + 4 + 4;
422
+ const view = new DataView(primary.buffer, primary.byteOffset + tiff, MPF_LENGTH - 4);
423
+ view.setUint32(0, 0x4d4d002a);
424
+ view.setUint32(4, 8);
425
+ view.setUint16(8, 3);
426
+ view.setUint16(10, 0xb000);
427
+ view.setUint16(12, 7);
428
+ view.setUint32(14, 4);
429
+ view.setUint32(18, 0x30313030);
430
+ view.setUint16(22, 0xb001);
431
+ view.setUint16(24, 4);
432
+ view.setUint32(26, 1);
433
+ view.setUint32(30, 2);
434
+ view.setUint16(34, 0xb002);
435
+ view.setUint16(36, 7);
436
+ view.setUint32(38, 32);
437
+ view.setUint32(42, 50);
438
+ view.setUint32(46, 0);
439
+ view.setUint32(50, 0x030000);
440
+ view.setUint32(54, primary.length);
441
+ view.setUint32(58, 0);
442
+ view.setUint32(66, 0);
443
+ view.setUint32(70, map.length);
444
+ view.setUint32(74, primary.length - tiff);
445
+ return join([primary, map]);
446
+ }