@monogrid/gainmap-js 3.1.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/CODE_OF_CONDUCT.md +1 -1
- package/CONTRIBUTING.md +1 -1
- package/README.md +113 -57
- package/dist/Loader-CsjVTcg5.js +424 -0
- package/dist/Loader-D4XqFES7.js +5 -0
- package/dist/{QuadRenderer-DuOPRGA4.js → QuadRenderer-BqJ2Q8P5.js} +39 -30
- package/dist/QuadRenderer-De5PMMtY.js +5 -0
- package/dist/{_commonjsHelpers-DeBGiDfT.js → _commonjsHelpers-C2Rq7Bzs.js} +2 -2
- package/dist/_commonjsHelpers-FnzxO7yL.js +5 -0
- package/dist/compress-HAw5HoXG.js +5 -0
- package/dist/{compress-B6OswAu8.js → compress-bMJEJ5JM.js} +4 -3
- package/dist/core/QuadRenderer.d.ts +2 -2
- package/dist/core/get-data-texture.d.ts +4 -3
- package/dist/core/types.d.ts +7 -1
- package/dist/decode/index.d.ts +1 -11
- package/dist/decode/shared/Loader.d.ts +59 -0
- package/dist/decode/shared/decode.d.ts +24 -0
- package/dist/decode/{extract.d.ts → shared/extract.d.ts} +4 -4
- package/dist/decode/shared/index.d.ts +8 -0
- package/dist/decode/shared/types.d.ts +53 -0
- package/dist/decode/{utils → shared/utils}/MPFExtractor.d.ts +1 -1
- package/dist/decode/{utils → shared/utils}/extractXMP.d.ts +1 -1
- package/dist/decode/{decode.d.ts → webgl/decode.d.ts} +6 -6
- package/dist/decode/webgl/index.d.ts +8 -0
- package/dist/decode/{loaders → webgl/loaders}/GainMapLoader.d.ts +5 -6
- package/dist/decode/{loaders → webgl/loaders}/HDRJPGLoader.d.ts +6 -7
- package/dist/decode/webgl/loaders/LoaderBaseWebGL.d.ts +20 -0
- package/dist/decode/{materials → webgl/materials}/GainMapDecoderMaterial.d.ts +2 -2
- package/dist/decode/webgpu/core/QuadRenderer.d.ts +153 -0
- package/dist/decode/webgpu/decode.d.ts +60 -0
- package/dist/decode/webgpu/index.d.ts +8 -0
- package/dist/decode/webgpu/loaders/GainMapLoader.d.ts +69 -0
- package/dist/decode/webgpu/loaders/HDRJPGLoader.d.ts +65 -0
- package/dist/decode/webgpu/loaders/LoaderBaseWebGPU.d.ts +20 -0
- package/dist/decode/webgpu/materials/GainMapDecoderMaterial.d.ts +78 -0
- package/dist/decode.js +45 -426
- package/dist/decode.min.js +5 -0
- package/dist/decode.umd.cjs +360 -314
- package/dist/decode.umd.min.cjs +5 -0
- package/dist/decode.webgpu.js +814 -0
- package/dist/decode.webgpu.min.js +5 -0
- package/dist/decode.webgpu.umd.cjs +1244 -0
- package/dist/decode.webgpu.umd.min.cjs +5 -0
- package/dist/encode/encode-and-compress.d.ts +4 -4
- package/dist/encode/encode.d.ts +3 -3
- package/dist/encode/find-texture-min-max.d.ts +4 -3
- package/dist/encode/types.d.ts +6 -5
- package/dist/encode.js +33 -12
- package/dist/encode.min.js +5 -0
- package/dist/encode.umd.cjs +70 -39
- package/dist/encode.umd.min.cjs +5 -0
- package/dist/libultrahdr/encode-jpeg-metadata.d.ts +6 -6
- package/dist/libultrahdr/jpeg-assembler.d.ts +41 -0
- package/dist/libultrahdr/jpeg-markers.d.ts +47 -0
- package/dist/libultrahdr/mpf-generator.d.ts +20 -0
- package/dist/libultrahdr/xmp-generator.d.ts +33 -0
- package/dist/libultrahdr.d.ts +0 -3
- package/dist/libultrahdr.js +548 -6598
- package/dist/libultrahdr.min.js +5 -0
- package/dist/libultrahdr.umd.cjs +633 -6686
- package/dist/libultrahdr.umd.min.cjs +5 -0
- package/dist/third-party.txt +301 -0
- package/dist/worker-interface.js +74 -64
- package/dist/worker-interface.min.js +5 -0
- package/dist/worker-interface.umd.cjs +73 -63
- package/dist/worker-interface.umd.min.cjs +5 -0
- package/dist/worker.js +103 -88
- package/dist/worker.min.js +5 -0
- package/dist/worker.umd.cjs +105 -89
- package/dist/worker.umd.min.cjs +5 -0
- package/package.json +79 -72
- package/dist/decode/loaders/LoaderBase.d.ts +0 -45
- package/dist/decode/types.d.ts +0 -42
- package/dist/libultrahdr/decode-jpeg-metadata.d.ts +0 -28
- package/dist/libultrahdr/library.d.ts +0 -9
- package/dist/libultrahdr-esm.wasm +0 -0
- package/libultrahdr-wasm/build/libultrahdr-debug.js +0 -7156
- package/libultrahdr-wasm/build/libultrahdr-debug.wasm +0 -0
- package/libultrahdr-wasm/build/libultrahdr-esm.js +0 -6633
- package/libultrahdr-wasm/build/libultrahdr-esm.wasm +0 -0
- package/libultrahdr-wasm/build/libultrahdr.d.ts +0 -30
- package/libultrahdr-wasm/build/libultrahdr.js +0 -6591
- package/libultrahdr-wasm/build/libultrahdr.wasm +0 -0
- /package/dist/decode/{errors → shared/errors}/GainMapNotFoundError.d.ts +0 -0
- /package/dist/decode/{errors → shared/errors}/XMPMetadataNotFoundError.d.ts +0 -0
- /package/dist/decode/{utils → shared/utils}/get-html-image-from-blob.d.ts +0 -0
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monogrid/gainmap-js v3.3.0
|
|
3
|
+
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
|
+
*/
|
|
5
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three"),require("three/webgpu"),require("three/tsl")):"function"==typeof define&&define.amd?define(["exports","three","three/webgpu","three/tsl"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@monogrid/gainmap-js"]={},e.three,e["three/webgpu"],e["three/tsl"])}(this,function(e,t,r,a){"use strict";function i(e){return r=>{const{sdr:a,gainMap:i,renderer:n}=r;a.colorSpace!==t.SRGBColorSpace&&(console.warn("SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically"),a.colorSpace=t.SRGBColorSpace),a.needsUpdate=!0,i.colorSpace!==t.LinearSRGBColorSpace&&(console.warn("Gainmap Colorspace needs to be *LinearSRGBColorSpace*, setting it automatically"),i.colorSpace=t.LinearSRGBColorSpace),i.needsUpdate=!0;const s=e.createMaterial({...r,sdr:a,gainMap:i});return e.createQuadRenderer({width:a.image.width,height:a.image.height,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:s,renderer:n,renderTargetOptions:r.renderTargetOptions})}}class n extends Error{}class s extends Error{}const o=(e,t,r)=>{const a=new RegExp(`${t}="([^"]*)"`,"i").exec(e);if(a)return a[1];const i=new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`,"i").exec(e);if(i){const e=i[1].match(/<rdf:li>([^<]*)<\/rdf:li>/g);return e&&3===e.length?e.map(e=>e.replace(/<\/?rdf:li>/g,"")):i[1].trim()}if(void 0!==r)return r;throw new Error(`Can't find ${t} in gainmap metadata`)},d=e=>{let t;t="undefined"!=typeof TextDecoder?(new TextDecoder).decode(e):e.toString();let r=t.indexOf("<x:xmpmeta");for(;-1!==r;){const e=t.indexOf("x:xmpmeta>",r),a=t.slice(r,e+10);try{const e=o(a,"hdrgm:GainMapMin","0"),t=o(a,"hdrgm:GainMapMax"),r=o(a,"hdrgm:Gamma","1"),i=o(a,"hdrgm:OffsetSDR","0.015625"),n=o(a,"hdrgm:OffsetHDR","0.015625"),s=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(a),d=s?s[1]:"0",p=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(a);if(!p)throw new Error("Incomplete gainmap metadata");const h=p[1];return{gainMapMin:Array.isArray(e)?e.map(e=>parseFloat(e)):[parseFloat(e),parseFloat(e),parseFloat(e)],gainMapMax:Array.isArray(t)?t.map(e=>parseFloat(e)):[parseFloat(t),parseFloat(t),parseFloat(t)],gamma:Array.isArray(r)?r.map(e=>parseFloat(e)):[parseFloat(r),parseFloat(r),parseFloat(r)],offsetSdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],offsetHdr:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],hdrCapacityMin:parseFloat(d),hdrCapacityMax:parseFloat(h)}}catch(e){}r=t.indexOf("<x:xmpmeta",e)}};class p{options;constructor(e){this.options={debug:!(!e||void 0===e.debug)&&e.debug,extractFII:!e||void 0===e.extractFII||e.extractFII,extractNonFII:!e||void 0===e.extractNonFII||e.extractNonFII}}extract(e){return new Promise((t,r)=>{const a=this.options.debug,i=new DataView(e.buffer);if(65496!==i.getUint16(0))return void r(new Error("Not a valid jpeg"));const n=i.byteLength;let s,o=2,d=0;for(;o<n;){if(++d>250)return void r(new Error(`Found no marker after ${d} loops 😵`));if(255!==i.getUint8(o))return void r(new Error(`Not a valid marker at offset 0x${o.toString(16)}, found: 0x${i.getUint8(o).toString(16)}`));if(s=i.getUint8(o+1),a&&console.log(`Marker: ${s.toString(16)}`),226===s){a&&console.log("Found APP2 marker (0xffe2)");const e=o+4;if(1297106432===i.getUint32(e)){const a=e+4;let n;if(18761===i.getUint16(a))n=!1;else{if(19789!==i.getUint16(a))return void r(new Error("No valid endianness marker found in TIFF header"));n=!0}if(42!==i.getUint16(a+2,!n))return void r(new Error("Not valid TIFF data! (no 0x002A marker)"));const s=i.getUint32(a+4,!n);if(s<8)return void r(new Error("Not valid TIFF data! (First offset less than 8)"));const o=a+s,d=i.getUint16(o,!n),p=o+2;let h=0;for(let e=p;e<p+12*d;e+=12)45057===i.getUint16(e,!n)&&(h=i.getUint32(e+8,!n));const g=o+2+12*d+4,l=[];for(let e=g;e<g+16*h;e+=16){const t={MPType:i.getUint32(e,!n),size:i.getUint32(e+4,!n),dataOffset:i.getUint32(e+8,!n),dependantImages:i.getUint32(e+12,!n),start:-1,end:-1,isFII:!1};t.dataOffset?(t.start=a+t.dataOffset,t.isFII=!1):(t.start=0,t.isFII=!0),t.end=t.start+t.size,l.push(t)}if(this.options.extractNonFII&&l.length){const e=new Blob([i]),r=[];for(const t of l){if(t.isFII&&!this.options.extractFII)continue;const a=e.slice(t.start,t.end+1,"image/jpeg");r.push(a)}t(r)}}}o+=2+i.getUint16(o+2)}})}}const h=async e=>{const t=d(e);if(!t)throw new s("Gain map XMP metadata not found");const r=new p({extractFII:!0,extractNonFII:!0}),a=await r.extract(e);if(2!==a.length)throw new n("Gain map recovery image not found");return{sdr:new Uint8Array(await a[0].arrayBuffer()),gainMap:new Uint8Array(await a[1].arrayBuffer()),metadata:t}},g=e=>new Promise((t,r)=>{const a=document.createElement("img");a.onload=()=>{t(a)},a.onerror=e=>{r(e)},a.src=URL.createObjectURL(e)});class l extends t.Loader{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,r){super(r),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new t.LoadingManager}setRenderer(e){return this._renderer=e,this}setRenderTargetOptions(e){return this._renderTargetOptions=e,this}prepareQuadRenderer(){this._renderer||console.warn("WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer.");const e=this._config.createMaterial({gainMapMax:[1,1,1],gainMapMin:[0,0,0],gamma:[1,1,1],offsetHdr:[1,1,1],offsetSdr:[1,1,1],hdrCapacityMax:1,hdrCapacityMin:0,maxDisplayBoost:1,gainMap:new t.Texture,sdr:new t.Texture});return this._config.createQuadRenderer({width:16,height:16,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}async processImages(e,t,r){const a=t?new Blob([t],{type:"image/jpeg"}):void 0,i=new Blob([e],{type:"image/jpeg"});let n,s,o=!1;if("undefined"==typeof createImageBitmap){const e=await Promise.all([a?g(a):Promise.resolve(void 0),g(i)]);s=e[0],n=e[1],o="flipY"===r}else{const e=await Promise.all([a?createImageBitmap(a,{imageOrientation:r||"flipY"}):Promise.resolve(void 0),createImageBitmap(i,{imageOrientation:r||"flipY"})]);s=e[0],n=e[1]}return{sdrImage:n,gainMapImage:s,needsFlip:o}}createTextures(e,r,a){const i=new t.Texture(r||new ImageData(2,2),t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.LinearSRGBColorSpace);i.flipY=a,i.needsUpdate=!0;const n=new t.Texture(e,t.UVMapping,t.ClampToEdgeWrapping,t.ClampToEdgeWrapping,t.LinearFilter,t.LinearMipMapLinearFilter,t.RGBAFormat,t.UnsignedByteType,1,t.SRGBColorSpace);return n.flipY=a,n.needsUpdate=!0,{gainMap:i,sdr:n}}updateQuadRenderer(e,t,r,a,i){e.width=t.width,e.height=t.height,e.material.gainMap=r,e.material.sdr=a,e.material.gainMapMin=i.gainMapMin,e.material.gainMapMax=i.gainMapMax,e.material.offsetHdr=i.offsetHdr,e.material.offsetSdr=i.offsetSdr,e.material.gamma=i.gamma,e.material.hdrCapacityMin=i.hdrCapacityMin,e.material.hdrCapacityMax=i.hdrCapacityMax,e.material.maxDisplayBoost=Math.pow(2,i.hdrCapacityMax),e.material.needsUpdate=!0}}class m{_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 t={format:r.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:r.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:r.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:r.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:r.ClampToEdgeWrapping};this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=m.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new r.Scene,this._camera=new r.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(),this._quad=new r.Mesh(new r.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new r.RenderTarget(this.width,this.height,t),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:r.UVMapping}static instantiateRenderer(){const e=new r.WebGPURenderer;return e.setSize(128,128),e}render=async()=>{this._renderer.hasInitialized()||await this._renderer.init(),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)};async toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");return await this._renderer.readRenderTargetPixelsAsync(this._renderTarget,0,0,this._width,this._height)}async toDataTexture(e){const t=new r.DataTexture(await this.toArray(),this.width,this.height,r.RGBAFormat,this._type,e?.mapping||r.UVMapping,e?.wrapS||r.ClampToEdgeWrapping,e?.wrapT||r.ClampToEdgeWrapping,e?.magFilter||r.LinearFilter,e?.minFilter||r.LinearFilter,e?.anisotropy||1,r.LinearSRGBColorSpace);return t.flipY=void 0===e?.flipY||e?.flipY,t.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,t}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&this._renderer.dispose()}dispose(e){e&&this.renderTarget.dispose(),this.material instanceof r.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof r.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof r.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose(),this.disposeOnDemandRenderer()}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 c=a.vec3(-65504,-65504,-65504),f=a.vec3(65504,65504,65504);class u extends r.MeshBasicNodeMaterial{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;_gammaUniform;_offsetHdrUniform;_offsetSdrUniform;_gainMapMinUniform;_gainMapMaxUniform;_weightFactorUniform;_sdrTexture;_gainMapTexture;constructor({gamma:e,offsetHdr:t,offsetSdr:i,gainMapMin:n,gainMapMax:s,maxDisplayBoost:o,hdrCapacityMin:d,hdrCapacityMax:p,sdr:h,gainMap:g}){super(),this.name="GainMapDecoderMaterial",this.blending=r.NoBlending,this.depthTest=!1,this.depthWrite=!1,this._sdrTexture=a.texture(h),this._gainMapTexture=a.texture(g),this._gammaUniform=a.uniform(a.vec3(1/e[0],1/e[1],1/e[2])),this._offsetHdrUniform=a.uniform(a.vec3(t[0],t[1],t[2])),this._offsetSdrUniform=a.uniform(a.vec3(i[0],i[1],i[2])),this._gainMapMinUniform=a.uniform(a.vec3(n[0],n[1],n[2])),this._gainMapMaxUniform=a.uniform(a.vec3(s[0],s[1],s[2]));const l=(Math.log2(o)-d)/(p-d);this._weightFactorUniform=a.uniform(l),this._maxDisplayBoost=o,this._hdrCapacityMin=d,this._hdrCapacityMax=p;const m=this._sdrTexture.rgb,u=this._gainMapTexture.rgb,M=a.pow(u,this._gammaUniform),_=a.sub(a.float(1),M),y=a.add(a.mul(this._gainMapMinUniform,_),a.mul(this._gainMapMaxUniform,M)),x=a.sub(a.mul(a.add(m,this._offsetSdrUniform),a.exp2(a.mul(y,this._weightFactorUniform))),this._offsetHdrUniform),w=a.max(c,a.min(f,x));this.colorNode=w}get sdr(){return this._sdrTexture.value}set sdr(e){this._sdrTexture.value=e}get gainMap(){return this._gainMapTexture.value}set gainMap(e){this._gainMapTexture.value=e}get offsetHdr(){return[this._offsetHdrUniform.value.x,this._offsetHdrUniform.value.y,this._offsetHdrUniform.value.z]}set offsetHdr(e){this._offsetHdrUniform.value.x=e[0],this._offsetHdrUniform.value.y=e[1],this._offsetHdrUniform.value.z=e[2]}get offsetSdr(){return[this._offsetSdrUniform.value.x,this._offsetSdrUniform.value.y,this._offsetSdrUniform.value.z]}set offsetSdr(e){this._offsetSdrUniform.value.x=e[0],this._offsetSdrUniform.value.y=e[1],this._offsetSdrUniform.value.z=e[2]}get gainMapMin(){return[this._gainMapMinUniform.value.x,this._gainMapMinUniform.value.y,this._gainMapMinUniform.value.z]}set gainMapMin(e){this._gainMapMinUniform.value.x=e[0],this._gainMapMinUniform.value.y=e[1],this._gainMapMinUniform.value.z=e[2]}get gainMapMax(){return[this._gainMapMaxUniform.value.x,this._gainMapMaxUniform.value.y,this._gainMapMaxUniform.value.z]}set gainMapMax(e){this._gainMapMaxUniform.value.x=e[0],this._gainMapMaxUniform.value.y=e[1],this._gainMapMaxUniform.value.z=e[2]}get gamma(){return[1/this._gammaUniform.value.x,1/this._gammaUniform.value.y,1/this._gammaUniform.value.z]}set gamma(e){this._gammaUniform.value.x=1/e[0],this._gammaUniform.value.y=1/e[1],this._gammaUniform.value.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this._weightFactorUniform.value=Math.max(0,Math.min(1,e))}}const M=i({renderer:r.WebGPURenderer,createMaterial:e=>new u(e),createQuadRenderer:e=>new m(e)});class _ extends l{constructor(e,t){super({renderer:e,createMaterial:e=>new u(e),createQuadRenderer:e=>new m(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:n,needsFlip:s}=await this.processImages(r,a,"from-image"),{gainMap:o,sdr:d}=this.createTextures(i,n,s);this.updateQuadRenderer(e,i,o,d,t),await e.render()}}class y extends _{load(e,t,a,i){const o=this.prepareQuadRenderer(),d=new r.FileLoader(this._internalLoadingManager);return d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setPath(this.path),d.setWithCredentials(this.withCredentials),this.manager.itemStart(e),d.load(e,async r=>{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const a=new Uint8Array(r);let d,p,g;try{const e=await h(a);d=e.sdr,p=e.gainMap,g=e.metadata}catch(t){if(!(t instanceof s||t instanceof n))throw t;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),g={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},d=a}try{await this.render(o,g,d.buffer,p?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof i&&i(t),void o.disposeOnDemandRenderer()}"function"==typeof t&&t(o),this.manager.itemEnd(e),o.disposeOnDemandRenderer()},a,t=>{this.manager.itemError(e),"function"==typeof i&&i(t)}),o}}e.GainMapDecoderMaterial=u,e.GainMapLoader=class extends _{load([e,t,a],i,n,s){const o=this.prepareQuadRenderer();let d,p,h;const g=async()=>{if(d&&p&&h){try{await this.render(o,h,d,p)}catch(r){return this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(a),"function"==typeof s&&s(r),void o.disposeOnDemandRenderer()}"function"==typeof i&&i(o),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(a),o.disposeOnDemandRenderer()}};let l=!0,m=0,c=0,f=!0,u=0,M=0,_=!0,y=0,x=0;const w=()=>{if("function"==typeof n){n(new ProgressEvent("progress",{lengthComputable:l&&f&&_,loaded:c+M+x,total:m+u+y}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(a);const T=new r.FileLoader(this._internalLoadingManager);T.setResponseType("arraybuffer"),T.setRequestHeader(this.requestHeader),T.setPath(this.path),T.setWithCredentials(this.withCredentials),T.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");d=e,await g()},e=>{l=e.lengthComputable,c=e.loaded,m=e.total,w()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const v=new r.FileLoader(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(t,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");p=e,await g()},e=>{f=e.lengthComputable,M=e.loaded,u=e.total,w()},e=>{this.manager.itemError(t),"function"==typeof s&&s(e)});const U=new r.FileLoader(this._internalLoadingManager);return U.setRequestHeader(this.requestHeader),U.setPath(this.path),U.setWithCredentials(this.withCredentials),U.load(a,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");h=JSON.parse(e),await g()},e=>{_=e.lengthComputable,x=e.loaded,y=e.total,w()},e=>{this.manager.itemError(a),"function"==typeof s&&s(e)}),o}},e.GainMapNotFoundError=n,e.HDRJPGLoader=y,e.JPEGRLoader=y,e.LoaderBaseShared=l,e.MPFExtractor=p,e.QuadRenderer=m,e.XMPMetadataNotFoundError=s,e.createDecodeFunction=i,e.decode=async e=>{if(!e.renderer)throw new Error("Renderer is required for decode function");const t=M({...e,renderer:e.renderer});try{await t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t},e.extractGainmapFromJPEG=h,e.extractXMP=d});
|
|
@@ -21,7 +21,7 @@ import { CompressedImage, EncodingParametersWithCompression } from './types';
|
|
|
21
21
|
* const image = await loader.loadAsync('image.exr')
|
|
22
22
|
*
|
|
23
23
|
* // find RAW RGB Max value of a texture
|
|
24
|
-
* const textureMax =
|
|
24
|
+
* const textureMax = findTextureMinMax(image)
|
|
25
25
|
*
|
|
26
26
|
* // Encode the gainmap
|
|
27
27
|
* const encodingResult = await encodeAndCompress({
|
|
@@ -32,7 +32,7 @@ import { CompressedImage, EncodingParametersWithCompression } from './types';
|
|
|
32
32
|
*
|
|
33
33
|
* // embed the compressed images + metadata into a single
|
|
34
34
|
* // JPEG file
|
|
35
|
-
* const jpeg =
|
|
35
|
+
* const jpeg = encodeJPEGMetadata({
|
|
36
36
|
* ...encodingResult,
|
|
37
37
|
* sdr: encodingResult.sdr,
|
|
38
38
|
* gainMap: encodingResult.gainMap
|
|
@@ -47,8 +47,8 @@ import { CompressedImage, EncodingParametersWithCompression } from './types';
|
|
|
47
47
|
export declare const encodeAndCompress: (params: EncodingParametersWithCompression) => Promise<{
|
|
48
48
|
sdr: CompressedImage;
|
|
49
49
|
gainMap: CompressedImage;
|
|
50
|
-
rawSDR: Uint8ClampedArray
|
|
51
|
-
rawGainMap: Uint8ClampedArray
|
|
50
|
+
rawSDR: Uint8ClampedArray<ArrayBufferLike>;
|
|
51
|
+
rawGainMap: Uint8ClampedArray<ArrayBufferLike>;
|
|
52
52
|
gamma: [number, number, number];
|
|
53
53
|
hdrCapacityMin: number;
|
|
54
54
|
hdrCapacityMax: number;
|
package/dist/encode/encode.d.ts
CHANGED
|
@@ -28,7 +28,7 @@ import { EncodingParametersBase } from './types';
|
|
|
28
28
|
* const image = await loader.loadAsync('image.exr')
|
|
29
29
|
*
|
|
30
30
|
* // find RAW RGB Max value of a texture
|
|
31
|
-
* const textureMax =
|
|
31
|
+
* const textureMax = findTextureMinMax(image)
|
|
32
32
|
*
|
|
33
33
|
* // Encode the gainmap
|
|
34
34
|
* const encodingResult = encode({
|
|
@@ -54,8 +54,8 @@ import { EncodingParametersBase } from './types';
|
|
|
54
54
|
* @returns
|
|
55
55
|
*/
|
|
56
56
|
export declare const encode: (params: EncodingParametersBase) => {
|
|
57
|
-
sdr: import("../
|
|
58
|
-
gainMap: import("../
|
|
57
|
+
sdr: import("../core").QuadRenderer<1009, import(".").SDRMaterial>;
|
|
58
|
+
gainMap: import("../core").QuadRenderer<1009, import(".").GainMapEncoderMaterial>;
|
|
59
59
|
hdr: import("three").DataTexture;
|
|
60
60
|
getMetadata: () => GainMapMetadata;
|
|
61
61
|
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { DataTexture, WebGLRenderer } from 'three';
|
|
2
|
-
import { EXR } from 'three/examples/jsm/loaders/EXRLoader';
|
|
3
|
-
import {
|
|
2
|
+
import { EXR } from 'three/examples/jsm/loaders/EXRLoader.js';
|
|
3
|
+
import { HDR } from 'three/examples/jsm/loaders/HDRLoader.js';
|
|
4
|
+
import { RGBE } from 'three/examples/jsm/loaders/RGBELoader.js';
|
|
4
5
|
/**
|
|
5
6
|
*
|
|
6
7
|
* @category Utility
|
|
@@ -11,4 +12,4 @@ import { RGBE } from 'three/examples/jsm/loaders/RGBELoader';
|
|
|
11
12
|
* @param renderer
|
|
12
13
|
* @returns
|
|
13
14
|
*/
|
|
14
|
-
export declare const findTextureMinMax: (image: EXR | RGBE | DataTexture, mode?: "min" | "max", renderer?: WebGLRenderer) => number[];
|
|
15
|
+
export declare const findTextureMinMax: (image: EXR | RGBE | HDR | DataTexture, mode?: "min" | "max", renderer?: WebGLRenderer) => number[];
|
package/dist/encode/types.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type DataTexture, ToneMapping, WebGLRenderer } from 'three';
|
|
2
|
-
import { type EXR } from 'three/examples/jsm/loaders/EXRLoader';
|
|
3
|
-
import { type
|
|
2
|
+
import { type EXR } from 'three/examples/jsm/loaders/EXRLoader.js';
|
|
3
|
+
import { type HDR } from 'three/examples/jsm/loaders/HDRLoader.js';
|
|
4
|
+
import { type RGBE } from 'three/examples/jsm/loaders/RGBELoader.js';
|
|
4
5
|
import { QuadRendererTextureOptions } from '../decode';
|
|
5
6
|
import { WorkerInterfaceImplementation } from '../worker-types';
|
|
6
7
|
/**
|
|
@@ -70,7 +71,7 @@ export type EncodingParametersBase = GainmapEncodingParameters & {
|
|
|
70
71
|
/**
|
|
71
72
|
* Input image for encoding, must be an HDR image
|
|
72
73
|
*/
|
|
73
|
-
image: EXR | RGBE | DataTexture;
|
|
74
|
+
image: EXR | RGBE | HDR | DataTexture;
|
|
74
75
|
/**
|
|
75
76
|
* Optional WebGLRenderer
|
|
76
77
|
* @remarks
|
|
@@ -139,7 +140,7 @@ export type CompressOptions = {
|
|
|
139
140
|
* @group Compression
|
|
140
141
|
*/
|
|
141
142
|
export type CompressedImage = {
|
|
142
|
-
data: Uint8Array
|
|
143
|
+
data: Uint8Array<ArrayBuffer>;
|
|
143
144
|
mimeType: CompressionMimeType;
|
|
144
145
|
width: number;
|
|
145
146
|
height: number;
|
|
@@ -157,7 +158,7 @@ export type CompressParameters = CompressOptions & ({
|
|
|
157
158
|
/**
|
|
158
159
|
* Encoded Image Data with a mimeType
|
|
159
160
|
*/
|
|
160
|
-
source: Uint8Array | Uint8ClampedArray
|
|
161
|
+
source: Uint8Array<ArrayBuffer> | Uint8ClampedArray<ArrayBuffer>;
|
|
161
162
|
/**
|
|
162
163
|
* mimeType of the encoded input
|
|
163
164
|
*/
|
package/dist/encode.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.
|
|
3
|
-
* With ❤️, by MONOGRID <
|
|
2
|
+
* @monogrid/gainmap-js v3.3.0
|
|
3
|
+
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { c as compress } from './compress-
|
|
7
|
-
import { DataTexture, RGBAFormat, UVMapping, RepeatWrapping, LinearFilter, LinearSRGBColorSpace, ShaderMaterial,
|
|
8
|
-
import { Q as QuadRenderer } from './QuadRenderer-
|
|
6
|
+
import { c as compress } from './compress-bMJEJ5JM.js';
|
|
7
|
+
import { DataTexture, RGBAFormat, UVMapping, RepeatWrapping, LinearFilter, LinearSRGBColorSpace, ShaderMaterial, NoBlending, Vector3, UnsignedByteType, ACESFilmicToneMapping, LinearToneMapping, CineonToneMapping, ReinhardToneMapping, SRGBColorSpace, AlphaFormat, RGBFormat, DepthFormat, DepthStencilFormat, RedFormat, RedIntegerFormat, RGFormat, RGIntegerFormat, RGBIntegerFormat, RGBAIntegerFormat, Vector2, WebGLRenderTarget, ClampToEdgeWrapping, NearestFilter, DataUtils, FloatType } from 'three';
|
|
8
|
+
import { Q as QuadRenderer } from './QuadRenderer-BqJ2Q8P5.js';
|
|
9
9
|
|
|
10
10
|
/**
|
|
11
11
|
* Utility function to obtain a `DataTexture` from various input formats
|
|
@@ -75,6 +75,11 @@ void main() {
|
|
|
75
75
|
* @group Materials
|
|
76
76
|
*/
|
|
77
77
|
class GainMapEncoderMaterial extends ShaderMaterial {
|
|
78
|
+
_minContentBoost;
|
|
79
|
+
_maxContentBoost;
|
|
80
|
+
_offsetSdr;
|
|
81
|
+
_offsetHdr;
|
|
82
|
+
_gamma;
|
|
78
83
|
/**
|
|
79
84
|
*
|
|
80
85
|
* @param params
|
|
@@ -339,6 +344,12 @@ void main() {
|
|
|
339
344
|
* @group Materials
|
|
340
345
|
*/
|
|
341
346
|
class SDRMaterial extends ShaderMaterial {
|
|
347
|
+
_brightness = 0;
|
|
348
|
+
_contrast = 1;
|
|
349
|
+
_saturation = 1;
|
|
350
|
+
_exposure = 1;
|
|
351
|
+
_toneMapping;
|
|
352
|
+
_map;
|
|
342
353
|
/**
|
|
343
354
|
*
|
|
344
355
|
* @param params
|
|
@@ -359,10 +370,6 @@ class SDRMaterial extends ShaderMaterial {
|
|
|
359
370
|
depthTest: false,
|
|
360
371
|
depthWrite: false
|
|
361
372
|
});
|
|
362
|
-
this._brightness = 0;
|
|
363
|
-
this._contrast = 1;
|
|
364
|
-
this._saturation = 1;
|
|
365
|
-
this._exposure = 1;
|
|
366
373
|
this._map = map;
|
|
367
374
|
this.toneMapping = this._toneMapping = toneMapping || ACESFilmicToneMapping;
|
|
368
375
|
this.needsUpdate = true;
|
|
@@ -486,7 +493,7 @@ const getSDRRendition = (hdrTexture, renderer, toneMapping, renderTargetOptions)
|
|
|
486
493
|
* const image = await loader.loadAsync('image.exr')
|
|
487
494
|
*
|
|
488
495
|
* // find RAW RGB Max value of a texture
|
|
489
|
-
* const textureMax =
|
|
496
|
+
* const textureMax = findTextureMinMax(image)
|
|
490
497
|
*
|
|
491
498
|
* // Encode the gainmap
|
|
492
499
|
* const encodingResult = encode({
|
|
@@ -561,7 +568,7 @@ const encode = (params) => {
|
|
|
561
568
|
* const image = await loader.loadAsync('image.exr')
|
|
562
569
|
*
|
|
563
570
|
* // find RAW RGB Max value of a texture
|
|
564
|
-
* const textureMax =
|
|
571
|
+
* const textureMax = findTextureMinMax(image)
|
|
565
572
|
*
|
|
566
573
|
* // Encode the gainmap
|
|
567
574
|
* const encodingResult = await encodeAndCompress({
|
|
@@ -572,7 +579,7 @@ const encode = (params) => {
|
|
|
572
579
|
*
|
|
573
580
|
* // embed the compressed images + metadata into a single
|
|
574
581
|
* // JPEG file
|
|
575
|
-
* const jpeg =
|
|
582
|
+
* const jpeg = encodeJPEGMetadata({
|
|
576
583
|
* ...encodingResult,
|
|
577
584
|
* sdr: encodingResult.sdr,
|
|
578
585
|
* gainMap: encodingResult.gainMap
|
|
@@ -701,6 +708,20 @@ void main() {
|
|
|
701
708
|
*/
|
|
702
709
|
const findTextureMinMax = (image, mode = 'max', renderer) => {
|
|
703
710
|
const srcTex = getDataTexture(image);
|
|
711
|
+
// check if texture has a valid format
|
|
712
|
+
if (srcTex.format !== AlphaFormat &&
|
|
713
|
+
srcTex.format !== RGBFormat &&
|
|
714
|
+
srcTex.format !== RGBAFormat &&
|
|
715
|
+
srcTex.format !== DepthFormat &&
|
|
716
|
+
srcTex.format !== DepthStencilFormat &&
|
|
717
|
+
srcTex.format !== RedFormat &&
|
|
718
|
+
srcTex.format !== RedIntegerFormat &&
|
|
719
|
+
srcTex.format !== RGFormat &&
|
|
720
|
+
srcTex.format !== RGIntegerFormat &&
|
|
721
|
+
srcTex.format !== RGBIntegerFormat &&
|
|
722
|
+
srcTex.format !== RGBAIntegerFormat) {
|
|
723
|
+
throw new Error('Unsupported texture format');
|
|
724
|
+
}
|
|
704
725
|
const cellSize = 2;
|
|
705
726
|
const mat = new ShaderMaterial({
|
|
706
727
|
vertexShader,
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monogrid/gainmap-js v3.3.0
|
|
3
|
+
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
|
+
*/
|
|
5
|
+
import{c as e}from"./compress-HAw5HoXG.js";import{DataTexture as n,RGBAFormat as t,UVMapping as r,RepeatWrapping as a,LinearFilter as o,LinearSRGBColorSpace as i,ShaderMaterial as s,NoBlending as m,Vector3 as c,UnsignedByteType as p,ACESFilmicToneMapping as d,LinearToneMapping as l,CineonToneMapping as u,ReinhardToneMapping as f,SRGBColorSpace as h,AlphaFormat as g,RGBFormat as v,DepthFormat as M,DepthStencilFormat as x,RedFormat as _,RedIntegerFormat as C,RGFormat as y,RGIntegerFormat as w,RGBIntegerFormat as T,RGBAIntegerFormat as S,Vector2 as A,WebGLRenderTarget as U,ClampToEdgeWrapping as E,NearestFilter as I,DataUtils as N,FloatType as b}from"three";import{Q as L}from"./QuadRenderer-De5PMMtY.js";const O=e=>{let s;if(e instanceof n){if(!(e.image.data instanceof Uint16Array||e.image.data instanceof Float32Array))throw new Error("Provided image is not HDR");s=e}else s=new n(e.data,e.width,e.height,"format"in e?e.format:t,e.type,r,a,a,o,o,1,"colorSpace"in e&&"srgb"===e.colorSpace?e.colorSpace:i),"header"in e&&"gamma"in e&&(s.flipY=!0),s.needsUpdate=!0;return s};class R extends s{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:e,hdr:n,offsetSdr:t,offsetHdr:r,maxContentBoost:a,minContentBoost:o,gamma:i}){if(!a)throw new Error("maxContentBoost is required");if(!e)throw new Error("sdr is required");if(!n)throw new Error("hdr is required");const s=i||[1,1,1],p=t||[1/64,1/64,1/64],d=r||[1/64,1/64,1/64],l=o||1,u=Math.max(a,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 c).fromArray(s)},offsetSdr:{value:(new c).fromArray(p)},offsetHdr:{value:(new c).fromArray(d)},minLog2:{value:Math.log2(l)},maxLog2:{value:Math.log2(u)}},blending:m,depthTest:!1,depthWrite:!1}),this._minContentBoost=l,this._maxContentBoost=u,this._offsetSdr=p,this._offsetHdr=d,this._gamma=s,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(e){this._gamma=e,this.uniforms.gamma.value=(new c).fromArray(e)}get offsetHdr(){return this._offsetHdr}set offsetHdr(e){this._offsetHdr=e,this.uniforms.offsetHdr.value=(new c).fromArray(e)}get offsetSdr(){return this._offsetSdr}set offsetSdr(e){this._offsetSdr=e,this.uniforms.offsetSdr.value=(new c).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:t,renderer:r}=e,a=O(n),o=new R({...e,sdr:t.renderTarget.texture,hdr:a}),s=new L({width:a.image.width,height:a.image.height,type:p,colorSpace:i,material:o,renderer:r,renderTargetOptions:e.renderTargetOptions});try{s.render()}catch(e){throw s.disposeOnDemandRenderer(),e}return s};class B extends s{_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\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:m,depthTest:!1,depthWrite:!1}),this._map=e,this.toneMapping=this._toneMapping=n||d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(e){let n=!1;switch(e){case d:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",n=!0;break;case f:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",n=!0;break;case u:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",n=!0;break;case l:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",n=!0;break;default:console.error(`Unsupported toneMapping: ${e}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=l}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 D=(e,n,t,r)=>{e.needsUpdate=!0;const a=new L({width:e.image.width,height:e.image.height,type:p,colorSpace:h,material:new B({map:e,toneMapping:t}),renderer:n,renderTargetOptions:r});try{a.render()}catch(e){throw a.disposeOnDemandRenderer(),e}return a},F=e=>{const{image:n,renderer:t}=e,r=O(n),a=D(r,t,e.toneMapping,e.renderTargetOptions),o=P({...e,image:r,sdr:a,renderer:a.renderer});return{sdr:a,gainMap:o,hdr:r,getMetadata:()=>({gainMapMax:o.material.gainMapMax,gainMapMin:o.material.gainMapMin,gamma:o.material.gamma,hdrCapacityMax:o.material.hdrCapacityMax,hdrCapacityMin:o.material.hdrCapacityMin,offsetHdr:o.material.offsetHdr,offsetSdr:o.material.offsetSdr})}},H=async n=>{const t=F(n),{mimeType:r,quality:a,flipY:o,withWorker:i}=n;let s,m,c;const p=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:p,mimeType:r,quality:a,flipY:o}),i.compress({source:d,mimeType:r,quality:a,flipY:o})]);s=e,m=e[0].source,c=e[1].source}else s=await Promise.all([e({source:p,mimeType:r,quality:a,flipY:o}),e({source:d,mimeType:r,quality:a,flipY:o})]),m=p.data,c=d.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:m,rawGainMap:c}},G=(e,n="max",r)=>{const a=O(e);if(a.format!==g&&a.format!==v&&a.format!==t&&a.format!==M&&a.format!==x&&a.format!==_&&a.format!==C&&a.format!==y&&a.format!==w&&a.format!==T&&a.format!==S)throw new Error("Unsupported texture format");const o=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 A(a.image.width,a.image.height)},map:{value:a}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:n,INITIAL_VALUE:"max"===n?0:65504}});a.needsUpdate=!0,o.needsUpdate=!0;let i=a.image.width,m=a.image.height;const c=new L({width:i,height:m,type:a.type,colorSpace:a.colorSpace,material:o,renderer:r}),p=[];for(;i>1||m>1;){i=Math.max(1,(i+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0);const e=new U(i,m,{type:c.type,format:a.format,colorSpace:c.colorSpace,minFilter:I,magFilter:I,wrapS:E,wrapT:E,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});p.push(e)}i=a.image.width,m=a.image.height,p.forEach(e=>{i=Math.max(1,(i+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0),c.renderTarget=e,c.render(),o.uniforms.map.value=e.texture,o.uniforms.u_srcResolution.value.x=i,o.uniforms.u_srcResolution.value.y=m});const d=c.toArray();return c.dispose(),p.forEach(e=>e.dispose()),[c.type===b?d[0]:N.fromHalfFloat(d[0]),c.type===b?d[1]:N.fromHalfFloat(d[1]),c.type===b?d[2]:N.fromHalfFloat(d[2])]};export{R as GainMapEncoderMaterial,B as SDRMaterial,e as compress,F as encode,H as encodeAndCompress,G as findTextureMinMax,P as getGainMap,D as getSDRRendition};
|
package/dist/encode.umd.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @monogrid/gainmap-js v3.
|
|
3
|
-
* With ❤️, by MONOGRID <
|
|
2
|
+
* @monogrid/gainmap-js v3.3.0
|
|
3
|
+
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
(function (global, factory) {
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
*/
|
|
21
21
|
const canvasToBlob = async (canvas, mimeType, quality) => {
|
|
22
22
|
if (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
|
|
23
|
-
return canvas.convertToBlob({ type: mimeType, quality: quality
|
|
23
|
+
return canvas.convertToBlob({ type: mimeType, quality: quality });
|
|
24
24
|
}
|
|
25
25
|
else if (canvas instanceof HTMLCanvasElement) {
|
|
26
26
|
return new Promise((resolve, reject) => {
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
resolve(res);
|
|
30
30
|
else
|
|
31
31
|
reject(new Error('Failed to convert canvas to blob'));
|
|
32
|
-
}, mimeType, quality
|
|
32
|
+
}, mimeType, quality);
|
|
33
33
|
});
|
|
34
34
|
}
|
|
35
35
|
/* istanbul ignore next
|
|
@@ -52,7 +52,6 @@
|
|
|
52
52
|
if (typeof createImageBitmap === 'undefined')
|
|
53
53
|
throw new Error('createImageBitmap() not supported.');
|
|
54
54
|
const { source, mimeType, quality, flipY } = params;
|
|
55
|
-
// eslint-disable-next-line no-undef
|
|
56
55
|
let imageBitmapSource;
|
|
57
56
|
if ((source instanceof Uint8Array || source instanceof Uint8ClampedArray) && 'sourceMimeType' in params) {
|
|
58
57
|
imageBitmapSource = new Blob([source], { type: params.sourceMimeType });
|
|
@@ -75,6 +74,8 @@
|
|
|
75
74
|
canvas.width = width;
|
|
76
75
|
canvas.height = height;
|
|
77
76
|
}
|
|
77
|
+
// apparently we do need to assert the type here for npx tsc to be happy
|
|
78
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
|
|
78
79
|
const ctx = canvas.getContext('2d');
|
|
79
80
|
if (!ctx)
|
|
80
81
|
throw new Error('Failed to create canvas Context');
|
|
@@ -188,29 +189,24 @@
|
|
|
188
189
|
* @group Core
|
|
189
190
|
*/
|
|
190
191
|
class QuadRenderer {
|
|
192
|
+
_renderer;
|
|
193
|
+
_rendererIsDisposable = false;
|
|
194
|
+
_material;
|
|
195
|
+
_scene;
|
|
196
|
+
_camera;
|
|
197
|
+
_quad;
|
|
198
|
+
_renderTarget;
|
|
199
|
+
_width;
|
|
200
|
+
_height;
|
|
201
|
+
_type;
|
|
202
|
+
_colorSpace;
|
|
203
|
+
_supportsReadPixels = true;
|
|
191
204
|
/**
|
|
192
205
|
* Constructs a new QuadRenderer
|
|
193
206
|
*
|
|
194
207
|
* @param options Parameters for this QuadRenderer
|
|
195
208
|
*/
|
|
196
209
|
constructor(options) {
|
|
197
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
|
|
198
|
-
this._rendererIsDisposable = false;
|
|
199
|
-
this._supportsReadPixels = true;
|
|
200
|
-
/**
|
|
201
|
-
* Renders the input texture using the specified material
|
|
202
|
-
*/
|
|
203
|
-
this.render = () => {
|
|
204
|
-
this._renderer.setRenderTarget(this._renderTarget);
|
|
205
|
-
try {
|
|
206
|
-
this._renderer.render(this._scene, this._camera);
|
|
207
|
-
}
|
|
208
|
-
catch (e) {
|
|
209
|
-
this._renderer.setRenderTarget(null);
|
|
210
|
-
throw e;
|
|
211
|
-
}
|
|
212
|
-
this._renderer.setRenderTarget(null);
|
|
213
|
-
};
|
|
214
210
|
this._width = options.width;
|
|
215
211
|
this._height = options.height;
|
|
216
212
|
this._type = options.type;
|
|
@@ -223,13 +219,13 @@
|
|
|
223
219
|
// user options
|
|
224
220
|
type: this._type, // set in class property
|
|
225
221
|
colorSpace: this._colorSpace, // set in class property
|
|
226
|
-
anisotropy:
|
|
227
|
-
generateMipmaps:
|
|
228
|
-
magFilter:
|
|
229
|
-
minFilter:
|
|
230
|
-
samples:
|
|
231
|
-
wrapS:
|
|
232
|
-
wrapT:
|
|
222
|
+
anisotropy: options.renderTargetOptions?.anisotropy !== undefined ? options.renderTargetOptions?.anisotropy : 1,
|
|
223
|
+
generateMipmaps: options.renderTargetOptions?.generateMipmaps !== undefined ? options.renderTargetOptions?.generateMipmaps : false,
|
|
224
|
+
magFilter: options.renderTargetOptions?.magFilter !== undefined ? options.renderTargetOptions?.magFilter : three.LinearFilter,
|
|
225
|
+
minFilter: options.renderTargetOptions?.minFilter !== undefined ? options.renderTargetOptions?.minFilter : three.LinearFilter,
|
|
226
|
+
samples: options.renderTargetOptions?.samples !== undefined ? options.renderTargetOptions?.samples : undefined,
|
|
227
|
+
wrapS: options.renderTargetOptions?.wrapS !== undefined ? options.renderTargetOptions?.wrapS : three.ClampToEdgeWrapping,
|
|
228
|
+
wrapT: options.renderTargetOptions?.wrapT !== undefined ? options.renderTargetOptions?.wrapT : three.ClampToEdgeWrapping
|
|
233
229
|
};
|
|
234
230
|
this._material = options.material;
|
|
235
231
|
if (options.renderer) {
|
|
@@ -267,7 +263,7 @@
|
|
|
267
263
|
this._quad.geometry.computeBoundingBox();
|
|
268
264
|
this._scene.add(this._quad);
|
|
269
265
|
this._renderTarget = new three.WebGLRenderTarget(this.width, this.height, rtOptions);
|
|
270
|
-
this._renderTarget.texture.mapping =
|
|
266
|
+
this._renderTarget.texture.mapping = options.renderTargetOptions?.mapping !== undefined ? options.renderTargetOptions?.mapping : three.UVMapping;
|
|
271
267
|
}
|
|
272
268
|
/**
|
|
273
269
|
* Instantiates a temporary renderer
|
|
@@ -283,6 +279,20 @@
|
|
|
283
279
|
// this._rendererIsDisposable = true
|
|
284
280
|
return renderer;
|
|
285
281
|
}
|
|
282
|
+
/**
|
|
283
|
+
* Renders the input texture using the specified material
|
|
284
|
+
*/
|
|
285
|
+
render = () => {
|
|
286
|
+
this._renderer.setRenderTarget(this._renderTarget);
|
|
287
|
+
try {
|
|
288
|
+
this._renderer.render(this._scene, this._camera);
|
|
289
|
+
}
|
|
290
|
+
catch (e) {
|
|
291
|
+
this._renderer.setRenderTarget(null);
|
|
292
|
+
throw e;
|
|
293
|
+
}
|
|
294
|
+
this._renderer.setRenderTarget(null);
|
|
295
|
+
};
|
|
286
296
|
/**
|
|
287
297
|
* Obtains a Buffer containing the rendered texture.
|
|
288
298
|
*
|
|
@@ -308,11 +318,11 @@
|
|
|
308
318
|
// fixed values
|
|
309
319
|
this.toArray(), this.width, this.height, three.RGBAFormat, this._type,
|
|
310
320
|
// user values
|
|
311
|
-
|
|
321
|
+
options?.mapping || three.UVMapping, options?.wrapS || three.ClampToEdgeWrapping, options?.wrapT || three.ClampToEdgeWrapping, options?.magFilter || three.LinearFilter, options?.minFilter || three.LinearFilter, options?.anisotropy || 1,
|
|
312
322
|
// fixed value
|
|
313
323
|
three.LinearSRGBColorSpace);
|
|
314
324
|
// set this afterwards, we can't set it in constructor
|
|
315
|
-
returnValue.generateMipmaps =
|
|
325
|
+
returnValue.generateMipmaps = options?.generateMipmaps !== undefined ? options?.generateMipmaps : false;
|
|
316
326
|
return returnValue;
|
|
317
327
|
}
|
|
318
328
|
/**
|
|
@@ -455,6 +465,11 @@ void main() {
|
|
|
455
465
|
* @group Materials
|
|
456
466
|
*/
|
|
457
467
|
class GainMapEncoderMaterial extends three.ShaderMaterial {
|
|
468
|
+
_minContentBoost;
|
|
469
|
+
_maxContentBoost;
|
|
470
|
+
_offsetSdr;
|
|
471
|
+
_offsetHdr;
|
|
472
|
+
_gamma;
|
|
458
473
|
/**
|
|
459
474
|
*
|
|
460
475
|
* @param params
|
|
@@ -719,6 +734,12 @@ void main() {
|
|
|
719
734
|
* @group Materials
|
|
720
735
|
*/
|
|
721
736
|
class SDRMaterial extends three.ShaderMaterial {
|
|
737
|
+
_brightness = 0;
|
|
738
|
+
_contrast = 1;
|
|
739
|
+
_saturation = 1;
|
|
740
|
+
_exposure = 1;
|
|
741
|
+
_toneMapping;
|
|
742
|
+
_map;
|
|
722
743
|
/**
|
|
723
744
|
*
|
|
724
745
|
* @param params
|
|
@@ -739,10 +760,6 @@ void main() {
|
|
|
739
760
|
depthTest: false,
|
|
740
761
|
depthWrite: false
|
|
741
762
|
});
|
|
742
|
-
this._brightness = 0;
|
|
743
|
-
this._contrast = 1;
|
|
744
|
-
this._saturation = 1;
|
|
745
|
-
this._exposure = 1;
|
|
746
763
|
this._map = map;
|
|
747
764
|
this.toneMapping = this._toneMapping = toneMapping || three.ACESFilmicToneMapping;
|
|
748
765
|
this.needsUpdate = true;
|
|
@@ -866,7 +883,7 @@ void main() {
|
|
|
866
883
|
* const image = await loader.loadAsync('image.exr')
|
|
867
884
|
*
|
|
868
885
|
* // find RAW RGB Max value of a texture
|
|
869
|
-
* const textureMax =
|
|
886
|
+
* const textureMax = findTextureMinMax(image)
|
|
870
887
|
*
|
|
871
888
|
* // Encode the gainmap
|
|
872
889
|
* const encodingResult = encode({
|
|
@@ -941,7 +958,7 @@ void main() {
|
|
|
941
958
|
* const image = await loader.loadAsync('image.exr')
|
|
942
959
|
*
|
|
943
960
|
* // find RAW RGB Max value of a texture
|
|
944
|
-
* const textureMax =
|
|
961
|
+
* const textureMax = findTextureMinMax(image)
|
|
945
962
|
*
|
|
946
963
|
* // Encode the gainmap
|
|
947
964
|
* const encodingResult = await encodeAndCompress({
|
|
@@ -952,7 +969,7 @@ void main() {
|
|
|
952
969
|
*
|
|
953
970
|
* // embed the compressed images + metadata into a single
|
|
954
971
|
* // JPEG file
|
|
955
|
-
* const jpeg =
|
|
972
|
+
* const jpeg = encodeJPEGMetadata({
|
|
956
973
|
* ...encodingResult,
|
|
957
974
|
* sdr: encodingResult.sdr,
|
|
958
975
|
* gainMap: encodingResult.gainMap
|
|
@@ -1081,6 +1098,20 @@ void main() {
|
|
|
1081
1098
|
*/
|
|
1082
1099
|
const findTextureMinMax = (image, mode = 'max', renderer) => {
|
|
1083
1100
|
const srcTex = getDataTexture(image);
|
|
1101
|
+
// check if texture has a valid format
|
|
1102
|
+
if (srcTex.format !== three.AlphaFormat &&
|
|
1103
|
+
srcTex.format !== three.RGBFormat &&
|
|
1104
|
+
srcTex.format !== three.RGBAFormat &&
|
|
1105
|
+
srcTex.format !== three.DepthFormat &&
|
|
1106
|
+
srcTex.format !== three.DepthStencilFormat &&
|
|
1107
|
+
srcTex.format !== three.RedFormat &&
|
|
1108
|
+
srcTex.format !== three.RedIntegerFormat &&
|
|
1109
|
+
srcTex.format !== three.RGFormat &&
|
|
1110
|
+
srcTex.format !== three.RGIntegerFormat &&
|
|
1111
|
+
srcTex.format !== three.RGBIntegerFormat &&
|
|
1112
|
+
srcTex.format !== three.RGBAIntegerFormat) {
|
|
1113
|
+
throw new Error('Unsupported texture format');
|
|
1114
|
+
}
|
|
1084
1115
|
const cellSize = 2;
|
|
1085
1116
|
const mat = new three.ShaderMaterial({
|
|
1086
1117
|
vertexShader,
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monogrid/gainmap-js v3.3.0
|
|
3
|
+
* With ❤️, by MONOGRID <gainmap@monogrid.com>
|
|
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 r=async e=>{if("undefined"==typeof createImageBitmap)throw new Error("createImageBitmap() not supported.");const{source:t,mimeType:r,quality:n,flipY:a}=e;let i;if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&"sourceMimeType"in e)i=new Blob([t],{type:e.sourceMimeType});else{if(!(t instanceof ImageData))throw new Error("Invalid source image");i=t}const o=await createImageBitmap(i),s=o.width,p=o.height;let d;"undefined"!=typeof OffscreenCanvas?d=new OffscreenCanvas(s,p):(d=document.createElement("canvas"),d.width=s,d.height=p);const h=d.getContext("2d");if(!h)throw new Error("Failed to create canvas Context");!0===a&&(h.translate(0,p),h.scale(1,-1)),h.drawImage(o,0,0,s,p);const m=await(async(e,t,r)=>{if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return e.convertToBlob({type:t,quality:r});if(e instanceof HTMLCanvasElement)return new Promise((n,a)=>{e.toBlob(e=>{e?n(e):a(new Error("Failed to convert canvas to blob"))},t,r)});throw new Error("Unsupported canvas element")})(d,r,n||.9);return{data:new Uint8Array(await m.arrayBuffer()),mimeType:r,width:s,height:p}},n=e=>{let r;if(e instanceof t.DataTexture){if(!(e.image.data instanceof Uint16Array||e.image.data instanceof Float32Array))throw new Error("Provided image is not HDR");r=e}else r=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&&(r.flipY=!0),r.needsUpdate=!0;return r},a=(e,r,n)=>{let a;switch(e){case t.UnsignedByteType:a=new Uint8ClampedArray(r*n*4);break;case t.HalfFloatType:a=new Uint16Array(r*n*4);break;case t.UnsignedIntType:a=new Uint32Array(r*n*4);break;case t.ByteType:a=new Int8Array(r*n*4);break;case t.ShortType:a=new Int16Array(r*n*4);break;case t.IntType:a=new Int32Array(r*n*4);break;case t.FloatType:a=new Float32Array(r*n*4);break;default:throw new Error("Unsupported data type")}return a};let i;class o{_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 r={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=o.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,r,n,o)=>{if(void 0!==i)return i;const s=new t.WebGLRenderTarget(1,1,o);r.setRenderTarget(s);const p=new t.Mesh(new t.PlaneGeometry,new t.MeshBasicMaterial({color:16777215}));r.render(p,n),r.setRenderTarget(null);const d=a(e,s.width,s.height);return r.readRenderTargetPixels(s,0,0,s.width,s.height,d),s.dispose(),p.geometry.dispose(),p.material.dispose(),i=0!==d[0],i})(this._type,this._renderer,this._camera,r)){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,r),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 r=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 r.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,r}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:r,offsetSdr:n,offsetHdr:a,maxContentBoost:i,minContentBoost:o,gamma:s}){if(!i)throw new Error("maxContentBoost is required");if(!e)throw new Error("sdr is required");if(!r)throw new Error("hdr is required");const p=s||[1,1,1],d=n||[1/64,1/64,1/64],h=a||[1/64,1/64,1/64],m=o||1,l=Math.max(i,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:r},gamma:{value:(new t.Vector3).fromArray(p)},offsetSdr:{value:(new t.Vector3).fromArray(d)},offsetHdr:{value:(new t.Vector3).fromArray(h)},minLog2:{value:Math.log2(m)},maxLog2:{value:Math.log2(l)}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._minContentBoost=m,this._maxContentBoost=l,this._offsetSdr=d,this._offsetHdr=h,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:r,sdr:a,renderer:i}=e,p=n(r),d=new s({...e,sdr:a.renderTarget.texture,hdr:p}),h=new o({width:p.image.width,height:p.image.height,type:t.UnsignedByteType,colorSpace:t.LinearSRGBColorSpace,material:d,renderer:i,renderTargetOptions:e.renderTargetOptions});try{h.render()}catch(e){throw h.disposeOnDemandRenderer(),e}return h};class d extends t.ShaderMaterial{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:e,toneMapping:r}){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\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=r||t.ACESFilmicToneMapping,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(e){let r=!1;switch(e){case t.ACESFilmicToneMapping:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",r=!0;break;case t.ReinhardToneMapping:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",r=!0;break;case t.CineonToneMapping:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",r=!0;break;case t.LinearToneMapping:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",r=!0;break;default:console.error(`Unsupported toneMapping: ${e}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=t.LinearToneMapping}r&&(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,r,n,a)=>{e.needsUpdate=!0;const i=new o({width:e.image.width,height:e.image.height,type:t.UnsignedByteType,colorSpace:t.SRGBColorSpace,material:new d({map:e,toneMapping:n}),renderer:r,renderTargetOptions:a});try{i.render()}catch(e){throw i.disposeOnDemandRenderer(),e}return i},m=e=>{const{image:t,renderer:r}=e,a=n(t),i=h(a,r,e.toneMapping,e.renderTargetOptions),o=p({...e,image:a,sdr:i,renderer:i.renderer});return{sdr:i,gainMap:o,hdr:a,getMetadata:()=>({gainMapMax:o.material.gainMapMax,gainMapMin:o.material.gainMapMin,gamma:o.material.gamma,hdrCapacityMax:o.material.hdrCapacityMax,hdrCapacityMin:o.material.hdrCapacityMin,offsetHdr:o.material.offsetHdr,offsetSdr:o.material.offsetSdr})}};e.GainMapEncoderMaterial=s,e.SDRMaterial=d,e.compress=r,e.encode=m,e.encodeAndCompress=async e=>{const t=m(e),{mimeType:n,quality:a,flipY:i,withWorker:o}=e;let s,p,d;const h=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),l=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(o){const e=await Promise.all([o.compress({source:h,mimeType:n,quality:a,flipY:i}),o.compress({source:l,mimeType:n,quality:a,flipY:i})]);s=e,p=e[0].source,d=e[1].source}else s=await Promise.all([r({source:h,mimeType:n,quality:a,flipY:i}),r({source:l,mimeType:n,quality:a,flipY:i})]),p=h.data,d=l.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:p,rawGainMap:d}},e.findTextureMinMax=(e,r="max",a)=>{const i=n(e);if(i.format!==t.AlphaFormat&&i.format!==t.RGBFormat&&i.format!==t.RGBAFormat&&i.format!==t.DepthFormat&&i.format!==t.DepthStencilFormat&&i.format!==t.RedFormat&&i.format!==t.RedIntegerFormat&&i.format!==t.RGFormat&&i.format!==t.RGIntegerFormat&&i.format!==t.RGBIntegerFormat&&i.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(i.image.width,i.image.height)},map:{value:i}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:r,INITIAL_VALUE:"max"===r?0:65504}});i.needsUpdate=!0,s.needsUpdate=!0;let p=i.image.width,d=i.image.height;const h=new o({width:p,height:d,type:i.type,colorSpace:i.colorSpace,material:s,renderer:a}),m=[];for(;p>1||d>1;){p=Math.max(1,(p+2-1)/2|0),d=Math.max(1,(d+2-1)/2|0);const e=new t.WebGLRenderTarget(p,d,{type:h.type,format:i.format,colorSpace:h.colorSpace,minFilter:t.NearestFilter,magFilter:t.NearestFilter,wrapS:t.ClampToEdgeWrapping,wrapT:t.ClampToEdgeWrapping,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});m.push(e)}p=i.image.width,d=i.image.height,m.forEach(e=>{p=Math.max(1,(p+2-1)/2|0),d=Math.max(1,(d+2-1)/2|0),h.renderTarget=e,h.render(),s.uniforms.map.value=e.texture,s.uniforms.u_srcResolution.value.x=p,s.uniforms.u_srcResolution.value.y=d});const l=h.toArray();return h.dispose(),m.forEach(e=>e.dispose()),[h.type===t.FloatType?l[0]:t.DataUtils.fromHalfFloat(l[0]),h.type===t.FloatType?l[1]:t.DataUtils.fromHalfFloat(l[1]),h.type===t.FloatType?l[2]:t.DataUtils.fromHalfFloat(l[2])]},e.getGainMap=p,e.getSDRRendition=h});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { GainMapMetadata } from '../core/types';
|
|
2
2
|
import { type CompressedImage } from '../encode/types';
|
|
3
3
|
/**
|
|
4
4
|
* Encapsulates a Gainmap into a single JPEG file (aka: JPEG-R) with the base map
|
|
@@ -17,7 +17,7 @@ import { type CompressedImage } from '../encode/types';
|
|
|
17
17
|
* const image = await loader.loadAsync('image.exr')
|
|
18
18
|
*
|
|
19
19
|
* // find RAW RGB Max value of a texture
|
|
20
|
-
* const textureMax =
|
|
20
|
+
* const textureMax = findTextureMinMax(image)
|
|
21
21
|
*
|
|
22
22
|
* // Encode the gainmap
|
|
23
23
|
* const encodingResult = encode({
|
|
@@ -63,7 +63,7 @@ import { type CompressedImage } from '../encode/types';
|
|
|
63
63
|
*
|
|
64
64
|
* // embed the compressed images + metadata into a single
|
|
65
65
|
* // JPEG file
|
|
66
|
-
* const jpeg =
|
|
66
|
+
* const jpeg = encodeJPEGMetadata({
|
|
67
67
|
* ...encodingResult,
|
|
68
68
|
* ...metadata,
|
|
69
69
|
* sdr,
|
|
@@ -73,12 +73,12 @@ import { type CompressedImage } from '../encode/types';
|
|
|
73
73
|
* // `jpeg` will be an `Uint8Array` which can be saved somewhere
|
|
74
74
|
*
|
|
75
75
|
*
|
|
76
|
-
* @param encodingResult
|
|
77
|
-
* @returns
|
|
76
|
+
* @param encodingResult - Encoding result containing SDR image, gain map image, and metadata
|
|
77
|
+
* @returns A Uint8Array representing a JPEG-R file
|
|
78
78
|
* @throws {Error} If `encodingResult.sdr.mimeType !== 'image/jpeg'`
|
|
79
79
|
* @throws {Error} If `encodingResult.gainMap.mimeType !== 'image/jpeg'`
|
|
80
80
|
*/
|
|
81
81
|
export declare const encodeJPEGMetadata: (encodingResult: GainMapMetadata & {
|
|
82
82
|
sdr: CompressedImage;
|
|
83
83
|
gainMap: CompressedImage;
|
|
84
|
-
}) =>
|
|
84
|
+
}) => Uint8Array<ArrayBuffer>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JPEG assembler for creating JPEG-R (JPEG with gain map) files
|
|
3
|
+
* Based on libultrahdr jpegr.cpp implementation
|
|
4
|
+
*/
|
|
5
|
+
import { GainMapMetadataExtended } from '../core/types';
|
|
6
|
+
import { type CompressedImage } from '../encode/types';
|
|
7
|
+
/**
|
|
8
|
+
* Options for assembling a JPEG with gain map
|
|
9
|
+
*/
|
|
10
|
+
export interface AssembleJpegOptions {
|
|
11
|
+
/** Primary (SDR) JPEG image */
|
|
12
|
+
sdr: CompressedImage;
|
|
13
|
+
/** Gain map JPEG image */
|
|
14
|
+
gainMap: CompressedImage;
|
|
15
|
+
/** Gain map metadata */
|
|
16
|
+
metadata: GainMapMetadataExtended;
|
|
17
|
+
/** Optional EXIF data to embed */
|
|
18
|
+
exif?: Uint8Array<ArrayBuffer>;
|
|
19
|
+
/** Optional ICC color profile */
|
|
20
|
+
icc?: Uint8Array<ArrayBuffer>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Assemble a JPEG-R file (JPEG with embedded gain map)
|
|
24
|
+
*
|
|
25
|
+
* The structure is:
|
|
26
|
+
* 1. Primary image:
|
|
27
|
+
* - SOI
|
|
28
|
+
* - APP1 (EXIF if present)
|
|
29
|
+
* - APP1 (XMP with gain map metadata)
|
|
30
|
+
* - APP2 (ICC profile if present)
|
|
31
|
+
* - APP2 (MPF data)
|
|
32
|
+
* - Rest of primary JPEG data
|
|
33
|
+
* 2. Secondary image (gain map):
|
|
34
|
+
* - SOI
|
|
35
|
+
* - APP1 (XMP with gain map parameters)
|
|
36
|
+
* - Rest of gain map JPEG data
|
|
37
|
+
*
|
|
38
|
+
* @param options - Assembly options
|
|
39
|
+
* @returns Complete JPEG-R file as Uint8Array
|
|
40
|
+
*/
|
|
41
|
+
export declare function assembleJpegWithGainMap(options: AssembleJpegOptions): Uint8Array<ArrayBuffer>;
|