@monogrid/gainmap-js 3.4.0 → 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.
- package/CHANGELOG.md +14 -0
- package/context7.json +4 -0
- package/dist/Loader-BdKdEGSJ.js +5 -0
- package/dist/{Loader-DLI-_JDP.js → Loader-CL7itwBq.js} +46 -6
- package/dist/{QuadRenderer-BoQMkXLf.js → QuadRenderer-DIHDdKl6.js} +1 -1
- package/dist/{QuadRenderer-Bj1xl_EK.js → QuadRenderer-DPiEee1I.js} +1 -1
- package/dist/{_commonjsHelpers-CDmClQiF.js → _commonjsHelpers-DVRbpukU.js} +1 -1
- package/dist/{_commonjsHelpers-v3qvwW2J.js → _commonjsHelpers-S7tZmPW-.js} +1 -1
- package/dist/{compress-DY-CSunh.js → compress-5gFn7Y4a.js} +1 -1
- package/dist/{compress-C-X439Jm.js → compress-CTBeaiI1.js} +1 -1
- package/dist/core/get-data-texture.d.ts +2 -5
- package/dist/core/iso-gainmap-metadata.d.ts +40 -0
- package/dist/decode/shared/extract.d.ts +5 -3
- package/dist/decode/shared/index.d.ts +1 -0
- package/dist/decode/shared/utils/extractISO.d.ts +15 -0
- package/dist/decode.js +5 -4
- package/dist/decode.min.js +2 -2
- package/dist/decode.umd.cjs +122 -5
- package/dist/decode.umd.min.cjs +2 -2
- package/dist/decode.webgpu.js +21 -24
- package/dist/decode.webgpu.min.js +2 -2
- package/dist/decode.webgpu.umd.cjs +137 -24
- package/dist/decode.webgpu.umd.min.cjs +2 -2
- package/dist/encode/find-texture-min-max.d.ts +2 -5
- package/dist/encode/types.d.ts +3 -6
- package/dist/encode.js +30 -8
- package/dist/encode.min.js +2 -2
- package/dist/encode.umd.cjs +27 -5
- package/dist/encode.umd.min.cjs +2 -2
- package/dist/iso-gainmap-metadata-DNTSE4Qp.js +5 -0
- package/dist/iso-gainmap-metadata-Dk2F4Eoz.js +141 -0
- package/dist/libultrahdr/jpeg-assembler.d.ts +2 -0
- package/dist/libultrahdr.js +30 -7
- package/dist/libultrahdr.min.js +2 -2
- package/dist/libultrahdr.umd.cjs +104 -7
- package/dist/libultrahdr.umd.min.cjs +2 -2
- package/dist/third-party.txt +69 -69
- package/dist/worker-interface.js +2 -2
- package/dist/worker-interface.min.js +2 -2
- package/dist/worker-interface.umd.cjs +1 -1
- package/dist/worker-interface.umd.min.cjs +1 -1
- package/dist/worker.js +3 -3
- package/dist/worker.min.js +2 -2
- package/dist/worker.umd.cjs +1 -1
- package/dist/worker.umd.min.cjs +1 -1
- package/package.json +7 -3
- package/dist/Loader-CKVwvejH.js +0 -5
package/dist/encode.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.
|
|
2
|
+
* @monogrid/gainmap-js v3.5.0
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
|
-
import{c as n}from"./compress-DY-CSunh.js";import{DataTexture as e,RGBAFormat as t,UVMapping as o,RepeatWrapping as r,LinearFilter as a,LinearSRGBColorSpace as i,ShaderMaterial as s,NoBlending as c,Vector3 as m,UnsignedByteType as l,ACESFilmicToneMapping as p,LinearToneMapping as d,NeutralToneMapping as u,AgXToneMapping as g,CineonToneMapping as f,ReinhardToneMapping as h,SRGBColorSpace as v,AlphaFormat as M,RGBFormat as x,DepthFormat as _,DepthStencilFormat as C,RedFormat as A,RedIntegerFormat as w,RGFormat as T,RGIntegerFormat as E,RGBIntegerFormat as y,RGBAIntegerFormat as I,Vector2 as S,WebGLRenderTarget as N,ClampToEdgeWrapping as R,NearestFilter as L,DataUtils as O,FloatType as b}from"three";import{Q as U}from"./QuadRenderer-BoQMkXLf.js";const P=n=>{let s;if(n instanceof e){if(!(n.image.data instanceof Uint16Array||n.image.data instanceof Float32Array))throw new Error("Provided image is not HDR");s=n}else s=new e(n.data,n.width,n.height,"format"in n?n.format:t,n.type,o,r,r,a,a,1,"colorSpace"in n&&"srgb"===n.colorSpace?n.colorSpace:i),"header"in n&&"gamma"in n&&(s.flipY=!0),s.needsUpdate=!0;return s};class D extends s{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:n,hdr:e,offsetSdr:t,offsetHdr:o,maxContentBoost:r,minContentBoost:a,gamma:i}){if(!r)throw new Error("maxContentBoost is required");if(!n)throw new Error("sdr is required");if(!e)throw new Error("hdr is required");const s=i||[1,1,1],l=t||[1/64,1/64,1/64],p=o||[1/64,1/64,1/64],d=a||1,u=Math.max(r,1.0001);super({name:"GainMapEncoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform sampler2D sdr;\nuniform sampler2D hdr;\nuniform vec3 gamma;\nuniform vec3 offsetSdr;\nuniform vec3 offsetHdr;\nuniform float minLog2;\nuniform float maxLog2;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 sdrColor = texture2D(sdr, vUv).rgb;\n vec3 hdrColor = texture2D(hdr, vUv).rgb;\n\n vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);\n vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);\n vec3 clampedRecovery = saturate(logRecovery);\n gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);\n}\n",uniforms:{sdr:{value:n},hdr:{value:e},gamma:{value:(new m).fromArray(s)},offsetSdr:{value:(new m).fromArray(l)},offsetHdr:{value:(new m).fromArray(p)},minLog2:{value:Math.log2(d)},maxLog2:{value:Math.log2(u)}},blending:c,depthTest:!1,depthWrite:!1}),this._minContentBoost=d,this._maxContentBoost=u,this._offsetSdr=l,this._offsetHdr=p,this._gamma=s,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(n){this._gamma=n,this.uniforms.gamma.value=(new m).fromArray(n)}get offsetHdr(){return this._offsetHdr}set offsetHdr(n){this._offsetHdr=n,this.uniforms.offsetHdr.value=(new m).fromArray(n)}get offsetSdr(){return this._offsetSdr}set offsetSdr(n){this._offsetSdr=n,this.uniforms.offsetSdr.value=(new m).fromArray(n)}get minContentBoost(){return this._minContentBoost}set minContentBoost(n){this._minContentBoost=n,this.uniforms.minLog2.value=Math.log2(n)}get maxContentBoost(){return this._maxContentBoost}set maxContentBoost(n){this._maxContentBoost=n,this.uniforms.maxLog2.value=Math.log2(n)}get gainMapMin(){return[Math.log2(this._minContentBoost),Math.log2(this._minContentBoost),Math.log2(this._minContentBoost)]}get gainMapMax(){return[Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost)]}get hdrCapacityMin(){return Math.min(Math.max(0,this.gainMapMin[0]),Math.max(0,this.gainMapMin[1]),Math.max(0,this.gainMapMin[2]))}get hdrCapacityMax(){return Math.max(Math.max(0,this.gainMapMax[0]),Math.max(0,this.gainMapMax[1]),Math.max(0,this.gainMapMax[2]))}}const B=n=>{const{image:e,sdr:t,renderer:o}=n,r=P(e),a=new D({...n,sdr:t.renderTarget.texture,hdr:r}),s=new U({width:r.image.width,height:r.image.height,type:l,colorSpace:i,material:a,renderer:o,renderTargetOptions:n.renderTargetOptions});try{s.render()}catch(n){throw s.disposeOnDemandRenderer(),n}return s};class F extends s{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:n,toneMapping:e}){super({name:"SDRMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform sampler2D map;\nuniform float brightness;\nuniform float contrast;\nuniform float saturation;\nuniform float exposure;\n\nvarying vec2 vUv;\n\nmat4 brightnessMatrix( float brightness ) {\n return mat4(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n brightness, brightness, brightness, 1\n );\n}\n\nmat4 contrastMatrix( float contrast ) {\n float t = ( 1.0 - contrast ) / 2.0;\n return mat4(\n contrast, 0, 0, 0,\n 0, contrast, 0, 0,\n 0, 0, contrast, 0,\n t, t, t, 1\n );\n}\n\nmat4 saturationMatrix( float saturation ) {\n vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );\n float oneMinusSat = 1.0 - saturation;\n vec3 red = vec3( luminance.x * oneMinusSat );\n red+= vec3( saturation, 0, 0 );\n vec3 green = vec3( luminance.y * oneMinusSat );\n green += vec3( 0, saturation, 0 );\n vec3 blue = vec3( luminance.z * oneMinusSat );\n blue += vec3( 0, 0, saturation );\n return mat4(\n red, 0,\n green, 0,\n blue, 0,\n 0, 0, 0, 1\n );\n}\n\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n // ODT_SAT => XYZ => D60_2_D65 => sRGB\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color = ACESInputMat * color;\n // Apply RRT and ODT\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n // Clamp to [0, 1]\n return saturate( color );\n}\n\n// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf\nvec3 ReinhardToneMapping( vec3 color ) {\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 CineonToneMapping( vec3 color ) {\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n\n// nothing\nvec3 LinearToneMapping ( vec3 color ) {\n return color;\n}\n\n// Matrices for rec 2020 <> rec 709 color space conversion\n// matrix provided in row-major order so it has been transposed\n// https://www.itu.int/pub/R-REP-BT.2407-2017\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\n\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\n\n// https://iolite-engine.com/blog_posts/minimal_agx_implementation\n// Mean error^2: 3.6705141e-06\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\n\n// AgX Tone Mapping implementation based on Filament, which in turn is based\n// on Blender's implementation using rec 2020 primaries\n// https://github.com/google/filament/pull/7236\n// Inputs and outputs are encoded as Linear-sRGB.\n\nvec3 AgXToneMapping( vec3 color ) {\n\n // AgX constants\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n\n // explicit AgXOutsetMatrix generated from Filaments AgXOutsetMatrixInv\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n\n // LOG2_MIN = -10.0\n // LOG2_MAX = +6.5\n // MIDDLE_GRAY = 0.18\n const float AgxMinEv = - 12.47393; // log2( pow( 2, LOG2_MIN ) * MIDDLE_GRAY )\n const float AgxMaxEv = 4.026069; // log2( pow( 2, LOG2_MAX ) * MIDDLE_GRAY )\n\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\n color = AgXInsetMatrix * color;\n\n // Log2 encoding\n color = max( color, 1e-10 ); // avoid 0 or negative numbers for log2\n color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\n color = clamp( color, 0.0, 1.0 );\n\n // Apply sigmoid\n color = agxDefaultContrastApprox( color );\n\n // Apply AgX look\n // v = agxLook(v, look);\n\n color = AgXOutsetMatrix * color;\n\n // Linearize\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\n // Gamut mapping. Simple clamp for now.\n color = clamp( color, 0.0, 1.0 );\n\n return color;\n\n}\n\n// https://modelviewer.dev/examples/tone-mapping\n\nvec3 NeutralToneMapping( vec3 color ) {\n\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n\n float x = min( color.r, min( color.g, color.b ) );\n\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\n color -= offset;\n\n float peak = max( color.r, max( color.g, color.b ) );\n\n if ( peak < StartCompression ) return color;\n\n float d = 1. - StartCompression;\n\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n\n color *= newPeak / peak;\n\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\n return mix( color, vec3( newPeak ), g );\n\n}\n\n\n\nvoid main() {\n vec4 color = texture2D(map, vUv);\n\n vec4 exposed = vec4(exposure * color.rgb, color.a);\n\n vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);\n\n vec4 adjusted =\n brightnessMatrix( brightness ) *\n contrastMatrix( contrast ) *\n saturationMatrix( saturation ) *\n tonemapped;\n\n gl_FragColor = adjusted;\n}\n",uniforms:{map:{value:n},brightness:{value:0},contrast:{value:1},saturation:{value:1},exposure:{value:1}},blending:c,depthTest:!1,depthWrite:!1}),this._map=n,this.toneMapping=this._toneMapping=e||p,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(n){let e=!1;switch(n){case p:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",e=!0;break;case h:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",e=!0;break;case f:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",e=!0;break;case d:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",e=!0;break;case g:this.defines.TONEMAPPING_FUNCTION="AgXToneMapping",e=!0;break;case u:this.defines.TONEMAPPING_FUNCTION="NeutralToneMapping",e=!0;break;default:console.error(`Unsupported toneMapping: ${n}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=d}e&&(this._toneMapping=n),this.needsUpdate=!0}get brightness(){return this._brightness}set brightness(n){this._brightness=n,this.uniforms.brightness.value=n}get contrast(){return this._contrast}set contrast(n){this._contrast=n,this.uniforms.contrast.value=n}get saturation(){return this._saturation}set saturation(n){this._saturation=n,this.uniforms.saturation.value=n}get exposure(){return this._exposure}set exposure(n){this._exposure=n,this.uniforms.exposure.value=n}get map(){return this._map}set map(n){this._map=n,this.uniforms.map.value=n}}const G=(n,e,t,o)=>{n.needsUpdate=!0;const r=new U({width:n.image.width,height:n.image.height,type:l,colorSpace:v,material:new F({map:n,toneMapping:t}),renderer:e,renderTargetOptions:o});try{r.render()}catch(n){throw r.disposeOnDemandRenderer(),n}return r},k=n=>{const{image:e,renderer:t}=n,o=P(e),r=G(o,t,n.toneMapping,n.renderTargetOptions),a=B({...n,image:o,sdr:r,renderer:r.renderer});return{sdr:r,gainMap:a,hdr:o,getMetadata:()=>({gainMapMax:a.material.gainMapMax,gainMapMin:a.material.gainMapMin,gamma:a.material.gamma,hdrCapacityMax:a.material.hdrCapacityMax,hdrCapacityMin:a.material.hdrCapacityMin,offsetHdr:a.material.offsetHdr,offsetSdr:a.material.offsetSdr})}},H=async e=>{const t=k(e),{mimeType:o,quality:r,flipY:a,withWorker:i}=e;let s,c,m;const l=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),p=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(i){const n=await Promise.all([i.compress({source:l,mimeType:o,quality:r,flipY:a}),i.compress({source:p,mimeType:o,quality:r,flipY:a})]);s=n,c=n[0].source,m=n[1].source}else s=await Promise.all([n({source:l,mimeType:o,quality:r,flipY:a}),n({source:p,mimeType:o,quality:r,flipY:a})]),c=l.data,m=p.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:c,rawGainMap:m}},X=(n,e="max",o)=>{const r=P(n);if(r.format!==M&&r.format!==x&&r.format!==t&&r.format!==_&&r.format!==C&&r.format!==A&&r.format!==w&&r.format!==T&&r.format!==E&&r.format!==y&&r.format!==I)throw new Error("Unsupported texture format");const a=new s({vertexShader:"\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\nprecision mediump float;\n\n#ifndef CELL_SIZE\n #define CELL_SIZE 2\n#endif\n\n#ifndef COMPARE_FUNCTION\n #define COMPARE_FUNCTION max\n#endif\n\n#ifndef INITIAL_VALUE\n #define INITIAL_VALUE 0\n#endif\n\nuniform sampler2D map;\nuniform vec2 u_srcResolution;\n\nvarying vec2 vUv;\n\nvoid main() {\n // compute the first pixel the source cell\n vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);\n\n // one pixel in source\n vec2 onePixel = vec2(1) / u_srcResolution;\n\n // uv for first pixel in cell. +0.5 for center of pixel\n vec2 uv = (srcPixel + 0.5) * onePixel;\n\n vec4 resultColor = vec4(INITIAL_VALUE);\n\n for (int y = 0; y < CELL_SIZE; ++y) {\n for (int x = 0; x < CELL_SIZE; ++x) {\n resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));\n }\n }\n\n gl_FragColor = resultColor;\n}\n",uniforms:{u_srcResolution:{value:new S(r.image.width,r.image.height)},map:{value:r}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:e,INITIAL_VALUE:"max"===e?0:65504}});r.needsUpdate=!0,a.needsUpdate=!0;let i=r.image.width,c=r.image.height;const m=new U({width:i,height:c,type:r.type,colorSpace:r.colorSpace,material:a,renderer:o}),l=[];for(;i>1||c>1;){i=Math.max(1,(i+2-1)/2|0),c=Math.max(1,(c+2-1)/2|0);const n=new N(i,c,{type:m.type,format:r.format,colorSpace:m.colorSpace,minFilter:L,magFilter:L,wrapS:R,wrapT:R,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});l.push(n)}i=r.image.width,c=r.image.height,l.forEach(n=>{i=Math.max(1,(i+2-1)/2|0),c=Math.max(1,(c+2-1)/2|0),m.renderTarget=n,m.render(),a.uniforms.map.value=n.texture,a.uniforms.u_srcResolution.value.x=i,a.uniforms.u_srcResolution.value.y=c});const p=m.toArray();return m.dispose(),l.forEach(n=>n.dispose()),[m.type===b?p[0]:O.fromHalfFloat(p[0]),m.type===b?p[1]:O.fromHalfFloat(p[1]),m.type===b?p[2]:O.fromHalfFloat(p[2])]};export{D as GainMapEncoderMaterial,F as SDRMaterial,n as compress,k as encode,H as encodeAndCompress,X as findTextureMinMax,B as getGainMap,G as getSDRRendition};
|
|
5
|
+
import{c as n}from"./compress-5gFn7Y4a.js";import{DataTexture as e,RGBAFormat as t,UVMapping as o,RepeatWrapping as a,LinearFilter as r,LinearSRGBColorSpace as i,ShaderMaterial as s,NoBlending as m,Vector3 as c,UnsignedByteType as l,ACESFilmicToneMapping as p,LinearToneMapping as d,NeutralToneMapping as g,AgXToneMapping as u,CineonToneMapping as f,ReinhardToneMapping as h,SRGBColorSpace as v,AlphaFormat as x,RGBFormat as M,DepthFormat as _,DepthStencilFormat as C,RedFormat as w,RedIntegerFormat as A,RGFormat as T,RGIntegerFormat as E,RGBIntegerFormat as y,RGBAIntegerFormat as I,Vector2 as S,WebGLRenderTarget as N,ClampToEdgeWrapping as R,NearestFilter as L,FloatType as b,DataUtils as O}from"three";import{Q as U}from"./QuadRenderer-DIHDdKl6.js";const B=n=>{let s;if(n instanceof e){if(!(n.image.data instanceof Uint16Array||n.image.data instanceof Float32Array))throw new Error("Provided image is not HDR");s=n}else{if(!n.data||!n.width||!n.height)throw new Error("Provided image has no data or size");s=new e(n.data,n.width,n.height,n.format??t,n.type,o,a,a,r,r,1,"colorSpace"in n&&"srgb"===n.colorSpace?n.colorSpace:i),"header"in n&&"gamma"in n&&(s.flipY=!0),s.needsUpdate=!0}return s},P=1.0001,D=n=>{console.warn(`gainmap-js: maxContentBoost is ${n} (<= 1), the source image has no HDR content. It will be clamped to 1.0001 and the result will be equivalent to an SDR image.`)},F=(n,e)=>{console.warn(`gainmap-js: minContentBoost (${n}) must be lower than maxContentBoost (${e}), the resulting gain map will be invalid.`)};class G extends s{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:n,hdr:e,offsetSdr:t,offsetHdr:o,maxContentBoost:a,minContentBoost:r,gamma:i}){if(!a)throw new Error("maxContentBoost is required");if(!n)throw new Error("sdr is required");if(!e)throw new Error("hdr is required");const s=i||[1,1,1],l=t||[1/64,1/64,1/64],p=o||[1/64,1/64,1/64];a<=1&&D(a);const d=r||1,g=Math.max(a,P);d>=g&&F(d,g),super({name:"GainMapEncoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform sampler2D sdr;\nuniform sampler2D hdr;\nuniform vec3 gamma;\nuniform vec3 offsetSdr;\nuniform vec3 offsetHdr;\nuniform float minLog2;\nuniform float maxLog2;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 sdrColor = texture2D(sdr, vUv).rgb;\n vec3 hdrColor = texture2D(hdr, vUv).rgb;\n\n vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);\n vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);\n vec3 clampedRecovery = saturate(logRecovery);\n gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);\n}\n",uniforms:{sdr:{value:n},hdr:{value:e},gamma:{value:(new c).fromArray(s)},offsetSdr:{value:(new c).fromArray(l)},offsetHdr:{value:(new c).fromArray(p)},minLog2:{value:Math.log2(d)},maxLog2:{value:Math.log2(g)}},blending:m,depthTest:!1,depthWrite:!1}),this._minContentBoost=d,this._maxContentBoost=g,this._offsetSdr=l,this._offsetHdr=p,this._gamma=s,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(n){this._gamma=n,this.uniforms.gamma.value=(new c).fromArray(n)}get offsetHdr(){return this._offsetHdr}set offsetHdr(n){this._offsetHdr=n,this.uniforms.offsetHdr.value=(new c).fromArray(n)}get offsetSdr(){return this._offsetSdr}set offsetSdr(n){this._offsetSdr=n,this.uniforms.offsetSdr.value=(new c).fromArray(n)}get minContentBoost(){return this._minContentBoost}set minContentBoost(n){n>=this._maxContentBoost&&F(n,this._maxContentBoost),this._minContentBoost=n,this.uniforms.minLog2.value=Math.log2(n)}get maxContentBoost(){return this._maxContentBoost}set maxContentBoost(n){n<=1&&D(n);const e=Math.max(n,P);this._minContentBoost>=e&&F(this._minContentBoost,e),this._maxContentBoost=e,this.uniforms.maxLog2.value=Math.log2(e)}get gainMapMin(){return[Math.log2(this._minContentBoost),Math.log2(this._minContentBoost),Math.log2(this._minContentBoost)]}get gainMapMax(){return[Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost)]}get hdrCapacityMin(){return Math.min(Math.max(0,this.gainMapMin[0]),Math.max(0,this.gainMapMin[1]),Math.max(0,this.gainMapMin[2]))}get hdrCapacityMax(){return Math.max(Math.max(0,this.gainMapMax[0]),Math.max(0,this.gainMapMax[1]),Math.max(0,this.gainMapMax[2]))}}const k=n=>{const{image:e,sdr:t,renderer:o}=n,a=B(e),r=new G({...n,sdr:t.renderTarget.texture,hdr:a}),s=new U({width:a.image.width,height:a.image.height,type:l,colorSpace:i,material:r,renderer:o,renderTargetOptions:n.renderTargetOptions});try{s.render()}catch(n){throw s.disposeOnDemandRenderer(),n}return s};class H extends s{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:n,toneMapping:e}){super({name:"SDRMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform sampler2D map;\nuniform float brightness;\nuniform float contrast;\nuniform float saturation;\nuniform float exposure;\n\nvarying vec2 vUv;\n\nmat4 brightnessMatrix( float brightness ) {\n return mat4(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n brightness, brightness, brightness, 1\n );\n}\n\nmat4 contrastMatrix( float contrast ) {\n float t = ( 1.0 - contrast ) / 2.0;\n return mat4(\n contrast, 0, 0, 0,\n 0, contrast, 0, 0,\n 0, 0, contrast, 0,\n t, t, t, 1\n );\n}\n\nmat4 saturationMatrix( float saturation ) {\n vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );\n float oneMinusSat = 1.0 - saturation;\n vec3 red = vec3( luminance.x * oneMinusSat );\n red+= vec3( saturation, 0, 0 );\n vec3 green = vec3( luminance.y * oneMinusSat );\n green += vec3( 0, saturation, 0 );\n vec3 blue = vec3( luminance.z * oneMinusSat );\n blue += vec3( 0, 0, saturation );\n return mat4(\n red, 0,\n green, 0,\n blue, 0,\n 0, 0, 0, 1\n );\n}\n\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n // ODT_SAT => XYZ => D60_2_D65 => sRGB\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color = ACESInputMat * color;\n // Apply RRT and ODT\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n // Clamp to [0, 1]\n return saturate( color );\n}\n\n// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf\nvec3 ReinhardToneMapping( vec3 color ) {\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 CineonToneMapping( vec3 color ) {\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n\n// nothing\nvec3 LinearToneMapping ( vec3 color ) {\n return color;\n}\n\n// Matrices for rec 2020 <> rec 709 color space conversion\n// matrix provided in row-major order so it has been transposed\n// https://www.itu.int/pub/R-REP-BT.2407-2017\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\n\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\n\n// https://iolite-engine.com/blog_posts/minimal_agx_implementation\n// Mean error^2: 3.6705141e-06\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\n\n// AgX Tone Mapping implementation based on Filament, which in turn is based\n// on Blender's implementation using rec 2020 primaries\n// https://github.com/google/filament/pull/7236\n// Inputs and outputs are encoded as Linear-sRGB.\n\nvec3 AgXToneMapping( vec3 color ) {\n\n // AgX constants\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n\n // explicit AgXOutsetMatrix generated from Filaments AgXOutsetMatrixInv\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n\n // LOG2_MIN = -10.0\n // LOG2_MAX = +6.5\n // MIDDLE_GRAY = 0.18\n const float AgxMinEv = - 12.47393; // log2( pow( 2, LOG2_MIN ) * MIDDLE_GRAY )\n const float AgxMaxEv = 4.026069; // log2( pow( 2, LOG2_MAX ) * MIDDLE_GRAY )\n\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\n color = AgXInsetMatrix * color;\n\n // Log2 encoding\n color = max( color, 1e-10 ); // avoid 0 or negative numbers for log2\n color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\n color = clamp( color, 0.0, 1.0 );\n\n // Apply sigmoid\n color = agxDefaultContrastApprox( color );\n\n // Apply AgX look\n // v = agxLook(v, look);\n\n color = AgXOutsetMatrix * color;\n\n // Linearize\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\n // Gamut mapping. Simple clamp for now.\n color = clamp( color, 0.0, 1.0 );\n\n return color;\n\n}\n\n// https://modelviewer.dev/examples/tone-mapping\n\nvec3 NeutralToneMapping( vec3 color ) {\n\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n\n float x = min( color.r, min( color.g, color.b ) );\n\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\n color -= offset;\n\n float peak = max( color.r, max( color.g, color.b ) );\n\n if ( peak < StartCompression ) return color;\n\n float d = 1. - StartCompression;\n\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n\n color *= newPeak / peak;\n\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\n return mix( color, vec3( newPeak ), g );\n\n}\n\n\n\nvoid main() {\n vec4 color = texture2D(map, vUv);\n\n vec4 exposed = vec4(exposure * color.rgb, color.a);\n\n vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);\n\n vec4 adjusted =\n brightnessMatrix( brightness ) *\n contrastMatrix( contrast ) *\n saturationMatrix( saturation ) *\n tonemapped;\n\n gl_FragColor = adjusted;\n}\n",uniforms:{map:{value:n},brightness:{value:0},contrast:{value:1},saturation:{value:1},exposure:{value:1}},blending:m,depthTest:!1,depthWrite:!1}),this._map=n,this.toneMapping=this._toneMapping=e||p,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(n){let e=!1;switch(n){case p:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",e=!0;break;case h:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",e=!0;break;case f:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",e=!0;break;case d:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",e=!0;break;case u:this.defines.TONEMAPPING_FUNCTION="AgXToneMapping",e=!0;break;case g:this.defines.TONEMAPPING_FUNCTION="NeutralToneMapping",e=!0;break;default:console.error(`Unsupported toneMapping: ${n}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=d}e&&(this._toneMapping=n),this.needsUpdate=!0}get brightness(){return this._brightness}set brightness(n){this._brightness=n,this.uniforms.brightness.value=n}get contrast(){return this._contrast}set contrast(n){this._contrast=n,this.uniforms.contrast.value=n}get saturation(){return this._saturation}set saturation(n){this._saturation=n,this.uniforms.saturation.value=n}get exposure(){return this._exposure}set exposure(n){this._exposure=n,this.uniforms.exposure.value=n}get map(){return this._map}set map(n){this._map=n,this.uniforms.map.value=n}}const X=(n,e,t,o)=>{n.needsUpdate=!0;const a=new U({width:n.image.width,height:n.image.height,type:l,colorSpace:v,material:new H({map:n,toneMapping:t}),renderer:e,renderTargetOptions:o});try{a.render()}catch(n){throw a.disposeOnDemandRenderer(),n}return a},j=n=>{const{image:e,renderer:t}=n,o=B(e),a=X(o,t,n.toneMapping,n.renderTargetOptions),r=k({...n,image:o,sdr:a,renderer:a.renderer});return{sdr:a,gainMap:r,hdr:o,getMetadata:()=>({gainMapMax:r.material.gainMapMax,gainMapMin:r.material.gainMapMin,gamma:r.material.gamma,hdrCapacityMax:r.material.hdrCapacityMax,hdrCapacityMin:r.material.hdrCapacityMin,offsetHdr:r.material.offsetHdr,offsetSdr:r.material.offsetSdr})}},Y=async e=>{const t=j(e),{mimeType:o,quality:a,flipY:r,withWorker:i}=e;let s,m,c;const l=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),p=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(i){const n=await Promise.all([i.compress({source:l,mimeType:o,quality:a,flipY:r}),i.compress({source:p,mimeType:o,quality:a,flipY:r})]);s=n,m=n[0].source,c=n[1].source}else s=await Promise.all([n({source:l,mimeType:o,quality:a,flipY:r}),n({source:p,mimeType:o,quality:a,flipY:r})]),m=l.data,c=p.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:m,rawGainMap:c}},q=(n,e="max",o)=>{const a=B(n);if(a.format!==x&&a.format!==M&&a.format!==t&&a.format!==_&&a.format!==C&&a.format!==w&&a.format!==A&&a.format!==T&&a.format!==E&&a.format!==y&&a.format!==I)throw new Error("Unsupported texture format");const r=new s({vertexShader:"\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\nprecision mediump float;\n\n#ifndef CELL_SIZE\n #define CELL_SIZE 2\n#endif\n\n#ifndef COMPARE_FUNCTION\n #define COMPARE_FUNCTION max\n#endif\n\n#ifndef INITIAL_VALUE\n #define INITIAL_VALUE 0\n#endif\n\nuniform sampler2D map;\nuniform vec2 u_srcResolution;\n\nvarying vec2 vUv;\n\nvoid main() {\n // compute the first pixel the source cell\n vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);\n\n // one pixel in source\n vec2 onePixel = vec2(1) / u_srcResolution;\n\n // uv for first pixel in cell. +0.5 for center of pixel\n vec2 uv = (srcPixel + 0.5) * onePixel;\n\n vec4 resultColor = vec4(INITIAL_VALUE);\n\n for (int y = 0; y < CELL_SIZE; ++y) {\n for (int x = 0; x < CELL_SIZE; ++x) {\n resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));\n }\n }\n\n gl_FragColor = resultColor;\n}\n",uniforms:{u_srcResolution:{value:new S(a.image.width,a.image.height)},map:{value:a}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:e,INITIAL_VALUE:"max"===e?0:65504}});a.needsUpdate=!0,r.needsUpdate=!0;let i=a.image.width,m=a.image.height;const c=new U({width:i,height:m,type:a.type,colorSpace:a.colorSpace,material:r,renderer:o}),l=[];for(;i>1||m>1;){i=Math.max(1,(i+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0);const n=new N(i,m,{type:c.type,format:a.format,colorSpace:c.colorSpace,minFilter:L,magFilter:L,wrapS:R,wrapT:R,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});l.push(n)}i=a.image.width,m=a.image.height,l.forEach(n=>{i=Math.max(1,(i+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0),c.renderTarget=n,c.render(),r.uniforms.map.value=n.texture,r.uniforms.u_srcResolution.value.x=i,r.uniforms.u_srcResolution.value.y=m});const p=c.toArray();return c.dispose(),l.forEach(n=>n.dispose()),[c.type===b?p[0]:O.fromHalfFloat(p[0]),c.type===b?p[1]:O.fromHalfFloat(p[1]),c.type===b?p[2]:O.fromHalfFloat(p[2])]};export{G as GainMapEncoderMaterial,H as SDRMaterial,n as compress,j as encode,Y as encodeAndCompress,q as findTextureMinMax,k as getGainMap,X as getSDRRendition};
|
package/dist/encode.umd.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.
|
|
2
|
+
* @monogrid/gainmap-js v3.5.0
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
5
|
|
|
@@ -113,7 +113,10 @@
|
|
|
113
113
|
dataTexture = image;
|
|
114
114
|
}
|
|
115
115
|
else {
|
|
116
|
-
|
|
116
|
+
if (!image.data || !image.width || !image.height) {
|
|
117
|
+
throw new Error('Provided image has no data or size');
|
|
118
|
+
}
|
|
119
|
+
dataTexture = new three.DataTexture(image.data, image.width, image.height, image.format ?? three.RGBAFormat, image.type, three.UVMapping, three.RepeatWrapping, three.RepeatWrapping, three.LinearFilter, three.LinearFilter, 1, 'colorSpace' in image && image.colorSpace === 'srgb' ? image.colorSpace : three.LinearSRGBColorSpace);
|
|
117
120
|
// TODO: This tries to detect a raw RGBE and applies flipY
|
|
118
121
|
// see if there's a better way to detect it?
|
|
119
122
|
if ('header' in image && 'gamma' in image) {
|
|
@@ -458,6 +461,14 @@ void main() {
|
|
|
458
461
|
gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);
|
|
459
462
|
}
|
|
460
463
|
`;
|
|
464
|
+
// maxContentBoost must be > 1, a gain map can't encode an empty boost range
|
|
465
|
+
const MIN_MAX_CONTENT_BOOST = 1.0001;
|
|
466
|
+
const warnNoHDRContent = (maxContentBoost) => {
|
|
467
|
+
console.warn(`gainmap-js: maxContentBoost is ${maxContentBoost} (<= 1), the source image has no HDR content. It will be clamped to ${MIN_MAX_CONTENT_BOOST} and the result will be equivalent to an SDR image.`);
|
|
468
|
+
};
|
|
469
|
+
const warnEmptyRange = (minContentBoost, maxContentBoost) => {
|
|
470
|
+
console.warn(`gainmap-js: minContentBoost (${minContentBoost}) must be lower than maxContentBoost (${maxContentBoost}), the resulting gain map will be invalid.`);
|
|
471
|
+
};
|
|
461
472
|
/**
|
|
462
473
|
* A Material which is able to encode a gainmap
|
|
463
474
|
*
|
|
@@ -484,8 +495,12 @@ void main() {
|
|
|
484
495
|
const _gamma = gamma || [1, 1, 1];
|
|
485
496
|
const _offsetSdr = offsetSdr || [1 / 64, 1 / 64, 1 / 64];
|
|
486
497
|
const _offsetHdr = offsetHdr || [1 / 64, 1 / 64, 1 / 64];
|
|
498
|
+
if (maxContentBoost <= 1)
|
|
499
|
+
warnNoHDRContent(maxContentBoost);
|
|
487
500
|
const _minContentBoost = minContentBoost || 1;
|
|
488
|
-
const _maxContentBoost = Math.max(maxContentBoost,
|
|
501
|
+
const _maxContentBoost = Math.max(maxContentBoost, MIN_MAX_CONTENT_BOOST);
|
|
502
|
+
if (_minContentBoost >= _maxContentBoost)
|
|
503
|
+
warnEmptyRange(_minContentBoost, _maxContentBoost);
|
|
489
504
|
super({
|
|
490
505
|
name: 'GainMapEncoderMaterial',
|
|
491
506
|
vertexShader: vertexShader$2,
|
|
@@ -541,6 +556,8 @@ void main() {
|
|
|
541
556
|
*/
|
|
542
557
|
get minContentBoost() { return this._minContentBoost; }
|
|
543
558
|
set minContentBoost(value) {
|
|
559
|
+
if (value >= this._maxContentBoost)
|
|
560
|
+
warnEmptyRange(value, this._maxContentBoost);
|
|
544
561
|
this._minContentBoost = value;
|
|
545
562
|
this.uniforms.minLog2.value = Math.log2(value);
|
|
546
563
|
}
|
|
@@ -550,8 +567,13 @@ void main() {
|
|
|
550
567
|
*/
|
|
551
568
|
get maxContentBoost() { return this._maxContentBoost; }
|
|
552
569
|
set maxContentBoost(value) {
|
|
553
|
-
|
|
554
|
-
|
|
570
|
+
if (value <= 1)
|
|
571
|
+
warnNoHDRContent(value);
|
|
572
|
+
const _value = Math.max(value, MIN_MAX_CONTENT_BOOST);
|
|
573
|
+
if (this._minContentBoost >= _value)
|
|
574
|
+
warnEmptyRange(this._minContentBoost, _value);
|
|
575
|
+
this._maxContentBoost = _value;
|
|
576
|
+
this.uniforms.maxLog2.value = Math.log2(_value);
|
|
555
577
|
}
|
|
556
578
|
/**
|
|
557
579
|
* @see {@link GainMapMetadata.gainMapMin}
|
package/dist/encode.umd.min.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.
|
|
2
|
+
* @monogrid/gainmap-js v3.5.0
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).encode={},e.three)}(this,function(e,t){"use strict";const n=async e=>{if("undefined"==typeof createImageBitmap)throw new Error("createImageBitmap() not supported.");const{source:t,mimeType:n,quality:r,flipY:a}=e;let o;if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&"sourceMimeType"in e)o=new Blob([t],{type:e.sourceMimeType});else{if(!(t instanceof ImageData))throw new Error("Invalid source image");o=t}const i=await createImageBitmap(o),s=i.width,p=i.height;let c;"undefined"!=typeof OffscreenCanvas?c=new OffscreenCanvas(s,p):(c=document.createElement("canvas"),c.width=s,c.height=p);const l=c.getContext("2d");if(!l)throw new Error("Failed to create canvas Context");!0===a&&(l.translate(0,p),l.scale(1,-1)),l.drawImage(i,0,0,s,p);const d=await(async(e,t,n)=>{if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return e.convertToBlob({type:t,quality:n});if(e instanceof HTMLCanvasElement)return new Promise((r,a)=>{e.toBlob(e=>{e?r(e):a(new Error("Failed to convert canvas to blob"))},t,n)});throw new Error("Unsupported canvas element")})(c,n,r||.9);return{data:new Uint8Array(await d.arrayBuffer()),mimeType:n,width:s,height:p}},r=e=>{let n;if(e instanceof t.DataTexture){if(!(e.image.data instanceof Uint16Array||e.image.data instanceof Float32Array))throw new Error("Provided image is not HDR");n=e}else n=new t.DataTexture(e.data,e.width,e.height,"format"in e?e.format:t.RGBAFormat,e.type,t.UVMapping,t.RepeatWrapping,t.RepeatWrapping,t.LinearFilter,t.LinearFilter,1,"colorSpace"in e&&"srgb"===e.colorSpace?e.colorSpace:t.LinearSRGBColorSpace),"header"in e&&"gamma"in e&&(n.flipY=!0),n.needsUpdate=!0;return n},a=(e,n,r)=>{let a;switch(e){case t.UnsignedByteType:a=new Uint8ClampedArray(n*r*4);break;case t.HalfFloatType:a=new Uint16Array(n*r*4);break;case t.UnsignedIntType:a=new Uint32Array(n*r*4);break;case t.ByteType:a=new Int8Array(n*r*4);break;case t.ShortType:a=new Int16Array(n*r*4);break;case t.IntType:a=new Int32Array(n*r*4);break;case t.FloatType:a=new Float32Array(n*r*4);break;default:throw new Error("Unsupported data type")}return a};let o;class i{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const n={format:t.RGBAFormat,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:t.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:t.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:t.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:t.ClampToEdgeWrapping};if(this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=i.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new t.Scene,this._camera=new t.OrthographicCamera,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),!((e,n,r,i)=>{if(void 0!==o)return o;const s=new t.WebGLRenderTarget(1,1,i);n.setRenderTarget(s);const p=new t.Mesh(new t.PlaneGeometry,new t.MeshBasicMaterial({color:16777215}));n.render(p,r),n.setRenderTarget(null);const c=a(e,s.width,s.height);return n.readRenderTargetPixels(s,0,0,s.width,s.height,c),s.dispose(),p.geometry.dispose(),p.material.dispose(),o=0!==c[0],o})(this._type,this._renderer,this._camera,n)){let e;if(this._type===t.HalfFloatType)e=this._renderer.extensions.has("EXT_color_buffer_float")?t.FloatType:void 0;void 0!==e?(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${t.FloatType}`),this._type=e):(this._supportsReadPixels=!1,console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown"))}this._quad=new t.Mesh(new t.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new t.WebGLRenderTarget(this.width,this.height,n),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:t.UVMapping}static instantiateRenderer(){const e=new t.WebGLRenderer;return e.setSize(128,128),e}render=()=>{this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=a(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(e){const n=new t.DataTexture(this.toArray(),this.width,this.height,t.RGBAFormat,this._type,e?.mapping||t.UVMapping,e?.wrapS||t.ClampToEdgeWrapping,e?.wrapT||t.ClampToEdgeWrapping,e?.magFilter||t.LinearFilter,e?.minFilter||t.LinearFilter,e?.anisotropy||1,t.LinearSRGBColorSpace);return n.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,n}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),e&&this.renderTarget.dispose(),this.material instanceof t.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof t.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof t.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}}class s extends t.ShaderMaterial{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:e,hdr:n,offsetSdr:r,offsetHdr:a,maxContentBoost:o,minContentBoost:i,gamma:s}){if(!o)throw new Error("maxContentBoost is required");if(!e)throw new Error("sdr is required");if(!n)throw new Error("hdr is required");const p=s||[1,1,1],c=r||[1/64,1/64,1/64],l=a||[1/64,1/64,1/64],d=i||1,m=Math.max(o,1.0001);super({name:"GainMapEncoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform sampler2D sdr;\nuniform sampler2D hdr;\nuniform vec3 gamma;\nuniform vec3 offsetSdr;\nuniform vec3 offsetHdr;\nuniform float minLog2;\nuniform float maxLog2;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 sdrColor = texture2D(sdr, vUv).rgb;\n vec3 hdrColor = texture2D(hdr, vUv).rgb;\n\n vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);\n vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);\n vec3 clampedRecovery = saturate(logRecovery);\n gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);\n}\n",uniforms:{sdr:{value:e},hdr:{value:n},gamma:{value:(new t.Vector3).fromArray(p)},offsetSdr:{value:(new t.Vector3).fromArray(c)},offsetHdr:{value:(new t.Vector3).fromArray(l)},minLog2:{value:Math.log2(d)},maxLog2:{value:Math.log2(m)}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._minContentBoost=d,this._maxContentBoost=m,this._offsetSdr=c,this._offsetHdr=l,this._gamma=p,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(e){this._gamma=e,this.uniforms.gamma.value=(new t.Vector3).fromArray(e)}get offsetHdr(){return this._offsetHdr}set offsetHdr(e){this._offsetHdr=e,this.uniforms.offsetHdr.value=(new t.Vector3).fromArray(e)}get offsetSdr(){return this._offsetSdr}set offsetSdr(e){this._offsetSdr=e,this.uniforms.offsetSdr.value=(new t.Vector3).fromArray(e)}get minContentBoost(){return this._minContentBoost}set minContentBoost(e){this._minContentBoost=e,this.uniforms.minLog2.value=Math.log2(e)}get maxContentBoost(){return this._maxContentBoost}set maxContentBoost(e){this._maxContentBoost=e,this.uniforms.maxLog2.value=Math.log2(e)}get gainMapMin(){return[Math.log2(this._minContentBoost),Math.log2(this._minContentBoost),Math.log2(this._minContentBoost)]}get gainMapMax(){return[Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost)]}get hdrCapacityMin(){return Math.min(Math.max(0,this.gainMapMin[0]),Math.max(0,this.gainMapMin[1]),Math.max(0,this.gainMapMin[2]))}get hdrCapacityMax(){return Math.max(Math.max(0,this.gainMapMax[0]),Math.max(0,this.gainMapMax[1]),Math.max(0,this.gainMapMax[2]))}}const p=e=>{const{image:n,sdr:a,renderer:o}=e,p=r(n),c=new s({...e,sdr:a.renderTarget.texture,hdr:p}),l=new i({width:p.image.width,height:p.image.height,type:t.UnsignedByteType,colorSpace:t.LinearSRGBColorSpace,material:c,renderer:o,renderTargetOptions:e.renderTargetOptions});try{l.render()}catch(e){throw l.disposeOnDemandRenderer(),e}return l};class c extends t.ShaderMaterial{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:e,toneMapping:n}){super({name:"SDRMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform sampler2D map;\nuniform float brightness;\nuniform float contrast;\nuniform float saturation;\nuniform float exposure;\n\nvarying vec2 vUv;\n\nmat4 brightnessMatrix( float brightness ) {\n return mat4(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n brightness, brightness, brightness, 1\n );\n}\n\nmat4 contrastMatrix( float contrast ) {\n float t = ( 1.0 - contrast ) / 2.0;\n return mat4(\n contrast, 0, 0, 0,\n 0, contrast, 0, 0,\n 0, 0, contrast, 0,\n t, t, t, 1\n );\n}\n\nmat4 saturationMatrix( float saturation ) {\n vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );\n float oneMinusSat = 1.0 - saturation;\n vec3 red = vec3( luminance.x * oneMinusSat );\n red+= vec3( saturation, 0, 0 );\n vec3 green = vec3( luminance.y * oneMinusSat );\n green += vec3( 0, saturation, 0 );\n vec3 blue = vec3( luminance.z * oneMinusSat );\n blue += vec3( 0, 0, saturation );\n return mat4(\n red, 0,\n green, 0,\n blue, 0,\n 0, 0, 0, 1\n );\n}\n\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n // ODT_SAT => XYZ => D60_2_D65 => sRGB\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color = ACESInputMat * color;\n // Apply RRT and ODT\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n // Clamp to [0, 1]\n return saturate( color );\n}\n\n// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf\nvec3 ReinhardToneMapping( vec3 color ) {\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 CineonToneMapping( vec3 color ) {\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n\n// nothing\nvec3 LinearToneMapping ( vec3 color ) {\n return color;\n}\n\n// Matrices for rec 2020 <> rec 709 color space conversion\n// matrix provided in row-major order so it has been transposed\n// https://www.itu.int/pub/R-REP-BT.2407-2017\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\n\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\n\n// https://iolite-engine.com/blog_posts/minimal_agx_implementation\n// Mean error^2: 3.6705141e-06\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\n\n// AgX Tone Mapping implementation based on Filament, which in turn is based\n// on Blender's implementation using rec 2020 primaries\n// https://github.com/google/filament/pull/7236\n// Inputs and outputs are encoded as Linear-sRGB.\n\nvec3 AgXToneMapping( vec3 color ) {\n\n // AgX constants\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n\n // explicit AgXOutsetMatrix generated from Filaments AgXOutsetMatrixInv\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n\n // LOG2_MIN = -10.0\n // LOG2_MAX = +6.5\n // MIDDLE_GRAY = 0.18\n const float AgxMinEv = - 12.47393; // log2( pow( 2, LOG2_MIN ) * MIDDLE_GRAY )\n const float AgxMaxEv = 4.026069; // log2( pow( 2, LOG2_MAX ) * MIDDLE_GRAY )\n\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\n color = AgXInsetMatrix * color;\n\n // Log2 encoding\n color = max( color, 1e-10 ); // avoid 0 or negative numbers for log2\n color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\n color = clamp( color, 0.0, 1.0 );\n\n // Apply sigmoid\n color = agxDefaultContrastApprox( color );\n\n // Apply AgX look\n // v = agxLook(v, look);\n\n color = AgXOutsetMatrix * color;\n\n // Linearize\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\n // Gamut mapping. Simple clamp for now.\n color = clamp( color, 0.0, 1.0 );\n\n return color;\n\n}\n\n// https://modelviewer.dev/examples/tone-mapping\n\nvec3 NeutralToneMapping( vec3 color ) {\n\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n\n float x = min( color.r, min( color.g, color.b ) );\n\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\n color -= offset;\n\n float peak = max( color.r, max( color.g, color.b ) );\n\n if ( peak < StartCompression ) return color;\n\n float d = 1. - StartCompression;\n\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n\n color *= newPeak / peak;\n\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\n return mix( color, vec3( newPeak ), g );\n\n}\n\n\n\nvoid main() {\n vec4 color = texture2D(map, vUv);\n\n vec4 exposed = vec4(exposure * color.rgb, color.a);\n\n vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);\n\n vec4 adjusted =\n brightnessMatrix( brightness ) *\n contrastMatrix( contrast ) *\n saturationMatrix( saturation ) *\n tonemapped;\n\n gl_FragColor = adjusted;\n}\n",uniforms:{map:{value:e},brightness:{value:0},contrast:{value:1},saturation:{value:1},exposure:{value:1}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._map=e,this.toneMapping=this._toneMapping=n||t.ACESFilmicToneMapping,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(e){let n=!1;switch(e){case t.ACESFilmicToneMapping:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",n=!0;break;case t.ReinhardToneMapping:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",n=!0;break;case t.CineonToneMapping:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",n=!0;break;case t.LinearToneMapping:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",n=!0;break;case t.AgXToneMapping:this.defines.TONEMAPPING_FUNCTION="AgXToneMapping",n=!0;break;case t.NeutralToneMapping:this.defines.TONEMAPPING_FUNCTION="NeutralToneMapping",n=!0;break;default:console.error(`Unsupported toneMapping: ${e}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=t.LinearToneMapping}n&&(this._toneMapping=e),this.needsUpdate=!0}get brightness(){return this._brightness}set brightness(e){this._brightness=e,this.uniforms.brightness.value=e}get contrast(){return this._contrast}set contrast(e){this._contrast=e,this.uniforms.contrast.value=e}get saturation(){return this._saturation}set saturation(e){this._saturation=e,this.uniforms.saturation.value=e}get exposure(){return this._exposure}set exposure(e){this._exposure=e,this.uniforms.exposure.value=e}get map(){return this._map}set map(e){this._map=e,this.uniforms.map.value=e}}const l=(e,n,r,a)=>{e.needsUpdate=!0;const o=new i({width:e.image.width,height:e.image.height,type:t.UnsignedByteType,colorSpace:t.SRGBColorSpace,material:new c({map:e,toneMapping:r}),renderer:n,renderTargetOptions:a});try{o.render()}catch(e){throw o.disposeOnDemandRenderer(),e}return o},d=e=>{const{image:t,renderer:n}=e,a=r(t),o=l(a,n,e.toneMapping,e.renderTargetOptions),i=p({...e,image:a,sdr:o,renderer:o.renderer});return{sdr:o,gainMap:i,hdr:a,getMetadata:()=>({gainMapMax:i.material.gainMapMax,gainMapMin:i.material.gainMapMin,gamma:i.material.gamma,hdrCapacityMax:i.material.hdrCapacityMax,hdrCapacityMin:i.material.hdrCapacityMin,offsetHdr:i.material.offsetHdr,offsetSdr:i.material.offsetSdr})}};e.GainMapEncoderMaterial=s,e.SDRMaterial=c,e.compress=n,e.encode=d,e.encodeAndCompress=async e=>{const t=d(e),{mimeType:r,quality:a,flipY:o,withWorker:i}=e;let s,p,c;const l=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),m=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(i){const e=await Promise.all([i.compress({source:l,mimeType:r,quality:a,flipY:o}),i.compress({source:m,mimeType:r,quality:a,flipY:o})]);s=e,p=e[0].source,c=e[1].source}else s=await Promise.all([n({source:l,mimeType:r,quality:a,flipY:o}),n({source:m,mimeType:r,quality:a,flipY:o})]),p=l.data,c=m.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:p,rawGainMap:c}},e.findTextureMinMax=(e,n="max",a)=>{const o=r(e);if(o.format!==t.AlphaFormat&&o.format!==t.RGBFormat&&o.format!==t.RGBAFormat&&o.format!==t.DepthFormat&&o.format!==t.DepthStencilFormat&&o.format!==t.RedFormat&&o.format!==t.RedIntegerFormat&&o.format!==t.RGFormat&&o.format!==t.RGIntegerFormat&&o.format!==t.RGBIntegerFormat&&o.format!==t.RGBAIntegerFormat)throw new Error("Unsupported texture format");const s=new t.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\nprecision mediump float;\n\n#ifndef CELL_SIZE\n #define CELL_SIZE 2\n#endif\n\n#ifndef COMPARE_FUNCTION\n #define COMPARE_FUNCTION max\n#endif\n\n#ifndef INITIAL_VALUE\n #define INITIAL_VALUE 0\n#endif\n\nuniform sampler2D map;\nuniform vec2 u_srcResolution;\n\nvarying vec2 vUv;\n\nvoid main() {\n // compute the first pixel the source cell\n vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);\n\n // one pixel in source\n vec2 onePixel = vec2(1) / u_srcResolution;\n\n // uv for first pixel in cell. +0.5 for center of pixel\n vec2 uv = (srcPixel + 0.5) * onePixel;\n\n vec4 resultColor = vec4(INITIAL_VALUE);\n\n for (int y = 0; y < CELL_SIZE; ++y) {\n for (int x = 0; x < CELL_SIZE; ++x) {\n resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));\n }\n }\n\n gl_FragColor = resultColor;\n}\n",uniforms:{u_srcResolution:{value:new t.Vector2(o.image.width,o.image.height)},map:{value:o}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:n,INITIAL_VALUE:"max"===n?0:65504}});o.needsUpdate=!0,s.needsUpdate=!0;let p=o.image.width,c=o.image.height;const l=new i({width:p,height:c,type:o.type,colorSpace:o.colorSpace,material:s,renderer:a}),d=[];for(;p>1||c>1;){p=Math.max(1,(p+2-1)/2|0),c=Math.max(1,(c+2-1)/2|0);const e=new t.WebGLRenderTarget(p,c,{type:l.type,format:o.format,colorSpace:l.colorSpace,minFilter:t.NearestFilter,magFilter:t.NearestFilter,wrapS:t.ClampToEdgeWrapping,wrapT:t.ClampToEdgeWrapping,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});d.push(e)}p=o.image.width,c=o.image.height,d.forEach(e=>{p=Math.max(1,(p+2-1)/2|0),c=Math.max(1,(c+2-1)/2|0),l.renderTarget=e,l.render(),s.uniforms.map.value=e.texture,s.uniforms.u_srcResolution.value.x=p,s.uniforms.u_srcResolution.value.y=c});const m=l.toArray();return l.dispose(),d.forEach(e=>e.dispose()),[l.type===t.FloatType?m[0]:t.DataUtils.fromHalfFloat(m[0]),l.type===t.FloatType?m[1]:t.DataUtils.fromHalfFloat(m[1]),l.type===t.FloatType?m[2]:t.DataUtils.fromHalfFloat(m[2])]},e.getGainMap=p,e.getSDRRendition=l});
|
|
5
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).encode={},e.three)}(this,function(e,t){"use strict";const n=async e=>{if("undefined"==typeof createImageBitmap)throw new Error("createImageBitmap() not supported.");const{source:t,mimeType:n,quality:r,flipY:a}=e;let o;if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&"sourceMimeType"in e)o=new Blob([t],{type:e.sourceMimeType});else{if(!(t instanceof ImageData))throw new Error("Invalid source image");o=t}const i=await createImageBitmap(o),s=i.width,p=i.height;let l;"undefined"!=typeof OffscreenCanvas?l=new OffscreenCanvas(s,p):(l=document.createElement("canvas"),l.width=s,l.height=p);const c=l.getContext("2d");if(!c)throw new Error("Failed to create canvas Context");!0===a&&(c.translate(0,p),c.scale(1,-1)),c.drawImage(i,0,0,s,p);const d=await(async(e,t,n)=>{if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return e.convertToBlob({type:t,quality:n});if(e instanceof HTMLCanvasElement)return new Promise((r,a)=>{e.toBlob(e=>{e?r(e):a(new Error("Failed to convert canvas to blob"))},t,n)});throw new Error("Unsupported canvas element")})(l,n,r||.9);return{data:new Uint8Array(await d.arrayBuffer()),mimeType:n,width:s,height:p}},r=e=>{let n;if(e instanceof t.DataTexture){if(!(e.image.data instanceof Uint16Array||e.image.data instanceof Float32Array))throw new Error("Provided image is not HDR");n=e}else{if(!e.data||!e.width||!e.height)throw new Error("Provided image has no data or size");n=new t.DataTexture(e.data,e.width,e.height,e.format??t.RGBAFormat,e.type,t.UVMapping,t.RepeatWrapping,t.RepeatWrapping,t.LinearFilter,t.LinearFilter,1,"colorSpace"in e&&"srgb"===e.colorSpace?e.colorSpace:t.LinearSRGBColorSpace),"header"in e&&"gamma"in e&&(n.flipY=!0),n.needsUpdate=!0}return n},a=(e,n,r)=>{let a;switch(e){case t.UnsignedByteType:a=new Uint8ClampedArray(n*r*4);break;case t.HalfFloatType:a=new Uint16Array(n*r*4);break;case t.UnsignedIntType:a=new Uint32Array(n*r*4);break;case t.ByteType:a=new Int8Array(n*r*4);break;case t.ShortType:a=new Int16Array(n*r*4);break;case t.IntType:a=new Int32Array(n*r*4);break;case t.FloatType:a=new Float32Array(n*r*4);break;default:throw new Error("Unsupported data type")}return a};let o;class i{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const n={format:t.RGBAFormat,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:t.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:t.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:t.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:t.ClampToEdgeWrapping};if(this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=i.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new t.Scene,this._camera=new t.OrthographicCamera,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),!((e,n,r,i)=>{if(void 0!==o)return o;const s=new t.WebGLRenderTarget(1,1,i);n.setRenderTarget(s);const p=new t.Mesh(new t.PlaneGeometry,new t.MeshBasicMaterial({color:16777215}));n.render(p,r),n.setRenderTarget(null);const l=a(e,s.width,s.height);return n.readRenderTargetPixels(s,0,0,s.width,s.height,l),s.dispose(),p.geometry.dispose(),p.material.dispose(),o=0!==l[0],o})(this._type,this._renderer,this._camera,n)){let e;if(this._type===t.HalfFloatType)e=this._renderer.extensions.has("EXT_color_buffer_float")?t.FloatType:void 0;void 0!==e?(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${t.FloatType}`),this._type=e):(this._supportsReadPixels=!1,console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown"))}this._quad=new t.Mesh(new t.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new t.WebGLRenderTarget(this.width,this.height,n),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:t.UVMapping}static instantiateRenderer(){const e=new t.WebGLRenderer;return e.setSize(128,128),e}render=()=>{this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=a(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(e){const n=new t.DataTexture(this.toArray(),this.width,this.height,t.RGBAFormat,this._type,e?.mapping||t.UVMapping,e?.wrapS||t.ClampToEdgeWrapping,e?.wrapT||t.ClampToEdgeWrapping,e?.magFilter||t.LinearFilter,e?.minFilter||t.LinearFilter,e?.anisotropy||1,t.LinearSRGBColorSpace);return n.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,n}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),e&&this.renderTarget.dispose(),this.material instanceof t.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof t.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof t.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}}const s=1.0001,p=e=>{console.warn(`gainmap-js: maxContentBoost is ${e} (<= 1), the source image has no HDR content. It will be clamped to 1.0001 and the result will be equivalent to an SDR image.`)},l=(e,t)=>{console.warn(`gainmap-js: minContentBoost (${e}) must be lower than maxContentBoost (${t}), the resulting gain map will be invalid.`)};class c extends t.ShaderMaterial{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:e,hdr:n,offsetSdr:r,offsetHdr:a,maxContentBoost:o,minContentBoost:i,gamma:c}){if(!o)throw new Error("maxContentBoost is required");if(!e)throw new Error("sdr is required");if(!n)throw new Error("hdr is required");const d=c||[1,1,1],m=r||[1/64,1/64,1/64],h=a||[1/64,1/64,1/64];o<=1&&p(o);const g=i||1,u=Math.max(o,s);g>=u&&l(g,u),super({name:"GainMapEncoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform sampler2D sdr;\nuniform sampler2D hdr;\nuniform vec3 gamma;\nuniform vec3 offsetSdr;\nuniform vec3 offsetHdr;\nuniform float minLog2;\nuniform float maxLog2;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 sdrColor = texture2D(sdr, vUv).rgb;\n vec3 hdrColor = texture2D(hdr, vUv).rgb;\n\n vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);\n vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);\n vec3 clampedRecovery = saturate(logRecovery);\n gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);\n}\n",uniforms:{sdr:{value:e},hdr:{value:n},gamma:{value:(new t.Vector3).fromArray(d)},offsetSdr:{value:(new t.Vector3).fromArray(m)},offsetHdr:{value:(new t.Vector3).fromArray(h)},minLog2:{value:Math.log2(g)},maxLog2:{value:Math.log2(u)}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._minContentBoost=g,this._maxContentBoost=u,this._offsetSdr=m,this._offsetHdr=h,this._gamma=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(e){this._gamma=e,this.uniforms.gamma.value=(new t.Vector3).fromArray(e)}get offsetHdr(){return this._offsetHdr}set offsetHdr(e){this._offsetHdr=e,this.uniforms.offsetHdr.value=(new t.Vector3).fromArray(e)}get offsetSdr(){return this._offsetSdr}set offsetSdr(e){this._offsetSdr=e,this.uniforms.offsetSdr.value=(new t.Vector3).fromArray(e)}get minContentBoost(){return this._minContentBoost}set minContentBoost(e){e>=this._maxContentBoost&&l(e,this._maxContentBoost),this._minContentBoost=e,this.uniforms.minLog2.value=Math.log2(e)}get maxContentBoost(){return this._maxContentBoost}set maxContentBoost(e){e<=1&&p(e);const t=Math.max(e,s);this._minContentBoost>=t&&l(this._minContentBoost,t),this._maxContentBoost=t,this.uniforms.maxLog2.value=Math.log2(t)}get gainMapMin(){return[Math.log2(this._minContentBoost),Math.log2(this._minContentBoost),Math.log2(this._minContentBoost)]}get gainMapMax(){return[Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost)]}get hdrCapacityMin(){return Math.min(Math.max(0,this.gainMapMin[0]),Math.max(0,this.gainMapMin[1]),Math.max(0,this.gainMapMin[2]))}get hdrCapacityMax(){return Math.max(Math.max(0,this.gainMapMax[0]),Math.max(0,this.gainMapMax[1]),Math.max(0,this.gainMapMax[2]))}}const d=e=>{const{image:n,sdr:a,renderer:o}=e,s=r(n),p=new c({...e,sdr:a.renderTarget.texture,hdr:s}),l=new i({width:s.image.width,height:s.image.height,type:t.UnsignedByteType,colorSpace:t.LinearSRGBColorSpace,material:p,renderer:o,renderTargetOptions:e.renderTargetOptions});try{l.render()}catch(e){throw l.disposeOnDemandRenderer(),e}return l};class m extends t.ShaderMaterial{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:e,toneMapping:n}){super({name:"SDRMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform sampler2D map;\nuniform float brightness;\nuniform float contrast;\nuniform float saturation;\nuniform float exposure;\n\nvarying vec2 vUv;\n\nmat4 brightnessMatrix( float brightness ) {\n return mat4(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n brightness, brightness, brightness, 1\n );\n}\n\nmat4 contrastMatrix( float contrast ) {\n float t = ( 1.0 - contrast ) / 2.0;\n return mat4(\n contrast, 0, 0, 0,\n 0, contrast, 0, 0,\n 0, 0, contrast, 0,\n t, t, t, 1\n );\n}\n\nmat4 saturationMatrix( float saturation ) {\n vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );\n float oneMinusSat = 1.0 - saturation;\n vec3 red = vec3( luminance.x * oneMinusSat );\n red+= vec3( saturation, 0, 0 );\n vec3 green = vec3( luminance.y * oneMinusSat );\n green += vec3( 0, saturation, 0 );\n vec3 blue = vec3( luminance.z * oneMinusSat );\n blue += vec3( 0, 0, saturation );\n return mat4(\n red, 0,\n green, 0,\n blue, 0,\n 0, 0, 0, 1\n );\n}\n\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n // ODT_SAT => XYZ => D60_2_D65 => sRGB\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color = ACESInputMat * color;\n // Apply RRT and ODT\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n // Clamp to [0, 1]\n return saturate( color );\n}\n\n// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf\nvec3 ReinhardToneMapping( vec3 color ) {\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 CineonToneMapping( vec3 color ) {\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n\n// nothing\nvec3 LinearToneMapping ( vec3 color ) {\n return color;\n}\n\n// Matrices for rec 2020 <> rec 709 color space conversion\n// matrix provided in row-major order so it has been transposed\n// https://www.itu.int/pub/R-REP-BT.2407-2017\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\n\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\n\n// https://iolite-engine.com/blog_posts/minimal_agx_implementation\n// Mean error^2: 3.6705141e-06\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\n\n// AgX Tone Mapping implementation based on Filament, which in turn is based\n// on Blender's implementation using rec 2020 primaries\n// https://github.com/google/filament/pull/7236\n// Inputs and outputs are encoded as Linear-sRGB.\n\nvec3 AgXToneMapping( vec3 color ) {\n\n // AgX constants\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n\n // explicit AgXOutsetMatrix generated from Filaments AgXOutsetMatrixInv\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n\n // LOG2_MIN = -10.0\n // LOG2_MAX = +6.5\n // MIDDLE_GRAY = 0.18\n const float AgxMinEv = - 12.47393; // log2( pow( 2, LOG2_MIN ) * MIDDLE_GRAY )\n const float AgxMaxEv = 4.026069; // log2( pow( 2, LOG2_MAX ) * MIDDLE_GRAY )\n\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\n color = AgXInsetMatrix * color;\n\n // Log2 encoding\n color = max( color, 1e-10 ); // avoid 0 or negative numbers for log2\n color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\n color = clamp( color, 0.0, 1.0 );\n\n // Apply sigmoid\n color = agxDefaultContrastApprox( color );\n\n // Apply AgX look\n // v = agxLook(v, look);\n\n color = AgXOutsetMatrix * color;\n\n // Linearize\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\n // Gamut mapping. Simple clamp for now.\n color = clamp( color, 0.0, 1.0 );\n\n return color;\n\n}\n\n// https://modelviewer.dev/examples/tone-mapping\n\nvec3 NeutralToneMapping( vec3 color ) {\n\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n\n float x = min( color.r, min( color.g, color.b ) );\n\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\n color -= offset;\n\n float peak = max( color.r, max( color.g, color.b ) );\n\n if ( peak < StartCompression ) return color;\n\n float d = 1. - StartCompression;\n\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n\n color *= newPeak / peak;\n\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\n return mix( color, vec3( newPeak ), g );\n\n}\n\n\n\nvoid main() {\n vec4 color = texture2D(map, vUv);\n\n vec4 exposed = vec4(exposure * color.rgb, color.a);\n\n vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);\n\n vec4 adjusted =\n brightnessMatrix( brightness ) *\n contrastMatrix( contrast ) *\n saturationMatrix( saturation ) *\n tonemapped;\n\n gl_FragColor = adjusted;\n}\n",uniforms:{map:{value:e},brightness:{value:0},contrast:{value:1},saturation:{value:1},exposure:{value:1}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._map=e,this.toneMapping=this._toneMapping=n||t.ACESFilmicToneMapping,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(e){let n=!1;switch(e){case t.ACESFilmicToneMapping:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",n=!0;break;case t.ReinhardToneMapping:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",n=!0;break;case t.CineonToneMapping:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",n=!0;break;case t.LinearToneMapping:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",n=!0;break;case t.AgXToneMapping:this.defines.TONEMAPPING_FUNCTION="AgXToneMapping",n=!0;break;case t.NeutralToneMapping:this.defines.TONEMAPPING_FUNCTION="NeutralToneMapping",n=!0;break;default:console.error(`Unsupported toneMapping: ${e}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=t.LinearToneMapping}n&&(this._toneMapping=e),this.needsUpdate=!0}get brightness(){return this._brightness}set brightness(e){this._brightness=e,this.uniforms.brightness.value=e}get contrast(){return this._contrast}set contrast(e){this._contrast=e,this.uniforms.contrast.value=e}get saturation(){return this._saturation}set saturation(e){this._saturation=e,this.uniforms.saturation.value=e}get exposure(){return this._exposure}set exposure(e){this._exposure=e,this.uniforms.exposure.value=e}get map(){return this._map}set map(e){this._map=e,this.uniforms.map.value=e}}const h=(e,n,r,a)=>{e.needsUpdate=!0;const o=new i({width:e.image.width,height:e.image.height,type:t.UnsignedByteType,colorSpace:t.SRGBColorSpace,material:new m({map:e,toneMapping:r}),renderer:n,renderTargetOptions:a});try{o.render()}catch(e){throw o.disposeOnDemandRenderer(),e}return o},g=e=>{const{image:t,renderer:n}=e,a=r(t),o=h(a,n,e.toneMapping,e.renderTargetOptions),i=d({...e,image:a,sdr:o,renderer:o.renderer});return{sdr:o,gainMap:i,hdr:a,getMetadata:()=>({gainMapMax:i.material.gainMapMax,gainMapMin:i.material.gainMapMin,gamma:i.material.gamma,hdrCapacityMax:i.material.hdrCapacityMax,hdrCapacityMin:i.material.hdrCapacityMin,offsetHdr:i.material.offsetHdr,offsetSdr:i.material.offsetSdr})}};e.GainMapEncoderMaterial=c,e.SDRMaterial=m,e.compress=n,e.encode=g,e.encodeAndCompress=async e=>{const t=g(e),{mimeType:r,quality:a,flipY:o,withWorker:i}=e;let s,p,l;const c=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),d=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(i){const e=await Promise.all([i.compress({source:c,mimeType:r,quality:a,flipY:o}),i.compress({source:d,mimeType:r,quality:a,flipY:o})]);s=e,p=e[0].source,l=e[1].source}else s=await Promise.all([n({source:c,mimeType:r,quality:a,flipY:o}),n({source:d,mimeType:r,quality:a,flipY:o})]),p=c.data,l=d.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:p,rawGainMap:l}},e.findTextureMinMax=(e,n="max",a)=>{const o=r(e);if(o.format!==t.AlphaFormat&&o.format!==t.RGBFormat&&o.format!==t.RGBAFormat&&o.format!==t.DepthFormat&&o.format!==t.DepthStencilFormat&&o.format!==t.RedFormat&&o.format!==t.RedIntegerFormat&&o.format!==t.RGFormat&&o.format!==t.RGIntegerFormat&&o.format!==t.RGBIntegerFormat&&o.format!==t.RGBAIntegerFormat)throw new Error("Unsupported texture format");const s=new t.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\nprecision mediump float;\n\n#ifndef CELL_SIZE\n #define CELL_SIZE 2\n#endif\n\n#ifndef COMPARE_FUNCTION\n #define COMPARE_FUNCTION max\n#endif\n\n#ifndef INITIAL_VALUE\n #define INITIAL_VALUE 0\n#endif\n\nuniform sampler2D map;\nuniform vec2 u_srcResolution;\n\nvarying vec2 vUv;\n\nvoid main() {\n // compute the first pixel the source cell\n vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);\n\n // one pixel in source\n vec2 onePixel = vec2(1) / u_srcResolution;\n\n // uv for first pixel in cell. +0.5 for center of pixel\n vec2 uv = (srcPixel + 0.5) * onePixel;\n\n vec4 resultColor = vec4(INITIAL_VALUE);\n\n for (int y = 0; y < CELL_SIZE; ++y) {\n for (int x = 0; x < CELL_SIZE; ++x) {\n resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));\n }\n }\n\n gl_FragColor = resultColor;\n}\n",uniforms:{u_srcResolution:{value:new t.Vector2(o.image.width,o.image.height)},map:{value:o}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:n,INITIAL_VALUE:"max"===n?0:65504}});o.needsUpdate=!0,s.needsUpdate=!0;let p=o.image.width,l=o.image.height;const c=new i({width:p,height:l,type:o.type,colorSpace:o.colorSpace,material:s,renderer:a}),d=[];for(;p>1||l>1;){p=Math.max(1,(p+2-1)/2|0),l=Math.max(1,(l+2-1)/2|0);const e=new t.WebGLRenderTarget(p,l,{type:c.type,format:o.format,colorSpace:c.colorSpace,minFilter:t.NearestFilter,magFilter:t.NearestFilter,wrapS:t.ClampToEdgeWrapping,wrapT:t.ClampToEdgeWrapping,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});d.push(e)}p=o.image.width,l=o.image.height,d.forEach(e=>{p=Math.max(1,(p+2-1)/2|0),l=Math.max(1,(l+2-1)/2|0),c.renderTarget=e,c.render(),s.uniforms.map.value=e.texture,s.uniforms.u_srcResolution.value.x=p,s.uniforms.u_srcResolution.value.y=l});const m=c.toArray();return c.dispose(),d.forEach(e=>e.dispose()),[c.type===t.FloatType?m[0]:t.DataUtils.fromHalfFloat(m[0]),c.type===t.FloatType?m[1]:t.DataUtils.fromHalfFloat(m[1]),c.type===t.FloatType?m[2]:t.DataUtils.fromHalfFloat(m[2])]},e.getGainMap=d,e.getSDRRendition=h});
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monogrid/gainmap-js v3.5.0
|
|
3
|
+
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
|
+
*/
|
|
5
|
+
const t="urn:iso:std:iso:ts:21496:-1\0",n=4294967295,r=new Uint8Array(4),e=t=>{const r=[0,1,2].map(n=>[t.gainMapMin[n],t.gainMapMax[n],t.gamma[n],t.offsetSdr[n],t.offsetHdr[n]]),e=r.some(t=>t.some((t,n)=>t!==r[0][n])),a=e?3:1,s=new Uint8Array(21+40*a),o=new DataView(s.buffer);let i=4;o.setUint8(i++,64|(e?128:0));const f=(t,r)=>{const[e,a]=((t,r)=>{const e=r?2147483647:n;if(!Number.isFinite(t)||!r&&t<0||Math.abs(t)>e)throw new Error(`Cannot represent ${t} as an ${r?"signed":"unsigned"} ISO 21496-1 fraction`);const a=Math.min(n,Math.floor(e/Math.max(1,Math.abs(t))));return[Math.round(t*a),a]})(t,r);r?o.setInt32(i,e):o.setUint32(i,e),o.setUint32(i+4,a),i+=8};f(t.hdrCapacityMin,!1),f(t.hdrCapacityMax,!1);for(let t=0;t<a;t++){const[n,e,a,s,o]=r[t];f(n,!0),f(e,!0),f(a,!1),f(s,!0),f(o,!0)}return s},a=t=>{const n=new DataView(t.buffer,t.byteOffset,t.byteLength);let r=0;const e=()=>{const t=n.getUint16(r);return r+=2,t},a=()=>{const t=n.getUint32(r);return r+=4,t},s=e();if(0!==s)throw new Error(`Unsupported ISO 21496-1 minimum_version ${s}`);e();const o=n.getUint8(r++);if(4&o)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const i=128&o?3:1,f=8&o?a():void 0,h=t=>{const e=t?(()=>{const t=n.getInt32(r);return r+=4,t})():a(),s=f??a();if(0===s)throw new Error("Invalid ISO 21496-1 fraction with zero denominator");return e/s},c=h(!1),p=h(!1);if(c>p)throw new Error("ISO 21496-1 metadata with HDR base image is not supported");const u=[],d=[],w=[],m=[],M=[];for(let t=0;t<i;t++)u.push(h(!0)),d.push(h(!0)),w.push(h(!1)),m.push(h(!0)),M.push(h(!0));const g=t=>3===i?t:[t[0],t[0],t[0]];return{gainMapMin:g(u),gainMapMax:g(d),gamma:g(w),offsetSdr:g(m),offsetHdr:g(M),hdrCapacityMin:c,hdrCapacityMax:p}};export{t as I,r as a,a as d,e};
|
|
@@ -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
|
package/dist/libultrahdr.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.
|
|
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
|
|
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
|
package/dist/libultrahdr.min.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.
|
|
2
|
+
* @monogrid/gainmap-js v3.5.0
|
|
3
3
|
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
|
-
const
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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};
|