@monogrid/gainmap-js 3.0.6 → 3.2.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/CHANGELOG.md +14 -0
- package/CODE_OF_CONDUCT.md +1 -1
- package/CONTRIBUTING.md +1 -1
- package/README.md +106 -2
- package/dist/Loader-BZcKUVaX.js +424 -0
- package/dist/{QuadRenderer-B3h-sJtp.js → QuadRenderer-Y5tm-R3m.js} +39 -30
- package/dist/{_commonjsHelpers-UqyNh5ZN.js → _commonjsHelpers-CuGYGi_5.js} +2 -2
- package/dist/{compress-CAiPfiRr.js → compress-BaKKOAXI.js} +2 -3
- package/dist/core/QuadRenderer.d.ts +2 -2
- package/dist/core/get-data-texture.d.ts +4 -3
- package/dist/core/types.d.ts +2 -1
- package/dist/decode/index.d.ts +1 -11
- package/dist/decode/shared/Loader.d.ts +59 -0
- package/dist/decode/shared/decode.d.ts +24 -0
- package/dist/decode/{extract.d.ts → shared/extract.d.ts} +4 -4
- package/dist/decode/shared/index.d.ts +8 -0
- package/dist/decode/shared/types.d.ts +53 -0
- package/dist/decode/{utils → shared/utils}/MPFExtractor.d.ts +1 -1
- package/dist/decode/shared/utils/extractXMP.d.ts +2 -0
- package/dist/decode/{decode.d.ts → webgl/decode.d.ts} +6 -6
- package/dist/decode/webgl/index.d.ts +8 -0
- package/dist/decode/{loaders → webgl/loaders}/GainMapLoader.d.ts +5 -6
- package/dist/decode/{loaders → webgl/loaders}/HDRJPGLoader.d.ts +6 -7
- package/dist/decode/webgl/loaders/LoaderBaseWebGL.d.ts +20 -0
- package/dist/decode/{materials → webgl/materials}/GainMapDecoderMaterial.d.ts +2 -2
- package/dist/decode/webgpu/core/QuadRenderer.d.ts +153 -0
- package/dist/decode/webgpu/decode.d.ts +60 -0
- package/dist/decode/webgpu/index.d.ts +8 -0
- package/dist/decode/webgpu/loaders/GainMapLoader.d.ts +69 -0
- package/dist/decode/webgpu/loaders/HDRJPGLoader.d.ts +65 -0
- package/dist/decode/webgpu/loaders/LoaderBaseWebGPU.d.ts +20 -0
- package/dist/decode/webgpu/materials/GainMapDecoderMaterial.d.ts +78 -0
- package/dist/decode.js +45 -442
- package/dist/decode.umd.cjs +388 -358
- package/dist/decode.webgpu.js +814 -0
- package/dist/decode.webgpu.umd.cjs +1244 -0
- package/dist/encode/encode-and-compress.d.ts +3 -3
- package/dist/encode/encode.d.ts +3 -3
- package/dist/encode/find-texture-min-max.d.ts +4 -3
- package/dist/encode/types.d.ts +4 -3
- package/dist/encode.js +32 -11
- package/dist/encode.umd.cjs +67 -38
- package/dist/libultrahdr/decode-jpeg-metadata.d.ts +0 -3
- package/dist/libultrahdr/encode-jpeg-metadata.d.ts +2 -2
- package/dist/libultrahdr.js +42 -75
- package/dist/libultrahdr.umd.cjs +46 -79
- package/dist/worker-interface.js +74 -64
- package/dist/worker-interface.umd.cjs +73 -63
- package/dist/worker.js +103 -88
- package/dist/worker.umd.cjs +103 -89
- package/package.json +79 -72
- package/dist/decode/loaders/LoaderBase.d.ts +0 -45
- package/dist/decode/types.d.ts +0 -42
- package/dist/decode/utils/extractXMP.d.ts +0 -7
- /package/dist/decode/{errors → shared/errors}/GainMapNotFoundError.d.ts +0 -0
- /package/dist/decode/{errors → shared/errors}/XMPMetadataNotFoundError.d.ts +0 -0
- /package/dist/decode/{utils → shared/utils}/get-html-image-from-blob.d.ts +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
+
# [3.2.0](https://github.com/MONOGRID/gainmap-js/compare/v3.1.0...v3.2.0) (2025-11-17)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Features
|
|
5
|
+
|
|
6
|
+
* WebGPU support ([#72](https://github.com/MONOGRID/gainmap-js/issues/72)) ([0d85bec](https://github.com/MONOGRID/gainmap-js/commit/0d85becd0e8b79fc5adfb5bbd757e35e032ee77e))
|
|
7
|
+
|
|
8
|
+
# [3.1.0](https://github.com/MONOGRID/gainmap-js/compare/v3.0.6...v3.1.0) (2024-12-05)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Features
|
|
12
|
+
|
|
13
|
+
* **decode:** removes `DOMParser`, decode is now compatible with Web Workers ([b6a607d](https://github.com/MONOGRID/gainmap-js/commit/b6a607d1be3e7e86524e059c9eb61c8ee2a9e6f7))
|
|
14
|
+
|
|
1
15
|
## [3.0.6](https://github.com/MONOGRID/gainmap-js/compare/v3.0.5...v3.0.6) (2024-09-03)
|
|
2
16
|
|
|
3
17
|
|
package/CODE_OF_CONDUCT.md
CHANGED
|
@@ -60,7 +60,7 @@ representative at an online or offline event.
|
|
|
60
60
|
|
|
61
61
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
|
62
62
|
reported to the community leaders responsible for enforcement at
|
|
63
|
-
|
|
63
|
+
gainmap@monogrid.com.
|
|
64
64
|
All complaints will be reviewed and investigated promptly and fairly.
|
|
65
65
|
|
|
66
66
|
All community leaders are obligated to respect the privacy and security of the
|
package/CONTRIBUTING.md
CHANGED
|
@@ -81,7 +81,7 @@ A good bug report shouldn't leave others needing to chase you up for more inform
|
|
|
81
81
|
<!-- omit in toc -->
|
|
82
82
|
#### How Do I Submit a Good Bug Report?
|
|
83
83
|
|
|
84
|
-
> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to <
|
|
84
|
+
> You must never report security related issues, vulnerabilities or bugs including sensitive information to the issue tracker, or elsewhere in public. Instead sensitive bugs must be sent by email to <gainmap@monogrid.com>.
|
|
85
85
|
<!-- You may add a PGP key to allow the messages to be sent encrypted as well. -->
|
|
86
86
|
|
|
87
87
|
We use GitHub issues to track bugs and errors. If you run into an issue with the project:
|
package/README.md
CHANGED
|
@@ -7,6 +7,13 @@ A Javascript (TypeScript) Encoder/Decoder Implementation of Adobe's Gain Map Tec
|
|
|
7
7
|
>
|
|
8
8
|
> It can be used for general encode/decode of gain maps but it depends on the three.js library which, in itself, is quite heavy if you only use it to encode/decode gain maps.
|
|
9
9
|
|
|
10
|
+
## Share Your Project!
|
|
11
|
+
Have you built something awesome using this library? We’d love to see what you’ve created!
|
|
12
|
+
Whether it’s a small demo or a full-scale application, your project can inspire others and help improve the library. Please share your work in one of these ways:
|
|
13
|
+
* GitHub Issues: [Open a new issue](https://github.com/MONOGRID/gainmap-js/issues/new) in this repository with a brief description, screenshots, and links to your project.
|
|
14
|
+
* Email: Send us an email at gainmap@monogrid.com with your project details.
|
|
15
|
+
Your contributions and creative ideas make our community stronger. We can’t wait to see what you build!
|
|
16
|
+
|
|
10
17
|
## Live Demo
|
|
11
18
|
|
|
12
19
|
https://monogrid.github.io/gainmap-js/
|
|
@@ -52,6 +59,7 @@ Refer to the [WIKI](https://github.com/MONOGRID/gainmap-js/wiki) for detailed do
|
|
|
52
59
|
The main use case of this library is to decode a JPEG file that contains gain map data
|
|
53
60
|
and use it instead of a traditional `.exr` or `.hdr` image.
|
|
54
61
|
|
|
62
|
+
> NOTE: Starting from v3.1.0 Decoding also works in a WebWorker, thanks to [Alejandro Romano](https://github.com/Arecsu) for the [contribution](https://github.com/MONOGRID/gainmap-js/pull/59)
|
|
55
63
|
|
|
56
64
|
### Using a single JPEG with embedded Gain map Metadata
|
|
57
65
|
|
|
@@ -79,6 +87,7 @@ import {
|
|
|
79
87
|
const renderer = new WebGLRenderer()
|
|
80
88
|
|
|
81
89
|
const loader = new HDRJPGLoader(renderer)
|
|
90
|
+
.setRenderTargetOptions({ mapping: EquirectangularReflectionMapping })
|
|
82
91
|
|
|
83
92
|
const result = await loader.loadAsync('gainmap.jpeg')
|
|
84
93
|
// `result` can be used to populate a Texture
|
|
@@ -98,7 +107,6 @@ renderer.render(scene, new PerspectiveCamera())
|
|
|
98
107
|
// it was previously needed to convert it
|
|
99
108
|
// to a DataTexture with `result.toDataTexture()`
|
|
100
109
|
scene.background = result.renderTarget.texture
|
|
101
|
-
scene.background.mapping = EquirectangularReflectionMapping
|
|
102
110
|
|
|
103
111
|
// result must be manually disposed
|
|
104
112
|
// when you are done using it
|
|
@@ -129,6 +137,7 @@ import {
|
|
|
129
137
|
const renderer = new WebGLRenderer()
|
|
130
138
|
|
|
131
139
|
const loader = new GainMapLoader(renderer)
|
|
140
|
+
.setRenderTargetOptions({ mapping: EquirectangularReflectionMapping })
|
|
132
141
|
|
|
133
142
|
const result = await loader.loadAsync(['sdr.jpeg', 'gainmap.jpeg', 'metadata.json'])
|
|
134
143
|
// `result` can be used to populate a Texture
|
|
@@ -148,13 +157,108 @@ renderer.render(scene, new PerspectiveCamera())
|
|
|
148
157
|
// it was previously needed to convert it
|
|
149
158
|
// to a DataTexture with `result.toDataTexture()`
|
|
150
159
|
scene.background = result.renderTarget.texture
|
|
151
|
-
scene.background.mapping = EquirectangularReflectionMapping
|
|
152
160
|
|
|
153
161
|
// result must be manually disposed
|
|
154
162
|
// when you are done using it
|
|
155
163
|
result.dispose()
|
|
156
164
|
```
|
|
157
165
|
|
|
166
|
+
### Decoding with WebGPU
|
|
167
|
+
|
|
168
|
+
> NOTE: WebGPU decoding requires three.js r163 or higher and a browser that supports WebGPU
|
|
169
|
+
|
|
170
|
+
The library provides WebGPU-accelerated decoding through the `@monogrid/gainmap-js/webgpu` entry point. WebGPU decoding uses Three.js Shading Language (TSL) and offers improved performance and modern GPU architecture support.
|
|
171
|
+
|
|
172
|
+
#### Using a single JPEG with embedded Gain map Metadata (WebGPU)
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
import { HDRJPGLoader } from '@monogrid/gainmap-js/webgpu'
|
|
176
|
+
import {
|
|
177
|
+
EquirectangularReflectionMapping,
|
|
178
|
+
Mesh,
|
|
179
|
+
MeshBasicMaterial,
|
|
180
|
+
PerspectiveCamera,
|
|
181
|
+
PlaneGeometry,
|
|
182
|
+
Scene,
|
|
183
|
+
WebGPURenderer
|
|
184
|
+
} from 'three/webgpu'
|
|
185
|
+
|
|
186
|
+
const renderer = new WebGPURenderer()
|
|
187
|
+
await renderer.init()
|
|
188
|
+
|
|
189
|
+
const loader = new HDRJPGLoader(renderer)
|
|
190
|
+
.setRenderTargetOptions({ mapping: EquirectangularReflectionMapping })
|
|
191
|
+
|
|
192
|
+
const result = await loader.loadAsync('gainmap.jpeg')
|
|
193
|
+
// `result` can be used to populate a Texture
|
|
194
|
+
|
|
195
|
+
const scene = new Scene()
|
|
196
|
+
const mesh = new Mesh(
|
|
197
|
+
new PlaneGeometry(),
|
|
198
|
+
new MeshBasicMaterial({ map: result.renderTarget.texture })
|
|
199
|
+
)
|
|
200
|
+
scene.add(mesh)
|
|
201
|
+
renderer.render(scene, new PerspectiveCamera())
|
|
202
|
+
|
|
203
|
+
// Starting from three.js r159
|
|
204
|
+
// `result.renderTarget.texture` can
|
|
205
|
+
// also be used as Equirectangular scene background
|
|
206
|
+
scene.background = result.renderTarget.texture
|
|
207
|
+
|
|
208
|
+
// result must be manually disposed
|
|
209
|
+
// when you are done using it
|
|
210
|
+
result.dispose()
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
#### Using separate files (WebGPU)
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
import { GainMapLoader } from '@monogrid/gainmap-js/webgpu'
|
|
217
|
+
import {
|
|
218
|
+
EquirectangularReflectionMapping,
|
|
219
|
+
Mesh,
|
|
220
|
+
MeshBasicMaterial,
|
|
221
|
+
PerspectiveCamera,
|
|
222
|
+
PlaneGeometry,
|
|
223
|
+
Scene,
|
|
224
|
+
WebGPURenderer
|
|
225
|
+
} from 'three/webgpu'
|
|
226
|
+
|
|
227
|
+
const renderer = new WebGPURenderer()
|
|
228
|
+
await renderer.init()
|
|
229
|
+
|
|
230
|
+
const loader = new GainMapLoader(renderer)
|
|
231
|
+
.setRenderTargetOptions({ mapping: EquirectangularReflectionMapping })
|
|
232
|
+
|
|
233
|
+
const result = await loader.loadAsync(['sdr.jpeg', 'gainmap.jpeg', 'metadata.json'])
|
|
234
|
+
// `result` can be used to populate a Texture
|
|
235
|
+
|
|
236
|
+
const scene = new Scene()
|
|
237
|
+
const mesh = new Mesh(
|
|
238
|
+
new PlaneGeometry(),
|
|
239
|
+
new MeshBasicMaterial({ map: result.renderTarget.texture })
|
|
240
|
+
)
|
|
241
|
+
scene.add(mesh)
|
|
242
|
+
renderer.render(scene, new PerspectiveCamera())
|
|
243
|
+
|
|
244
|
+
// Starting from three.js r159
|
|
245
|
+
// `result.renderTarget.texture` can
|
|
246
|
+
// also be used as Equirectangular scene background
|
|
247
|
+
scene.background = result.renderTarget.texture
|
|
248
|
+
|
|
249
|
+
// result must be manually disposed
|
|
250
|
+
// when you are done using it
|
|
251
|
+
result.dispose()
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
#### Key differences between WebGL and WebGPU
|
|
255
|
+
|
|
256
|
+
1. **Import path**: Use `@monogrid/gainmap-js/webgpu` instead of `@monogrid/gainmap-js`
|
|
257
|
+
2. **Three.js imports**: Use `three/webgpu` instead of `three`
|
|
258
|
+
3. **Renderer**: Use `WebGPURenderer` instead of `WebGLRenderer`
|
|
259
|
+
4. **Renderer initialization**: Call `await renderer.init()` before using WebGPU renderer
|
|
260
|
+
5. **Async decoding**: The `decode()` function is async in WebGPU
|
|
261
|
+
|
|
158
262
|
### Encoding
|
|
159
263
|
|
|
160
264
|
Encoding a Gain map starting from an EXR file.
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monogrid/gainmap-js v3.2.0
|
|
3
|
+
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { SRGBColorSpace, LinearSRGBColorSpace, HalfFloatType, Loader, LoadingManager, Texture, UVMapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType } from 'three';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Shared decode implementation factory
|
|
10
|
+
* Creates a decode function that prepares a QuadRenderer with the given parameters
|
|
11
|
+
*/
|
|
12
|
+
function createDecodeFunction(config) {
|
|
13
|
+
return (params) => {
|
|
14
|
+
const { sdr, gainMap, renderer } = params;
|
|
15
|
+
if (sdr.colorSpace !== SRGBColorSpace) {
|
|
16
|
+
console.warn('SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically');
|
|
17
|
+
sdr.colorSpace = SRGBColorSpace;
|
|
18
|
+
}
|
|
19
|
+
sdr.needsUpdate = true;
|
|
20
|
+
if (gainMap.colorSpace !== LinearSRGBColorSpace) {
|
|
21
|
+
console.warn('Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically');
|
|
22
|
+
gainMap.colorSpace = LinearSRGBColorSpace;
|
|
23
|
+
}
|
|
24
|
+
gainMap.needsUpdate = true;
|
|
25
|
+
const material = config.createMaterial({
|
|
26
|
+
...params,
|
|
27
|
+
sdr,
|
|
28
|
+
gainMap
|
|
29
|
+
});
|
|
30
|
+
const quadRenderer = config.createQuadRenderer({
|
|
31
|
+
width: sdr.image.width,
|
|
32
|
+
height: sdr.image.height,
|
|
33
|
+
type: HalfFloatType,
|
|
34
|
+
colorSpace: LinearSRGBColorSpace,
|
|
35
|
+
material,
|
|
36
|
+
renderer,
|
|
37
|
+
renderTargetOptions: params.renderTargetOptions
|
|
38
|
+
});
|
|
39
|
+
return quadRenderer;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
class GainMapNotFoundError extends Error {
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
class XMPMetadataNotFoundError extends Error {
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const getXMLValue = (xml, tag, defaultValue) => {
|
|
50
|
+
// Check for attribute format first: tag="value"
|
|
51
|
+
const attributeMatch = new RegExp(`${tag}="([^"]*)"`, 'i').exec(xml);
|
|
52
|
+
if (attributeMatch)
|
|
53
|
+
return attributeMatch[1];
|
|
54
|
+
// Check for tag format: <tag>value</tag> or <tag><rdf:li>value</rdf:li>...</tag>
|
|
55
|
+
const tagMatch = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, 'i').exec(xml);
|
|
56
|
+
if (tagMatch) {
|
|
57
|
+
// Check if it contains rdf:li elements
|
|
58
|
+
const liValues = tagMatch[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);
|
|
59
|
+
if (liValues && liValues.length === 3) {
|
|
60
|
+
return liValues.map(v => v.replace(/<\/?rdf:li>/g, ''));
|
|
61
|
+
}
|
|
62
|
+
return tagMatch[1].trim();
|
|
63
|
+
}
|
|
64
|
+
if (defaultValue !== undefined)
|
|
65
|
+
return defaultValue;
|
|
66
|
+
throw new Error(`Can't find ${tag} in gainmap metadata`);
|
|
67
|
+
};
|
|
68
|
+
const extractXMP = (input) => {
|
|
69
|
+
let str;
|
|
70
|
+
// support node test environment
|
|
71
|
+
if (typeof TextDecoder !== 'undefined')
|
|
72
|
+
str = new TextDecoder().decode(input);
|
|
73
|
+
else
|
|
74
|
+
str = input.toString();
|
|
75
|
+
let start = str.indexOf('<x:xmpmeta');
|
|
76
|
+
while (start !== -1) {
|
|
77
|
+
const end = str.indexOf('x:xmpmeta>', start);
|
|
78
|
+
const xmpBlock = str.slice(start, end + 10);
|
|
79
|
+
try {
|
|
80
|
+
const gainMapMin = getXMLValue(xmpBlock, 'hdrgm:GainMapMin', '0');
|
|
81
|
+
const gainMapMax = getXMLValue(xmpBlock, 'hdrgm:GainMapMax');
|
|
82
|
+
const gamma = getXMLValue(xmpBlock, 'hdrgm:Gamma', '1');
|
|
83
|
+
const offsetSDR = getXMLValue(xmpBlock, 'hdrgm:OffsetSDR', '0.015625');
|
|
84
|
+
const offsetHDR = getXMLValue(xmpBlock, 'hdrgm:OffsetHDR', '0.015625');
|
|
85
|
+
// These are always attributes, so we can use a simpler regex
|
|
86
|
+
const hdrCapacityMinMatch = /hdrgm:HDRCapacityMin="([^"]*)"/.exec(xmpBlock);
|
|
87
|
+
const hdrCapacityMin = hdrCapacityMinMatch ? hdrCapacityMinMatch[1] : '0';
|
|
88
|
+
const hdrCapacityMaxMatch = /hdrgm:HDRCapacityMax="([^"]*)"/.exec(xmpBlock);
|
|
89
|
+
if (!hdrCapacityMaxMatch)
|
|
90
|
+
throw new Error('Incomplete gainmap metadata');
|
|
91
|
+
const hdrCapacityMax = hdrCapacityMaxMatch[1];
|
|
92
|
+
return {
|
|
93
|
+
gainMapMin: Array.isArray(gainMapMin) ? gainMapMin.map(v => parseFloat(v)) : [parseFloat(gainMapMin), parseFloat(gainMapMin), parseFloat(gainMapMin)],
|
|
94
|
+
gainMapMax: Array.isArray(gainMapMax) ? gainMapMax.map(v => parseFloat(v)) : [parseFloat(gainMapMax), parseFloat(gainMapMax), parseFloat(gainMapMax)],
|
|
95
|
+
gamma: Array.isArray(gamma) ? gamma.map(v => parseFloat(v)) : [parseFloat(gamma), parseFloat(gamma), parseFloat(gamma)],
|
|
96
|
+
offsetSdr: Array.isArray(offsetSDR) ? offsetSDR.map(v => parseFloat(v)) : [parseFloat(offsetSDR), parseFloat(offsetSDR), parseFloat(offsetSDR)],
|
|
97
|
+
offsetHdr: Array.isArray(offsetHDR) ? offsetHDR.map(v => parseFloat(v)) : [parseFloat(offsetHDR), parseFloat(offsetHDR), parseFloat(offsetHDR)],
|
|
98
|
+
hdrCapacityMin: parseFloat(hdrCapacityMin),
|
|
99
|
+
hdrCapacityMax: parseFloat(hdrCapacityMax)
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
catch (e) {
|
|
103
|
+
// Continue searching for another xmpmeta block if this one fails
|
|
104
|
+
}
|
|
105
|
+
start = str.indexOf('<x:xmpmeta', end);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* MPF Extractor (Multi Picture Format Extractor)
|
|
111
|
+
* By Henrik S Nilsson 2019
|
|
112
|
+
*
|
|
113
|
+
* Extracts images stored in images based on the MPF format (found here: https://www.cipa.jp/e/std/std-sec.html
|
|
114
|
+
* under "CIPA DC-007-Translation-2021 Multi-Picture Format"
|
|
115
|
+
*
|
|
116
|
+
* Overly commented, and without intention of being complete or production ready.
|
|
117
|
+
* Created to extract depth maps from iPhone images, and to learn about image metadata.
|
|
118
|
+
* Kudos to: Phil Harvey (exiftool), Jaume Sanchez (android-lens-blur-depth-extractor)
|
|
119
|
+
*/
|
|
120
|
+
class MPFExtractor {
|
|
121
|
+
options;
|
|
122
|
+
constructor(options) {
|
|
123
|
+
this.options = {
|
|
124
|
+
debug: options && options.debug !== undefined ? options.debug : false,
|
|
125
|
+
extractFII: options && options.extractFII !== undefined ? options.extractFII : true,
|
|
126
|
+
extractNonFII: options && options.extractNonFII !== undefined ? options.extractNonFII : true
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
extract(imageArrayBuffer) {
|
|
130
|
+
return new Promise((resolve, reject) => {
|
|
131
|
+
const debug = this.options.debug;
|
|
132
|
+
const dataView = new DataView(imageArrayBuffer.buffer);
|
|
133
|
+
// If you're executing this line on a big endian machine, it'll be reversed.
|
|
134
|
+
// bigEnd further down though, refers to the endianness of the image itself.
|
|
135
|
+
if (dataView.getUint16(0) !== 0xffd8) {
|
|
136
|
+
reject(new Error('Not a valid jpeg'));
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const length = dataView.byteLength;
|
|
140
|
+
let offset = 2;
|
|
141
|
+
let loops = 0;
|
|
142
|
+
let marker; // APP# marker
|
|
143
|
+
while (offset < length) {
|
|
144
|
+
if (++loops > 250) {
|
|
145
|
+
reject(new Error(`Found no marker after ${loops} loops 😵`));
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (dataView.getUint8(offset) !== 0xff) {
|
|
149
|
+
reject(new Error(`Not a valid marker at offset 0x${offset.toString(16)}, found: 0x${dataView.getUint8(offset).toString(16)}`));
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
marker = dataView.getUint8(offset + 1);
|
|
153
|
+
if (debug)
|
|
154
|
+
console.log(`Marker: ${marker.toString(16)}`);
|
|
155
|
+
if (marker === 0xe2) {
|
|
156
|
+
if (debug)
|
|
157
|
+
console.log('Found APP2 marker (0xffe2)');
|
|
158
|
+
// Works for iPhone 8 Plus, X, and XSMax. Or any photos of MPF format.
|
|
159
|
+
// Great way to visualize image information in html is using Exiftool. E.g.:
|
|
160
|
+
// ./exiftool.exe -htmldump -wantTrailer photo.jpg > photo.html
|
|
161
|
+
const formatPt = offset + 4;
|
|
162
|
+
/*
|
|
163
|
+
* Structure of the MP Format Identifier
|
|
164
|
+
*
|
|
165
|
+
* Offset Addr. | Code (Hex) | Description
|
|
166
|
+
* +00 ff Marker Prefix <-- offset
|
|
167
|
+
* +01 e2 APP2
|
|
168
|
+
* +02 #n APP2 Field Length
|
|
169
|
+
* +03 #n APP2 Field Length
|
|
170
|
+
* +04 4d 'M' <-- formatPt
|
|
171
|
+
* +05 50 'P'
|
|
172
|
+
* +06 46 'F'
|
|
173
|
+
* +07 00 NULL
|
|
174
|
+
* <-- tiffOffset
|
|
175
|
+
*/
|
|
176
|
+
if (dataView.getUint32(formatPt) === 0x4d504600) {
|
|
177
|
+
// Found MPF tag, so we start dig out sub images
|
|
178
|
+
const tiffOffset = formatPt + 4;
|
|
179
|
+
let bigEnd; // Endianness from TIFF header
|
|
180
|
+
// Test for TIFF validity and endianness
|
|
181
|
+
// 0x4949 and 0x4D4D ('II' and 'MM') marks Little Endian and Big Endian
|
|
182
|
+
if (dataView.getUint16(tiffOffset) === 0x4949) {
|
|
183
|
+
bigEnd = false;
|
|
184
|
+
}
|
|
185
|
+
else if (dataView.getUint16(tiffOffset) === 0x4d4d) {
|
|
186
|
+
bigEnd = true;
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
reject(new Error('No valid endianness marker found in TIFF header'));
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (dataView.getUint16(tiffOffset + 2, !bigEnd) !== 0x002a) {
|
|
193
|
+
reject(new Error('Not valid TIFF data! (no 0x002A marker)'));
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
// 32 bit number stating the offset from the start of the 8 Byte MP Header
|
|
197
|
+
// to MP Index IFD Least possible value is thus 8 (means 0 offset)
|
|
198
|
+
const firstIFDOffset = dataView.getUint32(tiffOffset + 4, !bigEnd);
|
|
199
|
+
if (firstIFDOffset < 0x00000008) {
|
|
200
|
+
reject(new Error('Not valid TIFF data! (First offset less than 8)'));
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
// Move ahead to MP Index IFD
|
|
204
|
+
// Assume we're at the first IFD, so firstIFDOffset points to
|
|
205
|
+
// MP Index IFD and not MP Attributes IFD. (If we try extract from a sub image,
|
|
206
|
+
// we fail silently here due to this assumption)
|
|
207
|
+
// Count (2 Byte) | MP Index Fields a.k.a. MP Entries (count * 12 Byte) | Offset of Next IFD (4 Byte)
|
|
208
|
+
const dirStart = tiffOffset + firstIFDOffset; // Start of IFD (Image File Directory)
|
|
209
|
+
const count = dataView.getUint16(dirStart, !bigEnd); // Count of MPEntries (2 Byte)
|
|
210
|
+
// Extract info from MPEntries (starting after Count)
|
|
211
|
+
const entriesStart = dirStart + 2;
|
|
212
|
+
let numberOfImages = 0;
|
|
213
|
+
for (let i = entriesStart; i < entriesStart + 12 * count; i += 12) {
|
|
214
|
+
// Each entry is 12 Bytes long
|
|
215
|
+
// Check MP Index IFD tags, here we only take tag 0xb001 = Number of images
|
|
216
|
+
if (dataView.getUint16(i, !bigEnd) === 0xb001) {
|
|
217
|
+
// stored in Last 4 bytes of its 12 Byte entry.
|
|
218
|
+
numberOfImages = dataView.getUint32(i + 8, !bigEnd);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const nextIFDOffsetLen = 4; // 4 Byte offset field that appears after MP Index IFD tags
|
|
222
|
+
const MPImageListValPt = dirStart + 2 + count * 12 + nextIFDOffsetLen;
|
|
223
|
+
const images = [];
|
|
224
|
+
for (let i = MPImageListValPt; i < MPImageListValPt + numberOfImages * 16; i += 16) {
|
|
225
|
+
const image = {
|
|
226
|
+
MPType: dataView.getUint32(i, !bigEnd),
|
|
227
|
+
size: dataView.getUint32(i + 4, !bigEnd),
|
|
228
|
+
// This offset is specified relative to the address of the MP Endian
|
|
229
|
+
// field in the MP Header, unless the image is a First Individual Image,
|
|
230
|
+
// in which case the value of the offset shall be NULL (0x00000000).
|
|
231
|
+
dataOffset: dataView.getUint32(i + 8, !bigEnd),
|
|
232
|
+
dependantImages: dataView.getUint32(i + 12, !bigEnd),
|
|
233
|
+
start: -1,
|
|
234
|
+
end: -1,
|
|
235
|
+
isFII: false
|
|
236
|
+
};
|
|
237
|
+
if (!image.dataOffset) {
|
|
238
|
+
// dataOffset is 0x00000000 for First Individual Image
|
|
239
|
+
image.start = 0;
|
|
240
|
+
image.isFII = true;
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
image.start = tiffOffset + image.dataOffset;
|
|
244
|
+
image.isFII = false;
|
|
245
|
+
}
|
|
246
|
+
image.end = image.start + image.size;
|
|
247
|
+
images.push(image);
|
|
248
|
+
}
|
|
249
|
+
if (this.options.extractNonFII && images.length) {
|
|
250
|
+
const bufferBlob = new Blob([dataView]);
|
|
251
|
+
const imgs = [];
|
|
252
|
+
for (const image of images) {
|
|
253
|
+
if (image.isFII && !this.options.extractFII) {
|
|
254
|
+
continue; // Skip FII
|
|
255
|
+
}
|
|
256
|
+
const imageBlob = bufferBlob.slice(image.start, image.end + 1, 'image/jpeg');
|
|
257
|
+
// we don't need this
|
|
258
|
+
// const imageUrl = URL.createObjectURL(imageBlob)
|
|
259
|
+
// image.img = document.createElement('img')
|
|
260
|
+
// image.img.src = imageUrl
|
|
261
|
+
imgs.push(imageBlob);
|
|
262
|
+
}
|
|
263
|
+
resolve(imgs);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
offset += 2 + dataView.getUint16(offset + 2);
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Extracts XMP Metadata and the gain map recovery image
|
|
275
|
+
* from a single JPEG file.
|
|
276
|
+
*
|
|
277
|
+
* @category Decoding Functions
|
|
278
|
+
* @group Decoding Functions
|
|
279
|
+
* @param jpegFile an `Uint8Array` containing and encoded JPEG file
|
|
280
|
+
* @returns an sdr `Uint8Array` compressed in JPEG, a gainMap `Uint8Array` compressed in JPEG and the XMP parsed XMP metadata
|
|
281
|
+
* @throws Error if XMP Metadata is not found
|
|
282
|
+
* @throws Error if Gain map image is not found
|
|
283
|
+
* @example
|
|
284
|
+
* import { FileLoader } from 'three'
|
|
285
|
+
* import { extractGainmapFromJPEG } from '@monogrid/gainmap-js'
|
|
286
|
+
*
|
|
287
|
+
* const jpegFile = await new FileLoader()
|
|
288
|
+
* .setResponseType('arraybuffer')
|
|
289
|
+
* .loadAsync('image.jpg')
|
|
290
|
+
*
|
|
291
|
+
* const { sdr, gainMap, metadata } = extractGainmapFromJPEG(jpegFile)
|
|
292
|
+
*/
|
|
293
|
+
const extractGainmapFromJPEG = async (jpegFile) => {
|
|
294
|
+
const metadata = extractXMP(jpegFile);
|
|
295
|
+
if (!metadata)
|
|
296
|
+
throw new XMPMetadataNotFoundError('Gain map XMP metadata not found');
|
|
297
|
+
const mpfExtractor = new MPFExtractor({ extractFII: true, extractNonFII: true });
|
|
298
|
+
const images = await mpfExtractor.extract(jpegFile);
|
|
299
|
+
if (images.length !== 2)
|
|
300
|
+
throw new GainMapNotFoundError('Gain map recovery image not found');
|
|
301
|
+
return {
|
|
302
|
+
sdr: new Uint8Array(await images[0].arrayBuffer()),
|
|
303
|
+
gainMap: new Uint8Array(await images[1].arrayBuffer()),
|
|
304
|
+
metadata
|
|
305
|
+
};
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* private function, async get image from blob
|
|
310
|
+
*
|
|
311
|
+
* @param blob
|
|
312
|
+
* @returns
|
|
313
|
+
*/
|
|
314
|
+
const getHTMLImageFromBlob = (blob) => {
|
|
315
|
+
return new Promise((resolve, reject) => {
|
|
316
|
+
const img = document.createElement('img');
|
|
317
|
+
img.onload = () => { resolve(img); };
|
|
318
|
+
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
|
|
319
|
+
img.onerror = (e) => { reject(e); };
|
|
320
|
+
img.src = URL.createObjectURL(blob);
|
|
321
|
+
});
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Shared base class for loaders that extracts common logic
|
|
326
|
+
*/
|
|
327
|
+
class LoaderBaseShared extends Loader {
|
|
328
|
+
_renderer;
|
|
329
|
+
_renderTargetOptions;
|
|
330
|
+
_internalLoadingManager;
|
|
331
|
+
_config;
|
|
332
|
+
constructor(config, manager) {
|
|
333
|
+
super(manager);
|
|
334
|
+
this._config = config;
|
|
335
|
+
if (config.renderer)
|
|
336
|
+
this._renderer = config.renderer;
|
|
337
|
+
this._internalLoadingManager = new LoadingManager();
|
|
338
|
+
}
|
|
339
|
+
setRenderer(renderer) {
|
|
340
|
+
this._renderer = renderer;
|
|
341
|
+
return this;
|
|
342
|
+
}
|
|
343
|
+
setRenderTargetOptions(options) {
|
|
344
|
+
this._renderTargetOptions = options;
|
|
345
|
+
return this;
|
|
346
|
+
}
|
|
347
|
+
prepareQuadRenderer() {
|
|
348
|
+
if (!this._renderer) {
|
|
349
|
+
console.warn('WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer.');
|
|
350
|
+
}
|
|
351
|
+
const material = this._config.createMaterial({
|
|
352
|
+
gainMapMax: [1, 1, 1],
|
|
353
|
+
gainMapMin: [0, 0, 0],
|
|
354
|
+
gamma: [1, 1, 1],
|
|
355
|
+
offsetHdr: [1, 1, 1],
|
|
356
|
+
offsetSdr: [1, 1, 1],
|
|
357
|
+
hdrCapacityMax: 1,
|
|
358
|
+
hdrCapacityMin: 0,
|
|
359
|
+
maxDisplayBoost: 1,
|
|
360
|
+
gainMap: new Texture(),
|
|
361
|
+
sdr: new Texture()
|
|
362
|
+
});
|
|
363
|
+
return this._config.createQuadRenderer({
|
|
364
|
+
width: 16,
|
|
365
|
+
height: 16,
|
|
366
|
+
type: HalfFloatType,
|
|
367
|
+
colorSpace: LinearSRGBColorSpace,
|
|
368
|
+
material,
|
|
369
|
+
renderer: this._renderer,
|
|
370
|
+
renderTargetOptions: this._renderTargetOptions
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
async processImages(sdrBuffer, gainMapBuffer, imageOrientation) {
|
|
374
|
+
const gainMapBlob = gainMapBuffer ? new Blob([gainMapBuffer], { type: 'image/jpeg' }) : undefined;
|
|
375
|
+
const sdrBlob = new Blob([sdrBuffer], { type: 'image/jpeg' });
|
|
376
|
+
let sdrImage;
|
|
377
|
+
let gainMapImage;
|
|
378
|
+
let needsFlip = false;
|
|
379
|
+
if (typeof createImageBitmap === 'undefined') {
|
|
380
|
+
const res = await Promise.all([
|
|
381
|
+
gainMapBlob ? getHTMLImageFromBlob(gainMapBlob) : Promise.resolve(undefined),
|
|
382
|
+
getHTMLImageFromBlob(sdrBlob)
|
|
383
|
+
]);
|
|
384
|
+
gainMapImage = res[0];
|
|
385
|
+
sdrImage = res[1];
|
|
386
|
+
needsFlip = imageOrientation === 'flipY';
|
|
387
|
+
}
|
|
388
|
+
else {
|
|
389
|
+
const res = await Promise.all([
|
|
390
|
+
gainMapBlob ? createImageBitmap(gainMapBlob, { imageOrientation: imageOrientation || 'flipY' }) : Promise.resolve(undefined),
|
|
391
|
+
createImageBitmap(sdrBlob, { imageOrientation: imageOrientation || 'flipY' })
|
|
392
|
+
]);
|
|
393
|
+
gainMapImage = res[0];
|
|
394
|
+
sdrImage = res[1];
|
|
395
|
+
}
|
|
396
|
+
return { sdrImage, gainMapImage, needsFlip };
|
|
397
|
+
}
|
|
398
|
+
createTextures(sdrImage, gainMapImage, needsFlip) {
|
|
399
|
+
const gainMap = new Texture(gainMapImage || new ImageData(2, 2), UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType, 1, LinearSRGBColorSpace);
|
|
400
|
+
gainMap.flipY = needsFlip;
|
|
401
|
+
gainMap.needsUpdate = true;
|
|
402
|
+
const sdr = new Texture(sdrImage, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, LinearMipMapLinearFilter, RGBAFormat, UnsignedByteType, 1, SRGBColorSpace);
|
|
403
|
+
sdr.flipY = needsFlip;
|
|
404
|
+
sdr.needsUpdate = true;
|
|
405
|
+
return { gainMap, sdr };
|
|
406
|
+
}
|
|
407
|
+
updateQuadRenderer(quadRenderer, sdrImage, gainMap, sdr, metadata) {
|
|
408
|
+
quadRenderer.width = sdrImage.width;
|
|
409
|
+
quadRenderer.height = sdrImage.height;
|
|
410
|
+
quadRenderer.material.gainMap = gainMap;
|
|
411
|
+
quadRenderer.material.sdr = sdr;
|
|
412
|
+
quadRenderer.material.gainMapMin = metadata.gainMapMin;
|
|
413
|
+
quadRenderer.material.gainMapMax = metadata.gainMapMax;
|
|
414
|
+
quadRenderer.material.offsetHdr = metadata.offsetHdr;
|
|
415
|
+
quadRenderer.material.offsetSdr = metadata.offsetSdr;
|
|
416
|
+
quadRenderer.material.gamma = metadata.gamma;
|
|
417
|
+
quadRenderer.material.hdrCapacityMin = metadata.hdrCapacityMin;
|
|
418
|
+
quadRenderer.material.hdrCapacityMax = metadata.hdrCapacityMax;
|
|
419
|
+
quadRenderer.material.maxDisplayBoost = Math.pow(2, metadata.hdrCapacityMax);
|
|
420
|
+
quadRenderer.material.needsUpdate = true;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
export { GainMapNotFoundError as G, LoaderBaseShared as L, MPFExtractor as M, XMPMetadataNotFoundError as X, extractXMP as a, createDecodeFunction as c, extractGainmapFromJPEG as e };
|