@monogrid/gainmap-js 1.1.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +21 -8
  3. package/dist/QuadRenderer-2NcH1MyZ.js +238 -0
  4. package/dist/{_commonjsHelpers-1789f0cf.js → _commonjsHelpers-A0Fo_jMO.js} +1 -1
  5. package/dist/{compress-a4b59cab.js → compress-nWDFn7nF.js} +1 -1
  6. package/dist/{utils → core}/QuadRenderer.d.ts +3 -1
  7. package/dist/core/types.d.ts +64 -0
  8. package/dist/decode/decode.d.ts +56 -0
  9. package/dist/decode/extract.d.ts +10 -0
  10. package/dist/decode/index.d.ts +8 -0
  11. package/dist/{loaders → decode/loaders}/GainMapLoader.d.ts +1 -1
  12. package/dist/{loaders → decode/loaders}/JPEGRLoader.d.ts +3 -3
  13. package/dist/{loaders → decode/loaders}/LoaderBase.d.ts +2 -2
  14. package/dist/{materials → decode/materials}/GainMapDecoderMaterial.d.ts +3 -2
  15. package/dist/decode/types.d.ts +38 -0
  16. package/dist/decode/utils/MPFExtractor.d.ts +22 -0
  17. package/dist/decode/utils/extract-metadata-from-jpeg.d.ts +7 -0
  18. package/dist/decode.d.ts +1 -56
  19. package/dist/decode.js +735 -0
  20. package/dist/decode.umd.js +975 -0
  21. package/dist/{encode-utils → encode}/compress.d.ts +1 -1
  22. package/dist/encode/encode-and-compress.d.ts +61 -0
  23. package/dist/encode/encode.d.ts +58 -0
  24. package/dist/{encode-utils → encode}/get-gainmap.d.ts +3 -3
  25. package/dist/{encode-utils → encode}/get-sdr-rendition.d.ts +2 -3
  26. package/dist/encode/index.d.ts +10 -0
  27. package/dist/{types.d.ts → encode/types.d.ts} +2 -102
  28. package/dist/encode.d.ts +1 -117
  29. package/dist/{index.js → encode.js} +26 -218
  30. package/dist/encode.umd.js +1032 -0
  31. package/dist/libultrahdr/decode-jpeg-metadata.d.ts +2 -2
  32. package/dist/libultrahdr/encode-jpeg-metadata.d.ts +2 -1
  33. package/dist/libultrahdr.d.ts +0 -1
  34. package/dist/libultrahdr.js +2 -79
  35. package/dist/libultrahdr.umd.js +10 -460
  36. package/dist/worker-interface.js +2 -2
  37. package/dist/worker-interface.umd.js +1 -3
  38. package/dist/worker-types.d.ts +1 -1
  39. package/dist/worker.js +3 -3
  40. package/dist/worker.umd.js +1 -1
  41. package/package.json +36 -29
  42. package/dist/LoaderBase-eee19701.js +0 -382
  43. package/dist/index.d.ts +0 -11
  44. package/dist/index.umd.js +0 -1373
  45. package/dist/materials/index.d.ts +0 -3
  46. /package/dist/{utils → core}/get-data-texture.d.ts +0 -0
  47. /package/dist/{encode-utils → encode}/find-texture-min-max.d.ts +0 -0
  48. /package/dist/{materials → encode/materials}/GainMapEncoderMaterial.d.ts +0 -0
  49. /package/dist/{materials → encode/materials}/SDRMaterial.d.ts +0 -0
@@ -0,0 +1,975 @@
1
+ /**
2
+ * @monogrid/gainmap-js v2.0.0
3
+ * With ❤️, by MONOGRID <hello@mono-grid.com>
4
+ */
5
+
6
+ (function (global, factory) {
7
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three')) :
8
+ typeof define === 'function' && define.amd ? define(['exports', 'three'], factory) :
9
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@monogrid/gainmap-js"] = {}, global.three));
10
+ })(this, (function (exports, three) { 'use strict';
11
+
12
+ const getBufferForType = (type, width, height) => {
13
+ let out;
14
+ switch (type) {
15
+ case three.UnsignedByteType:
16
+ out = new Uint8ClampedArray(width * height * 4);
17
+ break;
18
+ case three.HalfFloatType:
19
+ out = new Uint16Array(width * height * 4);
20
+ break;
21
+ case three.UnsignedIntType:
22
+ out = new Uint32Array(width * height * 4);
23
+ break;
24
+ case three.ByteType:
25
+ out = new Int8Array(width * height * 4);
26
+ break;
27
+ case three.ShortType:
28
+ out = new Int16Array(width * height * 4);
29
+ break;
30
+ case three.IntType:
31
+ out = new Int32Array(width * height * 4);
32
+ break;
33
+ case three.FloatType:
34
+ out = new Float32Array(width * height * 4);
35
+ break;
36
+ default:
37
+ throw new Error('Unsupported data type');
38
+ }
39
+ return out;
40
+ };
41
+ let _canReadPixelsResult;
42
+ /**
43
+ * Test if this browser implementation can correctly read pixels from the specified
44
+ * Render target type.
45
+ *
46
+ * Runs only once
47
+ *
48
+ * @param type
49
+ * @param renderer
50
+ * @param camera
51
+ * @returns
52
+ */
53
+ const canReadPixels = (type, renderer, camera) => {
54
+ if (_canReadPixelsResult !== undefined)
55
+ return _canReadPixelsResult;
56
+ const testRT = new three.WebGLRenderTarget(1, 1, {
57
+ type,
58
+ colorSpace: three.NoColorSpace,
59
+ format: three.RGBAFormat,
60
+ magFilter: three.LinearFilter,
61
+ minFilter: three.LinearFilter,
62
+ wrapS: three.RepeatWrapping,
63
+ wrapT: three.RepeatWrapping,
64
+ depthBuffer: false,
65
+ stencilBuffer: false,
66
+ generateMipmaps: true
67
+ });
68
+ renderer.setRenderTarget(testRT);
69
+ const mesh = new three.Mesh(new three.PlaneGeometry(), new three.MeshBasicMaterial({ color: 0xffffff }));
70
+ renderer.render(mesh, camera);
71
+ renderer.setRenderTarget(null);
72
+ const out = getBufferForType(type, testRT.width, testRT.height);
73
+ renderer.readRenderTargetPixels(testRT, 0, 0, testRT.width, testRT.height, out);
74
+ testRT.dispose();
75
+ mesh.geometry.dispose();
76
+ mesh.material.dispose();
77
+ _canReadPixelsResult = out[0] !== 0;
78
+ return _canReadPixelsResult;
79
+ };
80
+ /**
81
+ * Utility structure used for rendering a texture with a material
82
+ *
83
+ * @category General
84
+ * @group General
85
+ */
86
+ class QuadRenderer {
87
+ /**
88
+ *
89
+ * @param sourceTexture
90
+ * @param renderer
91
+ */
92
+ constructor(width, height, type, colorSpace, material, renderer) {
93
+ this._rendererIsDisposable = false;
94
+ this._supportsReadPixels = true;
95
+ /**
96
+ * Renders the input texture using the specified material
97
+ */
98
+ this.render = () => {
99
+ this._renderer.setRenderTarget(this._renderTarget);
100
+ try {
101
+ this._renderer.render(this._scene, this._camera);
102
+ }
103
+ catch (e) {
104
+ this._renderer.setRenderTarget(null);
105
+ throw e;
106
+ }
107
+ this._renderer.setRenderTarget(null);
108
+ };
109
+ this._width = width;
110
+ this._height = height;
111
+ this._type = type;
112
+ this._colorSpace = colorSpace;
113
+ this._material = material;
114
+ if (renderer) {
115
+ this._renderer = renderer;
116
+ }
117
+ else {
118
+ this._renderer = QuadRenderer.instantiateRenderer();
119
+ this._rendererIsDisposable = true;
120
+ }
121
+ this._scene = new three.Scene();
122
+ this._camera = new three.OrthographicCamera();
123
+ this._camera.position.set(0, 0, 10);
124
+ this._camera.left = -0.5;
125
+ this._camera.right = 0.5;
126
+ this._camera.top = 0.5;
127
+ this._camera.bottom = -0.5;
128
+ this._camera.updateProjectionMatrix();
129
+ if (!canReadPixels(this._type, this._renderer, this._camera)) {
130
+ let alternativeType;
131
+ switch (this._type) {
132
+ case three.HalfFloatType:
133
+ alternativeType = this._renderer.extensions.has('EXT_color_buffer_float') ? three.FloatType : undefined;
134
+ break;
135
+ }
136
+ if (alternativeType !== undefined) {
137
+ console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${three.FloatType}`);
138
+ this._type = alternativeType;
139
+ }
140
+ else {
141
+ this._supportsReadPixels = false;
142
+ console.warn('This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown');
143
+ }
144
+ }
145
+ this._quad = new three.Mesh(new three.PlaneGeometry(), this._material);
146
+ this._quad.geometry.computeBoundingBox();
147
+ this._scene.add(this._quad);
148
+ this._renderTarget = new three.WebGLRenderTarget(width, height, {
149
+ type: this._type,
150
+ colorSpace,
151
+ format: three.RGBAFormat,
152
+ magFilter: three.LinearFilter,
153
+ minFilter: three.LinearMipMapLinearFilter,
154
+ wrapS: three.RepeatWrapping,
155
+ wrapT: three.RepeatWrapping,
156
+ depthBuffer: false,
157
+ stencilBuffer: false,
158
+ generateMipmaps: true
159
+ });
160
+ }
161
+ /**
162
+ * Instantiates a temporary renderer
163
+ *
164
+ * @returns
165
+ */
166
+ static instantiateRenderer() {
167
+ const renderer = new three.WebGLRenderer();
168
+ renderer.setSize(128, 128);
169
+ // renderer.outputColorSpace = SRGBColorSpace
170
+ // renderer.toneMapping = LinearToneMapping
171
+ // renderer.debug.checkShaderErrors = false
172
+ // this._rendererIsDisposable = true
173
+ return renderer;
174
+ }
175
+ /**
176
+ * Obtains a Buffer containing the rendered texture.
177
+ *
178
+ * @throws Error if the browser cannot read pixels from this RenderTarget type.
179
+ * @returns a TypedArray containing RGBA values from this renderer
180
+ */
181
+ toArray() {
182
+ if (!this._supportsReadPixels)
183
+ throw new Error('Can\'t read pixels in this browser');
184
+ const out = getBufferForType(this._type, this._width, this._height);
185
+ this._renderer.readRenderTargetPixels(this._renderTarget, 0, 0, this._width, this._height, out);
186
+ return out;
187
+ }
188
+ toDataTexture() {
189
+ return new three.DataTexture(this.toArray(), this.width, this.height, three.RGBAFormat, this._type, three.UVMapping, three.RepeatWrapping, three.RepeatWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, 1, three.NoColorSpace);
190
+ }
191
+ /**
192
+ * If using a disposable renderer, it will dispose it.
193
+ */
194
+ dispose() {
195
+ this._renderer.setRenderTarget(null);
196
+ if (this._rendererIsDisposable) {
197
+ this._renderer.dispose();
198
+ this._renderer.forceContextLoss();
199
+ }
200
+ }
201
+ /**
202
+ * Width of the texture
203
+ */
204
+ get width() { return this._width; }
205
+ set width(value) {
206
+ this._width = value;
207
+ this._renderTarget.setSize(this._width, this._height);
208
+ }
209
+ /**
210
+ * Height of the texture
211
+ */
212
+ get height() { return this._height; }
213
+ set height(value) {
214
+ this._height = value;
215
+ this._renderTarget.setSize(this._width, this._height);
216
+ }
217
+ /**
218
+ * The renderer used
219
+ */
220
+ get renderer() { return this._renderer; }
221
+ /**
222
+ * The `WebGLRenderTarget` used.
223
+ */
224
+ get renderTarget() { return this._renderTarget; }
225
+ set renderTarget(value) {
226
+ this._renderTarget = value;
227
+ this._width = value.width;
228
+ this._height = value.height;
229
+ // this._type = value.texture.type
230
+ }
231
+ /**
232
+ * The `Material` used.
233
+ */
234
+ get material() { return this._material; }
235
+ /**
236
+ *
237
+ */
238
+ get type() { return this._type; }
239
+ get colorSpace() { return this._colorSpace; }
240
+ }
241
+
242
+ const vertexShader = /* glsl */ `
243
+ varying vec2 vUv;
244
+
245
+ void main() {
246
+ vUv = uv;
247
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
248
+ }
249
+ `;
250
+ const fragmentShader = /* glsl */ `
251
+ uniform sampler2D sdr;
252
+ uniform sampler2D gainMap;
253
+ uniform vec3 gamma;
254
+ uniform vec3 offsetHdr;
255
+ uniform vec3 offsetSdr;
256
+ uniform vec3 gainMapMin;
257
+ uniform vec3 gainMapMax;
258
+ uniform float weightFactor;
259
+
260
+ varying vec2 vUv;
261
+
262
+ void main() {
263
+ vec3 rgb = texture2D(sdr, vUv).rgb;
264
+ vec3 recovery = texture2D(gainMap, vUv).rgb;
265
+ vec3 logRecovery = pow(recovery, gamma);
266
+ vec3 logBoost = gainMapMin * (1.0 - logRecovery) + gainMapMax * logRecovery;
267
+ vec3 hdrColor = (rgb + offsetSdr) * exp2(logBoost * weightFactor) - offsetHdr;
268
+ gl_FragColor = vec4(hdrColor, 1.0);
269
+ }
270
+ `;
271
+ /**
272
+ * A Material which is able to decode the Gainmap into a full HDR Representation
273
+ *
274
+ * @category Materials
275
+ * @group Materials
276
+ */
277
+ class GainMapDecoderMaterial extends three.ShaderMaterial {
278
+ /**
279
+ *
280
+ * @param params
281
+ */
282
+ constructor({ gamma, offsetHdr, offsetSdr, gainMapMin, gainMapMax, maxDisplayBoost, hdrCapacityMin, hdrCapacityMax, sdr, gainMap }) {
283
+ super({
284
+ name: 'GainMapDecoderMaterial',
285
+ vertexShader,
286
+ fragmentShader,
287
+ uniforms: {
288
+ sdr: { value: sdr },
289
+ gainMap: { value: gainMap },
290
+ gamma: { value: new three.Vector3(1.0 / gamma[0], 1.0 / gamma[1], 1.0 / gamma[2]) },
291
+ offsetHdr: { value: new three.Vector3().fromArray(offsetHdr) },
292
+ offsetSdr: { value: new three.Vector3().fromArray(offsetSdr) },
293
+ gainMapMin: { value: new three.Vector3().fromArray(gainMapMin) },
294
+ gainMapMax: { value: new three.Vector3().fromArray(gainMapMax) },
295
+ weightFactor: {
296
+ value: (Math.log2(maxDisplayBoost) - hdrCapacityMin) / (hdrCapacityMax - hdrCapacityMin)
297
+ }
298
+ },
299
+ blending: three.NoBlending,
300
+ depthTest: false,
301
+ depthWrite: false
302
+ });
303
+ this._maxDisplayBoost = maxDisplayBoost;
304
+ this._hdrCapacityMin = hdrCapacityMin;
305
+ this._hdrCapacityMax = hdrCapacityMax;
306
+ this.needsUpdate = true;
307
+ this.uniformsNeedUpdate = true;
308
+ }
309
+ get sdr() { return this.uniforms.sdr.value; }
310
+ set sdr(value) { this.uniforms.sdr.value = value; }
311
+ get gainMap() { return this.uniforms.gainMap.value; }
312
+ set gainMap(value) { this.uniforms.gainMap.value = value; }
313
+ /**
314
+ * @see {@link GainMapMetadata.offsetHdr}
315
+ */
316
+ get offsetHdr() { return this.uniforms.offsetHdr.value.toArray(); }
317
+ set offsetHdr(value) { this.uniforms.offsetHdr.value.fromArray(value); }
318
+ /**
319
+ * @see {@link GainMapMetadata.offsetSdr}
320
+ */
321
+ get offsetSdr() { return this.uniforms.offsetSdr.value.toArray(); }
322
+ set offsetSdr(value) { this.uniforms.offsetSdr.value.fromArray(value); }
323
+ /**
324
+ * @see {@link GainMapMetadata.gainMapMin}
325
+ */
326
+ get gainMapMin() { return this.uniforms.gainMapMin.value.toArray(); }
327
+ set gainMapMin(value) { this.uniforms.gainMapMin.value.fromArray(value); }
328
+ /**
329
+ * @see {@link GainMapMetadata.gainMapMax}
330
+ */
331
+ get gainMapMax() { return this.uniforms.gainMapMax.value.toArray(); }
332
+ set gainMapMax(value) { this.uniforms.gainMapMax.value.fromArray(value); }
333
+ /**
334
+ * @see {@link GainMapMetadata.gamma}
335
+ */
336
+ get gamma() {
337
+ const g = this.uniforms.gamma.value;
338
+ return [1 / g.x, 1 / g.y, 1 / g.z];
339
+ }
340
+ set gamma(value) {
341
+ const g = this.uniforms.gamma.value;
342
+ g.x = 1.0 / value[0];
343
+ g.y = 1.0 / value[1];
344
+ g.z = 1.0 / value[2];
345
+ }
346
+ /**
347
+ * @see {@link GainMapMetadata.hdrCapacityMin}
348
+ * @remarks Logarithmic space
349
+ */
350
+ get hdrCapacityMin() { return this._hdrCapacityMin; }
351
+ set hdrCapacityMin(value) {
352
+ this._hdrCapacityMin = value;
353
+ this.calculateWeight();
354
+ }
355
+ /**
356
+ * @see {@link GainMapMetadata.hdrCapacityMin}
357
+ * @remarks Logarithmic space
358
+ */
359
+ get hdrCapacityMax() { return this._hdrCapacityMax; }
360
+ set hdrCapacityMax(value) {
361
+ this._hdrCapacityMax = value;
362
+ this.calculateWeight();
363
+ }
364
+ /**
365
+ * @see {@link GainmapDecodingParameters.maxDisplayBoost}
366
+ * @remarks Non Logarithmic space
367
+ */
368
+ get maxDisplayBoost() { return this._maxDisplayBoost; }
369
+ set maxDisplayBoost(value) {
370
+ this._maxDisplayBoost = value;
371
+ this.calculateWeight();
372
+ }
373
+ calculateWeight() {
374
+ this.uniforms.weightFactor.value = (Math.log2(this._maxDisplayBoost) - this._hdrCapacityMin) / (this._hdrCapacityMax - this._hdrCapacityMin);
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Decodes a gain map using a WebGLRenderTarget
380
+ *
381
+ * @category Decoding
382
+ * @group Decoding
383
+ * @example
384
+ * import { decode } from '@monogrid/gainmap-js'
385
+ * import {
386
+ * Mesh,
387
+ * MeshBasicMaterial,
388
+ * PerspectiveCamera,
389
+ * PlaneGeometry,
390
+ * Scene,
391
+ * TextureLoader,
392
+ * WebGLRenderer
393
+ * } from 'three'
394
+ *
395
+ * const renderer = new WebGLRenderer()
396
+ *
397
+ * const textureLoader = new TextureLoader()
398
+ *
399
+ * // load SDR Representation
400
+ * const sdr = await textureLoader.loadAsync('sdr.jpg')
401
+ * // load Gain map recovery image
402
+ * const gainMap = await textureLoader.loadAsync('gainmap.jpg')
403
+ * // load metadata
404
+ * const metadata = await (await fetch('metadata.json')).json()
405
+ *
406
+ * const result = await decode({
407
+ * sdr,
408
+ * gainMap,
409
+ * // this allows to use `result.renderTarget.texture` directly
410
+ * renderer,
411
+ * // this will restore the full HDR range
412
+ * maxDisplayBoost: Math.pow(2, metadata.hdrCapacityMax),
413
+ * ...metadata
414
+ * })
415
+ *
416
+ * const scene = new Scene()
417
+ * // `result` can be used to populate a Texture
418
+ * const mesh = new Mesh(
419
+ * new PlaneGeometry(),
420
+ * new MeshBasicMaterial({ map: result.renderTarget.texture })
421
+ * )
422
+ * scene.add(mesh)
423
+ * renderer.render(scene, new PerspectiveCamera())
424
+ *
425
+ *
426
+ * @param params
427
+ * @returns
428
+ * @throws {Error} if the WebGLRenderer fails to render the gain map
429
+ */
430
+ const decode = (params) => {
431
+ const { sdr, gainMap, renderer } = params;
432
+ if (sdr.colorSpace !== three.SRGBColorSpace) {
433
+ console.warn('SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically');
434
+ sdr.colorSpace = three.SRGBColorSpace;
435
+ }
436
+ sdr.needsUpdate = true;
437
+ if (gainMap.colorSpace !== three.NoColorSpace) {
438
+ console.warn('Gainmap Colorspace needs to be *NoColorSpace*');
439
+ gainMap.colorSpace = three.NoColorSpace;
440
+ }
441
+ gainMap.needsUpdate = true;
442
+ const material = new GainMapDecoderMaterial(Object.assign(Object.assign({}, params), { sdr,
443
+ gainMap }));
444
+ const quadRenderer = new QuadRenderer(sdr.image.width, sdr.image.height, three.HalfFloatType, three.NoColorSpace, material, renderer);
445
+ try {
446
+ quadRenderer.render();
447
+ }
448
+ catch (e) {
449
+ quadRenderer.dispose();
450
+ throw e;
451
+ }
452
+ return quadRenderer;
453
+ };
454
+
455
+ const getAttribute = (description, name, defaultValue) => {
456
+ var _a;
457
+ let returnValue;
458
+ const parsedValue = (_a = description.attributes.getNamedItem(name)) === null || _a === void 0 ? void 0 : _a.nodeValue;
459
+ if (!parsedValue) {
460
+ const node = description.getElementsByTagName(name)[0];
461
+ if (node) {
462
+ const values = node.getElementsByTagName('rdf:li');
463
+ if (values.length === 3) {
464
+ returnValue = Array.from(values).map(v => v.innerHTML);
465
+ }
466
+ else {
467
+ throw new Error(`Gainmap metadata contains an array of items for ${name} but its length is not 3`);
468
+ }
469
+ }
470
+ else {
471
+ if (defaultValue)
472
+ return defaultValue;
473
+ else
474
+ throw new Error(`Can't find ${name} in gainmap metadata`);
475
+ }
476
+ }
477
+ else {
478
+ returnValue = parsedValue;
479
+ }
480
+ return returnValue;
481
+ };
482
+ /**
483
+ *
484
+ * @param input
485
+ * @returns
486
+ */
487
+ const extractXMP = (input) => {
488
+ var _a, _b;
489
+ let str;
490
+ // support node test evnvironment
491
+ if (typeof TextDecoder !== 'undefined')
492
+ str = new TextDecoder().decode(input);
493
+ else
494
+ str = input.toString();
495
+ let start = str.indexOf('<x:xmpmeta');
496
+ const parser = new DOMParser();
497
+ while (start !== -1) {
498
+ const end = str.indexOf('x:xmpmeta>', start);
499
+ str.slice(start, end + 10);
500
+ const xmpBlock = str.slice(start, end + 10);
501
+ try {
502
+ const xmlDocument = parser.parseFromString(xmpBlock, 'text/xml');
503
+ const description = xmlDocument.getElementsByTagName('rdf:Description')[0];
504
+ const gainMapMin = getAttribute(description, 'hdrgm:GainMapMin', '0');
505
+ const gainMapMax = getAttribute(description, 'hdrgm:GainMapMax');
506
+ const gamma = getAttribute(description, 'hdrgm:Gamma', '1');
507
+ const offsetSDR = getAttribute(description, 'hdrgm:OffsetSDR', '0.015625');
508
+ const offsetHDR = getAttribute(description, 'hdrgm:OffsetHDR', '0.015625');
509
+ let hdrCapacityMin = (_a = description.attributes.getNamedItem('hdrgm:HDRCapacityMin')) === null || _a === void 0 ? void 0 : _a.nodeValue;
510
+ if (!hdrCapacityMin)
511
+ hdrCapacityMin = '0';
512
+ const hdrCapacityMax = (_b = description.attributes.getNamedItem('hdrgm:HDRCapacityMax')) === null || _b === void 0 ? void 0 : _b.nodeValue;
513
+ if (!hdrCapacityMax)
514
+ throw new Error('Incomplete gainmap metadata');
515
+ return {
516
+ gainMapMin: Array.isArray(gainMapMin) ? gainMapMin.map(v => parseFloat(v)) : [parseFloat(gainMapMin), parseFloat(gainMapMin), parseFloat(gainMapMin)],
517
+ gainMapMax: Array.isArray(gainMapMax) ? gainMapMax.map(v => parseFloat(v)) : [parseFloat(gainMapMax), parseFloat(gainMapMax), parseFloat(gainMapMax)],
518
+ gamma: Array.isArray(gamma) ? gamma.map(v => parseFloat(v)) : [parseFloat(gamma), parseFloat(gamma), parseFloat(gamma)],
519
+ offsetSdr: Array.isArray(offsetSDR) ? offsetSDR.map(v => parseFloat(v)) : [parseFloat(offsetSDR), parseFloat(offsetSDR), parseFloat(offsetSDR)],
520
+ offsetHdr: Array.isArray(offsetHDR) ? offsetHDR.map(v => parseFloat(v)) : [parseFloat(offsetHDR), parseFloat(offsetHDR), parseFloat(offsetHDR)],
521
+ hdrCapacityMin: parseFloat(hdrCapacityMin),
522
+ hdrCapacityMax: parseFloat(hdrCapacityMax)
523
+ };
524
+ }
525
+ catch (e) {
526
+ }
527
+ start = str.indexOf('<x:xmpmeta', end);
528
+ }
529
+ };
530
+
531
+ /**
532
+ * MPF Extractor (Multi Picture Format Extractor)
533
+ * By Henrik S Nilsson 2019
534
+ *
535
+ * Extracts images stored in images based on the MPF format (found here: https://www.cipa.jp/e/std/std-sec.html
536
+ * under "CIPA DC-007-Translation-2021 Multi-Picture Format"
537
+ *
538
+ * Overly commented, and without intention of being complete or production ready.
539
+ * Created to extract depth maps from iPhone images, and to learn about image metadata.
540
+ * Kudos to: Phil Harvey (exiftool), Jaume Sanchez (android-lens-blur-depth-extractor)
541
+ */
542
+ class MPFExtractor {
543
+ constructor(options) {
544
+ this.options = {
545
+ debug: options && options.debug !== undefined ? options.debug : false,
546
+ extractFII: options && options.extractFII !== undefined ? options.extractFII : true,
547
+ extractNonFII: options && options.extractNonFII !== undefined ? options.extractNonFII : true
548
+ };
549
+ }
550
+ extract(imageArrayBuffer) {
551
+ return new Promise((resolve, reject) => {
552
+ const debug = this.options.debug;
553
+ const dataView = new DataView(imageArrayBuffer.buffer);
554
+ // If you're executing this line on a big endian machine, it'll be reversed.
555
+ // bigEnd further down though, refers to the endianness of the image itself.
556
+ if (dataView.getUint16(0) !== 0xffd8) {
557
+ reject('Not a valid jpeg');
558
+ return;
559
+ }
560
+ const length = dataView.byteLength;
561
+ let offset = 2;
562
+ let loops = 0;
563
+ let marker; // APP# marker
564
+ while (offset < length) {
565
+ if (++loops > 250) {
566
+ reject(`Found no marker after ${loops} loops 😵`);
567
+ return;
568
+ }
569
+ if (dataView.getUint8(offset) !== 0xff) {
570
+ reject(`Not a valid marker at offset 0x${offset.toString(16)}, found: 0x${dataView.getUint8(offset).toString(16)}`);
571
+ return;
572
+ }
573
+ marker = dataView.getUint8(offset + 1);
574
+ if (debug)
575
+ console.log(`Marker: ${marker.toString(16)}`);
576
+ if (marker === 0xe2) {
577
+ if (debug)
578
+ console.log('Found APP2 marker (0xffe2)');
579
+ // Works for iPhone 8 Plus, X, and XSMax. Or any photos of MPF format.
580
+ // Great way to visualize image information in html is using Exiftool. E.g.:
581
+ // ./exiftool.exe -htmldump -wantTrailer photo.jpg > photo.html
582
+ const formatPt = offset + 4;
583
+ /*
584
+ * Structure of the MP Format Identifier
585
+ *
586
+ * Offset Addr. | Code (Hex) | Description
587
+ * +00 ff Marker Prefix <-- offset
588
+ * +01 e2 APP2
589
+ * +02 #n APP2 Field Length
590
+ * +03 #n APP2 Field Length
591
+ * +04 4d 'M' <-- formatPt
592
+ * +05 50 'P'
593
+ * +06 46 'F'
594
+ * +07 00 NULL
595
+ * <-- tiffOffset
596
+ */
597
+ if (dataView.getUint32(formatPt) === 0x4d504600) {
598
+ // Found MPF tag, so we start dig out sub images
599
+ const tiffOffset = formatPt + 4;
600
+ let bigEnd; // Endianness from TIFF header
601
+ // Test for TIFF validity and endianness
602
+ // 0x4949 and 0x4D4D ('II' and 'MM') marks Little Endian and Big Endian
603
+ if (dataView.getUint16(tiffOffset) === 0x4949) {
604
+ bigEnd = false;
605
+ }
606
+ else if (dataView.getUint16(tiffOffset) === 0x4d4d) {
607
+ bigEnd = true;
608
+ }
609
+ else {
610
+ reject('No valid endianness marker found in TIFF header');
611
+ return;
612
+ }
613
+ if (dataView.getUint16(tiffOffset + 2, !bigEnd) !== 0x002a) {
614
+ reject('Not valid TIFF data! (no 0x002A marker)');
615
+ return;
616
+ }
617
+ // 32 bit number stating the offset from the start of the 8 Byte MP Header
618
+ // to MP Index IFD Least possible value is thus 8 (means 0 offset)
619
+ const firstIFDOffset = dataView.getUint32(tiffOffset + 4, !bigEnd);
620
+ if (firstIFDOffset < 0x00000008) {
621
+ reject('Not valid TIFF data! (First offset less than 8)');
622
+ return;
623
+ }
624
+ // Move ahead to MP Index IFD
625
+ // Assume we're at the first IFD, so firstIFDOffset points to
626
+ // MP Index IFD and not MP Attributes IFD. (If we try extract from a sub image,
627
+ // we fail silently here due to this assumption)
628
+ // Count (2 Byte) | MP Index Fields a.k.a. MP Entries (count * 12 Byte) | Offset of Next IFD (4 Byte)
629
+ const dirStart = tiffOffset + firstIFDOffset; // Start of IFD (Image File Directory)
630
+ const count = dataView.getUint16(dirStart, !bigEnd); // Count of MPEntries (2 Byte)
631
+ // Extract info from MPEntries (starting after Count)
632
+ const entriesStart = dirStart + 2;
633
+ let numberOfImages = 0;
634
+ for (let i = entriesStart; i < entriesStart + 12 * count; i += 12) {
635
+ // Each entry is 12 Bytes long
636
+ // Check MP Index IFD tags, here we only take tag 0xb001 = Number of images
637
+ if (dataView.getUint16(i, !bigEnd) === 0xb001) {
638
+ // stored in Last 4 bytes of its 12 Byte entry.
639
+ numberOfImages = dataView.getUint32(i + 8, !bigEnd);
640
+ }
641
+ }
642
+ const nextIFDOffsetLen = 4; // 4 Byte offset field that appears after MP Index IFD tags
643
+ const MPImageListValPt = dirStart + 2 + count * 12 + nextIFDOffsetLen;
644
+ const images = [];
645
+ for (let i = MPImageListValPt; i < MPImageListValPt + numberOfImages * 16; i += 16) {
646
+ const image = {
647
+ MPType: dataView.getUint32(i, !bigEnd),
648
+ size: dataView.getUint32(i + 4, !bigEnd),
649
+ // This offset is specified relative to the address of the MP Endian
650
+ // field in the MP Header, unless the image is a First Individual Image,
651
+ // in which case the value of the offset shall be NULL (0x00000000).
652
+ dataOffset: dataView.getUint32(i + 8, !bigEnd),
653
+ dependantImages: dataView.getUint32(i + 12, !bigEnd),
654
+ start: -1,
655
+ end: -1,
656
+ isFII: false
657
+ };
658
+ if (!image.dataOffset) {
659
+ // dataOffset is 0x00000000 for First Individual Image
660
+ image.start = 0;
661
+ image.isFII = true;
662
+ }
663
+ else {
664
+ image.start = tiffOffset + image.dataOffset;
665
+ image.isFII = false;
666
+ }
667
+ image.end = image.start + image.size;
668
+ images.push(image);
669
+ }
670
+ if (this.options.extractNonFII && images.length) {
671
+ const bufferBlob = new Blob([dataView]);
672
+ const imgs = [];
673
+ for (const image of images) {
674
+ if (image.isFII && !this.options.extractFII) {
675
+ continue; // Skip FII
676
+ }
677
+ const imageBlob = bufferBlob.slice(image.start, image.end + 1, 'image/jpeg');
678
+ // we don't need this
679
+ // const imageUrl = URL.createObjectURL(imageBlob)
680
+ // image.img = document.createElement('img')
681
+ // image.img.src = imageUrl
682
+ imgs.push(imageBlob);
683
+ }
684
+ resolve(imgs);
685
+ }
686
+ }
687
+ }
688
+ offset += 2 + dataView.getUint16(offset + 2);
689
+ }
690
+ });
691
+ }
692
+ }
693
+
694
+ /**
695
+ *
696
+ * @param jpegFile
697
+ * @returns
698
+ */
699
+ const extractGainmapFromJPEG = async (jpegFile) => {
700
+ const metadata = extractXMP(jpegFile);
701
+ if (!metadata)
702
+ throw new Error('Gain map XMP metadata not found');
703
+ const mpfExtractor = new MPFExtractor({ extractFII: true, extractNonFII: true });
704
+ const images = await mpfExtractor.extract(jpegFile);
705
+ if (images.length !== 2)
706
+ throw new Error('Gain map recovery image not found');
707
+ return {
708
+ sdr: new Uint8Array(await images[0].arrayBuffer()),
709
+ gainMap: new Uint8Array(await images[1].arrayBuffer()),
710
+ metadata
711
+ };
712
+ };
713
+
714
+ class LoaderBase extends three.Loader {
715
+ /**
716
+ *
717
+ * @param renderer
718
+ * @param manager
719
+ */
720
+ constructor(renderer, manager) {
721
+ super(manager);
722
+ this.renderer = renderer;
723
+ }
724
+ /**
725
+ * @private
726
+ * @returns
727
+ */
728
+ prepareQuadRenderer() {
729
+ // temporary values
730
+ const material = new GainMapDecoderMaterial({
731
+ gainMapMax: [1, 1, 1],
732
+ gainMapMin: [0, 0, 0],
733
+ gamma: [1, 1, 1],
734
+ offsetHdr: [1, 1, 1],
735
+ offsetSdr: [1, 1, 1],
736
+ hdrCapacityMax: 1,
737
+ hdrCapacityMin: 0,
738
+ maxDisplayBoost: 1,
739
+ gainMap: new three.Texture(),
740
+ sdr: new three.Texture()
741
+ });
742
+ return new QuadRenderer(16, 16, three.HalfFloatType, three.NoColorSpace, material, this.renderer);
743
+ }
744
+ /**
745
+ *
746
+ * @private
747
+ * @param quadRenderer
748
+ * @param gainMapBuffer
749
+ * @param sdrBuffer
750
+ * @param metadata
751
+ */
752
+ async render(quadRenderer, gainMapBuffer, sdrBuffer, metadata) {
753
+ const gainMapBlob = new Blob([gainMapBuffer], { type: 'image/jpeg' });
754
+ const sdrBlob = new Blob([sdrBuffer], { type: 'image/jpeg' });
755
+ const [gainMapImageBitmap, sdrImageBitmap] = await Promise.all([
756
+ createImageBitmap(gainMapBlob, { imageOrientation: 'flipY' }),
757
+ createImageBitmap(sdrBlob, { imageOrientation: 'flipY' })
758
+ ]);
759
+ const gainMap = new three.Texture(gainMapImageBitmap, three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.NoColorSpace);
760
+ gainMap.needsUpdate = true;
761
+ const sdr = new three.Texture(sdrImageBitmap, three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.SRGBColorSpace);
762
+ sdr.needsUpdate = true;
763
+ quadRenderer.width = sdrImageBitmap.width;
764
+ quadRenderer.height = sdrImageBitmap.height;
765
+ quadRenderer.material.gainMap = gainMap;
766
+ quadRenderer.material.sdr = sdr;
767
+ quadRenderer.material.gainMapMin = metadata.gainMapMin;
768
+ quadRenderer.material.gainMapMax = metadata.gainMapMax;
769
+ quadRenderer.material.offsetHdr = metadata.offsetHdr;
770
+ quadRenderer.material.offsetSdr = metadata.offsetSdr;
771
+ quadRenderer.material.gamma = metadata.gamma;
772
+ quadRenderer.material.hdrCapacityMin = metadata.hdrCapacityMin;
773
+ quadRenderer.material.hdrCapacityMax = metadata.hdrCapacityMax;
774
+ quadRenderer.material.maxDisplayBoost = Math.pow(2, metadata.hdrCapacityMax);
775
+ quadRenderer.material.needsUpdate = true;
776
+ quadRenderer.render();
777
+ }
778
+ }
779
+
780
+ /**
781
+ * A Three.js Loader for the gain map format.
782
+ *
783
+ * @category Loaders
784
+ * @group Loaders
785
+ *
786
+ * @example
787
+ * import { GainMapLoader } from '@monogrid/gainmap-js'
788
+ * import {
789
+ * EquirectangularReflectionMapping,
790
+ * LinearFilter,
791
+ * Mesh,
792
+ * MeshBasicMaterial,
793
+ * PerspectiveCamera,
794
+ * PlaneGeometry,
795
+ * Scene,
796
+ * WebGLRenderer
797
+ * } from 'three'
798
+ *
799
+ * const renderer = new WebGLRenderer()
800
+ *
801
+ * const loader = new GainMapLoader(renderer)
802
+ *
803
+ * const result = loader.load(['sdr.jpeg', 'gainmap.jpeg', 'metadata.json'])
804
+ * // `result` can be used to populate a Texture
805
+ *
806
+ * const scene = new Scene()
807
+ * const mesh = new Mesh(
808
+ * new PlaneGeometry(),
809
+ * new MeshBasicMaterial({ map: result.renderTarget.texture })
810
+ * )
811
+ * scene.add(mesh)
812
+ * renderer.render(scene, new PerspectiveCamera())
813
+ *
814
+ * // `result.renderTarget.texture` must be
815
+ * // converted to `DataTexture` in order
816
+ * // to use it as Equirectangular scene background
817
+ * // if needed
818
+ *
819
+ * scene.background = result.toDataTexture()
820
+ * scene.background.mapping = EquirectangularReflectionMapping
821
+ * scene.background.minFilter = LinearFilter
822
+ *
823
+ *
824
+ */
825
+ class GainMapLoader extends LoaderBase {
826
+ /**
827
+ * Loads a gainmap using separate data
828
+ * * sdr image
829
+ * * gain map image
830
+ * * metadata json
831
+ *
832
+ * useful for webp gain maps
833
+ *
834
+ * @param sdrUrl
835
+ * @param gainMapUrl
836
+ * @param metadataUrl
837
+ * @param onLoad
838
+ * @param onProgress
839
+ * @param onError
840
+ * @returns
841
+ */
842
+ load([sdrUrl, gainMapUrl, metadataUrl], onLoad, onProgress, onError) {
843
+ const quadRenderer = this.prepareQuadRenderer();
844
+ let sdr;
845
+ let gainMap;
846
+ let metadata;
847
+ const loadCheck = async () => {
848
+ if (sdr && gainMap && metadata) {
849
+ await this.render(quadRenderer, gainMap, sdr, metadata);
850
+ if (typeof onLoad === 'function')
851
+ onLoad(quadRenderer);
852
+ quadRenderer.dispose();
853
+ }
854
+ };
855
+ const progressHandler = (e) => {
856
+ };
857
+ const sdrLoader = new three.FileLoader(this.manager);
858
+ sdrLoader.setResponseType('arraybuffer');
859
+ sdrLoader.setRequestHeader(this.requestHeader);
860
+ sdrLoader.setPath(this.path);
861
+ sdrLoader.setWithCredentials(this.withCredentials);
862
+ sdrLoader.load(sdrUrl, async (buffer) => {
863
+ if (typeof buffer === 'string')
864
+ throw new Error('Invalid sdr buffer');
865
+ sdr = buffer;
866
+ loadCheck();
867
+ }, progressHandler, onError);
868
+ const gainMapLoader = new three.FileLoader(this.manager);
869
+ gainMapLoader.setResponseType('arraybuffer');
870
+ gainMapLoader.setRequestHeader(this.requestHeader);
871
+ gainMapLoader.setPath(this.path);
872
+ gainMapLoader.setWithCredentials(this.withCredentials);
873
+ gainMapLoader.load(gainMapUrl, async (buffer) => {
874
+ if (typeof buffer === 'string')
875
+ throw new Error('Invalid gainmap buffer');
876
+ gainMap = buffer;
877
+ loadCheck();
878
+ }, progressHandler, onError);
879
+ const metadataLoader = new three.FileLoader(this.manager);
880
+ // metadataLoader.setResponseType('json')
881
+ metadataLoader.setRequestHeader(this.requestHeader);
882
+ metadataLoader.setPath(this.path);
883
+ metadataLoader.setWithCredentials(this.withCredentials);
884
+ metadataLoader.load(metadataUrl, async (json) => {
885
+ if (typeof json !== 'string')
886
+ throw new Error('Invalid metadata string');
887
+ metadata = JSON.parse(json);
888
+ loadCheck();
889
+ }, progressHandler, onError);
890
+ return quadRenderer;
891
+ }
892
+ }
893
+
894
+ /**
895
+ * A Three.js Loader for a JPEG with embedded gainmap metadata.
896
+ *
897
+ * @category Loaders
898
+ * @group Loaders
899
+ *
900
+ * @example
901
+ * import { JPEGRLoader } from '@monogrid/gainmap-js'
902
+ * import {
903
+ * EquirectangularReflectionMapping,
904
+ * LinearFilter,
905
+ * Mesh,
906
+ * MeshBasicMaterial,
907
+ * PerspectiveCamera,
908
+ * PlaneGeometry,
909
+ * Scene,
910
+ * WebGLRenderer
911
+ * } from 'three'
912
+ *
913
+ * const renderer = new WebGLRenderer()
914
+ *
915
+ * const loader = new JPEGRLoader(renderer)
916
+ *
917
+ * const result = loader.load('gainmap.jpeg')
918
+ * // `result` can be used to populate a Texture
919
+ *
920
+ * const scene = new Scene()
921
+ * const mesh = new Mesh(
922
+ * new PlaneGeometry(),
923
+ * new MeshBasicMaterial({ map: result.renderTarget.texture })
924
+ * )
925
+ * scene.add(mesh)
926
+ * renderer.render(scene, new PerspectiveCamera())
927
+ *
928
+ * // `result.renderTarget.texture` must be
929
+ * // converted to `DataTexture` in order
930
+ * // to use it as Equirectangular scene background
931
+ * // if needed
932
+ *
933
+ * scene.background = result.toDataTexture()
934
+ * scene.background.mapping = EquirectangularReflectionMapping
935
+ * scene.background.minFilter = LinearFilter
936
+
937
+ *
938
+ */
939
+ class JPEGRLoader extends LoaderBase {
940
+ /**
941
+ *
942
+ * @param url
943
+ * @param onLoad
944
+ * @param onProgress
945
+ * @param onError
946
+ * @returns
947
+ */
948
+ load(url, onLoad, onProgress, onError) {
949
+ const quadRenderer = this.prepareQuadRenderer();
950
+ const loader = new three.FileLoader(this.manager);
951
+ loader.setResponseType('arraybuffer');
952
+ loader.setRequestHeader(this.requestHeader);
953
+ loader.setPath(this.path);
954
+ loader.setWithCredentials(this.withCredentials);
955
+ loader.load(url, async (jpeg) => {
956
+ if (typeof jpeg === 'string')
957
+ throw new Error('Invalid buffer');
958
+ const { gainMap: gainMapJPEG, sdr: sdrJPEG, metadata } = await extractGainmapFromJPEG(new Uint8Array(jpeg));
959
+ await this.render(quadRenderer, gainMapJPEG, sdrJPEG, metadata);
960
+ if (typeof onLoad === 'function')
961
+ onLoad(quadRenderer);
962
+ quadRenderer.dispose();
963
+ }, onProgress, onError);
964
+ return quadRenderer;
965
+ }
966
+ }
967
+
968
+ exports.GainMapDecoderMaterial = GainMapDecoderMaterial;
969
+ exports.GainMapLoader = GainMapLoader;
970
+ exports.JPEGRLoader = JPEGRLoader;
971
+ exports.QuadRenderer = QuadRenderer;
972
+ exports.decode = decode;
973
+ exports.extractGainmapFromJPEG = extractGainmapFromJPEG;
974
+
975
+ }));