@monogrid/gainmap-js 3.4.1 → 3.5.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/Loader-BdKdEGSJ.js +5 -0
  3. package/dist/{Loader-Bi9FKrn4.js → Loader-CL7itwBq.js} +46 -6
  4. package/dist/{QuadRenderer-D1rYlVRa.js → QuadRenderer-DIHDdKl6.js} +1 -1
  5. package/dist/{QuadRenderer-Bl8ThfRL.js → QuadRenderer-DPiEee1I.js} +1 -1
  6. package/dist/{_commonjsHelpers-D4ntYHBT.js → _commonjsHelpers-DVRbpukU.js} +1 -1
  7. package/dist/{_commonjsHelpers-CHnLGTFq.js → _commonjsHelpers-S7tZmPW-.js} +1 -1
  8. package/dist/{compress-B5svUHuf.js → compress-5gFn7Y4a.js} +1 -1
  9. package/dist/{compress-DBGuVQfM.js → compress-CTBeaiI1.js} +1 -1
  10. package/dist/core/iso-gainmap-metadata.d.ts +40 -0
  11. package/dist/decode/shared/extract.d.ts +5 -3
  12. package/dist/decode/shared/index.d.ts +1 -0
  13. package/dist/decode/shared/utils/extractISO.d.ts +15 -0
  14. package/dist/decode.js +5 -4
  15. package/dist/decode.min.js +2 -2
  16. package/dist/decode.umd.cjs +122 -5
  17. package/dist/decode.umd.min.cjs +2 -2
  18. package/dist/decode.webgpu.js +4 -3
  19. package/dist/decode.webgpu.min.js +2 -2
  20. package/dist/decode.webgpu.umd.cjs +122 -5
  21. package/dist/decode.webgpu.umd.min.cjs +2 -2
  22. package/dist/encode.js +4 -4
  23. package/dist/encode.min.js +2 -2
  24. package/dist/encode.umd.cjs +1 -1
  25. package/dist/encode.umd.min.cjs +1 -1
  26. package/dist/iso-gainmap-metadata-DNTSE4Qp.js +5 -0
  27. package/dist/iso-gainmap-metadata-Dk2F4Eoz.js +141 -0
  28. package/dist/libultrahdr/jpeg-assembler.d.ts +2 -0
  29. package/dist/libultrahdr.js +30 -7
  30. package/dist/libultrahdr.min.js +2 -2
  31. package/dist/libultrahdr.umd.cjs +104 -7
  32. package/dist/libultrahdr.umd.min.cjs +2 -2
  33. package/dist/third-party.txt +69 -69
  34. package/dist/worker-interface.js +2 -2
  35. package/dist/worker-interface.min.js +2 -2
  36. package/dist/worker-interface.umd.cjs +1 -1
  37. package/dist/worker-interface.umd.min.cjs +1 -1
  38. package/dist/worker.js +3 -3
  39. package/dist/worker.min.js +2 -2
  40. package/dist/worker.umd.cjs +1 -1
  41. package/dist/worker.umd.min.cjs +1 -1
  42. package/package.json +5 -1
  43. package/dist/Loader-uEDs4JZg.js +0 -5
@@ -0,0 +1,141 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.5.0
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+
6
+ /**
7
+ * ISO 21496-1 binary gain map metadata (de)serialization
8
+ * Based on libultrahdr gainmapmetadata.cpp implementation
9
+ *
10
+ * Layout (big endian):
11
+ * - u16 minimum_version, u16 writer_version
12
+ * - u8 flags (bit 7: multichannel, bit 6: use base colour space, bit 2: backward direction, bit 3: common denominator)
13
+ * - headroom: base_hdr_headroom, alternate_hdr_headroom (unsigned fractions)
14
+ * - per channel: gain_map_min (s), gain_map_max (s), gamma (u), base_offset (s), alternate_offset (s)
15
+ *
16
+ * Fractions are written as numerator + denominator, or numerator only when the common denominator flag is set.
17
+ */
18
+ /**
19
+ * Namespace identifying an ISO 21496-1 APP2 segment (null terminated)
20
+ */
21
+ const ISO_NAMESPACE = 'urn:iso:std:iso:ts:21496:-1\0';
22
+ const IS_MULTICHANNEL_MASK = 1 << 7;
23
+ const USE_BASE_COLOR_SPACE_MASK = 1 << 6;
24
+ const USE_COMMON_DENOMINATOR_MASK = 1 << 3;
25
+ const BACKWARD_DIRECTION_MASK = 1 << 2;
26
+ const INT32_MAX = 0x7fffffff;
27
+ const UINT32_MAX = 0xffffffff;
28
+ /**
29
+ * Converts a float into a fraction, using the largest denominator that keeps the numerator in range
30
+ */
31
+ const toFraction = (value, signed) => {
32
+ const max = signed ? INT32_MAX : UINT32_MAX;
33
+ if (!Number.isFinite(value) || (!signed && value < 0) || Math.abs(value) > max) {
34
+ throw new Error(`Cannot represent ${value} as an ${signed ? 'signed' : 'unsigned'} ISO 21496-1 fraction`);
35
+ }
36
+ const denominator = Math.min(UINT32_MAX, Math.floor(max / Math.max(1, Math.abs(value))));
37
+ return [Math.round(value * denominator), denominator];
38
+ };
39
+ /**
40
+ * The version-only payload stored in the primary image (minimum_version = 0, writer_version = 0)
41
+ */
42
+ const ISO_VERSION_ONLY = new Uint8Array(4);
43
+ /**
44
+ * Serializes gain map metadata into an ISO 21496-1 binary payload
45
+ * (without namespace), to be stored in the gain map image.
46
+ *
47
+ * Values are already in the expected space: gainMapMin/Max and hdrCapacityMin/Max
48
+ * are log2, gamma and offsets are linear.
49
+ *
50
+ * @param metadata
51
+ * @returns
52
+ */
53
+ const encodeISOGainMapMetadata = (metadata) => {
54
+ const channels = [0, 1, 2].map(i => [metadata.gainMapMin[i], metadata.gainMapMax[i], metadata.gamma[i], metadata.offsetSdr[i], metadata.offsetHdr[i]]);
55
+ const isMultiChannel = channels.some(c => c.some((v, j) => v !== channels[0][j]));
56
+ const channelCount = isMultiChannel ? 3 : 1;
57
+ const data = new Uint8Array(5 + 16 + 40 * channelCount);
58
+ const view = new DataView(data.buffer);
59
+ let pos = 4; // minimum_version and writer_version are 0
60
+ // the gain map is computed in the base image colour space
61
+ view.setUint8(pos++, (isMultiChannel ? IS_MULTICHANNEL_MASK : 0) | USE_BASE_COLOR_SPACE_MASK);
62
+ const writeFraction = (value, signed) => {
63
+ const [n, d] = toFraction(value, signed);
64
+ if (signed)
65
+ view.setInt32(pos, n);
66
+ else
67
+ view.setUint32(pos, n);
68
+ view.setUint32(pos + 4, d);
69
+ pos += 8;
70
+ };
71
+ writeFraction(metadata.hdrCapacityMin, false);
72
+ writeFraction(metadata.hdrCapacityMax, false);
73
+ for (let i = 0; i < channelCount; i++) {
74
+ const [min, max, gamma, offsetSdr, offsetHdr] = channels[i];
75
+ writeFraction(min, true);
76
+ writeFraction(max, true);
77
+ writeFraction(gamma, false);
78
+ writeFraction(offsetSdr, true);
79
+ writeFraction(offsetHdr, true);
80
+ }
81
+ return data;
82
+ };
83
+ /**
84
+ * Parses an ISO 21496-1 binary payload (without namespace)
85
+ *
86
+ * @param data
87
+ * @returns the parsed metadata
88
+ * @throws {Error} if the payload is unsupported (version, backward direction) or malformed
89
+ */
90
+ const decodeISOGainMapMetadata = (data) => {
91
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
92
+ let pos = 0;
93
+ const readU16 = () => { const v = view.getUint16(pos); pos += 2; return v; };
94
+ const readU32 = () => { const v = view.getUint32(pos); pos += 4; return v; };
95
+ const readS32 = () => { const v = view.getInt32(pos); pos += 4; return v; };
96
+ const minimumVersion = readU16();
97
+ if (minimumVersion !== 0)
98
+ throw new Error(`Unsupported ISO 21496-1 minimum_version ${minimumVersion}`);
99
+ readU16(); // writer_version
100
+ const flags = view.getUint8(pos++);
101
+ if (flags & BACKWARD_DIRECTION_MASK)
102
+ throw new Error('ISO 21496-1 metadata with HDR base image is not supported');
103
+ const channelCount = flags & IS_MULTICHANNEL_MASK ? 3 : 1;
104
+ const commonDenominator = flags & USE_COMMON_DENOMINATOR_MASK ? readU32() : undefined;
105
+ const readFraction = (signed) => {
106
+ const n = signed ? readS32() : readU32();
107
+ const d = commonDenominator ?? readU32();
108
+ if (d === 0)
109
+ throw new Error('Invalid ISO 21496-1 fraction with zero denominator');
110
+ return n / d;
111
+ };
112
+ const hdrCapacityMin = readFraction(false);
113
+ const hdrCapacityMax = readFraction(false);
114
+ // base headroom greater than alternate headroom means the base image is the HDR rendition
115
+ if (hdrCapacityMin > hdrCapacityMax)
116
+ throw new Error('ISO 21496-1 metadata with HDR base image is not supported');
117
+ const gainMapMin = [];
118
+ const gainMapMax = [];
119
+ const gamma = [];
120
+ const offsetSdr = [];
121
+ const offsetHdr = [];
122
+ for (let i = 0; i < channelCount; i++) {
123
+ gainMapMin.push(readFraction(true));
124
+ gainMapMax.push(readFraction(true));
125
+ gamma.push(readFraction(false));
126
+ offsetSdr.push(readFraction(true));
127
+ offsetHdr.push(readFraction(true));
128
+ }
129
+ const toRGB = (v) => (channelCount === 3 ? v : [v[0], v[0], v[0]]);
130
+ return {
131
+ gainMapMin: toRGB(gainMapMin),
132
+ gainMapMax: toRGB(gainMapMax),
133
+ gamma: toRGB(gamma),
134
+ offsetSdr: toRGB(offsetSdr),
135
+ offsetHdr: toRGB(offsetHdr),
136
+ hdrCapacityMin,
137
+ hdrCapacityMax
138
+ };
139
+ };
140
+
141
+ export { ISO_NAMESPACE as I, ISO_VERSION_ONLY as a, decodeISOGainMapMetadata as d, encodeISOGainMapMetadata as e };
@@ -28,11 +28,13 @@ export interface AssembleJpegOptions {
28
28
  * - APP1 (EXIF if present)
29
29
  * - APP1 (XMP with gain map metadata)
30
30
  * - APP2 (ICC profile if present)
31
+ * - APP2 (ISO 21496-1 version)
31
32
  * - APP2 (MPF data)
32
33
  * - Rest of primary JPEG data
33
34
  * 2. Secondary image (gain map):
34
35
  * - SOI
35
36
  * - APP1 (XMP with gain map parameters)
37
+ * - APP2 (ISO 21496-1 gain map parameters)
36
38
  * - Rest of gain map JPEG data
37
39
  *
38
40
  * @param options - Assembly options
@@ -1,8 +1,10 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.4.1
2
+ * @monogrid/gainmap-js v3.5.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
6
+ import { I as ISO_NAMESPACE, e as encodeISOGainMapMetadata, a as ISO_VERSION_ONLY } from './iso-gainmap-metadata-Dk2F4Eoz.js';
7
+
6
8
  /**
7
9
  * JPEG marker constants
8
10
  * Based on JPEG specification and libultrahdr implementation
@@ -398,6 +400,15 @@ function copyJpegWithoutExif(jpegData, exifPos, exifSize) {
398
400
  result.set(jpegData.subarray(exifPos + exifSize), exifPos);
399
401
  return result;
400
402
  }
403
+ /**
404
+ * Concatenate two byte arrays
405
+ */
406
+ function concat(a, b) {
407
+ const result = new Uint8Array(a.length + b.length);
408
+ result.set(a, 0);
409
+ result.set(b, a.length);
410
+ return result;
411
+ }
401
412
  /**
402
413
  * Write a JPEG marker and its data
403
414
  *
@@ -433,11 +444,13 @@ function writeMarker(buffer, pos, marker, data) {
433
444
  * - APP1 (EXIF if present)
434
445
  * - APP1 (XMP with gain map metadata)
435
446
  * - APP2 (ICC profile if present)
447
+ * - APP2 (ISO 21496-1 version)
436
448
  * - APP2 (MPF data)
437
449
  * - Rest of primary JPEG data
438
450
  * 2. Secondary image (gain map):
439
451
  * - SOI
440
452
  * - APP1 (XMP with gain map parameters)
453
+ * - APP2 (ISO 21496-1 gain map parameters)
441
454
  * - Rest of gain map JPEG data
442
455
  *
443
456
  * @param options - Assembly options
@@ -467,10 +480,17 @@ function assembleJpegWithGainMap(options) {
467
480
  // Generate XMP for secondary image
468
481
  const xmpSecondary = generateXmpForSecondaryImage(metadata);
469
482
  const xmpSecondaryBytes = new TextEncoder().encode(xmpSecondary);
470
- // Calculate secondary image size
471
- // 2 bytes SOI + 2 bytes marker + 2 bytes length field + namespace + XMP data + gain map data (without SOI)
472
483
  const namespaceBytes = new TextEncoder().encode(XMP_NAMESPACE);
473
- const secondaryImageSize = 2 + 2 + 2 + namespaceBytes.length + xmpSecondaryBytes.length + (gainMap.data.length - 2);
484
+ const xmpSecondaryData = new Uint8Array(namespaceBytes.length + xmpSecondaryBytes.length);
485
+ xmpSecondaryData.set(namespaceBytes, 0);
486
+ xmpSecondaryData.set(xmpSecondaryBytes, namespaceBytes.length);
487
+ // ISO 21496-1 metadata: version only in the primary image, full metadata in the gain map image
488
+ const isoNamespaceBytes = new TextEncoder().encode(ISO_NAMESPACE);
489
+ const isoPrimaryData = concat(isoNamespaceBytes, ISO_VERSION_ONLY);
490
+ const isoSecondaryData = concat(isoNamespaceBytes, encodeISOGainMapMetadata(metadata));
491
+ // Calculate secondary image size
492
+ // SOI + APP1 (XMP) + APP2 (ISO) + gain map data (without SOI)
493
+ const secondaryImageSize = 2 + 2 + 2 + xmpSecondaryData.length + 2 + 2 + isoSecondaryData.length + (gainMap.data.length - 2);
474
494
  // Generate XMP for primary image
475
495
  const xmpPrimary = generateXmpForPrimaryImage(secondaryImageSize, metadata);
476
496
  const xmpPrimaryBytes = new TextEncoder().encode(xmpPrimary);
@@ -486,6 +506,7 @@ function assembleJpegWithGainMap(options) {
486
506
  totalSize += 2 + 2 + xmpPrimaryData.length; // APP1 + length + XMP primary
487
507
  if (icc)
488
508
  totalSize += 2 + 2 + icc.length; // APP2 + length + ICC
509
+ totalSize += 2 + 2 + isoPrimaryData.length; // APP2 + length + ISO version
489
510
  totalSize += 2 + 2 + mpfLength; // APP2 + length + MPF
490
511
  totalSize += primaryJpegData.length - 2; // Primary JPEG without SOI
491
512
  totalSize += secondaryImageSize; // Secondary image
@@ -496,6 +517,7 @@ function assembleJpegWithGainMap(options) {
496
517
  (exifData ? 2 + 2 + exifData.length : 0) +
497
518
  2 + 2 + xmpPrimaryData.length +
498
519
  (icc ? 2 + 2 + icc.length : 0) +
520
+ 2 + 2 + isoPrimaryData.length +
499
521
  2 + 2 + 4 // APP2 marker + length + MPF signature
500
522
  );
501
523
  // Generate MPF data
@@ -516,6 +538,8 @@ function assembleJpegWithGainMap(options) {
516
538
  if (icc) {
517
539
  pos = writeMarker(output, pos, MARKERS.APP2, icc);
518
540
  }
541
+ // Write ISO 21496-1 version
542
+ pos = writeMarker(output, pos, MARKERS.APP2, isoPrimaryData);
519
543
  // Write MPF
520
544
  pos = writeMarker(output, pos, MARKERS.APP2, mpfDataActual);
521
545
  // Write rest of primary JPEG (skip SOI)
@@ -525,10 +549,9 @@ function assembleJpegWithGainMap(options) {
525
549
  // Write SOI
526
550
  pos = writeMarker(output, pos, MARKERS.SOI);
527
551
  // Write XMP for secondary image
528
- const xmpSecondaryData = new Uint8Array(namespaceBytes.length + xmpSecondaryBytes.length);
529
- xmpSecondaryData.set(namespaceBytes, 0);
530
- xmpSecondaryData.set(xmpSecondaryBytes, namespaceBytes.length);
531
552
  pos = writeMarker(output, pos, MARKERS.APP1, xmpSecondaryData);
553
+ // Write ISO 21496-1 metadata for secondary image
554
+ pos = writeMarker(output, pos, MARKERS.APP2, isoSecondaryData);
532
555
  // Write rest of gain map JPEG (skip SOI)
533
556
  output.set(gainMap.data.subarray(2), pos);
534
557
  // pos += gainMap.data.length - 2
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.4.1
2
+ * @monogrid/gainmap-js v3.5.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
- const t=216,e=225,n=226,a=218,r={SIGNATURE:new Uint8Array([77,80,70,0]),BIG_ENDIAN:new Uint8Array([77,77]),TIFF_MAGIC:42,NUM_PICTURES:2,TAG_COUNT:3,TAG_SIZE:12,MP_ENTRY_SIZE:16},s=45056,i=45057,p=45058,o=7,h=4,g=0,m=536870912,c=new Uint8Array([48,49,48,48]);function d(){return r.SIGNATURE.length+2+2+4+2+r.TAG_COUNT*r.TAG_SIZE+4+r.NUM_PICTURES*r.MP_ENTRY_SIZE}const u="Primary",f="GainMap",M="image/jpeg";function l(t){return String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function U(t,e,n,a){const r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.setUint8(e++,255),r.setUint8(e++,n),a&&a.length>0){const n=a.length+2;r.setUint16(e,n,!1),e+=2,t.set(a,e),e+=a.length}return e}function x(x){const{sdr:y,gainMap:w,metadata:T,exif:I,icc:A}=x;if("image/jpeg"!==y.mimeType)throw new Error("SDR image must be JPEG format");if("image/jpeg"!==w.mimeType)throw new Error("Gain map image must be JPEG format");const E=function(n){const r=new DataView(n.buffer,n.byteOffset,n.byteLength);if(255!==r.getUint8(0)||r.getUint8(1)!==t)return null;let s=2;const i="Exif\0\0";for(;s<n.length-1&&255===r.getUint8(s);){const t=r.getUint8(s+1);if(t===a)break;if(t===e){const t=r.getUint16(s+2,!1),e=s+4;let a=!0;for(let t=0;t<6;t++)if(e+t>=n.length||n[e+t]!==i.charCodeAt(t)){a=!1;break}if(a){const a=t-2;return{data:n.slice(e,e+a),pos:s,size:t+2}}}s+=2+r.getUint16(s+2,!1)}return null}(y.data);if(E&&I)throw new Error("Primary image already contains EXIF data, cannot add external EXIF");let C=y.data,S=I;E&&(C=function(t,e,n){const a=t.length-n,r=new Uint8Array(a);return r.set(t.subarray(0,e),0),r.set(t.subarray(e+n),e),r}(y.data,E.pos,E.size),S=E.data);const R=function(t){const e=[],n=t.hdrCapacityMin,a=t.hdrCapacityMax,r=t=>Array.isArray(t)?t.reduce((t,e)=>t+e,0)/t.length:t,s=r(t.gainMapMin),i=r(t.gainMapMax),p=r(t.gamma),o=r(t.offsetSdr),h=r(t.offsetHdr);return e.push('<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>'),e.push('<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.1.2">'),e.push(' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'),e.push(" <rdf:Description"),e.push(' xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/"'),e.push(` hdrgm:Version="${l(t.version)}"`),e.push(` hdrgm:GainMapMin="${l(s)}"`),e.push(` hdrgm:GainMapMax="${l(i)}"`),e.push(` hdrgm:Gamma="${l(p)}"`),e.push(` hdrgm:OffsetSDR="${l(o)}"`),e.push(` hdrgm:OffsetHDR="${l(h)}"`),e.push(` hdrgm:HDRCapacityMin="${l(n)}"`),e.push(` hdrgm:HDRCapacityMax="${l(a)}"`),e.push(' hdrgm:BaseRenditionIsHDR="False"'),e.push(' rdf:about=""/>'),e.push(" </rdf:RDF>"),e.push("</x:xmpmeta>"),e.push('<?xpacket end="w"?>'),e.join("\n")}(T),b=(new TextEncoder).encode(R),G=(new TextEncoder).encode("http://ns.adobe.com/xap/1.0/\0"),D=6+G.length+b.length+(w.data.length-2),N=function(t,e){const n=[];return n.push('<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>'),n.push('<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.1.2">'),n.push(' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'),n.push(" <rdf:Description"),n.push(' xmlns:Container="http://ns.google.com/photos/1.0/container/"'),n.push(' xmlns:Item="http://ns.google.com/photos/1.0/container/item/"'),n.push(' xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/"'),n.push(` hdrgm:Version="${l(e.version)}"`),n.push(' rdf:about="">'),n.push(" <Container:Directory>"),n.push(" <rdf:Seq>"),n.push(' <rdf:li rdf:parseType="Resource">'),n.push(" <Container:Item"),n.push(` Item:Semantic="${u}"`),n.push(` Item:Mime="${M}"/>`),n.push(" </rdf:li>"),n.push(' <rdf:li rdf:parseType="Resource">'),n.push(" <Container:Item"),n.push(` Item:Semantic="${f}"`),n.push(` Item:Mime="${M}"`),n.push(` Item:Length="${t}"/>`),n.push(" </rdf:li>"),n.push(" </rdf:Seq>"),n.push(" </Container:Directory>"),n.push(" </rdf:Description>"),n.push(" </rdf:RDF>"),n.push("</x:xmpmeta>"),n.push('<?xpacket end="w"?>'),n.join("\n")}(D,T),_=(new TextEncoder).encode(N),$=new Uint8Array(G.length+_.length);$.set(G,0),$.set(_,G.length);const P=d();let F=2;S&&(F+=4+S.length),F+=4+$.length,A&&(F+=4+A.length),F+=4+P,F+=C.length-2,F+=D;const k=F-D,j=function(t,e,n,a){const u=d(),f=new ArrayBuffer(u),M=new DataView(f),l=new Uint8Array(f);let U=0;l.set(r.SIGNATURE,U),U+=r.SIGNATURE.length,l.set(r.BIG_ENDIAN,U);const x=!1;U+=2,M.setUint16(U,r.TIFF_MAGIC,x),U+=2,M.setUint32(U,8,x),U+=4,M.setUint16(U,r.TAG_COUNT,x),U+=2,M.setUint16(U,s,x),U+=2,M.setUint16(U,o,x),U+=2,M.setUint32(U,c.length,x),U+=4,l.set(c,U),U+=4,M.setUint16(U,i,x),U+=2,M.setUint16(U,h,x),U+=2,M.setUint32(U,1,x),U+=4,M.setUint32(U,r.NUM_PICTURES,x),U+=4,M.setUint16(U,p,x),U+=2,M.setUint16(U,o,x),U+=2,M.setUint32(U,r.MP_ENTRY_SIZE*r.NUM_PICTURES,x),U+=4;const y=U-r.SIGNATURE.length+4+4;return M.setUint32(U,y,x),U+=4,M.setUint32(U,0,x),U+=4,M.setUint32(U,g|m,x),U+=4,M.setUint32(U,t,x),U+=4,M.setUint32(U,e,x),U+=4,M.setUint16(U,0,x),U+=2,M.setUint16(U,0,x),U+=2,M.setUint32(U,g,x),U+=4,M.setUint32(U,n,x),U+=4,M.setUint32(U,a,x),U+=4,M.setUint16(U,0,x),U+=2,M.setUint16(U,0,x),l}(k,0,D,k-(2+(S?4+S.length:0)+2+2+$.length+(A?4+A.length:0)+2+2+4)),H=new Uint8Array(F);let z=0;z=U(H,z,t),S&&(z=U(H,z,e,S)),z=U(H,z,e,$),A&&(z=U(H,z,n,A)),z=U(H,z,n,j),H.set(C.subarray(2),z),z+=C.length-2,z=U(H,z,t);const O=new Uint8Array(G.length+b.length);return O.set(G,0),O.set(b,G.length),z=U(H,z,e,O),H.set(w.data.subarray(2),z),H}const y=t=>{if("image/jpeg"!==t.sdr.mimeType)throw new Error("This function expects an SDR image compressed in jpeg");if("image/jpeg"!==t.gainMap.mimeType)throw new Error("This function expects a GainMap image compressed in jpeg");const e={version:"1.0",gainMapMin:t.gainMapMin,gainMapMax:t.gainMapMax,gamma:t.gamma,offsetSdr:t.offsetSdr,offsetHdr:t.offsetHdr,hdrCapacityMin:t.hdrCapacityMin,hdrCapacityMax:t.hdrCapacityMax,minContentBoost:Array.isArray(t.gainMapMin)?Math.pow(2,t.gainMapMin.reduce((t,e)=>t+e,0)/t.gainMapMin.length):Math.pow(2,t.gainMapMin),maxContentBoost:Array.isArray(t.gainMapMax)?Math.pow(2,t.gainMapMax.reduce((t,e)=>t+e,0)/t.gainMapMax.length):Math.pow(2,t.gainMapMax)};return x({sdr:t.sdr,gainMap:t.gainMap,metadata:e})};export{y as encodeJPEGMetadata};
5
+ import{I as t,e,a as n}from"./iso-gainmap-metadata-DNTSE4Qp.js";const a=216,r=225,s=226,i=218,p={SIGNATURE:new Uint8Array([77,80,70,0]),BIG_ENDIAN:new Uint8Array([77,77]),TIFF_MAGIC:42,NUM_PICTURES:2,TAG_COUNT:3,TAG_SIZE:12,MP_ENTRY_SIZE:16},o=45056,h=45057,g=45058,m=7,c=4,d=0,u=536870912,f=new Uint8Array([48,49,48,48]);function l(){return p.SIGNATURE.length+2+2+4+2+p.TAG_COUNT*p.TAG_SIZE+4+p.NUM_PICTURES*p.MP_ENTRY_SIZE}const M="Primary",U="GainMap",x="image/jpeg";function y(t){return String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function w(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function T(t,e,n,a){const r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.setUint8(e++,255),r.setUint8(e++,n),a&&a.length>0){const n=a.length+2;r.setUint16(e,n,!1),e+=2,t.set(a,e),e+=a.length}return e}function I(I){const{sdr:A,gainMap:E,metadata:C,exif:S,icc:R}=I;if("image/jpeg"!==A.mimeType)throw new Error("SDR image must be JPEG format");if("image/jpeg"!==E.mimeType)throw new Error("Gain map image must be JPEG format");const b=function(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(255!==e.getUint8(0)||e.getUint8(1)!==a)return null;let n=2;const s="Exif\0\0";for(;n<t.length-1&&255===e.getUint8(n);){const a=e.getUint8(n+1);if(a===i)break;if(a===r){const a=e.getUint16(n+2,!1),r=n+4;let i=!0;for(let e=0;e<6;e++)if(r+e>=t.length||t[r+e]!==s.charCodeAt(e)){i=!1;break}if(i){const e=a-2;return{data:t.slice(r,r+e),pos:n,size:a+2}}}n+=2+e.getUint16(n+2,!1)}return null}(A.data);if(b&&S)throw new Error("Primary image already contains EXIF data, cannot add external EXIF");let G=A.data,D=S;b&&(G=function(t,e,n){const a=t.length-n,r=new Uint8Array(a);return r.set(t.subarray(0,e),0),r.set(t.subarray(e+n),e),r}(A.data,b.pos,b.size),D=b.data);const N=function(t){const e=[],n=t.hdrCapacityMin,a=t.hdrCapacityMax,r=t=>Array.isArray(t)?t.reduce((t,e)=>t+e,0)/t.length:t,s=r(t.gainMapMin),i=r(t.gainMapMax),p=r(t.gamma),o=r(t.offsetSdr),h=r(t.offsetHdr);return e.push('<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>'),e.push('<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.1.2">'),e.push(' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'),e.push(" <rdf:Description"),e.push(' xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/"'),e.push(` hdrgm:Version="${y(t.version)}"`),e.push(` hdrgm:GainMapMin="${y(s)}"`),e.push(` hdrgm:GainMapMax="${y(i)}"`),e.push(` hdrgm:Gamma="${y(p)}"`),e.push(` hdrgm:OffsetSDR="${y(o)}"`),e.push(` hdrgm:OffsetHDR="${y(h)}"`),e.push(` hdrgm:HDRCapacityMin="${y(n)}"`),e.push(` hdrgm:HDRCapacityMax="${y(a)}"`),e.push(' hdrgm:BaseRenditionIsHDR="False"'),e.push(' rdf:about=""/>'),e.push(" </rdf:RDF>"),e.push("</x:xmpmeta>"),e.push('<?xpacket end="w"?>'),e.join("\n")}(C),_=(new TextEncoder).encode(N),$=(new TextEncoder).encode("http://ns.adobe.com/xap/1.0/\0"),P=new Uint8Array($.length+_.length);P.set($,0),P.set(_,$.length);const F=(new TextEncoder).encode(t),j=w(F,n),k=w(F,e(C)),H=6+P.length+2+2+k.length+(E.data.length-2),z=function(t,e){const n=[];return n.push('<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>'),n.push('<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.1.2">'),n.push(' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'),n.push(" <rdf:Description"),n.push(' xmlns:Container="http://ns.google.com/photos/1.0/container/"'),n.push(' xmlns:Item="http://ns.google.com/photos/1.0/container/item/"'),n.push(' xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/"'),n.push(` hdrgm:Version="${y(e.version)}"`),n.push(' rdf:about="">'),n.push(" <Container:Directory>"),n.push(" <rdf:Seq>"),n.push(' <rdf:li rdf:parseType="Resource">'),n.push(" <Container:Item"),n.push(` Item:Semantic="${M}"`),n.push(` Item:Mime="${x}"/>`),n.push(" </rdf:li>"),n.push(' <rdf:li rdf:parseType="Resource">'),n.push(" <Container:Item"),n.push(` Item:Semantic="${U}"`),n.push(` Item:Mime="${x}"`),n.push(` Item:Length="${t}"/>`),n.push(" </rdf:li>"),n.push(" </rdf:Seq>"),n.push(" </Container:Directory>"),n.push(" </rdf:Description>"),n.push(" </rdf:RDF>"),n.push("</x:xmpmeta>"),n.push('<?xpacket end="w"?>'),n.join("\n")}(H,C),O=(new TextEncoder).encode(z),B=new Uint8Array($.length+O.length);B.set($,0),B.set(O,$.length);const V=l();let Z=2;D&&(Z+=4+D.length),Z+=4+B.length,R&&(Z+=4+R.length),Z+=4+j.length,Z+=4+V,Z+=G.length-2,Z+=H;const X=Z-H,q=function(t,e,n,a){const r=l(),s=new ArrayBuffer(r),i=new DataView(s),M=new Uint8Array(s);let U=0;M.set(p.SIGNATURE,U),U+=p.SIGNATURE.length,M.set(p.BIG_ENDIAN,U);const x=!1;U+=2,i.setUint16(U,p.TIFF_MAGIC,x),U+=2,i.setUint32(U,8,x),U+=4,i.setUint16(U,p.TAG_COUNT,x),U+=2,i.setUint16(U,o,x),U+=2,i.setUint16(U,m,x),U+=2,i.setUint32(U,f.length,x),U+=4,M.set(f,U),U+=4,i.setUint16(U,h,x),U+=2,i.setUint16(U,c,x),U+=2,i.setUint32(U,1,x),U+=4,i.setUint32(U,p.NUM_PICTURES,x),U+=4,i.setUint16(U,g,x),U+=2,i.setUint16(U,m,x),U+=2,i.setUint32(U,p.MP_ENTRY_SIZE*p.NUM_PICTURES,x),U+=4;const y=U-p.SIGNATURE.length+4+4;return i.setUint32(U,y,x),U+=4,i.setUint32(U,0,x),U+=4,i.setUint32(U,d|u,x),U+=4,i.setUint32(U,t,x),U+=4,i.setUint32(U,e,x),U+=4,i.setUint16(U,0,x),U+=2,i.setUint16(U,0,x),U+=2,i.setUint32(U,d,x),U+=4,i.setUint32(U,n,x),U+=4,i.setUint32(U,a,x),U+=4,i.setUint16(U,0,x),U+=2,i.setUint16(U,0,x),M}(X,0,H,X-(2+(D?4+D.length:0)+2+2+B.length+(R?4+R.length:0)+2+2+j.length+2+2+4)),v=new Uint8Array(Z);let L=0;return L=T(v,L,a),D&&(L=T(v,L,r,D)),L=T(v,L,r,B),R&&(L=T(v,L,s,R)),L=T(v,L,s,j),L=T(v,L,s,q),v.set(G.subarray(2),L),L+=G.length-2,L=T(v,L,a),L=T(v,L,r,P),L=T(v,L,s,k),v.set(E.data.subarray(2),L),v}const A=t=>{if("image/jpeg"!==t.sdr.mimeType)throw new Error("This function expects an SDR image compressed in jpeg");if("image/jpeg"!==t.gainMap.mimeType)throw new Error("This function expects a GainMap image compressed in jpeg");const e={version:"1.0",gainMapMin:t.gainMapMin,gainMapMax:t.gainMapMax,gamma:t.gamma,offsetSdr:t.offsetSdr,offsetHdr:t.offsetHdr,hdrCapacityMin:t.hdrCapacityMin,hdrCapacityMax:t.hdrCapacityMax,minContentBoost:Array.isArray(t.gainMapMin)?Math.pow(2,t.gainMapMin.reduce((t,e)=>t+e,0)/t.gainMapMin.length):Math.pow(2,t.gainMapMin),maxContentBoost:Array.isArray(t.gainMapMax)?Math.pow(2,t.gainMapMax.reduce((t,e)=>t+e,0)/t.gainMapMax.length):Math.pow(2,t.gainMapMax)};return I({sdr:t.sdr,gainMap:t.gainMap,metadata:e})};export{A as encodeJPEGMetadata};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.4.1
2
+ * @monogrid/gainmap-js v3.5.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
@@ -9,6 +9,82 @@
9
9
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.libultrahdr = {}));
10
10
  })(this, (function (exports) { 'use strict';
11
11
 
12
+ /**
13
+ * ISO 21496-1 binary gain map metadata (de)serialization
14
+ * Based on libultrahdr gainmapmetadata.cpp implementation
15
+ *
16
+ * Layout (big endian):
17
+ * - u16 minimum_version, u16 writer_version
18
+ * - u8 flags (bit 7: multichannel, bit 6: use base colour space, bit 2: backward direction, bit 3: common denominator)
19
+ * - headroom: base_hdr_headroom, alternate_hdr_headroom (unsigned fractions)
20
+ * - per channel: gain_map_min (s), gain_map_max (s), gamma (u), base_offset (s), alternate_offset (s)
21
+ *
22
+ * Fractions are written as numerator + denominator, or numerator only when the common denominator flag is set.
23
+ */
24
+ /**
25
+ * Namespace identifying an ISO 21496-1 APP2 segment (null terminated)
26
+ */
27
+ const ISO_NAMESPACE = 'urn:iso:std:iso:ts:21496:-1\0';
28
+ const IS_MULTICHANNEL_MASK = 1 << 7;
29
+ const USE_BASE_COLOR_SPACE_MASK = 1 << 6;
30
+ const INT32_MAX = 0x7fffffff;
31
+ const UINT32_MAX = 0xffffffff;
32
+ /**
33
+ * Converts a float into a fraction, using the largest denominator that keeps the numerator in range
34
+ */
35
+ const toFraction = (value, signed) => {
36
+ const max = signed ? INT32_MAX : UINT32_MAX;
37
+ if (!Number.isFinite(value) || (!signed && value < 0) || Math.abs(value) > max) {
38
+ throw new Error(`Cannot represent ${value} as an ${signed ? 'signed' : 'unsigned'} ISO 21496-1 fraction`);
39
+ }
40
+ const denominator = Math.min(UINT32_MAX, Math.floor(max / Math.max(1, Math.abs(value))));
41
+ return [Math.round(value * denominator), denominator];
42
+ };
43
+ /**
44
+ * The version-only payload stored in the primary image (minimum_version = 0, writer_version = 0)
45
+ */
46
+ const ISO_VERSION_ONLY = new Uint8Array(4);
47
+ /**
48
+ * Serializes gain map metadata into an ISO 21496-1 binary payload
49
+ * (without namespace), to be stored in the gain map image.
50
+ *
51
+ * Values are already in the expected space: gainMapMin/Max and hdrCapacityMin/Max
52
+ * are log2, gamma and offsets are linear.
53
+ *
54
+ * @param metadata
55
+ * @returns
56
+ */
57
+ const encodeISOGainMapMetadata = (metadata) => {
58
+ const channels = [0, 1, 2].map(i => [metadata.gainMapMin[i], metadata.gainMapMax[i], metadata.gamma[i], metadata.offsetSdr[i], metadata.offsetHdr[i]]);
59
+ const isMultiChannel = channels.some(c => c.some((v, j) => v !== channels[0][j]));
60
+ const channelCount = isMultiChannel ? 3 : 1;
61
+ const data = new Uint8Array(5 + 16 + 40 * channelCount);
62
+ const view = new DataView(data.buffer);
63
+ let pos = 4; // minimum_version and writer_version are 0
64
+ // the gain map is computed in the base image colour space
65
+ view.setUint8(pos++, (isMultiChannel ? IS_MULTICHANNEL_MASK : 0) | USE_BASE_COLOR_SPACE_MASK);
66
+ const writeFraction = (value, signed) => {
67
+ const [n, d] = toFraction(value, signed);
68
+ if (signed)
69
+ view.setInt32(pos, n);
70
+ else
71
+ view.setUint32(pos, n);
72
+ view.setUint32(pos + 4, d);
73
+ pos += 8;
74
+ };
75
+ writeFraction(metadata.hdrCapacityMin, false);
76
+ writeFraction(metadata.hdrCapacityMax, false);
77
+ for (let i = 0; i < channelCount; i++) {
78
+ const [min, max, gamma, offsetSdr, offsetHdr] = channels[i];
79
+ writeFraction(min, true);
80
+ writeFraction(max, true);
81
+ writeFraction(gamma, false);
82
+ writeFraction(offsetSdr, true);
83
+ writeFraction(offsetHdr, true);
84
+ }
85
+ return data;
86
+ };
87
+
12
88
  /**
13
89
  * JPEG marker constants
14
90
  * Based on JPEG specification and libultrahdr implementation
@@ -404,6 +480,15 @@
404
480
  result.set(jpegData.subarray(exifPos + exifSize), exifPos);
405
481
  return result;
406
482
  }
483
+ /**
484
+ * Concatenate two byte arrays
485
+ */
486
+ function concat(a, b) {
487
+ const result = new Uint8Array(a.length + b.length);
488
+ result.set(a, 0);
489
+ result.set(b, a.length);
490
+ return result;
491
+ }
407
492
  /**
408
493
  * Write a JPEG marker and its data
409
494
  *
@@ -439,11 +524,13 @@
439
524
  * - APP1 (EXIF if present)
440
525
  * - APP1 (XMP with gain map metadata)
441
526
  * - APP2 (ICC profile if present)
527
+ * - APP2 (ISO 21496-1 version)
442
528
  * - APP2 (MPF data)
443
529
  * - Rest of primary JPEG data
444
530
  * 2. Secondary image (gain map):
445
531
  * - SOI
446
532
  * - APP1 (XMP with gain map parameters)
533
+ * - APP2 (ISO 21496-1 gain map parameters)
447
534
  * - Rest of gain map JPEG data
448
535
  *
449
536
  * @param options - Assembly options
@@ -473,10 +560,17 @@
473
560
  // Generate XMP for secondary image
474
561
  const xmpSecondary = generateXmpForSecondaryImage(metadata);
475
562
  const xmpSecondaryBytes = new TextEncoder().encode(xmpSecondary);
476
- // Calculate secondary image size
477
- // 2 bytes SOI + 2 bytes marker + 2 bytes length field + namespace + XMP data + gain map data (without SOI)
478
563
  const namespaceBytes = new TextEncoder().encode(XMP_NAMESPACE);
479
- const secondaryImageSize = 2 + 2 + 2 + namespaceBytes.length + xmpSecondaryBytes.length + (gainMap.data.length - 2);
564
+ const xmpSecondaryData = new Uint8Array(namespaceBytes.length + xmpSecondaryBytes.length);
565
+ xmpSecondaryData.set(namespaceBytes, 0);
566
+ xmpSecondaryData.set(xmpSecondaryBytes, namespaceBytes.length);
567
+ // ISO 21496-1 metadata: version only in the primary image, full metadata in the gain map image
568
+ const isoNamespaceBytes = new TextEncoder().encode(ISO_NAMESPACE);
569
+ const isoPrimaryData = concat(isoNamespaceBytes, ISO_VERSION_ONLY);
570
+ const isoSecondaryData = concat(isoNamespaceBytes, encodeISOGainMapMetadata(metadata));
571
+ // Calculate secondary image size
572
+ // SOI + APP1 (XMP) + APP2 (ISO) + gain map data (without SOI)
573
+ const secondaryImageSize = 2 + 2 + 2 + xmpSecondaryData.length + 2 + 2 + isoSecondaryData.length + (gainMap.data.length - 2);
480
574
  // Generate XMP for primary image
481
575
  const xmpPrimary = generateXmpForPrimaryImage(secondaryImageSize, metadata);
482
576
  const xmpPrimaryBytes = new TextEncoder().encode(xmpPrimary);
@@ -492,6 +586,7 @@
492
586
  totalSize += 2 + 2 + xmpPrimaryData.length; // APP1 + length + XMP primary
493
587
  if (icc)
494
588
  totalSize += 2 + 2 + icc.length; // APP2 + length + ICC
589
+ totalSize += 2 + 2 + isoPrimaryData.length; // APP2 + length + ISO version
495
590
  totalSize += 2 + 2 + mpfLength; // APP2 + length + MPF
496
591
  totalSize += primaryJpegData.length - 2; // Primary JPEG without SOI
497
592
  totalSize += secondaryImageSize; // Secondary image
@@ -502,6 +597,7 @@
502
597
  (exifData ? 2 + 2 + exifData.length : 0) +
503
598
  2 + 2 + xmpPrimaryData.length +
504
599
  (icc ? 2 + 2 + icc.length : 0) +
600
+ 2 + 2 + isoPrimaryData.length +
505
601
  2 + 2 + 4 // APP2 marker + length + MPF signature
506
602
  );
507
603
  // Generate MPF data
@@ -522,6 +618,8 @@
522
618
  if (icc) {
523
619
  pos = writeMarker(output, pos, MARKERS.APP2, icc);
524
620
  }
621
+ // Write ISO 21496-1 version
622
+ pos = writeMarker(output, pos, MARKERS.APP2, isoPrimaryData);
525
623
  // Write MPF
526
624
  pos = writeMarker(output, pos, MARKERS.APP2, mpfDataActual);
527
625
  // Write rest of primary JPEG (skip SOI)
@@ -531,10 +629,9 @@
531
629
  // Write SOI
532
630
  pos = writeMarker(output, pos, MARKERS.SOI);
533
631
  // Write XMP for secondary image
534
- const xmpSecondaryData = new Uint8Array(namespaceBytes.length + xmpSecondaryBytes.length);
535
- xmpSecondaryData.set(namespaceBytes, 0);
536
- xmpSecondaryData.set(xmpSecondaryBytes, namespaceBytes.length);
537
632
  pos = writeMarker(output, pos, MARKERS.APP1, xmpSecondaryData);
633
+ // Write ISO 21496-1 metadata for secondary image
634
+ pos = writeMarker(output, pos, MARKERS.APP2, isoSecondaryData);
538
635
  // Write rest of gain map JPEG (skip SOI)
539
636
  output.set(gainMap.data.subarray(2), pos);
540
637
  // pos += gainMap.data.length - 2
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.4.1
2
+ * @monogrid/gainmap-js v3.5.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).libultrahdr={})}(this,function(t){"use strict";const e=216,n=225,a=226,r=218,i={SIGNATURE:new Uint8Array([77,80,70,0]),BIG_ENDIAN:new Uint8Array([77,77]),TIFF_MAGIC:42,NUM_PICTURES:2,TAG_COUNT:3,TAG_SIZE:12,MP_ENTRY_SIZE:16},s=45056,p=45057,o=45058,h=7,g=4,d=0,u=536870912,c=new Uint8Array([48,49,48,48]);function m(){return i.SIGNATURE.length+2+2+4+2+i.TAG_COUNT*i.TAG_SIZE+4+i.NUM_PICTURES*i.MP_ENTRY_SIZE}const f="Primary",l="GainMap",M="image/jpeg";function U(t){return String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function x(t,e,n,a){const r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.setUint8(e++,255),r.setUint8(e++,n),a&&a.length>0){const n=a.length+2;r.setUint16(e,n,!1),e+=2,t.set(a,e),e+=a.length}return e}function y(t){const{sdr:y,gainMap:w,metadata:T,exif:E,icc:I}=t;if("image/jpeg"!==y.mimeType)throw new Error("SDR image must be JPEG format");if("image/jpeg"!==w.mimeType)throw new Error("Gain map image must be JPEG format");const A=function(t){const a=new DataView(t.buffer,t.byteOffset,t.byteLength);if(255!==a.getUint8(0)||a.getUint8(1)!==e)return null;let i=2;const s="Exif\0\0";for(;i<t.length-1&&255===a.getUint8(i);){const e=a.getUint8(i+1);if(e===r)break;if(e===n){const e=a.getUint16(i+2,!1),n=i+4;let r=!0;for(let e=0;e<6;e++)if(n+e>=t.length||t[n+e]!==s.charCodeAt(e)){r=!1;break}if(r){const a=e-2;return{data:t.slice(n,n+a),pos:i,size:e+2}}}i+=2+a.getUint16(i+2,!1)}return null}(y.data);if(A&&E)throw new Error("Primary image already contains EXIF data, cannot add external EXIF");let b=y.data,C=E;A&&(b=function(t,e,n){const a=t.length-n,r=new Uint8Array(a);return r.set(t.subarray(0,e),0),r.set(t.subarray(e+n),e),r}(y.data,A.pos,A.size),C=A.data);const S=function(t){const e=[],n=t.hdrCapacityMin,a=t.hdrCapacityMax,r=t=>Array.isArray(t)?t.reduce((t,e)=>t+e,0)/t.length:t,i=r(t.gainMapMin),s=r(t.gainMapMax),p=r(t.gamma),o=r(t.offsetSdr),h=r(t.offsetHdr);return e.push('<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>'),e.push('<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.1.2">'),e.push(' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'),e.push(" <rdf:Description"),e.push(' xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/"'),e.push(` hdrgm:Version="${U(t.version)}"`),e.push(` hdrgm:GainMapMin="${U(i)}"`),e.push(` hdrgm:GainMapMax="${U(s)}"`),e.push(` hdrgm:Gamma="${U(p)}"`),e.push(` hdrgm:OffsetSDR="${U(o)}"`),e.push(` hdrgm:OffsetHDR="${U(h)}"`),e.push(` hdrgm:HDRCapacityMin="${U(n)}"`),e.push(` hdrgm:HDRCapacityMax="${U(a)}"`),e.push(' hdrgm:BaseRenditionIsHDR="False"'),e.push(' rdf:about=""/>'),e.push(" </rdf:RDF>"),e.push("</x:xmpmeta>"),e.push('<?xpacket end="w"?>'),e.join("\n")}(T),R=(new TextEncoder).encode(S),G=(new TextEncoder).encode("http://ns.adobe.com/xap/1.0/\0"),D=6+G.length+R.length+(w.data.length-2),N=function(t,e){const n=[];return n.push('<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>'),n.push('<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.1.2">'),n.push(' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'),n.push(" <rdf:Description"),n.push(' xmlns:Container="http://ns.google.com/photos/1.0/container/"'),n.push(' xmlns:Item="http://ns.google.com/photos/1.0/container/item/"'),n.push(' xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/"'),n.push(` hdrgm:Version="${U(e.version)}"`),n.push(' rdf:about="">'),n.push(" <Container:Directory>"),n.push(" <rdf:Seq>"),n.push(' <rdf:li rdf:parseType="Resource">'),n.push(" <Container:Item"),n.push(` Item:Semantic="${f}"`),n.push(` Item:Mime="${M}"/>`),n.push(" </rdf:li>"),n.push(' <rdf:li rdf:parseType="Resource">'),n.push(" <Container:Item"),n.push(` Item:Semantic="${l}"`),n.push(` Item:Mime="${M}"`),n.push(` Item:Length="${t}"/>`),n.push(" </rdf:li>"),n.push(" </rdf:Seq>"),n.push(" </Container:Directory>"),n.push(" </rdf:Description>"),n.push(" </rdf:RDF>"),n.push("</x:xmpmeta>"),n.push('<?xpacket end="w"?>'),n.join("\n")}(D,T),_=(new TextEncoder).encode(N),P=new Uint8Array(G.length+_.length);P.set(G,0),P.set(_,G.length);const $=m();let F=2;C&&(F+=4+C.length),F+=4+P.length,I&&(F+=4+I.length),F+=4+$,F+=b.length-2,F+=D;const j=F-D,k=function(t,e,n,a){const r=m(),f=new ArrayBuffer(r),l=new DataView(f),M=new Uint8Array(f);let U=0;M.set(i.SIGNATURE,U),U+=i.SIGNATURE.length,M.set(i.BIG_ENDIAN,U);const x=!1;U+=2,l.setUint16(U,i.TIFF_MAGIC,x),U+=2,l.setUint32(U,8,x),U+=4,l.setUint16(U,i.TAG_COUNT,x),U+=2,l.setUint16(U,s,x),U+=2,l.setUint16(U,h,x),U+=2,l.setUint32(U,c.length,x),U+=4,M.set(c,U),U+=4,l.setUint16(U,p,x),U+=2,l.setUint16(U,g,x),U+=2,l.setUint32(U,1,x),U+=4,l.setUint32(U,i.NUM_PICTURES,x),U+=4,l.setUint16(U,o,x),U+=2,l.setUint16(U,h,x),U+=2,l.setUint32(U,i.MP_ENTRY_SIZE*i.NUM_PICTURES,x),U+=4;const y=U-i.SIGNATURE.length+4+4;return l.setUint32(U,y,x),U+=4,l.setUint32(U,0,x),U+=4,l.setUint32(U,d|u,x),U+=4,l.setUint32(U,t,x),U+=4,l.setUint32(U,e,x),U+=4,l.setUint16(U,0,x),U+=2,l.setUint16(U,0,x),U+=2,l.setUint32(U,d,x),U+=4,l.setUint32(U,n,x),U+=4,l.setUint32(U,a,x),U+=4,l.setUint16(U,0,x),U+=2,l.setUint16(U,0,x),M}(j,0,D,j-(2+(C?4+C.length:0)+2+2+P.length+(I?4+I.length:0)+2+2+4)),H=new Uint8Array(F);let z=0;z=x(H,z,e),C&&(z=x(H,z,n,C)),z=x(H,z,n,P),I&&(z=x(H,z,a,I)),z=x(H,z,a,k),H.set(b.subarray(2),z),z+=b.length-2,z=x(H,z,e);const O=new Uint8Array(G.length+R.length);return O.set(G,0),O.set(R,G.length),z=x(H,z,n,O),H.set(w.data.subarray(2),z),H}t.encodeJPEGMetadata=t=>{if("image/jpeg"!==t.sdr.mimeType)throw new Error("This function expects an SDR image compressed in jpeg");if("image/jpeg"!==t.gainMap.mimeType)throw new Error("This function expects a GainMap image compressed in jpeg");const e={version:"1.0",gainMapMin:t.gainMapMin,gainMapMax:t.gainMapMax,gamma:t.gamma,offsetSdr:t.offsetSdr,offsetHdr:t.offsetHdr,hdrCapacityMin:t.hdrCapacityMin,hdrCapacityMax:t.hdrCapacityMax,minContentBoost:Array.isArray(t.gainMapMin)?Math.pow(2,t.gainMapMin.reduce((t,e)=>t+e,0)/t.gainMapMin.length):Math.pow(2,t.gainMapMin),maxContentBoost:Array.isArray(t.gainMapMax)?Math.pow(2,t.gainMapMax.reduce((t,e)=>t+e,0)/t.gainMapMax.length):Math.pow(2,t.gainMapMax)};return y({sdr:t.sdr,gainMap:t.gainMap,metadata:e})}});
5
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).libultrahdr={})}(this,function(t){"use strict";const e=4294967295,n=new Uint8Array(4),a=t=>{const n=[0,1,2].map(e=>[t.gainMapMin[e],t.gainMapMax[e],t.gamma[e],t.offsetSdr[e],t.offsetHdr[e]]),a=n.some(t=>t.some((t,e)=>t!==n[0][e])),r=a?3:1,s=new Uint8Array(21+40*r),i=new DataView(s.buffer);let o=4;i.setUint8(o++,64|(a?128:0));const p=(t,n)=>{const[a,r]=((t,n)=>{const a=n?2147483647:e;if(!Number.isFinite(t)||!n&&t<0||Math.abs(t)>a)throw new Error(`Cannot represent ${t} as an ${n?"signed":"unsigned"} ISO 21496-1 fraction`);const r=Math.min(e,Math.floor(a/Math.max(1,Math.abs(t))));return[Math.round(t*r),r]})(t,n);n?i.setInt32(o,a):i.setUint32(o,a),i.setUint32(o+4,r),o+=8};p(t.hdrCapacityMin,!1),p(t.hdrCapacityMax,!1);for(let t=0;t<r;t++){const[e,a,r,s,i]=n[t];p(e,!0),p(a,!0),p(r,!1),p(s,!0),p(i,!0)}return s},r=216,s=225,i=226,o=218,p={SIGNATURE:new Uint8Array([77,80,70,0]),BIG_ENDIAN:new Uint8Array([77,77]),TIFF_MAGIC:42,NUM_PICTURES:2,TAG_COUNT:3,TAG_SIZE:12,MP_ENTRY_SIZE:16},h=45056,g=45057,d=45058,c=7,u=4,m=0,f=536870912,l=new Uint8Array([48,49,48,48]);function M(){return p.SIGNATURE.length+2+2+4+2+p.TAG_COUNT*p.TAG_SIZE+4+p.NUM_PICTURES*p.MP_ENTRY_SIZE}const U="Primary",x="GainMap",y="image/jpeg";function w(t){return String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function T(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function A(t,e,n,a){const r=new DataView(t.buffer,t.byteOffset,t.byteLength);if(r.setUint8(e++,255),r.setUint8(e++,n),a&&a.length>0){const n=a.length+2;r.setUint16(e,n,!1),e+=2,t.set(a,e),e+=a.length}return e}function E(t){const{sdr:e,gainMap:E,metadata:I,exif:b,icc:C}=t;if("image/jpeg"!==e.mimeType)throw new Error("SDR image must be JPEG format");if("image/jpeg"!==E.mimeType)throw new Error("Gain map image must be JPEG format");const S=function(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(255!==e.getUint8(0)||e.getUint8(1)!==r)return null;let n=2;const a="Exif\0\0";for(;n<t.length-1&&255===e.getUint8(n);){const r=e.getUint8(n+1);if(r===o)break;if(r===s){const r=e.getUint16(n+2,!1),s=n+4;let i=!0;for(let e=0;e<6;e++)if(s+e>=t.length||t[s+e]!==a.charCodeAt(e)){i=!1;break}if(i){const e=r-2;return{data:t.slice(s,s+e),pos:n,size:r+2}}}n+=2+e.getUint16(n+2,!1)}return null}(e.data);if(S&&b)throw new Error("Primary image already contains EXIF data, cannot add external EXIF");let R=e.data,G=b;S&&(R=function(t,e,n){const a=t.length-n,r=new Uint8Array(a);return r.set(t.subarray(0,e),0),r.set(t.subarray(e+n),e),r}(e.data,S.pos,S.size),G=S.data);const D=function(t){const e=[],n=t.hdrCapacityMin,a=t.hdrCapacityMax,r=t=>Array.isArray(t)?t.reduce((t,e)=>t+e,0)/t.length:t,s=r(t.gainMapMin),i=r(t.gainMapMax),o=r(t.gamma),p=r(t.offsetSdr),h=r(t.offsetHdr);return e.push('<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>'),e.push('<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.1.2">'),e.push(' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'),e.push(" <rdf:Description"),e.push(' xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/"'),e.push(` hdrgm:Version="${w(t.version)}"`),e.push(` hdrgm:GainMapMin="${w(s)}"`),e.push(` hdrgm:GainMapMax="${w(i)}"`),e.push(` hdrgm:Gamma="${w(o)}"`),e.push(` hdrgm:OffsetSDR="${w(p)}"`),e.push(` hdrgm:OffsetHDR="${w(h)}"`),e.push(` hdrgm:HDRCapacityMin="${w(n)}"`),e.push(` hdrgm:HDRCapacityMax="${w(a)}"`),e.push(' hdrgm:BaseRenditionIsHDR="False"'),e.push(' rdf:about=""/>'),e.push(" </rdf:RDF>"),e.push("</x:xmpmeta>"),e.push('<?xpacket end="w"?>'),e.join("\n")}(I),N=(new TextEncoder).encode(D),_=(new TextEncoder).encode("http://ns.adobe.com/xap/1.0/\0"),$=new Uint8Array(_.length+N.length);$.set(_,0),$.set(N,_.length);const P=(new TextEncoder).encode("urn:iso:std:iso:ts:21496:-1\0"),F=T(P,n),j=T(P,a(I)),k=6+$.length+2+2+j.length+(E.data.length-2),H=function(t,e){const n=[];return n.push('<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>'),n.push('<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.1.2">'),n.push(' <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">'),n.push(" <rdf:Description"),n.push(' xmlns:Container="http://ns.google.com/photos/1.0/container/"'),n.push(' xmlns:Item="http://ns.google.com/photos/1.0/container/item/"'),n.push(' xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/"'),n.push(` hdrgm:Version="${w(e.version)}"`),n.push(' rdf:about="">'),n.push(" <Container:Directory>"),n.push(" <rdf:Seq>"),n.push(' <rdf:li rdf:parseType="Resource">'),n.push(" <Container:Item"),n.push(` Item:Semantic="${U}"`),n.push(` Item:Mime="${y}"/>`),n.push(" </rdf:li>"),n.push(' <rdf:li rdf:parseType="Resource">'),n.push(" <Container:Item"),n.push(` Item:Semantic="${x}"`),n.push(` Item:Mime="${y}"`),n.push(` Item:Length="${t}"/>`),n.push(" </rdf:li>"),n.push(" </rdf:Seq>"),n.push(" </Container:Directory>"),n.push(" </rdf:Description>"),n.push(" </rdf:RDF>"),n.push("</x:xmpmeta>"),n.push('<?xpacket end="w"?>'),n.join("\n")}(k,I),z=(new TextEncoder).encode(H),O=new Uint8Array(_.length+z.length);O.set(_,0),O.set(z,_.length);const B=M();let V=2;G&&(V+=4+G.length),V+=4+O.length,C&&(V+=4+C.length),V+=4+F.length,V+=4+B,V+=R.length-2,V+=k;const Z=V-k,X=function(t,e,n,a){const r=M(),s=new ArrayBuffer(r),i=new DataView(s),o=new Uint8Array(s);let U=0;o.set(p.SIGNATURE,U),U+=p.SIGNATURE.length,o.set(p.BIG_ENDIAN,U);const x=!1;U+=2,i.setUint16(U,p.TIFF_MAGIC,x),U+=2,i.setUint32(U,8,x),U+=4,i.setUint16(U,p.TAG_COUNT,x),U+=2,i.setUint16(U,h,x),U+=2,i.setUint16(U,c,x),U+=2,i.setUint32(U,l.length,x),U+=4,o.set(l,U),U+=4,i.setUint16(U,g,x),U+=2,i.setUint16(U,u,x),U+=2,i.setUint32(U,1,x),U+=4,i.setUint32(U,p.NUM_PICTURES,x),U+=4,i.setUint16(U,d,x),U+=2,i.setUint16(U,c,x),U+=2,i.setUint32(U,p.MP_ENTRY_SIZE*p.NUM_PICTURES,x),U+=4;const y=U-p.SIGNATURE.length+4+4;return i.setUint32(U,y,x),U+=4,i.setUint32(U,0,x),U+=4,i.setUint32(U,m|f,x),U+=4,i.setUint32(U,t,x),U+=4,i.setUint32(U,e,x),U+=4,i.setUint16(U,0,x),U+=2,i.setUint16(U,0,x),U+=2,i.setUint32(U,m,x),U+=4,i.setUint32(U,n,x),U+=4,i.setUint32(U,a,x),U+=4,i.setUint16(U,0,x),U+=2,i.setUint16(U,0,x),o}(Z,0,k,Z-(2+(G?4+G.length:0)+2+2+O.length+(C?4+C.length:0)+2+2+F.length+2+2+4)),q=new Uint8Array(V);let v=0;return v=A(q,v,r),G&&(v=A(q,v,s,G)),v=A(q,v,s,O),C&&(v=A(q,v,i,C)),v=A(q,v,i,F),v=A(q,v,i,X),q.set(R.subarray(2),v),v+=R.length-2,v=A(q,v,r),v=A(q,v,s,$),v=A(q,v,i,j),q.set(E.data.subarray(2),v),q}t.encodeJPEGMetadata=t=>{if("image/jpeg"!==t.sdr.mimeType)throw new Error("This function expects an SDR image compressed in jpeg");if("image/jpeg"!==t.gainMap.mimeType)throw new Error("This function expects a GainMap image compressed in jpeg");const e={version:"1.0",gainMapMin:t.gainMapMin,gainMapMax:t.gainMapMax,gamma:t.gamma,offsetSdr:t.offsetSdr,offsetHdr:t.offsetHdr,hdrCapacityMin:t.hdrCapacityMin,hdrCapacityMax:t.hdrCapacityMax,minContentBoost:Array.isArray(t.gainMapMin)?Math.pow(2,t.gainMapMin.reduce((t,e)=>t+e,0)/t.gainMapMin.length):Math.pow(2,t.gainMapMin),maxContentBoost:Array.isArray(t.gainMapMax)?Math.pow(2,t.gainMapMax.reduce((t,e)=>t+e,0)/t.gainMapMax.length):Math.pow(2,t.gainMapMax)};return E({sdr:t.sdr,gainMap:t.gainMap,metadata:e})}});